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

GO
ALTER TABLE [sAcademic].[tLessonPlan]
    ADD [Remark] NVARCHAR (MAX) NULL;


GO

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


GO
ALTER FUNCTION [sConfig].[fDisplayFieldLessionGet](@rOrgId int)
RETURNS  @List TABLE (
		 IsObjective bit,
		 IsSummary bit,
		 IsLearningExperience bit,
		 IsEssentialMaterial bit,
		 IsToolsTechniques bit,
		 IsIndicativeHomework bit,
		 IsAssessmentQuestion bit,
		 IsTeacherExample bit,
		 IsGuidedPractice bit,
		 IsIndependentPractice bit,
		 IsSubTopicSelect bit,
		 IsSubTopicText bit,
		 IsSession bit,
		 IsTrainingMethod bit,
		 IsPeriodCount bit,
		 OrgId smallint,
		 IsRemark bit,
		 IsAttachment bit
		 
		 
)  WITH EXECUTE AS CALLER
AS 
BEGIN

    declare @rIsObjective bit 
	declare @rIsSummary bit 
    declare @rIsLearningExperience bit
    declare @rIsEssentialMaterial bit 
    declare @rIsToolsTechniques bit
    declare @rIsIndicativeHomework bit 
    declare @rIsAssessmentQuestion bit 
    declare @rIsTeacherExample bit 
    declare @rIsGuidedPractice bit 
    declare @rIsIndependentPractice bit
    declare @rIsSubTopicSelect bit
    declare @rIsSubTopicText bit
	declare @rIsSession bit
	declare @rIsTrainingMethod bit
	declare @rIsPeriodCount bit
	declare @rIsRemark bit
	declare @rIsAttachment bit
   
	select @rIsObjective=DisplayFieldId FROM sConfig.tDisplayFieldOrg where orgId = @rOrgId and DisplayFieldId = 201
	select @rIsSummary=DisplayFieldId FROM sConfig.tDisplayFieldOrg where orgId = @rOrgId and DisplayFieldId = 203
	select @rIsLearningExperience =DisplayFieldId FROM sConfig.tDisplayFieldOrg where orgId = @rOrgId and DisplayFieldId = 202
	select @rIsEssentialMaterial=DisplayFieldId FROM sConfig.tDisplayFieldOrg where orgId = @rOrgId and DisplayFieldId = 204
	select @rIsToolsTechniques=DisplayFieldId FROM sConfig.tDisplayFieldOrg where orgId = @rOrgId and DisplayFieldId = 205
	select @rIsIndicativeHomework=DisplayFieldId FROM sConfig.tDisplayFieldOrg where orgId = @rOrgId and DisplayFieldId = 206
	select @rIsAssessmentQuestion=DisplayFieldId FROM sConfig.tDisplayFieldOrg where orgId = @rOrgId and DisplayFieldId = 207
	select @rIsTeacherExample=DisplayFieldId FROM sConfig.tDisplayFieldOrg where orgId = @rOrgId and DisplayFieldId = 208
	select @rIsGuidedPractice=DisplayFieldId FROM sConfig.tDisplayFieldOrg where orgId = @rOrgId and DisplayFieldId = 209
	select @rIsIndependentPractice=DisplayFieldId  FROM sConfig.tDisplayFieldOrg where orgId = @rOrgId and DisplayFieldId = 210
	select @rIsSubTopicSelect=DisplayFieldId  FROM sConfig.tDisplayFieldOrg where orgId = @rOrgId and DisplayFieldId = 211
	select @rIsSubTopicText=DisplayFieldId  FROM sConfig.tDisplayFieldOrg where orgId = @rOrgId and DisplayFieldId = 212
	select @rIsSession=DisplayFieldId  FROM sConfig.tDisplayFieldOrg where orgId = @rOrgId and DisplayFieldId = 1219
	select @rIsTrainingMethod=DisplayFieldId  FROM sConfig.tDisplayFieldOrg where orgId = @rOrgId and DisplayFieldId = 1220
	select @rIsPeriodCount=DisplayFieldId  FROM sConfig.tDisplayFieldOrg where orgId = @rOrgId and DisplayFieldId = 1221
	select @rIsRemark = DisplayFieldId  FROM sConfig.tDisplayFieldOrg where orgId = @rOrgId and DisplayFieldId = 1223
	select @rIsAttachment = DisplayFieldId  FROM sConfig.tDisplayFieldOrg where orgId = @rOrgId and DisplayFieldId = 1224
	 	
	INSERT INTO @List 
	SELECT 
		(CASE WHEN @rIsObjective Is Null THEN  0 ELSE 1 END) AS IsObjective,
		(CASE WHEN @rIsSummary Is Null THEN 0 ELSE 1 END)AS IsSummary,
		(CASE WHEN @rIsLearningExperience Is Null THEN 0 ELSE 1 END)AS IsLearningExperience,
		(CASE WHEN @rIsEssentialMaterial Is Null THEN 0  ELSE 1 END)AS IsEssentialMaterial,
		(CASE WHEN @rIsToolsTechniques Is Null THEN 0  ELSE 1 END)AS IsToolsTechniques,
		(CASE WHEN @rIsIndicativeHomework Is Null THEN 0  ELSE 1 END)AS IsIndicativeHomework,
		(CASE WHEN @rIsAssessmentQuestion Is Null THEN 0  ELSE 1 END)AS IsAssessmentQuestion ,
		(CASE WHEN @rIsTeacherExample Is Null THEN 0 ELSE  1 END)AS  IsTeacherExample,
		(CASE WHEN @rIsGuidedPractice Is Null THEN 0  ELSE 1 END)AS IsGuidedPractice,
		(CASE WHEN @rIsIndependentPractice Is Null THEN 0 ELSE  1 END)AS IsIndependentPractice,
		(CASE WHEN @rIsSubTopicSelect Is Null THEN 0 ELSE  1 END)AS IsSubTopicSelect,
		(CASE WHEN @rIsSubTopicText Is Null THEN 0 ELSE  1 END)AS IsSubTopicText,
		(CASE WHEN @rIsSession Is Null THEN 0 ELSE  1 END)AS IsSession,
		(CASE WHEN @rIsTrainingMethod Is Null THEN 0 ELSE  1 END)AS IsTrainingMethod,
		(CASE WHEN @rIsPeriodCount Is Null THEN 0 ELSE  1 END)AS IsPeriodCount,
		@rOrgId AS OrgId,
		(CASE WHEN @rIsRemark Is Null THEN 0 ELSE  1 END)AS IsRemark,		  
		(CASE WHEN @rIsAttachment Is Null THEN 0 ELSE  1 END)AS IsAttachment
    RETURN  
    
END
GO




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


GO

 
ALTER PROCEDURE [sAcademic].[pClassworkStudentGet]

	 @rStudentId bigint,
	 @rBatchId int,	 
	 @rFromDate date='',
     @rToDate date='',
     @rHomeWorkEndDate	date=''
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	DECLARE @lOrgGroupBatchId int=0
	SELECT @lOrgGroupBatchId=OrgGroupBatchId FROM sSetup.tBatchMaster WHERE Id = @rBatchId

	DECLARE @lDivisionId int
	SELECT @lDivisionId = DivisionId FROM sStudent.tAcademic WHERE StudentId = @rStudentId AND BatchId = @rBatchId

	DECLARE @lConfigValue nvarchar(50)
	DECLARE @lIsClassworkHomeworkBasedOnApproval bit=0
	SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 323 AND SourceTypeId = 2010 AND SourceId = LEFT(@lOrgGroupBatchId,4)

	IF (@lConfigValue IS NULL) OR (@lConfigValue = 'False')
	SET @lIsClassworkHomeworkBasedOnApproval = 0
	ELSE
	SET @lIsClassworkHomeworkBasedOnApproval = 1	
	
	SELECT 
			AC.Id,
			AC.EmployeeId,
			AC.ClassId,
			AC.DivisionId,
			AC.SubjectId,
		    AC.Classwork,
		    AC.Homework,
		    AC.ClassWorkDate,
		    AC.HomeWorkEndDate,
		    --ISNULL(AC.HomeWorkEndDate,'') AS HomeWorkEndDate,
		    ISNULL(SM.Title,'') as SubjectName,
		    ISNULL(EM.FirstName +' ' + EM.LastName,'') AS TeacherName,
		    ISNULL(CM.Title,'') AS ClassName,
		    ISNULL(DM.Title,'') AS DivisionName,
		    OM.OrgGroupId AS OrgId,
			ISNULL(AC.IsSubmitHomework,0) AS IsSubmitHomework
	FROM 
			sAcademic.tClasswork AC			 
			INNER Join sSetup.tSubjectMaster SM On SM.Id=AC.SubjectId
			INNER Join sHrm.tEmployeeMaster EM On EM.Id = AC.EmployeeId
			INNER Join sSetup.tClassMaster CM On CM.Id = AC.ClassId
			INNER Join sSetup.tDivisionMaster DM On DM.Id = AC.DivisionId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = DM.OrgId
			
	WHERE 
	    AC.DivisionId = @lDivisionId		 
		AND (AC.ClassWorkDate>=@rFromDate OR ISNULL(@rFromDate,'')='')
		AND (AC.ClassWorkDate<=@rToDate OR ISNULL(@rToDate,'')='')
		AND (AC.HomeWorkEndDate>=@rHomeWorkEndDate OR ISNULL(@rHomeWorkEndDate,'')='')
		AND ((@lIsClassworkHomeworkBasedOnApproval=0) OR (@lIsClassworkHomeworkBasedOnApproval=1 AND AC.StatusId=550))
		AND ISNULL(EM.IsOtherUser,0) = 0 
		AND AC.BatchId = @rBatchId
		order by  AC.CreatedDateTime desc
END
GO
PRINT N'Altering [sAcademic].[pGetLessonPlanApi]...';


GO
ALTER PROCEDURE [sAcademic].[pGetLessonPlanApi]

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

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

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

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


GO

ALTER PROCEDURE [sAcademic].[pLessonPlanAdd]
	 
        @rId bigint=0,
        @rTopicId int,
        @rDivisionId int, 
        @rNoOfPeriodRequired smallint,
        @rObjective nvarchar(1000),
        @rIndicativeHomework nvarchar(200),
        @rSummary nvarchar(200),
        @rStartDate date='',
        @rEndDate date='',
        @rIsCompleted bit=0,
        @rEmployeeId bigint,
        @rBatchId int,
        @rCreatedUserId bigint,
        @rOrgId smallint,
        @rLearningExperience nvarchar(1000)='',
        @rToolsAndTechniques nvarchar(500)='',
        @rEssentialMaterial nvarchar(500)='',
		@rAssessmentQuestion	nvarchar(1000)='',	
		@rTeacherExample	nvarchar(1000)='',
		@rGuidedPractice	nvarchar(1000)='',
		@rIndependentPractice	nvarchar(1000)	='',
		@rSubTopic nvarchar(1000)='' ,
	    @rSession nvarchar(100)='' ,
		@rTrainingMethod  nvarchar(100)='' ,
		@rPeriodCount int =0,
		@rRemark nvarchar(MAX) = ''

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	 
	--IF(@rId = 0)	
	--BEGIN
	--	--If Exists(select Id from sCommunication.tNews where Code=@rCode AND OrgGroupBatchId=@rOrgGroupBatchId)
	--	--	BEGIN
	--	--	select -102 as Result
	--	--	RETURN
	--	--END 
	
	--	If Exists(select Id from sAcademic.tTopicMaster where Number=@rNumber AND OrgId=@rOrgId)
	--		BEGIN
	--		select -103 as Result
	--		RETURN
	--	END 
	--END
	--ELSE
	--BEGIN
	--	--If Exists(select Id from sCommunication.tNews where Code=@rCode AND OrgGroupBatchId=@rOrgGroupBatchId AND Id<>@rId)
	--	--Begin
	--	--	select -102 as Result
	--	--	RETURN
	--	--End
	--	If  Exists(select Id from sAcademic.tTopicMaster where Number=@rNumber AND OrgId=@rOrgId AND Id<>@rId)
	--	Begin
	--		select -103 as Result
	--		RETURN
	--	End

	--END
	
	IF(@rId = 0)	
	BEGIN
		IF EXISTS(SELECT Id FROM sAcademic.tLessonPlan WHERE DivisionId=@rDivisionId AND TopicId = @rTopicId AND StartDate = @rStartDate AND EndDate = @rEndDate)
		BEGIN
			SELECT -101 AS Result
			RETURN
		END 
	END
	ELSE
	BEGIN
		IF  EXISTS(SELECT Id FROM sAcademic.tLessonPlan WHERE DivisionId=@rDivisionId AND TopicId = @rTopicId AND StartDate = @rStartDate AND EndDate = @rEndDate AND Id <> @rId)
		BEGIN
			SELECT -101 AS Result
			RETURN
		END
	END

	DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAcademic.tLessonPlan', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sAcademic.tLessonPlan
		(
			Id,
			TopicId,
			DivisionId,
			NoOfPeriodRequired,
			Objective,
			IndicativeHomework,
			Summary,
			StartDate,
			EndDate,
			IsCompleted,
			EmployeeId,
			BatchId,
			CreatedUserId,
			CreatedDateTime,
			LearningExperience,
			ToolsAndTechniques,
			EssentialMaterial,
			AssessmentQuestion,
			TeacherExample,
			GuidedPractice,
			IndependentPractice,
			SubTopic ,
			[Session] ,
			TrainingMethod ,
			PeriodCount,
			Remark
		)
	VALUES
		(
			@lNextNumber,
			@rTopicId,
			@rDivisionId,
			@rNoOfPeriodRequired,
			@rObjective,
			@rIndicativeHomework,
			@rSummary,
			@rStartDate,
			@rEndDate,
			@rIsCompleted,
			@rEmployeeId,
			@rBatchId,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rLearningExperience,
			@rToolsAndTechniques,
			@rEssentialMaterial,
			@rAssessmentQuestion,
			@rTeacherExample,
			@rGuidedPractice,
			@rIndependentPractice,
			CASE WHEN @rSubTopic = '-1' Then '' ELSE @rSubTopic END ,
			@rSession ,
		    @rTrainingMethod ,
			@rPeriodCount,
			@rRemark
		)
		    SELECT 1 AS Result , @lNextNumber As Id
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sAcademic.tLessonPlan
	    SET
			TopicId=@rTopicId,
			DivisionId=@rDivisionId,
			NoOfPeriodRequired=@rNoOfPeriodRequired,
			Objective=@rObjective,
			IndicativeHomework=@rIndicativeHomework,
			Summary=@rSummary,
			StartDate=@rStartDate,
			EndDate=@rEndDate,
			IsCompleted=@rIsCompleted,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate(),
			LearningExperience = @rLearningExperience,
			ToolsAndTechniques = @rToolsAndTechniques,
			EssentialMaterial =@rEssentialMaterial,
			EmployeeId = @rEmployeeId,
			AssessmentQuestion=@rAssessmentQuestion,
			TeacherExample=@rTeacherExample,
			GuidedPractice=@rGuidedPractice,
			IndependentPractice=@rIndependentPractice,
			SubTopic= CASE WHEN @rSubTopic = '-1' Then '' ELSE @rSubTopic END ,
			[Session] = @rSession ,
			TrainingMethod =@rTrainingMethod ,
			PeriodCount =@rPeriodCount,
			Remark=@rRemark
	      WHERE Id = @rId
	      SELECT 11 AS Result, @lNextNumber As Id
	 END  	

END
GO
PRINT N'Altering [sAcademic].[pLessonPlanGet]...';


GO

ALTER PROCEDURE [sAcademic].[pLessonPlanGet]

	 @rId bigint=0,
	 @rClassId int=0,
	 @rSubjectId int=0,
	 @rDivisionId int=0,
	 @rIsCompleted bit=0,
	 @rBatchId int=0,
	 @rEmployeeId bigint=0,
	 @rDepartmentid int=0,
	 @rFromDate datetime='',
     @rToDate datetime='',
     @rCreatedUserId bigint=0,
	 @rStatus int = 0,
	 @rIsWithHeader bit=0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	
	IF(@rStatus = 0)
	BEGIN
	SELECT 
			LP.Id,
			TM.ClassId,
		    LP.DivisionId,
			TM.SubjectId,
			LP.TopicId,
			LP.NoOfPeriodRequired,
			LP.Objective,
			LP.IndicativeHomework,
			LP.Summary,
			ISNULL(LP.StartDate,'') AS StartDate ,
			ISNULL(LP.EndDate,'') AS EndDate,
			ISNULL(LP.IsCompleted,0) AS IsCompleted,
			LP.EmployeeId,
			LP.BatchId,
			LP.CreatedUserId,
			LP.CreatedDateTime,
			TM.Title AS TopicName,
			DM.Code AS ClassDivisionName,
			SM.Title AS SubjectName,
			--vTSD.ClassTitle+' - '+ vTSD.DivisionTitle AS ClassDivisionName,
			 
			--vTSD.SubjectName,
			--ISNULL(EM.FirstName,'') + ' ' + ISNULL(EM.LastName,'') AS  EmployeeName,
			[sHrm].[fEmployeeNameGet](EM.FirstName , EM.MiddleName, EM.LastName,ISNULL(OM.EmployeeNameFormatId,1)) AS EmployeeName,
			LP.LearningExperience,
			LP.ToolsAndTechniques,
			LP.EssentialMaterial,
			LP.AssessmentQuestion,
			LP.TeacherExample,
			LP.GuidedPractice,
			LP.IndependentPractice,
			LP.SubTopic,
			@rIsWithHeader AS IsWithHeader,
			(CASE WHEN @rIsWithHeader=1 THEN OI.CertificateHeaderA4 ELSE NULL END)AS MarksheetHeaderA4 ,
			ISNULL(LP.[Session] ,'') As [Session] ,
			ISNULL(LP.TrainingMethod,'') As TrainingMethod,
			ISNULL(LP.PeriodCount,0) As PeriodCount ,
			ISNULL(LP.Remark,'') As Remark
	FROM 
			sAcademic.tLessonPlan LP
			INNER JOIN sSetup.tDivisionMaster DM ON LP.DivisionId = DM.Id
			INNER JOIN sSetup.tClassMaster CM ON CM.Id = DM.ClassId
			LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id=LP.EmployeeId
			INNER JOIN sSetup.tOrganizationMaster OM ON EM.OrgID = OM.Id
			INNER JOIN sAcademic.tTopicMaster TM ON TM.Id=LP.TopicId 
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = TM.SubjectId   
			LEFT JOIN sSetup.tOrgImages OI ON OI.Orgid = CM.OrgId
			--sAcademic.tLessonPlan LP
			--INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id=LP.EmployeeId
			--INNER JOIN sAcademic.tTopicMaster TM ON TM.Id=LP.TopicId
			--INNER JOIN sAcademic.vTeacherSubjectDivision vTSD ON vTSD.DivisionId = LP.DivisionId
			--AND vTSD.ClassId = TM.ClassId 
			--AND vTSD.SubjectId = TM.SubjectId 
			--AND vTSD.EmployeeId = LP.EmployeeId
			--INNER JOIN sSetup.tClassMaster CM ON CM.Id = vTSD.ClassId
	WHERE 
		((LP.BatchId = @rBatchId) OR (LP.BatchId = 0))
		 AND ((LP.EmployeeId = @rEmployeeId) OR (@rEmployeeId=0))
		AND ((LP.Id = @rId) OR (@rId = 0))
		AND ((TM.ClassId = @rClassId) OR (@rClassId = 0))
		AND ((LP.DivisionId = @rDivisionId) OR (@rDivisionId = 0))
		AND ((TM.SubjectId = @rSubjectId) OR (@rSubjectId = 0))
		AND ((LP.IsCompleted='False') OR (LP.IsCompleted=@rIsCompleted))		
		AND ((CM.DepartmentId = @rDepartmentid) OR (@rDepartmentid=0))
		--AND (LP.StartDate>=@rFromDate OR ISNULL(@rFromDate,'')='')
		--AND (LP.StartDate<=@rToDate OR ISNULL(@rToDate,'')='')
		AND ((LP.StartDate >= @rFromDate OR ISNULL(@rFromDate,'')='' )AND (LP.StartDate <= @rToDate OR ISNULL(@rToDate,'')='')
		OR (LP.EndDate >= @rFromDate OR ISNULL(@rFromDate,'')='' )AND (LP.EndDate <= @rToDate OR ISNULL(@rToDate,'')='')
		)
		AND (LP.CreatedUserId=@rCreatedUserId OR ISNULL(@rCreatedUserId,'')='')
		AND ISNULL(EM.IsOtherUser,0) = 0
	ORDER BY
		LP.id 
	END
	ELSE
	BEGIN
	SELECT 
			LP.Id,
			TM.ClassId,
		    LP.DivisionId,
			TM.SubjectId,
			LP.TopicId,
			LP.NoOfPeriodRequired,
			LP.Objective,
			LP.IndicativeHomework,
			LP.Summary,
			ISNULL(LP.StartDate,'') AS StartDate ,
			ISNULL(LP.EndDate,'') AS EndDate,
			ISNULL(LP.IsCompleted,0) AS IsCompleted,
			LP.EmployeeId,
			LP.BatchId,
			LP.CreatedUserId,
			LP.CreatedDateTime,
			TM.Title AS TopicName,
			DM.Code AS ClassDivisionName,
			SM.Title AS SubjectName,
			--vTSD.ClassTitle+' - '+ vTSD.DivisionTitle AS ClassDivisionName,
			 
			--vTSD.SubjectName,
			--ISNULL(EM.FirstName,'') + ' ' + ISNULL(EM.LastName,'') AS  EmployeeName,
			[sHrm].[fEmployeeNameGet](EM.FirstName , EM.MiddleName, EM.LastName,ISNULL(OM.EmployeeNameFormatId,1)) AS EmployeeName,
			LP.LearningExperience,
			LP.ToolsAndTechniques,
			LP.EssentialMaterial,
			LP.AssessmentQuestion,
			LP.TeacherExample,
			LP.GuidedPractice,
			LP.IndependentPractice,
			LP.SubTopic,
			@rIsWithHeader AS IsWithHeader,
			(CASE WHEN @rIsWithHeader=1 THEN OI.CertificateHeaderA4 ELSE NULL END)AS MarksheetHeaderA4 ,
			ISNULL(LP.Session ,'') As [Session],
			ISNULL(LP.TrainingMethod,'') As TrainingMethod,
			ISNULL(LP.PeriodCount,0) As PeriodCount,
			ISNULL(LP.Remark,'') As Remark
	FROM 
			sAcademic.tLessonPlan LP
			INNER JOIN sSetup.tDivisionMaster DM ON LP.DivisionId = DM.Id
			INNER JOIN sSetup.tClassMaster CM ON CM.Id = DM.ClassId
			LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id=LP.EmployeeId
			INNER JOIN sSetup.tOrganizationMaster OM ON EM.OrgID = OM.Id
			INNER JOIN sAcademic.tTopicMaster TM ON TM.Id=LP.TopicId 
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = TM.SubjectId 
			LEFT JOIN sSetup.tOrgImages OI ON OI.Orgid = CM.OrgId  

			--sAcademic.tLessonPlan LP
			--INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id=LP.EmployeeId
			--INNER JOIN sAcademic.tTopicMaster TM ON TM.Id=LP.TopicId
			--INNER JOIN sAcademic.vTeacherSubjectDivision vTSD ON vTSD.DivisionId = LP.DivisionId
			--AND vTSD.ClassId = TM.ClassId 
			--AND vTSD.SubjectId = TM.SubjectId 
			--AND vTSD.EmployeeId = LP.EmployeeId
			--INNER JOIN sSetup.tClassMaster CM ON CM.Id = vTSD.ClassId
	WHERE 
		((LP.BatchId = @rBatchId) OR (LP.BatchId = 0))
		 AND ((LP.EmployeeId = @rEmployeeId) OR (@rEmployeeId=0))
		AND ((LP.Id = @rId) OR (@rId = 0))
		AND ((TM.ClassId = @rClassId) OR (@rClassId = 0))
		AND ((LP.DivisionId = @rDivisionId) OR (@rDivisionId = 0))
		AND ((TM.SubjectId = @rSubjectId) OR (@rSubjectId = 0))
		AND ((@rStatus = 2) OR (LP.IsCompleted=@rIsCompleted))
		AND ((CM.DepartmentId = @rDepartmentid) OR (@rDepartmentid=0))
		--AND (LP.StartDate>=@rFromDate OR ISNULL(@rFromDate,'')='')
		--AND (LP.StartDate<=@rToDate OR ISNULL(@rToDate,'')='')
	    AND ((LP.StartDate >= @rFromDate OR ISNULL(@rFromDate,'')='' )AND (LP.StartDate <= @rToDate OR ISNULL(@rToDate,'')='')
		OR (LP.EndDate >= @rFromDate OR ISNULL(@rFromDate,'')='' )AND (LP.EndDate <= @rToDate OR ISNULL(@rToDate,'')='')
		)

		AND (LP.CreatedUserId=@rCreatedUserId OR ISNULL(@rCreatedUserId,'')='')
		AND ISNULL(EM.IsOtherUser,0) = 0
	ORDER BY
		LP.id 
	END
END
GO
PRINT N'Altering [sAcademic].[pTeacherSubjectDivisionCopyToAnotherEmployee]...';


GO


ALTER PROCEDURE [sAcademic].[pTeacherSubjectDivisionCopyToAnotherEmployee]
	
	@rExistingEmployeeId bigint,
	@rNewEmployeeId bigint
	

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

--this delete will affect all related modules
	DELETE FROM sAcademic.tTeacherSubject WHERE EmployeeId = @rNewEmployeeId
	DELETE FROM sAcademic.tTeacherSubjectDivision WHERE EmployeeId = @rNewEmployeeId

	INSERT INTO sAcademic.tTeacherSubject
           (
		   EmployeeId
           ,SubjectId
		   )
     SELECT
		    @rNewEmployeeId,
            SubjectId
	
		   FROM sAcademic.tTeacherSubject WHERE EmployeeId = @rExistingEmployeeId

	INSERT INTO sAcademic.tTeacherSubjectDivision
			   (
				EmployeeId
			   ,SubjectId
			   ,DivisionId
			   ,SubjectCordinatorEmployeeId
			   )

		 Select @rNewEmployeeId,
				SubjectId,
				DivisionId,
				null

		 FROM sAcademic.tTeacherSubjectDivision WHERE EmployeeId = @rExistingEmployeeId

		 SELECT 1 AS Result
END
GO
PRINT N'Altering [sAdmission].[pAdmissionAndInquiryConsolidateDashBoardGet]...';


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

	DECLARE @lTempOrgBatchOrder TABLE( OrgId int, BatchOrderIndex int)
	INSERT INTO @lTempOrgBatchOrder ( OrgId,BatchOrderIndex )
	SELECT 
		OM.Id AS OrgId, MAX(BM.OrderIndex) AS BatchOrderIndex
	FROM
		sSetup.tOrganizationMaster OM
		INNER JOIN sSetup.tBatchMaster BM ON BM.OrgId = OM.Id
		INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
	WHERE 
		((OM.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId = 0))
		AND BM.IsObsolete = 0 AND COGBM.Id=@rCommonOrgGroupBatchId
		AND BM.IsInContext = 1
	GROUP BY
		OM.Id
		
	DECLARE @lTempBatchId TABLE(OrgId int, BatchId int)
	INSERT INTO @lTempBatchId (OrgId , BatchId)
	SELECT 
		BM.OrgId AS OrgId,
		BM.Id AS BatchId
	FROM 
		sSetup.tBatchMaster BM
		INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		--INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		INNER JOIN @lTempOrgBatchOrder BO ON BO.OrgId = BM.OrgId
	WHERE
		BO.BatchOrderIndex = BM.OrderIndex  AND COGBM.Id=@rCommonOrgGroupBatchId
		AND BM.IsInContext = 1
	
	DECLARE @lConfigValue nvarchar(50)=''
	IF(@rOrgGroupId = 0)
	BEGIN
		DECLARE @lOrgGroupId int
		SELECT @lOrgGroupId = OrgGroupId FROM sSetup.tOrganizationMaster WHERE Id = @rOrgId
		
		SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 397 AND SourceTypeId = 2010 AND SourceId = @lOrgGroupId
	END
	ELSE
	BEGIN
		SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 397 AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId
	END
	IF @lConfigValue = ''
		SET @lConfigValue = 'False' 

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

		IF(@rSyncDate =1)
				BEGIN
				DELETE  sAdmission.tTempAdmissionFormCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))  
				IF EXISTS (SELECT 1 FROM sAdmission.tTempAdmissionFormCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND (OrgGroupId = @rOrgGroupId))  
				BEGIN  
					IF(@rOrgGroupId !=0)  
					INSERT INTO sAdmission.tTempAdmissionFormCount  
					SELECT ISNULL(OGM.Id,0) AS OrgGroupId,OGM.Title AS OrgGroupTitle,ISNULL(COUNT(AF.Id),0) AS AdmissionCount,@rCommonOrgGroupBatchId,GetDate(),

					(SELECT ISNULL(COUNT(AF1.Id),0) FROM sSetup.tOrgGroupMaster OGM1     
					INNER JOIN sSetup.tOrganizationMaster OM1 ON OGM1.Id = OM1.OrgGroupId   
					INNER JOIN @lTempBatchId TB1 ON TB1.OrgId = OM1.Id  
					LEFT JOIN sSetup.tBatchMaster BM1 ON BM1.Id = TB1.BatchId AND BM1.IsInContext = 1  
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM1 ON OGBM1.ID=BM1.OrgGroupBatchId AND OGM1.Id = OGBM1.OrgGroupId   
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM1 ON COGBM1.Id=OGBM1.CommonOrgGroupBatchId   
					LEFT JOIN sAdmission.tAdmissionForm AF1 ON BM1.Id = AF1.BatchId
					LEFT JOIN sAdmission.tAdmissionFormSelected AFS ON AF1.Id = AFS.AdmissionFormId
				    LEFT JOIN sAdmission.tAdmissionStatusMaster ASM ON ASM.Id = AFS.AdmissionStatusId WHERE OGM1.Id<>1 AND COGBM1.Id = COGBM.Id AND OGM1.Id = OGM.Id AND ASM.Id = null) as PendingCount,

					(SELECT ISNULL(COUNT(AF1.Id),0) FROM sSetup.tOrgGroupMaster OGM1     
					INNER JOIN sSetup.tOrganizationMaster OM1 ON OGM1.Id = OM1.OrgGroupId   
					INNER JOIN @lTempBatchId TB1 ON TB1.OrgId = OM1.Id  
					LEFT JOIN sSetup.tBatchMaster BM1 ON BM1.Id = TB1.BatchId AND BM1.IsInContext = 1
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM1 ON OGBM1.ID=BM1.OrgGroupBatchId AND OGM1.Id = OGBM1.OrgGroupId   
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM1 ON COGBM1.Id=OGBM1.CommonOrgGroupBatchId   
					LEFT JOIN sAdmission.tAdmissionForm AF1 ON BM1.Id = AF1.BatchId
					LEFT JOIN sAdmission.tAdmissionFormSelected AFS ON AF1.Id = AFS.AdmissionFormId
				    LEFT JOIN sAdmission.tAdmissionStatusMaster ASM ON ASM.Id = AFS.AdmissionStatusId WHERE OGM1.Id<>1 AND COGBM1.Id = COGBM.Id AND OGM1.Id = OGM.Id AND ASM.Id = 3) as ConfirmCount
					
					FROM sSetup.tOrgGroupMaster OGM     
					INNER JOIN sSetup.tOrganizationMaster OM ON OGM.Id = OM.OrgGroupId   
					INNER JOIN @lTempBatchId TB ON TB.OrgId = OM.Id  
					LEFT JOIN sSetup.tBatchMaster BM ON BM.Id = TB.BatchId AND BM.IsInContext = 1
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId AND OGM.Id = OGBM.OrgGroupId   
					--INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId        
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId   
					LEFT JOIN sAdmission.tAdmissionForm AF ON BM.Id = AF.BatchId  
					WHERE   
					OGM.Id<>1 AND  
					COGBM.Id=@rCommonOrgGroupBatchId AND  
					--BM.IsActive = 1  
					BM.Id = TB.BatchId  
					GROUP BY OGM.Id,OGM.Title,COGBM.Id  
					SELECT * FROM sAdmission.tTempAdmissionFormCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))  
				END  
				ELSE  
				BEGIN  
					INSERT INTO sAdmission.tTempAdmissionFormCount  
					SELECT ISNULL(OGM.Id,0) AS OrgGroupId,OGM.Title AS OrgGroupTitle,ISNULL(COUNT(AF.Id),0) AS AdmissionCount,@rCommonOrgGroupBatchId,GetDate(),

					(SELECT ISNULL(COUNT(AF1.Id),0) FROM sSetup.tOrgGroupMaster OGM1     
					INNER JOIN sSetup.tOrganizationMaster OM1 ON OGM1.Id = OM1.OrgGroupId   
					INNER JOIN @lTempBatchId TB1 ON TB1.OrgId = OM1.Id  
					LEFT JOIN sSetup.tBatchMaster BM1 ON BM1.Id = TB1.BatchId  AND BM1.IsInContext = 1
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM1 ON OGBM1.ID=BM1.OrgGroupBatchId AND OGM1.Id = OGBM1.OrgGroupId   
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM1 ON COGBM1.Id=OGBM1.CommonOrgGroupBatchId   
					LEFT JOIN sAdmission.tAdmissionForm AF1 ON BM1.Id = AF1.BatchId
					LEFT JOIN sAdmission.tAdmissionFormSelected AFS ON AF1.Id = AFS.AdmissionFormId
				    LEFT JOIN sAdmission.tAdmissionStatusMaster ASM ON ASM.Id = AFS.AdmissionStatusId WHERE OGM1.Id<>1 AND COGBM1.Id = COGBM.Id AND OGM1.Id = OGM.Id AND ASM.Id IS NULL) as PendingCount,

					(SELECT ISNULL(COUNT(AF1.Id),0) FROM sSetup.tOrgGroupMaster OGM1     
					INNER JOIN sSetup.tOrganizationMaster OM1 ON OGM1.Id = OM1.OrgGroupId   
					INNER JOIN @lTempBatchId TB1 ON TB1.OrgId = OM1.Id  
					LEFT JOIN sSetup.tBatchMaster BM1 ON BM1.Id = TB1.BatchId  AND BM1.IsInContext = 1
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM1 ON OGBM1.ID=BM1.OrgGroupBatchId AND OGM1.Id = OGBM1.OrgGroupId   
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM1 ON COGBM1.Id=OGBM1.CommonOrgGroupBatchId   
					LEFT JOIN sAdmission.tAdmissionForm AF1 ON BM1.Id = AF1.BatchId
					LEFT JOIN sAdmission.tAdmissionFormSelected AFS ON AF1.Id = AFS.AdmissionFormId
				    LEFT JOIN sAdmission.tAdmissionStatusMaster ASM ON ASM.Id = AFS.AdmissionStatusId WHERE OGM1.Id<>1 AND COGBM1.Id = COGBM.Id AND OGM1.Id = OGM.Id AND ASM.Id = 3) as ConfirmCount

					FROM sSetup.tOrgGroupMaster OGM     
					INNER JOIN sSetup.tOrganizationMaster OM ON OGM.Id = OM.OrgGroupId   
					INNER JOIN @lTempBatchId TB ON TB.OrgId = OM.Id  
					LEFT JOIN sSetup.tBatchMaster BM ON BM.Id = TB.BatchId AND BM.IsInContext = 1 
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId AND OGM.Id = OGBM.OrgGroupId   
					--INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId        
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId   
					LEFT JOIN sAdmission.tAdmissionForm AF ON BM.Id = AF.BatchId  
					WHERE   
					OGM.Id<>1 AND  
					COGBM.Id=@rCommonOrgGroupBatchId AND  
					--BM.IsActive = 1  
					BM.Id = TB.BatchId  
					GROUP BY OGM.Id,OGM.Title,COGBM.Id  
					SELECT * FROM sAdmission.tTempAdmissionFormCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))  
				END  
		END
		ELSE
			BEGIN
			 IF  Exists(select 1 from sAdmission.tTempAdmissionFormCount   where CONVERT(date,UpdateDate) =  CONVERT(date,getdate(),102) AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0)) AND CommonOrgGroupBatchId=@rCommonOrgGroupBatchId)   
			 BEGIN  
				 SELECT * FROM sAdmission.tTempAdmissionFormCount   WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))  
				 return  
			 END  
			 ELSE  
			 BEGIN  
				DELETE  sAdmission.tTempAdmissionFormCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))  
				IF EXISTS (SELECT 1 FROM sAdmission.tTempAdmissionFormCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0)))  
				BEGIN  
					IF(@rOrgGroupId !=0)  
        
					INSERT INTO sAdmission.tTempAdmissionFormCount  
					SELECT ISNULL(OGM.Id,0) AS OrgGroupId,OGM.Title AS OrgGroupTitle,ISNULL(COUNT(AF.Id),0) AS AdmissionCount,@rCommonOrgGroupBatchId,GetDate(),
				
					(SELECT ISNULL(COUNT(AF1.Id),0) FROM sSetup.tOrgGroupMaster OGM1     
					INNER JOIN sSetup.tOrganizationMaster OM1 ON OGM1.Id = OM1.OrgGroupId   
					INNER JOIN @lTempBatchId TB1 ON TB1.OrgId = OM1.Id  
					LEFT JOIN sSetup.tBatchMaster BM1 ON BM1.Id = TB1.BatchId AND BM1.IsInContext = 1
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM1 ON OGBM1.ID=BM1.OrgGroupBatchId AND OGM1.Id = OGBM1.OrgGroupId   
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM1 ON COGBM1.Id=OGBM1.CommonOrgGroupBatchId   
					LEFT JOIN sAdmission.tAdmissionForm AF1 ON BM1.Id = AF1.BatchId
					LEFT JOIN sAdmission.tAdmissionFormSelected AFS ON AF1.Id = AFS.AdmissionFormId
					LEFT JOIN sAdmission.tAdmissionStatusMaster ASM ON ASM.Id = AFS.AdmissionStatusId WHERE OGM1.Id<>1 AND COGBM1.Id = COGBM.Id AND OGM1.Id = OGM.Id AND ASM.Id IS NULL) as PendingCount,

					(SELECT ISNULL(COUNT(AF1.Id),0) FROM sSetup.tOrgGroupMaster OGM1     
					INNER JOIN sSetup.tOrganizationMaster OM1 ON OGM1.Id = OM1.OrgGroupId   
					INNER JOIN @lTempBatchId TB1 ON TB1.OrgId = OM1.Id  
					LEFT JOIN sSetup.tBatchMaster BM1 ON BM1.Id = TB1.BatchId  AND BM1.IsInContext = 1
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM1 ON OGBM1.ID=BM1.OrgGroupBatchId AND OGM1.Id = OGBM1.OrgGroupId   
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM1 ON COGBM1.Id=OGBM1.CommonOrgGroupBatchId   
					LEFT JOIN sAdmission.tAdmissionForm AF1 ON BM1.Id = AF1.BatchId
					LEFT JOIN sAdmission.tAdmissionFormSelected AFS ON AF1.Id = AFS.AdmissionFormId
					LEFT JOIN sAdmission.tAdmissionStatusMaster ASM ON ASM.Id = AFS.AdmissionStatusId WHERE OGM1.Id<>1 AND COGBM1.Id = COGBM.Id AND OGM1.Id = OGM.Id AND ASM.Id = 3) as ConfirmCount
					  
					FROM sSetup.tOrgGroupMaster OGM     
					INNER JOIN sSetup.tOrganizationMaster OM ON OGM.Id = OM.OrgGroupId   
					INNER JOIN @lTempBatchId TB ON TB.OrgId = OM.Id  
					LEFT JOIN sSetup.tBatchMaster BM ON BM.Id = TB.BatchId  AND BM.IsInContext = 1
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId AND OGM.Id = OGBM.OrgGroupId   
					--INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId        
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId   
					LEFT JOIN sAdmission.tAdmissionForm AF ON BM.Id = AF.BatchId  
					WHERE   
					OGM.Id<>1 AND  
					COGBM.Id=@rCommonOrgGroupBatchId AND  
					--BM.IsActive = 1  
					BM.Id = TB.BatchId  
					GROUP BY OGM.Id,OGM.Title,COGBM.Id
					SELECT * FROM sAdmission.tTempAdmissionFormCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))  
				END  
				ELSE  
				BEGIN  
					INSERT INTO sAdmission.tTempAdmissionFormCount  
					SELECT ISNULL(OGM.Id,0) AS OrgGroupId,OGM.Title AS OrgGroupTitle,ISNULL(COUNT(AF.Id),0) AS AdmissionCount,@rCommonOrgGroupBatchId,GetDate(),
			
					(SELECT ISNULL(COUNT(AF1.Id),0) FROM sSetup.tOrgGroupMaster OGM1     
					INNER JOIN sSetup.tOrganizationMaster OM1 ON OGM1.Id = OM1.OrgGroupId   
					INNER JOIN @lTempBatchId TB1 ON TB1.OrgId = OM1.Id  
					LEFT JOIN sSetup.tBatchMaster BM1 ON BM1.Id = TB1.BatchId  AND BM1.IsInContext = 1
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM1 ON OGBM1.ID=BM1.OrgGroupBatchId AND OGM1.Id = OGBM1.OrgGroupId   
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM1 ON COGBM1.Id=OGBM1.CommonOrgGroupBatchId   
					LEFT JOIN sAdmission.tAdmissionForm AF1 ON BM1.Id = AF1.BatchId
					LEFT JOIN sAdmission.tAdmissionFormSelected AFS ON AF1.Id = AFS.AdmissionFormId
					LEFT JOIN sAdmission.tAdmissionStatusMaster ASM ON ASM.Id = AFS.AdmissionStatusId WHERE OGM1.Id<>1 AND COGBM1.Id = COGBM.Id AND OGM1.Id = OGM.Id AND ASM.Id IS NULL) as PendingCount,

					(SELECT ISNULL(COUNT(AF1.Id),0) FROM sSetup.tOrgGroupMaster OGM1     
					INNER JOIN sSetup.tOrganizationMaster OM1 ON OGM1.Id = OM1.OrgGroupId   
					INNER JOIN @lTempBatchId TB1 ON TB1.OrgId = OM1.Id  
					LEFT JOIN sSetup.tBatchMaster BM1 ON BM1.Id = TB1.BatchId AND BM1.IsInContext = 1 
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM1 ON OGBM1.ID=BM1.OrgGroupBatchId AND OGM1.Id = OGBM1.OrgGroupId   
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM1 ON COGBM1.Id=OGBM1.CommonOrgGroupBatchId   
					LEFT JOIN sAdmission.tAdmissionForm AF1 ON BM1.Id = AF1.BatchId
					LEFT JOIN sAdmission.tAdmissionFormSelected AFS ON AF1.Id = AFS.AdmissionFormId
					LEFT JOIN sAdmission.tAdmissionStatusMaster ASM ON ASM.Id = AFS.AdmissionStatusId WHERE OGM1.Id<>1 AND COGBM1.Id = COGBM.Id AND OGM1.Id = OGM.Id AND ASM.Id = 3) as ConfirmCount
				     
					FROM sSetup.tOrgGroupMaster OGM     
					INNER JOIN sSetup.tOrganizationMaster OM ON OGM.Id = OM.OrgGroupId   
					INNER JOIN @lTempBatchId TB ON TB.OrgId = OM.Id  
					LEFT JOIN sSetup.tBatchMaster BM ON BM.Id = TB.BatchId AND BM.IsInContext = 1   
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId AND OGM.Id = OGBM.OrgGroupId   
					--INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId        
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId   
					LEFT JOIN sAdmission.tAdmissionForm AF ON BM.Id = AF.BatchId  
					WHERE   
					OGM.Id<>1 AND  
					COGBM.Id=@rCommonOrgGroupBatchId AND  
					--BM.IsActive = 1  
					BM.Id = TB.BatchId  
					GROUP BY OGM.Id,OGM.Title,COGBM.Id  
					SELECT * FROM sAdmission.tTempAdmissionFormCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))  
				END  
			END  
		END
	END
-- For Admission TypeId=1
	IF(@rType='Organization')
		BEGIN
			SELECT ISNULL(OM.Id,0) AS OrgId,OM.Title AS Organization,ISNULL(COUNT(AF.Id),0) AS AdmissionCount,OM.OrderIndex
			FROM sAdmission.tAdmissionForm AF 
			LEFT JOIN  sSetup.tOrganizationMaster OM ON AF.OrgId = OM.Id 
			LEFT JOIN sSetup.tBatchMaster BM ON BM.Id = AF.BatchId AND BM.IsInContext = 1
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			
			
			LEFT JOIN @lTempBatchId TB ON TB.OrgId = OM.Id and BM.Id = TB.BatchId
			WHERE --BM.IsActive = 1 
			OM.OrgGroupId = @rOrgGroupId 	
			AND BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId 
			And ISNULL(O.IsObsolete,0) = 0
			GROUP BY OM.Id,OM.Title,OM.OrderIndex
			Order BY OM.OrderIndex
		END
-- For Admission TypeId=1
	IF(@rType='Status')
		BEGIN
			SELECT ISNULL(ASM.Id,0) AS InquiryStatusId,ISNULL(OM.Id,0) AS OrgId,OM.Title AS Organization, ISNULL(ASM.Title,'Pending') AS StatusName ,ISNULL(COUNT(AF.Id),0) AS StatusCount ,0 AS InquiryMainStatusId
			,OM.OrderIndex
			FROM sAdmission.tAdmissionForm AF 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AF.BatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			
			INNER JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AF.OrgId = OM.Id
			LEFT JOIN sAdmission.tAdmissionFormSelected AFS ON AF.Id = AFS.AdmissionFormId
			LEFT JOIN sAdmission.tAdmissionStatusMaster ASM ON ASM.Id = AFS.AdmissionStatusId
			WHERE --BM.IsActive = 1 
			BM.Id = TB.BatchId AND OM.Id = @rOrgId AND COGBM.Id=@rCommonOrgGroupBatchId 
			And ISNULL(O.IsObsolete,0) = 0
			AND BM.IsInContext = 1
			GROUP BY OM.Id,OM.Title,ASM.Id,ASM.Title,OM.OrderIndex
			Order By OM.OrderIndex
		END
-- For Admission TypeId=1
	IF(@rType='StatusOrgGroupWise')
		BEGIN
		    CREATE Table #MyTempTable(
						  OrgId Int,
						  Organization nvarchar(100),
                          StatusName nvarchar(100),
                          StatusCount BigInt)
            INSERT INTO #MyTempTable(OrgId,Organization,StatusName,StatusCount)
			SELECT OM.Id,OM.Title AS Organization, ISNULL(ASM.Title,'Pending') AS StatusName ,AF.Id AS StatusCount 			
			FROM sAdmission.tAdmissionForm AF 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AF.BatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			
			INNER JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AF.OrgId = OM.Id
			
			LEFT JOIN sAdmission.tAdmissionFormSelected AFS ON AF.Id = AFS.AdmissionFormId
			LEFT JOIN sAdmission.tAdmissionStatusMaster ASM ON ASM.Id = AFS.AdmissionStatusId
			WHERE --BM.IsActive = 1 
			BM.Id = TB.BatchId
			AND OM.OrgGroupId = @rOrgGroupId AND COGBM.Id=@rCommonOrgGroupBatchId
			And ISNULL(O.IsObsolete,0) = 0
			AND BM.IsInContext = 1

	DECLARE 
    @columns NVARCHAR(MAX) = '', 
    @sql     NVARCHAR(MAX) = '';

	SELECT 
    @columns+=QUOTENAME(ASM.Title) + ','
  FROM 
    sAdmission.tAdmissionStatusMaster ASM
  ORDER BY 
    ASM.Title;
  -- Add Pending Column
  SET @columns = LEFT(@columns, LEN(@columns) - 1)+',Pending';


  -- construct dynamic SQL
  SET @sql ='
  SELECT * FROM #MyTempTable MT  
  PIVOT(
    Count(MT.StatusCount)
    FOR MT.StatusName IN ('+ @columns +')
  ) AS pivot_table;';

  -- execute the dynamic SQL
  EXECUTE sp_executesql @sql;
  DROP Table #MyTempTable
		END

	--For Admission Form Count
	IF(@rType='AdmissionFormOrgGroupWise')
	BEGIN
		SELECT ISNULL(ASM.Id,0) AS InquiryStatusId,ISNULL(OM.Id,0) AS OrgId,OM.Title AS Organization, ISNULL(ASM.Title,'Pending') AS StatusName ,ISNULL(COUNT(AF.Id),0) AS StatusCount , 0 AS InquiryMainStatusId
		,OM.OrderIndex
		FROM sAdmission.tAdmissionForm AF 
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AF.BatchId
		INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		   INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		   INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		
		INNER JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
		INNER JOIN sSetup.tOrganizationMaster OM ON AF.OrgId = OM.Id
		
		LEFT JOIN sAdmission.tAdmissionFormSelected AFS ON AF.Id = AFS.AdmissionFormId
		LEFT JOIN sAdmission.tAdmissionStatusMaster ASM ON ASM.Id = AFS.AdmissionStatusId
		WHERE --BM.IsActive = 1 
		BM.Id = TB.BatchId
		AND BM.IsInContext = 1
		AND OM.OrgGroupId = @rOrgGroupId AND COGBM.Id=@rCommonOrgGroupBatchId
		And ISNULL(O.IsObsolete,0) = 0
		GROUP BY OM.Id,OM.Title,ASM.Id,ASM.Title,OM.OrderIndex
		Order BY OM.OrderIndex	
	END

	IF(@rType='AdmissionFormStatusWise')
	BEGIN
		SELECT ISNULL(ASM.Id,0) AS InquiryStatusId,ISNULL(OM.Id,0) AS OrgId,OM.Title AS Organization, ISNULL(ASM.Title,'Pending') AS StatusName ,ISNULL(COUNT(AF.Id),0) AS StatusCount , 0 AS InquiryMainStatusId
		,OM.OrderIndex
		FROM sAdmission.tAdmissionForm AF 
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AF.BatchId
		INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		   INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		   INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		
		INNER JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
		INNER JOIN sSetup.tOrganizationMaster OM ON AF.OrgId = OM.Id
		
		LEFT JOIN sAdmission.tAdmissionFormSelected AFS ON AF.Id = AFS.AdmissionFormId
		LEFT JOIN sAdmission.tAdmissionStatusMaster ASM ON ASM.Id = AFS.AdmissionStatusId
		WHERE --BM.IsActive = 1 
		BM.Id = TB.BatchId
		AND BM.IsInContext = 1
		AND OM.OrgGroupId = @rOrgGroupId AND COGBM.Id=@rCommonOrgGroupBatchId
		And ISNULL(O.IsObsolete,0) = 0
		AND ISNULL(ASM.Id,0)=@rInquiryStatusId
		GROUP BY OM.Id,OM.Title,ASM.Id,ASM.Title,OM.OrderIndex
		Order BY OM.OrderIndex	
	END
-- For Admission TypeId=1
	ELSE IF(@rType='StatusClassWise')
		BEGIN
		
			SELECT CM.Id AS ClassId,CM.DisplayTitle AS ClassName,ISNULL(COUNT(AF.Id),0) AS StatusCount ,CM.OrderIndex 
			FROM sAdmission.tAdmissionForm AF 
			INNER JOIN sSetup.tClassMaster CM ON CM.Id = AF.ForClassId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AF.BatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
			INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
			INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			INNER JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AF.OrgId = OM.Id

			LEFT JOIN sAdmission.tAdmissionFormSelected AFS ON AF.Id = AFS.AdmissionFormId
			LEFT JOIN sAdmission.tAdmissionStatusMaster ASM ON ASM.Id = AFS.AdmissionStatusId
			WHERE --BM.IsActive = 1 
			BM.Id = TB.BatchId
			AND OM.OrgGroupId = @rOrgGroupId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISNULL(ASM.Id,0)=@rInquiryStatusId
			And ISNULL(O.IsObsolete,0) = 0
			AND((CM.OrgId = @rOrgId)OR(@rOrgId=0))
			AND BM.IsInContext = 1
			GROUP BY CM.Id,CM.DisplayTitle,CM.OrderIndex
		END
-- For Admission TypeId=1
ELSE IF(@rType='StatusClassWise')
		BEGIN
		
			SELECT CM.Id AS ClassId,CM.DisplayTitle AS ClassName,ISNULL(COUNT(AF.Id),0) AS StatusCount ,CM.OrderIndex 
			FROM sAdmission.tAdmissionForm AF 
			INNER JOIN sSetup.tClassMaster CM ON CM.Id = AF.ForClassId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AF.BatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
			INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
			INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			INNER JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AF.OrgId = OM.Id

			LEFT JOIN sAdmission.tAdmissionFormSelected AFS ON AF.Id = AFS.AdmissionFormId
			LEFT JOIN sAdmission.tAdmissionStatusMaster ASM ON ASM.Id = AFS.AdmissionStatusId
			WHERE --BM.IsActive = 1 
			BM.Id = TB.BatchId
			AND OM.OrgGroupId = @rOrgGroupId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISNULL(ASM.Id,0)=@rInquiryStatusId
			And ISNULL(O.IsObsolete,0) = 0
			AND((CM.OrgId = @rOrgId)OR(@rOrgId=0))
			AND BM.IsInContext = 1
			GROUP BY CM.Id,CM.DisplayTitle,CM.OrderIndex
		END
-- For Admission TypeId=1
ELSE IF(@rType='StatusStudentList')
			BEGIN
			SELECT AF.FormNo As InquiryId, AF.FirstName+' '+AF.MiddleName +' '+ AF.LastName AS StudentName,AF.ContactNo AS ContactNo 
			FROM sAdmission.tAdmissionForm AF 
			INNER JOIN sSetup.tClassMaster CM ON CM.Id = AF.ForClassId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AF.BatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
			INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
			INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			INNER JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AF.OrgId = OM.Id
			LEFT JOIN sAdmission.tAdmissionFormSelected AFS ON AF.Id = AFS.AdmissionFormId
			LEFT JOIN sAdmission.tAdmissionStatusMaster ASM ON ASM.Id = AFS.AdmissionStatusId
			WHERE --BM.IsActive = 1 
			BM.Id = TB.BatchId
			AND OM.OrgGroupId = @rOrgGroupId 
			AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISNULL(ASM.Id,0)=@rInquiryStatusId
			AND((CM.OrgId = @rOrgId)OR(@rOrgId=0))
			AND((CM.Id = @rClassId)OR(@rClassId=0))
			And ISNULL(O.IsObsolete,0) = 0
			AND BM.IsInContext = 1
			GROUP BY AF.FirstName,AF.MiddleName,AF.LastName,AF.ContactNo,AF.FormNo
			END
			END
	
-- For Inquiry
	IF(@rTypeId=2)
	BEGIN
	IF(@rType='OrgGroup')
		BEGIN
			IF(@rSyncDate =1)
				BEGIN
			DELETE  sAdmission.tTempAdmissionInquiryCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))  
			IF EXISTS (SELECT 1 FROM sAdmission.tTempAdmissionInquiryCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND (OrgGroupId = @rOrgGroupId))  
				   BEGIN  
				   IF(@rOrgGroupId !=0)  
				   INSERT INTO sAdmission.tTempAdmissionInquiryCount  
					SELECT ISNULL(OGM.Id,0) AS OrgGroupId,OGM.Title AS OrgGroupTitle,ISNULL(COUNT(AI.Id),0) AS AdmissionCount,@rCommonOrgGroupBatchId,GetDate()  
					FROM   
					sSetup.tOrgGroupMaster OGM  
					INNER JOIN sSetup.tOrganizationMaster OM ON OGM.Id = OM.OrgGroupId   
			        
					INNER JOIN @lTempBatchId TB ON TB.OrgId = OM.Id  
					LEFT JOIN sSetup.tBatchMaster BM ON BM.Id = TB.BatchId AND BM.IsInContext = 1
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId  
					INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId        
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId   
			        
					LEFT JOIN sAdmission.tAdmissionInquiry AI ON BM.Id = AI.ForBatchId    
					WHERE OGM.Id<>1 and BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId   
					--BM.IsActive = 1  
					GROUP BY OGM.Id,OGM.Title  
					SELECT OrgGroupTitle AS OrgGroup,0 AS PendingCount,0 AS ConfirmCount,* FROM sAdmission.tTempAdmissionInquiryCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))  
				   END  
      ELSE   
       BEGIN  
		    INSERT INTO sAdmission.tTempAdmissionInquiryCount  
        SELECT ISNULL(OGM.Id,0) AS OrgGroupId,OGM.Title AS OrgGroupTitle,ISNULL(COUNT(AI.Id),0) AS AdmissionCount,@rCommonOrgGroupBatchId,GetDate()  
       FROM   
       sSetup.tOrgGroupMaster OGM  
       INNER JOIN sSetup.tOrganizationMaster OM ON OGM.Id = OM.OrgGroupId   
       
       INNER JOIN @lTempBatchId TB ON TB.OrgId = OM.Id  
       LEFT JOIN sSetup.tBatchMaster BM ON BM.Id = TB.BatchId AND BM.IsInContext = 1
       INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId  
       INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId        
       INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId   
       LEFT JOIN sAdmission.tAdmissionInquiry AI ON BM.Id = AI.ForBatchId  
       WHERE OGM.Id<>1 and BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId   
       --BM.IsActive = 1  
       GROUP BY OGM.Id,OGM.Title  
		  SELECT OrgGroupTitle AS OrgGroup,0 AS PendingCount,0 AS ConfirmCount,* FROM sAdmission.tTempAdmissionInquiryCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))  
       END  
				END
			ELSE
				BEGIN
						IF  Exists(select 1 from sAdmission.tTempAdmissionInquiryCount   where CONVERT(date,UpdateDate) =  CONVERT(date,getdate(),102)   AND CommonOrgGroupBatchId=@rCommonOrgGroupBatchId  AND (OrgGroupId = @rOrgGroupId))  
			  BEGIN  
			   SELECT  OrgGroupTitle AS OrgGroup,0 AS PendingCount,0 AS ConfirmCount,* FROM sAdmission.tTempAdmissionInquiryCount   WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))  
			   return  
			  END  
			 ELSE  
			  BEGIN  
			  DELETE  sAdmission.tTempAdmissionInquiryCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))  
			  IF EXISTS (SELECT 1 FROM sAdmission.tTempAdmissionInquiryCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0)))  
			   BEGIN  
				IF(@rOrgGroupId !=0)  
				INSERT INTO sAdmission.tTempAdmissionInquiryCount  
				 SELECT ISNULL(OGM.Id,0) AS OrgGroupId,OGM.Title AS OrgGroupTitle,ISNULL(COUNT(AI.Id),0) AS AdmissionCount,@rCommonOrgGroupBatchId,GetDate()  
				FROM   
				sSetup.tOrgGroupMaster OGM  
				INNER JOIN sSetup.tOrganizationMaster OM ON OGM.Id = OM.OrgGroupId   
		        
				INNER JOIN @lTempBatchId TB ON TB.OrgId = OM.Id  
				LEFT JOIN sSetup.tBatchMaster BM ON BM.Id = TB.BatchId AND BM.IsInContext = 1
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId  
				INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId        
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId   
		        
				LEFT JOIN sAdmission.tAdmissionInquiry AI ON BM.Id = AI.ForBatchId  
				WHERE OGM.Id<>1 and BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId   
				--BM.IsActive = 1  
				GROUP BY OGM.Id,OGM.Title  
				SELECT OrgGroupTitle AS OrgGroup,0 AS PendingCount,0 AS ConfirmCount,* FROM sAdmission.tTempAdmissionInquiryCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))  
			   END  
			  ELSE  
			   BEGIN  
				DELETE  sAdmission.tTempAdmissionInquiryCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))  
				INSERT INTO sAdmission.tTempAdmissionInquiryCount  
				 SELECT ISNULL(OGM.Id,0) AS OrgGroupId,OGM.Title AS OrgGroupTitle,ISNULL(COUNT(AI.Id),0) AS AdmissionCount,@rCommonOrgGroupBatchId,GetDate()  
				FROM   
				sSetup.tOrgGroupMaster OGM  
				INNER JOIN sSetup.tOrganizationMaster OM ON OGM.Id = OM.OrgGroupId   
				INNER JOIN @lTempBatchId TB ON TB.OrgId = OM.Id  
				LEFT JOIN sSetup.tBatchMaster BM ON BM.Id = TB.BatchId AND BM.IsInContext = 1
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId  
				INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId        
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId   
				LEFT JOIN sAdmission.tAdmissionInquiry AI ON BM.Id = AI.ForBatchId  
				WHERE OGM.Id<>1 and BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId   
				--BM.IsActive = 1  
				GROUP BY OGM.Id,OGM.Title  
				SELECT OrgGroupTitle AS OrgGroup,0 AS PendingCount,0 AS ConfirmCount,* FROM sAdmission.tTempAdmissionInquiryCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))  
       END  
		END  
		 END		
		END
-- For Inquiry
	IF(@rType='Organization')
		BEGIN
			SELECT ISNULL(OM.Id,0) AS OrgId,OM.Title AS Organization,ISNULL(COUNT(AI.Id),0) AS AdmissionCount,OM.OrderIndex
			FROM sAdmission.tAdmissionInquiry AI 
			LEFT JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId AND BM.IsInContext = 1
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			
			--sAdmission.tAdmissionForm AF 
			--LEFT JOIN  sSetup.tOrganizationMaster OM ON AF.OrgId = OM.Id 	
			--LEFT JOIN sSetup.tBatchMaster BM ON BM.Id = AF.BatchId
			--LEFT JOIN @lTempBatchId TB ON TB.OrgId = OM.Id and BM.Id = TB.BatchId
			WHERE BM.Id = TB.BatchId
			And ISNULL(O.IsObsolete,0) = 0
			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId AND COGBM.Id=@rCommonOrgGroupBatchId
			GROUP BY OM.Id,OM.Title,OM.OrderIndex
			ORDER BY OM.OrderIndex
		END
-- For Inquiry
	IF(@rType='Status')
		BEGIN
		IF(@lConfigValue = 'True')
		BEGIN
-- 11
-- Inquiry Form 
			SELECT 
			ISM.Id AS InquiryStatusId,
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM.Title,'') AS StatusName,
			(
			SELECT 
			ISNULL(COUNT(ISM.Id),0) AS StatusCount 
			FROM sAdmission.tAdmissionInquiry AI1 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI1.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI1.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI1.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId >= 11
			AND((OM.Id = @rOrgId)OR(@rOrgId=0)) AND OM.Id = AI.OrgId
			AND BM.IsInContext = 1
			) AS StatusCount,
			ISM.InquiryMainStatusId AS InquiryMainStatusId
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId = 11
			--BM.IsActive = 1 
			AND((OM.Id = @rOrgId)OR(@rOrgId=0))
			And ISNULL(O.IsObsolete,0) = 0
			AND BM.IsInContext = 1
			
			GROUP BY OM.Id,OM.Title,ISM.Id,ISM.Title,ISM.InquiryMainStatusId,AI.OrgId
			
			UNION ALL
-- 21
-- Admission Form Given
			SELECT 
			ISM.Id AS InquiryStatusId,
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM.Title,'') AS StatusName,
			(
			SELECT 
			ISNULL(COUNT(ISM.Id),0) AS StatusCount 
			FROM sAdmission.tAdmissionInquiry AI1
			INNER JOIN sSetup.tClassMaster CM ON CM.Id = AI1.ForClassId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI1.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI1.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI1.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId > 11
			--BM.IsActive = 1 
			AND((OM.Id = @rOrgId)OR(@rOrgId=0)) AND OM.Id = AI.OrgId AND BM.IsInContext = 1
			) AS StatusCount,
			ISM.InquiryMainStatusId AS InquiryMainStatusId
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId = 21
			--BM.IsActive = 1 
			AND((OM.Id = @rOrgId)OR(@rOrgId=0))
			And ISNULL(O.IsObsolete,0) = 0
			AND BM.IsInContext = 1
			GROUP BY OM.Id,OM.Title,ISM.Id,ISM.Title,ISM.InquiryMainStatusId,AI.OrgId
			
			UNION ALL
-- 31
-- Admission Form Submitted
			SELECT 
			ISM.Id AS InquiryStatusId,
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM.Title,'') AS StatusName,
			(
			SELECT 
			ISNULL(COUNT(ISM.Id),0) AS StatusCount 
			FROM sAdmission.tAdmissionInquiry AI1 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI1.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI1.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI1.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId > 21
			--BM.IsActive = 1 
			AND((OM.Id = @rOrgId)OR(@rOrgId=0))  AND OM.Id = AI.OrgId
			AND BM.IsInContext = 1
			) AS StatusCount ,
			ISM.InquiryMainStatusId AS InquiryMainStatusId
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId =31
			--BM.IsActive = 1 
			AND((OM.Id = @rOrgId)OR(@rOrgId=0))
			And ISNULL(O.IsObsolete,0) = 0
			AND BM.IsInContext = 1
			GROUP BY OM.Id,OM.Title,ISM.Id,ISM.Title,ISM.InquiryMainStatusId,AI.OrgId
			
			UNION ALL
-- 41
-- Appeared For Entrance Exam
			SELECT 
			ISM.Id AS InquiryStatusId,
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM.Title,'') AS StatusName,
			(
			SELECT 
			ISNULL(COUNT(ISM.Id),0) AS StatusCount 
			FROM sAdmission.tAdmissionInquiry AI1 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI1.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI1.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI1.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId > 31
			--BM.IsActive = 1 
			AND((OM.Id = @rOrgId)OR(@rOrgId=0))  AND OM.Id = AI.OrgId
			AND BM.IsInContext = 1
			) AS StatusCount  ,
			ISM.InquiryMainStatusId AS InquiryMainStatusId
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId =41
			--BM.IsActive = 1 
			AND((OM.Id = @rOrgId)OR(@rOrgId=0))
			And ISNULL(O.IsObsolete,0) = 0
			AND BM.IsInContext = 1
			GROUP BY OM.Id,OM.Title,ISM.Id,ISM.Title,ISM.InquiryMainStatusId,AI.OrgId
			
			UNION ALL
-- 51
-- Came for Interaction
			SELECT 
			ISM.Id AS InquiryStatusId,
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM.Title,'') AS StatusName,
			(
			SELECT 
			ISNULL(COUNT(ISM.Id),0) AS StatusCount 
			FROM sAdmission.tAdmissionInquiry AI1
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI1.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI1.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI1.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId > 41 and ISM.InquiryMainStatusId <> 61

			--BM.IsActive = 1 
			AND((OM.Id = @rOrgId)OR(@rOrgId=0)) AND OM.Id = AI.OrgId
			AND BM.IsInContext = 1
			) AS StatusCount  ,
			ISM.InquiryMainStatusId AS InquiryMainStatusId
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId =51 
			--BM.IsActive = 1 
			AND((OM.Id = @rOrgId)OR(@rOrgId=0))
			And ISNULL(O.IsObsolete,0) = 0
			AND BM.IsInContext = 1
			GROUP BY OM.Id,OM.Title,ISM.Id,ISM.Title,ISM.InquiryMainStatusId,AI.OrgId
			
			UNION ALL
-- 61
-- Not Came for interaction
			SELECT 
			ISM.Id AS InquiryStatusId,
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM.Title,'') AS StatusName,
			(
			SELECT 
			ISNULL(COUNT(ISM.Id),0) AS StatusCount 
			FROM sAdmission.tAdmissionInquiry AI1
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI1.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI1.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI1.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			--AND ISM.InquiryMainStatusId > 51  AND ISM.InquiryMainStatusId !=71
			AND ISM.InquiryMainStatusId = 61

			--BM.IsActive = 1 
			AND((OM.Id = @rOrgId)OR(@rOrgId=0))  AND OM.Id = AI.OrgId
			AND BM.IsInContext = 1
			) AS StatusCount  ,
			ISM.InquiryMainStatusId AS InquiryMainStatusId
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId = 61 

			--BM.IsActive = 1 
			AND((OM.Id = @rOrgId)OR(@rOrgId=0))
			And ISNULL(O.IsObsolete,0) = 0
			AND BM.IsInContext = 1
			GROUP BY OM.Id,OM.Title,ISM.Id,ISM.Title,ISM.InquiryMainStatusId,AI.OrgId
		
		    UNION ALL
			
-- 71
--Confirmed Admission

			SELECT
			ISM.Id AS InquiryStatusId, 
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM.Title,'') AS StatusName,
			(
			SELECT 
			ISNULL(COUNT(ISM.Id),0) AS StatusCount 
			FROM sAdmission.tAdmissionInquiry AI1
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI1.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI1.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI1.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId > 61 

			--BM.IsActive = 1 
			AND((OM.Id = @rOrgId)OR(@rOrgId=0))  AND OM.Id = AI.OrgId
			AND BM.IsInContext = 1
			) AS StatusCount  ,
			ISM.InquiryMainStatusId AS InquiryMainStatusId
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId =71
			--BM.IsActive = 1 
			AND((OM.Id = @rOrgId)OR(@rOrgId=0))
			And ISNULL(O.IsObsolete,0) = 0
			AND BM.IsInContext = 1
			GROUP BY OM.Id,OM.Title,ISM.Id,ISM.Title,ISM.InquiryMainStatusId,AI.OrgId
			UNION ALL
-- 81
-- Rejected Form
			SELECT 
			ISM.Id AS InquiryStatusId,
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM.Title,'') AS StatusName,
			(
			SELECT 
			ISNULL(COUNT(ISM.Id),0) AS StatusCount 
			FROM sAdmission.tAdmissionInquiry AI1 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI1.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI1.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI1.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId =81
			--BM.IsActive = 1 
			AND((OM.Id = @rOrgId)OR(@rOrgId=0)) AND OM.Id = AI.OrgId
			AND BM.IsInContext = 1
			) AS StatusCount  ,
			ISM.InquiryMainStatusId AS InquiryMainStatusId
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId =81
			--BM.IsActive = 1 
			AND((OM.Id = @rOrgId)OR(@rOrgId=0))
			And ISNULL(O.IsObsolete,0) = 0
			AND BM.IsInContext = 1
			GROUP BY OM.Id,OM.Title,ISM.Id,ISM.Title,ISM.InquiryMainStatusId,AI.OrgId
			UNION ALL
-- 91
-- Fees Paid

			SELECT 
			ISM.Id AS InquiryStatusId,
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM.Title,'') AS StatusName,
			(
			SELECT 
			ISNULL(COUNT(ISM.Id),0) AS StatusCount 
			FROM sAdmission.tAdmissionInquiry AI1 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI1.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI1.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI1.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId > 81 AND ISM.InquiryMainStatusId !=101

			--BM.IsActive = 1 
			AND((OM.Id = @rOrgId)OR(@rOrgId=0))  AND OM.Id = AI.OrgId
			AND BM.IsInContext = 1
			) AS StatusCount ,
			ISM.InquiryMainStatusId AS InquiryMainStatusId 
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId =91

 
			--BM.IsActive = 1 
			AND((OM.Id = @rOrgId)OR(@rOrgId=0))
			And ISNULL(O.IsObsolete,0) = 0
			AND BM.IsInContext = 1
			GROUP BY OM.Id,OM.Title,ISM.Id,ISM.Title,ISM.InquiryMainStatusId,AI.OrgId
			UNION ALL
-- 101		
-- Fees not paid
			SELECT 
			ISM.Id AS InquiryStatusId,
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM.Title,'') AS StatusName,
			(
			SELECT 
			ISNULL(COUNT(ISM.Id),0) AS StatusCount 
			FROM sAdmission.tAdmissionInquiry AI1 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI1.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI1.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI1.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId =101
			--BM.IsActive = 1 
			AND((OM.Id = @rOrgId)OR(@rOrgId=0))AND OM.Id = AI.OrgId
			AND BM.IsInContext = 1
			) AS StatusCount ,
			ISM.InquiryMainStatusId AS InquiryMainStatusId 
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId =101
			--BM.IsActive = 1 
			AND((OM.Id = @rOrgId)OR(@rOrgId=0))
			And ISNULL(O.IsObsolete,0) = 0
			AND BM.IsInContext = 1
			GROUP BY OM.Id,OM.Title,ISM.Id,ISM.Title,ISM.InquiryMainStatusId,AI.OrgId
			UNION ALL
-- 111			
-- Refunded Fees
			SELECT 
			ISM.Id AS InquiryStatusId,
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM.Title,'') AS StatusName,
			(
			SELECT 
			ISNULL(COUNT(ISM.Id),0) AS StatusCount 
			FROM sAdmission.tAdmissionInquiry AI1 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI1.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI1.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI1.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId > 101

			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId  AND OM.Id = AI.OrgId
			AND BM.IsInContext = 1
			) AS StatusCount  ,
			ISM.InquiryMainStatusId AS InquiryMainStatusId
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId =111
 
			--BM.IsActive = 1 
			AND((OM.Id = @rOrgId)OR(@rOrgId=0))
			And ISNULL(O.IsObsolete,0) = 0
			AND BM.IsInContext = 1
			GROUP BY OM.Id,OM.Title,ISM.Id,ISM.Title,ISM.InquiryMainStatusId,AI.OrgId
		END
		ELSE 
		BEGIN
			SELECT 
			ISM1.Id AS InquiryStatusId,
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM1.Title,'') AS StatusName,
			ISNULL(COUNT(ISM1.Id),0) AS StatusCount, 
			ISM1.InquiryMainStatusId AS InquiryMainStatusId
			,OM.OrderIndex
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM1 ON ISM1.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			--AND ISM.InquiryMainStatusId = 11
			--BM.IsActive = 1 
			AND((OM.Id = @rOrgId)OR(@rOrgId=0))
			And ISNULL(O.IsObsolete,0) = 0
			AND BM.IsInContext = 1
			GROUP BY OM.Id,OM.Title,ISM1.Id,ISM1.Title,ISM1.InquiryMainStatusId,AI.OrgId,OM.OrderIndex
			ORDER BY OM.OrderIndex
		END
		END
		
	IF(@rType='StatusOrgGroupWise')
		BEGIN
		IF(@lConfigValue = 'True')
		BEGIN

-- 11
-- Inquiry Form 
			SELECT 
			ISM.Id AS InquiryStatusId,
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM.Title,'') AS StatusName,
			(
			SELECT 
			ISNULL(COUNT(ISM.Id),0) AS StatusCount 
			FROM sAdmission.tAdmissionInquiry AI1 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI1.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI1.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI1.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId >= 11
			AND OM.OrgGroupId = @rOrgGroupId AND OM.Id = AI.OrgId
			AND BM.IsInContext = 1
			) AS StatusCount,
			ISNULL(ISM.InquiryMainStatusId,0) AS InquiryMainStatusId
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId = 11
			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId
			And ISNULL(O.IsObsolete,0) = 0
			AND BM.IsInContext = 1
			GROUP BY OM.Id,OM.Title,ISM.Id,ISM.Title,ISM.InquiryMainStatusId,AI.OrgId
			
			UNION ALL
-- 21
-- Admission Form Given
			SELECT 
			ISM.Id AS InquiryStatusId,
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM.Title,'') AS StatusName,
			(
			SELECT 
			ISNULL(COUNT(ISM.Id),0) AS StatusCount 
			FROM sAdmission.tAdmissionInquiry AI1
			INNER JOIN sSetup.tClassMaster CM ON CM.Id = AI1.ForClassId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI1.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI1.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI1.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId > 11
			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId AND OM.Id = AI.OrgId
			AND BM.IsInContext = 1
			) AS StatusCount,
			ISM.InquiryMainStatusId AS InquiryMainStatusId
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId = 21
			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId
			And ISNULL(O.IsObsolete,0) = 0
			AND BM.IsInContext = 1
			GROUP BY OM.Id,OM.Title,ISM.Id,ISM.Title,ISM.InquiryMainStatusId,AI.OrgId
			
			UNION ALL
-- 31
-- Admission Form Submitted
			SELECT 
			ISM.Id AS InquiryStatusId,
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM.Title,'') AS StatusName,
			(
			SELECT 
			ISNULL(COUNT(ISM.Id),0) AS StatusCount 
			FROM sAdmission.tAdmissionInquiry AI1 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI1.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI1.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI1.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId > 21
			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId  AND OM.Id = AI.OrgId
			AND BM.IsInContext = 1
			) AS StatusCount ,
			ISM.InquiryMainStatusId AS InquiryMainStatusId
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId =31
			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId
			And ISNULL(O.IsObsolete,0) = 0
			AND BM.IsInContext = 1
			GROUP BY OM.Id,OM.Title,ISM.Id,ISM.Title,ISM.InquiryMainStatusId,AI.OrgId
			
			UNION ALL
-- 41
-- Appeared For Entrance Exam
			SELECT 
			ISM.Id AS InquiryStatusId,
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM.Title,'') AS StatusName,
			(
			SELECT 
			ISNULL(COUNT(ISM.Id),0) AS StatusCount 
			FROM sAdmission.tAdmissionInquiry AI1 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI1.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI1.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI1.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId > 31
			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId  AND OM.Id = AI.OrgId
			AND BM.IsInContext = 1
			) AS StatusCount  ,
			ISM.InquiryMainStatusId AS InquiryMainStatusId
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId =41
			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId
			And ISNULL(O.IsObsolete,0) = 0
			AND BM.IsInContext = 1
			GROUP BY OM.Id,OM.Title,ISM.Id,ISM.Title,ISM.InquiryMainStatusId,AI.OrgId
			
			
			
			UNION ALL
-- 51
-- Came for Interaction
			SELECT 
			ISM.Id AS InquiryStatusId,
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM.Title,'') AS StatusName,
			(
			SELECT 
			ISNULL(COUNT(ISM.Id),0) AS StatusCount 
			FROM sAdmission.tAdmissionInquiry AI1
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI1.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI1.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI1.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId > 41 and ISM.InquiryMainStatusId <> 61

			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId AND OM.Id = AI.OrgId
			AND BM.IsInContext = 1
			) AS StatusCount  ,
			ISM.InquiryMainStatusId AS InquiryMainStatusId
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId =51 
			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId
			And ISNULL(O.IsObsolete,0) = 0
			AND BM.IsInContext = 1
			GROUP BY OM.Id,OM.Title,ISM.Id,ISM.Title,ISM.InquiryMainStatusId,AI.OrgId
			
			UNION ALL
-- 61
-- Not Came for interaction
			SELECT 
			ISM.Id AS InquiryStatusId,
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM.Title,'') AS StatusName,
			(
			SELECT 
			ISNULL(COUNT(ISM.Id),0) AS StatusCount 
			FROM sAdmission.tAdmissionInquiry AI1
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI1.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI1.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI1.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			--AND ISM.InquiryMainStatusId > 51  AND ISM.InquiryMainStatusId !=71
			AND ISM.InquiryMainStatusId = 61

			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId  AND OM.Id = AI.OrgId
			AND BM.IsInContext = 1
			) AS StatusCount  ,
			ISM.InquiryMainStatusId AS InquiryMainStatusId
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId = 61 

			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId
			And ISNULL(O.IsObsolete,0) = 0
			AND BM.IsInContext = 1
			GROUP BY OM.Id,OM.Title,ISM.Id,ISM.Title,ISM.InquiryMainStatusId,AI.OrgId
		
		UNION ALL
			
-- 71
--Confirmed Admission

			SELECT
			ISM.Id AS InquiryStatusId, 
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM.Title,'') AS StatusName,
			(
			SELECT 
			ISNULL(COUNT(ISM.Id),0) AS StatusCount 
			FROM sAdmission.tAdmissionInquiry AI1
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI1.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI1.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI1.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId > 61 

			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId  AND OM.Id = AI.OrgId
			AND BM.IsInContext = 1
			) AS StatusCount  ,
			ISM.InquiryMainStatusId AS InquiryMainStatusId
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId =71
			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId
			And ISNULL(O.IsObsolete,0) = 0
			AND BM.IsInContext = 1
			GROUP BY OM.Id,OM.Title,ISM.Id,ISM.Title,ISM.InquiryMainStatusId,AI.OrgId
			UNION ALL
-- 81
-- Rejected Form
			SELECT 
			ISM.Id AS InquiryStatusId,
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM.Title,'') AS StatusName,
			(
			SELECT 
			ISNULL(COUNT(ISM.Id),0) AS StatusCount 
			FROM sAdmission.tAdmissionInquiry AI1 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI1.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI1.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI1.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId =81
			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId  AND OM.Id = AI.OrgId
			AND BM.IsInContext = 1
			) AS StatusCount  ,
			ISM.InquiryMainStatusId AS InquiryMainStatusId
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId =81
			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId
			And ISNULL(O.IsObsolete,0) = 0
			AND BM.IsInContext = 1
			GROUP BY OM.Id,OM.Title,ISM.Id,ISM.Title,ISM.InquiryMainStatusId,AI.OrgId
			UNION ALL
-- 91
-- Fees Paid

			SELECT 
			ISM.Id AS InquiryStatusId,
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM.Title,'') AS StatusName,
			(
			SELECT 
			ISNULL(COUNT(ISM.Id),0) AS StatusCount 
			FROM sAdmission.tAdmissionInquiry AI1 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI1.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI1.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI1.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId > 81 AND ISM.InquiryMainStatusId !=101

			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId  AND OM.Id = AI.OrgId
			AND BM.IsInContext = 1
			) AS StatusCount ,
			ISM.InquiryMainStatusId AS InquiryMainStatusId 
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId =91

 
			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId
			And ISNULL(O.IsObsolete,0) = 0
			AND BM.IsInContext = 1
			GROUP BY OM.Id,OM.Title,ISM.Id,ISM.Title,ISM.InquiryMainStatusId,AI.OrgId
			UNION ALL
-- 101		
-- Fees not paid
			SELECT 
			ISM.Id AS InquiryStatusId,
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM.Title,'') AS StatusName,
			(
			SELECT 
			ISNULL(COUNT(ISM.Id),0) AS StatusCount 
			FROM sAdmission.tAdmissionInquiry AI1 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI1.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI1.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI1.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId =101
			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId AND OM.Id = AI.OrgId
			AND BM.IsInContext = 1
			) AS StatusCount ,
			ISM.InquiryMainStatusId AS InquiryMainStatusId 
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId =101
			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId
			And ISNULL(O.IsObsolete,0) = 0
			AND BM.IsInContext = 1
			GROUP BY OM.Id,OM.Title,ISM.Id,ISM.Title,ISM.InquiryMainStatusId,AI.OrgId
			UNION ALL
-- 111			
-- Refunded Fees
			SELECT 
			ISM.Id AS InquiryStatusId,
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM.Title,'') AS StatusName,
			(
			SELECT 
			ISNULL(COUNT(ISM.Id),0) AS StatusCount 
			FROM sAdmission.tAdmissionInquiry AI1 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI1.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI1.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI1.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId > 101

			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId  AND OM.Id = AI.OrgId
			AND BM.IsInContext = 1
			) AS StatusCount  ,
			ISM.InquiryMainStatusId AS InquiryMainStatusId
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId =111
 
			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId
			And ISNULL(O.IsObsolete,0) = 0
			AND BM.IsInContext = 1
			GROUP BY OM.Id,OM.Title,ISM.Id,ISM.Title,ISM.InquiryMainStatusId,AI.OrgId
		 END
		 ELSE
		 BEGIN
			SELECT 
			ISM1.Id AS InquiryStatusId,
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM1.Title,'') AS StatusName,
			ISNULL(COUNT(ISM1.Id),0) AS StatusCount,
			ISNULL(ISM1.InquiryMainStatusId,0) AS InquiryMainStatusId
			,OM.OrderIndex
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM1 ON ISM1.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			--AND ISM.InquiryMainStatusId = 11
			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId
			And ISNULL(O.IsObsolete,0) = 0
			AND BM.IsInContext = 1
			GROUP BY OM.Id,OM.Title,ISM1.Id,ISM1.Title,ISM1.InquiryMainStatusId,AI.OrgId,OM.OrderIndex
			ORDER BY OM.OrderIndex
		 END
		END

	IF(@rType='StatusClassWise')
		BEGIN
				IF(@lConfigValue = 'True')
				BEGIN

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


				DECLARE @lSQLString nvarchar(max)=''

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

						SELECT 
							AI2.ForClassId AS ClassId,CM.Title AS ClassName,CM.OrderIndex,
							(SELECT ISNULL(COUNT(ISM.Id),0) AS StatusCount 
							FROM sAdmission.tAdmissionInquiry AI 
							INNER JOIN sSetup.tClassMaster CM ON CM.Id = AI.ForClassId
							INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
							INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
							INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
							INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
							LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
							INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
							LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
							WHERE BM.Id = TB.BatchId AND COGBM.Id='+CONVERT(nvarchar(20),@rCommonOrgGroupBatchId)+'
								'+CONVERT(nvarchar(500),@lInquiryMainStatus)+' and AI2.ForClassId = CM.Id
							AND BM.IsInContext = 1
							--BM.IsActive = 1 And ISNULL(O.IsObsolete,0) = 0
							AND ((OM.OrgGroupId = '+CONVERT(nvarchar(20),@rOrgGroupId)+' )OR('+CONVERT(nvarchar(20),@rOrgGroupId)+'=0)))
							AS StatusCount
						FROM 
							sAdmission.tAdmissionInquiry AI2
							INNER JOIN sSetup.tClassMaster CM ON CM.Id = AI2.ForClassId
							INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI2.ForBatchId
							LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
							LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI2.InquiryStatusId
						WHERE BM.Id = TB.BatchId 
						--and OM.OrgId = @rOrgId
							--and Ai2.ForClassId = CM.Id
							--AND COGBM.Id=1
							AND BM.IsInContext = 1
							AND ((CM.OrgId = '+CONVERT(nvarchar(20),@rOrgId)+' )OR('+CONVERT(nvarchar(20),@rOrgId)+'=0))
							'+CONVERT(nvarchar(500),@lInquiryMainStatus)+'
						Group BY 
							AI2.ForClassId,CM.Title,CM.OrderIndex '

						print @lSQLString

						execute(@lSQLString)
				END
				ELSE 
				BEGIN
						DECLARE @lSQLString1 nvarchar(max)=''

						SET @lSQLString1 = 'DECLARE @lTempOrgBatchOrder TABLE( OrgId int, BatchOrderIndex int)
						INSERT INTO @lTempOrgBatchOrder ( OrgId,BatchOrderIndex )
						SELECT OM.Id AS OrgId, MAX(BM.OrderIndex) AS BatchOrderIndex
						FROM
							sSetup.tOrganizationMaster OM
							INNER JOIN sSetup.tBatchMaster BM ON BM.OrgId = OM.Id
							INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
							INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
						WHERE 
							((OM.OrgGroupId='+CONVERT(nvarchar(20),@rOrgGroupId)+') OR ('+CONVERT(nvarchar(20),@rOrgGroupId)+' = 0))
							AND BM.IsObsolete = 0  AND COGBM.Id='+CONVERT(nvarchar(20),@rCommonOrgGroupBatchId)+'
							AND BM.IsInContext = 1
						GROUP BY
							OM.Id
		
						DECLARE @lTempBatchId TABLE(OrgId int, BatchId int)
						INSERT INTO @lTempBatchId (OrgId , BatchId)
						SELECT 
							BM.OrgId AS OrgId,
							BM.Id AS BatchId
						FROM 
							sSetup.tBatchMaster BM
							INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
							INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		 
							INNER JOIN @lTempOrgBatchOrder BO ON BO.OrgId = BM.OrgId
						WHERE
							BO.BatchOrderIndex = BM.OrderIndex  AND COGBM.Id='+CONVERT(nvarchar(20),@rCommonOrgGroupBatchId)+'
							AND BM.IsInContext = 1
						SELECT 
							AI2.ForClassId AS ClassId,CM.Title AS ClassName,CM.OrderIndex,
							(SELECT ISNULL(COUNT(ISM.Id),0) AS StatusCount 
							FROM sAdmission.tAdmissionInquiry AI 
							INNER JOIN sSetup.tClassMaster CM ON CM.Id = AI.ForClassId
							INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
							INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
							INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
							INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
							LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
							INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
							LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
							WHERE BM.Id = TB.BatchId AND COGBM.Id='+CONVERT(nvarchar(20),@rCommonOrgGroupBatchId)+'
								and ISM.InquiryMainStatusId = ISM1.InquiryMainStatusId and AI2.ForClassId = CM.Id
							--BM.IsActive = 1 And ISNULL(O.IsObsolete,0) = 0
							AND BM.IsInContext = 1
							AND ((OM.OrgGroupId = '+CONVERT(nvarchar(20),@rOrgGroupId)+' )OR('+CONVERT(nvarchar(20),@rOrgGroupId)+'=0)))
							AS StatusCount
						FROM 
							sAdmission.tAdmissionInquiry AI2
							INNER JOIN sSetup.tClassMaster CM ON CM.Id = AI2.ForClassId
							INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI2.ForBatchId
							LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
							LEFT JOIN sAdmission.tInquiryStatusMaster ISM1 ON ISM1.Id = AI2.InquiryStatusId
						WHERE BM.Id = TB.BatchId 
						--and OM.OrgId = @rOrgId
							--and Ai2.ForClassId = CM.Id
							--AND COGBM.Id=1
							AND ISM1.InquiryMainStatusId  = '+CONVERT(nvarchar(20),@rInquiryMainStatus)+'
							AND ((CM.OrgId = '+CONVERT(nvarchar(20),@rOrgId)+' )OR('+CONVERT(nvarchar(20),@rOrgId)+'=0))
							AND BM.IsInContext = 1
						Group BY 
							AI2.ForClassId,CM.Title,CM.OrderIndex,ISM1.InquiryMainStatusId'

						print @lSQLString1

						execute(@lSQLString1)
				END
			END

	ELSE IF(@rType='StatusStudentList')
		BEGIN
				IF(@lConfigValue = 'True')
				BEGIN

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

				DECLARE @lSQLStduentList nvarchar(max)=''

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

					--print @lSQLStduentList

					execute(@lSQLStduentList)

					END
					ELSE
					BEGIN	
						DECLARE @lSQLStduentList1 nvarchar(max)=''

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

					print @lSQLStduentList1

						execute(@lSQLStduentList1)
			END
		END

    ELSE IF(@rType='NotDoneStatusClassWise')
		BEGIN
				IF(@lConfigValue = 'True')
				BEGIN

				DECLARE @lInqMainStatus nvarchar(500)='' 
				SET  @lInqMainStatus = 'AND ISM.Id =' + CONVERT(nvarchar,@rInquiryStatusId)
				--IF(@rInquiryMainStatus=11)
				--SET  @lInquiryMainStatus = 'AND ISM.InquiryMainStatusId >= 11'
				--ELSE IF(@rInquiryMainStatus=21)
				--SET  @lInquiryMainStatus = 'AND ISM.InquiryMainStatusId > 11'
				--ELSE IF(@rInquiryMainStatus=31)
				--SET  @lInquiryMainStatus ='AND ISM.InquiryMainStatusId > 21'
				--ELSE IF(@rInquiryMainStatus=41)
				--SET  @lInquiryMainStatus ='AND ISM.InquiryMainStatusId > 31'
				--ELSE IF(@rInquiryMainStatus=51)
				--SET  @lInquiryMainStatus ='AND ISM.InquiryMainStatusId > 41 and ISM.InquiryMainStatusId <> 61'
				--ELSE IF(@rInquiryMainStatus=61)
				--SET  @lInquiryMainStatus ='AND ISM.InquiryMainStatusId = 61 '
				--ELSE IF(@rInquiryMainStatus=71)
				--SET  @lInquiryMainStatus ='AND ISM.InquiryMainStatusId > 61'
				--ELSE IF(@rInquiryMainStatus=81)
				--SET  @lInquiryMainStatus ='AND ISM.InquiryMainStatusId = 81'
				--ELSE IF(@rInquiryMainStatus=91)
				--SET  @lInquiryMainStatus ='AND ISM.InquiryMainStatusId > 81 AND ISM.InquiryMainStatusId !=101'
				--ELSE IF(@rInquiryMainStatus=101)
				--SET  @lInquiryMainStatus ='AND ISM.InquiryMainStatusId = 101'
				--ELSE IF(@rInquiryMainStatus=111)
				--SET  @lInquiryMainStatus ='AND ISM.InquiryMainStatusId > 101'


				DECLARE @lSQLString3 nvarchar(max)=''

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

						SELECT 
							AI2.ForClassId AS ClassId,CM.Title AS ClassName,CM.OrderIndex,
							(SELECT ISNULL(COUNT(ISM.Id),0) AS StatusCount 
							FROM sAdmission.tAdmissionInquiry AI 
							INNER JOIN sSetup.tClassMaster CM ON CM.Id = AI.ForClassId
							INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
							INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
							INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
							INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
							LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
							INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
							LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
							WHERE BM.Id = TB.BatchId AND COGBM.Id='+CONVERT(nvarchar(20),@rCommonOrgGroupBatchId)+'
								'+CONVERT(nvarchar(500),@lInqMainStatus)+' and AI2.ForClassId = CM.Id
							--BM.IsActive = 1 And ISNULL(O.IsObsolete,0) = 0
							AND BM.IsInContext = 1
							AND ((OM.OrgGroupId = '+CONVERT(nvarchar(20),@rOrgGroupId)+' )OR('+CONVERT(nvarchar(20),@rOrgGroupId)+'=0)))
							AS StatusCount
						FROM 
							sAdmission.tAdmissionInquiry AI2
							INNER JOIN sSetup.tClassMaster CM ON CM.Id = AI2.ForClassId
							INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI2.ForBatchId
							LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
							LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI2.InquiryStatusId
						WHERE BM.Id = TB.BatchId 
						--and OM.OrgId = @rOrgId
							--and Ai2.ForClassId = CM.Id
							--AND COGBM.Id=1
							AND ((CM.OrgId = '+CONVERT(nvarchar(20),@rOrgId)+' )OR('+CONVERT(nvarchar(20),@rOrgId)+'=0))
							'+CONVERT(nvarchar(500),@lInqMainStatus)+'
							AND BM.IsInContext = 1
						Group BY 
							AI2.ForClassId,CM.Title,CM.OrderIndex '

						print @lSQLString3

						execute(@lSQLString3)
				END
				ELSE 
				BEGIN
						DECLARE @lSQLString4 nvarchar(max)=''

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

						SELECT 
							AI2.ForClassId AS ClassId,CM.Title AS ClassName,CM.OrderIndex,
							(SELECT ISNULL(COUNT(ISM.Id),0) AS StatusCount 
							FROM sAdmission.tAdmissionInquiry AI 
							INNER JOIN sSetup.tClassMaster CM ON CM.Id = AI.ForClassId
							INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
							INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
							INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
							INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
							LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
							INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
							LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
							WHERE BM.Id = TB.BatchId AND COGBM.Id='+CONVERT(nvarchar(20),@rCommonOrgGroupBatchId)+'
								and ISM.InquiryMainStatusId = ISM1.InquiryMainStatusId and AI2.ForClassId = CM.Id
							--BM.IsActive = 1 And ISNULL(O.IsObsolete,0) = 0
							AND BM.IsInContext = 1
							AND ((OM.OrgGroupId = '+CONVERT(nvarchar(20),@rOrgGroupId)+' )OR('+CONVERT(nvarchar(20),@rOrgGroupId)+'=0)))
							AS StatusCount
						FROM 
							sAdmission.tAdmissionInquiry AI2
							INNER JOIN sSetup.tClassMaster CM ON CM.Id = AI2.ForClassId
							INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI2.ForBatchId
							LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
							LEFT JOIN sAdmission.tInquiryStatusMaster ISM1 ON ISM1.Id = AI2.InquiryStatusId
						WHERE BM.Id = TB.BatchId 
						--and OM.OrgId = @rOrgId
							--and Ai2.ForClassId = CM.Id
							--AND COGBM.Id=1
							AND ISM1.InquiryMainStatusId  = '+CONVERT(nvarchar(20),@rInquiryMainStatus)+'
							AND ((CM.OrgId = '+CONVERT(nvarchar(20),@rOrgId)+' )OR('+CONVERT(nvarchar(20),@rOrgId)+'=0))
							AND BM.IsInContext = 1
						Group BY 
							AI2.ForClassId,CM.Title,CM.OrderIndex,ISM1.InquiryMainStatusId'

						print @lSQLString4

						execute(@lSQLString4)
				END
			END

	ELSE IF(@rType='NotDoneStatusStudentList')
		BEGIN
				IF(@lConfigValue = 'True')
				BEGIN

				DECLARE @lInqMainStatusStudent nvarchar(500)='' 
				 
				SET  @lInqMainStatusStudent = 'AND ISM.Id =' + CONVERT(nvarchar,@rInquiryStatusId)
				--IF(@rInquiryMainStatus=11)
				--SET  @lInquiryMainStatusStudent = 'AND ISM.InquiryMainStatusId >=11'
				--ELSE IF(@rInquiryMainStatus=21)
				--SET  @lInquiryMainStatusStudent = 'AND ISM.InquiryMainStatusId > 11'
				--ELSE IF(@rInquiryMainStatus=31)
				--SET  @lInquiryMainStatusStudent ='AND ISM.InquiryMainStatusId > 21'
				--ELSE IF(@rInquiryMainStatus=41)
				--SET  @lInquiryMainStatusStudent ='AND ISM.InquiryMainStatusId > 31'
				--ELSE IF(@rInquiryMainStatus=51)
				--SET  @lInquiryMainStatusStudent ='AND ISM.InquiryMainStatusId > 41 and ISM.InquiryMainStatusId <> 61'
				--ELSE IF(@rInquiryMainStatus=61)
				--SET  @lInquiryMainStatusStudent ='AND ISM.InquiryMainStatusId > 51 AND ISM.InquiryMainStatusId !=71'
				--ELSE IF(@rInquiryMainStatus=71)
				--SET  @lInquiryMainStatusStudent ='AND ISM.InquiryMainStatusId > 61'
				--ELSE IF(@rInquiryMainStatus=81)
				--SET  @lInquiryMainStatusStudent ='AND ISM.InquiryMainStatusId > 71 AND ISM.InquiryMainStatusId !=91'
				--ELSE IF(@rInquiryMainStatus=91)
				--SET  @lInquiryMainStatusStudent ='AND ISM.InquiryMainStatusId > 81 AND ISM.InquiryMainStatusId !=101'
				--ELSE IF(@rInquiryMainStatus=101)
				--SET  @lInquiryMainStatusStudent ='AND ISM.InquiryMainStatusId > 91 AND ISM.InquiryMainStatusId !=111'
				--ELSE IF(@rInquiryMainStatus=111)
				--SET  @lInquiryMainStatusStudent ='AND ISM.InquiryMainStatusId > 101'


				DECLARE @lSQLStduentList3 nvarchar(max)=''

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

					--print @lSQLStduentList

					execute(@lSQLStduentList3)

					END
					ELSE
					BEGIN	
						DECLARE @lSQLStduentList4 nvarchar(max)=''

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

					print @lSQLStduentList4

						execute(@lSQLStduentList4)
			END
		END
	END


	-- For AdmissionConverted Tab
	IF(@rTypeId = 3)
	BEGIN
		IF(@rType='OrgGroupWise')
		BEGIN
			-- Organization wise Count
			SELECT OrgId, Organization, ISNULL(Inquiry, 0) AS InquiryCount, ISNULL(Form, 0) AS FormCount, (ISNULL([Converted Inquiry], 0) + ISNULL([Converted Form], 0)) AS ConvertedCount
			FROM  
			(
				SELECT 
					ISNULL(OM.Id,0) AS OrgId,
					OM.Title AS Organization,
					'Inquiry' AS Type,
					ISNULL(COUNT(AI.Id),0) AS Total
				FROM sAdmission.tAdmissionInquiry AI 
					INNER JOIN sAdmission.tInquiryStatusMaster SM ON SM.Id=AI.InquiryStatusId
					INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
					INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
					LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
					INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
				WHERE 
					BM.Id = TB.BatchId 
					AND COGBM.Id=@rCommonOrgGroupBatchId
					--AND OM.OrgGroupId = @rOrgGroupId
					And ISNULL(O.IsObsolete,0) = 0
					AND BM.IsInContext = 1
				GROUP BY OM.Id,OM.Title

				UNION ALL

				SELECT 
					OM.Id, 
					OM.Title AS Organization,
					'Form' AS Type,
					COUNT(AF.Id) AS Total
				FROM sAdmission.tAdmissionForm AF 
					INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AF.BatchId
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
					INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					INNER JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
					INNER JOIN sSetup.tOrganizationMaster OM ON AF.OrgId = OM.Id
				WHERE
					BM.Id = TB.BatchId
					AND OM.OrgGroupId = @rOrgGroupId 
					AND COGBM.Id = @rCommonOrgGroupBatchId
					And ISNULL(O.IsObsolete,0) = 0
					AND BM.IsInContext = 1
				GROUP BY OM.Id, OM.Title

				UNION ALL

				SELECT
					ISNULL(OM.Id,0) AS OrgId,
					OM.Title AS Organization,
					'Converted Inquiry' AS Type,
					COUNT(AI.Id) AS Total
				FROM sAdmission.tAdmissionInquiry AI
					INNER JOIN sAdmission.tInquiryStatusMaster SM ON SM.Id=AI.InquiryStatusId
					LEFT JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId AND BM.IsInContext = 1
					LEFT JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
					LEFT JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
					LEFT JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
					LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
					LEFT JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
					LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
				WHERE 
					BM.Id = TB.BatchId 
					AND COGBM.Id=@rCommonOrgGroupBatchId
					AND ISM.InquiryMainStatusId = 71
					--AND OM.OrgGroupId = @rOrgGroupId
					And ISNULL(O.IsObsolete,0) = 0
				GROUP BY OM.Id, OM.Title

				UNION ALL

				SELECT 
					OM.Id, 
					OM.Title AS Organization,
					'Converted Form' AS Type,
					COUNT(AF.Id) AS Total
				FROM sAdmission.tAdmissionForm AF 
					INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AF.BatchId
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
					INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					INNER JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
					INNER JOIN sSetup.tOrganizationMaster OM ON AF.OrgId = OM.Id
				WHERE
					BM.Id = TB.BatchId
					AND OM.OrgGroupId = @rOrgGroupId 
					AND COGBM.Id = @rCommonOrgGroupBatchId
					And ISNULL(O.IsObsolete,0) = 0
					AND AF.StatusId = 208 --Closed
					AND BM.IsInContext = 1
				GROUP BY OM.Id, OM.Title
			   ) AS A
				PIVOT  
				(SUM(Total) FOR [Type] IN ([Inquiry],[Form],[Converted Inquiry],[Converted Form])) AS A1
		END

		IF(@rType='ClassWise')
		BEGIN
			-- Class wise Count
			SELECT ClassId, ClassName, OrderIndex, ISNULL(Inquiry, 0) AS InquiryCount, ISNULL(Form, 0) AS FormCount,(ISNULL([Converted Inquiry], 0) + ISNULL([Converted Form], 0)) AS ConvertedCount
			FROM  
			(
				--Inquiry
				SELECT 
					AI.ForClassId AS ClassId, CM.Title AS ClassName, 'Inquiry' AS Type, ISNULL(COUNT(AI.Id),0) AS Total, CM.OrderIndex
				FROM sAdmission.tAdmissionInquiry AI
					INNER JOIN sAdmission.tInquiryStatusMaster SM ON SM.Id=AI.InquiryStatusId
					INNER JOIN sSetup.tClassMaster CM ON CM.Id = AI.ForClassId
					INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
					LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
				WHERE 
					BM.Id = TB.BatchId 
					AND ((CM.OrgId = @rOrgId) OR (@rOrgId=0))
					AND BM.IsInContext = 1				
				Group BY AI.ForClassId,CM.Title,CM.OrderIndex 

				UNION ALL 

				-- Form
				SELECT 
					CM.Id AS ClassId, CM.DisplayTitle AS ClassName, 'Form' AS Type, ISNULL(COUNT(AF.Id),0) AS Total, CM.OrderIndex 
				FROM sAdmission.tAdmissionForm AF 
					INNER JOIN sSetup.tClassMaster CM ON CM.Id = AF.ForClassId
					INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AF.BatchId
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
					INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
					INNER JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
					INNER JOIN sSetup.tOrganizationMaster OM ON AF.OrgId = OM.Id
				WHERE 
					BM.Id = TB.BatchId
					AND OM.OrgGroupId = 9911 AND COGBM.Id=@rCommonOrgGroupBatchId
					And ISNULL(O.IsObsolete,0) = 0
					AND ((CM.OrgId = @rOrgId) OR (@rOrgId=0))
					AND BM.IsInContext = 1
				GROUP BY CM.Id,CM.DisplayTitle,CM.OrderIndex

				UNION ALL
				
				SELECT 
					AI.ForClassId AS ClassId, CM.Title AS ClassName, 'Converted Inquiry' AS Type, ISNULL(COUNT(AI.Id),0) AS Total, CM.OrderIndex
				FROM sAdmission.tAdmissionInquiry AI
					INNER JOIN sAdmission.tInquiryStatusMaster SM ON SM.Id=AI.InquiryStatusId
					INNER JOIN sSetup.tClassMaster CM ON CM.Id = AI.ForClassId
					INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
					LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
					LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
				WHERE 
					BM.Id = TB.BatchId 
					AND ((CM.OrgId = @rOrgId )OR(@rOrgId=0))
					AND ISM.InquiryMainStatusId = 71		
					AND BM.IsInContext = 1	
				Group BY AI.ForClassId,CM.Title,CM.OrderIndex 

				UNION ALL

				SELECT 
					CM.Id AS ClassId, CM.DisplayTitle AS ClassName, 'Converted Form' AS Type, ISNULL(COUNT(AF.Id),0) AS Total, CM.OrderIndex 
				FROM sAdmission.tAdmissionForm AF 
					INNER JOIN sSetup.tClassMaster CM ON CM.Id = AF.ForClassId
					INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AF.BatchId
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
					INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
					INNER JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
					INNER JOIN sSetup.tOrganizationMaster OM ON AF.OrgId = OM.Id
				WHERE 
					BM.Id = TB.BatchId
					AND OM.OrgGroupId = @rOrgGroupId 
					AND COGBM.Id=@rCommonOrgGroupBatchId
					And ISNULL(O.IsObsolete,0) = 0
					AND AF.StatusId = 208 --Closed
					AND((CM.OrgId = @rOrgId)OR(@rOrgId=0))
					AND BM.IsInContext = 1
				GROUP BY CM.Id,CM.DisplayTitle,CM.OrderIndex
			)  
			AS A
			PIVOT  
			(SUM(Total) FOR [Type] IN ([Inquiry],[Form],[Converted Inquiry],[Converted Form])) AS A2
		END
	END

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


GO
 
  

ALTER PROCEDURE [sAdmission].[pAdmissionFormGet]

	 @rAdmissionFormId bigint = 0,
	 @rFormNo int,
	 @rForClassId int,
	 @rBatchId int=0,
	 @rStatusId smallint='',
	 @rOrgId int,
	 @rFirstName nvarchar(100),
	 @rLastName nvarchar(100),
	 @rMeritMarks decimal(10,2),
	 @rFromDate datetime= '1900-01-01',
	 @rToDate datetime = '9990-12-31',
	 @rDepartmentId int=0,
	 @rIsTransportFilter int=2,
	 @rIsHostelFilter int=2,
	 @rDataEntryStatusId smallint=0,
	 @rIsCommonSearch bit=0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
	SET @rToDate = DATEADD(d,1,@rToDate)		 

BEGIN 
		--IF @rIsSearch = 1
		BEGIN
		SET @rFirstName = ISNULL(@rFirstName,'')
		SET @rLastName = ISNULL(@rLastName,'')
			SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
			SET @rLastName = sCommon.fSearchStringGet(@rLastName)
		END
	
	SELECT 
			 AF.Id
			,AF.FormNo
			,AF.FirstName
			,AF.MiddleName
			,AF.LastName

			--,AF.FirstName+' '+AF.LastName as Name
			,[sStudent].[fStudentNameGet](AF.FirstName , ISNULL(AF.MiddleName,'') , AF.LastName,OM.StudentNameFormatId ) AS Name

			,AF.ForClassId
			,AF.BatchId
			,CM.Title AS ClassName
			,AF.ForBatch
			,ISNULL(AF.DateOfBirth,'') AS DateOfBirth
			,AF.DateOfBirthInWord
			,AF.StatusId
			,SM.Title as StatusName
			,ISNULL(ASM.Title,'') AS FormStatus
			,AF.StreetOne
			,AF.StreetTwo
			,AF.StreetThree
			,AF.Country
			,AF.State
			,AF.City
			,AF.ZipCode
			,AF.ContactNo
			,AF.ContactEmail
			,AF.Remark
			,AF.PreviousSchool
			,AF.MeritMarks
			,AF.MeritGrade
			,AF.GenderId
			,ISNULL(GM.Title,'') AS Gender
			,ISNULL(AF.ReligionId,0) AS ReligionId
			,AF.FamilyCast
			,AF.FamilySubCast
			,ISNULL(AF.CastCategoryId,0) AS CastCategoryId
			,AF.CreatedDateTime AS AdmissionFormDate
			,ISNULL(AF.StudentId,0) AS StudentId
			,ISNULL(AF.AdmissionDate,'') AS AdmissionDate
			--,AF.StudentPhoto,
			,(CASE WHEN @rIsCommonSearch=0 THEN ISNULL(AF.StudentPhoto,0) ELSE NULL END) AS StudentPhoto
			
			,ISNULL(AFFD.FatherName,'') AS FatherName,
			Isnull(AFFD.FatherDateOfBirth,'') AS FatherDateOfBirth,
			Isnull(AFFD.FatherOccupation,'') AS FatherOccupation,
			Isnull(AFFD.FatherQualification,'') AS FatherQualification,
			Isnull(AFFD.FatherContactNo,'') AS FatherContactNo,
			Isnull(AFFD.FatherMail,'') AS FatherMail,
			Isnull(AFFD.FatherOfficeAddress,'') As FatherOfficeAddress,
			isnull(AFFD.FatherOrganization,'') as FatherOrganization,
			isnull(AFFD.FatherDesignation,'') as FatherDesignation,
			Isnull(AFFD.FatherIncome,'') as FatherIncome,
			Isnull(AFFD.MotherName,'') AS MotherName,
			iSNULL(AFFD.MotherDateOfBirth,'')AS MotherDateOfBirth,
			isnull(AFFD.MotherOccupation,'') AS MotherOccupation,
			isnull(AFFD.MotherQualification,'') AS MotherQualification,
			isnull(AFFD.MotherContactNo,'') as MotherContactNo,
			isnull(AFFD.MotherMail,'') As MotherMail,
			isnull(AFFD.MotherOfficeAddress,'') as MotherOfficeAddress,
			isnull(AFFD.MotherOrganization,'') as MotherOrganization,
			isnull(AFFD.MotherDesignation,'') as MotherDesignation,
			isnull(AFFD.MotherIncome,'') as MotherIncome,
			AF.MotherTongue AS MotherTongue,
		 
			isnull(AFFD.RelationshipName,'') as RelationshipName,
			isnull(AFFD.RelativeName,'')  AS GuardianName ,
			isnull(AFFD.RelativeDateOfBirth ,'')AS GuardianDateOfBirth,
			isnull(AFFD.RelativeOccupation,'') AS GuardianOccupation,
			isnull(AFFD.RelativeQualification,'') AS GuardianQualification,
			isnull(AFFD.RelativeContactNo,'') AS GuardianContactNo,
			isnull(AFFD.RelativeMail,'')  AS GuardianMail,
			isnull(AFFD.RelativeOfficeAddress,'') AS GuardianOfficeAddress,
			isnull(AFFD.RelativeOrganization,'') as RelativeOrganization,
			isnull(AFFD.RelativeDesignation,'') as RelativeDesignation,
			isnull(AFFD.RelativeIncome,'') AS GuardianIncome  ,
			isnull(AF.IsHostelRequired,0) AS IsHostelRequired  ,
			isnull(AF.IsTransportRequired,0) AS IsTransportRequired,
			isnull(AF.BirthPlace,'') AS BirthPlace,
			isnull(AF.BirthTaluka,'') AS BirthTaluka,
			isnull(AF.BirthDistrict,'') AS BirthDistrict,
			isnull(AF.BloodGroupId,0) AS BloodGroupId,
			isnull(AF.AdhaarNumber,'') AS AdhaarNumber,
			isnull(AF.IsPysicalDeformity,0) AS IsPysicalDeformity,
			isnull(AF.PysicalDeformityRemark,'') AS PysicalDeformityRemark,
			isnull(AF.IsMajorIllness,0) AS IsMajorIllness,
			isnull(AF.MajorIllnessRemark,'') AS MajorIllnessRemark,
			isnull(AF.IsAllergy,0) AS IsAllergy,
			isnull(AF.AllergyRemark,'') AS AllergyRemark,
			isnull(AF.BirthState,'') AS BirthState,
			isnull(AF.BirthCountry,'') AS BirthCountry,
			isnull(SA.PreviousStandard,'') As PreviousStandard,
	        isnull(AFFD.LiveWithId,0) AS LiveWithId,
			--isnull(ASB.SiblingName,'') AS SiblingName,
			--isnull(ASB.SiblingRelation,'')AS SiblingRelation,
			
			--isnull(ASB.SiblingStandard,'') AS SiblingStandard,
			--isnull(ASB.SiblingSchool,'')AS SiblingSchool
			
			 ISNULL(AF.CustomField1Answer,'') AS CustomField1Answer,
			 ISNULL(AF.CustomField2Answer,'') AS CustomField2Answer,
			 ISNULL(AF.CustomField3Answer,'') AS CustomField3Answer,
			 SM1.Title AS DataEntryStatus,
			 AF.Nationality,
			 ISNULL(AFFD.FatherAdhaarNumber,'') AS FatherAdhaarNumber,
			 AF.CreatedDateTime AS AdmissionFormDate,
			 ISNULL(AFFD.MotherAadhaarNumber,'') AS MotherAadhaarNumber,
			 ISNULL(AFFD.RelativeAadhaarNumber,'') AS RelativeAadhaarNumber,
			 ISNULL(AFFD.FatherOfficePhone,'') AS FatherOfficePhone,
			 ISNULL(AFFD.MotherOfficePhone,'') AS MotherOfficePhone,
			 CASE WHEN AF.DataEntryModeId = 561 THEN 'Online' ELSE 'Offline' END DataEntryMode
			 
  FROM 
            sAdmission.tAdmissionForm AF
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = AF.OrgId
			INNER JOIN sCommon.tStatusMaster SM ON SM.Id=AF.StatusId
			INNER JOIN sCommon.tStatusMaster SM1 ON SM1.Id=AF.DataEntryStatusId			
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=AF.ForClassId
			LEFT JOIN sCommon.tGenderMaster GM ON GM.Id=AF.GenderId
			LEFT JOIN sAdmission.tAdmissionFormSelected AFS ON AF.Id = AFS.AdmissionFormId
			LEFT JOIN sAdmission.tAdmissionStatusMaster ASM ON ASM.Id = AFS.AdmissionStatusId
			LEFT JOIN sAdmission.tAdmissionFormFamilyDetail AFFD ON AFFD.AdmissionFormId = AF.Id
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = AF.StudentId
			 --LEFT JOIN sAdmission.tAdmissionFormSibling ASB ON ASB.AdmissionFormId = AF.Id
			LEFT JOIN sStudent.tStudentAdmission SA ON SA.StudentID=AF.StudentID
  WHERE 
  
      ((AF.Id = @rAdmissionFormId) OR (@rAdmissionFormId = 0))
		AND ((AF.FormNo=@rFormNo) OR (@rFormNo=0))
		AND ((AF.FirstName like @rFirstName) OR (@rFirstName=''))
		AND ((AF.LastName like @rLastName) OR (@rLastName=''))
		--AND ((AF.CreatedDateTime>= @rFromDate) OR (@rFromDate=''))
		AND ((Cast(AF.AdmissionDate as datetime)>= @rFromDate) OR (@rFromDate=''))
		--AND ((AF.AdmissionDate is not null AND Cast(AF.AdmissionDate as datetime)>= @rFromDate) or (AF.AdmissionDate is null AND AF.CreatedDateTime>= @rFromDate) or (@rFromDate=''))
		--AND ((AF.CreatedDateTime < @rToDate) OR (@rToDate=''))
		AND ((Cast(AF.AdmissionDate as datetime)<= @rToDate) OR (@rToDate=''))
		--AND ((AF.AdmissionDate is not null AND Cast(AF.AdmissionDate as datetime)< @rToDate) or (AF.AdmissionDate is null AND AF.CreatedDateTime< @rToDate) or (@rToDate=''))
		AND ((AF.StatusId=@rStatusId) OR (@rStatusId=0))
		AND ((AF.ForClassId=@rForClassId) OR (@rForClassId=0)) 
		AND ((AF.BatchId=@rBatchId) OR (@rBatchId=0)) 
		--AND ((AF.MeritMarks=@rMeritMarks) OR (@rMeritMarks=0))
		AND ((AF.StatusId=@rStatusId) OR (@rStatusId = ''))
		AND ((AF.DataEntryStatusId=@rDataEntryStatusId) OR (@rDataEntryStatusId = 0))
		AND ((CM.DepartmentId=@rDepartmentId) OR (@rDepartmentId = 0))
		AND AF.OrgId=@rOrgId
        AND ((ISnull(AF.IsHostelRequired,0)=@rIsHostelFilter ) OR   (ISNULL(@rIsHostelFilter,2)=2) )
	   AND ((ISNUll(AF.IsTransportRequired,0)=@rIsTransportFilter) OR (isnull(@rIsTransportFilter,0) = 2))
	  
 order by AF.FormNo
END
GO
PRINT N'Altering [sAlert].[pParentPortalLoginGet]...';


GO

ALTER PROCEDURE [sAlert].[pParentPortalLoginGet]
	 	 
	@rOrgId smallint,
	@rBatchId int,
	--@rIsPendingLogin bit,
	--@rIsCreatedLogin bit,
	@rClassId int =0,
	@rDivisionId int=0,
	--@rNotRegister bit=0,
	@rTemplate nvarchar(max),
	@rStudentId bigint = 0,
	@rSubject nvarchar(100)=''

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	SELECT 
			SC.AcademicId,
			SC.Code,
			SC.Name,
			SC.ParentContactNo AS MobileNo,	
			SC.ParentEmail AS EmailId,
			ISNULL(SC.StudentContactNo,'') AS StudentContactNo,
			ISNULL(SC.StudentEmail,'') AS StudentEmail,
			ISNULL(SC.FatherContactNo,'') AS FatherContactNo,
			ISNULL(SC.FatherMail,'') AS FatherMail,
			ISNULL(SC.MotherContactNo,'') AS MotherContactNo,
			ISNULL(SC.MotherMail,'') AS MotherMail,
			replace(replace(replace(@rTemplate,'[UserName]',U.LoginTitle),'[Password]','[Password]'),'[StudentName]',SC.Name)
			 AS Template,
			 --Add for StudentWise
			 replace(replace(replace(@rTemplate,'[UserName]',U.LoginTitle),'[Password]','[Password]'),'[StudentName]',SC.Name)
			 AS MsgText,
			 @rSubject AS Subject,
			 2003 AS ReceiverSourceTypeId,
			 SC.StudentId AS ReceiverSourceId,
			 SC.StudentId AS SourceId,
			 2003 AS SourceTypeId,
			 SC.OrgGroupId,
			 SC.OrgId,

			 SC.ClassName AS Class,
			 SC.DivisionName AS Division,
			 SC.WhatsAppContactNo,
			 U.LoginPassword AS Password
	FROM 
			sStudent.vStudentCommunication SC
			INNER JOIN sSecurity.tUser U ON U.SourceId = SC.StudentId AND U.SourceTypeId=2003
			INNER JOIN sStudent.tStatusMaster SM ON SM.Id = SC.StatusId 
			 
	WHERE 
			 (SC.OrgId = @rOrgId)
			 AND (SC.BatchId = @rBatchId) 
			 AND ((SC.ClassId = @rClassId) OR(@rClassId=0))
			 AND ((SC.DivisionId = @rDivisionId) OR(@rDivisionId=0))
			 AND SC.StatusId = 1 AND U.ISobsolete = 0
			 AND ((SC.StudentId = @rStudentId) OR (@rStudentId = 0))
END
GO
PRINT N'Altering [sAlert].[pVisitorGatePassGet]...';


GO
ALTER PROCEDURE [sAlert].[pVisitorGatePassGet]
	
		 @rVisitorLogId int,
	 	 @rOrgId int,
	 	 @rTemplate nvarchar(max),
		 @rSubject nvarchar(100)='',
		 @rIsOutEntry bit = 0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	IF(@rIsOutEntry=0)
	BEGIN
		SELECT 
			VL.Id,
			VL.VisitorName,
			EC.MobileNumber AS MobileNo,
			VL.VisitorContactNumber AS ContactNumber,
			EC.CompanyEmail AS EmailId,
			replace (
			replace (
			replace(@rTemplate,'[VisitorName]',VL.VisitorName),
			'[NoOfVisitors]',VL.NoOfVisitor),
			'[PurposeOfVisit]',VL.PurposeOfVisit)
			AS MsgText,
			@rSubject AS Subject,
			95 AS ReceiverSourceTypeId,
			EM.Id AS ReceiverSourceId,
			EM.Id AS SourceId,
			95 AS SourceTypeId,
			OM.OrgGroupId,
			VL.OrgId,
			VL.NoOfVisitor AS NoOfVisitors,
			VL.PurposeOfVisit AS PurposeOfVisit,
			ISNULL(EC.WhatsAppContactNo,'') AS WhatsAppContactNo
		FROM 
			sFrontOffice.tVisitorLog VL
			INNER JOIN [sHrm].[tEmployeeMaster] EM ON VL.WhomToMeet=EM.Id
			INNER JOIN [sHrm].[tEmployeeCommunications] EC ON EM.Id=EC.EmployeeId
			INNER JOIN sSetup.tOrganizationMaster OM ON VL.OrgId = OM.Id	
		WHERE
			((VL.OrgId=@rOrgId) OR (@rOrgId=0))
			AND VL.Id = @rVisitorLogId
	END
	ELSE
	BEGIN
		SELECT 
			VL.Id,
			VL.VisitorName,
			VL.VisitorContactNumber AS MobileNo,
			'' AS EmailId,
			replace (
			replace (
			replace(@rTemplate,'[VisitorName]',VL.VisitorName),
			'[NoOfVisitors]',VL.NoOfVisitor),
			'[PurposeOfVisit]',VL.PurposeOfVisit)
			AS MsgText,
			@rSubject AS Subject,
			0 AS ReceiverSourceTypeId,
			0 AS ReceiverSourceId,
			0 AS SourceId,
			0 AS SourceTypeId,
			OM.OrgGroupId,
			VL.OrgId,
			VL.NoOfVisitor AS NoOfVisitors,
			VL.PurposeOfVisit AS PurposeOfVisit,
			ISNULL(VL.VisitorContactNumber,'') AS WhatsAppContactNo
		FROM 
			sFrontOffice.tVisitorLog VL
			--To Send Alert on Visitor Contact No
			--LEFT JOIN [sHrm].[tEmployeeMaster] EM ON VL.WhomToMeet=EM.Id
			--LEFT JOIN [sHrm].[tEmployeeCommunications] EC ON EM.Id=EC.EmployeeId
			LEFT JOIN sSetup.tOrganizationMaster OM ON VL.OrgId = OM.Id	
		WHERE
			((VL.OrgId=@rOrgId) OR (@rOrgId=0))
			AND VL.Id = @rVisitorLogId
	END
END
GO
PRINT N'Altering [sAssessment].[pMarkEntryAllSubjectCountGet]...';


GO

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

BEGIN 		
DECLARE @cols AS NVARCHAR(MAX),
@query  AS NVARCHAR(MAX),@query1  AS NVARCHAR(MAX),@query2  AS NVARCHAR(MAX),@query3 AS NVARCHAR(MAX)
select @cols = STUFF((SELECT  distinct ',' +   QUOTENAME(CS.SubjectCode) 
					  From  
					   sSetup.vExamSubject CS  
					   INNER JOIN sAssessment.tExamMaster E ON E.Id=CS.ExamId AND E.ExamSubGroupId =  @rExamId 
					   INNER JOIN sSetup.tClassMaster CL on CL.Id=CS.ClassId
					   INNER JOIN sSetup.tDivisionMaster CM ON CM.ClassId=CL.Id
					    WHere ((CM.ClassId =@rClassID) OR (@rClassId=0)) AND ((CM.Id=@rDivisionId) OR (@rDivisionId=0)) 
						AND E.BatchId=@rBatchId
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')
 
set @query = 'SELECT  ClassId,DivisionId,ClassName,ExamId,

 ' + @cols + '
FROM
(
Select   CM.Id As ClassId,DM.Id as DivisionId,CM.Title+'' ''+DM.Title ClassName,Count(A.AcademicId) AS AcademicId,ED.ExamId, SM.Code as ExamDetailId
FROM sStudent.vStudentAcademic A 
INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId=CM.Id AND A.DivisionId=DM.Id
INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
LEFT JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.AcademicId
INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
INNER JOIN sSetup.tClassSubject CS ON CS.Id = ED.ClassSubjectId
INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = CS.SubjectId
LEFT JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id 
 
WHERE A.StatusId =1 AND A.BatchId = '+ CONVERT(nvarchar(15),@rBatchId) +' And  EM.ExamSubGroupId = ' + convert(nvarchar(15),@rExamId) + 
'AND ISNULL(RD.Obtain,0)>0 AND ((A.ClassId='+convert(nvarchar(15),@rClassId)+') OR (' +convert(nvarchar(15),@rClassId) + '=0)) 
AND ((A.DivisionId='+Convert(nvarchar(15),@rDivisionId)+') OR ('+Convert(nvarchar(15),@rDivisionId)+'=0))
Group By ED.ExamId,Ed.Id,CM.Title,DM.TItle,Cm.Id,Dm.Id,SM.Code) 
MAIN
PIVOT
(
	MAX(AcademicId )
FOR ExamDetailId IN (' + @cols + ')
)pvt '
--AND ISNULL(RD.Obtain,0)>0 (Ramesh Gurjar)Date: 19/02/2022 Remove this condition, for DPS chas 0 mark entry not count in verify screen
--print (@query)
execute(@query)
		
END
GO
PRINT N'Altering [sAssessment].[pRptExamResultSubCombine]...';


GO




ALTER PROCEDURE [sAssessment].[pRptExamResultSubCombine]
	 
	 -- @rAcademicId bigint=0,
	 @rExamSubGroupId int=0,
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rOrgId int =0,
	 @rBatchId int ,
	 @rDepartmentid int=0,
	 @rStatusId int=0
	 
	
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	SELECT 
			 
			 CONVERT(nvarchar(20),EM.Id) AS ExamIdText,
			 CONVERT(nvarchar(20),@rClassId) AS ClassIdText,
			 CONVERT(nvarchar(20),DM.Id) AS DivisionIdText,
			 CONVERT(nvarchar(20),@rBatchId) AS BatchIdText,
			 CONVERT(nvarchar(20),@rStatusId) AS StatusIdText,
	 
			 
			CM.DisplayTitle + '-' + DM.DisplayTitle AS ClassDivision,
			DM.Title AS Division,
			CM.Title AS Class,
			E.FirstName + ' ' + E.LastName AS ClassTeacherName,
			BM.Title AS Batch,
			DM.Id AS DivisionId,
			CM.Id AS ClassId
			FROM 
			 
		 
			sAssessment.tExamMaster EM
			--INNER JOIN sAssessment.tResult R ON EM.Id=R.ExamId
		 --   INNER JOIN sStudent.tAcademic A	ON A.Id=R.Academic
			 INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=EM.ClassId
			--INNER JOIN sSetup.tClassSubject CS ON CS.ClassId=CM.Id
			INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId=CM.Id
			 LEFT JOIN sHrm.tEmployeeMaster E ON E.Id =DM.InchargeEmployeeId
			--INNER JOIN sSetup.tOrganizationMaster OM ON DM.OrgId = OM.Id
			 INNER JOIN sSetup.tBatchMaster BM ON BM.Id=EM.BatchId
	WHERE 
	 
	     (CM.Id=@rClassId OR @rClassId=0) 
		AND (DM.Id=@rDivisionId OR @rDivisionId=0)
		AND (EM.ExamSubGroupId = @rExamSubGroupId OR @rExamSubGroupId =0)
		AND  ISNULL(E.IsOtherUser,0) = 0
		--AND OM.Id=@rOrgId
		AND BM.Id = @rBatchId
		 
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 

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

	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,
			ISNULL(SR.PresentDays,0)AS PresentDays,
			ISNULL(SR.TotalDays,0)AS TotalDays,
			ED.IsShowSubjectGrade,
			ED.IsShowSubjectMark,
			(EmpM.FirstName + ' ' +EmpM.LastName ) AS InchargeEmployeeName,
			CONVERT(bit,@lAbsentRemarkConfig) AS IsAbsentRemark,
			ISNULL(RD.AbsentRemark,'') AS AbsentRemark

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


GO



ALTER PROCEDURE [sAssessment].[pRptStudentClassWise]
	 
	  --@rAcademicId bigint=0,
	 @rExamId int=0,
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rBatchId int =0,
	 @rStatusId int=0	
 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	SELECT 
			-- CONVERT(nvarchar(20),A.Id) AS AcademicIdText,
			 CONVERT(nvarchar(20),@rExamId) AS ExamIdText,
			 CONVERT(nvarchar(20),@rClassId) AS ClassIdText,
			 CONVERT (nvarchar(20),@rDivisionId) AS DivisionIdText,
			 --CONVERT(nvarchar(20),@rBatchId) AS BatchIdText,
			
			 (Select COUNT(A.Id) from sStudent.tAcademic A	
				INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
				INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
				WHERE A.ClassId=@rClassId AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0)) AND ((StuM.StatusId=@rStatusId)OR(@rStatusId=0)) AND A.BatchId=@rBatchId AND SO.GenderId=2) AS TotalGirls,
		
			 (Select COUNT(A.Id) from sStudent.tAcademic A
			 INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
				INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
				WHERE ClassId=@rClassId AND ((DivisionId=@rDivisionId) OR (@rDivisionId = 0)) AND ((StuM.StatusId=@rStatusId)OR(@rStatusId=0)) AND BatchId=@rBatchId AND SO.GenderId=1) AS TotalBoys,
			
			 (Select COUNT(A.Id) from sStudent.tAcademic A
				INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId
				INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
				WHERE ClassId=@rClassId AND ((DivisionId=@rDivisionId) OR (@rDivisionId = 0)) AND ((SM.StatusId=@rStatusId)OR(@rStatusId=0)) AND BatchId=@rBatchId AND SO.GenderId=2 AND SM.StatusId=3) AS LeftGirls,
			
			 (Select COUNT(A.Id) from sStudent.tAcademic A
				INNER JOIN  sStudent.tStudentMaster SM ON SM.Id= A.StudentId
				INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
				WHERE ClassId=@rClassId AND ((DivisionId=@rDivisionId) OR (@rDivisionId = 0)) AND ((SM.StatusId=@rStatusId)OR(@rStatusId=0)) AND BatchId=@rBatchId AND SO.GenderId=1 AND SM.StatusId=3) AS LeftBoys,
			
			
			(Select COUNT(R.AcademicId) from sAssessment.tResult R 
				 INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
				 INNER JOIN  sStudent.tStudentMaster SM ON SM.Id= A.StudentId
				 INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
				 WHERE A.ClassId=@rClassId AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId = 0)) AND ((SM.StatusId=@rStatusId)OR(@rStatusId=0)) AND A.BatchId=@rBatchId AND R.ExamId=@rExamId AND SO.GenderId=2) AS AppearedGirls,
				 
			 (Select COUNT(R.AcademicId) from sAssessment.tResult R 
				INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
				INNER JOIN  sStudent.tStudentMaster SM ON SM.Id= A.StudentId
				INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
				WHERE A.ClassId=@rClassId AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId = 0)) AND ((SM.StatusId=@rStatusId)OR(@rStatusId=0)) AND A.BatchId=@rBatchId AND R.ExamId=@rExamId AND So.GenderId=1) AS AppearedBoys,	
				
			 (Select COUNT(R.AcademicId) from sAssessment.tResult R 
				INNER JOIN sAssessment.tResultDetail RD ON R.Id = RD.ResultId
				INNER JOIN sAssessment.tExamDetail ED ON Rd.ExamDetailId = ED.Id
				INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
				INNER JOIN sStudent.tStudentMaster SM ON SM.Id= A.StudentId
				INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
				 WHERE A.ClassId=@rClassId AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId = 0)) AND ((SM.StatusId=@rStatusId)OR(@rStatusId=0)) AND A.BatchId=@rBatchId AND R.ExamId=@rExamId AND SO.GenderId=2
				 AND RD.IsPresent=0) AS AbsentGirls,
				 
			 (Select COUNT(R.AcademicId) from sAssessment.tResult R 
				INNER JOIN sAssessment.tResultDetail RD ON R.Id = RD.ResultId
				INNER JOIN sAssessment.tExamDetail ED ON Rd.ExamDetailId = ED.Id
				INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
				INNER JOIN sStudent.tStudentMaster SM ON SM.Id= A.StudentId
				INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
				 WHERE A.ClassId=@rClassId AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId = 0)) AND ((SM.StatusId=@rStatusId)OR(@rStatusId=0)) AND A.BatchId=@rBatchId AND R.ExamId=@rExamId AND SO.GenderId=1
				  AND RD.IsPresent=0) AS AbsentBoys,
			 
			 (Select COUNT(R.AcademicId) from sAssessment.tResult R 
				 INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
				 INNER JOIN sStudent.tStudentMaster SM ON SM.Id= A.StudentId
				 INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
				 WHERE A.ClassId=@rClassId AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId = 0)) AND ((SM.StatusId=@rStatusId)OR(@rStatusId=0)) AND A.BatchId=@rBatchId AND R.ExamId=@rExamId AND SO.GenderId=2
					AND R.ResultStatus='PASS') AS PassedGirls,    
				
			 (Select COUNT(R.AcademicId) from sAssessment.tResult R
				INNER JOIN sStudent.tAcademic A ON A.Id = R.AcademicId
				INNER JOIN sStudent.tStudentMaster SM ON SM.Id= A.StudentId
				INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
				WHERE  A.ClassId=@rClassId  AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId = 0)) AND ((SM.StatusId=@rStatusId)OR(@rStatusId=0)) AND  A.BatchId=@rBatchId  AND  R.ExamId=@rExamId  AND SO.GenderId=1
					AND R.ResultStatus='PASS') AS PassedBoys,      
				
			 (Select COUNT(R.AcademicId) from sAssessment.tResult R
				INNER JOIN sStudent.tAcademic A ON A.Id = R.AcademicId
				INNER JOIN sStudent.tStudentMaster SM ON SM.Id= A.StudentId
				INNER JOIN sStudent.tStudentOther  SO ON SO.StudentId=A.StudentId
				WHERE  A.ClassId=@rClassId AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId = 0)) AND ((SM.StatusId=@rStatusId)OR(@rStatusId=0)) AND  A.BatchId=@rBatchId AND  R.ExamId=@rExamId AND SO.GenderId=2
					 AND R.ResultStatus='PROMOTED') AS PassWithGraceGirls,
				
			 (Select COUNT(R.AcademicId) from  sAssessment.tResult R
				INNER JOIN sStudent.tAcademic A ON A.Id =R.AcademicId
				INNER JOIN sStudent.tStudentMaster SM ON SM.Id= A.StudentId
				INNER JOIN sStudent.tStudentOther  SO ON SO.StudentId=A.StudentId
				WHERE  A.ClassId=@rClassId AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId = 0)) AND ((SM.StatusId=@rStatusId)OR(@rStatusId=0)) AND A.BatchId=@rBatchId AND   R.ExamId=@rExamId AND SO.GenderId=1
					AND R.ResultStatus='PROMOTED') AS PassWithGraceBoys,
				
			 (Select COUNT(R.AcademicId) from sAssessment.tResult R
				INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
				INNER JOIN sStudent.tStudentMaster SM ON SM.Id= A.StudentId
				INNER JOIN sStudent.tStudentOther SO ON  SO.StudentId=A.StudentId
				WHERE   A.ClassId=@rClassId AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId = 0))  AND ((SM.StatusId=@rStatusId)OR(@rStatusId=0)) AND A.BatchId=@rBatchId AND R.ExamId=@rExamId AND SO.GenderId=2
					AND R.ResultStatus='FAIL') AS FailedGirls,
					
			 (Select COUNT(R.AcademicId) from sAssessment.tResult R
				INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
				INNER JOIN sStudent.tStudentMaster SM ON SM.Id= A.StudentId
				INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
				WHERE A.ClassId=@rClassId AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId = 0)) AND ((SM.StatusId=@rStatusId)OR(@rStatusId=0)) AND A.BatchId=@rBatchId AND R.ExamId=@rExamId AND SO.GenderId=1
						AND R.ResultStatus='FAIL') AS FailedBoys,
						
			 (Select COUNT(A.Id) from sStudent.tAcademic A
				INNER JOIN sStudent.tStudentMaster SM ON SM.Id= A.StudentId
				WHERE A.ClassId=@rClassId AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId = 0)) AND ((SM.StatusId=@rStatusId)OR(@rStatusId=0)) AND A.BatchId=@rBatchId) Total
			 
			FROM 
			sAssessment.tExamMaster EM 
			 INNER JOIN sSetup.tClassMaster CM ON CM.Id=EM.ClassId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId=CM.Id
 
	WHERE 
		  ((EM.Id=@rExamId) OR (@rExamId=0))
		 AND((CM.Id=@rClassId) OR (@rClassId=0))
		 AND((DM.Id=@rDivisionId) OR (@rDivisionId=0))
 
 		AND EM.BatchId=@rBatchId
END
GO
PRINT N'Altering [sAssessment].[pRptStudentSubjectWise]...';


GO



ALTER PROCEDURE [sAssessment].[pRptStudentSubjectWise]  
	 
	 -- @rAcademicId bigint=0,
	 @rExamId int=0,
	@rClassId int=0,
	@rDivisionId int=0,
 
	@rBatchId int=0,
	@rStatusId int=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	SELECT 
			 --CONVERT(nvarchar(20),A.Id) AS AcademicIdText,
			 CONVERT(nvarchar(20),@rExamId) AS ExamIdText,
			 CONVERT(nvarchar(20),@rClassId) AS ClassIdText,
			 CONVERT (nvarchar(20),@rDivisionId) AS DivisionIdText,
	
			 CONVERT (nvarchar(20),SM.Title) AS SubjectName,
			
			 (Select COUNT(A.Id) from sStudent.tAcademic A	
				INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
				INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
				WHERE CS.ClassId=@rClassId AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId = 0)) AND ((StuM.StatusId=@rStatusId)OR(@rStatusId=0)) AND A.BatchId=@rBatchId  AND SO.GenderId=2) AS TotalGirls,
		
			 (Select COUNT(A.Id) from sStudent.tAcademic A
				INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
				INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
				WHERE ClassId=@rClassId AND ((DivisionId=@rDivisionId) OR (@rDivisionId = 0)) AND ((StuM.StatusId=@rStatusId)OR(@rStatusId=0)) AND BatchId=@rBatchId AND SO.GenderId=1) AS TotalBoys,
			
			 (Select COUNT(A.Id) from sStudent.tAcademic A
				INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId
				INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
				WHERE ClassId=@rClassId AND ((DivisionId=@rDivisionId) OR (@rDivisionId = 0)) AND ((SM.StatusId=@rStatusId)OR(@rStatusId=0)) AND BatchId=@rBatchId AND SO.GenderId=2 AND SM.StatusId=3) AS LeftGirls,
			
			 (Select COUNT(A.Id) from sStudent.tAcademic A
				
				INNER JOIN  sStudent.tStudentMaster SM ON SM.Id= A.StudentId
				INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
				WHERE ClassId=@rClassId AND ((DivisionId=@rDivisionId) OR (@rDivisionId = 0)) AND ((SM.StatusId=@rStatusId)OR(@rStatusId=0)) AND BatchId=@rBatchId AND SO.GenderId=1 AND SM.StatusId=3) AS LeftBoys,
			
			
			 (Select COUNT(R.AcademicId) from sAssessment.tResult R 
				INNER JOIN sAssessment.tResultDetail RD ON R.Id = RD.ResultId
				INNER JOIN sAssessment.tExamDetail ED ON Rd.ExamDetailId = ED.Id
				INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
				INNER JOIN  sStudent.tStudentMaster SM ON SM.Id= A.StudentId
				INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
				 WHERE A.ClassId=@rClassId AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId = 0)) AND ((SM.StatusId=@rStatusId)OR(@rStatusId=0)) AND A.BatchId=@rBatchId AND R.ExamId=@rExamId AND SO.GenderId=2
				 AND ED.ClassSubjectId = EDO.ClassSubjectId
				 )  AS AppearedGirls,
				 
			(Select COUNT(R.AcademicId) from sAssessment.tResult R 
				INNER JOIN sAssessment.tResultDetail RD ON R.Id = RD.ResultId
				INNER JOIN sAssessment.tExamDetail ED ON Rd.ExamDetailId = ED.Id
				INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
				INNER JOIN  sStudent.tStudentMaster SM ON SM.Id= A.StudentId
				INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
				 WHERE A.ClassId=@rClassId AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId = 0)) AND ((SM.StatusId=@rStatusId)OR(@rStatusId=0)) AND A.BatchId=@rBatchId AND R.ExamId=@rExamId AND SO.GenderId=1
				 AND ED.ClassSubjectId = EDO.ClassSubjectId
				
				) AS AppearedBoys,	
				
			 (Select COUNT(R.AcademicId) from sAssessment.tResult R 
				INNER JOIN sAssessment.tResultDetail RD ON R.Id = RD.ResultId
				INNER JOIN sAssessment.tExamDetail ED ON Rd.ExamDetailId = ED.Id
				INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
				INNER JOIN  sStudent.tStudentMaster SM ON SM.Id= A.StudentId
				INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
				 WHERE A.ClassId=@rClassId AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId = 0)) AND ((SM.StatusId=@rStatusId)OR(@rStatusId=0)) AND A.BatchId=@rBatchId AND R.ExamId=@rExamId AND SO.GenderId=2
				 AND ED.ClassSubjectId = EDO.ClassSubjectId AND RD.IsPresent=0
				) AS AbsentGirls,
				
			 (Select COUNT(R.AcademicId) from sAssessment.tResult R 
				INNER JOIN sAssessment.tResultDetail RD ON R.Id = RD.ResultId
				INNER JOIN sAssessment.tExamDetail ED ON Rd.ExamDetailId = ED.Id
				INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
				INNER JOIN  sStudent.tStudentMaster SM ON SM.Id= A.StudentId
				INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
				 WHERE A.ClassId=@rClassId AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId = 0)) AND ((SM.StatusId=@rStatusId)OR(@rStatusId=0)) AND A.BatchId=@rBatchId AND R.ExamId=@rExamId AND SO.GenderId=1
				 AND ED.ClassSubjectId = EDO.ClassSubjectId AND RD.IsPresent=0
				) AS AbsentBoys,
			 
			 (Select COUNT(R.AcademicId) from sAssessment.tResult R 
				INNER JOIN sAssessment.tResultDetail RD ON R.Id = RD.ResultId
				INNER JOIN sAssessment.tExamDetail ED ON Rd.ExamDetailId = ED.Id
				INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
				INNER JOIN  sStudent.tStudentMaster SM ON SM.Id= A.StudentId
				INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
				 WHERE A.ClassId=@rClassId AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId = 0)) AND ((SM.StatusId=@rStatusId)OR(@rStatusId=0)) AND A.BatchId=@rBatchId AND R.ExamId=@rExamId AND SO.GenderId=2
				 AND ED.ClassSubjectId = EDO.ClassSubjectId AND RD.Obtain >= ED.Minimum AND ISNULL(RD.GraceMark,0) = 0
				 ) AS PassedGirls,
				
			 (Select COUNT(R.AcademicId) from sAssessment.tResult R 
				INNER JOIN sAssessment.tResultDetail RD ON R.Id = RD.ResultId
				INNER JOIN sAssessment.tExamDetail ED ON Rd.ExamDetailId = ED.Id
				INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
				INNER JOIN  sStudent.tStudentMaster SM ON SM.Id= A.StudentId
				INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
				 WHERE A.ClassId=@rClassId AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId = 0)) AND ((SM.StatusId=@rStatusId)OR(@rStatusId=0)) AND A.BatchId=@rBatchId AND R.ExamId=@rExamId AND SO.GenderId=1
				 AND ED.ClassSubjectId = EDO.ClassSubjectId AND RD.Obtain >= ED.Minimum AND ISNULL(RD.GraceMark,0)=0
				 ) AS PassedBoys,
				
			 (Select COUNT(R.AcademicId) from sAssessment.tResult R 
				INNER JOIN sAssessment.tResultDetail RD ON R.Id = RD.ResultId
				INNER JOIN sAssessment.tExamDetail ED ON Rd.ExamDetailId = ED.Id
				INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
				INNER JOIN  sStudent.tStudentMaster SM ON SM.Id= A.StudentId
				INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
				 WHERE A.ClassId=@rClassId AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId = 0)) AND ((SM.StatusId=@rStatusId)OR(@rStatusId=0)) AND A.BatchId=@rBatchId AND R.ExamId=@rExamId AND SO.GenderId=2
				 AND ED.ClassSubjectId = EDO.ClassSubjectId AND RD.Obtain + RD.GraceMark >= ED.Minimum AND ISNULL(RD.GraceMark,0) > 0
				 ) AS PassWithGraceGirls,
				
			 (Select COUNT(R.AcademicId) from sAssessment.tResult R 
				INNER JOIN sAssessment.tResultDetail RD ON R.Id = RD.ResultId
				INNER JOIN sAssessment.tExamDetail ED ON Rd.ExamDetailId = ED.Id
				INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
				INNER JOIN  sStudent.tStudentMaster SM ON SM.Id= A.StudentId
				INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
				 WHERE A.ClassId=@rClassId AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId = 0)) AND ((SM.StatusId=@rStatusId)OR(@rStatusId=0)) AND A.BatchId=@rBatchId AND R.ExamId=@rExamId AND SO.GenderId=1
				 AND ED.ClassSubjectId = EDO.ClassSubjectId AND RD.Obtain + RD.GraceMark >= ED.Minimum AND ISNULL(RD.GraceMark,0) > 0
				  ) AS PassWithGraceBoys,
				
			 (Select COUNT(R.AcademicId) from sAssessment.tResult R 
				INNER JOIN sAssessment.tResultDetail RD ON R.Id = RD.ResultId
				INNER JOIN sAssessment.tExamDetail ED ON Rd.ExamDetailId = ED.Id
				INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
				INNER JOIN  sStudent.tStudentMaster SM ON SM.Id= A.StudentId
				INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
				 WHERE A.ClassId=@rClassId AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId = 0)) AND ((SM.StatusId=@rStatusId)OR(@rStatusId=0)) AND A.BatchId=@rBatchId AND R.ExamId=@rExamId AND SO.GenderId=2
				 AND ED.ClassSubjectId = EDO.ClassSubjectId AND RD.Obtain + ISNULL(RD.GraceMark,0) < ED.Minimum 
				 ) AS FailedGirls,
				
			 (Select COUNT(R.AcademicId) from sAssessment.tResult R 
				INNER JOIN sAssessment.tResultDetail RD ON R.Id = RD.ResultId
				INNER JOIN sAssessment.tExamDetail ED ON Rd.ExamDetailId = ED.Id
				INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
				INNER JOIN  sStudent.tStudentMaster SM ON SM.Id= A.StudentId
				INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
				 WHERE A.ClassId=@rClassId AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId = 0)) AND ((SM.StatusId=@rStatusId)OR(@rStatusId=0)) AND A.BatchId=@rBatchId AND R.ExamId=@rExamId AND SO.GenderId=1
				 AND ED.ClassSubjectId = EDO.ClassSubjectId AND RD.Obtain +ISNULL(RD.GraceMark ,0)< ED.Minimum  
				 ) AS FailedBoys,
				
			 (Select COUNT(A.Id) from sStudent.tAcademic A	
				INNER JOIN sStudent.tStudentMaster SM ON SM.Id= A.StudentId
				INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
				WHERE A.ClassId=@rClassId AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId = 0)) AND ((SM.StatusId=@rStatusId)OR(@rStatusId=0)) AND A.BatchId=@rBatchId) AS Total,
			--A.RollNo,
			--A.Id AS AcademicId,
			
			SM.Title AS SubjectName,
			SM.Id AS SubjectId
		 
		 
			FROM 
			
			sAssessment.tExamMaster EM
			INNER JOIN sAssessment.tExamDetail EDO ON EDO.ExamId=EM.Id
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=EDO.ClassSubjectId
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId=CS.ClassId
		
	WHERE 
		 
	 ((EM.Id=@rExamId) OR (@rExamId=0))
	 AND((CS.ClassId =@rClassId) OR (@rClassId=0))
	 AND((DM.Id =@rDivisionId)  OR(@rDivisionId=0))
	 
	 AND(EM.BatchId=@rBatchId)
		order by CS.OrderIndex
	
END
GO
PRINT N'Altering [sAssessment].[pRptStudentTopperClassSectionWise]...';


GO




ALTER PROCEDURE [sAssessment].[pRptStudentTopperClassSectionWise]
	 
	--  @rAcademicId bigint=0,
	 @rExamId int=0,
	 @rClassId int=0, 
	 @rBatchId int=0,
	 --@rDivisionId int=0,
	 @rStatusId int=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
SELECT r1.*
FROM
(	
	SELECT  
	 
			R.Percentage,
			ROW_NUMBER() OVER(PARTITION BY 
				  CM.Id 
			 ORDER BY R.Percentage DESC) CM ,
	 		--CONVERT(nvarchar(20),A.Id) AS AcademicIdText,
		    CONVERT(nvarchar(20),@rExamId) AS ExamIdText,
		    CONVERT(nvarchar(20),@rClassId) AS ClassIdText,
		    --CONVERT(nvarchar(20),@rDivisionId) AS DivisionIdText,
					
		      R.RankNumber AS RankNumber,	
		      
			 R.TotalObtain AS ObtMarks,
			   
			 R.TotalMarks AS  OutOfMarks,
				
			 CM.Title + '-' + DM.Title AS ClassDivision,
			STM.FirstName + ' ' + STM.LastName AS Name,
			A.RollNo ,
			 DM.Id AS DivisionId
			 
			 
			
		 FROM
			sAssessment.tExamMaster EM
			INNER JOIN sAssessment.tResult R ON EM.Id=R.ExamId 
		    INNER JOIN sStudent.tAcademic A	ON A.Id=R.AcademicId
			INNER JOIN sStudent.tStudentMaster STM ON STM.Id=A.StudentId
		  
		   INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
			
	 WHERE 
		 ((EM.Id=@rExamId) OR (@rExamId=0))
		 AND ((EM.ClassId=@rClassId) OR (@rClassId=0))
		 
		 AND ((R.RankNumber <=3) AND (R.RankNumber<>0))
		 AND ((STM.StatusId=@rStatusId)OR(@rStatusId=0))
			 
		)r1
		WHERE((r1.CM <=3) OR (r1.Cm=0))
			
			 
		
END
GO
PRINT N'Altering [sAssessment].[pRptStudentTopperClassWise]...';


GO




ALTER PROCEDURE [sAssessment].[pRptStudentTopperClassWise]
	 
	 -- @rAcademicId bigint=0,
	 @rExamId int=0,
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rBatchId int=0,
	 @rStatusId int=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	SELECT  
			
			 
			R.Percentage,
	 		--CONVERT(nvarchar(20),A.Id) AS AcademicIdText,
		    CONVERT(nvarchar(20),@rExamId) AS ExamIdText,
		    CONVERT(nvarchar(20),@rClassId) AS ClassIdText,
		    CONVERT(nvarchar(20),@rDivisionId) AS DivisionIdText,
				
		      R.RankNumber AS RankNumber,	
		      
			R.TotalObtain AS ObtMarks,
			 R.TotalMarks AS OutOfMarks,
			 
			STM.FirstName + ' ' + STM.LastName AS Name,
			A.RollNo,
			A.Id AS AcademicId,
			EM.Id AS ExamId
			
		 
			FROM 
				sAssessment.tExamMaster EM
			INNER JOIN sAssessment.tResult R ON EM.Id=R.ExamId
		    INNER JOIN sStudent.tAcademic A	ON A.Id=R.AcademicId
			INNER JOIN sStudent.tStudentMaster STM ON STM.Id=A.StudentId
		 
		 
	 WHERE 
		 ((EM.Id=@rExamId) OR (@rExamId=0))
		 AND((EM.ClassId=@rClassId) OR (@rClassId=0))
		 AND((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		  
		 AND ((R.RankNumber <= 3) AND(R.RankNumber<>0))
		 AND ((STM.StatusId=@rStatusId)OR(@rStatusId=0))
			order by A.DivisionId,R.RankNumber 
	 
END
GO
PRINT N'Altering [sAssessment].[pRptSubjectResultListFloating]...';


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

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

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


GO
ALTER PROCEDURE [sAssessment].[pValidateImportSubjectActivity]
     @rOrgId smallint,
	 @rXmldoc [nvarchar](max)
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
DECLARE @lCount INT
DECLARE @lInterrorCode INT,@intDoc INT, @lCode nvarchar(100),  @lTitle nvarchar(200), @lNumber int,@lClass nvarchar(100), 
        @lSubCode nvarchar(100),  @lSubTitle nvarchar(200), @lSubNumber int,@lSubClass nvarchar(100),@1SubOrderIndex int,
	    @lSubject nvarchar(100), @1OrderIndex int,  @1ReturnCode int = 1,@lGradeSet nvarchar(100),@1SubDuplicateCode nvarchar(max) = '',
        @1ExistCode nvarchar(max) = '',@1DuplicateCode nvarchar(max) = '', @1ExistOrderIndex nvarchar(max) = '',
        @1DuplicateTitle nvarchar(max) = '', @1DuplicateOrderIndex nvarchar(max) = '', @1SubDuplicateTitle nvarchar(max) = '', @1SubDuplicateOrderIndex nvarchar(max) = '',
        @1ExistNumber nvarchar(max) = '',@1ExistTitle nvarchar(max) = '',@lClassSubjectId int,@lOrderIndex int,@1DuplicateNumber nvarchar(max)='',@SubDuplicateNumber nvarchar(max)='',
        @1SubExistNumber nvarchar(max) = '',@1SubExistTitle nvarchar(max) = '', @1SubExistCode nvarchar(max) = '',@1SubExistOrderIndex nvarchar(max) = '',@lSubjectActivityId int=0
EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc
CREATE TABLE #tTable1 
 (
		Id bigint identity,
		Code nvarchar(100), 
		Name nvarchar(200),
		Number int, 
	    OrderIndex int,
		GradeSet nvarchar(100),
	    Class Nvarchar(100),
	    Subject Nvarchar(100),
	    SubNumber int, 
		SubCode nvarchar(100), 
		SubName nvarchar(200),
		SubOrderIndex int
  )
  INSERT INTO #tTable1(Code,Name,Number,OrderIndex,GradeSet,Class,Subject,SubNumber,SubCode,SubName,SubOrderIndex)
    
   SELECT
          Code,Name,Number,OrderIndex,GradeSet,Class,Subject,SubNumber,SubCode,SubName,SubOrderIndex
   FROM OPENXML (@intDoc, '/Table/ImportSubjectActivity', 1)
   With
   (
        Code nvarchar(100) '@Code',			
		Name nvarchar(200) '@Name',			
		Number int '@Number',			
		GradeSet nvarchar(100) '@GradeSet',			
		OrderIndex int '@OrderIndex',
		Class nvarchar(100) '@Class',
		Subject  nvarchar(100) '@Subject',
		SubNumber int '@SubNumber',
		SubCode nvarchar(100) '@SubCode',			
		SubName nvarchar(200) '@SubName',
		SubOrderIndex int '@SubOrderIndex'
   )     
   
EXEC sp_xml_removedocument @intDoc
			
IF EXISTS(SELECT 1 fROM #tTable1 WHERE Code IS NULL OR Code COLLATE DATABASE_DEFAULT='' COLLATE DATABASE_DEFAULT)
BEGIN
	SELECT 'Code Should not be empty' AS ValidateCode
END
 IF EXISTS(SELECT 1 fROM #tTable1 WHERE Name IS NULL OR Name COLLATE DATABASE_DEFAULT='' COLLATE DATABASE_DEFAULT)
BEGIN
	SELECT 'Name Should not be empty' AS ValidateCode
END
 IF EXISTS(SELECT 1 fROM #tTable1 WHERE Class IS NULL OR Class COLLATE DATABASE_DEFAULT='' COLLATE DATABASE_DEFAULT)
BEGIN
	SELECT 'Class Should not be empty' AS ValidateCode
END
 IF EXISTS(SELECT 1 fROM #tTable1 WHERE Subject IS NULL OR Subject COLLATE DATABASE_DEFAULT='' COLLATE DATABASE_DEFAULT)
BEGIN
	SELECT 'Subject Should not be empty' AS ValidateCode
END
IF EXISTS(SELECT 1 fROM #tTable1 WHERE Number IS NULL OR Number ='')
BEGIN
	SELECT 'Number Should not be empty' AS ValidateCode
END
IF EXISTS(SELECT 1 fROM #tTable1 WHERE OrderIndex IS NULL OR OrderIndex ='')
BEGIN
	SELECT 'OrderIndex Should not be empty' AS ValidateCode
END
IF EXISTS(SELECT 1 fROM #tTable1 WHERE SubName IS NULL OR SubName COLLATE DATABASE_DEFAULT='' COLLATE DATABASE_DEFAULT)
BEGIN
	SELECT 'Sub Name Should not be empty' AS ValidateCode
END
IF EXISTS(SELECT 1 fROM #tTable1 WHERE SubCode IS NULL OR SubCode COLLATE DATABASE_DEFAULT='' COLLATE DATABASE_DEFAULT)
BEGIN
	SELECT 'Sub Code Should not be empty' AS ValidateCode
END
IF EXISTS(SELECT 1 fROM #tTable1 WHERE SubOrderIndex IS NULL OR SubOrderIndex ='')
BEGIN
	SELECT 'Sub OrderIndex Should not be empty' AS ValidateCode
END
IF EXISTS(SELECT 1 fROM #tTable1 WHERE SubNumber IS NULL OR SubNumber ='')
BEGIN
	SELECT 'Sub Number Should not be empty' AS ValidateCode
END
ELSE
BEGIN	
SELECT @lCount =  COUNT(Id) FROM #tTable1
WHILE @lCount > 0 
BEGIN
	SELECT @lCode = Code,@lTitle=Name,@lNumber=Number,@lOrderIndex=OrderIndex,@lSubject=Subject,@lClass=Class,@lGradeSet=GradeSet,
	@lSubCode =SubCode,@lSubTitle=SubName,@1SubOrderIndex=SubOrderIndex,@lSubNumber=SubNumber
	FROM #tTable1 WHERE Id = @lCount  
IF NOT EXists(SELECT  1 FROM sSetup.vClassSubject  VS
	INNER JOIN  sSetup.tClassMaster CM ON CM.Id=VS.ClassId where VS.IsObsolete=0 AND CM.Title=@lClass  AND Vs.SubjectName=@lSubject AND CM.OrgId=@rOrgId)
 BEGIN
     SELECT 'Enter proper value for Class  or Subject  :' + @lClass + '/' + @lSubject AS ValidateCode
    END
    ELSE
    BEGIN
    SET @lClassSubjectId=0
    SELECT @lClassSubjectId= ClassSubjectId FROM sSetup.vClassSubject  VS
	INNER JOIN  sSetup.tClassMaster CM ON CM.Id=VS.ClassId where VS.IsObsolete=0 AND CM.Title=@lClass  AND Vs.SubjectName=@lSubject AND CM.OrgId=@rOrgId 
    END
	 IF NOT EXists( SELECT 1 FROM sAssessment.tGradeSetMaster WHERE  OrgId=@rOrgId  AND Title=@lGradeSet )
  BEGIN
     SELECT 'Enter proper value for Gradeset : ' + @lGradeSet  AS ValidateCode
    END
 IF NOT Exists (select 1  FROM  sAssessment.tCCESubjectActivityMaster where OrgId=@rOrgId AND Code=@lCode AND ClassSubjectId = @lClassSubjectId )
 BEGIN
 SET @lSubjectActivityId=0
 END
 ELSE
 BEGIN
   SELECT @lSubjectActivityId=Id FROM   sAssessment.tCCESubjectActivityMaster   where OrgId=@rOrgId AND Code=@lCode
  IF Exists ((select 1 from sAssessment.tCCESubjectSubActivityMaster where OrgId=@rOrgId AND SubjectActivityId = @lSubjectActivityId AND Code COLLATE DATABASE_DEFAULT = @lSubCode COLLATE DATABASE_DEFAULT))         
    BEGIN
		SET @1SubExistCode = @1SubExistCode + @lSubCode + ','
    END	  
 IF Exists ((select 1 from sAssessment.tCCESubjectSubActivityMaster where OrgId=@rOrgId AND SubjectActivityId = @lSubjectActivityId AND Title COLLATE DATABASE_DEFAULT = @lSubTitle COLLATE DATABASE_DEFAULT))         
    BEGIN
		SET @1SubExistTitle = @1SubExistTitle + @lSubTitle + ','
    END	  
  IF Exists ((select 1 from sAssessment.tCCESubjectSubActivityMaster where OrgId=@rOrgId AND OrderIndex =Convert(varchar,@1SubOrderIndex) AND SubjectActivityId = @lSubjectActivityId AND Convert(varchar,OrderIndex) COLLATE DATABASE_DEFAULT = Convert(varchar,@1SubOrderIndex) COLLATE DATABASE_DEFAULT))         
    BEGIN
		SET @1SubExistOrderIndex= @1SubExistOrderIndex + Convert(varchar,@1SubOrderIndex )+ ','
    END	  
 IF Exists ((select 1 from sAssessment.tCCESubjectSubActivityMaster where OrgId=@rOrgId AND Number =Convert(varchar,@lSubNumber) AND SubjectActivityId = @lSubjectActivityId AND Convert(varchar,Number) COLLATE DATABASE_DEFAULT = Convert(varchar,@lSubNumber) COLLATE DATABASE_DEFAULT))               
    BEGIN
		SET @1SubExistNumber= @1SubExistNumber + Convert(varchar,@lSubNumber) + ','
    END	  
  END
  IF Exists ((select 1 from sAssessment.tCCESubjectActivityMaster where OrgId=@rOrgId AND OrderIndex =Convert(varchar,@lOrderIndex) AND Convert(varchar,OrderIndex) COLLATE DATABASE_DEFAULT = Convert(varchar,@lOrderIndex) COLLATE DATABASE_DEFAULT))         
    BEGIN
		SET @1ExistOrderIndex= @1ExistOrderIndex + Convert(varchar,@lOrderIndex )+ ','
    END	
	SET @lCount = @lCount - 1	
 END
 

	SELECT @1SubDuplicateCode=COALESCE(@1SubDuplicateCode ,'') + SubCode + ',' FROM #tTable1 GROUP BY SubCode,Class,subject,Code,Name HAVING ( COUNT(SubCode) > 1 )	
    SELECT @1SubDuplicateTitle=COALESCE(@1SubDuplicateTitle ,'') + SubName + ',' FROM #tTable1 GROUP BY SubName,Class,subject,Code,Name HAVING ( COUNT(SubName) > 1 )	
  	SELECT @1SubDuplicateOrderIndex=COALESCE(@1SubDuplicateOrderIndex,'')  + convert(varchar,SubOrderIndex) + ',' FROM #tTable1 GROUP BY SubOrderIndex,Class,subject,Code,Name HAVING ( COUNT(SubOrderIndex) > 1 )	
  	SELECT @SubDuplicateNumber=COALESCE(@SubDuplicateNumber,'')  + convert(varchar,SubNumber) + ',' FROM #tTable1 GROUP BY SubNumber,Class,subject,Code,Name HAVING ( COUNT(SubNumber) > 1 )
	SELECT @1DuplicateOrderIndex=COALESCE(@1DuplicateOrderIndex,'')  + convert(varchar,OrderIndex) + ',' FROM #tTable1 GROUP BY OrderIndex,Class,subject,Code,Name HAVING ( COUNT(OrderIndex) > 1 )		
	IF(@1SubDuplicateCode IS NOT NULL AND @1SubDuplicateCode != '')
	BEGIN
		SET @1SubDuplicateCode = 'Duplicate Sub Code : ' + @1SubDuplicateCode
	END
	IF(@1SubDuplicateTitle IS NOT NULL AND @1SubDuplicateTitle != '')
	BEGIN
	SET @1SubDuplicateTitle = 'Duplicate Sub Name : ' + @1SubDuplicateTitle
	END
	IF(@1SubDuplicateOrderIndex IS  NOT NULL AND @1SubDuplicateOrderIndex != '')
	BEGIN
	SET @1SubDuplicateOrderIndex = 'Duplicate Sub OrderIndex : ' + @1SubDuplicateOrderIndex
	END
	IF(@SubDuplicateNumber IS NOT NULL AND @SubDuplicateNumber != '')
	BEGIN
	SET @SubDuplicateNumber = 'Duplicate Sub Number : ' + @SubDuplicateNumber
	END
	 IF (@1SubExistCode IS NOT NULL AND @1SubExistCode != '' )
	BEGIN
		SET @1SubExistCode = 'Exist Sub Code : ' + @1SubExistCode
	END
	ELSE IF (@1SubExistCode IS NOT NULL AND @1SubExistCode = '' )
	BEGIN
		SET @1SubExistCode=''
	END
	 IF (@1SubExistTitle IS NOT NULL AND @1SubExistTitle != '' )
	BEGIN
		SET @1SubExistTitle = 'Exist Sub Title : ' + @1SubExistTitle
	END
	
	 IF (@1SubExistOrderIndex IS NOT NULL  AND @1SubExistOrderIndex != '' )
	BEGIN
		SET @1SubExistOrderIndex = 'Exist Sub OrderIndex : ' + @1SubExistOrderIndex
	END
	
	 IF (@1ExistOrderIndex IS NOT NULL  AND @1ExistOrderIndex != '' )
	BEGIN
		SET @1ExistOrderIndex = 'Exist OrderIndex : ' + @1ExistOrderIndex
	END

  	 IF (@1SubExistNumber IS NOT NULL AND @1SubExistNumber != '' )
	BEGIN
		SET @1SubExistNumber = 'Exist Sub Number : ' + @1SubExistNumber
	END
	END
	Select Isnull(@1SubDuplicateCode,'')+Isnull(@1SubDuplicateTitle,'')+Isnull(@SubDuplicateNumber,'')+Isnull(@1SubDuplicateOrderIndex,'')+
	Isnull(@1SubExistCode,'') +Isnull(@1SubExistTitle,'')+Isnull(@1SubExistNumber,'')+Isnull(@1SubExistOrderIndex,'') +Isnull(@1DuplicateOrderIndex,'')+Isnull(@1ExistOrderIndex,'')
	  AS ValidateCode
END
GO
PRINT N'Altering [sAssetManagement].[pAssetMasterListDataGet]...';


GO
ALTER PROCEDURE [sAssetManagement].[pAssetMasterListDataGet]
 	@rOrgGroupId smallint,

	@rId [int] = 0,
	@rCode [nvarchar](100) = '',
	@rTitle [nvarchar](100) = '',
	@rLocationId [int] = 0,
	@rIsWildCard [bit] = 0,
	@rStoreLocationId int,
	@rDepartmentId int

 	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

SET @rCode  = ISNULL(@rCode, '') 
SET @rTitle = ISNULL(@rTitle, '') 

IF @rIsWildCard = 1
BEGIN
SET @rCode  = sCommon.fSearchStringGet(@rCode)
SET @rTitle = sCommon.fSearchStringGet(@rTitle)
END

       SELECT AM.Id,
                  AM.Code,
                  AM.Title,
                  Specification,
                  Accessories,
                  AM.LocationId,
                  StatusId,
                  VendorId,
                  VM.Title AS VendorName,
                  GoodsReceiptNumber,
                  GoodsReceiptDate,
                  IsInstallationRequired,
                  InstallationDate,
                  CategoryId,
                  DepreciationUptoDate,
                  IsFullyDepreciated,
                  StandardPrice,
                  MinStockRequired,
                  MaintenancePeriod,
                  IsAmc,                  
                  MaintenanceAlertPeriod,
                  AmcVendorId,
                  VM1.Title AS AmcVendorName,
                  UsageStatusId,
                  LastServiceCost,
                  TotalServiceCost,
                  LastDownTime,
                  TotalDownTime,
                  LastMaintenanceDate,
                  NextMaintenanceDate,
                  ModelNumber,
                  IsCritical,
                  AM.IsObsolete,
                  AM.CreatedUserId,
                  AM.CreatedDateTime,
                  AM.UpdatedUserId,
                  AM.UpdatedDateTime,
                  AM.DepartmentID,
                  ServiceEntry,
                  ODM.Title AS DepartmentTitle,
                  VAD1.Title AS LocationTitle,
                  FCM.Title AS CategoryTitle,
                  CM.Title AS StatusTitle,
                  
                   AM.IsCheckRequired,
				  ISNULL (AM.CheckFrequencyId,0) AS CheckFrequencyId,	
				  AM.CheckList,	
                  --AM.CheckedLastDate,
                   ISNULL(AM.CheckedLastDate,'0001/01/01') AS CheckedLastDate,
                  AM.CheckedByUserId,
                  ISNULL(AM.CheckedStatusId,0) AS CheckedStatusId,
                  AM.CheckedRemark,
                  IsRenewRequired,
                  ISNULL(RenewLastDate,'0001/01/01') AS RenewLastDate,
                  ISNULL(RenewNextDate,'0001/01/01') AS RenewNextDate,
                --  AM.RenewLastDate,
                  --AM.RenewNextDate,
				  AM.RenewRemark,
				  AM.RenewCheckList,
				  AM.RenewAlertBeforeDays,
				  U.LoginTitle AS UserTitle
				,ISNULL (AM.IsMaintenanceRequired,0) AS IsMaintenanceRequired
				,ISNULL(AM.WarrantyDate,'0001/01/01') AS WarrantyDate
				,AM.AssetImage AS AssetImage
				,ISNULL(AM.AssetCode,'') AS AssetCode
         FROM sAssetManagement.tAssetMaster AM
         LEFT JOIN sProcurement.tVendorMaster VM
                  ON VM.Id = AM.VendorId 
         LEFT JOIN sProcurement.tVendorMaster VM1
                  ON VM1.Id = AM.AmcVendorId 
            --INNER JOIN (SELECT DISTINCT DepartmentId, DepartmentTitle FROM sAssetManagement.vExtAssetDepartment) VAD
            --ON VAD.DepartmentId = AM.DepartmentID
            INNER JOIN sSetup.tDepartmentMaster ODM ON ODM.Id = AM.DepartmentId
             --left JOIN sCommon.tOrganizationDepartmentMaster ODM ON ODM.Id = AM.DepartmentId
            INNER JOIN sFixedAsset.tLocationMaster VAD1
            ON VAD1.Id = AM.LocationId 
            INNER JOIN (SELECT DISTINCT Id, Title FROM sFixedAsset.tCategoryMaster ) FCM
            ON FCM.Id = AM.CategoryId
            INNER JOIN (SELECT DISTINCT Id, Title FROM sCommon.tStatusMaster) CM
            ON CM.Id = AM.UsageStatusId
             LEFT JOIN sSecurity.tUser U ON U.Id=AM.CheckedByUserId
        WHERE ((AM.Id = @rId) OR (@rId = 0)) 
		AND ((AM.Code LIKE @rCode) OR (@rCode = '')) 
		--AND ((AM.AssetCode LIKE @rAssetCode) OR (@rAssetCode = ''))
		AND ((AM.Title LIKE @rTitle) OR (@rTitle = ''))
        AND AM.OrgGroupId = @rOrgGroupId
        AND AM.StoreLocationId=@rStoreLocationId
        AND ((AM.LocationId = @rLocationId) OR (@rLocationId = 0))
        AND ((AM.DepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))
        ORDER BY AM.Code DESC

END
GO
PRINT N'Altering [sAttendance].[pTakeAttendanceList]...';


GO

ALTER PROCEDURE [sAttendance].[pTakeAttendanceList]

	@rOrgId int=0,
	@rOrgGroupId int=0,
	@rUserId bigint =0,
	@rUserSourceId bigint = 0,
	@rAttendanceEntry nvarchar(100),
	@rOrgGroupBatchId int =0,
	@rAttendanceDate Date = null,
	@rAttendanceTypeId int =0,
	@rAttendanceTagId int =0,
	@rAbsentReasonId int =0
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	IF(@rAttendanceEntry = 'Class Teacher')
	BEGIN
		SELECT DISTINCT CM.Id AS ClassId,DM.Id AS DivisionId,OM.Id AS OrgId,CM.DisplayTitle+'-'+DM.Title AS ClassDivision,OM.DisplayTitle AS OrganizationName,
		CM.OrderIndex AS ClassOrderIndex,DM.OrderIndex AS DivisionOrderIndex,OM.OrderIndex AS OrganizationOrderIndex,
		convert(bit,(SELECT CASE WHEN COUNT(*)>0 THEN 1 ELSE 0 END AS IsTakeAttendance  FROM sAttendance.tStudentRegister SR
		INNER JOIN sStudent.tAcademic A ON A.Id = SR.AcademicId 
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId 
		WHERE AttendanceTypeId=@rAttendanceTypeId AND AttendanceDate=@rAttendanceDate AND  BM.OrgGroupBatchId = @rOrgGroupBatchId AND A.ClassId=CM.Id AND A.DivisionId=DM.Id )) AS IsTakeAttendance,
		(SELECT ATM.Title FROM sAttendance.tStudentRegister SR INNER JOIN sAttendance.tAttendanceTagMaster ATM ON ATM.Id = SR.AttendanceTagId WHere ATM.Id =@rAttendanceTagId GROUP BY ATM.Title) AS AttendanceTag,
		(SELECT ARM.Title FROM sAttendance.tStudentRegister SR INNER JOIN sAttendance.tAbsentReasonMaster ARM ON ARM.Id =SR.AbsentReasonId  WHere  ARM.Id  =@rAbsentReasonId GROUP BY ARM.Title) AS AbsentReason
		FROM sSetup.tClassMaster CM 
		INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId = CM.Id
		INNER JOIN sSetup.tOrganizationMaster OM ON CM.OrgId = OM .Id
		WHERE DM.InchargeemployeeID= @rUserSourceId AND OM.OrgGroupId= @rOrgGroupId  AND CM.IsObsolete=0 AND DM.IsObsolete=0 
		ORDER BY OM.OrderIndex,CM.OrderIndex,DM.OrderIndex
	END
	ELSE IF(@rAttendanceEntry ='Academic Setup')
	BEGIN 
		SELECT DISTINCT TD.ClassId AS ClassId,TD.DivisionId AS DivisionId,OM.Id AS OrgId,TD.ClassTitle+'-'+TD.DivisionTitle AS ClassDivision,OM.DisplayTitle AS OrganizationName,
		CONVERT(bit,(SELECT CASE WHEN COUNT(*)>0 THEN 1 ELSE 0 END AS IsTakeAttendance  FROM sAttendance.tStudentRegister SR
		INNER JOIN sStudent.tAcademic A ON A.Id = SR.AcademicId 
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId 
		WHERE AttendanceTypeId=@rAttendanceTypeId AND AttendanceDate=@rAttendanceDate AND  BM.OrgGroupBatchId = @rOrgGroupBatchId AND A.ClassId=TD.ClassId AND A.DivisionId=TD.DivisionId )) AS IsTakeAttendance,
		(SELECT ATM.Title FROM sAttendance.tStudentRegister SR INNER JOIN sAttendance.tAttendanceTagMaster ATM ON ATM.Id = SR.AttendanceTagId WHere ATM.Id =@rAttendanceTagId GROUP BY ATM.Title) AS AttendanceTag,
		(SELECT ARM.Title FROM sAttendance.tStudentRegister SR INNER JOIN sAttendance.tAbsentReasonMaster ARM ON ARM.Id =SR.AbsentReasonId  WHere  ARM.Id  =@rAbsentReasonId GROUP BY ARM.Title) AS AbsentReason,
		TD.ClassOrderIndex AS ClassOrderIndex,OM.OrderIndex AS OrganizationOrderIndex 
		FROM sAcademic.vTeacherSubjectDivision TD
		INNER JOIN sSetup.tOrganizationMaster OM ON TD.OrgId = OM.Id
		WHERE TD.EmployeeId= @rUserSourceId  AND OM.OrgGroupId= @rOrgGroupId  AND CMIsObsolete=0  AND DMIsObsolete=0 
		ORDER BY OM.OrderIndex,TD.ClassOrderIndex
	END
	ELSE IF(@rAttendanceEntry ='User Access')
	BEGIN
		SELECT DISTINCT CM.Id AS ClassId,DM.Id AS DivisionId,OM.Id AS OrgId,CM.DisplayTitle+'-'+DM.Title AS ClassDivision,OM.DisplayTitle AS OrganizationName,
		convert(bit,(SELECT CASE WHEN COUNT(*)>0 THEN 1 ELSE 0 END AS IsTakeAttendance  FROM sAttendance.tStudentRegister SR
		INNER JOIN sStudent.tAcademic A ON A.Id = SR.AcademicId 
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId 
		WHERE AttendanceTypeId=@rAttendanceTypeId AND AttendanceDate=@rAttendanceDate AND BM.OrgGroupBatchId = @rOrgGroupBatchId AND A.ClassId=CM.Id AND A.DivisionId=DM.Id )) AS IsTakeAttendance,
		(SELECT ATM.Title FROM sAttendance.tStudentRegister SR INNER JOIN sAttendance.tAttendanceTagMaster ATM ON ATM.Id = SR.AttendanceTagId WHere ATM.Id =@rAttendanceTagId GROUP BY ATM.Title) AS AttendanceTag,
		(SELECT ARM.Title FROM sAttendance.tStudentRegister SR INNER JOIN sAttendance.tAbsentReasonMaster ARM ON ARM.Id =SR.AbsentReasonId  WHere  ARM.Id  =@rAbsentReasonId GROUP BY ARM.Title) AS AbsentReason,
		CM.OrderIndex AS ClassOrderIndex,DM.OrderIndex AS DivisionOrderIndex,OM.OrderIndex AS OrganizationOrderIndex
		from sSetup.tClassMaster CM 
		INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId = CM.Id
		INNER JOIN sSetup.tOrganizationMaster OM ON CM.OrgId = OM.Id
		INNER JOIN sSecurity.tUserAccess U ON U.SourceId = DM.Id 
		Where OM.OrgGroupId= @rOrgGroupId AND U.SourceTypeId=2005 AND U.UserId = @rUserId AND CM.IsObsolete=0 AND DM.IsObsolete=0 
		ORDER BY OM.OrderIndex,CM.OrderIndex,DM.OrderIndex
	END
	ELSE IF(@rAttendanceEntry = 'Class Teacher Batch')
	BEGIN
		SELECT DISTINCT CM.Id AS ClassId,DM.Id AS DivisionId,OM.Id AS OrgId,CM.DisplayTitle+'-'+DM.Title AS ClassDivision,OM.DisplayTitle AS OrganizationName,
		CM.OrderIndex AS ClassOrderIndex,DM.OrderIndex AS DivisionOrderIndex,OM.OrderIndex AS OrganizationOrderIndex,
		convert(bit,(SELECT CASE WHEN COUNT(*)>0 THEN 1 ELSE 0 END AS IsTakeAttendance  FROM sAttendance.tStudentRegister SR
		INNER JOIN sStudent.tAcademic A ON A.Id = SR.AcademicId 
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId 
		WHERE AttendanceTypeId=@rAttendanceTypeId AND AttendanceDate=@rAttendanceDate AND  BM.OrgGroupBatchId = @rOrgGroupBatchId AND A.ClassId=CM.Id AND A.DivisionId=DM.Id )) AS IsTakeAttendance,
		(SELECT ATM.Title FROM sAttendance.tStudentRegister SR INNER JOIN sAttendance.tAttendanceTagMaster ATM ON ATM.Id = SR.AttendanceTagId WHere ATM.Id =@rAttendanceTagId GROUP BY ATM.Title) AS AttendanceTag,
		(SELECT ARM.Title FROM sAttendance.tStudentRegister SR INNER JOIN sAttendance.tAbsentReasonMaster ARM ON ARM.Id =SR.AbsentReasonId  WHere  ARM.Id  =@rAbsentReasonId GROUP BY ARM.Title) AS AbsentReason
		FROM sSetup.tClassMaster CM 
		INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId = CM.Id
		INNER JOIN sSetup.tDivisionInchargeEmployee DIE ON DIE.DivisionId = DM.Id
		INNER JOIN sSetup.tOrganizationMaster OM ON CM.OrgId = OM .Id
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = DIE.BatchId AND BM.OrgGroupBatchId = @rOrgGroupBatchId
		WHERE DIE.EmployeeId= @rUserSourceId AND OM.OrgGroupId= @rOrgGroupId AND CM.IsObsolete=0 AND DM.IsObsolete=0 
		ORDER BY OM.OrderIndex,CM.OrderIndex,DM.OrderIndex
	END
	
END
GO
PRINT N'Altering [sAudit].[pActivityLogAdd]...';


GO
ALTER PROCEDURE [sAudit].[pActivityLogAdd]
	 
		@rOrgGroupId int=0,
		@rOrgId int,
		@rUserId bigint,
		@rSessionId nvarchar(100),
		@rScreenId int,
		@rActivity nvarchar(500),
		@rRecordSourceId bigint,
		@rRecordDetail nvarchar(max),
		@rOSTypeId tinyint=0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	BEGIN TRANSACTION	
	
	INSERT INTO sAudit.tActivityLog
		(
			OrgGroupId,
			OrgId,
			UserId,
			SessionId,
			ScreenId,
			AuditDate,
			Activity,
			RecordSourceId,
			RecordDetail,
			OSTypeId
		)
	VALUES
		(
			@rOrgGroupId,
			@rOrgId,
			@rUserId,
			@rSessionId,
			@rScreenId,
			sCommon.fGetDate(),
			@rActivity,
			@rRecordSourceId,
			@rRecordDetail,
			@rOSTypeId
		)
		SELECT 1 AS Result
	
	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sAudit].[pActivityLogGet]...';


GO


ALTER PROCEDURE [sAudit].[pActivityLogGet]
	@rOrgGroupId int,
	@rOrgId int,
	@rUserName nvarchar(100),
	@rScreenName nvarchar(100),
	@rActivity nvarchar(500),
	@rFromDate date,
	@rToDate date,
	@rOSTypeId tinyint=0,
	@rIsHistory bit = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
SET @rScreenName = sCommon.fSearchStringGet(@rScreenName)
SET @rActivity = sCommon.fSearchStringGet(@rActivity)
SET @rToDate = DATEADD(day,1,@rToDate)

	IF(@rIsHistory = 1)
	BEGIN
       SELECT 
            AL.OrgGroupId,
            AL.OrgId,
            OM.Title AS OrganizationName,
            AL.UserId,
			U.DisplayTitle AS UserName,
			U.LoginTitle,
			U.SessionId,
			S.Title AS ScreenName,
			AL.AuditDate,
			(CASE WHEN AL.ScreenId=126
				  THEN AL.Activity		
			      WHEN AL.ScreenId=20878
				  THEN AL.Activity		
				  WHEN AL.ScreenId=30179
				  THEN AL.Activity
				  WHEN AL.ScreenId=20196
				  THEN AL.Activity
				  WHEN AL.ScreenId=30788
				  THEN AL.Activity
				  WHEN AL.ScreenId=30780
				  THEN AL.Activity
				  WHEN AL.ScreenId=30790
				  THEN AL.Activity
			 ELSE SUBSTRING(AL.Activity, CHARINDEX(' ', AL.Activity)+1, LEN(AL.Activity)-(CHARINDEX(' ', AL.Activity)-1))  END)AS  Activity,			
			ISNULL(AL.RecordSourceId,0) AS RecordSourceId,
			ISNULL(AL.RecordDetail,'') AS RecordDetail,
			ISNULL(OS.Title,'') AS OSType
			
       FROM 
		   sAudit.tActivityLogHistory AL
		   INNER JOIN sSecurity.tUser U ON U.Id = AL.UserId
		   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = AL.OrgId
		   INNER JOIN sSecurity.tScreen S ON S.Id = AL.ScreenId
		   LEFT JOIN sAlert.tOSType OS ON OS.Id = AL.OSTypeId
       WHERE
		   AL.OrgGroupId = @rOrgGroupId
		   AND ((AL.OrgId = @rOrgId) OR (@rOrgId=0))
		   AND ((U.DisplayTitle = @rUserName) OR (@rUserName = ''))
		   AND ((S.Title LIKE @rScreenName) OR (@rScreenName = ''))
		   AND ((AL.Activity LIKE @rActivity) OR (@rActivity = ''))
		   AND (AL.AuditDate >= @rFromDate)
		   AND (AL.AuditDate <= @rToDate)
		   AND ((AL.OSTypeId = @rOSTypeId) OR (@rOSTypeId=0))
       ORDER BY 
			AL.AuditDate DESC
	END
	ELSE
	BEGIN
		SELECT 
            AL.OrgGroupId,
            AL.OrgId,
            OM.Title AS OrganizationName,
            AL.UserId,
			U.DisplayTitle AS UserName,
			U.LoginTitle,
			U.SessionId,
			S.Title AS ScreenName,
			AL.AuditDate,
			(CASE WHEN AL.ScreenId=126
				  THEN AL.Activity		
			      WHEN AL.ScreenId=20878
				  THEN AL.Activity		
				  WHEN AL.ScreenId=30179
				  THEN AL.Activity
				  WHEN AL.ScreenId=20196
				  THEN AL.Activity
				  WHEN AL.ScreenId=30788
				  THEN AL.Activity
				  WHEN AL.ScreenId=30780
				  THEN AL.Activity
				  WHEN AL.ScreenId=30790
				  THEN AL.Activity
				  WHEN AL.ScreenId=20884
				  THEN AL.Activity
			 ELSE SUBSTRING(AL.Activity, CHARINDEX(' ', AL.Activity)+1, LEN(AL.Activity)-(CHARINDEX(' ', AL.Activity)-1))  END) AS  Activity,			
			ISNULL(AL.RecordSourceId,0) AS RecordSourceId,
			ISNULL(AL.RecordDetail,'') AS RecordDetail,
			ISNULL(OS.Title,'') AS OSType
			
       FROM 
		   sAudit.tActivityLog AL
		   INNER JOIN sSecurity.tUser U ON U.Id = AL.UserId
		   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = AL.OrgId
		   INNER JOIN sSecurity.tScreen S ON S.Id = AL.ScreenId
		   LEFT JOIN sAlert.tOSType OS ON OS.Id = AL.OSTypeId
       WHERE
		   AL.OrgGroupId = @rOrgGroupId
		   AND ((AL.OrgId = @rOrgId) OR (@rOrgId=0))
		   AND ((U.DisplayTitle = @rUserName) OR (@rUserName = ''))
		   AND ((S.Title LIKE @rScreenName) OR (@rScreenName = ''))
		   AND ((AL.Activity LIKE @rActivity) OR (@rActivity = ''))
		   AND (AL.AuditDate >= @rFromDate)
		   AND (AL.AuditDate <= @rToDate)
		   AND ((AL.OSTypeId = @rOSTypeId) OR (@rOSTypeId=0))
       ORDER BY 
			AL.AuditDate DESC
	END
END
GO
PRINT N'Altering [sBiometric].[pRptMonthlyLateInSummaryGet]...';


GO

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

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


		DROP Table #TempMonthTrans	

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


End
GO
PRINT N'Altering [sCommon].[pMasterDataAdd]...';


GO
ALTER  PROCEDURE [sCommon].[pMasterDataAdd]
	 
        
		@rTitle nvarchar(100)='',
		@rCode nvarchar(50)='',
		@rIsObsolete bit=0,
		@rCreatedUserId bigint,
		@rOrgGroupId smallint,
		@rOrgId int,
		@rTable_Name int=0,
		@rDependId int=0,
		@rNo int=0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY

	 DECLARE @lNextNumber BIGINT 
	 DECLARE @lReligionId INT 
			 
		IF(@rTable_Name=1)
		BEGIN
		
			If Exists(select Id from sFinanceCommon.tBankMaster where Title=@rTitle AND OrgGroupId=@rOrgGroupId)
				BEGIN
				select -103 as Result
				RETURN
	 		END 
	 		EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sFinanceCommon.tBankMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
			INSERT INTO sFinanceCommon.tBankMaster
			(
			
				Id,
				Code,
				Title,
				 IsObsolete,
				 OrgGroupId,
				CreatedUserId,
				UpdateduserId,
				CreatedDateTime,
				UpdatedDateTime 
			)
		VALUES
			(
				@lNextNumber,
				@rCode,
				@rTitle,
				 @rIsObsolete,
				 @rOrgGroupId,
				@rCreatedUserId,
				@rCreatedUserId,
				sCommon.fGetDate() ,
				sCommon.fGetDate() 
			)
			END
			
			IF(@rTable_Name=2)
		BEGIN
		
			If Exists(select Id from sCommon.tReligionMaster where Title=@rTitle AND OrgGroupId=@rOrgGroupId)
				BEGIN
				select -103 as Result
				RETURN
	 		END 
	 		EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sCommon.tReligionMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
			INSERT INTO sCommon.tReligionMaster
			(
			
				Id,
				Code,
				Title,
				 IsObsolete,
				 OrgGroupId,
				CreatedUserId,
				UpdateduserId,
				CreatedDateTime,
				UpdatedDateTime 
			)
		VALUES
			(
				@lNextNumber,
				@rCode,
				@rTitle,
				 @rIsObsolete,
				 @rOrgGroupId,
				@rCreatedUserId,
				@rCreatedUserId,
				sCommon.fGetDate() ,
				sCommon.fGetDate() 
			)
			END
			
			IF(@rTable_Name=3)
		BEGIN
		
			If Exists(select Id from sCommon.tOccupationMaster where Title=@rTitle AND OrgGroupId=@rOrgGroupId)
				BEGIN
				select -103 as Result
				RETURN
	 		END 
	 		EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sCommon.tOccupationMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
			INSERT INTO sCommon.tOccupationMaster
			(
			
				Id,
				Code,
				Title,
				 IsObsolete,
				 OrgGroupId,
				CreatedUserId,
				UpdateduserId,
				CreatedDateTime,
				UpdatedDateTime 
			)
		VALUES
			(
				@lNextNumber,
				@rCode,
				@rTitle,
				 @rIsObsolete,
				 @rOrgGroupId,
				@rCreatedUserId,
				@rCreatedUserId,
				sCommon.fGetDate() ,
				sCommon.fGetDate() 
			)
			END
			
			
			IF(@rTable_Name=4)
		BEGIN
		
			If Exists(select Id from sCommon.tMotherTongueMaster where Title=@rTitle AND OrgGroupId=@rOrgGroupId)
				BEGIN
				select -103 as Result
				RETURN
	 		END 
	 		EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sCommon.tMotherTongueMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
			INSERT INTO sCommon.tMotherTongueMaster
			(
			
				Id,
				Code,
				Title,
				 IsObsolete,
				 OrgGroupId,
				CreatedUserId,
				UpdateduserId,
				CreatedDateTime,
				UpdatedDateTime 
			)
		VALUES
			(
				@lNextNumber,
				@rCode,
				@rTitle,
				 @rIsObsolete,
				 @rOrgGroupId,
				@rCreatedUserId,
				@rCreatedUserId,
				sCommon.fGetDate() ,
				sCommon.fGetDate() 
			)
			END
			
		IF(@rTable_Name=5)
		BEGIN
		
			If Exists(select Id from sCommon.tPreviousSchoolMaster where Title=@rTitle AND OrgGroupId=@rOrgGroupId)
				BEGIN
				select -103 as Result
				RETURN
	 		END 
	 		EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sCommon.tPreviousSchoolMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
			INSERT INTO sCommon.tPreviousSchoolMaster
			(
			
				Id,
				Code,
				Title,
				 IsObsolete,
				 OrgGroupId,
				CreatedUserId,
				UpdateduserId,
				CreatedDateTime,
				UpdatedDateTime 
			)
		VALUES
			(
				@lNextNumber,
				@rCode,
				@rTitle,
				 @rIsObsolete,
				 @rOrgGroupId,
				@rCreatedUserId,
				@rCreatedUserId,
				sCommon.fGetDate() ,
				sCommon.fGetDate() 
			)
			END
			
			IF(@rTable_Name=6)
		BEGIN
		
			If Exists(select Id from sHrm.tQualificationMaster where Title=@rTitle AND OrgGroupId=@rOrgGroupId)
				BEGIN
				select -103 as Result
				RETURN
	 		END 
	 		EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sHrm.tQualificationMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
			INSERT INTO sHrm.tQualificationMaster
			(
			
				Id,
				Code,
				Title,
				 IsObsolete,
				 OrgGroupId,
				CreatedUserId,
				UpdateduserId,
				CreatedDateTime,
				UpdatedDateTime 
			)
		VALUES
			(
				@lNextNumber,
				@rCode,
				@rTitle,
				 @rIsObsolete,
				 @rOrgGroupId,
				@rCreatedUserId,
				@rCreatedUserId,
				sCommon.fGetDate() ,
				sCommon.fGetDate() 
			)
			END
			
				IF(@rTable_Name=7)
		BEGIN
		
			If Exists(select Id from sCommon.tCountryMaster where Title=@rTitle AND OrgGroupId=@rOrgGroupId)
				BEGIN
				select -103 as Result
				RETURN
	 		END 
	 		EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sCommon.tCountryMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
			INSERT INTO sCommon.tCountryMaster
			(
			
				Id,
				Title,
				Nationality,
			
				 IsObsolete,
				 OrgGroupId,
				CreatedUserId,
				UpdateduserId,
				CreatedDateTime,
				UpdatedDateTime ,
				IsShow
			)
		VALUES
			(
				@lNextNumber,
				
				@rTitle,
				@rCode,
				 @rIsObsolete,
				 @rOrgGroupId,
				@rCreatedUserId,
				@rCreatedUserId,
				sCommon.fGetDate() ,
				sCommon.fGetDate() ,
				1
			)
			END
			
				IF(@rTable_Name=8)
		BEGIN
			If Exists(select Id from sCommon.tStateMaster where Title=@rTitle AND CountryId=@rDependId AND OrgGroupId=@rOrgGroupId)
				BEGIN
				select -103 as Result
				RETURN
	 		END 
	 		EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sCommon.tStateMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
			INSERT INTO sCommon.tStateMaster
			(
			
				Id,
				Title,
				CountryId,
			
				 IsObsolete,
				 OrgGroupId,
				CreatedUserId,
				UpdateduserId,
				CreatedDateTime,
				UpdatedDateTime ,
				IsShow
			)
		VALUES
			(
				@lNextNumber,
				
				@rTitle,
				@rDependId,
				 @rIsObsolete,
				 @rOrgGroupId,
				@rCreatedUserId,
				@rCreatedUserId,
				sCommon.fGetDate() ,
				sCommon.fGetDate() ,
				1
			)
			END
			
			
				IF(@rTable_Name=9)
		BEGIN
				If Exists(select Id from sCommon.tCityMaster where Title=@rTitle AND StateId =@rDependId AND OrgGroupId=@rOrgGroupId)
				BEGIN
				select -103 as Result
				RETURN
	 		END 
	 		EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sCommon.tCityMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
			INSERT INTO sCommon.tCityMaster
			(
			
				Id,
				Title,
				StateId,
			
				 IsObsolete,
				 OrgGroupId,
				CreatedUserId,
				UpdateduserId,
				CreatedDateTime,
				UpdatedDateTime ,
				IsShow
			)
		VALUES
			(
				@lNextNumber,
				
				@rTitle,
				@rDependId,
				 @rIsObsolete,
				 @rOrgGroupId,
				@rCreatedUserId,
				@rCreatedUserId,
				sCommon.fGetDate() ,
				sCommon.fGetDate() ,
				1
			)
			END
			
				IF(@rTable_Name=10)
		BEGIN
				If Exists(select Id from sCommon.tHobbyMaster where Title=@rTitle AND OrgGroupId=@rOrgGroupId)
				BEGIN
				select -103 as Result
				RETURN
	 		END 
	 		EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sCommon.tHobbyMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
			INSERT INTO sCommon.tHobbyMaster
			(
			
				Id,
				Title,
				Code,
				 IsObsolete,
				 OrgGroupId,
				CreatedUserId,
				UpdateduserId,
				CreatedDateTime,
				UpdatedDateTime 
			 
			)
		VALUES
			(
				@lNextNumber,
				
				@rTitle,
				@rCode,
				 @rIsObsolete,
				 @rOrgGroupId,
				@rCreatedUserId,
				@rCreatedUserId,
				sCommon.fGetDate() ,
				sCommon.fGetDate() 
				 
			)
			END
			
		 IF(@rTable_Name=11)
		BEGIN
				If Exists(select Id from sCommon.tHostelMaster where Title=@rTitle AND OrgGroupId=@rOrgGroupId)
				BEGIN
				select -103 as Result
				RETURN
	 		END 
	 		EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sCommon.tHostelMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
			INSERT INTO sCommon.tHostelMaster
			(
			
				Id,
				Title,
				Code,
				 IsObsolete,
				 OrgGroupId,
				CreatedUserId,
				UpdateduserId,
				CreatedDateTime,
				UpdatedDateTime 
			 
			)
		VALUES
			(
				@lNextNumber,
				
				@rTitle,
				@rCode,
				 @rIsObsolete,
				 @rOrgGroupId,
				@rCreatedUserId,
				@rCreatedUserId,
				sCommon.fGetDate() ,
				sCommon.fGetDate() 
				 
			)
			END
		 
		 	
		 IF(@rTable_Name=12)
		BEGIN
				If Exists(select Id from sCommon.tAreaMaster where Title=@rTitle AND CityId =@rDependId AND OrgGroupId=@rOrgGroupId)
				BEGIN
				select -103 as Result
				RETURN
	 		END 
	 		EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sCommon.tAreaMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
			INSERT INTO sCommon.tAreaMaster
			(
			
				Id,
				Title,
				CityId,
				 IsObsolete,
				 OrgGroupId,
				CreatedUserId,
				UpdateduserId,
				CreatedDateTime,
				UpdatedDateTime,
				IsShow
			 
			)
		VALUES
			(
				@lNextNumber,
				
				@rTitle,
				@rDependId,
				 @rIsObsolete,
				 @rOrgGroupId,
				@rCreatedUserId,
				@rCreatedUserId,
				sCommon.fGetDate() ,
				sCommon.fGetDate() ,
				1
				
				 
			)
			END
		 
		  IF(@rTable_Name=13)
		BEGIN
				If Exists(select Id from sCommon.tFamiliyCastMaster where FamiliyCast=@rTitle AND CastCategoryId=@rDependId AND OrgGroupId=@rOrgGroupId)	--add CastCategoryId
				BEGIN
				select -103 as Result
				RETURN
	 		END 
	 		
	  
	 		EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sCommon.tFamiliyCastMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
			INSERT INTO sCommon.tFamiliyCastMaster
			(
			
				Id,
				FamiliyCast, 
				 FamiliySubCast, 
				 OrgGroupId,
				 IsObsolete,
				CreatedUserId,
				UpdateduserId,
				CreatedDateTime,
				UpdatedDateTime,
				CastCategoryId,		--added
				ReligionId			--added
			 
			 
			)
		VALUES
			(
				@lNextNumber,
				@rTitle, 
				@rCode,
				 @rOrgGroupId,
				 @rIsObsolete,
				@rCreatedUserId,
				@rCreatedUserId,
				sCommon.fGetDate() ,
				sCommon.fGetDate(),
				@rDependId,			--added
				-1					--added
				 
				
				 
			)
			END
			
			
			
			 IF(@rTable_Name=14)
		BEGIN
		If Exists(select Id from sSetup.tSubjectMaster where Code=@rCode AND OrgId=@rOrgId)			--add if condition
			BEGIN
			select -102 as Result
			RETURN
		END
				If Exists(select Id from sSetup.tSubjectMaster where Title=@rTitle   AND OrgId=@rOrgId)
				BEGIN
				select -103 as Result
				RETURN
				END
				If Exists(select Id from sSetup.tSubjectMaster where Number=@rNo and OrgId=@rOrgId)		--add if condition
			BEGIN
			select -104 as Result
			RETURN
	 		END 
	 		
	  
	 		EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sSetup.tSubjectMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
			INSERT INTO sSetup.tSubjectMaster
			(
			
				Id,
				Code, 
				 Number, 
				 Title,
				 IsObsolete,
				 OrgId,
				 OrderIndex,
				CreatedUserId,
				UpdateduserId,
				CreatedDateTime,
				UpdatedDateTime 
			 
			 
			)
		VALUES
			(
				@lNextNumber,
				@rCode,
				@rNo,
				@rTitle, 
				 @rIsObsolete,
				 @rOrgId,
				 @rNo,
				@rCreatedUserId,
				@rCreatedUserId,
				sCommon.fGetDate() ,
				sCommon.fGetDate()  
				 
				
				 
			)
			END
			
			
			SELECT 1 AS Result
			
			
		 
 
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sCommunication].[pAssignTaskSearchGet]...';


GO

ALTER PROCEDURE [sCommunication].[pAssignTaskSearchGet]

	 @rId bigint,
	 @rOrgId int,
	 @rFromStartDate DateTime,
	 @rToStartDate DateTime,
	 @rFromDueDate DateTime,
	 @rToDueDate DateTime,
	 @rSourceTypeId int,
	 @rIsComplete bit,
	 @rIsClosed bit,
	 @rCreatedUserId bigint,
	 @rCode nvarchar(max)

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
IF(@rSourceTypeId = 95)
	BEGIN
	
		SELECT 
				DISTINCT AT.Id,
				AT.AssignedToSourceTypeId,
				AT.AssignedToSourceId,
				EM.Code AS SourceCode,
				EM.EmployeeName AS SourceName,
				CONVERT(varchar,AT.AssignedDate ,105) AS AssignedDate,
				CONVERT(varchar,AT.DueDate ,105) AS DueDate,
				AT.Remark,
				AT.IsCompleted,
				AT.IsClosed,
				OM.DisplayTitle AS Organization,
				ISNULL(CASE WHEN U.SourceTypeId = 2003 THEN (SELECT Name FROM sStudent.vStudentName WHERE StudentId = U.SourceId)
				ELSE (SELECT ShortName FROM sHrm.vExtEmployeeMaster WHERE EmployeeId = U.SourceId) END,'') AS AssignedBy,
				ISNULL(AT.DueReasonRemark,'') AS DueReasonRemark
				--ISNULL((SELECT ShortName FROM sHrm.vExtEmployeeMaster WHERE EmployeeId = U.SourceId),'') AS AssignedBy
		FROM 
				sCommunication.tAssignTask AT
				INNER JOIN sHrm.vExtEmployeeMaster EM ON EM.Id=AT.AssignedToSourceId AND AT.AssignedToSourceTypeId=95
				INNER JOIN sSecurity.tUser U ON U.Id=AT.CreatedUserId
				INNER JOIN sSetup.tOrganizationMaster OM ON AT.OrgId=OM.Id
		WHERE 
				((AT.Id=@rId) OR (ISNULL(@rId,0) = 0))
			AND ((AT.AssignedDate >= @rFromStartDate) OR (ISNULL(@rFromStartDate,0) = 0))
			AND ((AT.AssignedDate <= @rToStartDate) OR (ISNULL(@rToStartDate,0) = 0)) 
			AND ((AT.DueDate >= @rFromDueDate) OR (ISNULL(@rFromDueDate,0) = 0))
			AND ((AT.DueDate <= @rToDueDate) OR (ISNULL(@rToDueDate,0) = 0))
			AND ((AT.CreatedUserId = @rCreatedUserId) OR (@rCreatedUserId=0))
			AND ((AT.IsCompleted= @rIsComplete))
			AND (AT.IsClosed= @rIsClosed)
			AND (AT.OrgId=@rOrgId OR @rOrgId = 0)
			AND AT.IsDeleted=0
			AND ((EM.Code =@rCode) OR ISNULL(@rCode,'')='')
	END			
ELSE
	BEGIN
	print 'Yes'
		SELECT 
				DISTINCT AT.Id,
				AT.AssignedToSourceTypeId,
				AT.AssignedToSourceId,
				SN.Code AS SourceCode,
				SN.Name AS SourceName,
				CONVERT(varchar,AT.AssignedDate,105) AS AssignedDate,
				CONVERT(varchar,AT.DueDate,105) AS DueDate,
				AT.Remark,
				AT.IsCompleted,
				AT.IsClosed,
				OM.DisplayTitle AS Organization,
				ISNULL(CASE WHEN U.SourceTypeId = 2003 THEN (SELECT [sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) FROM sStudent.tStudentMaster SM 
				 INNER JOIN sSetup.tOrganizationMaster OM ON SM.OrgId = OM.Id WHERE SM.Id = U.SourceId)
				 ELSE (SELECT ShortName FROM sHrm.vExtEmployeeMaster WHERE EmployeeId = U.SourceId) END,'') AS AssignedBy
		FROM 
				sCommunication.tAssignTask AT
				INNER JOIN sStudent.vStudentName SN ON SN.StudentId=AT.AssignedToSourceId AND AT.AssignedToSourceTypeId=2003
				INNER JOIN sSecurity.tUser U ON U.Id=AT.CreatedUserId
				INNER JOIN sSetup.tOrganizationMaster OM ON AT.OrgId=OM.Id
		WHERE 
				((AT.Id=@rId) OR (ISNULL(@rId,0) = 0))
				AND ((AT.AssignedDate >= @rFromStartDate) OR (ISNULL(@rFromStartDate,0) = 0))
				AND ((AT.AssignedDate <= @rToStartDate) OR (ISNULL(@rToStartDate,0) = 0)) 
				AND ((AT.DueDate >= @rFromDueDate) OR (ISNULL(@rFromDueDate,0) = 0))
				AND ((AT.DueDate <= @rToDueDate) OR (ISNULL(@rToDueDate,0) = 0))
				AND ((AT.CreatedUserId = @rCreatedUserId) OR (@rCreatedUserId=0))
				AND ((AT.IsCompleted= @rIsComplete))
				AND (AT.IsClosed= @rIsClosed)
				AND (AT.OrgId=@rOrgId OR @rOrgId = 0)
				AND AT.IsDeleted=0
				AND ((SN.Code =@rCode) OR ISNULL(@rCode,'')='') 
	END
END
GO
PRINT N'Altering [sCommunication].[pAssignTaskToMeGet]...';


GO
ALTER PROCEDURE [sCommunication].[pAssignTaskToMeGet]
	 
	 @rOrgId int,
	 @rUserSourceId bigint,
	 @rUserSourceTypeId smallint,
	 @rSyncedDateTime datetime
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 

IF(@rUserSourceTypeId=95)
BEGIN

	SELECT 
		AT.Id,
		AT.AssignedDate,
		AT.DueDate,
		AT.Remark,
		AT.IsCompleted,
		AT.IsClosed,
		AT.IsDeleted,
		(CASE 
		WHEN U.SourceTypeId=95 
		THEN (SELECT Id FROM sHrm.tEmployeeMaster WHERE Id=U.SourceId AND ISNULL(IsOtherUser,0) = 0 )
		WHEN U.SourceTypeId=2003
		THEN (SELECT Id FROM sStudent.tStudentMaster WHERE Id=U.SourceId)
		END)AS AssignedBySourceId,
		(CASE 
		WHEN U.SourceTypeId=95 
		THEN 95
		WHEN U.SourceTypeId=2003
		THEN 2003
		END)AS AssignedBySourceTypeId,
		(CASE 
		WHEN U.SourceTypeId=95 
		THEN (SELECT FirstName +' '+LastName FROM sHrm.tEmployeeMaster WHERE Id=U.SourceId AND ISNULL(IsOtherUser,0) = 0)
		WHEN U.SourceTypeId=2003
		THEN (SELECT FirstName +' '+LastName FROM sStudent.tStudentMaster WHERE Id=U.SourceId)
		END)AS AssignedByName,
		(CASE 
		WHEN U.SourceTypeId=95 
		THEN (SELECT Code FROM sHrm.tEmployeeMaster WHERE Id=U.SourceId AND ISNULL(IsOtherUser,0) = 0)
		WHEN U.SourceTypeId=2003
		THEN (SELECT Code FROM sStudent.tStudentMaster WHERE Id=U.SourceId)
		END)AS AssignedByCode,
		AT.DueReasonRemark  
						
	FROM 
		sCommunication.tAssignTask AT
		INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id=AT.AssignedToSourceId AND AT.AssignedToSourceTypeId=95
		INNER JOIN sSecurity.tUser U ON AT.CreatedUserId=U.Id
		
	WHERE 
		AT.AssignedToSourceId=@rUserSourceId
		AND (AT.OrgId=@rOrgId OR @rOrgId=0)
		AND (AT.UpdatedDateTime > @rSyncedDateTime OR @rSyncedDateTime IS NULL)
		AND ISNULL(EM.IsOtherUser,0) = 0 
	ORDER BY AT.DueDate
END
ELSE
BEGIN
	
	SELECT 
		AT.Id,
		AT.AssignedDate,
		AT.DueDate,
		AT.Remark,
		AT.IsCompleted,
		AT.IsClosed,
		AT.IsDeleted,
		(CASE 
		WHEN U.SourceTypeId=95 
		THEN (SELECT Id FROM sHrm.tEmployeeMaster WHERE Id=U.SourceId AND ISNULL(IsOtherUser,0) = 0)
		WHEN U.SourceTypeId=2003
		THEN (SELECT Id FROM sStudent.tStudentMaster WHERE Id=U.SourceId)
		END)AS AssignedBySourceId,
		(CASE 
		WHEN U.SourceTypeId=95 
		THEN 95
		WHEN U.SourceTypeId=2003
		THEN 2003
		END)AS AssignedBySourceTypeId,
		(CASE 
		WHEN U.SourceTypeId=95 
		THEN (SELECT FirstName +' '+LastName FROM sHrm.tEmployeeMaster WHERE Id=U.SourceId AND ISNULL(IsOtherUser,0) = 0)
		WHEN U.SourceTypeId=2003
		THEN (SELECT FirstName +' '+LastName FROM sStudent.tStudentMaster WHERE Id=U.SourceId)
		END)AS AssignedByName,
		(CASE 
		WHEN U.SourceTypeId=95 
		THEN (SELECT Code FROM sHrm.tEmployeeMaster WHERE Id=U.SourceId AND ISNULL(IsOtherUser,0) = 0)
		WHEN U.SourceTypeId=2003
		THEN (SELECT Code FROM sStudent.tStudentMaster WHERE Id=U.SourceId)
		END)AS AssignedByCode,
		'' as DueReasonRemark --DueReasonRemark need only in Employee Side
					
	FROM 
		sCommunication.tAssignTask AT
		INNER JOIN sStudent.tStudentMaster SM ON SM.Id=AT.AssignedToSourceId AND AT.AssignedToSourceTypeId=2003
		INNER JOIN sSecurity.tUser U ON AT.CreatedUserId=U.Id
		
	WHERE 
		AT.AssignedToSourceId=@rUserSourceId
		AND (AT.OrgId=@rOrgId OR @rOrgId=0)
		AND (AT.UpdatedDateTime > @rSyncedDateTime OR @rSyncedDateTime IS NULL)
	ORDER BY AT.DueDate
END

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


GO
 
ALTER PROCEDURE [sCommunication].[pQueryAdd]
	 
	@rOrgGroupId smallint,
	@rOrgGroupBatchId int,
	@rQueryCategoryId int,
	@rId AS bigint,
	@rTitle nvarchar(100),
	@rRemark nvarchar(1000),
	@rIsUserView bit,
	@rIsAssigneeView bit,
	@rStatusId smallint,
	@rCreatedUserId bigint,
	@rCreatedDateTime datetime,
	@rSubjectId int=0,
	@rAssignedToEmployeeId bigint=0,
	@rAssignedToRemark nvarchar(500)='',
	@rIsOfflineEntry bit=0,
	@rFromSourceTypeId smallInt=0,
	@rFromSourceId bigint=0,
	@rTargetResolutionDate datetime=null    
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	BEGIN TRANSACTION
		IF(@rId = 0)
BEGIN
DECLARE @lNextNumber BIGINT     
	
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sCommunication.tQuery', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	DECLARE @lNumber int=0
	SELECT @lNumber=ISNULL(MAX(Number),0)+1 FROM sCommunication.tQuery WHERE OrgGroupBatchId = @rOrgGroupBatchId
	
	
	INSERT INTO sCommunication.tQuery
		(
			OrgGroupId,
			OrgGroupBatchId,
			QueryCategoryId,
			Id,
			Title,
			Number,
			Remark,
			IsUserView,
			IsAssigneeView,
			StatusId,
			CreatedUserId,
			CreatedDateTime,
			SubjectId,
			AssignedToEmployeeId,
			AssignedToRemark,
			IsOfflineEntry,
			FromSourceTypeId,
			FromSourceId,
			TargetResolutionDate
		)
	VALUES
		(
			@rOrgGroupId,
			@rOrgGroupBatchId,
			@rQueryCategoryId,
			@lNextNumber,
			@rTitle,
			@lNumber,
			@rRemark,
			@rIsUserView,
			@rIsAssigneeView,
			@rStatusId,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rSubjectId,
			@rAssignedToEmployeeId,
			@rAssignedToRemark,
			@rIsOfflineEntry,
			@rFromSourceTypeId,
			@rFromSourceId,
			@rTargetResolutionDate
		)
		select @lNextNumber,1 as result
		--select @lNextNumber,@lNextNumber as result
END
ELSE
BEGIN
		UPDATE sCommunication.tQuery 
		SET IsUserView = @rIsUserView,
		IsAssigneeView=@rIsAssigneeView,
		AssignedToEmployeeId=@rAssignedToEmployeeId,
		AssignedToRemark=@rAssignedToRemark,
		IsOfflineEntry=@rIsOfflineEntry,
		FromSourceTypeId=@rFromSourceTypeId,
		FromSourceId=@rFromSourceId,
		TargetResolutionDate=@rTargetResolutionDate,
		Remark=@rRemark
		
		 WHERE Id = @rId
		select 0,11 as result
END
	
	COMMIT TRANSACTION
	
END TRY

	BEGIN CATCH
	    ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH  
END
GO
PRINT N'Altering [sCommunication].[pQueryCategoryDropdownGet]...';


GO
ALTER PROCEDURE [sCommunication].[pQueryCategoryDropdownGet]
	@rOrgGroupBatchId int,
	@rUserSourceId bigint,
	@rUserSourceTypeId int
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	DECLARE @lAcademicId bigint,@lStudentId bigint,@lClassId int,@lDivisionId int,@lOrgId int,@lDepartmentId int,@lEmployeeId bigint

	IF @rUserSourceTypeId = 95 -- For Employee Login
	BEGIN
		SELECT 
			@lDepartmentId=EJD.OrganizationDepartmentId,
			@lOrgId = EM.OrgId,
			@lEmployeeId = EM.Id 
		FROM 
			sHrm.tEmployeeMaster EM INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id 
		WHERE 
			EM.Id=@rUserSourceId
		
		SELECT Distinct	
			QCM.Id,
			QCM.Title
		FROM 
			sCommunication.tQueryCategoryMaster QCM           
			INNER JOIN 
			(SELECT QCS.QueryCategoryId FROM sCommunication.tQueryCategoryScope QCS
				WHERE (((QCS.SourceTypeId = 2021 AND QCS.SourceId =@lOrgId) OR
				(QCS.SourceTypeId = 2017 AND QCS.SourceId =@lDepartmentId) OR
				(QCS.SourceTypeId = 95 AND QCS.SourceId =@lEmployeeId )) 
				AND ((QCS.AssigneeToId=3) OR (QCS.AssigneeToId IS NULL) OR (ISNULL(QCS.AssigneeToId,0)=0)))) D
				ON D.QueryCategoryId= QCM.Id
			--INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=QCM.OrgGroupBatchId AND OGBM.Id=@rOrgGroupBatchId
			--INNER JOIN sSecurity.tUser U ON U.Id=QCM.CreatedUserId
		WHERE 
			QCM.AssignedToId IN (1,3) 
			AND QCM.IsObsolete = 0

		--UNION

		--SELECT Distinct	
		--	QCM.Id,
		--	QCM.Title
		--FROM 
		--	sCommunication.tQueryCategoryMaster QCM           
		--	INNER JOIN sCommunication.tQueryCategoryAssignedTo QCA ON QCM.Id = QCA.QueryCategoryId
		--	AND QCA.SourceTypeId = 95 AND QCA.SourceId =@lEmployeeId
	
		--WHERE 
		--	QCM.AssignedToId IN (1,3) 
		--	AND QCM.IsObsolete = 0

	END
	ELSE IF @rUserSourceTypeId = 2003 -- For Student Login
	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 
			INNER JOIN sSetup.tClassMaster CM ON CM.Id = A.ClassId
		WHERE StudentId = @rUserSourceId AND BM.OrgGroupBatchId = @rOrgGroupBatchId
  
		SELECT 	Distinct
			QCM.Id,
			QCM.Title
		FROM 
			sCommunication.tQueryCategoryMaster QCM
			INNER JOIN (SELECT QCS.QueryCategoryId 
				FROM sCommunication.tQueryCategoryScope QCS
				WHERE (((QCS.SourceTypeId = 2021 AND QCS.SourceId =@lOrgId) OR
				(QCS.SourceTypeId = 2017 AND QCS.SourceId =@lDepartmentId) OR
				(QCS.SourceTypeId = 2016 AND QCS.SourceId =@lClassId) OR
				(QCS.SourceTypeId = 2005 AND QCS.SourceId =@lDivisionId) OR
				(QCS.SourceTypeId = 2003 AND QCS.SourceId =@lStudentId) OR
				(QCS.SourceTypeId = 2001 AND QCS.SourceId =@lAcademicId) )
				)AND ((QCS.AssigneeToId=2) OR (QCS.AssigneeToId IS NULL) OR (ISNULL(QCS.AssigneeToId,0)=0))) D ON D.QueryCategoryId= QCM.Id 
		WHERE
			QCM.AssignedToId IN (1,2) 
			AND QCM.IsObsolete = 0
	END
	ELSE
	--For Other Users
	BEGIN
		SELECT 	
			QCM.Id,
			QCM.Title
		FROM 
			sCommunication.tQueryCategoryMaster QCM
		WHERE 
			QCM.AssignedToId IN (1,2,3)
			AND QCM.IsObsolete = 0
	END
END
GO
PRINT N'Altering [sCommunication].[pTempCircularScopeValidate]...';


GO
ALTER PROCEDURE [sCommunication].[pTempCircularScopeValidate]
	 
        @rTempCircularId nvarchar(100),
		@rSourceTypeId smallint,
		@rSourceId bigint,
		@rAssigneeToId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
					/* Source Type Value
					   2021 - Organization
					   2017 - Department
					   2016 - Class
					   2005 - Division
					   2003 - Student */


		If EXISTS(select 1 from sCommunication.tTempCircularScope CS where CS.SourceId=@rSourceId AND
					CS.SourceTypeId=@rSourceTypeId AND CS.TempCircularId=@rTempCircularId AND AssigneeToId=@rAssigneeToId) 
			BEGIN
				select -101 as Result,'Item Already Exists' AS Msg
				RETURN
			END 

	
	IF(@rSourceTypeId = 2021) -- Organization	
		BEGIN
			If EXISTS(select 1 from  sCommunication.tTempCircularScope CS
			 INNER JOIN  sSetup.tDepartmentMaster DM 
				ON CS.SourceId=DM.Id AND CS.SourceTypeId= 2017
				where DM.OrgId=@rSourceId  AND CS.TempCircularId=@rTempCircularId AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -103 as Result,'Department already Exists' AS Msg
						RETURN
					END 
			If EXISTS(select 1 from  sCommunication.tTempCircularScope CS 
			 INNER JOIN  sSetup.tClassMaster CM 
				ON CS.SourceId=CM.Id AND CS.SourceTypeId= 2016
				where CM.OrgId=@rSourceId  AND CS.TempCircularId=@rTempCircularId AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -103 as Result,'Class already Exists' AS Msg
						RETURN
					END 
					
			If EXISTS(select 1 from  sCommunication.tTempCircularScope CS 
			 INNER JOIN  sSetup.tDivisionMaster DM 
				ON CS.SourceId=DM.Id AND CS.SourceTypeId= 2005
				where DM.OrgId=@rSourceId  AND CS.TempCircularId=@rTempCircularId AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -103 as Result,'Division already Exists' AS Msg
						RETURN
					END 
					
			If EXISTS(select 1 from  sCommunication.tTempCircularScope CS 
			 INNER JOIN  sStudent.tStudentMaster SM
				ON CS.SourceId=SM.Id AND CS.SourceTypeId= 2003
				where SM.OrgId=@rSourceId  AND CS.TempCircularId=@rTempCircularId AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -103 as Result,'Student already Exists' AS Msg
						RETURN
					END 		

			If EXISTS(select 1 from  sCommunication.tTempCircularScope CS 
			 INNER JOIN  sHrm.tEmployeeMaster EM
				ON CS.SourceId=EM.Id AND CS.SourceTypeId= 95
				where EM.OrgId=@rSourceId  AND CS.TempCircularId=@rTempCircularId AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -103 as Result,'Employee already Exists' AS Msg
						RETURN
					END 	
	    END
	
	IF(@rSourceTypeId = 2017) -- Department	
		BEGIN
			If EXISTS(select 1 from  sCommunication.tTempCircularScope CS
			 INNER JOIN  sSetup.tDepartmentMaster DM
				ON CS.SourceId=DM.OrgId AND CS.SourceTypeId= 2021
				where DM.Id=@rSourceId  AND CS.TempCircularId=@rTempCircularId AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -102 as Result,'Organization already Exists' AS Msg
						RETURN
					END 
			If EXISTS(select 1 from  sCommunication.tTempCircularScope CS
			 INNER JOIN sSetup.tClassMaster CM
				ON CS.SourceId=CM.Id AND CS.SourceTypeId= 2016
				where CM.DepartmentId=@rSourceId  AND CS.TempCircularId=@rTempCircularId  AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -103 as Result,'Class already Exists' AS Msg
						RETURN
					END 
					
			If EXISTS(select 1 from  sCommunication.tTempCircularScope CS 
			 INNER JOIN  sSetup.tDivisionMaster DM 
				ON CS.SourceId=DM.Id AND CS.SourceTypeId= 2005
			 INNER JOIN sSetup.tClassMaster CM
				ON CM.Id=DM.ClassId
				where CM.DepartmentId=@rSourceId  AND CS.TempCircularId=@rTempCircularId  AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -103 as Result,'Division already Exists' AS Msg
						RETURN
					END 
					
			If EXISTS(select 1 from  sCommunication.tTempCircularScope CS 
			 INNER JOIN sStudent.tAcademic SA 
				ON CS.SourceId=SA.StudentId AND CS.SourceTypeId=2003
			 INNER JOIN sSetup.tClassMaster CM
				ON CM.Id=SA.ClassId
   			 INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
				where CM.DepartmentId=@rSourceId  AND CS.TempCircularId=@rTempCircularId  AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -103 as Result,'Student already Exists' AS Msg
						RETURN
					END 	
			
			If EXISTS(select 1 from sCommunication.tTempCircularScope CS 
			 INNER JOIN sHrm.tEmployeeMaster  EM ON EM.Id =CS.SourceID AND CS.SourceTypeId= 95
			 INNER JOIN  sHrm.tEmployeeJobDetail EJD ON EM.Id=EJD.EmployeeId 			
			 where  EJD.OrganizationDepartmentId=@rSourceId  AND CS.TempCircularId=@rTempCircularId AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -103 as Result,'Employee already Exists' AS Msg
					RETURN
				END 
		
	    END
	    
    IF(@rSourceTypeId = 2016) -- Class	
	BEGIN
		If EXISTS(select 1 from  sCommunication.tTempCircularScope CS 
		 INNER JOIN  sSetup.tClassMaster CM
			ON CS.SourceId=CM.OrgId AND CS.SourceTypeId= 2021
			where CM.Id=@rSourceId  AND CS.TempCircularId=@rTempCircularId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Organization already Exists' AS Msg
					RETURN
				END 
		If EXISTS(select 1 from  sCommunication.tTempCircularScope CS 
		 INNER JOIN  sSetup.tClassMaster CM
			ON CS.SourceId=CM.DepartmentId AND CS.SourceTypeId= 2017
			where CM.Id=@rSourceId  AND CS.TempCircularId=@rTempCircularId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Department already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from  sCommunication.tTempCircularScope CS
		 INNER JOIN  sSetup.tDivisionMaster DM 
			ON CS.SourceId=DM.Id AND CS.SourceTypeId= 2005
			where DM.ClassId=@rSourceId  AND CS.TempCircularId=@rTempCircularId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -103 as Result,'Division already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from sCommunication.tTempCircularScope CS 
		  INNER JOIN sStudent.tAcademic SA 
				ON CS.SourceId=SA.StudentId AND CS.SourceTypeId=2003
		  INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.ClassId=@rSourceId  AND CS.TempCircularId=@rTempCircularId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -103 as Result,'Student already Exists' AS Msg
					RETURN
				END 			
    END
    
    IF(@rSourceTypeId = 2005) -- Division	
	BEGIN
		If EXISTS(select 1 from  sCommunication.tTempCircularScope CS
		 INNER JOIN  sSetup.tDivisionMaster DM 
			ON CS.SourceId=DM.OrgId AND CS.SourceTypeId= 2021
			where DM.Id=@rSourceId  AND CS.TempCircularId=@rTempCircularId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Organization already Exists' AS Msg
					RETURN
				END 
		If EXISTS(select 1 from  sCommunication.tTempCircularScope CS
		 INNER JOIN sSetup.tClassMaster CM 
			ON CS.SourceId=CM.DepartmentId AND CS.SourceTypeId= 2017
		 INNER JOIN  sSetup.tDivisionMaster DM 
			ON DM.ClassId=CM.Id
			where DM.Id=@rSourceId  AND CS.TempCircularId=@rTempCircularId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Department already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from  sCommunication.tTempCircularScope CS 
		 INNER JOIN  sSetup.tDivisionMaster DM 
			ON CS.SourceId=DM.ClassId AND CS.SourceTypeId= 2016
			where DM.Id=@rSourceId  AND CS.TempCircularId=@rTempCircularId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Class already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from sCommunication.tTempCircularScope CS 
		  INNER JOIN sStudent.tAcademic SA 
				ON CS.SourceId=SA.StudentId AND CS.SourceTypeId=2003
		  INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.DivisionId=@rSourceId  AND CS.TempCircularId=@rTempCircularId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -103 as Result,'Student already Exists' AS Msg
					RETURN
				END 
				
			If EXISTS(select 1 from sCommunication.tTempCircularScope CS 
		  INNER JOIN sStudent.tAcademic SA 
				ON CS.SourceId=SA.DivisionId AND CS.SourceTypeId=2005
		  INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.DivisionId=@rSourceId  AND CS.TempCircularId=@rTempCircularId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -103 as Result,'Student already Exists' AS Msg
					RETURN
				END 
								
    END
    
    IF(@rSourceTypeId = 2003) -- Student	
	BEGIN
		If EXISTS(select 1 from  sCommunication.tTempCircularScope CS 
		 INNER JOIN  sStudent.tStudentMaster SM 
			ON CS.SourceId=SM.OrgId AND CS.SourceTypeId= 2021
			where SM.Id=@rSourceId  AND CS.TempCircularId=@rTempCircularId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Organization already Exists' AS Msg
					RETURN
				END 
		If EXISTS(select 1 from sCommunication.tTempCircularScope CS 
		 INNER JOIN  sSetup.tClassMaster CM 
			ON CS.SourceId=CM.DepartmentId AND CS.SourceTypeId= 2017
		 INNER JOIN sStudent.tAcademic SA 
				ON CM.Id=SA.ClassId 
		 INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.StudentId=@rSourceId  AND CS.TempCircularId=@rTempCircularId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Department already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from  sCommunication.tTempCircularScope CS 
		 INNER JOIN sStudent.tAcademic SA 
				ON CS.SourceId=SA.ClassId AND CS.SourceTypeId= 2016
		 INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.StudentId=@rSourceId  AND CS.TempCircularId=@rTempCircularId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Class already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from  sCommunication.tTempCircularScope CS
		 INNER JOIN sStudent.tAcademic SA 
				ON CS.SourceId=SA.DivisionId AND CS.SourceTypeId= 2005
		 INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.StudentId=@rSourceId  AND CS.TempCircularId=@rTempCircularId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Division already Exists' AS Msg
					RETURN
				END 			
    END
    
    IF(@rSourceTypeId = 95) -- Employee	
	BEGIN
	
	
		If EXISTS(select 1 from  sCommunication.tTempCircularScope CS 
		 INNER JOIN  sHrm.tEmployeeMaster EM 
			ON CS.SourceId=EM.OrgId AND CS.SourceTypeId= 2021
			where EM.Id=@rSourceId AND  ISNULL(EM.IsOtherUser,0) = 0  AND CS.TempCircularId=@rTempCircularId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Organization already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from sCommunication.tTempCircularScope CS 
		 INNER JOIN  sHrm.tEmployeeJobDetail EJD
			ON CS.SourceId=EJD.OrganizationDepartmentId AND CS.SourceTypeId= 2017
			where  EJD.EmployeeId=@rSourceId  AND CS.TempCircularId=@rTempCircularId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Department already Exists' AS Msg
					RETURN
				END 
						
		
		 
	 
    END
    IF(@rSourceTypeId = 2001) -- Academic	
	BEGIN
		If EXISTS(select 1 from  sCommunication.tTempCircularScope CS
		 INNER JOIN sStudent.tAcademic SA 
				ON CS.SourceId=SA.DivisionId AND CS.SourceTypeId= 2005
		 INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.Id=@rSourceId  AND CS.TempCircularId=@rTempCircularId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Division already Exists' AS Msg
					RETURN
				END 		
	END
			select 1 as Result,'' AS Msg
	
END
GO
PRINT N'Altering [sCommunication].[pTempMultiPhotoCategoryScopeValidate]...';


GO
ALTER PROCEDURE [sCommunication].[pTempMultiPhotoCategoryScopeValidate]
	 
        @rTempPhotoCategoryId nvarchar(100),
		@rSourceTypeId smallint,
		@rSourceId bigint,
		@rAssigneeToId int,
		@rPhotoCategoryId int=0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
					/* Source Type Value
					   2021 - Organization
					   2017 - Department
					   2016 - Class
					   2005 - Division
					   2003 - Student */


		If EXISTS(select 1 from [sCommunication].[tTempMultiPhotoCategoryScope] CS where CS.SourceId=@rSourceId AND
					CS.SourceTypeId=@rSourceTypeId AND CS.TempMultiPhotoCategoryId=@rTempPhotoCategoryId AND AssigneeToId=@rAssigneeToId) 
			BEGIN
				select -101 as Result,'Item Already Exists' AS Msg
				RETURN
			END 
		IF(@rPhotoCategoryId > 0)
		BEGIN
			If EXISTS(select 1 from sCommunication.tMultiPhotoCategoryScope CS where CS.ScopeSourceId=@rSourceId AND
				CS.ScopeSourceTypeId=@rSourceTypeId AND CS.MultiPhotoCategoryId=@rPhotoCategoryId AND AssigneeToId=@rAssigneeToId) 
			BEGIN
				select -101 as Result,'Item Already Exists' AS Msg
				RETURN
			END 
		END
	
	IF(@rSourceTypeId = 2021) -- Organization	
		BEGIN
			If EXISTS(select 1 from  [sCommunication].[tTempMultiPhotoCategoryScope] CS
			 INNER JOIN  sSetup.tDepartmentMaster DM 
				ON CS.SourceId=DM.Id AND CS.SourceTypeId= 2017
				where DM.OrgId=@rSourceId  AND CS.TempMultiPhotoCategoryId=@rTempPhotoCategoryId AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -103 as Result,'Department already Exists' AS Msg
						RETURN
					END 
			If EXISTS(select 1 from  [sCommunication].[tTempMultiPhotoCategoryScope] CS 
			 INNER JOIN  sSetup.tClassMaster CM 
				ON CS.SourceId=CM.Id AND CS.SourceTypeId= 2016
				where CM.OrgId=@rSourceId  AND CS.TempMultiPhotoCategoryId=@rTempPhotoCategoryId AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -103 as Result,'Class already Exists' AS Msg
						RETURN
					END 
					
			If EXISTS(select 1 from  [sCommunication].[tTempMultiPhotoCategoryScope] CS 
			 INNER JOIN  sSetup.tDivisionMaster DM 
				ON CS.SourceId=DM.Id AND CS.SourceTypeId= 2005
				where DM.OrgId=@rSourceId  AND CS.TempMultiPhotoCategoryId=@rTempPhotoCategoryId AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -103 as Result,'Division already Exists' AS Msg
						RETURN
					END 
					
			If EXISTS(select 1 from  [sCommunication].[tTempMultiPhotoCategoryScope] CS 
			 INNER JOIN  sStudent.tStudentMaster SM
				ON CS.SourceId=SM.Id AND CS.SourceTypeId= 2003
				where SM.OrgId=@rSourceId  AND CS.TempMultiPhotoCategoryId=@rTempPhotoCategoryId AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -103 as Result,'Student already Exists' AS Msg
						RETURN
					END 
					
			If EXISTS(select 1 from  sCommunication.tTempMultiPhotoCategoryScope CS 
			 INNER JOIN  sHrm.tEmployeeMaster EM
				ON CS.SourceId=EM.Id AND CS.SourceTypeId= 95
				where EM.OrgId=@rSourceId  AND CS.TempMultiPhotoCategoryId=@rTempPhotoCategoryId AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -103 as Result,'Employee already Exists' AS Msg
						RETURN
					END 		
	    END
	
	IF(@rSourceTypeId = 2017) -- Department	
		BEGIN
			If EXISTS(select 1 from  [sCommunication].[tTempMultiPhotoCategoryScope] CS
			 INNER JOIN  sSetup.tDepartmentMaster DM
				ON CS.SourceId=DM.OrgId AND CS.SourceTypeId= 2021
				where DM.Id=@rSourceId  AND CS.TempMultiPhotoCategoryId=@rTempPhotoCategoryId AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -102 as Result,'Organization already Exists' AS Msg
						RETURN
					END 
			If EXISTS(select 1 from  [sCommunication].[tTempMultiPhotoCategoryScope] CS
			 INNER JOIN sSetup.tClassMaster CM
				ON CS.SourceId=CM.Id AND CS.SourceTypeId= 2016
				where CM.DepartmentId=@rSourceId  AND CS.TempMultiPhotoCategoryId=@rTempPhotoCategoryId  AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -103 as Result,'Class already Exists' AS Msg
						RETURN
					END 
					
			If EXISTS(select 1 from  [sCommunication].[tTempMultiPhotoCategoryScope] CS 
			 INNER JOIN  sSetup.tDivisionMaster DM 
				ON CS.SourceId=DM.Id AND CS.SourceTypeId= 2005
			 INNER JOIN sSetup.tClassMaster CM
				ON CM.Id=DM.ClassId
				where CM.DepartmentId=@rSourceId  AND CS.TempMultiPhotoCategoryId=@rTempPhotoCategoryId  AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -103 as Result,'Division already Exists' AS Msg
						RETURN
					END 
					
			If EXISTS(select 1 from  [sCommunication].[tTempMultiPhotoCategoryScope] CS 
			 INNER JOIN sStudent.tAcademic SA 
				ON CS.SourceId=SA.StudentId AND CS.SourceTypeId=2003
			 INNER JOIN sSetup.tClassMaster CM
				ON CM.Id=SA.ClassId
   			 INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
				where CM.DepartmentId=@rSourceId  AND CS.TempMultiPhotoCategoryId=@rTempPhotoCategoryId  AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -103 as Result,'Student already Exists' AS Msg
						RETURN
					END
					
			If EXISTS(select 1 from sCommunication.tTempMultiPhotoCategoryScope CS 
			 INNER JOIN sHrm.tEmployeeMaster  EM ON EM.Id =CS.SourceID AND CS.SourceTypeId= 95
			 INNER JOIN  sHrm.tEmployeeJobDetail EJD ON EM.Id=EJD.EmployeeId 			
			 where  EJD.OrganizationDepartmentId=@rSourceId  AND CS.TempMultiPhotoCategoryId=@rTempPhotoCategoryId AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -103 as Result,'Employee already Exists' AS Msg
					RETURN
				END 			
	    END
	    
    IF(@rSourceTypeId = 2016) -- Class	
	BEGIN
		If EXISTS(select 1 from  [sCommunication].[tTempMultiPhotoCategoryScope] CS 
		 INNER JOIN  sSetup.tClassMaster CM
			ON CS.SourceId=CM.OrgId AND CS.SourceTypeId= 2021
			where CM.Id=@rSourceId  AND CS.TempMultiPhotoCategoryId=@rTempPhotoCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Organization already Exists' AS Msg
					RETURN
				END 
		If EXISTS(select 1 from  [sCommunication].[tTempMultiPhotoCategoryScope] CS 
		 INNER JOIN  sSetup.tClassMaster CM
			ON CS.SourceId=CM.DepartmentId AND CS.SourceTypeId= 2017
			where CM.Id=@rSourceId  AND CS.TempMultiPhotoCategoryId=@rTempPhotoCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Department already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from  [sCommunication].[tTempMultiPhotoCategoryScope] CS
		 INNER JOIN  sSetup.tDivisionMaster DM 
			ON CS.SourceId=DM.Id AND CS.SourceTypeId= 2005
			where DM.ClassId=@rSourceId  AND CS.TempMultiPhotoCategoryId=@rTempPhotoCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -103 as Result,'Division already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from [sCommunication].[tTempMultiPhotoCategoryScope] CS 
		  INNER JOIN sStudent.tAcademic SA 
				ON CS.SourceId=SA.StudentId AND CS.SourceTypeId=2003
		  INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.ClassId=@rSourceId  AND CS.TempMultiPhotoCategoryId=@rTempPhotoCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -103 as Result,'Student already Exists' AS Msg
					RETURN
				END 			
    END
    
    IF(@rSourceTypeId = 2005) -- Division	
	BEGIN
		If EXISTS(select 1 from  [sCommunication].[tTempMultiPhotoCategoryScope] CS
		 INNER JOIN  sSetup.tDivisionMaster DM 
			ON CS.SourceId=DM.OrgId AND CS.SourceTypeId= 2021
			where DM.Id=@rSourceId  AND CS.TempMultiPhotoCategoryId=@rTempPhotoCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Organization already Exists' AS Msg
					RETURN
				END 
		If EXISTS(select 1 from  [sCommunication].[tTempMultiPhotoCategoryScope] CS
		 INNER JOIN sSetup.tClassMaster CM 
			ON CS.SourceId=CM.DepartmentId AND CS.SourceTypeId= 2017
		 INNER JOIN  sSetup.tDivisionMaster DM 
			ON DM.ClassId=CM.Id
			where DM.Id=@rSourceId  AND CS.TempMultiPhotoCategoryId=@rTempPhotoCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Department already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from  [sCommunication].[tTempMultiPhotoCategoryScope] CS 
		 INNER JOIN  sSetup.tDivisionMaster DM 
			ON CS.SourceId=DM.ClassId AND CS.SourceTypeId= 2016
			where DM.Id=@rSourceId  AND CS.TempMultiPhotoCategoryId=@rTempPhotoCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Class already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from [sCommunication].[tTempMultiPhotoCategoryScope] CS 
		  INNER JOIN sStudent.tAcademic SA 
				ON CS.SourceId=SA.StudentId AND CS.SourceTypeId=2003
		  INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.DivisionId=@rSourceId  AND CS.TempMultiPhotoCategoryId=@rTempPhotoCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -103 as Result,'Student already Exists' AS Msg
					RETURN
				END 
				
			If EXISTS(select 1 from [sCommunication].[tTempMultiPhotoCategoryScope] CS 
		  INNER JOIN sStudent.tAcademic SA 
				ON CS.SourceId=SA.DivisionId AND CS.SourceTypeId=2005
		  INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.DivisionId=@rSourceId  AND CS.TempMultiPhotoCategoryId=@rTempPhotoCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -103 as Result,'Student already Exists' AS Msg
					RETURN
				END 
								
    END
    
    IF(@rSourceTypeId = 2003) -- Student	
	BEGIN
		If EXISTS(select 1 from  [sCommunication].[tTempMultiPhotoCategoryScope] CS 
		 INNER JOIN  sStudent.tStudentMaster SM 
			ON CS.SourceId=SM.OrgId AND CS.SourceTypeId= 2021
			where SM.Id=@rSourceId  AND CS.TempMultiPhotoCategoryId=@rTempPhotoCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Organization already Exists' AS Msg
					RETURN
				END 
		If EXISTS(select 1 from [sCommunication].[tTempMultiPhotoCategoryScope] CS 
		 INNER JOIN  sSetup.tClassMaster CM 
			ON CS.SourceId=CM.DepartmentId AND CS.SourceTypeId= 2017
		 INNER JOIN sStudent.tAcademic SA 
				ON CM.Id=SA.ClassId 
		 INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.StudentId=@rSourceId  AND CS.TempMultiPhotoCategoryId=@rTempPhotoCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Department already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from  [sCommunication].[tTempMultiPhotoCategoryScope] CS 
		 INNER JOIN sStudent.tAcademic SA 
				ON CS.SourceId=SA.ClassId AND CS.SourceTypeId= 2016
		 INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.StudentId=@rSourceId  AND CS.TempMultiPhotoCategoryId=@rTempPhotoCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Class already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from  [sCommunication].[tTempMultiPhotoCategoryScope] CS
		 INNER JOIN sStudent.tAcademic SA 
				ON CS.SourceId=SA.DivisionId AND CS.SourceTypeId= 2005
		 INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.StudentId=@rSourceId  AND CS.TempMultiPhotoCategoryId=@rTempPhotoCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Division already Exists' AS Msg
					RETURN
				END 			
    END
    
    IF(@rSourceTypeId = 95) -- Employee	
	BEGIN
	
	
		If EXISTS(select 1 from  [sCommunication].[tTempMultiPhotoCategoryScope] CS 
		 INNER JOIN  sHrm.tEmployeeMaster EM 
			ON CS.SourceId=EM.OrgId AND CS.SourceTypeId= 2021
			where EM.Id=@rSourceId AND  ISNULL(EM.IsOtherUser,0) = 0  AND CS.TempMultiPhotoCategoryId=@rTempPhotoCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Organization already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from [sCommunication].[tTempMultiPhotoCategoryScope] CS 
		 INNER JOIN  sHrm.tEmployeeJobDetail EJD
			ON CS.SourceId=EJD.OrganizationDepartmentId AND CS.SourceTypeId= 2017
			where  EJD.EmployeeId=@rSourceId  AND CS.TempMultiPhotoCategoryId=@rTempPhotoCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Department already Exists' AS Msg
					RETURN
				END 
						
		
		 
	 
    END
    IF(@rSourceTypeId = 2001) -- Academic	
	BEGIN
		If EXISTS(select 1 from  [sCommunication].[tTempMultiPhotoCategoryScope] CS
		 INNER JOIN sStudent.tAcademic SA 
				ON CS.SourceId=SA.DivisionId AND CS.SourceTypeId= 2005
		 INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.Id=@rSourceId  AND CS.TempMultiPhotoCategoryId=@rTempPhotoCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Division already Exists' AS Msg
					RETURN
				END 		
	END
			select 1 as Result,'' AS Msg
	
END
GO
PRINT N'Altering [sCommunication].[pTempQueryCategoryScopeValidate]...';


GO
ALTER PROCEDURE [sCommunication].[pTempQueryCategoryScopeValidate]
	 
        @rTempQueryCategoryId nvarchar(100),
		@rSourceTypeId smallint,
		@rSourceId bigint,
		@rAssigneeToId int,
		@rQueryCategoryId int=0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
					/* Source Type Value
					   2021 - Organization
					   2017 - Department
					   2016 - Class
					   2005 - Division
					   2003 - Student */


		If EXISTS(select 1 from sCommunication.tTempQueryCategoryScope CS where CS.SourceId=@rSourceId AND
					CS.SourceTypeId=@rSourceTypeId AND CS.TempQueryCategoryId=@rTempQueryCategoryId AND AssigneeToId=@rAssigneeToId) 
			BEGIN
				select -101 as Result,'Item Already Exists' AS Msg
				RETURN
			END 
		IF(@rQueryCategoryId > 0)
		BEGIN
			If EXISTS(select 1 from sCommunication.tQueryCategoryScope CS where CS.SourceId=@rSourceId AND
				CS.SourceTypeId=@rSourceTypeId AND CS.QueryCategoryId=@rQueryCategoryId AND AssigneeToId=@rAssigneeToId) 
			BEGIN
				select -101 as Result,'Item Already Exists' AS Msg
				RETURN
			END 
		END

			
	IF(@rSourceTypeId = 2021) -- Organization	
		BEGIN
			If EXISTS(select 1 from  sCommunication.tTempQueryCategoryScope CS
			 INNER JOIN  sSetup.tDepartmentMaster DM 
				ON CS.SourceId=DM.Id AND CS.SourceTypeId= 2017
				where DM.OrgId=@rSourceId  AND CS.TempQueryCategoryId=@rTempQueryCategoryId AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -103 as Result,'Department already Exists' AS Msg
						RETURN
					END 
			If EXISTS(select 1 from  sCommunication.tTempQueryCategoryScope CS 
			 INNER JOIN  sSetup.tClassMaster CM 
				ON CS.SourceId=CM.Id AND CS.SourceTypeId= 2016
				where CM.OrgId=@rSourceId  AND CS.TempQueryCategoryId=@rTempQueryCategoryId AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -103 as Result,'Class already Exists' AS Msg
						RETURN
					END 
					
			If EXISTS(select 1 from  sCommunication.tTempQueryCategoryScope CS 
			 INNER JOIN  sSetup.tDivisionMaster DM 
				ON CS.SourceId=DM.Id AND CS.SourceTypeId= 2005
				where DM.OrgId=@rSourceId  AND CS.TempQueryCategoryId=@rTempQueryCategoryId AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -103 as Result,'Division already Exists' AS Msg
						RETURN
					END 
					
			If EXISTS(select 1 from  sCommunication.tTempQueryCategoryScope CS 
			 INNER JOIN  sStudent.tStudentMaster SM
				ON CS.SourceId=SM.Id AND CS.SourceTypeId= 2003
				where SM.OrgId=@rSourceId  AND CS.TempQueryCategoryId=@rTempQueryCategoryId AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -103 as Result,'Student already Exists' AS Msg
						RETURN
					END 
			
			If EXISTS(select 1 from  sCommunication.tTempQueryCategoryScope CS 
			 INNER JOIN  sHrm.tEmployeeMaster EM
				ON CS.SourceId=EM.Id AND CS.SourceTypeId= 95
				where EM.OrgId=@rSourceId  AND CS.TempQueryCategoryId=@rTempQueryCategoryId AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -103 as Result,'Employee already Exists' AS Msg
						RETURN
					END 
				
		IF(@rQueryCategoryId > 0)	
		BEGIN
			If EXISTS(select 1 from  sCommunication.tQueryCategoryScope CS
			 INNER JOIN  sSetup.tDepartmentMaster DM 
				ON CS.SourceId=DM.Id AND CS.SourceTypeId= 2017
				where DM.OrgId=@rSourceId  AND CS.QueryCategoryId=@rQueryCategoryId AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -103 as Result,'Department already Exists' AS Msg
						RETURN
					END 
			If EXISTS(select 1 from  sCommunication.tQueryCategoryScope CS 
			 INNER JOIN  sSetup.tClassMaster CM 
				ON CS.SourceId=CM.Id AND CS.SourceTypeId= 2016
				where CM.OrgId=@rSourceId  AND CS.QueryCategoryId=@rQueryCategoryId AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -103 as Result,'Class already Exists' AS Msg
						RETURN
					END 
					
			If EXISTS(select 1 from  sCommunication.tQueryCategoryScope CS 
			 INNER JOIN  sSetup.tDivisionMaster DM 
				ON CS.SourceId=DM.Id AND CS.SourceTypeId= 2005
				where DM.OrgId=@rSourceId  AND CS.QueryCategoryId=@rQueryCategoryId AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -103 as Result,'Division already Exists' AS Msg
						RETURN
					END 
					
			If EXISTS(select 1 from  sCommunication.tQueryCategoryScope CS 
			 INNER JOIN  sStudent.tStudentMaster SM
				ON CS.SourceId=SM.Id AND CS.SourceTypeId= 2003
				where SM.OrgId=@rSourceId  AND CS.QueryCategoryId=@rQueryCategoryId AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -103 as Result,'Student already Exists' AS Msg
						RETURN
					END 

			If EXISTS(select 1 from  sCommunication.tQueryCategoryScope CS 
					INNER JOIN  sHrm.tEmployeeMaster EM
				ON CS.SourceId=EM.Id AND CS.SourceTypeId= 95
				where EM.OrgId=@rSourceId  AND CS.QueryCategoryId=@rQueryCategoryId AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -103 as Result,'Employee already Exists' AS Msg
						RETURN
					END 
		END

							
	    END
	
	IF(@rSourceTypeId = 2017) -- Department	
		BEGIN
			If EXISTS(select 1 from  sCommunication.tTempQueryCategoryScope CS
			 INNER JOIN  sSetup.tDepartmentMaster DM
				ON CS.SourceId=DM.OrgId AND CS.SourceTypeId= 2021
				where DM.Id=@rSourceId  AND CS.TempQueryCategoryId=@rTempQueryCategoryId AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -102 as Result,'Organization already Exists' AS Msg
						RETURN
					END 
			
			If EXISTS(select 1 from  sCommunication.tTempQueryCategoryScope CS
			 INNER JOIN sSetup.tClassMaster CM
				ON CS.SourceId=CM.Id AND CS.SourceTypeId= 2016
				where CM.DepartmentId=@rSourceId  AND CS.TempQueryCategoryId=@rTempQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -103 as Result,'Class already Exists' AS Msg
						RETURN
					END 
					
			If EXISTS(select 1 from  sCommunication.tTempQueryCategoryScope CS 
			 INNER JOIN  sSetup.tDivisionMaster DM 
				ON CS.SourceId=DM.Id AND CS.SourceTypeId= 2005
			 INNER JOIN sSetup.tClassMaster CM
				ON CM.Id=DM.ClassId
				where CM.DepartmentId=@rSourceId  AND CS.TempQueryCategoryId=@rTempQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -103 as Result,'Division already Exists' AS Msg
						RETURN
					END 
					
			If EXISTS(select 1 from  sCommunication.tTempQueryCategoryScope CS 
			 INNER JOIN sStudent.tAcademic SA 
				ON CS.SourceId=SA.StudentId AND CS.SourceTypeId=2003
			 INNER JOIN sSetup.tClassMaster CM
				ON CM.Id=SA.ClassId
   			 INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
				where CM.DepartmentId=@rSourceId  AND CS.TempQueryCategoryId=@rTempQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -103 as Result,'Student already Exists' AS Msg
						RETURN
					END 
					
			If EXISTS(select 1 from sCommunication.tTempQueryCategoryScope CS 
			 INNER JOIN sHrm.tEmployeeMaster  EM ON EM.Id =CS.SourceID AND CS.SourceTypeId= 95
			 INNER JOIN  sHrm.tEmployeeJobDetail EJD ON EM.Id=EJD.EmployeeId 			
			 where  EJD.OrganizationDepartmentId=@rSourceId  AND CS.TempQueryCategoryId=@rTempQueryCategoryId AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -103 as Result,'Employee already Exists' AS Msg
					RETURN
				END
						
			IF(@rQueryCategoryId > 0)
			BEGIN
				If EXISTS(select 1 from  sCommunication.tQueryCategoryScope CS
				 INNER JOIN  sSetup.tDepartmentMaster DM
					ON CS.SourceId=DM.OrgId AND CS.SourceTypeId= 2021
					where DM.Id=@rSourceId  AND CS.QueryCategoryId=@rQueryCategoryId AND AssigneeToId=@rAssigneeToId)
						BEGIN
							select -102 as Result,'Organization already Exists' AS Msg
							RETURN
						END 
				If EXISTS(select 1 from  sCommunication.tQueryCategoryScope CS
				 INNER JOIN sSetup.tClassMaster CM
					ON CS.SourceId=CM.Id AND CS.SourceTypeId= 2016
					where CM.DepartmentId=@rSourceId  AND CS.QueryCategoryId=@rQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
						BEGIN
							select -103 as Result,'Class already Exists' AS Msg
							RETURN
						END 
					
				If EXISTS(select 1 from  sCommunication.tQueryCategoryScope CS 
				 INNER JOIN  sSetup.tDivisionMaster DM 
					ON CS.SourceId=DM.Id AND CS.SourceTypeId= 2005
				 INNER JOIN sSetup.tClassMaster CM
					ON CM.Id=DM.ClassId
					where CM.DepartmentId=@rSourceId  AND CS.QueryCategoryId=@rQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
						BEGIN
							select -103 as Result,'Division already Exists' AS Msg
							RETURN
						END 
					
				If EXISTS(select 1 from  sCommunication.tQueryCategoryScope CS 
				 INNER JOIN sStudent.tAcademic SA 
					ON CS.SourceId=SA.StudentId AND CS.SourceTypeId=2003
				 INNER JOIN sSetup.tClassMaster CM
					ON CM.Id=SA.ClassId
   				 INNER JOIN sSetup.tBatchMaster BM 
   					ON BM.Id = SA.BatchId AND BM.IsActive=1
					where CM.DepartmentId=@rSourceId  AND CS.QueryCategoryId=@rQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
						BEGIN
							select -103 as Result,'Student already Exists' AS Msg
							RETURN
						END 
			
			If EXISTS(select 1 from sCommunication.tQueryCategoryScope CS 
				INNER JOIN sHrm.tEmployeeMaster  EM ON EM.Id =CS.SourceID AND CS.SourceTypeId= 95
				INNER JOIN  sHrm.tEmployeeJobDetail EJD ON EM.Id=EJD.EmployeeId 			
				where  EJD.OrganizationDepartmentId=@rSourceId  AND CS.QueryCategoryId=@rQueryCategoryId AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -103 as Result,'Employee already Exists' AS Msg
					RETURN
				END	
			END		
	    END
	    
    IF(@rSourceTypeId = 2016) -- Class	
	BEGIN
		If EXISTS(select 1 from  sCommunication.tTempQueryCategoryScope CS 
		 INNER JOIN  sSetup.tClassMaster CM
			ON CS.SourceId=CM.OrgId AND CS.SourceTypeId= 2021
			where CM.Id=@rSourceId  AND CS.TempQueryCategoryId=@rTempQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Organization already Exists' AS Msg
					RETURN
				END 
		If EXISTS(select 1 from  sCommunication.tTempQueryCategoryScope CS 
		 INNER JOIN  sSetup.tClassMaster CM
			ON CS.SourceId=CM.DepartmentId AND CS.SourceTypeId= 2017
			where CM.Id=@rSourceId  AND CS.TempQueryCategoryId=@rTempQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Department already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from  sCommunication.tTempQueryCategoryScope CS
		 INNER JOIN  sSetup.tDivisionMaster DM 
			ON CS.SourceId=DM.Id AND CS.SourceTypeId= 2005
			where DM.ClassId=@rSourceId  AND CS.TempQueryCategoryId=@rTempQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -103 as Result,'Division already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from sCommunication.tTempQueryCategoryScope CS 
		  INNER JOIN sStudent.tAcademic SA 
				ON CS.SourceId=SA.StudentId AND CS.SourceTypeId=2003
		  INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.ClassId=@rSourceId  AND CS.TempQueryCategoryId=@rTempQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -103 as Result,'Student already Exists' AS Msg
					RETURN
				END 		
				
		IF(@rQueryCategoryId > 0)
		BEGIN	
			If EXISTS(select 1 from  sCommunication.tQueryCategoryScope CS 
			 INNER JOIN  sSetup.tClassMaster CM
				ON CS.SourceId=CM.OrgId AND CS.SourceTypeId= 2021
				where CM.Id=@rSourceId  AND CS.QueryCategoryId=@rQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -102 as Result,'Organization already Exists' AS Msg
						RETURN
					END 
			If EXISTS(select 1 from  sCommunication.tQueryCategoryScope CS 
			 INNER JOIN  sSetup.tClassMaster CM
				ON CS.SourceId=CM.DepartmentId AND CS.SourceTypeId= 2017
				where CM.Id=@rSourceId  AND CS.QueryCategoryId=@rQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -102 as Result,'Department already Exists' AS Msg
						RETURN
					END 
				
			If EXISTS(select 1 from  sCommunication.tQueryCategoryScope CS
			 INNER JOIN  sSetup.tDivisionMaster DM 
				ON CS.SourceId=DM.Id AND CS.SourceTypeId= 2005
				where DM.ClassId=@rSourceId  AND CS.QueryCategoryId=@rQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -103 as Result,'Division already Exists' AS Msg
						RETURN
					END 
				
			If EXISTS(select 1 from sCommunication.tQueryCategoryScope CS 
			  INNER JOIN sStudent.tAcademic SA 
					ON CS.SourceId=SA.StudentId AND CS.SourceTypeId=2003
			  INNER JOIN sSetup.tBatchMaster BM 
   					ON BM.Id = SA.BatchId AND BM.IsActive=1
				where SA.ClassId=@rSourceId  AND CS.QueryCategoryId=@rQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -103 as Result,'Student already Exists' AS Msg
						RETURN
					END 
		END
    END
    
    IF(@rSourceTypeId = 2005) -- Division	
	BEGIN
		If EXISTS(select 1 from  sCommunication.tTempQueryCategoryScope CS
		 INNER JOIN  sSetup.tDivisionMaster DM 
			ON CS.SourceId=DM.OrgId AND CS.SourceTypeId= 2021
			where DM.Id=@rSourceId  AND CS.TempQueryCategoryId=@rTempQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Organization already Exists' AS Msg
					RETURN
				END 
		If EXISTS(select 1 from  sCommunication.tTempQueryCategoryScope CS
		 INNER JOIN sSetup.tClassMaster CM 
			ON CS.SourceId=CM.DepartmentId AND CS.SourceTypeId= 2017
		 INNER JOIN  sSetup.tDivisionMaster DM 
			ON DM.ClassId=CM.Id
			where DM.Id=@rSourceId  AND CS.TempQueryCategoryId=@rTempQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Department already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from  sCommunication.tTempQueryCategoryScope CS 
		 INNER JOIN  sSetup.tDivisionMaster DM 
			ON CS.SourceId=DM.ClassId AND CS.SourceTypeId= 2016
			where DM.Id=@rSourceId  AND CS.TempQueryCategoryId=@rTempQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Class already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from sCommunication.tTempQueryCategoryScope CS 
		  INNER JOIN sStudent.tAcademic SA 
				ON CS.SourceId=SA.StudentId AND CS.SourceTypeId=2003
		  INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.DivisionId=@rSourceId  AND CS.TempQueryCategoryId=@rTempQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -103 as Result,'Student already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from sCommunication.tTempQueryCategoryScope CS 
		  INNER JOIN sStudent.tAcademic SA 
				ON CS.SourceId=SA.DivisionId AND CS.SourceTypeId=2005
		  INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.DivisionId=@rSourceId  AND CS.TempQueryCategoryId=@rTempQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -103 as Result,'Student already Exists' AS Msg
					RETURN
				END 

		IF(@rQueryCategoryId > 0)
		BEGIN
		If EXISTS(select 1 from  sCommunication.tQueryCategoryScope CS
		 INNER JOIN  sSetup.tDivisionMaster DM 
			ON CS.SourceId=DM.OrgId AND CS.SourceTypeId= 2021
			where DM.Id=@rSourceId  AND CS.QueryCategoryId=@rQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Organization already Exists' AS Msg
					RETURN
				END 
		If EXISTS(select 1 from  sCommunication.tQueryCategoryScope CS
		 INNER JOIN sSetup.tClassMaster CM 
			ON CS.SourceId=CM.DepartmentId AND CS.SourceTypeId= 2017
		 INNER JOIN  sSetup.tDivisionMaster DM 
			ON DM.ClassId=CM.Id
			where DM.Id=@rSourceId  AND CS.QueryCategoryId=@rQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Department already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from  sCommunication.tQueryCategoryScope CS 
		 INNER JOIN  sSetup.tDivisionMaster DM 
			ON CS.SourceId=DM.ClassId AND CS.SourceTypeId= 2016
			where DM.Id=@rSourceId  AND CS.QueryCategoryId=@rQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Class already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from sCommunication.tQueryCategoryScope CS 
		  INNER JOIN sStudent.tAcademic SA 
				ON CS.SourceId=SA.StudentId AND CS.SourceTypeId=2003
		  INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.DivisionId=@rSourceId  AND CS.QueryCategoryId=@rQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -103 as Result,'Student already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from sCommunication.tQueryCategoryScope CS 
		  INNER JOIN sStudent.tAcademic SA 
				ON CS.SourceId=SA.DivisionId AND CS.SourceTypeId=2005
		  INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.DivisionId=@rSourceId  AND CS.QueryCategoryId=@rQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -103 as Result,'Student already Exists' AS Msg
					RETURN
				END 
		END	
								
    END
    
    IF(@rSourceTypeId = 2003) -- Student	
	BEGIN
		If EXISTS(select 1 from  sCommunication.tTempQueryCategoryScope CS 
		 INNER JOIN  sStudent.tStudentMaster SM 
			ON CS.SourceId=SM.OrgId AND CS.SourceTypeId= 2021
			where SM.Id=@rSourceId  AND CS.TempQueryCategoryId=@rTempQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Organization already Exists' AS Msg
					RETURN
				END 
		If EXISTS(select 1 from sCommunication.tTempQueryCategoryScope CS 
		 INNER JOIN  sSetup.tClassMaster CM 
			ON CS.SourceId=CM.DepartmentId AND CS.SourceTypeId= 2017
		 INNER JOIN sStudent.tAcademic SA 
				ON CM.Id=SA.ClassId 
		 INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.StudentId=@rSourceId  AND CS.TempQueryCategoryId=@rTempQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Department already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from  sCommunication.tTempQueryCategoryScope CS 
		 INNER JOIN sStudent.tAcademic SA 
				ON CS.SourceId=SA.ClassId AND CS.SourceTypeId= 2016
		 INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.StudentId=@rSourceId  AND CS.TempQueryCategoryId=@rTempQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Class already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from  sCommunication.tTempQueryCategoryScope CS
		 INNER JOIN sStudent.tAcademic SA 
				ON CS.SourceId=SA.DivisionId AND CS.SourceTypeId= 2005
		 INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.StudentId=@rSourceId  AND CS.TempQueryCategoryId=@rTempQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Division already Exists' AS Msg
					RETURN
				END 	
				
		IF(@rQueryCategoryId > 0)
		BEGIN	

		If EXISTS(select 1 from  sCommunication.tQueryCategoryScope CS 
		 INNER JOIN  sStudent.tStudentMaster SM 
			ON CS.SourceId=SM.OrgId AND CS.SourceTypeId= 2021
			where SM.Id=@rSourceId  AND CS.QueryCategoryId=@rQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Organization already Exists' AS Msg
					RETURN
				END 
		If EXISTS(select 1 from sCommunication.tQueryCategoryScope CS 
		 INNER JOIN  sSetup.tClassMaster CM 
			ON CS.SourceId=CM.DepartmentId AND CS.SourceTypeId= 2017
		 INNER JOIN sStudent.tAcademic SA 
				ON CM.Id=SA.ClassId 
		 INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.StudentId=@rSourceId  AND CS.QueryCategoryId=@rQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Department already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from  sCommunication.tQueryCategoryScope CS 
		 INNER JOIN sStudent.tAcademic SA 
				ON CS.SourceId=SA.ClassId AND CS.SourceTypeId= 2016
		 INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.StudentId=@rSourceId  AND CS.QueryCategoryId=@rQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Class already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from  sCommunication.tQueryCategoryScope CS
		 INNER JOIN sStudent.tAcademic SA 
				ON CS.SourceId=SA.DivisionId AND CS.SourceTypeId= 2005
		 INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.StudentId=@rSourceId  AND CS.QueryCategoryId=@rQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Division already Exists' AS Msg
					RETURN
				END 	
		END	
    END
    
    IF(@rSourceTypeId = 95) -- Employee	
	BEGIN
	
	
		If EXISTS(select 1 from  sCommunication.tTempQueryCategoryScope CS 
		 INNER JOIN  sHrm.tEmployeeMaster EM 
			ON CS.SourceId=EM.OrgId AND CS.SourceTypeId= 2021
			where EM.Id=@rSourceId AND  ISNULL(EM.IsOtherUser,0) = 0  AND CS.TempQueryCategoryId=@rTempQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Organization already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from sCommunication.tTempQueryCategoryScope CS 
		 INNER JOIN  sHrm.tEmployeeJobDetail EJD
			ON CS.SourceId=EJD.OrganizationDepartmentId AND CS.SourceTypeId= 2017
			where  EJD.EmployeeId=@rSourceId  AND CS.TempQueryCategoryId=@rTempQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Department already Exists' AS Msg
					RETURN
				END 
						
		IF(@rQueryCategoryId > 0)
		BEGIN	
		If EXISTS(select 1 from  sCommunication.tQueryCategoryScope CS 
		 INNER JOIN  sHrm.tEmployeeMaster EM 
			ON CS.SourceId=EM.OrgId AND CS.SourceTypeId= 2021
			where EM.Id=@rSourceId AND  ISNULL(EM.IsOtherUser,0) = 0  AND CS.QueryCategoryId=@rQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Organization already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from sCommunication.tQueryCategoryScope CS 
		 INNER JOIN  sHrm.tEmployeeJobDetail EJD
			ON CS.SourceId=EJD.OrganizationDepartmentId AND CS.SourceTypeId= 2017
			where  EJD.EmployeeId=@rSourceId  AND CS.QueryCategoryId=@rQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Department already Exists' AS Msg
					RETURN
				END 
		END
		 
	 
    END
    IF(@rSourceTypeId = 2001) -- Academic	
	BEGIN
		If EXISTS(select 1 from  sCommunication.tTempQueryCategoryScope CS
		 INNER JOIN sStudent.tAcademic SA 
				ON CS.SourceId=SA.DivisionId AND CS.SourceTypeId= 2005
		 INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.Id=@rSourceId  AND CS.TempQueryCategoryId=@rTempQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Division already Exists' AS Msg
					RETURN
				END 	
		IF(@rQueryCategoryId > 0)
		BEGIN
			If EXISTS(select 1 from  sCommunication.tQueryCategoryScope CS
		 INNER JOIN sStudent.tAcademic SA 
				ON CS.SourceId=SA.DivisionId AND CS.SourceTypeId= 2005
		 INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.Id=@rSourceId  AND CS.QueryCategoryId=@rQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Division already Exists' AS Msg
					RETURN
				END 	
		END	
	END
			select 1 as Result,'' AS Msg
	
END
GO
PRINT N'Altering [sEExam].[pDeactiveALLTestParticipant]...';


GO

ALTER PROCEDURE [sEExam].[pDeactiveALLTestParticipant]
	 
	 @rTestId bigint,	 
	 @rMode int	 
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	BEGIN TRY
		BEGIN TRANSACTION			   	   
		   
		  --IF(@rMode = 1)  --Activate All Participant
		  --  BEGIN
		    
				--CREATE Table #TempTestParticipant
				--(
				--   Id Int Identity(1,1), 
				--   SourceId bigint,
				--   SourceTypeId int,
				--   TestDate Date, 
				--   TotalMarks decimal(6,2)				   
				--)
		  --    SELECT StudentId FROM sStudent.vStudentAcademic VSA Where DivisionId = @rSourceId  
		     
		  --    UPDATE sEExam.tTestParticipant SET TestStatusId = 543 WHERE TestId = @rTestId  
		  -- 	  AND ISNULL(TestStatusId,0) NOT IN (544,545) 		   	   
			 --    -- When I Deactive Div Then Also Deactive Student Which Is Active 	   
			  
			 -- UPDATE sEExam.tTestAssign SET TestStatusId = 543 Where TestId = @rTestId 
			 -- AND ISNULL(TestStatusId,0) NOT IN (544,545) 
			  			  
			 -- SELECT 1 AS Result 			  
		  --  END	   	   
		   	    
		  -- ELSE 
		   IF(@rMode = 0) --DeActivate All Participant 
		   	 BEGIN 
		   	  UPDATE sEExam.tTestParticipant SET TestStatusId = 0 WHERE TestId = @rTestId  
		   	  AND ISNULL(TestStatusId,0) NOT IN (544,545)		   	   
			     -- When I Deactive Div Then Also Deactive Student Which Is Active 	   
			  UPDATE sEExam.tTestAssign SET TestStatusId = 0 Where TestId = @rTestId 
			  AND ISNULL(TestStatusId,0)  NOT IN (544,545) 

			  ----Delete Participant Answer
			  --DELETE TPA FROM sEExam.tTestParticipantAnswer TPA 
			  --INNER JOIN sEExam.tTestParticipant TP ON TPA.TestParticipantId=TP.Id
			  --WHERE TPA.TestId= @rTestId 

			  SELECT 1 AS Result  
		     END		    
		   ELSE   -- Delete All Participant
		     BEGIN
		           
		         Delete from  sEExam.tTestParticipant   WHERE TestId = @rTestId  
		   	     AND ISNULL(TestStatusId,0) NOT IN (544,545)	
		   	      		        		        
				 DELETE FROM sEExam.tTestAssign   Where TestId = @rTestId 
				 AND ISNULL(TestStatusId,0)  NOT IN (544,545) 

			   ----Delete Participant Answer
				  --DELETE TPA FROM sEExam.tTestParticipantAnswer TPA 
				  --INNER JOIN sEExam.tTestParticipant TP ON TPA.TestParticipantId=TP.Id
				  --WHERE TPA.TestId= @rTestId 
				  
				 SELECT 1 AS Result 
		     END 	
		COMMIT TRANSACTION	
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END
GO
PRINT N'Altering [sEExam].[pDeactiveTestParticipant]...';


GO

ALTER PROCEDURE [sEExam].[pDeactiveTestParticipant]
	 
	 @rTestId bigint,
	 @rSourceId bigint,
	 @rSourceTypeId int,
	 @rBatchId int	
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	BEGIN TRY
		BEGIN TRANSACTION			
		    IF(@rSourceTypeId = 2005)
			   BEGIN           
					 UPDATE  TP 
					 SET TP.TestStatusId = 0
					 FROM sEExam.tTestParticipant TP INNER JOIN sStudent.vStudentAcademic VSA 
					 ON TP.SourceId = VSA.StudentId 
					 Where DivisionId = @rSourceId  AND TP.TestId = @rTestId AND VSA.BatchId = @rBatchId
					 --INSERT INTO sEExam.tTestParticipant
					 --Select @rTestId,2003,StudentId,@rTestDate,@rStartTime,@rEndTime,1,@rTotalMarks,@rScoredMarks,@rTotalQuestions,@rRightQuestions,@rWrongQuestions,@rNotAttemptedQuestions
					 --FROM sStudent.vStudentAcademic VSA Where DivisionId = @rSourceId  
			           
			         UPDATE  TA 
					 SET TA.TestStatusId = 0
					 FROM sEExam.tTestAssign TA INNER JOIN sStudent.vStudentAcademic VSA 
					 ON TA.SourceId = VSA.StudentId 
					 Where DivisionId = @rSourceId AND TA.TestId = @rTestId AND VSA.BatchId = @rBatchId
				     
				  --   UPDATE  TP 
					 --SET TA.TestStatusId = 0
					 --FROM sEExam.tTestParticipant TP INNER JOIN sEExam.tTestAssign TA ON TP.SourceId = TA.SourceId					  
					 --WHERE  TP.SourceTypeId = 2003 AND TA.TestStatusId = 1 

					 ----Delete Participant Answer
					 --DELETE TPA FROM sEExam.tTestParticipantAnswer TPA 
					 --INNER JOIN sEExam.tTestParticipant TP ON TPA.TestParticipantId=TP.Id
					 --INNER JOIN sStudent.vStudentAcademic VSA ON TP.SourceId = VSA.StudentId 
					 --WHERE TPA.TestId= @rTestId  
					 --AND VSA.DivisionId = @rSourceId  AND VSA.BatchId = @rBatchId
			          
					SELECT 1 AS Result 
               END 
			ELSE 
			   BEGIN
			      UPDATE sEExam.tTestParticipant SET TestStatusId = 0 WHERE   SourceId = @rSourceId AND SourceTypeId = @rSourceTypeId AND TestId = @rTestId
			   END			   
			   -- When I Deactive Div Then Also Deactive Student Which Is Active 
			    UPDATE sEExam.tTestAssign SET TestStatusId = 0 Where SourceId = @rSourceId AND SourceTypeId = @rSourceTypeId AND TestId = @rTestId

				----Delete Participant Answer
				--DELETE TPA FROM sEExam.tTestParticipantAnswer TPA 
				--INNER JOIN sEExam.tTestParticipant TP ON TPA.TestParticipantId=TP.Id
				--INNER JOIN sStudent.vStudentAcademic VSA ON TP.SourceId = VSA.StudentId 
				--WHERE TPA.TestId= @rTestId AND  TP.SourceId = @rSourceId AND TP.SourceTypeId = @rSourceTypeId
		  
			SELECT 1 AS Result 
			
		COMMIT TRANSACTION	
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END
GO
PRINT N'Altering [sEExam].[pTestParticipantIndividualAnswerAdd]...';


GO
 
 
ALTER PROCEDURE [sEExam].[pTestParticipantIndividualAnswerAdd]
	 
	@rTestParticipantId bigint,
	@rTestId int,
	@rQuestionDetailXml [nvarchar](max),
	@rQuestionOptionDetailXml [nvarchar](max),
	@rQuestionId bigint=0, 
	@rQuestionOptionId bigint=0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

	DECLARE @loQuestionDoc INT
	EXEC sp_xml_preparedocument @loQuestionDoc OUTPUT, @rQuestionDetailXml
	
	DECLARE @loQuestionOptionDoc INT
	EXEC sp_xml_preparedocument @loQuestionOptionDoc OUTPUT, @rQuestionOptionDetailXml
	
BEGIN

	BEGIN TRY	
	BEGIN TRANSACTION
	
	--SELECT * FROM sEExam.tTestParticipantAnswer WHERE TestParticipantId=@rTestParticipantId AND TestId=@rTestId AND QuestionId=@rQuestionId 
	DELETE FROM sEExam.tTestParticipantAnswer WHERE TestParticipantId=@rTestParticipantId AND TestId=@rTestId AND QuestionId=@rQuestionId 
	--AND QuestionOptionId=@rQuestionOptionId
	
	UPDATE sEExam.tTestParticipant
	    SET
			TestDate = A.TestDate,
			StartTime = A.StartTime,
			EndTime = A.EndTime,
			TestStatusId = A.TestStatusId,
			TotalMarks = A.TotalMarks,
			ScoredMarks = A.ScoredMarks,
			TotalQuestions = A.TotalQuestions,
			RightQuestions = A.RightQuestions,
			WrongQuestions = A.WrongQuestions,
			SkippQuestions = A.SkippQuestions,
			NotAttemptedQuestions = A.NotAttemptedQuestions
			FROM
		 (
	  SELECT TOP 1
	        @rTestParticipantId AS TestParticipantId,
	        @rTestId AS TestId,
			TestDate,
			StartTime,
			EndTime,
			TestStatusId,
			TotalMarks,
			ScoredMarks,
			TotalQuestions,
			RightQuestions,
			WrongQuestions,
			SkippQuestions,
			NotAttemptedQuestions
		FROM OPENXML (@loQuestionDoc, '/Table/QuestionDetail', 1)
		WITH ( 
		        SourceTypeId smallint,
			    SourceId bigint,
			    TestDate date,
			    StartTime time,
			    EndTime time,
			    TestStatusId smallint,
				TotalMarks decimal(6,2),
				ScoredMarks decimal(6,2),
				TotalQuestions int,
				RightQuestions int,
				WrongQuestions int,
				SkippQuestions int,
				NotAttemptedQuestions int
			  ))A	
			    WHERE A.TestParticipantId = @rTestParticipantId AND A.TestId = @rTestId
			    AND sEExam.tTestParticipant.Id = A.TestParticipantId
			    
	INSERT INTO sEExam.tTestParticipantAnswer
		(
			TestId,
			QuestionId,
			QuestionOptionId,
			ScoredMark,
			AnswerStatusId,
			OrderIndex,
			TestParticipantId
		)
	  SELECT 
			@rTestId,
			QuestionId,
			QuestionOptionId,
			ScoredMark,
			AnswerStatusId,
			OrderIndex,
			@rTestParticipantId
			
		FROM OPENXML (@loQuestionOptionDoc, '/Table/QuestionOptionDetail', 1)
		WITH ( 
		        TestId Int,
				QuestionId bigint,
				QuestionOptionId bigint,
				ScoredMark decimal(6,2),
				AnswerStatusId smallint,
				OrderIndex smallint
			  ) 
		SELECT 1 AS Result   
		
		SELECT IsDisplayResultOnComplete FROM sEExam.tTestMaster WHERE Id =@rTestId
		
		EXEC sp_xml_removedocument @loQuestionDoc
		EXEC sp_xml_removedocument @loQuestionOptionDoc
		COMMIT TRANSACTION
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
		EXEC sp_xml_removedocument @loQuestionDoc
		EXEC sp_xml_removedocument @loQuestionOptionDoc
	END CATCH	 
	 
	
   
END
GO
PRINT N'Altering [sFee].[pEMandateTransactionGet]...';


GO
 
 
ALTER PROCEDURE [sFee].[pEMandateTransactionGet]
	@rAcademicId bigint = 0,
	@rFromDate nvarchar(10) = '',
	@rToDate nvarchar(10) = '',
	@rOrgGroupId smallint=0,
	@rOrgId int=0,
	@rBatchId int=0,
	@rReferenceNo bigint=0
AS
SET NOCOUNT ON

BEGIN
	 SELECT  
		ISNULL(EM.ResponseStatus,'Pending') as ResponseStatus,
		EM.Customer_DebitAmount,
		EM.Customer_MaxAmount,
		EM.Customer_StartDate,
		EM.Customer_ExpiryDate,
		CONVERT(nvarchar(20),SM.Code) AS Code,
		SM.FirstName + ' ' + SM.LastName AS Name,
		CM.DisplayTitle +' - '+ DM.DisplayTitle AS ClassName,
		EM.Id AS EMandateId
	
	FROM 
		sFee.tEmandate EM
		INNER JOIN sStudent.tAcademic A ON A.Id = EM.AcademicId
		INNER JOIN sStudent.tStudentMaster SM ON SM.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 OM.Id = CM.OrgId
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
		
	WHERE 
		 ((EM.Customer_StartDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		 AND ((EM.Customer_StartDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		 AND ((EM.AcademicId = @rAcademicId) OR (@rAcademicId=0))
		 AND OM.OrgGroupId = @rOrgGroupId
		 AND OM.Id = @rOrgId
		 AND BM.Id = @rBatchId
		 AND (EM.Id= @rReferenceNo OR @rReferenceNo=0)
		 ORDER BY EM.Customer_StartDate DESC
END
GO
PRINT N'Altering [sFee].[pFeeGenerateReport]...';


GO
ALTER PROCEDURE [sFee].[pFeeGenerateReport]
	
	@rId bigint,
	@rTitle nvarchar(50),
	@rColumnName nvarchar(max) = '',
	@rOrderBy nvarchar(max) = 'ReceiptNumber',
	@rOrgGroupBatchId int,
	@rOrgId smallint,
	@rBatchId int,
	@rCurrentOrgId smallint,
	@rCode [nvarchar](20) = '',
	@rFirstName [nvarchar](50) = '',	
	@rLastName [nvarchar](50) = '',
	--@rClassId nvarchar(max) = '',
	@rDivisionId nvarchar(max) = '',
	@rReceiptBookId nvarchar(max) = '',
	@rFromReceiptDate Date = '0001-01-01',
	@rToReceiptDate Date = '9999-12-31',
	@rFromReceiptNo int,
	@rToReceiptNo int,
	@rIsObsolete bit,
	@rIsCommon bit,
	@rCreatedUserId bigint,
	@rInsertUserId bigint,
	@rDropDownStatusId int,
	@rDropDownClassId int,
	@rDropDownDivisionId int,
	@rDropDownReceiptBookId int,
	@rIsCommonForOrg bit,
	@rAdmissionCategoryId int = 0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	
	IF(@rFromReceiptDate IS NULL)
			SET @rFromReceiptDate='0001-01-01'
	IF(@rToReceiptDate IS NULL)
		SET @rToReceiptDate='9999-12-31'
	
	IF(@rTitle != '' AND @rId = 0)
	BEGIN
	DECLARE @lNextNumber BIGINT     
	EXECUTE sCommon.pTableRowIdGet @rCurrentOrgId, 'sFee.tFeeCustomSearch', 0, 1, 1,@outNextNumber = @lNextNumber output

	INSERT INTO sFee.tFeeCustomSearch
		(
			Id,
			Title,
			ColumnName,
			OrderBy,
			OrgGroupBatchId,
			OrgId,
			BatchId,
			Code,
			FirstName,	
			LastName,
			DivisionId,
			ReceiptBookId,
			FromReceiptDate,
			ToReceiptDate,
			FromReceiptNo,
			ToReceiptNo,
			IsObsolete,
			IsCommon,
			UserId,
			CreatedUserId,
			CreatedDateTime,
			IsCommonForOrg
		)
	VALUES
		(
			@lNextNumber,
			@rTitle,
			@rColumnName,
			@rOrderBy,
			@rOrgGroupBatchId,
			@rOrgId,
			@rBatchId,
			@rCode,
			@rFirstName,	
			@rLastName,
			@rDivisionId,
			@rReceiptBookId,
			@rFromReceiptDate,
			@rToReceiptDate,
			@rFromReceiptNo,
			@rToReceiptNo,
			@rIsObsolete,
			@rIsCommon,
			@rCreatedUserId,
			@rInsertUserId,
			sCommon.fGetDate(),
			@rIsCommonForOrg
		)
		--SELECT @lNextNumber AS Result
	END
	IF(@rId > 0)
	BEGIN
		Select
				@rColumnName=ColumnName,
				@rOrderBy=OrderBy,
				@rOrgGroupBatchId=OrgGroupBatchId,
				@rOrgId=OrgId,
				@rBatchId=BatchId,
				@rCode=Code,
				@rFirstName=FirstName,	
				@rLastName=LastName,
				@rDivisionId=DivisionId,
				@rReceiptBookId=ReceiptBookId,
				@rFromReceiptDate=FromReceiptDate,
				@rToReceiptDate=ToReceiptDate,
				@rFromReceiptNo=FromReceiptNo,
				@rToReceiptNo=ToReceiptNo,
				@rIsObsolete=IsObsolete,
				@rCreatedUserId=UserId
		FROM
			sFee.tFeeCustomSearch
		WHERE
			Id=@rId
	END
	 
		SET @rColumnName=Replace(@rColumnName,'ID No','Code')
		SET @rOrderBy=Replace(@rOrderBy,'ID No','Code')
	  
		SET @rColumnName=Replace(@rColumnName,'GR No','Code')
	 
		SET @rOrderBy=Replace(@rOrderBy,'GR No','Code')
	 
		DECLARE @Sql nvarchar(MAX)
		
		SET @rCode = sCommon.fSearchStringGet(@rCode)
		SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
		SET @rLastName = sCommon.fSearchStringGet(@rLastName)
	
		SELECT 
				*
		INTO sFee.tTempFee
		FROM sFee.vFeeCustomSearch FCS
		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 ((ISNULL(FCS.EndDate,'9999-12-31') <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
				--AND (FCS.ClassId In( SELECT item FROM  sCommon.fnsplit(@rClassId,','))OR @rClassId=''))
			    
				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 ((FCS.AdmissionCategoryId = @rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
	     
	     
		SET @rColumnName=Replace(@rColumnName,',ID No',',Code')
		SET @rOrderBy=Replace(@rOrderBy,'ID No','Code')
    
		SET @rColumnName=Replace(@rColumnName,',GR No',',Code')
		SET @rOrderBy=Replace(@rOrderBy,'GR No','Code')
		
			
		 
		--SET @rOrderBy=Replace(@rOrderBy,',Code',',Code AS [ID No]')    
		
		
		SET @sql=
		'SELECT '+
		@rColumnName+' 
		FROM sFee.tTempFee ORDER BY '+@rOrderBy
			 
		 --print @sql;
		exec(@Sql)
		
		DROP Table sFee.tTempFee
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		--SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sFee].[pOldFeewiseImportAdd]...';


GO
ALTER PROCEDURE [sFee].[pOldFeewiseImportAdd]
	
	@rOldOrgGroupBatchId int,
	@rNewOrgGroupBatchId int,
	@rOldBatchId int,
	@rNewBatchId int,
	@rOldAdmissionCategoryId int,
	@rNewAdmissionCategoryId int,
	@rOldReceiptBookId int,
	@rNewReceiptBookId int,
	@rOldFeeIds nvarchar(max),
	@rNewFeeId int,
	@rOrgId int,
	@rCreatedUserId bigint,
	@rIdNos nvarchar(max)=''
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
BEGIN TRY 

	DECLARE @lCount int
	-- Old Fee Import Temp Table
	CREATE TABLE #TempOldFeeImport
	(
		[AutoId] int identity,
		[StudentId] bigint NULL ,
		[AcademicId] bigint NULL,
		[PendingAmount] decimal(12,2) NULL
	)
	-- End Old Fee Import Temp Table
	
	
	INSERT INTO #TempOldFeeImport 
	SELECT 
		SA.StudentId,
		SA.AcademicId,
		SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)) AS PendingAmount
  FROM 
  
			 sStudent.vStudentAcademic SA
		INNER JOIN 
		(
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName			 
			FROM sFee.tFeeSetup FS1
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
			AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.AdmissionCategoryId=@rOldAdmissionCategoryId) OR (@rOldAdmissionCategoryId=0))
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOldOrgGroupBatchId
			WHERE 
			    SA1.OrgGroupBatchId = @rOldOrgGroupBatchId
			    AND ((FS1.AdmissionCategoryId=@rOldAdmissionCategoryId) OR (@rOldAdmissionCategoryId=0))
			    AND ((FS1.ReceiptBookId=@rOldReceiptBookId) OR (@rOldReceiptBookId=0))
				AND (FS1.IsOptional=0)
				AND ((FS1.BatchId=@rOldBatchId) OR (@rOldBatchId=0))
				AND ((SA1.BatchId=@rOldBatchId) OR (@rOldBatchId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND FM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit(@rOldFeeIds,','))
				AND (SA1.Code IN (SELECT item from sCommon.fnSplit(@rIdNos, ',')) OR ISNULL(@rIdNos,'')='')
				UNION ALL
				
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName 
				
			FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO
			ON FO.FeeSetupId=FS1.Id
	    INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
			AND ((SA1.AdmissionCategoryId=@rOldAdmissionCategoryId) OR (@rOldAdmissionCategoryId=0))
		INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOldOrgGroupBatchId
		WHERE
		        SA1.OrgGroupBatchId = @rOldOrgGroupBatchId
		        AND ((FS1.AdmissionCategoryId=@rOldAdmissionCategoryId) OR (@rOldAdmissionCategoryId=0))
		        AND ((FS1.ReceiptBookId=@rOldReceiptBookId) OR (@rOldReceiptBookId=0))
				AND (FS1.IsOptional=1)
				AND ((FS1.BatchId=@rOldBatchId) OR (@rOldBatchId=0))
				AND ((SA1.BatchId=@rOldBatchId) OR (@rOldBatchId=0))	
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND FM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit(@rOldFeeIds,','))
				AND (SA1.Code IN (SELECT item from sCommon.fnSplit(@rIdNos, ',')) OR ISNULL(@rIdNos,'')='')
				
		) FS ON FS.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
		LEFT JOIN
		(
		    SELECT 
					ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
		    FROM
				sFee.tReceipt R 
				INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
				INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
				INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId				
				
			WHERE		
				(R.SourceTypeId = 2001)
				AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND (R.IsObsolete = 0) 
				AND ((SA1.OrgGroupBatchId = @rOldOrgGroupBatchId))
				AND (R.OrgGroupBatchId = @rOldOrgGroupBatchId)
				AND ((R.BatchId=@rOldBatchId) OR (@rOldBatchId=0))
				AND FM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit(@rOldFeeIds,','))
				AND (SA1.Code IN (SELECT item from sCommon.fnSplit(@rIdNos, ',')) OR ISNULL(@rIdNos,'')='')
				GROUP BY FeeSetupId,R.SourceId
		) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
				 
	WHERE	
			SA.OrgGroupBatchId = @rOldOrgGroupBatchId
			AND SA.OrgId = @rOrgId 
			AND SA.BatchId=@rOldBatchId
			AND (ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00) -ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00) > 0)
			AND (SA.Code IN (SELECT item from sCommon.fnSplit(@rIdNos, ',')) OR ISNULL(@rIdNos,'')='')
			GROUP BY SA.StudentId,SA.AcademicId
	
	SELECT @lCount = COUNT(AutoId) FROM #TempOldFeeImport
	
	IF EXISTS 
	(
		SELECT 1 FROM sFee.tReceipt R
		INNER JOIN sFee.tReceiptDetail RD ON R.Id = RD.ReceiptId
		INNER JOIN sStudent.vStudentAcademic SA ON R.SourceId = SA.AcademicId AND SA.BatchId = @rNewBatchId
		INNER JOIN sFee.tFeeSetup FS ON FS.Id = RD.FeeSetupId AND FS.ClassId = SA.ClassId AND FS.BatchId = @rNewBatchId
		AND FS.AdmissionCategoryId = @rNewAdmissionCategoryId AND FS.FeeId = @rNewFeeId 
		AND FS.ReceiptBookId = @rNewReceiptBookId
		AND (SA.Code IN (SELECT item from sCommon.fnSplit(@rIdNos, ',')) OR ISNULL(@rIdNos,'')='')
	)
	BEGIN
		SELECT -101 AS Result
		RETURN
	END
	
	BEGIN TRANSACTION
	
	---- Delete Fee Optional
	DELETE FO FROM sFee.tFeeOptional FO 
	INNER JOIN sStudent.tAcademic SA ON FO.SourceId = SA.Id AND SA.BatchId = @rNewBatchId
	INNER JOIN sFee.tFeeSetup FS ON FO.FeeSetupId = FS.Id AND SA.ClassId = FS.ClassId
	INNER JOIN sStudent.vStudentAcademic SA1 ON SA.Id = SA1.AcademicId AND SA1.BatchId = @rNewBatchId
	AND FS.BatchId = @rNewBatchId 
	AND FS.AdmissionCategoryId = @rNewAdmissionCategoryId 
	AND FS.FeeId = @rNewFeeId  
	AND FS.ReceiptBookId = @rNewReceiptBookId
	AND (SA1.Code IN (SELECT item from sCommon.fnSplit(@rIdNos, ',')) OR ISNULL(@rIdNos,'')='')
	INNER JOIN #TempOldFeeImport TOFI ON TOFI.StudentId = SA.StudentId 

	-- Delete Fee Allocation
	DELETE FA FROM sFee.tFeeAllocation FA 
	INNER JOIN sStudent.tAcademic SA ON FA.SourceId = SA.Id AND SA.BatchId = @rNewBatchId
	INNER JOIN sFee.tFeeSetup FS ON FA.FeeSetupId = FS.Id AND SA.ClassId = FS.ClassId
	INNER JOIN sStudent.vStudentAcademic SA1 ON SA.Id = SA1.AcademicId AND SA1.BatchId = @rNewBatchId
	AND FS.BatchId = @rNewBatchId 
	AND FS.AdmissionCategoryId = @rNewAdmissionCategoryId 
	AND FS.FeeId = @rNewFeeId AND FA.FeeSetupId = FS.Id
	AND FS.ReceiptBookId = @rNewReceiptBookId
	AND (SA1.Code IN (SELECT item from sCommon.fnSplit(@rIdNos, ',')) OR ISNULL(@rIdNos,'')='')
	INNER JOIN #TempOldFeeImport TOFI ON TOFI.StudentId = SA.StudentId 

	WHILE (@lCount > 0)
	BEGIN
		DECLARE @lAcademicId bigint = NULL
		DECLARE @lStudentId bigint = NULL
		DECLARE @lClassId int = NULL
		DECLARE @lFeeSetupId int = NULL
		DECLARE @lPendingAmount decimal(12,2)
		
		SELECT @lStudentId = StudentId,@lPendingAmount=PendingAmount FROM #TempOldFeeImport WHERE AutoId = @lCount
		SELECT @lAcademicId = Id, @lClassId=ClassId FROM  sStudent.tAcademic SA WHERE StudentId = @lStudentId AND BatchId = @rNewBatchId
		SELECT @lFeeSetupId = Id FROM sFee.tFeeSetup WHERE  ClassId = @lClassId AND AdmissionCategoryId = @rNewAdmissionCategoryId AND BatchId=@rNewBatchId AND FeeId = @rNewFeeId AND ReceiptBookId = @rNewReceiptBookId
		
		IF @lAcademicId IS NOT NULL AND @lFeeSetupId IS NOT NULL AND @lClassId IS NOT NULL
		BEGIN
			-- Insert Fee Optional
			INSERT INTO sFee.tFeeOptional
			   (
			    FeeSetupId,
			    SourceTypeId,
			    SourceId,
			    BatchId
			   )
				VALUES
			   (
				@lFeeSetupId,
				2001,
				@lAcademicId,
				@rNewBatchId
			   )
			 
				-- Insert Fee Allocation
				INSERT INTO sFee.tFeeAllocation
			   (
			    SourceTypeId,
			    SourceId,
			    FeeSetupId,
			    VariableAmount,
			    DiscountAmount,
			    AdditionalAmount,
			    NotApplicableAmount,
			    Remark,
			    ReferenceTypeId,
			    ReferenceSourceId,
			    CreatedUserId,
			    CreatedDateTime,
			    UpdatedUserId,
			    UpdatedDateTime
			   )
				VALUES
			   (
				2001,
				@lAcademicId,
				@lFeeSetupId,
				@lPendingAmount,
				0,
				NULL,
				NULL,
				'Old Year Pending Fee',
				NULL,
				NULL,
				@rCreatedUserId,
				sCommon.fGetDate(),
				NULL,
				NULL
			   )
		END
		 
		SET @lCount = @lCount -1
	END
	 
	DROP TABLE #TempOldFeeImport
	SELECT 1 AS Result
	COMMIT TRANSACTION
END TRY

BEGIN CATCH 
DROP TABLE #TempOldFeeImport
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
END CATCH	
END
GO
PRINT N'Altering [sFee].[pRptDepositMinusGet]...';


GO
 
ALTER PROCEDURE [sFee].[pRptDepositMinusGet]
          
           @rOrgId int,
           @rBatchId int,
           @rCode nvarchar(20),
           @rOrgGroupBatchId int = 0
AS
SET NOCOUNT ON
BEGIN
SELECT 
		'Student' AS SourceType,
		2003 AS SourceTypeId,
		ISNULL(SA.StudentId,0) as SourceId,
		SA.SUId AS SUId,
		SA.Code as SourceCode,
		SA.Name as StudentName,
		SA.ClassName+'-'+SA.DivisionName as ClassDivisionName,
		SA.RollNo,
--		DA.HostelDepositHeadId,
--		DHM.Title AS DepositHeadName,
		SA.OrgId,
		SA.OrganizationName,
		(D.TotalDeposit - A.TotalAdjustment) AS MinusAmount,
		sA.BatchId
  FROM 		
		sStudent.vStudentAcademic SA
		INNER JOIN
		(SELECT SUM(ISNULL(DA.Amount,0)) AS TotalDeposit,DA.AcademicId FROM sFee.tDepositAdd DA GROUP BY DA.AcademicId  )D 
		ON D.AcademicId=SA.AcademicId
		LEFT JOIN 
		(select SUM(ISNULL(AD.Amount,0)) AS TotalAdjustment,AD.AcademicId   FROM sFee.tDepositAdjustment AD  GROUP BY AD.AcademicId) A 
		ON A.AcademicId=SA.AcademicId
		--INNER JOIN sHostel.tHostelDepositHeadMaster DHM ON DHM.Id = D.HostelDepositHeadId
  WHERE  
       
  	 -- SA.BatchId = @rBatchId 
		 (SA.OrgId=@rOrgId OR @rOrgId=0)
		--AND (DA.DepositHeadId=@rDepositHeadId OR @rDepositHeadId=0)
		--AND ((DA.Amount >= @rFromAmount) OR (@rFromAmount = 0))
		--AND ((DA.Amount <= @rToAmount) OR (@rToAmount = 0))
		--AND ((DA.AdjustmentDate >= @rFromAdjustmentDate) OR (ISNULL(@rFromAdjustmentDate,'') = ''))
		--AND ((DA.AdjustmentDate <= @rToAdjustmentDate) OR (ISNULL(@rToAdjustmentDate,'') = ''))
		AND ((SA.Code=@rCode) OR (ISNULL(@rCode,'')=''))
		AND  (SA.OrgGroupBatchId=@rOrgGroupBatchId OR @rOrgGroupBatchId=0)
		AND  D.TotalDeposit - A.TotalAdjustment < 0 
		  
		
END
GO
PRINT N'Altering [sFee].[pRptFeeReceiptListGet]...';


GO
ALTER PROCEDURE [sFee].[pRptFeeReceiptListGet]  
  @rReportId int=0,  
  @rReceiptBookId int=0,  
  @rAdmissionCategoryId int=0,  
  @rClassId int=0,  
  @rDivisionId int=0,  
  @rFromDate date='',  
  @rToDate date='',  
  @rFromReceiptNo int=0,  
  @rToReceiptNo int=0,  
  @rBatchId int,  
  @rUserId bigint=0,  
  @rBuilder1 nvarchar(max)=0,  
  @rBuilder2 nvarchar(max)=0,  
  @rIsDetail bit=0,  
  @rIsCancel bit=0,  
  @rOrgId int,  
  @rOrgGroupBatchId int,  
  @rStatusId int=0,  
  @rPaytypeId int=0,  
  @rCommonBatch nvarchar(100)='',  
  @rDepartmentId int=0,  
  @rFromRollNo int=0,  
     @rToRollNo int=0,  
     @rCode nvarchar(20),  
     @rIsFilter bit=0,  
     @rIsHeader bit=0,  
     @rCreatedUserName nvarchar(100)='',  
     @rFeeHeadId nvarchar(max) = '',  
     @rIsDisplayOrgGroup bit=0,  
     @rIsDiscount bit = 0,  
     @rFeeId nvarchar(max) = '',  
     @rFilterId int=0,  
     @rCustomGroupId smallint = 0,  
     @rOrgGroupId int=0,  
     @rFeeStatusId int=0,  
     @rFromChequeDate date='',      
  @rToChequeDate date='',      
     @rBankName nvarchar(100)='',  
     @rOrgIds nvarchar(max) = '',  
     @rBankNames nvarchar(max) = '',  
  
  @rFromChequeClearDate Date = '',  
  @rToChequeClearDate Date = '' ,
  @rClassStatusId int=0 ,
  @rPayTypeIds nvarchar(max) = '',
  @rUserAcessUserId bigint = 0,
  @rReceiptBookIds nvarchar(max) = ''
 WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  
      
BEGIN   
   
  BEGIN      
  SET @rBankName = sCommon.fSearchStringGet(@rBankName)      
    END   
	--OR @rReportId=20547
  IF(@rReportId=10138 OR @rReportId=20456)
	BEGIN
		SELECT   
		  @rBuilder1 AS Builder1,  
		  @rBuilder2 AS Builder2,  
		  @rIsDetail AS IsDetail,  
		  (CASE WHEN @rReportId IN (20456,30804) THEN  R.IsObsolete ELSE @rIsCancel END) AS IsCancel,  
		  --@rIsCancel AS IsCancel,  
		  @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.Code,  
		  SA.Name,  
		  ISNULL(PTM.Title,'') AS PayType,  
		  --ISNULL(R.ChequeNo,'') AS ChequeNo,  
		  CASE WHEN ISNULL(R.ChequeNo,'') != '' THEN R.ChequeNo ELSE CONVERT(nvarchar(20),R.PaymentTransactionId) END AS ChequeNo,
		  ISNULL(R.BankName,'') AS BankName,  
		  R.ReceiptAmount,  
		  --R.ReceiptDate,  
		  CASE  WHEN @rReportId = 30611 AND R.ChequeClearDate IS NOT NULL THEN R.ChequeClearDate ELSE R.ReceiptDate END AS ReceiptDate,  
		  R.CreatedUserId,  
		  ISNULL(U.LoginTitle,'') AS UserName,  
		  ISNULL(RBM.Title,'') AS ReceiptBookTitle,  
		  ISNULL(RBM.BankName,'') AS ReceiptBookBank,  
		  ISNULL(RBM.BankAccountNumber,'') AS BankAccountNumber,  
		  ISNULL(R.ReceiptBookId,'0') As ReceiptBookId,  
		  ISNULL((CASE @rReportId WHEN 20461 THEN [sFee].[fReceiptFeeDetailGet](R.Id)  
		   ELSE '' END),'') AS FeeDetail,  
		   R.Remark,  
		   R.DiscountAmount,  
		   ISNULL(RBM.OrderIndex,0) AS ReceiptBookOrderIndex,  
		   SA.OrgId,  
		   SA.OrganizationName,  
		   ISNULL(R.AmountAfterDiscount,0) AS AmountAfterDiscount,  
		   ISNULL(R.CGSTPercentage,0) AS CGSTPercentage,  
		   ISNULL(R.SGSTPercentage,0) AS SGSTPercentage,  
		   ISNULL(R.CGSTAmount,0) AS CGSTAmount,  
		   ISNULL(R.SGSTAmount,0) AS SGSTAmount,  
		   @rCustomGroupId AS CustomGroupId,  
		   SA.OrgGroupBatchId AS BatchId,  
		   SA.BatchName,  
		   R.ChequeDate,  
		   R.ChequeClearDate ,
		   SA.GenderId,
		  0 AS FeeId,
		  '' AS FeeCode,
		  '' AS FeeTitle,
		   0 AS FeeOrderIndex,
		   R.CancelStatusRemark AS CancelRemark
		  FROM   
		   sFee.tReceipt R  
		  --INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id   
		  --INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id  
		  --INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id  
    
		  INNER JOIN sStudent.vStudentAcademic SA  
		   ON SA.AcademicId=R.SourceId AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0)) 

		  --According UserAccess
		  INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id =SA.OrgId
		  INNER JOIN sSecurity.tUserOrganization UO ON UO.OrgId=SA.OrgId AND OM.IsObsolete=0 AND UO.UserId=@rUserAcessUserId  

		  INNER JOIN sFinanceCommon.tPayTypeMaster PTM  
		   ON PTM.Id=R.PayTypeId  
		  INNER JOIN sFee.tReceiptBookMaster RBM   
		   ON RBM.Id=R.ReceiptBookId  
		  
		  --According UserAccess
		  INNER JOIN sSecurity.tUserAccess UA ON UA.SourceId=RBM.Id AND UA.SourceTypeId=2013 AND RBM.IsObsolete=0 AND UA.UserId =@rUserAcessUserId 


		  LEFT JOIN sSecurity.tUser U  
		   ON U.Id=R.CreatedUserId  
		 LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0) AND (SA.OrgGroupBatchId = AR.OrgGroupBatchId))   
			LEFT JOIN  
		 (SELECT AT.SourceId,B.OrgGroupBatchId FROM sTransport.tAssignRoute AT   
			INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId   
			INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT  
			ON RT.SourceId = SA.StudentId   
			AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))    
			AND (SA.OrgGroupBatchId = RT.OrgGroupBatchId)  
		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) OR (@rOrgGroupBatchId = 0))  
		 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 (@rReportId != 20456 
												--OR @rReportId != 30804
				))  OR   
		  ((@rReportId = 20456 OR @rReportId = 30804) AND ((@rFeeStatusId = 0) -- All  
		  OR (@rFeeStatusId = 1 AND R.IsObsolete = 0) -- Valid  
		  OR (@rFeeStatusId = 2 AND R.IsObsolete = 1) -- Cancel  
		  )))  
		 AND (SA.StatusId=@rStatusId OR @rStatusId=0)  
		 AND (SA.ClassStatusId=@rClassStatusId OR @rClassStatusId=0)  
		 AND (R.PayTypeId = @rPaytypeId OR @rPaytypeId=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 ((@rIsDiscount =1 AND R.DiscountAmount!=0) OR (@rIsDiscount=0))  
		 --AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')  
		  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 ((RBM.OrgGroupId=@rOrgGroupId) OR (@rOrgGroupId=0))  
		 AND ((UPPER(R.BankName) like UPPER(@rBankName)) OR(ISNULL(@rBankName,'')=''))  
		 AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')    
		 AND (ISNULL(R.BankName,'') IN( SELECT cast(item as nvarchar(100)) FROM  sCommon.fnsplit(@rBankNames,',')) OR @rBankNames='')   
		 AND ((R.ChequeClearDate>=@rFromChequeClearDate)OR(ISNULL(@rFromChequeClearDate,'')=''))      
		 AND ((R.ChequeClearDate<=@rToChequeClearDate)OR(ISNULL(@rToChequeClearDate,'')=''))
		 AND (ISNULL(R.PayTypeId,0) IN (SELECT cast(item as tinyint) FROM sCommon.fnsplit(@rPayTypeIds,',')) OR @rPayTypeIds='')
		 AND (ISNULL(R.ReceiptBookId,0) IN (SELECT cast(item as int) FROM sCommon.fnsplit(@rReceiptBookIds,',')) OR @rReceiptBookIds='')
  
		 ORDER BY R.ReceiptNumber
	END

	ELSE IF(@rReportId=30866)
	BEGIN
		SELECT   
		  @rBuilder1 AS Builder1,  
		  @rBuilder2 AS Builder2,  
		  @rIsDetail AS IsDetail,  
		  (CASE WHEN @rReportId IN (20456,30804) THEN  R.IsObsolete ELSE @rIsCancel END) AS IsCancel,  
		  --@rIsCancel AS IsCancel,  
		  @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.Code,  
		  SA.Name,  
		  ISNULL(PTM.Title,'') AS PayType,  
		  --ISNULL(R.ChequeNo,'') AS ChequeNo,  
		  CASE WHEN ISNULL(R.ChequeNo,'') != '' THEN R.ChequeNo ELSE CONVERT(nvarchar(20),R.PaymentTransactionId) END AS ChequeNo,
		  ISNULL(R.BankName,'') AS BankName,
		  --R.ReceiptAmount,  
		  RD.Amount AS ReceiptAmount,
		  --R.ReceiptDate,  
		  CASE  WHEN @rReportId = 30611 AND R.ChequeClearDate IS NOT NULL THEN R.ChequeClearDate ELSE R.ReceiptDate END AS ReceiptDate,  
		  R.CreatedUserId,  
		  ISNULL(U.LoginTitle,'') AS UserName,  
		  ISNULL(RBM.Title,'') AS ReceiptBookTitle,  
		  ISNULL(RBM.BankName,'') AS ReceiptBookBank,  
		  ISNULL(RBM.BankAccountNumber,'') AS BankAccountNumber,  
		  ISNULL(R.ReceiptBookId,'0') As ReceiptBookId,  
		  ISNULL((CASE @rReportId WHEN 20461 THEN [sFee].[fReceiptFeeDetailGet](R.Id)  
		   WHEN 30940 THEN [sFee].[fReceiptFeeDetailGet](R.Id) ELSE '' END),'') AS FeeDetail,  
		   R.Remark,  
		   R.DiscountAmount,  
		   ISNULL(RBM.OrderIndex,0) AS ReceiptBookOrderIndex,  
		   SA.OrgId,  
		   SA.OrganizationName,  
		   ISNULL(R.AmountAfterDiscount,0) AS AmountAfterDiscount,  
		   ISNULL(R.CGSTPercentage,0) AS CGSTPercentage,  
		   ISNULL(R.SGSTPercentage,0) AS SGSTPercentage,  
		   ISNULL(R.CGSTAmount,0) AS CGSTAmount,  
		   ISNULL(R.SGSTAmount,0) AS SGSTAmount,  
		   @rCustomGroupId AS CustomGroupId,  
		   SA.OrgGroupBatchId AS BatchId,  
		   SA.BatchName,  
		   R.ChequeDate,  
		   R.ChequeClearDate,
		   FM.Id AS FeeId,
		  FM.Code AS FeeCode,
		  FM.Title AS FeeTitle,
		   FM.OrderIndex AS FeeOrderIndex
		      
		  FROM   
		   sFee.tReceipt R  
		  INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id   
		  INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id  
		  INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id  
		  INNER JOIN sStudent.vStudentAcademic 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.tReceiptBookMaster RBM   
		   ON RBM.Id=R.ReceiptBookId  
		  LEFT JOIN sSecurity.tUser U  
		   ON U.Id=R.CreatedUserId  
		 LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0) AND (SA.OrgGroupBatchId = AR.OrgGroupBatchId))   
			LEFT JOIN  
		 (SELECT AT.SourceId,B.OrgGroupBatchId FROM sTransport.tAssignRoute AT   
			INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId   
			INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT  
			ON RT.SourceId = SA.StudentId   
			AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))    
			AND (SA.OrgGroupBatchId = RT.OrgGroupBatchId)  
		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) OR (@rOrgGroupBatchId = 0))  
		 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 (@rReportId != 20456 OR @rReportId != 30804))  OR   
		  ((@rReportId = 20456 OR @rReportId = 30804) AND ((@rFeeStatusId = 0) -- All  
		  OR (@rFeeStatusId = 1 AND R.IsObsolete = 0) -- Valid  
		  OR (@rFeeStatusId = 2 AND R.IsObsolete = 1) -- Cancel  
		  )))  
		 AND (SA.StatusId=@rStatusId OR @rStatusId=0)  
		 AND (SA.ClassStatusId=@rClassStatusId OR @rClassStatusId=0)  
		 AND (R.PayTypeId = @rPaytypeId OR @rPaytypeId=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 ((@rIsDiscount =1 AND R.DiscountAmount!=0) OR (@rIsDiscount=0))  
		 --AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')  
		  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 ((RBM.OrgGroupId=@rOrgGroupId) OR (@rOrgGroupId=0))  
		 AND ((UPPER(R.BankName) like UPPER(@rBankName)) OR(ISNULL(@rBankName,'')=''))  
		 AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')    
		 AND (ISNULL(R.BankName,'') IN( SELECT cast(item as nvarchar(100)) FROM  sCommon.fnsplit(@rBankNames,',')) OR @rBankNames='')   
		 AND ((R.ChequeClearDate>=@rFromChequeClearDate)OR(ISNULL(@rFromChequeClearDate,'')=''))      
		 AND ((R.ChequeClearDate<=@rToChequeClearDate)OR(ISNULL(@rToChequeClearDate,'')=''))
		 AND (ISNULL(R.PayTypeId,0) IN (SELECT cast(item as tinyint) FROM sCommon.fnsplit(@rPayTypeIds,',')) OR @rPayTypeIds='')  		 
  
		 ORDER BY R.ReceiptNumber  
	END

	ELSE IF(@rReportId=20547)
	BEGIN
		SELECT   
		  @rBuilder1 AS Builder1,  
		  @rBuilder2 AS Builder2,  
		  @rIsDetail AS IsDetail,  
		  (CASE WHEN @rReportId IN (20456,30804) THEN  R.IsObsolete ELSE @rIsCancel END) AS IsCancel,  
		  --@rIsCancel AS IsCancel,  
		  @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.Code,  
		  SA.Name,  
		  ISNULL(PTM.Title,'') AS PayType,  
		  --ISNULL(R.ChequeNo,'') AS ChequeNo,  
		  CASE WHEN ISNULL(R.ChequeNo,'') != '' THEN R.ChequeNo ELSE CONVERT(nvarchar(20),R.PaymentTransactionId) END AS ChequeNo,
		  ISNULL(R.BankName,'') AS BankName,  
		  RD.Amount AS ReceiptAmount,  
		  --R.ReceiptDate,  
		  CASE  WHEN @rReportId = 30611 AND R.ChequeClearDate IS NOT NULL THEN R.ChequeClearDate ELSE R.ReceiptDate END AS ReceiptDate,  
		  R.CreatedUserId,  
		  ISNULL(U.LoginTitle,'') AS UserName,  
		  ISNULL(RBM.Title,'') AS ReceiptBookTitle,  
		  ISNULL(RBM.BankName,'') AS ReceiptBookBank,  
		  ISNULL(RBM.BankAccountNumber,'') AS BankAccountNumber,  
		  ISNULL(R.ReceiptBookId,'0') As ReceiptBookId,  
		  ISNULL((CASE @rReportId WHEN 20461 THEN [sFee].[fReceiptFeeDetailGet](R.Id)  
		   ELSE '' END),'') AS FeeDetail,  
		   R.Remark,  
		   R.DiscountAmount,  
		   ISNULL(RBM.OrderIndex,0) AS ReceiptBookOrderIndex,  
		   SA.OrgId,  
		   SA.OrganizationName,  
		   ISNULL(R.AmountAfterDiscount,0) AS AmountAfterDiscount,  
		   ISNULL(R.CGSTPercentage,0) AS CGSTPercentage,  
		   ISNULL(R.SGSTPercentage,0) AS SGSTPercentage,  
		   ISNULL(R.CGSTAmount,0) AS CGSTAmount,  
		   ISNULL(R.SGSTAmount,0) AS SGSTAmount,  
		   @rCustomGroupId AS CustomGroupId,  
		   SA.OrgGroupBatchId AS BatchId,  
		   SA.BatchName,  
		   R.ChequeDate,  
		   R.ChequeClearDate ,
		   SA.GenderId
		  FROM   
		   sFee.tReceipt R  
		  INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id   
		  INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id  
		  INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id  
    
		  INNER JOIN sStudent.vStudentAcademic SA  
		   ON SA.AcademicId=R.SourceId AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0)) 

		  --According UserAccess
		  INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id =SA.OrgId
		  INNER JOIN sSecurity.tUserOrganization UO ON UO.OrgId=SA.OrgId AND OM.IsObsolete=0 AND UO.UserId=@rUserAcessUserId  

		  INNER JOIN sFinanceCommon.tPayTypeMaster PTM  
		   ON PTM.Id=R.PayTypeId  
		  INNER JOIN sFee.tReceiptBookMaster RBM   
		   ON RBM.Id=R.ReceiptBookId  
		  
		  --According UserAccess
		  INNER JOIN sSecurity.tUserAccess UA ON UA.SourceId=RBM.Id AND UA.SourceTypeId=2013 AND RBM.IsObsolete=0 AND UA.UserId =@rUserAcessUserId 


		  LEFT JOIN sSecurity.tUser U  
		   ON U.Id=R.CreatedUserId  
		 LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0) AND (SA.OrgGroupBatchId = AR.OrgGroupBatchId))   
			LEFT JOIN  
		 (SELECT AT.SourceId,B.OrgGroupBatchId FROM sTransport.tAssignRoute AT   
			INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId   
			INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT  
			ON RT.SourceId = SA.StudentId   
			AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))    
			AND (SA.OrgGroupBatchId = RT.OrgGroupBatchId)  
		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) OR (@rOrgGroupBatchId = 0))  
		 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 (@rReportId != 20456 OR @rReportId != 30804))  OR   
		  ((@rReportId = 20456 OR @rReportId = 30804) AND ((@rFeeStatusId = 0) -- All  
		  OR (@rFeeStatusId = 1 AND R.IsObsolete = 0) -- Valid  
		  OR (@rFeeStatusId = 2 AND R.IsObsolete = 1) -- Cancel  
		  )))  
		 AND (SA.StatusId=@rStatusId OR @rStatusId=0)  
		 AND (SA.ClassStatusId=@rClassStatusId OR @rClassStatusId=0)  
		 AND (R.PayTypeId = @rPaytypeId OR @rPaytypeId=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 ((@rIsDiscount =1 AND R.DiscountAmount!=0) OR (@rIsDiscount=0))  
		 AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')  
		 AND (ISNULL(FM.Id, 0) IN (SELECT CAST(item as int) FROM sCommon.fnsplit(@rFeeId,',')) OR @rFeeId = '')
		 
		  AND (  
		  (@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 ((RBM.OrgGroupId=@rOrgGroupId) OR (@rOrgGroupId=0))  
		 AND ((UPPER(R.BankName) like UPPER(@rBankName)) OR(ISNULL(@rBankName,'')=''))  
		 AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')    
		 AND (ISNULL(R.BankName,'') IN( SELECT cast(item as nvarchar(100)) FROM  sCommon.fnsplit(@rBankNames,',')) OR @rBankNames='')   
		 AND ((R.ChequeClearDate>=@rFromChequeClearDate)OR(ISNULL(@rFromChequeClearDate,'')=''))      
		 AND ((R.ChequeClearDate<=@rToChequeClearDate)OR(ISNULL(@rToChequeClearDate,'')=''))
		 AND (ISNULL(R.PayTypeId,0) IN (SELECT cast(item as tinyint) FROM sCommon.fnsplit(@rPayTypeIds,',')) OR @rPayTypeIds='')
		 AND (ISNULL(R.ReceiptBookId,0) IN (SELECT cast(item as int) FROM sCommon.fnsplit(@rReceiptBookIds,',')) OR @rReceiptBookIds='')
  
		--GROUP BY R.Id,R.IsObsolete,R.ReceiptNumber,SA.ClassId,SA.DivisionId,SA.ClassName,SA.DivisionName,SA.RollNo, SA.Code,SA.Name,PTM.Title,R.ChequeNo,R.PaymentTransactionId
		--  ,R.BankName,R.ReceiptAmount,R.ChequeClearDate,R.ReceiptDate,R.CreatedUserId,U.LoginTitle,RBM.Title,RBM.BankName,RBM.BankAccountNumber,
		--  R.ReceiptBookId,R.Remark,R.DiscountAmount,RBM.OrderIndex,SA.OrgId,SA.OrganizationName,  
		--  R.AmountAfterDiscount,R.CGSTPercentage,R.SGSTPercentage,R.CGSTAmount,R.SGSTAmount,SA.OrgGroupBatchId,
		--  SA.BatchName,R.ChequeDate,R.ChequeClearDate,SA.GenderId

		 ORDER BY R.ReceiptNumber
	END

	ELSE IF(@rReportId=30630)
	BEGIN
	 
	 SELECT   
		  @rBuilder1 AS Builder1,  
		  @rBuilder2 AS Builder2,  
		  @rIsDetail AS IsDetail,  
		  (CASE WHEN @rReportId IN (20456,30804) THEN  R.IsObsolete ELSE @rIsCancel END) AS IsCancel,  
		  --@rIsCancel AS IsCancel,  
		  @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.Code,  
		  SA.Name,  
		  ISNULL(PTM.Title,'') AS PayType,  
		  --ISNULL(R.ChequeNo,'') AS ChequeNo,  
		  CASE WHEN ISNULL(R.ChequeNo,'') != '' THEN R.ChequeNo ELSE CONVERT(nvarchar(20),R.PaymentTransactionId) END AS ChequeNo,
		  ISNULL(R.BankName,'') AS BankName,
		  --R.ReceiptAmount,  
		  A.ReceiptAmount as ReceiptAmount,
		  --R.ReceiptDate,  
		  CASE  WHEN @rReportId = 30611 AND R.ChequeClearDate IS NOT NULL THEN R.ChequeClearDate ELSE R.ReceiptDate END AS ReceiptDate,  
		  R.CreatedUserId,  
		  ISNULL(U.LoginTitle,'') AS UserName,  
		  ISNULL(RBM.Title,'') AS ReceiptBookTitle,  
		  ISNULL(RBM.BankName,'') AS ReceiptBookBank,  
		  ISNULL(RBM.BankAccountNumber,'') AS BankAccountNumber,  
		  ISNULL(R.ReceiptBookId,'0') As ReceiptBookId,  
		  ISNULL((CASE @rReportId WHEN 20461 THEN [sFee].[fReceiptFeeDetailGet](R.Id)  
		   WHEN 30940 THEN [sFee].[fReceiptFeeDetailGet](R.Id) ELSE '' END),'') AS FeeDetail,  
		   R.Remark,  
		   R.DiscountAmount,  
		   ISNULL(RBM.OrderIndex,0) AS ReceiptBookOrderIndex,  
		   SA.OrgId,  
		   SA.OrganizationName,  
		   ISNULL(R.AmountAfterDiscount,0) AS AmountAfterDiscount,  
		   ISNULL(R.CGSTPercentage,0) AS CGSTPercentage,  
		   ISNULL(R.SGSTPercentage,0) AS SGSTPercentage,  
		   ISNULL(R.CGSTAmount,0) AS CGSTAmount,  
		   ISNULL(R.SGSTAmount,0) AS SGSTAmount,  
		   @rCustomGroupId AS CustomGroupId,  
		   SA.OrgGroupBatchId AS BatchId,  
		   SA.BatchName,  
		   R.ChequeDate,  
		   R.ChequeClearDate   
		  FROM   
		   sFee.tReceipt R  
		  --INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id   
		  --INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id  
		  --INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id  
		  INNER JOIN (Select SUM(RD.Amount) AS ReceiptAmount,RD.ReceiptId
					    FROM
						sFee.tReceiptDetail RD
						INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id  
						INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id  
						WHERE (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')  
						AND (ISNULL(FM.Id, 0) IN (SELECT CAST(item as int) FROM sCommon.fnsplit(@rFeeId,',')) OR @rFeeId = '')
						Group By RD.ReceiptId)A ON A.ReceiptId = R.Id
    
		  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.tReceiptBookMaster RBM   
		   ON RBM.Id=R.ReceiptBookId  
		  LEFT JOIN sSecurity.tUser U  
		   ON U.Id=R.CreatedUserId  
		 LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0) AND (SA.OrgGroupBatchId = AR.OrgGroupBatchId))   
			LEFT JOIN  
		 (SELECT AT.SourceId,B.OrgGroupBatchId FROM sTransport.tAssignRoute AT   
			INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId   
			INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT  
			ON RT.SourceId = SA.StudentId   
			AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))    
			AND (SA.OrgGroupBatchId = RT.OrgGroupBatchId)  
		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) OR (@rOrgGroupBatchId = 0))  
		 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 (@rReportId != 20456 OR @rReportId != 30804))  OR   
		  ((@rReportId = 20456 OR @rReportId = 30804) AND ((@rFeeStatusId = 0) -- All  
		  OR (@rFeeStatusId = 1 AND R.IsObsolete = 0) -- Valid  
		  OR (@rFeeStatusId = 2 AND R.IsObsolete = 1) -- Cancel  
		  )))  
		 AND (SA.StatusId=@rStatusId OR @rStatusId=0)  
		 AND (SA.ClassStatusId=@rClassStatusId OR @rClassStatusId=0)  
		 AND (R.PayTypeId = @rPaytypeId OR @rPaytypeId=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 ((@rIsDiscount =1 AND R.DiscountAmount!=0) OR (@rIsDiscount=0))  
		 --AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')  
		  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 ((RBM.OrgGroupId=@rOrgGroupId) OR (@rOrgGroupId=0))  
		 AND ((UPPER(R.BankName) like UPPER(@rBankName)) OR(ISNULL(@rBankName,'')=''))  
		 AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')    
		 AND (ISNULL(R.BankName,'') IN( SELECT cast(item as nvarchar(100)) FROM  sCommon.fnsplit(@rBankNames,',')) OR @rBankNames='')   
		 AND ((R.ChequeClearDate>=@rFromChequeClearDate)OR(ISNULL(@rFromChequeClearDate,'')=''))      
		 AND ((R.ChequeClearDate<=@rToChequeClearDate)OR(ISNULL(@rToChequeClearDate,'')=''))
		 AND (ISNULL(R.PayTypeId,0) IN (SELECT cast(item as tinyint) FROM sCommon.fnsplit(@rPayTypeIds,',')) OR @rPayTypeIds='')  		
		 ORDER BY R.ReceiptNumber  

	END
	ELSE
	BEGIN
		SELECT   
		  @rBuilder1 AS Builder1,  
		  @rBuilder2 AS Builder2,  
		  @rIsDetail AS IsDetail,  
		  (CASE WHEN @rReportId IN (20456,30804) THEN  R.IsObsolete ELSE @rIsCancel END) AS IsCancel,  
		  --@rIsCancel AS IsCancel,  
		  @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.Code,  
		  SA.Name,  
		  ISNULL(PTM.Title,'') AS PayType,  
		  --ISNULL(R.ChequeNo,'') AS ChequeNo,  
		  CASE WHEN ISNULL(R.ChequeNo,'') != '' THEN R.ChequeNo ELSE CONVERT(nvarchar(20),R.PaymentTransactionId) END AS ChequeNo,
		  ISNULL(R.BankName,'') AS BankName,  
		  R.ReceiptAmount,  
		  --R.ReceiptDate,  
		  CASE  WHEN @rReportId = 30611 AND R.ChequeClearDate IS NOT NULL THEN R.ChequeClearDate ELSE R.ReceiptDate END AS ReceiptDate,  
		  R.CreatedUserId,  
		  ISNULL(U.LoginTitle,'') AS UserName,  
		  ISNULL(RBM.Title,'') AS ReceiptBookTitle,  
		  ISNULL(RBM.BankName,'') AS ReceiptBookBank,  
		  ISNULL(RBM.BankAccountNumber,'') AS BankAccountNumber,  
		  ISNULL(R.ReceiptBookId,'0') As ReceiptBookId,  
		  ISNULL((CASE @rReportId WHEN 20461 THEN [sFee].[fReceiptFeeDetailGet](R.Id)  
		   WHEN 30940 THEN [sFee].[fReceiptFeeDetailGet](R.Id) ELSE '' END),'') AS FeeDetail,  
		   R.Remark,  
		   R.DiscountAmount,  
		   ISNULL(RBM.OrderIndex,0) AS ReceiptBookOrderIndex,  
		   SA.OrgId,  
		   SA.OrganizationName,  
		   ISNULL(R.AmountAfterDiscount,0) AS AmountAfterDiscount,  
		   ISNULL(R.CGSTPercentage,0) AS CGSTPercentage,  
		   ISNULL(R.SGSTPercentage,0) AS SGSTPercentage,  
		   ISNULL(R.CGSTAmount,0) AS CGSTAmount,  
		   ISNULL(R.SGSTAmount,0) AS SGSTAmount,  
		   @rCustomGroupId AS CustomGroupId,  
		   SA.OrgGroupBatchId AS BatchId,  
		   SA.BatchName,  
		   R.ChequeDate,  
		   R.ChequeClearDate   
		  FROM   
		   sFee.tReceipt R  
		  --INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id   
		  --INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id  
		  --INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id  
    
		  INNER JOIN sStudent.vStudentAcademic 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.tReceiptBookMaster RBM   
		   ON RBM.Id=R.ReceiptBookId  
		  LEFT JOIN sSecurity.tUser U  
		   ON U.Id=R.CreatedUserId  
		 LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0) AND (SA.OrgGroupBatchId = AR.OrgGroupBatchId))   
			LEFT JOIN  
		 (SELECT AT.SourceId,B.OrgGroupBatchId FROM sTransport.tAssignRoute AT   
			INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId   
			INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT  
			ON RT.SourceId = SA.StudentId   
			AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))    
			AND (SA.OrgGroupBatchId = RT.OrgGroupBatchId)  
		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) OR (@rOrgGroupBatchId = 0))  
		 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 (@rReportId != 20456 OR @rReportId != 30804))  OR   
		  ((@rReportId = 20456 OR @rReportId = 30804) AND ((@rFeeStatusId = 0) -- All  
		  OR (@rFeeStatusId = 1 AND R.IsObsolete = 0) -- Valid  
		  OR (@rFeeStatusId = 2 AND R.IsObsolete = 1) -- Cancel  
		  )))  
		 AND (SA.StatusId=@rStatusId OR @rStatusId=0)  
		 AND (SA.ClassStatusId=@rClassStatusId OR @rClassStatusId=0)  
		 AND (R.PayTypeId = @rPaytypeId OR @rPaytypeId=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 ((@rIsDiscount =1 AND R.DiscountAmount!=0) OR (@rIsDiscount=0))  
		 --AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')  
		  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 ((RBM.OrgGroupId=@rOrgGroupId) OR (@rOrgGroupId=0))  
		 AND ((UPPER(R.BankName) like UPPER(@rBankName)) OR(ISNULL(@rBankName,'')=''))  
		 AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')    
		 AND (ISNULL(R.BankName,'') IN( SELECT cast(item as nvarchar(100)) FROM  sCommon.fnsplit(@rBankNames,',')) OR @rBankNames='')   
		 AND ((R.ChequeClearDate>=@rFromChequeClearDate)OR(ISNULL(@rFromChequeClearDate,'')=''))      
		 AND ((R.ChequeClearDate<=@rToChequeClearDate)OR(ISNULL(@rToChequeClearDate,'')=''))
		 AND (ISNULL(R.PayTypeId,0) IN (SELECT cast(item as tinyint) FROM sCommon.fnsplit(@rPayTypeIds,',')) OR @rPayTypeIds='')  		 
  
		 ORDER BY R.ReceiptNumber  
	END
 
-- 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 [sFee].[pRptFeeStatusCollectionGroupWiseGet]...';


GO

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

CREATE TABLE #TempIsOptional
	(
		FeeId int,  
		Id int,  
		IsOptional bit,  
		IsVariable bit,  
		Amount decimal(12,2),  
		StartDate date,  
		EndDate date,  
		BatchId int,  
		ReceiptBookId int,  
		AcademicId bigint,  
		FeeName nvarchar(100),  
		FeeHeadId int,
		CollectionGroupId int,
		CollectionGroup nvarchar(max)
	)
	
	INSERT INTO #TempIsOptional
		SELECT   
			FS1.FeeId,  
			FS1.Id,  
			ISNULL(FS1.IsOptional,0)AS IsOptional,  
			ISNULL(FS1.IsVariable,0)AS IsVariable,  
			ISNULL(FS1.Amount,0)AS Amount,  
			ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,  
			ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,  
			FS1.BatchId,  
			ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,  
			SA1.Id AS AcademicId,  
			FM.Title AS FeeName,  
			FM.FeeHeadId,
			ISNULL(CGM.Id,0) AS CollectionGroupId,
		    ISNULL(CGM.Title,'') AS CollectionGroup      
		FROM 
			sFee.tFeeSetup FS1  
			INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId   
			INNER JOIN sStudent.tStudentMaster SM ON SA1.StudentId = SM.Id      
			AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId  
			AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))  
			AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))  
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId  
			INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId  
			LEFT JOIN sFee.tCollectionGroupMaster CGM ON FS1.CollectionGroupId=CGM.Id 
			--AND RBM.Id = CGM.ReceiptBookId 
			AND CGM.OrgGroupBatchId = @rOrgGroupBatchId
		WHERE   
			BM.OrgGroupBatchId = @rOrgGroupBatchId  
			AND ((FS1.ClassId=@rClassId) OR (@rClassId=0))      
			AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))  
			AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))  
			AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))  
			AND ((FS1.CollectionGroupId=@rCollectionGroupId) OR (@rCollectionGroupId=0))  
			AND (FS1.IsOptional=0)  
			AND ((BM.Title = @rCommonBatch) OR (@rCommonBatch = ''))  
			AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))  
			AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))      
			AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')  
			AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')  
			AND (ISNULL(CGM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rCollectionGroupId,','))OR @rCollectionGroupId='')  

	UNION ALL  

		SELECT   
			FS1.FeeId,  
			FS1.Id,  
			ISNULL(FS1.IsOptional,0)AS IsOptional,  
			ISNULL(FS1.IsVariable,0)AS IsVariable,  
			ISNULL(FS1.Amount,0)AS Amount,  
			ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,  
			ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,  
			FS1.BatchId,  
			ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,  
			SA1.Id AS AcademicId,  
			FM.Title AS FeeName,  
			FM.FeeHeadId,
			ISNULL(CGM.Id,0) AS CollectionGroupId,
		    ISNULL(CGM.Title,'') AS CollectionGroup       
		FROM 
			sFee.tFeeSetup FS1  
			INNER JOIN sFee.tFeeOptional FO  
			ON FO.FeeSetupId=FS1.Id  
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId  
			INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=FO.SourceId   
			AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.ClassId = FS1.ClassId  
			
			AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))  
			AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))  
			INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId 
			LEFT JOIN sFee.tCollectionGroupMaster CGM ON FS1.CollectionGroupId=CGM.Id 
			--AND RBM.Id = CGM.ReceiptBookId 
			AND CGM.OrgGroupBatchId = @rOrgGroupBatchId 
		WHERE  
			BM.OrgGroupBatchId = @rOrgGroupBatchId  
			AND ((FS1.ClassId=@rClassId) OR (@rClassId=0))  
			AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))  
			AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))  
			AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))  
			AND ((FS1.CollectionGroupId=@rCollectionGroupId) OR (@rCollectionGroupId=0))  
			AND (FS1.IsOptional=1)  
			AND ((BM.Title = @rCommonBatch) OR (@rCommonBatch = ''))  
			AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))  
			AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))      
			AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')  
			AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')  
			AND (ISNULL(CGM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rCollectionGroupId,','))OR @rCollectionGroupId='')  

	CREATE TABLE #TempReceipt
	(
		PaidAmount decimal(12,2),
		FeeSetupId int,
		SourceId bigint  
	)
	
	INSERT INTO #TempReceipt
	SELECT   
		ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId  
	FROM  
		sFee.tReceipt R   
		INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id   
		INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id  
		INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id  
		INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=R.SourceId  
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA1.BatchId     
		AND (SA1.ClassId=@rClassId OR @rClassId=0)   
		AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))  
		AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)  
	WHERE    
		(R.SourceTypeId = 2001)  
		AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))  
		AND (R.IsObsolete = 0)   
		AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId))  
		AND (R.OrgGroupBatchId = @rOrgGroupBatchId)  
		AND (R.ReceiptDate <= @rUptoDate) -- added condition after nes issue on 09/08/2016  
		-- OR (@rOrgGroupBatchId = @rOrgGroupBatchId))  
		AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))  
		AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))  
		AND ((BM.Title = @rCommonBatch) OR (@rCommonBatch = ''))  
		AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')  
		AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')  
	GROUP BY FeeSetupId,R.SourceId  

	CREATE TABLE #PaidPendingCount
	(
		CollectionGroupMasterId int,
		ReceiptBookMasterId int,
		ClassId int,
		AcademicId bigint,
		ToPayAmount decimal(12,2)
	)
	INSERT INTO #PaidPendingCount

			SELECT 
			CGM1.Id,RBM1.Id,S1.ClassId,S1.Id,FAS.ToPayAmount FROM sStudent.tAcademic S1
			INNER JOIN sFee.tFeeAllocationStudent FAS ON FAS.AcademicId=S1.Id  
		    INNER JOIN sFee.tFeeSetup FS ON FAS.FeeSetupId = FS.Id
			INNER JOIN sFee.tReceiptBookMaster RBM1 ON FS.ReceiptBookId=RBM1.Id
			LEFT JOIN sFee.tCollectionGroupMaster CGM1 ON FS.CollectionGroupId=CGM1.Id AND RBM1.Id = CGM1.ReceiptBookId AND CGM1.OrgGroupBatchId = @rOrgGroupBatchId
	
	CREATE TABLE #TempAssignRoute
	(
		SourceId bigint  
	)
	
	INSERT INTO #TempAssignRoute
	SELECT 
		AT.SourceId 
	FROM 
		sTransport.tAssignRoute AT   
		INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId  
		INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))

	SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		@rIsDetail AS IsDetail,
		@rIsFilter As IsFilter,
		@rIsHeader As IsHeader, 
		@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
		SA.AcademicId,
		SA.RollNo,
		SA.Name,
		SA.Code,
		SA.ClassId,
		SA.DivisionId,
		SA.ClassName,
		SA.DivisionName,
		SA.DivisionOrder AS DivisionOrderIndex,
		SA.ClassOrderIndex AS ClassOrderIndex,
		SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
		FS.Id AS FeeSetupId,
		
		ISNULL(FS.IsVariable,0)AS IsVariable,
		ISNULL(FS.Amount,0)AS Amount,
		ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
		ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
		ISNULL(FA.VariableAmount,0.00)AS FAAmount,
		ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
		ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
		ISNULL(FA.NotApplicableAmount,0.00)AS NotApplicableAmount,
		ISNULL(R.PaidAmount,0) AS PaidAmount,
		ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)AS PendingAmount,
		ISNULL(FA.Remark,'') AS Remark,
		FS.ReceiptBookId,
		FS.FeeName,
		SA.OrgId,
		O.DisplayTitle AS OrgName,
		O.OrderIndex AS OrgOrderIndex,
		ISNULL(RBM.Title,'') AS ReceiptBookTitle,
		ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
		SA.DepartmentId,
		SA.DepartmentName,
		SA.ExemptionTypeId,
		ISNULL(ETM.Title,'') AS ExemptionType,
		FHM.Id AS FeeHeadId,
		FHM.Title AS FeeHeadName,
		FHM.OrderIndex AS FeeHeadOrderIndex,
		@rFeeGroupId As FeeGroup,
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Title,'') AS CollectionGroup,
		ISNULL(CGM.OrderIndex,0) AS CollectionGroupOrderIndex,		
		CASE WHEN ROW_NUMBER() OVER (PARTITION BY SA.ClassId  ORDER BY SA.ClassId ) =1 THEN (SELECT COUNT(1) FROM sStudent.tAcademic A INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId WHERE A.ClassId= SA.ClassId AND A.BatchId = SA.BatchId  AND A.OrgId = SA.OrgId AND BM.OrgGroupBatchId = SA.OrgGroupBatchId GROUP BY ClassId) ELSE 0 END AS StudentCount,
		--CASE WHEN ROW_NUMBER() OVER (PARTITION BY SA.AcademicId  ORDER BY SA.AcademicId) =1 THEN (CASE WHEN (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)) > 0) THEN 1 ELSE 0 END) ELSE 0 END AS PendingAmount

		--( SELECT SUM(T.PaidCount) FROM 
		--(SELECT 
		--	COUNT(DISTINCT(S1.Id)) AS PaidCount FROM sStudent.tAcademic S1
		--	INNER JOIN sFee.tFeeAllocationStudent FAS ON FAS.AcademicId=S1.Id  
		-- INNER JOIN sFee.tFeeSetup FS ON FAS.FeeSetupId = FS.Id
		--INNER JOIN sFee.tReceiptBookMaster RBM1 ON FS.ReceiptBookId=RBM1.Id
		--LEFT JOIN sFee.tCollectionGroupMaster CGM1 ON FS.CollectionGroupId=CGM1.Id AND RBM1.Id = CGM1.ReceiptBookId AND CGM1.OrgGroupBatchId = @rOrgGroupBatchId
		--WHERE (CGM1.Id = CGM.Id OR ISNULL(CGM.Id,0) = 0) AND RBM1.Id = RBM.Id AND S1.ClassId = SA.ClassId
		--GROUP BY S1.Id
		--HAVING SUM(ISNULL(FAS.ToPayAmount,0.00)) = 0 
		--) T )			
		--	AS PaidCount,
		--( SELECT SUM(T.PendingCount) FROM 
		--(SELECT 
		--	COUNT(DISTINCT(S1.Id)) AS PendingCount FROM sStudent.tAcademic S1
		--	INNER JOIN sFee.tFeeAllocationStudent FAS ON FAS.AcademicId=S1.Id  
		-- INNER JOIN sFee.tFeeSetup FS ON FAS.FeeSetupId = FS.Id
		--INNER JOIN sFee.tReceiptBookMaster RBM1 ON FS.ReceiptBookId=RBM1.Id
		--LEFT JOIN sFee.tCollectionGroupMaster CGM1 ON FS.CollectionGroupId=CGM1.Id AND RBM1.Id = CGM1.ReceiptBookId AND CGM1.OrgGroupBatchId = @rOrgGroupBatchId
		--WHERE (CGM1.Id = CGM.Id OR ISNULL(CGM.Id,0) = 0) AND RBM1.Id = RBM.Id AND S1.ClassId = SA.ClassId
		--GROUP BY S1.Id
		--HAVING SUM(ISNULL(FAS.ToPayAmount,0.00)) > 0 
		--) T )			
		--	AS PendingCount,
	    --Comment PaidCount and PendingCount due to performance issue and create 2 temp table #PaidPendingCount and #TempAssignRoute--26/05/2023
		(SELECT COUNT(distinct(AcademicId)) FROM #PaidPendingCount WHERE ClassId = SA.ClassId AND ReceiptBookMasterId = RBM.Id AND CollectionGroupMasterId = CGM.Id AND ISNULL(ToPayAmount,0.00) = 0) AS PaidCount,
		(SELECT COUNT(distinct(AcademicId)) FROM #PaidPendingCount WHERE ClassId = SA.ClassId AND ReceiptBookMasterId = RBM.Id AND CollectionGroupMasterId = CGM.Id AND ISNULL(ToPayAmount,0.00) > 0) AS PendingCount,
		ISNULL(SC.PresentStreetOne,'')+' '+ISNULL(SC.PresentStreetTwo,'')+' '+ISNULL(SC.PresentStreetThree,'')+' '+ISNULL(SC.PresentCity,'')+' '+ISNULL(SC.PresentState,'') AS [Address],
		ISNULL(SF.FatherContactNo,'')AS FatherContactNo,
		ISNULL(SF.MotherContactNo,'')AS MotherContactNo
		--CGM.Id,
		--RBM.Id,
		--SA.ClassId

		--( SELECT SUM(T.PaidCount) FROM (SELECT 
		--	COUNT(DISTINCT(S1.AcademicId)) AS PaidCount FROM sStudent.vStudentAcademic S1
		--	INNER JOIN 
		--	(
		--		SELECT 
		--			FS1.FeeId,
		--			FS1.Id,
		--			ISNULL(FS1.IsOptional,0)AS IsOptional,
		--			ISNULL(FS1.IsVariable,0)AS IsVariable,
		--			ISNULL(FS1.Amount,0)AS Amount,
		--			ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
		--			ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
		--			FS1.BatchId,
		--			ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
		--			SA1.AcademicId,				 
		--			FS1.CollectionGroupId
		--		FROM sFee.tFeeSetup FS1
		--		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
		--		AND ((SA1.ClassId=@rClassId) OR (@rClassId=0))
		--		AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))			
		--		WHERE 
		--			((FS1.ClassId=@rClassId) OR (@rClassId=0))
		--			AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
		--			AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
		--			AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
		--			AND (FS1.IsOptional=0)
		--			AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
		--			AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
		--			AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
		--			AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))			 
		--			--AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
		--			UNION ALL
				
		--		SELECT 
		--			FS1.FeeId,
		--			FS1.Id,
		--			ISNULL(FS1.IsOptional,0)AS IsOptional,
		--			ISNULL(FS1.IsVariable,0)AS IsVariable,
		--			ISNULL(FS1.Amount,0)AS Amount,
		--			ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
		--			ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
		--			FS1.BatchId,
		--			ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
		--			SA1.AcademicId,				 
		--			FS1.CollectionGroupId
		--		FROM sFee.tFeeSetup FS1
		--	INNER JOIN sFee.tFeeOptional FO
		--		ON FO.FeeSetupId=FS1.Id 
		--	--INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		--	INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId
		--	AND FS1.BatchId = SA1.BatchId AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
		--		AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) 
		--	AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
		--WHERE
		--			((FS1.ClassId=@rClassId) OR (@rClassId=0))
		--			AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
		--		AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
		--		AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
		--		AND (FS1.IsOptional=1)
		--		AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
		--		AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
		--		AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
		--		AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))							
		--	) FS ON FS.AcademicId=S1.AcademicId
		--	LEFT JOIN sFee.tFeeAllocation FA
		--		ON FA.FeeSetupId=FS.Id AND FA.SourceId=S1.AcademicId
		--	LEFT JOIN
		--	(
		--		SELECT 
		--				ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
		--		FROM
		--				sFee.tReceipt R 
		--			INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
		--			INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
		--			INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
		--			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId 
		--			AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
		--			AND (SA1.ClassId=@rClassId OR @rClassId=0) 
		--			AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
		--		WHERE		
		--			(R.SourceTypeId = 2001)
		--		AND (R.IsObsolete = 0) 
		--		AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
		--		AND (SA1.OrgGroupBatchId = @rOrgGroupBatchId)
		--		AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
		--		AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
		--		AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
		--		AND (R.ReceiptDate <= @rUptoDate)
		--			AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit('',','))OR ''='')
		--			AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit('',','))OR ''='')
		--			--AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
		--				GROUP BY FeeSetupId,R.SourceId
		
		--	) R ON R.FeeSetupId = FS.Id AND S1.AcademicId = R.SourceId
		--	INNER JOIN sFee.tReceiptBookMaster RBM1
		--		ON FS.ReceiptBookId=RBM.Id
		--	LEFT JOIN sFee.tCollectionGroupMaster CGM1
		--		ON FS.CollectionGroupId=CGM1.Id AND RBM1.Id = CGM1.ReceiptBookId AND CGM1.OrgGroupBatchId = @rOrgGroupBatchId
		--	WHERE (CGM1.Id = CGM.Id OR ISNULL(CGM.Id,0) = 0) AND RBM1.Id = RBM.Id AND S1.ClassId = SA.ClassId
		--	GROUP BY S1.AcademicId
		--HAVING 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)) = 0 
		--) T )			
		--	AS PaidCount,

		--	( SELECT SUM(T.PendingCount) FROM (SELECT 
		--	COUNT(DISTINCT(S1.AcademicId)) AS PendingCount FROM sStudent.vStudentAcademic S1
		--	INNER JOIN 
		--	(
		--		SELECT 
		--			FS1.FeeId,
		--			FS1.Id,
		--			ISNULL(FS1.IsOptional,0)AS IsOptional,
		--			ISNULL(FS1.IsVariable,0)AS IsVariable,
		--			ISNULL(FS1.Amount,0)AS Amount,
		--			ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
		--			ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
		--			FS1.BatchId,
		--			ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
		--			SA1.AcademicId,				 
		--			FS1.CollectionGroupId
		--		FROM sFee.tFeeSetup FS1
		--		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
		--		AND ((SA1.ClassId=@rClassId) OR (@rClassId=0))
		--		AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))			
		--		WHERE 
		--			((FS1.ClassId=@rClassId) OR (@rClassId=0))
		--			AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
		--			AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
		--			AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
		--			AND (FS1.IsOptional=0)
		--			AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
		--			AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
		--			AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
		--			AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))			 
		--			--AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
		--			UNION ALL
				
		--		SELECT 
		--			FS1.FeeId,
		--			FS1.Id,
		--			ISNULL(FS1.IsOptional,0)AS IsOptional,
		--			ISNULL(FS1.IsVariable,0)AS IsVariable,
		--			ISNULL(FS1.Amount,0)AS Amount,
		--			ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
		--			ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
		--			FS1.BatchId,
		--			ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
		--			SA1.AcademicId,				 
		--			FS1.CollectionGroupId
		--		FROM sFee.tFeeSetup FS1
		--	INNER JOIN sFee.tFeeOptional FO
		--		ON FO.FeeSetupId=FS1.Id 
		--	--INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		--	INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId
		--	AND FS1.BatchId = SA1.BatchId AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
		--		AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) 
		--	AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
		--WHERE
		--			((FS1.ClassId=@rClassId) OR (@rClassId=0))
		--			AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
		--		AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
		--		AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
		--		AND (FS1.IsOptional=1)
		--		AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
		--		AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
		--		AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
		--		AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))							
		--	) FS ON FS.AcademicId=S1.AcademicId
		--	LEFT JOIN sFee.tFeeAllocation FA
		--		ON FA.FeeSetupId=FS.Id AND FA.SourceId=S1.AcademicId
		--	LEFT JOIN
		--	(
		--		SELECT 
		--				ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
		--		FROM
		--				sFee.tReceipt R 
		--			INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
		--			INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
		--			INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
		--			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId 
		--			AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
		--			AND (SA1.ClassId=@rClassId OR @rClassId=0) 
		--			AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
		--		WHERE		
		--			(R.SourceTypeId = 2001)
		--		AND (R.IsObsolete = 0) 
		--		AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
		--		AND (SA1.OrgGroupBatchId = @rOrgGroupBatchId)
		--		AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
		--		AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
		--		AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
		--		AND (R.ReceiptDate <= @rUptoDate)
		--			AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit('',','))OR ''='')
		--			AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit('',','))OR ''='')
		--			--AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
		--				GROUP BY FeeSetupId,R.SourceId
		
		--	) R ON R.FeeSetupId = FS.Id AND S1.AcademicId = R.SourceId
		--	INNER JOIN sFee.tReceiptBookMaster RBM1
		--		ON FS.ReceiptBookId=RBM.Id
		--	LEFT JOIN sFee.tCollectionGroupMaster CGM1
		--		ON FS.CollectionGroupId=CGM1.Id AND RBM1.Id = CGM1.ReceiptBookId AND CGM1.OrgGroupBatchId = @rOrgGroupBatchId
		--	WHERE (CGM1.Id = CGM.Id OR ISNULL(CGM.Id,0) = 0) AND RBM1.Id = RBM.Id AND S1.ClassId = SA.ClassId
		--	GROUP BY S1.AcademicId
		--HAVING 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)) > 0 
		--) T )			
		--	AS PendingCount



  FROM 
  
	    sStudent.vStudentAcademic SA
		INNER JOIN sStudent.tStudentCommunication SC ON SC.StudentId=SA.StudentId
		LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SA.StudentId
		INNER JOIN #TempIsOptional FS ON FS.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
		LEFT JOIN #TempReceipt R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
		INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
		INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
		LEFT JOIN sFee.tCollectionGroupMaster CGM ON FS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId AND CGM.OrgGroupBatchId = @rOrgGroupBatchId
		INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FS.FeeHeadId	
		LEFT JOIN sFee.tExemptionTypeMaster ETM ON ETM.Id = SA.ExemptionTypeId
		LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
		LEFT JOIN #TempAssignRoute RT ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))
 --       LEFT JOIN
	--(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
 --   INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
 --   INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
    --ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
	WHERE	
	((@rIsExemption = 0 AND  1 = 1) OR (@rIsExemption = 1  AND  ISNULL(FA.DiscountAmount,0) > 0))
    AND	((SA.BatchId=@rBatchId) OR (@rBatchId=0))   
    AND	((SA.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))   
    AND (SA.StatusId=@rStatusId OR @rStatusId=0)
	--AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
	AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
	AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
	AND ((SA.Code=@rCode) OR (@rCode=''))
	AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))		
	AND ((SA.ExemptionTypeId=@rExemptionTypeId) OR (@rExemptionTypeId=0))		
	AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
	AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
	AND	((CGM.Id=@rCollectionGroupId) OR (@rCollectionGroupId=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 ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))
    --AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')			     
			Order by SA.RollNo
			

	DROP TABLE #TempIsOptional
	DROP TABLE #TempReceipt
	DROP TABLE #PaidPendingCount
	DROP TABLE #TempAssignRoute
	--SELECT 
	--	'' AS Builder1,
	--	'' AS Builder2,
	--	'' AS IsDetail,
	--	'' As IsFilter,
	--	'' As IsHeader, 
	--	'' AS IsDisplayOrgGroup,
	--	0 AS AcademicId,
	--	0 AS RollNo,
	--	'' AS Name,
	--	'' AS Code,
	--	0 AS ClassId,
	--	0 AS DivisionId,
	--	'' AS ClassName,
	--	'' AS DivisionName,
	--	0  AS DivisionOrderIndex,
	--	0 AS ClassOrderIndex,
	--	'' AS ClassDivision,
	--	0 AS FeeSetupId,
		
	--	0 AS IsVariable,
	--	0 AS Amount,
	--	'' AS StartDate,
	--	'' AS EndDate,
	--	0 AS FAAmount,
	--	0 AS DiscountAmount,
	--	0 AS AdditionalAmount,
	--	0 AS NotApplicableAmount,
	--	0 AS PaidAmount,
	--	0 AS PendingAmount,
	--	'' AS Remark,
	--	0 AS ReceiptBookId,
	--	'' AS FeeName,
	--	0 AS OrgId,
	--	'' AS OrgName,
	--	0 AS OrgOrderIndex,
	--	'' AS ReceiptBookTitle,
	--	0 AS ReceiptOrderIndex,
	--	0 AS DepartmentId,
	--	'' AS DepartmentName,
	--	0 AS ExemptionTypeId,
	--	'' AS ExemptionType,
	--	0 AS FeeHeadId,
	--	'' AS FeeHeadName,
	--	0 AS FeeHeadOrderIndex,
	--	0 As FeeGroup,
	--	0 AS CollectionGroupId,
	--	'' AS CollectionGroup,
	--	0 AS CollectionGroupOrderIndex,		
	--	0 AS StudentCount,
	--	0 AS PaidCount,
	--	0 AS PendingCount,
	--	'' AS Address,
	--	'' AS FatherContactNo,
	--	'' AS MotherContactNo
				

END
GO
PRINT N'Altering [sFrontOffice].[pStudentGatePassGet]...';


GO
ALTER PROCEDURE [sFrontOffice].[pStudentGatePassGet]
          
           @rId int,
           @rOrgId int=0,
           @rFromGatePassDate datetime='',
           @rToGatePassDate datetime='',
           @rEntryModeStatusId smallint=0,
           @rCode nvarchar(20)='',
           @rIsPrintView bit=0,
           @rOrgGroupId int=0,
           @rUserId bigint= 0,
		   @rDepartmentId int=0,
		   @rClassId int=0,
		   @rDivisionId int=0
AS
SET NOCOUNT ON
BEGIN
		Declare @GatePassConfig nvarchar(20)=''
		SELECT @GatePassConfig =ItemValue From sConfig.tConfigurationSetup WHERE ConfigurationId = 241 AND SourceId = @rOrgGroupId
		
		SELECT  
			SGP.Id,
			vSA.Code,
			vSA.FirstName+' '+vSA.MiddleName+' '+vSA.LastName AS Name,
			VSA.ClassName+' - '+VSA.DivisionName AS Class,
			SGP.AcademicId,
			ISNULL(SGP.RelationshipId,0) AS RelationshipId,
			RM.Title AS Relationship,
			SGP.Relation,
			SGP.VisitorName,
			ISNULL(SGP.VisitorMobile,0) As VisitorMobile,
			SGP.ReasonOfGatePass,
			(CASE  WHEN @rIsPrintView=1 THEN 
				SGP.VisitorPhoto		
			ELSE ISNULL(SGP.VisitorPhoto, CONVERT(VARBINARY(MAX), 0)) END) AS VisitorPhoto,
			--ISNULL(SGP.VisitorPhoto, CONVERT(VARBINARY(MAX), 0)) AS VisitorPhoto,
			ISNULL(SGP.GatePassDate,'') As GatePassDate,
			ISNULL(SGP.ReturnGatePassDate,'') As ReturnGatePassDate,
			ISNULL(SGP.GatePassTime,'') As GatePassTime,
			ISNULL(SGP.ReturnGatePassTime,'') As ReturnGatePassTime,
			ISNULL(SGP.EntryModeStatusId,0) AS EntryModeStatusId,
			ISNULL(SM.Title,'')  AS EntryModeStatus,
			OM.Id AS OrgId,
			OM.OrgLogo,
			OM.DisplayTitle AS Organization,
			(CASE  WHEN @rIsPrintView=1 THEN 
				SI.StudentPhoto		
			ELSE ISNULL(SI.StudentPhoto, CONVERT(VARBINARY(MAX), 0)) END) AS StudentPhoto,
			
			(CASE  WHEN @rIsPrintView=1 THEN 
				SI.FatherPhoto		
			ELSE ISNULL(SI.FatherPhoto, CONVERT(VARBINARY(MAX), 0)) END) AS FatherPhoto,
			
			(CASE  WHEN @rIsPrintView=1 THEN 
				SI.MotherPhoto		
			ELSE ISNULL(SI.MotherPhoto, CONVERT(VARBINARY(MAX), 0)) END) AS MotherPhoto,
			
			(CASE  WHEN @rIsPrintView=1 THEN 
				SI.RelativePhoto		
			ELSE ISNULL(SI.RelativePhoto, CONVERT(VARBINARY(MAX), 0)) END) AS RelativePhoto,
			
			--ISNULL(SI.StudentPhoto, CONVERT(VARBINARY(MAX), 0)) AS StudentPhoto,
			ISNULL(U.DisplayTitle,'') AS UserName,
			vSA.SUId,
			Remark,
			@GatePassConfig AS ConfigValue,
				
			SF.FatherContactNo,
			SF.MotherContactNo,
			SF.RelativeContactNo,
			SF.FatherName,
			SF.MotherName,
			SF.RelativeName,
			ISNULL(SGP.GatePassNo,0)AS GatePassNo
		FROM 
		    sStudent.vStudentAcademic vSA
			INNER JOIN sFrontOffice.tStudentGatePass SGP ON SGP.AcademicId = vSA.AcademicId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=vSA.OrgId
			INNER JOIN sCommon.tRelationshipMaster RM ON RM.Id=SGP.RelationshipId
			INNER JOIN sCommon.tStatusMaster SM ON SM.Id=SGP.EntryModeStatusId			
			INNER JOIN sSecurity.tUserOrganization UO ON UO.OrgId = SGP.OrgId AND UO.UserId = @rUserId
			LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=vSA.StudentId
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SI.StudentId
			LEFT JOIN sSecurity.tUser U	ON U.Id=SGP.CreatedUserId
			
		WHERE 
		  ((SGP.Id=@rId) OR (@rId=0))
			AND ((SGP.OrgId=@rOrgId) OR (@rOrgId=0))
			AND ((SGP.GatePassDate>=@rFromGatePassDate) OR (ISNULL(@rFromGatePassDate,'')=''))
			AND ((SGP.GatePassDate<=@rToGatePassDate) OR (ISNULL(@rToGatePassDate,'')=''))
			AND ((SGP.EntryModeStatusId=@rEntryModeStatusId) OR (@rEntryModeStatusId=0))
			AND ((vSA.Code=@rCode) OR (ISNULL(@rCode,'')=''))
			AND (OM.OrgGroupId=@rOrgGroupId)
			AND ((vSA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
			AND ((vSA.ClassId=@rClassId) OR (@rClassId=0))
			AND ((vSA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			--AND vSA.IsActiveBatch=1
			ORDER BY SGP.GatePassDate,SGP.GatePassTime DESC
			
END
GO
PRINT N'Altering [sHrm].[pLeaveTypeGradeSeetingListGet]...';


GO

ALTER PROCEDURE [sHrm].[pLeaveTypeGradeSeetingListGet]
    @rEmployeeGradeId int = 0,
    @rOrgId int
AS
SET NOCOUNT ON

BEGIN
       
       SELECT 
				 LTM.Id AS LeaveTypeId,
				 LTM.Title AS LeaveType,
				 ISNULL(LTGS.EmployeeGradeId,0) AS EmployeeGradeId,
				 ISNULL(LTGS.NoOfLeave,'') AS NoOFLeave,
				 ISNULL(LTGS.MaxInMonth,0) AS MaxInMonth,
				 LTGS.LeaveTypeId --,
				 --Isnull(LTGS.LeaveCarryForwordRuleId,1) AS LeaveCarryForwordRuleId
       FROM 
			   sHrm.tLeaveTypeMaster LTM 
		   LEFT JOIN sHrm.tLeaveTypeGradeSettings LTGS ON LTGS.LeaveTypeId = LTM.Id AND EmployeeGradeId = @rEmployeeGradeId
       WHERE 
			   LTM.IsObsolete = 0
			AND LTM.OrgId = @rOrgId   AND IsLWP = 0
END
GO
PRINT N'Altering [sHrm].[pLeaveTypeGradeSettingAdd]...';


GO
ALTER PROCEDURE [sHrm].[pLeaveTypeGradeSettingAdd]
           
           @rLeaveTypeId int,
           @rEmployeeGradeId int,
           @rNoOfLeave int,
           @rMaxInMonth decimal(5,2),          
           @rOrgId smallint--,
		  -- @rLeaveCarryForwordRuleId int=1
        
AS
SET NOCOUNT ON

BEGIN

	BEGIN TRY
	
	BEGIN TRANSACTION

	DECLARE @lNextNumber bigint	  
	
	IF EXISTS(SELECT 1 FROM sHrm.tLeaveTypeGradeSettings WHere LeaveTypeId = @rLeaveTypeId AND OrgId = @rOrgId AND EmployeeGradeId = @rEmployeeGradeId)
	DELETE FROM sHrm.tLeaveTypeGradeSettings WHere LeaveTypeId = @rLeaveTypeId AND OrgId = @rOrgId AND EmployeeGradeId = @rEmployeeGradeId
	
	BEGIN		     
		   INSERT INTO [sHrm].[tLeaveTypeGradeSettings]
           (
            [OrgId]
           ,[LeaveTypeId]
           ,[EmployeeGradeId]
           ,[NoOfLeave]
           ,[MaxInMonth]
		   --,[LeaveCarryForwordRuleId]
           )
     VALUES
           (
            @rOrgId
           ,@rLeaveTypeId
           ,@rEmployeeGradeId
           ,@rNoOfLeave
           ,@rMaxInMonth
		   --,@rLeaveCarryForwordRuleId
           )		 
          END
	   SELECT 1 AS Result	   
	   COMMIT TRANSACTION
	   		
	END TRY	
	BEGIN CATCH
		ROLLBACK TRANSACTION
		SELECT -1 AS RESULT
	END CATCH
	
END
GO
PRINT N'Altering [sHrm].[pStaffCountDashboardGet]...';


GO
 
ALTER PROCEDURE [sHrm].[pStaffCountDashboardGet]
	 
	 @rTypeId smallint,
	 @rOrgGroupId int = 0,
	 @rOrgId int = 0,
	 @rDepartmentId int = 0,
	 @rCommonOrgGroupBatchId int = 0	 
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	IF (@rTypeId=1)
	BEGIN
		 
	SELECT     
		OGM.Id AS OrgGroupId,
		OGM.Title AS OrgGroupTitle,
		EDM.Title AS Designation,
		COUNT(ISNULL(EM.Id, 0)) AS StaffCount
	FROM sHrm.tEmployeeMaster EM 
		INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
		INNER JOIN sHrm.tEmployeeDesignationMaster EDM  ON EDM.Id = EJD.EmployeeDesignationId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgID
		INNER JOIN sSetup.tOrgGroupMaster OGM ON OM.OrgGroupId = OGM.Id
		INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGM.Id
		INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId 
	
	WHERE 
					 
		(OGM.Id=@rOrgGroupId OR @rOrgGroupId=0) 
		AND COGBM.Id = @rCommonOrgGroupBatchId
		AND EDM.IsObsolete = 0
		AND EM.StatusId = 7
		And ISNULL(OGM.IsObsolete,0) = 0
	
	GROUP BY OGM.Id, OGM.Title, EDM.Title
			 
	END
END
GO
PRINT N'Altering [sLibrary].[pBookMasterGet]...';


GO

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


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

	 
	SELECT @quer='SELECT BM.Code,
	BM.Title,
	ISNULL(BM.Publisher,'''')AS Publisher,
	ISNULL(BM.Supplier,'''')AS Supplier,
	ISNULL(BM.Author,'''')AS Author,
	ISNULL(BM.BookSubject,'''') AS BookSubject,
	ISNULL(BM.BookLanguage,'''') AS BookLanguage,
	ISNULL(BM.Location,'''') AS Location,
	ISNULL(BM.Edition,'''')AS Edition,
	ISNULL(BM.ISBNNumber,'''') AS ISBNNumber,
	ISNULL(BM.Price,0) AS Price,
	ISNULL(BM.Currency,'''') AS Currency,
	ISNULL(BM.BookTag,'''')AS BookTag,
	ISNULL(BM.BookCustomTag,'''') AS BookCustomTag,
	ISNULL(BM.BookDepartment,'''') AS BookDepartment,
	ISNULL(BM.ClassNumber,'''') AS ClassNumber,
	ISNULL(BM.BookVolume,1) AS BookVolume,
	ISNULL(BM.NoOfCopies,1) AS NoOfCopies,
	SM.Title AS StatusName,
	BM.Id,
	ISNULL(AGM.Id,0)AS BookAgeGroupId,
	ISNULL(RTM.Id,0) AS ResourceTypeId,
	BM.CreatedUserId,
	ISNULL(U1.DisplayTitle,'''') AS CreatedUserName ,
	BM.CreatedDateTime,
	ISNULL(BM.UpdatedUserId,0) AS UpdatedUserId,
	ISNULL(U2.DisplayTitle,'''') AS UpdatedUserName ,
	ISNULL(BM.UpdatedDateTime,'''') AS UpdatedDateTime,
	BM.LibraryId,
	ISNULL(LM.Title,'''') AS LibraryName,
	SM.Id AS StatusId,
	BM.ClassificationNo,
	BM.AccessionNo,
	ISNUll(BM.NoOfPages,0) AS NoOfPages,
	 ISNULL(BM.PurchaseDate,''0001/01/01'') AS PurchaseDate,
    ISNUll(BM.BookRemark,'''') AS BookRemark,
    ISNULL(BM.BillNumber,'''') AS BillNumber,
    BM.YearOfPublication,
    ISNULL(BM.BookEntryDate,''0001/01/01'') AS BookEntryDate,
    CASE WHEN ' + convert(varchar,@rShowWithPhotoId) + '= 1 Then ISNULL(BM.BookImage, CONVERT(VARBINARY(MAX), 0)) ELSE BM.BookImage END AS BookPicture,
    ISNULL(BM.BookGroup1Id,0) AS BookGroup1Id,
    ISNULL(BM.BookGroup2Id,0) AS BookGroup2Id,
	ISNULL(BM.OrderIndex,0) AS OrderIndex 
	
	
	
    

	FROM 
         sLibrary.tBookMaster BM
         LEFT JOIN sLibrary.tBookAgeGroupMaster AGM ON BM.BookAgeGroupId=AGM.Id
         INNER JOIN sLibrary.tResourceTypeMaster RTM ON BM.ResourceTypeId=RTM.Id
         INNER JOIN sLibrary.tBookLog BL ON BL.ResourceSourceId = BM.Id AND IsCurrentStatus=1
         INNER JOIN sCommon.tStatusMaster SM ON SM.Id=BL.StatusId 
		 INNER JOIN sLibrary.tLibraryMaster LM ON LM.Id = BM.LibraryId
		 INNER JOIN sSecurity.tUser U1 ON U1.Id = BM.CreatedUserId
		 Left JOIN sSecurity.tUser U2 ON U2.Id = BM.UpdatedUserId
		  
         
         WHERE ((BM.Id = ' + convert(varchar,@lId) + ') OR (' + convert(varchar,@lId) + ' = 0))
	AND ((BM.Code = ''' + @lCode + ''') OR (''' + @lCode + ''' = ''''))
	AND ((BM.Title like N''' + @lTitle + ''') OR (''' + @lTitle + ''' = '''')) 
	AND ((BM.AccessionNo like ''' + @lAccession + ''') OR (''' + @lAccession + ''' = '''')) 
	AND ((BM.Publisher like N''' + @lPublisher + ''') OR (''' + @lPublisher + ''' = '''')) 
	AND ((BM.Supplier like ''' + @lSupplier + ''') OR (''' + @lSupplier + ''' = '''')) 
	AND ((BM.Author like N''' + @lAuthor + ''') OR (''' + @lAuthor + ''' = '''')) 
	AND ((BM.BookSubject like N''' + @lSubject + ''') OR (''' + @lSubject + ''' = ''''))  
	AND ((BM.BookLanguage like N''' + @lLanguage + ''') OR (''' + @lLanguage + ''' = ''''))  
	AND ((BM.Location like ''' + @lLocation + ''') OR (''' + @lLocation + ''' = ''''))  
	AND ((BM.Edition like ''' + @lEdition + ''') OR (''' + @lEdition + ''' = ''''))  
	AND ((BM.ISBNNumber like ''' + @lISBNNumber + ''') OR (''' + @lISBNNumber + ''' = ''''))  
	AND ((BM.BookTag like ''' + @lBookTag + ''') OR ( ''' + @lBookTag + ''' = ''''))
	AND ((BM.BookCustomTag like ''' + @lBookCustomTag + ''') OR (''' + @lBookCustomTag + ''' = ''''))
	AND ((BM.BookAgeGroupId = ' + convert(varchar,@lBookAgeGroupId) + ') OR(' + convert(varchar,@lBookAgeGroupId) + ' = 0))
	AND ((BM.ResourceTypeId = ' + convert(varchar,@lResourceTypeId) + ') OR (' + convert(varchar,@lResourceTypeId) + ' = 0))
	AND ((BM.BookGroup1Id = ' + convert(varchar,@lBookGroup1Id) + ') OR (' + convert(varchar,@lBookGroup1Id) + ' = 0))
	AND ((BM.BookGroup2Id = ' + convert(varchar,@lBookGroup2Id) + ') OR (' + convert(varchar,@lBookGroup2Id) + ' = 0))
	AND ((BM.Price = ' + convert(varchar,@lPrice) + ') OR (' + convert(varchar,@lPrice) + ' = 0))
	AND ((BM.Currency like ''' + @lCurrency + ''') OR (''' + @lCurrency  + ''' = ''''))
	AND ((BL.StatusId = ' + convert(varchar,@lStatusId) + ') OR (' + convert(varchar,@lStatusId) + '=0))
	AND ((BM.BookDepartment like ''' + @lBookDepartment + ''') OR (''' + @lBookDepartment + ''' = ''''))
	AND (BM.LibraryId = ' + convert(varchar,@lLibraryId) +')
	ORDER BY BM.OrderIndex ASC'
	print(@quer);
	exec (@quer)
	

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


GO

 
ALTER PROCEDURE [sMis].[pRptAttendanceSummaryOrgnizationwiseGet]
	
		@rBuilder1 nvarchar(max)='',
		@rBuilder2 nvarchar(max)='', 
		@rOrgSubGroupId int=0,
		@rOrgId smallint=0,
		@rFromDate Date='',
		@rToDate Date='',
		@rStrOrgSubGroupId nvarchar(max)='',
		@rStrOrgId nvarchar(max)='',
		@rOrgGroupId int=0,
		@rStatusId int=0,
		@rStudentStatusId int=0,
		@rIsTestOrg bit=0,
		@rIsTestSubGroup bit =0,
		@rStrClassId nvarchar(max)='',
		@rStrDivisionId nvarchar(max)=''
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
CREATE TABLE #PresentAbsentCount
(
OrgSubGroupId int,
OrgSubGroupTitle nvarchar(50),
OrgId smallint,
OrgDisplayTitle nvarchar(100),
AcademicId bigint,
PresentCount int,
AbsentCount int,
OrgOrderIndex int ,
ClassId int,
ClassTitle nvarchar(100),
DivisionId int ,
DivisionTitle nvarchar(100),
DepartmentId int ,
DepartmentTitle nvarchar(100)

)

INSERT INTO #PresentAbsentCount
SELECT		
			--OMGM.Id AS OrgMainGroupId,
			--OMGM.Title AS OrgMainGroupTitle,
			OSGM.Id AS OrgSubGroupId,
			OSGM.Title AS OrgSubGroupTitle,
			OM.Id AS OrgId,
			OM.DisplayTitle AS OrgDisplayTitle,
			SR.AcademicId ,
			COUNT(CASE WHEN  SR.IsPresent=1 THEN 1 END)As PresentCount,
			COUNT(CASE WHEN  SR.IsPresent=0 THEN 1 END)As AbsentCount,
			OM.OrderIndex As OrgOrderIndex ,
			CM.Id As ClassId ,
			CM.Title As ClassTitle ,
			DIM.Id As DivisionId ,
			DIM.Title As DivisionTitle,
			DM.Id As DepartmentId,
			DM.Title As DepartmentTitle

			from sAttendance.tStudentRegister SR
			INNER JOIN sStudent.tAcademic A ON SR.AcademicId = A.Id 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId AND (BM.IsActive = @rStatusId OR @rStatusId IS NULL)
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId
			INNER JOIN sSetup.tOrganizationMaster OM  ON OM.Id=A.OrgId
			INNER JOIN sSetup.tOrgSubGroupMaster OSGM ON OSGM.Id = OM.OrgSubGroupId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId = CM.Id
			INNER JOIN sSetup.tDivisionMaster DIM ON DIM.ClassId = CM.Id And DIM.Id = A.DivisionId
			INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id = CM.DepartmentId
			--INNER JOIN sSetup.tOrgMainGroupMaster OMGM ON OMGM.Id = OSGM.OrgMainGroupId
			WHERE
			AttendanceTypeId = 1
			AND (SR.AttendanceDate >= @rFromDate OR @rFromDate IS NULL)
			AND SR.AttendanceDate <= @rToDate
			AND   ((BM.IsActive =@rStatusId) OR @rStatusId IS NULL)
			AND ((OSGM.Id=@rOrgSubGroupId) OR (@rOrgSubGroupId=0))
			AND ((OM.Id=@rOrgId) OR (@rOrgId=0))
			--AND ((OM.OrgGroupId = @rOrgGroupId))
			AND ((SM.StatusID =@rStudentStatusId) OR (@rStudentStatusId=0))
			AND (OSGM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit(@rStrOrgSubGroupId,','))OR @rStrOrgSubGroupId='')
			AND (OM.Id IN (SELECT cast (item as int) FROM  sCommon.fnsplit (@rStrOrgId,','))OR @rStrOrgId='')
			AND (A.ClassId IN (SELECT cast(item as int) FROM  sCommon.fnsplit  (@rStrClassId,','))OR @rStrClassId='') 
			AND (A.DivisionId IN (SELECT cast(item as int) FROM  sCommon.fnsplit  (@rStrDivisionId,','))OR @rStrDivisionId='')
			GROUP BY AcademicId,OSGM.Id,OSGM.Title,OM.Id,OM.DisplayTitle,OM.OrderIndex,CM.Id,CM.Title,DIM.Id,DIM.Title ,  DM.Id,DM.Title

--SELECT * FROM #PresentAbsentCount
CREATE TABLE #PresentAbsentPercentage
(
OrgSubGroupId int,
OrgSubGroupTitle nvarchar(50),
OrgId smallint,
OrgDisplayTitle nvarchar(100),
AcademicId bigint,
Percentage Decimal,
OrgOrderIndex int,
ClassId int,
ClassTitle nvarchar(100),
DivisionId int ,
DivisionTitle nvarchar(100) ,
DepartmentId int ,
DepartmentTitle nvarchar(100)

)

	INSERT INTO #PresentAbsentPercentage
	SELECT OrgSubGroupId,OrgSubGroupTitle,OrgId,OrgDisplayTitle,AcademicId,
	(PresentCount*100)/(PresentCount+AbsentCount),OrgOrderIndex,ClassId,ClassTitle,DivisionId,DivisionTitle,DepartmentId,DepartmentTitle
		FROM #PresentAbsentCount

	--Select * FROM #PresentAbsentPercentage
		SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		OrgSubGroupId,
		OrgSubGroupTitle,
		OrgId,
		OrgDisplayTitle,
		COUNT(CASE WHEN Percentage > 80 THEN 1 END) AS Greaterthan80,
		COUNT(CASE WHEN Percentage > 70 AND Percentage <=80  THEN 1 END) AS Between7080,
		COUNT(CASE WHEN Percentage > 60 AND Percentage <=70  THEN 1 END) AS Between6070,
		COUNT(CASE WHEN Percentage > 50 AND Percentage <=60  THEN 1 END) AS Between5160,
		COUNT(CASE WHEN Percentage <= 50 THEN 1 END) AS Lessthan50,
		COUNT(CASE WHEN Percentage =100  THEN 1 END) AS Equal100,
		COUNT(CASE WHEN Percentage >= 91 AND Percentage <=99  THEN 1 END) AS Between9199,
		COUNT(CASE WHEN Percentage >= 81 AND Percentage <=90  THEN 1 END) AS Between8190,
		COUNT(CASE WHEN Percentage >= 21 AND Percentage <=50  THEN 1 END) AS Between2150,
		COUNT(CASE WHEN Percentage > 0 AND Percentage <=20  THEN 1 END) AS Between120,
		COUNT(CASE WHEN Percentage <=0  THEN 1 END) AS Equal0,
		OrgOrderIndex,		
		@rIsTestOrg AS IsTestOrg,
		@rIsTestSubGroup AS IsTestSubGroup,
		ClassId,
		ClassTitle,
		DivisionId,
		DivisionTitle ,
		DepartmentId ,
		DepartmentTitle
		FROM #PresentAbsentPercentage 
		GROUP By OrgSubGroupId,OrgSubGroupTitle,OrgId,OrgDisplayTitle,OrgOrderIndex,ClassId,ClassTitle,DivisionId,DivisionTitle ,DepartmentId ,DepartmentTitle
			
		DROP TABLE #PresentAbsentPercentage
		DROP TABLE #PresentAbsentCount



			 -- SELECT 
			 --'' AS Builder1,
			 --'' AS Builder2,
			 --0 AS OrgSubGroupId,
			 --'' AS OrgSubGroupTitle,
			 --0 AS OrgId,
			 --'' AS OrgDisplayTitle,
			 --0 AS Greaterthan80,
			 --0 AS Between7080,
			 --0 AS Between6070,
			 --0 AS Between5160,
			 --0 AS Lessthan50,
			 --0 AS Equal100,
			--0  AS Between9199,
			--0 AS Between8190,
			 --0 AS Between2150,
			 --0 AS Between120,
			 --0 AS Equal0,
			 --0 AS OrgOrderIndex,
			 --0 AS IsTestOrg,
			 --0 AS IsTestSubGroup ,
			 --0 As ClassId ,
			 --'' As ClassTitle ,
			 --0 As DivisionId ,
			 --'' As DivisionTitle ,
			 --0 As DepartmentId ,
			 --'' As DepartmentTitle
END
GO
PRINT N'Altering [sSecurity].[pDashletGet]...';


GO
ALTER PROCEDURE [sSecurity].[pDashletGet]
	@rOrgGroupId int=0,
	@rDate date='',
	@rDashletId int=0,
	@rOrgGroupBatchId int=0,
	@rUserId bigint=0,
	@rUserSourceId bigint=0,
	@rUserSourceTypeId int=0,
	@rOrgId Int=0,
	@rSourceTypeId smallint=0,
	@rSourceId bigint=0,
	@rBatchId int=0,
	@rExamId int=0,
	@rStatusId int =0
	
									
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
BEGIN
DECLARE @TimeZoneDate datetime
SET  @TimeZoneDate=sCommon.fGetDate()
if(@rDashletId='1')
       BEGIN
        exec sCommunication.pCircularListGet @rUserSourceId=@rUserSourceId,@rOrgGroupBatchId=@rOrgGroupBatchId,@rUserSourceTypeId=@rUserSourceTypeId,@rUserId=@rUserId,@rStartDate=@rDate
        END
 if(@rDashletId='2')
        BEGIN
        SELECT  N.Id,N.Title FROM sCommunication.tNews N WHERE N.OrgGroupBatchId=@rOrgGroupBatchId AND Convert(date,N.CreatedDateTime)=convert(date,@TimeZoneDate)
        END
 if(@rDashletId='3')
          BEGIN
        exec sActivity.pMyEventGet @rSourceTypeId=@rSourceTypeId,@rSourceId=@rSourceId,@rOrgId=@rOrgId,@rBatchId=@rBatchId,@rFromDate=@rDate,@rToDate=@rDate
          END
if(@rDashletId='4')
        BEGIN
        exec sCommunication.pAssignTaskGet @rId=0,@rOrgId=@rOrgId,@rCreatedUserId=@rUserId,@rIsAssignTaskToMe=1,@rStatus=0,@rIsSearch=1
        END
 if(@rDashletId='5')
        BEGIN
        exec sCommunication.pAssignTaskGet @rId=0,@rOrgId=@rOrgId,@rCreatedUserId=@rUserId,@rIsAssignTaskToMe=0,@rStatus=0,@rIsSearch=1
        END
 if(@rDashletId='6')
        BEGIN
		DECLARE @BirthdayDays int=0
		IF EXISTS (SELECT 1 FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 355 AND SourceTypeId = 1016 AND SourceId = @rOrgId)
			BEGIN
			SET @BirthdayDays = (SELECT ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 355 AND SourceTypeId = 1016 AND SourceId = @rOrgId)
			END
		ELSE 
			BEGIN
			SET @BirthdayDays = 7
			END
        SELECT 	EM.FirstName + ' ' + EM.MiddleName + ' ' + EM.LastName AS Name,	EM.DepartmentName, EM.DateOfBirth AS DateOfBirth  FROM [sHrm].[vExtEmployeeMaster] EM	
        WHERE  	EM.OrgId = @rOrgId  
     --    AND (MONTH(EM.DateOfBirth) = CAST(MONTH(@TimeZoneDate) AS varchar(2))) AND EM.DateOfBirth!='' AND EM.StatusId=7
	    --AND (DAY(EM.DateOfBirth) = CAST(DAY(@TimeZoneDate) AS varchar(2)))
		--AND(MONTH(EM.DateOfBirth) <= CAST(MONTH(@TimeZoneDate) AS varchar(2)) AND MONTH(EM.DateOfBirth) >= CAST(MONTH(@TimeZoneDate) AS varchar(2)))
		--AND(DAY(EM.DateOfBirth) <= CAST(DAY(@TimeZoneDate+@BirthdayDay) AS varchar(2)) AND DAY(EM.DateOfBirth) >= CAST(DAY(@TimeZoneDate) AS varchar(2)))

		AND CONVERT(VARCHAR(5),EM.DateOfBirth,110) <= CONVERT(VARCHAR(5),@TimeZoneDate+@BirthdayDays,110) 
		AND CONVERT(VARCHAR(5),EM.DateOfBirth,110) >= CONVERT(VARCHAR(5),@TimeZoneDate,110)
		AND EM.DateOfBirth!='' AND EM.StatusId=7
		ORDER BY CONVERT(VARCHAR(5),EM.DateOfBirth,110)
		
        END
 if(@rDashletId='7')
        BEGIN
        SELECT SC.FirstName + ' ' + SC.MiddleName + ' ' + SC.LastName AS Name, SC.ClassName+' '+SC.DivisionName AS ClassName FROM sStudent.vStudentAllDetail SC WHERE SC.OrgId=@rOrgId AND SC.BatchId=@rBatchId
         AND (MONTH(SC.DateOfBirth) = CAST(MONTH(@TimeZoneDate) AS varchar(2))) AND SC.DateOfBirth!='' AND SC.StatusId=1
	    AND (DAY(SC.DateOfBirth) = CAST(DAY(@TimeZoneDate) AS varchar(2)))   
        END
         if(@rDashletId='10')
        BEGIN
       exec sAttendance.pDashletAttendanceStatusGet @rAcademicId=@rSourceId
        END
   
   if(@rDashletId='11')
        BEGIN
       SELECT EM.EmployeeName,L.FromDate,L.ToDate FROM  sHrm.tLeave L 
        INNER JOIN sSetup.tBatchMaster BM ON BM.Id = L.BatchId	
        INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = L.EmployeeId
        INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = L.EmployeeId
         WHERE  
			   BM.OrgGroupBatchId = @rOrgGroupBatchId
			   AND L.OrgId = @rOrgId
			   AND (EJD.EmployeeManagerId = @rUserSourceId OR @rUserSourceId = 0)
			   AND ((L.FromDate >= @rDate) OR (ISNULL(@rDate,'') = ''))
			   AND EM.EmployeeStatusId=7
             
       -- exec [sHrm].[pLeaveListingGet] @rOrgId=@rOrgId,@rEmployeeId=@rUserSourceId,@rLeaveTypeId=0,@rOrgGroupBatchId=@rOrgGroupBatchId,@rFromDate=@rDate,@rTodate=''
        END
   if(@rDashletId='12')
        BEGIN
     exec sCommunication.pPollGet @rOrgGroupBatchId=@rOrgGroupBatchId,@rSourceTypeId=@rUserSourceTypeId,@rCreatedUserId=@rUserId,@rCreatedDateTime=@rDate
        END
  if(@rDashletId='14')
       BEGIN
        exec sCommunication.pMyBookGet @rReaderSourceTypeId=@rUserSourceTypeId,@rReaderSourceId=@rUserSourceId,@rBatchId=@rBatchId,@rStatusId=@rStatusId

        END
  if(@rDashletId='16')
        BEGIN
      exec [sFee].[pRptFeeReceiptTotalGet] @rFromDate=@rDate,@rToDate=@rDate,@rOrgGroupBatchId=@rOrgGroupBatchId
        END
      
  if(@rDashletId='17')
        BEGIN
      exec [sFee].[pFeeDueAlertGet] @rSourceId=@rSourceId,@rSourceTypeId=@rSourceTypeId,@rBatchId=@rBatchId

        END
  if(@rDashletId='18')
        BEGIN
     exec sCommunication.pBlogGet @rId=0,@rOrgGroupBatchId=@rOrgGroupBatchId,@rTitle=NULL,@rCreatedUserId=0,@rOrgId=@rOrgId,@rCreatedDateTime=@rDate
        END
 if(@rDashletId='19')
        BEGIN
     exec sAssessment.pStudentResultGet @rAcademicId=@rSourceId,@rStudentId=@rUserSourceId,@rBatchId=@rBatchId,@rExamId=@rExamId
     END
  if(@rDashletId='21')
       BEGIN
       SELECT vCD.ClassDivisionName,ISNULL(EM.FirstName+' '+ EM.LastName,'') AS ClassTeacherName,
	   CASE WHEN COUNT(SR.AcademicId)=0 THEN CASE WHEN (Select [sCommon].[fCountAbsentStudent](A.DivisionId,  @rBatchId,@rDate,1,0)) =0 THEN 'Pending' ELSE 'Complete' END ELSE 'Complete' END AS PresentStatus
        FROM sStudent.tAcademic A INNER JOIN sSetup.vClassDivision vCD ON vCD.ClassId=A.ClassId 
       AND vCD.DivisionId=A.DivisionId AND A.OrgId=vCD.OrgId AND A.OrgId=@rOrgId  AND A.BatchId=@rBatchId AND vCD.IsObsolete=0 
       INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vCD.DivisionId LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId 
       LEFT JOIN sAttendance.tStudentRegister SR ON A.Id = SR.AcademicId AND SR.AttendanceTypeId = 1 
       AND SR.IsPresent=1 AND SR.AttendanceDate=@rDate GROUP BY A.DivisionId,A.BatchId,vCD.ClassDivisionName,vCD.OrderIndex,EM.FirstName,EM.LastName ORDER BY vCD.OrderIndex
         END
  if(@rDashletId='22')
       BEGIN
        SELECT VL.Id,VL.VisitorName, VL.NoOfVisitor,  (isnull(case when isnull(VL.WhomToMeet,0)!=0 then isnull(EM.EmployeeName,'') else ISNULL(VL.WhomToMeetName,'') end,'' )) AS WhomToMeetName
		FROM sFrontOffice.tVisitorLog VL  
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=VL.OrgId 
		 LEFT JOIN sHrm.vExtEmployeeMaster EM ON EM.EmployeeId=VL.WhomToMeet
        WHERE VL.OrgId=@rOrgId AND VL.VisitDate=@rDate ORDER BY VL.VisitDate DESC,VL.InTime DESC
        END
  if(@rDashletId='23')
       BEGIN
        SELECT DispatchedTo, DispatchedCity  FROM sFrontOffice.tCourierDispatch  WHERE OrgGroupId=@rOrgGroupId AND DispatchDate=@rDate  AND @rDashletId='23' ORDER BY DispatchDate
        END
    if(@rDashletId='24')
       BEGIN
        SELECT ReceiveFrom, ReceiveFor  FROM  sFrontOffice.tCourierReceive  WHERE OrgGroupId=@rOrgGroupId  AND ReceiveDate=@rDate  AND @rDashletId='24' ORDER BY ReceiveDate
    END
     if(@rDashletId='25')
        BEGIN
     SELECT ISNULL(Ps.LectureNumber,'') AS LactureNumber,PS.EmployeeId,ISNULL(SMT.Title,'') AS Subject,ISNULL(EM1.FirstName,'') + ' '+ISNULL(EM1.LastName,'') AS EmployeeName,ISNULL(Em.FirstName,'') + ' '+ISNULL(Em.LastName,'') AS ProxyEmployeeName, ISNULL(DV.Code,'') AS ClassDivisionName,ISNULL(SM.Title,'') AS ProxySubject from sTimetable.tProxySetting PS 
     INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = PS.SubjectId INNER JOIN sCommon.tDayMaster DM ON DM.Id = PS.DayId INNER JOIN sSetup.tDivisionMaster DV ON DV.Id = PS.DivisionId
     INNER JOIN sTimetable.tTimeTable TT ON TT.Id=PS.TimeTableId 
     INNER JOIN sSetup.tSubjectMaster SMT ON SMT.Id = TT.SubjectId 
     INNER JOIN sHrm.tEmployeeMaster EM1  ON TT.EmployeeId=EM1.Id 
     INNER JOIN sHrm.tEmployeeMaster Em ON Em.Id = PS.EmployeeId  WHERE PS.ProxyDate=@rDate AND PS.BatchId=@rBatchId AND ((PS.EmployeeId=@rSourceId) OR (@rSourceId=0))  ORDER BY PS.ProxyDate
        END
        
        if(@rDashletId='27')
        BEGIN
     --Asset Check
		SELECT LM.Title AS LocationName, AM.Code AS AssetCode, AM.Title AS AssetName, CONVERT(nvarchar(12),AM.CheckedLastDate,103) AS CheckedLastDate
        FROM sAssetManagement.tAssetMaster AM INNER JOIN sAssetManagement.tAssetInchargeUser AU ON AM.Id = AU.AssetId 
        INNER JOIN sFixedAsset.tLocationMaster LM ON LM.Id = AM.LocationId 
        WHERE ISNULL(AM.IsCheckRequired,0) = 1 AND (AM.CheckFrequencyId=1 AND AM.CheckedLastDate <=  DATEADD(dd,1,@TimeZoneDate) OR AM.CheckFrequencyId=2 AND AM.CheckedLastDate <=  DATEADD(dd,7,@TimeZoneDate) OR AM.CheckFrequencyId=3 AND AM.CheckedLastDate <= DATEADD(dd,30,@TimeZoneDate))
        AND AU.InchargeUserId =   @rUserId AND AM.OrgGroupId = @rOrgGroupId
     
     
     
  --      SELECT LM.Title AS LocationName, AM.Code AS AssetCode, AM.Title AS AssetName,CONVERT(nvarchar(12),
		--AM.LastMaintenanceDate,103) AS LastMaintenanceDate,CONVERT(nvarchar(12),AM.NextMaintenanceDate,103) AS NextMaintenanceDate
		--FROM sAssetManagement.tAssetMaster AM 
		--INNER JOIN sAssetManagement.tAssetInchargeUser AU ON AM.Id = AU.AssetId 
		--INNER JOIN sFixedAsset.tLocationMaster LM ON LM.Id = AM.LocationId
		-- WHERE AU.InchargeUserId = @rUserId AND AM.OrgGroupId = @rOrgGroupId
		 END
		if(@rDashletId='28')
        BEGIN
     --Asset maintenance
			 SELECT LM.Title AS LocationName, AM.Code AS AssetCode, AM.Title AS AssetName,CONVERT(nvarchar(12),
			 AM.LastMaintenanceDate,103) AS LastMaintenanceDate,CONVERT(nvarchar(12),AM.NextMaintenanceDate,103) AS NextMaintenanceDate 
             FROM sAssetManagement.tAssetMaster AM 
             INNER JOIN sAssetManagement.tAssetInchargeUser AU ON AM.Id = AU.AssetId 
             INNER JOIN sFixedAsset.tLocationMaster LM ON LM.Id = AM.LocationId 
                                WHERE AU.InchargeUserId =@rUserId  AND AM.OrgGroupId = @rOrgGroupId
		 END
		if(@rDashletId='29')
        BEGIN
     --Asset Renew
        SELECT LM.Title AS LocationName, AM.Code AS AssetCode, AM.Title AS AssetName, CONVERT(nvarchar(12),
         AM.RenewLastDate,103) AS RenewLastDate, CONVERT(nvarchar(12), AM.RenewNextDate,103) AS RenewNextDate
           FROM sAssetManagement.tAssetMaster AM INNER JOIN sAssetManagement.tAssetInchargeUser AU ON AM.Id = AU.AssetId 
           INNER JOIN sFixedAsset.tLocationMaster LM ON LM.Id = AM.LocationId 
            WHERE ISNULL(AM.IsRenewRequired,0) = 1
            -- AND AM.RenewNextDate >= DATEADD(dd,ISNULL(AM.RenewAlertBeforeDays,0),AM.RenewLastDate) 
             AND convert(Date,@TimeZoneDate) >=  DATEADD(dd,-ISNULL(AM.RenewAlertBeforeDays,0), AM.RenewNextDate)
                           AND AU.InchargeUserId =  @rUserId  AND AM.OrgGroupId = @rOrgGroupId
        END
        --Inward
       IF(@rDashletId='30')
        BEGIN
        DECLARE @InwardRegisterGrid VARCHAR(max)=''
        SELECT  @InwardRegisterGrid = @InwardRegisterGrid + '<tr>
	       <td align="left" scope="col">' + ISNULL(LetterNumber,'') + '</td>
	       <td align="left" scope="col">' + ISNULL(LetterSubject,'') + '</td>
	       <td align="left" scope="col">' + ISNULL(LetterFrom,'') + '</td>
	       <td align="left" scope="col">' + convert(varchar,isnull(ReceivedDate,'01/01/0001'),103) + '</td>
	 	</tr>'		
	 	FROM
	 	 sFrontOffice.tInwardRegister
	 	 WHERE IsReplyRequired=1 AND IsReplied=0 AND OrgId=@rOrgId
	 	 AND ReceivedDate<=convert(Date,@TimeZoneDate)
		 Order by ReceivedDate Desc

	   SELECT Isnull(@InwardRegisterGrid,'') As	InwardRegisterGrid
        END
            --Outward
         IF(@rDashletId='31')
        BEGIN
        DECLARE @OutwardRegisterGrid VARCHAR(max)=''
        SELECT  @OutwardRegisterGrid = @OutwardRegisterGrid + '<tr>
	    <td align="left" scope="col">' + ISNULL(LetterNumber,'') + '</td>
	       <td align="left" scope="col">' + ISNULL(LetterSubject,'') + '</td>
	       <td align="left" scope="col">' + ISNULL(LetterTo,'') + '</td>
	       <td align="left" scope="col">' + convert(varchar,isnull(OutWardDate,'01/01/0001'),103) + '</td>
	 	</tr>'	
	 	FROM
	 	 sFrontOffice.tOutwardRegister
	 	 WHERE IsReplyRequired=1 AND IsReplied=0 AND OrgId=@rOrgId
	 	 AND OutwardDate<=convert(Date,@TimeZoneDate)
		 Order by OutwardDate Desc

	   SELECT Isnull(@OutwardRegisterGrid,'') As	OutwardRegisterGrid
	   END
	   
	   IF(@rDashletId='32')
        BEGIN
        DECLARE @ReorderQuantityGrid VARCHAR(max)=''
        SELECT   @ReorderQuantityGrid=@ReorderQuantityGrid+'<tr>
		     <td align="left" scope="col">' + ISNULL(SE.Title,'')  + '</td>
	        <td align="left" scope="col">' +ISNULL(SM.Title,'')  + '</td>
	      <td align="left" scope="col">' +convert(varchar,ISNULL(SUM(SB.AvailableQuantity),0))+ '</td>
	       <td align="left" scope="col">' + convert(varchar,isnull(SP.ReOrderQuantity,0)) + '</td>
	 	 </tr>'	
	 	FROM
	 	 sProcurement.tStockBatch SB
	 	  INNER JOIN sIp.tStockItemMaster SM ON SM.Id=SB.STockItemID
	 	 INNER JOIN sIp.tStoreLocationMaster SE ON SE.Id=SB.StoreLocationId
	 	 INNER JOIN sIp.tStockItemPlanning SP ON SP.STockItemID=SM.Id AND SP.StoreLocationId =SE.Id
	 	 --INNER JOIN  sSecurity.tUserLocation UL ON UL.StoreLocationId = SB.StoreLocationId
	 	 WHERE  SM.OrgGroupId=@rOrgGroupId AND SM.IsObsolete=0 
	 	 group by SE.Title,SM.Title,SP.ReOrderQuantity,SP.ReOrderPoint
	 	 HAVING SUM(SB.AvailableQuantity) < SP.ReOrderPoint
	   
		SELECT Isnull(@ReorderQuantityGrid,'') As	ReorderQuantityGrid
		END
		
		 IF(@rDashletId='33')
        BEGIN
        DECLARE @SafetyStockGrid VARCHAR(max)=''
        SELECT   @SafetyStockGrid=@SafetyStockGrid+'<tr>
		     <td align="left" scope="col">' + ISNULL(SE.Title,'')  + '</td>
	        <td align="left" scope="col">' +ISNULL(SM.Title,'')  + '</td>
	      <td align="left" scope="col">' +convert(varchar,ISNULL(SUM(SB.AvailableQuantity),0))+ '</td>
	       <td align="left" scope="col">' + convert(varchar,isnull(SP.SafetyStock,0)) + '</td>
	 	 </tr>'	
	 	FROM
	 	 sProcurement.tStockBatch SB
	 	  INNER JOIN sIp.tStockItemMaster SM ON SM.Id=SB.STockItemID
	 	 INNER JOIN sIp.tStoreLocationMaster SE ON SE.Id=SB.StoreLocationId
	 	 INNER JOIN sIp.tStockItemPlanning SP ON SP.STockItemID=SM.Id AND SP.StoreLocationId =SE.Id
	 	 --INNER JOIN  sSecurity.tUserLocation UL ON UL.StoreLocationId = SB.StoreLocationId
	 	 WHERE  SM.OrgGroupId=@rOrgGroupId AND SM.IsObsolete=0 
	 	 group by SE.Title,SM.Title,SP.SafetyStock,SP.ReOrderPoint
	 	 HAVING SUM(SB.AvailableQuantity) < SP.SafetyStock
	   
		SELECT Isnull(@SafetyStockGrid,'') As	SafetyStockGrid
        END
		 IF(@rDashletId='34')
		 BEGIN 
		 DECLARE @Increment varchar(max)=''
		 SELECT @Increment=@Increment+'<tr>
		  <td align="left" scope="col">' + ISNULL(EM.FirstName,'') + ' '+ISNULL(EM.LastName,'') + '</td>
	        <td align="left" scope="col">' +convert(varchar,isnull(IncrementDate,'01/01/0001'),103)  + '</td></tr>'
		FROM sHrm.tEmployeeStatutoryAndOther SA
		INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id=SA.EmployeeId
		WHERE IncrementDate BETWEEN GETDATE()-1 AND GETDATE()+7
		AND EM.OrgID=@rOrgId And EM.StatusId=7
		SELECT Isnull(@Increment, '') As	IncrementGrid
		END
		
			 IF(@rDashletId='78')
		 BEGIN 
		 DECLARE @Retirement varchar(max)=''
		 SELECT @Retirement=@Retirement+'<tr>
		  <td align="left" scope="col">' + ISNULL(EM.FirstName,'') + ' '+ISNULL(EM.LastName,'') + '</td>
	        <td align="left" scope="col">' +convert(varchar,isnull(RetirementDate,'01/01/0001'),103)  + '</td></tr>'
		FROM sHrm.tEmployeeStatutoryAndOther SA
		INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id=SA.EmployeeId
		WHERE RetirementDate BETWEEN GETDATE()-1 AND GETDATE()+30
		AND EM.OrgID=@rOrgId And EM.StatusId=7
		SELECT Isnull(@Retirement, '') As RetirementGrid
		END

	if(@rDashletId='83')
        BEGIN
			SELECT SA.Name,L.LeaveFromDate,L.LeaveToDate 
			FROM  sAttendance.tStudentLeaveRequest L   
			INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = L.AcademicId  
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId    
			WHERE  
				 SA.BatchId = @rBatchId
				AND SA.OrgId = @rOrgId
				AND ((L.LeaveFromDate <= @rDate) OR (ISNULL(@rDate,'') = ''))
				AND ((L.LeaveToDate >= @rDate) OR (ISNULL(@rDate,'') = ''))
				AND SA.StatusId=1
		END
  END
GO
PRINT N'Altering [sSecurity].[pTraceabilityTrackAdd]...';


GO
ALTER PROCEDURE [sSecurity].[pTraceabilityTrackAdd]

@rScreenId int,
@rTraceabilityId int,
@rTraceabilitySourceId int

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
IF EXISTS(Select 1 from sSecurity.tTraceabilityTrack WHERE ScreenId = @rScreenId AND TraceabilityId=@rTraceabilityId AND TraceabilitySourceId=@rTraceabilitySourceId)
BEGIN
	    SELECT -103 AS Result
		RETURN
END

BEGIN TRANSACTION
BEGIN
	INSERT INTO 
		sSecurity.tTraceabilityTrack
		VALUES
		(@rScreenId,
		@rTraceabilityId,
		@rTraceabilitySourceId)
        SELECT 1 AS Result
		END
COMMIT TRANSACTION		
--END TRY
--BEGIN CATCH 
--ROLLBACK TRANSACTION
--		SELECT -1 AS Result
--		RETURN
--	END CATCH
END
GO
PRINT N'Altering [sSetup].[pHistoryTransfer]...';


GO
 
 
ALTER PROCEDURE [sSetup].[pHistoryTransfer]
	 @rType smallint = 0,
	 @rDate date = ''
	 	 	 
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN
BEGIN TRY
		BEGIN TRANSACTION 
	IF(@rType = 1) -- Copy To History Table
	BEGIN

	INSERT INTO [sAlert].[tAlertLogHistory] SELECT * FROM [sAlert].[tAlertLog] WHERE CAST(CreatedDateTime AS DATE) < @rDate
	DELETE FROM [sAlert].[tAlertLog] WHERE CAST(CreatedDateTime AS DATE) < @rDate

	INSERT INTO [sAlert].[tNotificationLogHistory] SELECT * FROM [sAlert].[tNotificationLog] WHERE CAST(CreatedDateTime AS DATE) < @rDate
	DELETE FROM [sAlert].[tNotificationLog] WHERE CAST(CreatedDateTime AS DATE) < @rDate

	INSERT INTO [sAlert].[tWhatsAppLogHistory] SELECT * FROM [sAlert].[tWhatsAppLog] WHERE CAST(CreatedDateTime AS DATE) < @rDate
	DELETE FROM [sAlert].[tWhatsAppLog] WHERE CAST(CreatedDateTime AS DATE) < @rDate

	INSERT INTO [sAudit].[tActivityLogHistory] SELECT * FROM [sAudit].[tActivityLog] WHERE CAST(AuditDate AS DATE) < @rDate
	DELETE FROM [sAudit].[tActivityLog] WHERE CAST(AuditDate AS DATE) < @rDate

	--INSERT INTO [sAudit].[tOperationLogHistory] SELECT * FROM [sAudit].[tOperationLog] WHERE CAST(CreatedDateTime AS DATE) < @rDate
	--DELETE FROM [sAudit].[tOperationLog] WHERE CAST(CreatedDateTime AS DATE) < @rDate

	--INSERT INTO [sHrm].[tLeaveBalanceLogHistory] SELECT * FROM [sHrm].[tLeaveBalanceLog] WHERE CAST(CreatedDateTime AS DATE) < @rDate
	--DELETE FROM [sHrm].[tLeaveBalanceLog] WHERE CAST(CreatedDateTime AS DATE) < @rDate

	--INSERT INTO [sLibrary].[tBookLogHistory] SELECT * FROM [sLibrary].[tBookLog] WHERE CAST(CreatedDateTime AS DATE) < @rDate
	--DELETE FROM [sLibrary].[tBookLog] WHERE CAST(CreatedDateTime AS DATE) < @rDate

	--INSERT INTO [sRecruitment].[tRecruitmentStatusLogHistory] SELECT * FROM [sRecruitment].[tRecruitmentStatusLog] WHERE CAST(CreatedDateTime AS DATE) < @rDate
	--DELETE FROM [sRecruitment].[tRecruitmentStatusLog] WHERE CAST(CreatedDateTime AS DATE) < @rDate

	INSERT INTO [sSecurity].[tUserLogHistory] SELECT * FROM [sSecurity].[tUserLog] WHERE CAST(LoggedInDateTime AS DATE) < @rDate
	DELETE FROM [sSecurity].[tUserLog] WHERE CAST(LoggedInDateTime AS DATE) < @rDate

	INSERT INTO [sSystem].[tBackupLogHistory] SELECT * FROM [sSystem].[tBackupLog] WHERE CAST(BackupDateTime AS DATE) < @rDate
	DELETE FROM [sSystem].[tBackupLog] WHERE CAST(BackupDateTime AS DATE) < @rDate

	INSERT INTO [sAcademic].[tClassworkViewHistory] SELECT * FROM [sAcademic].[tClassworkView] WHERE CAST(ViewByDateTime AS DATE) < @rDate
	DELETE FROM [sAcademic].[tClassworkView] WHERE CAST(ViewByDateTime AS DATE) < @rDate

	INSERT INTO [sAcademic].[tOnlineLearningViewHistory] (OnlineLearningId,AcademicId,IsViewReference,IsViewAssignment,IsViewResource,ViewByUserId,LastViewByDateTime,AssignmentTeacherRemark) SELECT OnlineLearningId,AcademicId,IsViewReference,IsViewAssignment,IsViewResource,ViewByUserId,LastViewByDateTime,AssignmentTeacherRemark FROM [sAcademic].[tOnlineLearningView] WHERE CAST(LastViewByDateTime AS DATE) < @rDate
	DELETE FROM [sAcademic].[tOnlineLearningView] WHERE CAST(LastViewByDateTime AS DATE) < @rDate

	INSERT INTO  [sCommunication].[tAssignmentViewHistory] SELECT * FROM [sCommunication].[tAssignmentView] WHERE CAST(ViewByDateTime AS DATE) < @rDate
	DELETE FROM [sCommunication].[tAssignmentView] WHERE CAST(ViewByDateTime AS DATE) < @rDate

	INSERT INTO  [sCommunication].[tCircularViewHistory] SELECT * FROM [sCommunication].[tCircularView] WHERE CAST(ViewByDateTime AS DATE) < @rDate
	DELETE FROM [sCommunication].[tCircularView] WHERE CAST(ViewByDateTime AS DATE) < @rDate

	--exec [sAcademic].[pOnlineLearningMigrateToHistoryAdd] @rDate
	
	SELECT 1 AS MSG
	END
	ELSE IF(@rType = 2) -- Delete From Exception Table
	BEGIN 
		DELETE FROM [sSystem].[tExceptionLog] WHERE CAST(CreatedDateTime AS DATE) < @rDate
		SELECT 1 AS MSG
	END
	COMMIT TRANSACTION			 
	END TRY
	
	BEGIN CATCH 
		SELECT ERROR_MESSAGE() AS MSG
		ROLLBACK TRANSACTION		
	END CATCH	
END
GO
PRINT N'Altering [sStudent].[pIDRegisterGet]...';


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

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

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

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


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


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

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


GO
ALTER PROCEDURE [sStudent].[pImportAdmissionInquiry]
    
    @rOrgGroupId smallint,
    @rOrgId smallint,
	@rXmldoc [nvarchar](max),
	@rUserId bigint,
	@rBatchId int

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
BEGIN TRY

DECLARE @lCount INT
DECLARE @lInterrorCode INT,
			@intDoc INT,
			@lFirstName nvarchar(100),
			@lMiddleName nvarchar(100),
			@lLastName nvarchar(100),
			@lClassId int,
			@lClass nvarchar(50),
			@lDOB date,
			@lStatusId int,
			--@lStatus nvarchar(20),
			@lPresentStreetOne nvarchar(150),
			@lPresentStreetTwo nvarchar(150),
			@lPresentStreetThree nvarchar(150),
			@lPresentCountry nvarchar(50),
			@lPresentState nvarchar(50),
			
			@lPresentCity nvarchar(50),
			@lPresentZipCode nvarchar(20),
			@lParentContactNo nvarchar(20),
			@lParentEmail nvarchar(50),
			@lRemark nvarchar(200),
			@lInquiryModeId smallint,
			@lInquiryMode nvarchar(50),
			@lInquiryReferenceId int,
			@lInquiryReference nvarchar(50),
			@lAdmissionCategoryId int,
			@lAdmissionCategory nvarchar(100),
			@lPreviousSchool nvarchar(200),
			@lMeritMarks decimal(10,2),
			@lMeritGrade nvarchar(20),
			@lMeritMarksBreakup nvarchar(100),
			@lGenderId int,
			@lGender nvarchar(10),
			 @lFollowupDate date,
			@lFollowupRemark nvarchar(150),
			@lInquiryDate date,
			--@lCode nvarchar(20),
			@lNumber bigint,
			@lHandledBy nvarchar(100),
			@lInquiryStatusId int,
			@lInquiryStatus nvarchar(50) 
		 
			 
			 
			
 		
--DECLARE @OutClassId int
--DECLARE @OutDivisionId int
DECLARE @OutStudentId bigint 
--DECLARE @OutAdmissionStandardId int
--DECLARE @OutReligionId int
--DECLARE @OutAdmissionCategoryId int		
SET @lAdmissionCategoryId=sCommon.fGetIntIdForOrg(1,@rOrgGroupId)	
				 
EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc
	 
	CREATE TABLE #tTable  
	(
		Id bigint identity,	 
		FirstName nvarchar(100),
		MiddleName nvarchar(100),
		LastName nvarchar(100),
		ClassId int  ,
		Class nvarchar(100),
		DOB date,
		StatusId smallint,
		--Status nvarchar(20),
		PresentStreetOne nvarchar(150),
		PresentStreetTwo nvarchar(150),
		PresentStreetThree nvarchar(150),
		PresentCountry nvarchar(50),
		PresentState nvarchar(50),
		PresentCity nvarchar(50),
		PresentZipCode nvarchar(20),
		ParentContactNo nvarchar(20),
		ParentEmail nvarchar(50),
		Remark nvarchar(200),
		InquiryModeId smallint,
		InquiryMode nvarchar(50),
		InquiryReferenceId int,
		InquiryReference nvarchar(50),
		AdmissionCategoryId int,
		AdmissionCategory nvarchar(100),
		PreviousSchool nvarchar(200),
		MeritMarks decimal(10,2),
		MeritGrade nvarchar(20),
		MeritMarksBreakup nvarchar(100),
		GenderId int,
		Gender nvarchar(10),
		 FollowupDate date,
		FollowupRemark nvarchar(150),
		CreatedUserId bigint,
		InquiryDate date,
		Number bigint,
		HandledBy nvarchar(100),
		InquiryStatusId int,
		InquiryStatus nvarchar(50) 
		 
		 
	)
	
	INSERT INTO #tTable
	(
		 
		FirstName,
		MiddleName,
		LastName,
		ClassId,
		Class,
		DOB,
		StatusId,
		--Status,
		PresentStreetOne,
		PresentStreetTwo,
		PresentStreetThree,
		PresentCountry,
		PresentState,
		PresentCity,
		PresentZipCode,
		ParentContactNo,
		ParentEmail,
		Remark,
		InquiryModeId,
		InquiryMode,
		InquiryReferenceId,
		InquiryReference,
		AdmissionCategoryId,
		AdmissionCategory,
		PreviousSchool,
		MeritMarks,
		MeritGrade,
		MeritMarksBreakup,
		GenderId,
		Gender,
		 FollowupDate,
		FollowupRemark,
		CreatedUserId,
		InquiryDate,
		Number,
		HandledBy,
		InquiryStatusId,
		InquiryStatus  
		
		
		 
	)
	
	SELECT
	 
		FirstName,
		MiddleName,
		LastName,
		0,
		Class,
		DOB,
		0,
	   -- Status,
	    PresentStreetOne,
		PresentStreetTwo,
		PresentStreetThree,
		PresentCountry,
		PresentState,
		PresentCity,
		PresentZipCode,
		ParentContactNo,
		ParentEmail,
		Remark,
		0,
		InquiryMode,
		0,
		InquiryReference,
		0,
		AdmissionCategory,
		PreviousSchool,
		MeritMarks,
		MeritGrade,
		MeritMarksBreakup,
		0,
		Gender,
		 FollowupDate,
		FollowupRemark,
		CreatedUserId,
		InquiryDate,
		Number,
		HandledBy,
		0,
		InquiryStatus  
		
		
			
	FROM OPENXML (@intDoc, '/Table/ImportStudent', 1)
	WITH
	( 
		  
		FirstName nvarchar(100) '@FirstName',
		MiddleName nvarchar(100) '@MiddleName',
		LastName nvarchar(100) '@LastName',
		Class nvarchar(100) '@Class',
		DOB DATE '@DOB',
		--Status nvarchar(20) '@Status',
		 PresentStreetOne nvarchar(150) '@PresentStreetOne',
		PresentStreetTwo nvarchar(150) '@PresentStreetTwo',
		PresentStreetThree nvarchar(150) '@PresentStreetThree',
		PresentCountry nvarchar(50) '@PresentCountry',
		PresentState nvarchar(50) '@PresentState',
		PresentCity nvarchar(50) '@PresentCity',
		PresentZipCode nvarchar(20) '@PresentZipCode',
		ParentContactNo nvarchar(20) '@ParentContactNo',
		ParentEmail nvarchar(50) '@ParentEmail',
		Remark nvarchar(200) '@Remark',
		InquiryMode  nvarchar(50) '@InquiryMode',
		InquiryReference nvarchar(50) '@InquiryReference',
		AdmissionCategory nvarchar(100) '@AdmissionCategory',
		PreviousSchool nvarchar(200) '@PreviousSchool',
		MeritMarks decimal(10,2) '@MeritMarks',
		MeritGrade nvarchar(20) '@MeritGrade',
		MeritMarksBreakup nvarchar(100) '@MeritMarksBreakup',
		Gender nvarchar(10) '@Gender',
		 FollowupDate date '@FollowupDate',
		FollowupRemark nvarchar(150) '@FollowupRemark',
		CreatedUserId bigint '@CreatedUserId' ,
		InquiryDate date '@InquiryDate',
		Number bigint '@Number',
		HandledBy nvarchar(100) '@HandledBy',
		InquiryStatus nvarchar(50) '@InquiryStatus'
		 
		
	)
	
	 --print 'check'
 
 
EXEC sp_xml_removedocument @intDoc
			
SELECT @lCount =  COUNT(Id) FROM #tTable

WHILE @lCount > 0 

BEGIN
		 
		SET @lFirstName = ''
		SET @lMiddleName = ''
		SET @lLastName = ''
		SET @lClassId = null
		SET @lClass = ''
		
		SET @lDOB  = ''
		SET @lStatusId =null
		--SET @lStatus  = ''
		SET @lPresentStreetOne = ''
		SET @lPresentStreetTwo = ''
		SET @lPresentStreetThree = ''
		SET @lPresentCountry = ''
		SET @lPresentState = ''
		SET @lPresentCity = ''
		SET @lPresentZipCode = ''
		SET @lParentContactNo = ''
		SET @lParentEmail = ''	
		SEt @lRemark = ''
		SEt @lInquiryModeId =null
		SET @lInquiryMode =''
		SET @lInquiryReferenceId =null
		SET @lInquiryReference =''
		SET @lAdmissionCategoryId =null
		SEt @lAdmissionCategory =''
		SEt @lPreviousSchool =''
		SEt @lMeritMarks =null
		SEt @lMeritGrade  =''
		SET @lMeritMarksBreakup =''
		SEt @lGenderId  =null
		SEt @lGender=''
		SEt @lFollowupDate =''
		SET @lFollowupRemark =''
		SEt @lInquiryDate =''
		SEt @lNumber =null
		SET @lHandledBy =''
		SET @lInquiryStatusId  =null
		SET @lInquiryStatus =''
		
	 
		--SET @OutStudentId = null

		
SELECT		
		 
		@lFirstName = FirstName,
		@lMiddleName = MiddleName,
		@lLastName = LastName,
		@lClass = Class,
		@lDOB = CASE WHEN DOB = '' THEN  NULL ELSE DOB END,
		--@lStatus = Status,
		@lPresentStreetOne = PresentStreetOne,
		@lPresentStreetTwo = PresentStreetTwo,
		@lPresentStreetThree = PresentStreetThree,
		@lPresentCountry = PresentCountry,
		@lPresentState = PresentState,
		@lPresentCity = PresentCity,
		@lPresentZipCode = PresentZipCode,
		@lParentContactNo = ParentContactNo,
		@lParentEmail = ParentEmail,
		@lRemark = Remark,
		@lInquiryMode =InquiryMode,
		@lInquiryReference = InquiryReference,
		@lAdmissionCategory  =AdmissionCategory,
		@lPreviousSchool  = PreviousSchool,
		@lMeritMarks = MeritMarks,
		@lMeritGrade  =MeritGrade,
		@lMeritMarksBreakup  =MeritMarksBreakup,
		@lGender  =Gender,
		@lFollowupDate =CASE WHEN FollowupDate = '' THEN  NULL ELSE FollowupDate END,
		@lFollowupRemark  =FollowupRemark,
		@lInquiryDate  =  CASE WHEN InquiryDate = '' THEN  NULL ELSE InquiryDate END,
		@lNumber =Number,
		@lHandledBy =HandledBy,
		@lInquiryStatus =InquiryStatus 
		
		 
											 	 
FROM #tTable WHERE Id = @lCount  
--print @lInquiryMode 
select *  FROM #tTable
	SELECT	@lGenderId = ID FROM sCommon.tGenderMaster WHERE Title = @lGender
	SELECT	@lClassId  = ID FROM sSetup.tClassMaster WHERE Title = @lClass AND OrgId = @rOrgId
	SELECT  @lInquiryModeId = ID from sAdmission.tInquiryModeMaster WHERE Title = @lInquiryMode 
	SELECT @lInquiryReferenceId =ID from sAdmission.tInquiryReferenceMaster Where Title = @lInquiryReference AND OrgGroupId = @rOrgGroupId
	Select @lInquiryStatusId = ID from sAdmission.tInquiryStatusMaster WHERE Title =@lInquiryStatus  AND  OrgGroupId =@rOrgGroupId
	Select @lStatusId = StatusId from sAdmission.tInquiryStatusMaster WHERE Id = @lInquiryStatusId
	
	SELECT	@lAdmissionCategoryId  = ID FROM tAdmissionCategoryMaster WHERE Title = @lAdmissionCategory AND OrgGroupId = @rOrgGroupId
	--SELECT	@lCastCategoryId  = ID FROM sCommon.tCastCategoryMaster WHERE Title = @lCastCategory AND OrgGroupId = @rOrgGroupId	
 
	
	IF(@lClassId IS NULL)
		SET @lClassId = 0
	IF(@lGenderId IS NULL)
		SET @lGenderId = 0
 
	IF(@lAdmissionCategoryId IS NULL)
		SET	@lAdmissionCategoryId = 0
	 
	 IF (@lInquiryModeId IS NULL)
		SET @lInquiryModeId=0
	IF (@lInquiryReferenceId IS Null)
		SET @lInquiryReferenceId=0
	IF (@lMeritMarks IS Null   )
		SET @lMeritMarks=0
	IF (@lNumber IS Null   )
		SET @lNumber=0 
		
 BEGIN TRANSACTION

 EXEC sAdmission.pAdmissionInquiryAdd 0,@lFirstName,@lMiddleName,@lLastName,@lClassId,@rBatchId,@lDOB,@rOrgId, @lInquiryStatusId,
									 @lPresentStreetOne,@lPresentStreetTwo,@lPresentStreetTwo,@lPresentCountry,@lPresentState,@lPresentCity,
									 @lPresentZipCode,@lParentContactNo,@lParentEmail,@lRemark,@lInquiryModeId,@lInquiryReferenceId,
									  @lAdmissionCategoryId,@lPreviousSchool,@lMeritMarks,@lMeritGrade,@lMeritMarksBreakup,
									  @lGenderId,@lFollowupDate,@lFollowupRemark,@rUserId,@lInquiryDate,@lNumber,@lHandledBy,@rOrgGroupId
	
		SET @lCount = @lCount - 1	
 
		 COMMIT TRANSACTION		
 
 
END
 

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


GO
ALTER PROCEDURE [sStudent].[pRptStudentAttendanceSummaryGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rOrgId smallint,
	 @rBatchId int,
	 @rClassId int,
	 @rDivisionId int,
	 @rFromDate date='',
	 @rToDate date='',
	 @rDepartmentId int,
	 @rAttendanceTypeId int,
	 @rIsDetail bit= 0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
CREATE TABLE #tmp
(
Builder1 nvarchar(max),
Builder2 nvarchar(max),
AcademicId bigint,
ClassId int,
DivisionId int,
DepartmentId int,
ClassName nvarchar(500),
DivisionName nvarchar(500),
IsPresent bit,
ClassOrderIndex int,
DivisionOrder int,
AttendanceDate Date,
RowNo int,
AttendanceType nvarchar(100),
AttendanceTypeId int,
GenderId int,
MonthTitle nvarchar(50),
MonthNumber int,
YearNumber int
)
INSERT INTO #tmp
SELECT 	@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		SA.AcademicId,
		SA.ClassId,
		SA.DivisionId,
		SA.DepartmentId,
		SA.ClassName,
		SA.DivisionName,
		ISNULL(SR.IsPresent,0)AS IsPresent,
		SA.ClassOrderIndex,
		SA.DivisionOrder,
		SR.AttendanceDate,		
		--1 AS AttendanceDay,
		Row_Number() OVER(PARTITION BY SA.ClassId,SA.DivisionId,SR.AttendanceDate ORDER BY SR.AttendanceDate ASC) AS RowNo,
		ATM.Title AS AttendanceType,
		SR.AttendanceTypeId,
		SA.GenderId,
		DATENAME(MONTH,SR.AttendanceDate) AS MonthTitle,
		DATEPART(MONTH,SR.AttendanceDate) AS MonthNumber,
		DATENAME(YEAR,SR.AttendanceDate) AS YearNumber
	FROM 
            sStudent.vStudentAcademic SA 
            INNER JOIN sStudent.tStudentAdmission AD ON SA.StudentId = AD.StudentId
			LEFT JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.AcademicId
			INNER JOIN sAttendance.tAttendanceTypeMaster ATM ON SR.AttendanceTypeId = ATM.Id
			AND (SR.AttendanceTypeId=@rAttendanceTypeId OR @rAttendanceTypeId = 0)
			AND ((SR.AttendanceDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
    		AND ((SR.AttendanceDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			--INNER JOIN #tmpDates tmp ON tmp.AllDates = SR.AttendanceDate
		Where SA.OrgId = @rOrgId
			  AND SA.BatchId = @rBatchId
			  AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
			  AND ((SA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))
			  AND ((SA.DepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))
			
			  AND SA.StatusId = 1
			  AND (AD.LeftDate > SR.AttendanceDate OR ISNULL(AD.LeftDate,'')= '')
			  AND (AD.AdmissionDate <= SR.AttendanceDate)
			  Order By SA.ClassOrderIndex,SA.DivisionOrder,SR.AttendanceDate
			   
SELECT
Builder1,
Builder2,
@rIsDetail AS IsDetail,
AcademicId,
ClassId,
DivisionId,
DepartmentId,
ClassName,
DivisionName,
IsPresent,
ClassOrderIndex,
DivisionOrder,
AttendanceDate,
(CASE WHEN RowNo = 1 THEN 1 ELSE 0 END)AS AttendanceDay,
AttendanceType,
AttendanceTypeId,
GenderId,
MonthTitle,
MonthNumber,
YearNumber
FROM
#tmp

DROP TABLE #tmp

--Select
--'' AS Builder1,
--'' AS Builder2,
--0 AS IsDetail,
--CONVERT(bigint,0) AS AcademicId,
--0 AS ClassId,
--0 AS DivisionId,
--0 AS DepartmentId,
--'' AS ClassName,
--'' AS DivisionName,
--CONVERT(bit,0) AS IsPresent,
--0 AS ClassOrderIndex,
--0 AS DivisionOrder,
--CONVERT(DATE,'') AS AttendanceDate,
--0 AS AttendanceDay,
--'' AS AttendanceType,
--0 AS AttendanceTypeId,
--0 AS GenderId,
--'' AS MonthTitle,
--0 AS MonthNumber,
--0 AS YearNumber
END
GO
PRINT N'Altering [sStudent].[pRptStudentRegisterGet]...';


GO
ALTER PROCEDURE [sStudent].[pRptStudentRegisterGet]
	 
	 @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,
	 @rClassStatusId int,
	 @rDateOfBirth int,
	 @rDepartmentId int,
	 @rFromAdmissionDate date='', 
     @rToAdmissionDate date='',
     @rFromStudentCode nvarchar(max)='',
     @rToStudentCode nvarchar(max)='',
	 @rFromNumber int = 0,
	 @rToNumber int = 0  
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 

	SELECT  
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			SD.AcademicId,
			SD.StudentId, 
			SD.ClassId,
			SD.DivisionId,
			SD.ClassDivision,
			SD.Code,
			SD.RollNo,			
			SD.FirstName,
			SD.MiddleName,			
			SD.LastName,
			SD.Name,		
			SD.ClassName,
			SD.DivisionName,
			SD.StatusName,
			SD.StatusId,
			SD.LCProgress,
			SD.Religion,
			SD.FamilyCast,
			SD.FamilySubCast,
			SD.LCConduct,
			SD.BirthPlace,
			SD.BirthTaluka,
			SD.BirthDistrict,
			SD.LeftDate,
			SD.PreviousSchool,
			SD.DateOfBirth,
			SD.BirthDateInWord,
			SD.LeftReason,
			SD.AdmissionDate,
			SD.AdmissionStandard,
			SD.LeftStandard,
			SD.LCNumber,
			SD.LCDate,
			SD.StudentPhoto,
			SD.BloodGroup,
			SD.PresentAddress,
			SD.ContactNo,
			SD.Batch,
			SD.InactiveDate,
			OM.Title AS OrgName,
			SF.MotherName,
			SD.DivisionOrder,
			SD.Number AS StudentNumber,
			SF.FatherName,
			SD.Nationality,
			SD.MotherTongue,
			SD.BirthState,
			SD.BirthCountry,
			SD.SUId,
            SD.AdhaarNumber,
            SD.ClassStatusId,
            SD.ClassStatusName,
			SD.UIDNumber,
			SD.Gender,
			SF.FatherOfficeContactNo,
			SF.MotherOfficeContactNo
			
	FROM 
			sStudent.vStudentAllDetail SD
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=SD.OrgId
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId=SD.StudentId
			INNER JOIN sSetup.tBatchClass BC ON BC.ClassID =  SD.ClassID AND BC.BatchId = SD.BatchId AND SD.BatchId= @rBatchId
			--LEFT JOIN sStudent.tStudentAdmission SAM ON SD.StudentId=SAM.StudentId				
			--AND ((SAM.AdmissionDate>=@rFromAdmissionDate)OR(ISNULL(@rFromAdmissionDate,'')=''))    
			--AND ((SAM.AdmissionDate<=@rToAdmissionDate)OR(ISNULL(@rToAdmissionDate,'')=''))  
			--AND	SAM.BatchId = @rBatchId   
	WHERE 
		SD.OrgId=@rOrgId
		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.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))
		AND ((MONTH(SD.DateOfBirth)=@rDateOfBirth OR @rDateOfBirth=0))
	    AND ((SD.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
	    AND((SD.Code>=@rFromStudentCode) OR (ISNULL(@rFromStudentCode,'')=''))
	    AND((SD.Code<=@rToStudentCode) OR (ISNULL(@rToStudentCode,'')=''))
		AND((SD.Number>=@rFromNumber) OR (ISNULL(@rFromNumber,0)=0))
	    AND((SD.Number<=@rToNumber) OR (ISNULL(@rToNumber,0)=0))
		AND((SD.AdmissionDate>=@rFromAdmissionDate) OR (ISNULL(@rFromAdmissionDate,'')=''))		
		AND((SD.AdmissionDate<=@rToAdmissionDate) OR (ISNULL(@rToAdmissionDate,'')=''))			
	   
	 Order by
	 SD.RollNo
END
GO
PRINT N'Altering [sStudent].[pStudentCustomFieldAdd]...';


GO

ALTER PROCEDURE [sStudent].[pStudentCustomFieldAdd]
		 
	@rId int,
	@rOrgId int,
	@rFieldTitle nvarchar(500),
	@rFieldTypeId tinyint,
	@rFieldList nvarchar(500),
	@rIsFieldMandatory bit,
	@rFieldGroup nvarchar(200),
	@rFieldOrder smallint,
	@rCreatedUserId bigint,	
	@rCreatedDateTime datetime,
	@rUpdatedUserId bigint,
	@rUpdatedDateTime datetime,
	@rIsObsolete int =0,
	@rDataTypeId int = 1

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

BEGIN TRY
BEGIN TRANSACTION	

DECLARE @lOrgGroupId int=0
SELECT @lOrgGroupId= OrgGroupId FROM sSetup.tOrganizationMAster WHERE Id = @rOrgId
 
IF(@rId = 0)	
BEGIN
    IF NOT EXISTS(SELECT 2 FROM sStudent.tStudentCustomFieldMaster WHERE FieldTitle=@rFieldTitle AND FieldGroup=@rFieldGroup AND DataId=@rDataTypeId )
    --IF NOT EXISTS(SELECT 2 FROM sStudent.tStudentCustomFieldMaster WHERE FieldTitle=@rFieldTitle)
	BEGIN
	      DECLARE @lNextNumber int
	      EXECUTE sCommon.pTableRowIdGet @lOrgGroupId, 'sStudent.tStudentCustomFieldMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
Print @lNextNumber
	      INSERT INTO sStudent.tStudentCustomFieldMaster
	      (
		    Id
		   ,FieldTitle
		   ,FieldTypeId
		   ,FieldList
		   ,IsFieldMandatory
		   ,FieldGroup
		   ,FieldOrder
		   ,CreatedUserId
		   ,CreatedDateTime
		   ,OrgGroupId
		   ,IsObsolete
		   ,DataId
	      )
	     VALUES
	     (
		   @lNextNumber
		  ,@rFieldTitle
		  ,@rFieldTypeId
		  ,@rFieldList
		  ,@rIsFieldMandatory
		  ,@rFieldGroup
		  ,@rFieldOrder
		  ,@rCreatedUserId
		  ,@rCreatedDateTime
		  ,@lOrgGroupId
		  ,@rIsObsolete
		  ,@rDataTypeId
	     )
     END
	 ELSE
	 SELECT -101 As RESULT
END
	 	 
ELSE
BEGIN
	SET @lNextNumber = @rId

	
	
		UPDATE sStudent.tStudentCustomFieldMaster
		SET 
		FieldTitle = @rFieldTitle
		,FieldTypeId = @rFieldTypeId
		,FieldList=@rFieldList
		,IsFieldMandatory=@rIsFieldMandatory
		,IsObsolete=@rIsObsolete
		,FieldGroup=@rFieldGroup
		,FieldOrder=@rFieldOrder
		,UpdatedUserId=@rUpdatedUserId
		,UpdatedDateTime=@rUpdatedDateTime
		,DataId = @rDataTypeId
		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 [sStudent].[pStudentFullProfileGet]...';


GO
 
 
ALTER PROCEDURE [sStudent].[pStudentFullProfileGet]
	 
	 @rBatchId int,
	 @rStudentId bigint,
	 @rReportId int=0,
	 @rOrgId int,
	 @rStrCode nvarchar(max)='',
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rFromRollNo int=0,
	 @rToRollNo int=0,
	 @rStatusId int=0,
	 @rClassStatusId int=0,
	 @rDateOfBirth int=0,
	 @rDepartmentId int=0,
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='',
	 @rOrgGroupBatchId int,
	 @rFromAdmissionDate date = '',
	 @rToAdmissionDate date = ''
	 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	
	DECLARE @lAcademicId bigint
	SELECT @lAcademicId = Id from sStudent.tAcademic Where StudentId = @rStudentId AND BatchId = @rBatchId
	
	SELECT 
			--Academic
			@rBuilder1 As Builder1,
			SA.StudentId AS Id,
			--SA.FirstName + ' ' + ISNULL(SA.MiddleName,'') + ' ' + 	SA.LastName AS StudentName,
			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
			CASE WHEN @rReportId=0 THEN ISNULL(SA.DateOfBirth,'0001/01/01')  
			WHEN @rReportId=1 THEN  SA.DateOfBirth END  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,
			CASE WHEN @rReportId=0 THEN ISNULL(SA.AdmissionDate,'0001/01/01')
			WHEN @rReportId=1 THEN  SA.AdmissionDate END AS AdmissionDate,
	
			ISNULL(SA.PreviousSchool,'') AS PreviousSchool,
			ISNULL(SA.AdmissionCategory,'') AS StudentAdmissionCategory,
			CASE WHEN @rReportId=0 THEN ISNULL(SA.LeftDate,'0001/01/01')
			WHEN @rReportId=1 THEN  SA.LeftDate END AS LeftDate,
						 
			ISNULL(SA.LeftStandard,'') AS LeftStandard,
			--ISNULL(SA.InactiveDate,'0001/01/01') AS InactiveDate,
			CASE WHEN @rReportId=0 THEN ISNULL(SA.InactiveDate,'0001/01/01')
			WHEN @rReportId=1 THEN  SA.InactiveDate END AS InactiveDate,		
			ISNULL(SA.LCNumber,'') AS LCNumber,
			--ISNULL(SA.LCDate,'0001/01/01') AS LCDate,
			 CASE WHEN @rReportId=0 THEN ISNULL(SA.LCDate,'0001/01/01')
			WHEN @rReportId=1 THEN  SA.LCDate END 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,
					
	   	    --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,
	   	   CASE WHEN @rReportId=0
			THEN ISNULL(SA.StudentPhoto, CONVERT(VARBINARY(MAX), 0))
			WHEN @rReportId=1
			THEN ISNULL(SA.StudentPhoto, CONVERT(VARBINARY(MAX), ''))
			END AS StudentPhoto,
			
			CASE WHEN @rReportId=0
			THEN ISNULL(SA.MotherPhoto, CONVERT(VARBINARY(MAX), 0))
			WHEN @rReportId=1
			THEN ISNULL(SA.MotherPhoto, CONVERT(VARBINARY(MAX), ''))
			END AS MotherPhoto,
			
			CASE WHEN @rReportId=0
			THEN ISNULL(SA.FatherPhoto, CONVERT(VARBINARY(MAX), 0))
			WHEN @rReportId=1
			THEN ISNULL(SA.FatherPhoto, CONVERT(VARBINARY(MAX), ''))
			END AS FatherPhoto,
			
			CASE WHEN @rReportId=0
			THEN ISNULL(SA.RelativePhoto, CONVERT(VARBINARY(MAX), 0))
			WHEN @rReportId=1
			THEN ISNULL(SA.RelativePhoto, CONVERT(VARBINARY(MAX), ''))
			END 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(EI.EmployeePhoto, CONVERT(VARBINARY(MAX), 0)) AS TeacherPhoto,
		    ISNULL(DF.IsDisplayFamilyDetail,0) AS IsDisplayFamilyDetail,
		    ISNULL(DF.IsDisplaySiblingDetail,0) AS IsDisplaySiblingDetail,
		    ISNULL(DF.IsDisplayPassportDetail,0) AS IsDisplayPassportDetail,
		    ISNULL(DF.IsDisplayBankDetail,0) AS IsDisplayBankDetail,
		    ISNULL(DF.IsDisplayCBSEREGDetail,0) AS IsDisplayCBSEREGDetail,
		    ISNULL(DF.IsDisplayCollegeDetail,0) AS IsDisplayCollegeDetail,
		    ISNULL(DF.IsDisplayGOVREGNoDetail,0) AS IsDisplayGOVREGNoDetail,
		    ISNULL(DF.IsDisplayHealthDetail,0) AS IsDisplayHealthDetail,
		    ISNULL(DF.IsDisplayTransportDetail,0) AS IsDisplayTransportDetail,
		    ISNULL(DF.IsDisplayHostelDetail,0) AS IsDisplayHostelDetail,
		    ISNULL(DF.IsDisplayClubDetail,0) AS IsDisplayClubDetail,
		    
		    ISNULL(DF.IsDisplaySSCResultDDetail,0) AS IsDisplaySSCResultDDetail,
		    ISNULL(DF.IsDisplayHSCResultDetail,0) AS IsDisplayHSCResultDetail,
		    ISNULL(DF.IsDisplayJeeDetail,0) AS IsDisplayJeeDetail,
		    ISNULL(DF.IsDisplayDiplomaDetail,0) AS IsDisplayDiplomaDetail,
			ISNULL(DF.IsDisplayClassTeacherDetail,0) AS IsDisplayClassTeacherDetail,
		    --Sibling Detail
		    isnull(SS.SiblingName1,'') AS SiblingName1,
	        ISNULL (SS.SiblingInstitue1,'') AS SiblingInstitue1,
	        ISNULL(SS.SiblingClass1,'')AS SiblingClass1,
	        ISNULL(SS.SiblingAge1,'')AS SiblingAge1,
	        ISNULL(SS.SiblingRelation1,'')AS SiblingRelation1,
	        isnull(SS.SiblingName2,'') AS SiblingName2,
	        ISNULL(SS.SiblingInstitue2,'')AS SiblingInstitue2,
	        ISNULL(SS.SiblingClass2,'')AS SiblingClass2,
	        ISNULL(SS.SiblingAge2,'') AS SiblingAge2,
	        ISNULL(SS.SiblingRelation2,'')AS SiblingRelation2,
	        isnull(SS.SiblingName3,'') AS SiblingName3,
	        ISNULL( SS.SiblingInstitue3,'')AS SiblingInstitue3,
	        ISNULL(SS.SiblingClass3,'')AS SiblingClass3,
	        ISNULL(SS.SiblingAge3,'')AS SiblingAge3,
	        ISNULL(SS.SiblingRelation3,'')AS SiblingRelation3,
	        ISNULL(SAD.BankAccountNumber,'')AS BankAccountNumber,
	        ISNULL(SAD.BankName,'')AS BankName,
	        ISNULL(SAD.BankBranch,'') AS BankBranch,
	        ISNULL(SAD.BankIFSCCode,'')AS BankIFSCCode,
	        ISNULL(SAD.Class9BoardRegistrationNumber,'') AS Class9BoardRegistrationNumber,
	        ISNULL(SAD.Class11BoardRegistrationNumber,'')AS Class11BoardRegistrationNumber,
	        ISNULL(SAD.PassportNumber,'')AS PassportNumber, 
	        ISNULL(SAD.PassportType,'') AS PassportType,
	       ISNULL( SAD.PassportCountryCode,'') AS PassportCountryCode,
	        CASE WHEN @rReportId=0 THEN ISNULL(SAD.PassportIssueDate,'0001/01/01')
			WHEN @rReportId=1 THEN  SAD.PassportIssueDate END AS PassportIssueDate,
			CASE WHEN @rReportId=0 THEN ISNULL(SAD.PassportExpiryDate,'0001/01/01')
			WHEN @rReportId=1 THEN  SAD.PassportExpiryDate END AS PassportExpiryDate,
	        ISNULL(SA.UIDNumber,'')AS UIDNumber,
	        ISNULL(SA.AdhaarNumber,'') AS AdhaarNumber,
	       ISNull(SA.StatusId,0) AS StatusId,
	       ISNUll(SA.IsTransfer,0)AS IsTransfer,
	       ISNULL(SA.TransferFrom,'') AS TransferFrom,
	       ISNULL(SA.CertificateName,'') AS CertificateName,
	       ISNUll(SA.IsTFWS,0)AS IsTFWS,
	       ISNUll(SA.IsCertificateHolder,0)AS IsCertificateHolder,
	       ISNULL(CD.SSCBoard,'') AS SSCBoard,
	       ISNULL(CD.SSCSchool,'') AS SSCSchool,
	       ISNULL(CD.SSCPassingYear,'') AS SSCPassingYear,
	       ISNULL(CD.SSCObtainMarks,0) AS SSCObtainMarks,
	       ISNULL(CD.SSCOutOfMarks,0) AS SSCOutOfMarks,
	       ISNULL(CD.SSCPercentage,0) AS SSCPercentage,
	       ISNULL(CD.SSCMathMarks,0) AS SSCMathMarks,
	       ISNULL(CD.SSCMathOutOfMarks,0) AS SSCMathOutOfMarks,
	       ISNULL(CD.SSCPercentile,0) AS SSCPercentile,
	       ISNULL(CD.SSCGrade,0) AS SSCGrade,
	       ISNULL(CD.HSCBoard,'') AS HSCBoard,
	       ISNULL(CD.HSCSchool,'') AS HSCSchool,
	       ISNULL(CD.HSCPassingYear,0) AS HSCPassingYear,
	       ISNULL(CD.HSCObtainMarks,0) AS HSCObtainMarks,
	       ISNULL(CD.HSCOutOfMarks,0) AS HSCOutOfMarks,
	       ISNULL(CD.HSCPercentage,0) AS HSCPercentage,
	       ISNULL(CD.HSCPhysicsMarks,0) AS HSCPhysicsMarks,
	       ISNULL(CD.HSCPhysicsOutOfMarks,0) AS HSCPhysicsOutOfMarks,
	       ISNULL(CD.HSCChemistryMarks,0) AS HSCChemistryMarks,
	       ISNULL(CD.HSCChemistryOutOfMarks,0) AS HSCChemistryOutOfMarks,
	       ISNULL(CD.HSCMathMarks,0) AS HSCMathMarks,
	       ISNULL(CD.HSCMathOutOfMarks,0) AS HSCMathOutOfMarks,
	       ISNULL(CD.HSCBiologyMarks,0) AS HSCBiologyMarks,
	       ISNULL(CD.HSCBiologyOutOfMarks,0) AS HSCBiologyOutOfMarks,
	       ISNULL(CD.PCMMarks,0) AS PCMMarks,
	       ISNULL(CD.PCBMarks,0) AS PCBMarks,
	       ISNULL(CD.JEERollNo,'') AS JEERollNo,
	       ISNULL(CD.JEEMeritNo,'') AS JEEMeritNo,
	       ISNULL(CD.JEEMeritMarks,0) AS JEEMeritMarks,
	       ISNULL(CD.JEEOutOfMarks,0) AS JEEOutOfMarks,
	       ISNULL(CD.DiplomaBoard,'') AS DiplomaBoard,
	       ISNULL(CD.DiplomaCollege,'') AS DiplomaCollege,
	       ISNULL(CD.DiplomaPassingYear,'') AS DiplomaPassingYear,
	       ISNULL(CD.DiplomaObtainMarks,0) AS DiplomaObtainMarks,
	       ISNULL(CD.DiplomaOutOfMarks,0) AS DiplomaOutOfMarks,
	       ISNULL(CD.DiplomaPercentage,0) AS DiplomaPercentage,
	       ISNULL(CD.ApplicationNo,'') AS ApplicationNo,
	       ISNULL(CD.AdmissionRound,0) AS AdmissionRound,
	       ISNULL(CD.MaritalStatusId,0) AS MaritalStatusId,
	       ISNULL(MS.Title,'') AS MaritalStatus,
	       ISNULL(ACD.RepeatCount,1)AS RepeatCount,
	       ISNULL(SA.MotherTongue,'') As MotherTongue,
	       ISNULL(SA.FamilyCast,'') AS FamilyCast,
	      ISNULL(CM.Nationality,'') AS Nationality,
	       ISNULL(CT.Title,'') AS CasteCategory,
	       ISnull(SA.ClassName,'') AS ClassName ,
	       ISnull( SA.DivisionName,'') AS DivisionName,
	      ISNULL( SF.IsFatherExStudent,0) AS IsFatherExStudent,
	       ISnull(SF.FatherPassOutYear,'') AS FatherPassOutYear,
	       Isnull(SF.IsMotherExStudent,0) AS IsMotherExStudent,
	       Isnull(SF.MotherPassOutYear,'') AS MotherPassOutYear,
	       ISNULL(SF.IsRelativeExStudent,0) AS IsRelativeExStudent,
	       ISNULL(SF.RelativePassOutYear,'') AS RelativePassOutYear,
	       ISNULL(Sa.PresentDistanceFromSchool,0) AS PresentDistanceFromSchool,
	        SA.StudentId,
	        SA.ClassId,
	        SA.DivisionId,
	        SA.BirthState,
	        SA.BirthCountry,
	         ISNULL(SA.PreviousStandard,'')AS PreviousStandard
	        ,ISNULL(CGG.Title,'') AS CustomGroup
			,ISNULL(SGM.Title,'') As StudentGroup
			,ISNULL(SOGM.Title,'') As StudentOtherGroup
			,ISNULL([sStudent].[fAssignedClubGet](@lAcademicId),'') AS ClubName
			,ISNULL([sStudent].[fAssignedCustomTagGet](@lAcademicId),'') AS CustomTag 
	        ,SA.ClassStatusId
	        ,SA.ClassStatusName
	        ,PDCM.Title As PhysicalDisabilityCategory
			,ISNULL(SAM.PreviousLCNumber,'') AS PreviousLCNumber
			,ISNULL(SAM.PreviousLCDate,'') AS PreviousLCDate,
			ISNULL(SAM.AdmissionNumber,'') AS  AdmissionNumber,
			ISNULL(SAM.AdmissionFormNumber,'') AS  AdmissionFormNumber,
			SA.SUId,
	       --[sHostel].[fHostelWardenGet](HM.Id) As WardenName
		   MS.Title AS MaritalStatus

  FROM 
           sStudent.vStudentAllDetail SA
          -- LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
           LEFT JOIN sStudent.tStudentHealth SH ON SA.StudentId=SH.StudentId
           LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SA.StudentId 
          -- LEFT JOIN sStudent.tStudentOther SO ON SO.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
            (
		   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 sHostel.tHostelWarden HW ON HW.HostelId=HM.Id
           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 
           ( 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
  WHERE 
			((SA.StudentId=@rStudentId)OR(@rStudentId=0))
			AND((SA.BatchId=@rBatchId) OR(@rBatchId=0))
			AND (ISNULL(SA.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rStrCode,',')) OR @rStrCode='') 
			AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
			AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			AND ((SA.StudentId=@rStudentId) OR (@rStudentId=0))
			AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
			AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
			AND ((SA.StatusId=@rStatusId)OR(@rStatusId=0))
			AND ((SA.ClassStatusId=@rClassStatusId)OR(@rClassStatusId=0))
			AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
			AND ((SA.OrgGroupBatchId=@rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
			AND ((SA.AdmissionDate >= @rFromAdmissionDate) OR (ISNULL(@rFromAdmissionDate,'') = ''))
			AND ((SA.AdmissionDate <= @rToAdmissionDate) OR (ISNULL(@rToAdmissionDate,'') = ''))
			--AND(SA.OrgId=@rOrgId)
			
END
GO
PRINT N'Altering [sStudent].[pStudentGenerateReport]...';


GO

ALTER PROCEDURE [sStudent].[pStudentGenerateReport]
	@rId bigint,
	@rTitle nvarchar(50),
	@rColumnName nvarchar(max) = '',
	@rOrderBy nvarchar(max) = 'RollNo',
	@rOrgId smallint,
	@rCode [nvarchar](20) = '',
	@rFirstName [nvarchar](50) = '',	
	@rLastName [nvarchar](50) = '',
	@rCountry [nvarchar](50) = '',
	@rState [nvarchar](50) = '',
	@rCity nvarchar(max) = '',
	@rArea nvarchar(max) = '',
	@rDivisionId nvarchar(max) = '',
	@rStatusId nvarchar(max) = '',
	@rTransportModeId nvarchar(max) = '',
	@rBusRouteDestinationId nvarchar(max) = '',
	@rBloodGroupId nvarchar(max) = '',
	@rGenderId nvarchar(max) = '',
	@rReligionId nvarchar(max) = '',
	@rCastCategoryId nvarchar(max) = '',
	@rHouseId nvarchar(max) = '',
	@rMotherTongueId nvarchar(max) = '',
	@rNationalityId nvarchar(max) = '',
	@rHobby nvarchar(50) = '',
	@rFatherQualification nvarchar(max) = '',
	@rMotherQualification nvarchar(max) = '',
	@rFatherOccupation nvarchar(max) = '',
	@rMotherOccupation nvarchar(max) = '',
	@rPreviousSchool nvarchar(max) = '',
	@rAdmissionCategoryId nvarchar(max) = '',
	@rDOBFromDate Date = '0001-01-01',
	@rDOBToDate Date = '9999-12-31',
	@rDOAFromDate Date = '0001-01-01',
	@rDOAToDate Date = '9999-12-31',
	@rDOLFromDate Date = '0001-01-01',
	@rDOLToDate Date = '9999-12-31',
	@rIsPysicalDeformity bit,
	@rIsMajorIllness bit,
	@rIsCommon bit,
	@rIsCommonForOrg bit,
	@rCreatedUserId bigint,
	@BatchId int,
	@rIsBlackList bit,
	@rFromCode nvarchar(20), 
	@rToCode nvarchar(20),
	@rSpecificCode nvarchar(max),
	@rDropDownStatusId int,
	@rDropDownClassId int,
	@rDropDownDivisionId int,
	@rCustomTagId nvarchar(max) = '',
	@rCustomGroupId nvarchar(max) = '',
	@rClubId nvarchar(max) = '',
	@rRepeatCount smallint=0,
	@rStudentStatusId smallint=0,
	@rHostelId nvarchar(max) = '',
	@rStudentGroupId nvarchar(max) = '',
	@rStudentOtherGroupId nvarchar(max) = '',
	@rOrgGroupBatchId int,
	@rBusRouteId nvarchar(max) = '',
	@rFeeExemption nvarchar(max)='',
	@rRecordTagId nvarchar(max) = '',
	@rContactNo nvarchar(50) = '',
	@rBirthDay int =0,
	@rDateOfMonth int =0,
	@rStopApplicationAccess int = 0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
		IF(@rHostelId IS NULL)
			SET @rHostelId = ''
		IF(@rStudentGroupId IS NULL)
			SET @rStudentGroupId = ''
		IF(@rStudentOtherGroupId IS NULL)
			SET @rStudentOtherGroupId = ''	
		IF(@rOrgGroupBatchId IS NULL)
			SET @rOrgGroupBatchId = 0
		IF(@rGenderId IS NULL)
			SET @rGenderId = ''
		IF(@rBusRouteId IS NULL)
			SET @rBusRouteId = ''	
		IF(@rDOBFromDate IS NULL)
			SET @rDOBFromDate='0001-01-01'
		IF(@rDOBToDate IS NULL)
			SET @rDOBToDate='9999-12-31'
		IF(@rDOAFromDate IS NULL)
			SET @rDOAFromDate='0001-01-01'
		IF(@rDOAToDate IS NULL)
			SET @rDOAToDate='9999-12-31'
		IF(@rDOLFromDate IS NULL)
			SET @rDOLFromDate='0001-01-01'
		IF(@rDOLToDate IS NULL)
			SET @rDOLToDate='9999-12-31'
		
		IF(@rTitle != '' AND @rId = 0)
		BEGIN
			DECLARE @lNextNumber BIGINT
			EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sStudent.tStudentCustomSearch', 0, 1, 1,@outNextNumber = @lNextNumber output
			INSERT INTO sStudent.tStudentCustomSearch
			(
				Id,Title,ColumnName,OrderBy,OrgId,Code,FirstName,LastName,Country,State,City,Area,DivisionId,
				StatusId,TransportModeId,BusRouteDestinationId,BloodGroupId,GenderId,ReligionId,CastCategoryId,
				HouseId,MotherTongueId,NationalityId,Hobby,FatherQualification,MotherQualification,FatherOccupation,
				MotherOccupation,PreviousSchool,AdmissionCategoryId,DOBFromDate,DOBToDate,DOAFromDate,DOAToDate,
				DOLFromDate,DOLToDate,IsPysicalDeformity,IsMajorIllness,IsCommon,IsCommonForOrg, CreatedUserId,CreatedDateTime,
				IsBlackList,FromCode,ToCode,CustomTag,CustomGroup,Club,RepeatCount,StudentStatusId,Hostel,StudentGroup,
				StudentOtherGroup,FeeExemption,RecordTag,ContactNo,BirthDay,DateOfMonth,IsStopApplicationAccess
			)
			VALUES
			(
				@lNextNumber,@rTitle,@rColumnName,@rOrderBy,@rOrgId,@rSpecificCode,@rFirstName,@rLastName,@rCountry,@rState,
				@rCity,@rArea,@rDivisionId,@rStatusId,@rTransportModeId,@rBusRouteDestinationId,@rBloodGroupId,@rGenderId,
				@rReligionId,@rCastCategoryId,@rHouseId,@rMotherTongueId,@rNationalityId,@rHobby,@rFatherQualification,
				@rMotherQualification,@rFatherOccupation,@rMotherOccupation,@rPreviousSchool,@rAdmissionCategoryId,
				@rDOBFromDate,@rDOBToDate,@rDOAFromDate,@rDOAToDate,@rDOLFromDate,@rDOLToDate,@rIsPysicalDeformity,
				@rIsMajorIllness,@rIsCommon,@rIsCommonForOrg,@rCreatedUserId,sCommon.fGetDate(),@rIsBlackList,@rFromCode,@rToCode,
				@rCustomTagId,@rCustomGroupId,@rClubId,@rRepeatCount,@rStudentStatusId,@rHostelId,@rStudentGroupId,
				@rStudentOtherGroupId,@rFeeExemption,@rRecordTagId,@rContactNo,@rBirthDay,@rDateOfMonth,@rStopApplicationAccess
			)
		END
		
		
		IF(@rId > 0)
		BEGIN
			Select @rColumnName=ColumnName,@rOrderBy=OrderBy,@rOrgId=OrgId,@rSpecificCode=Code,@rFirstName=FirstName,
			@rLastName=LastName,@rCountry=Country,@rState=State,@rCity=City,@rArea=Area,@rDivisionId=DivisionId,
			@rStatusId=StatusId,@rTransportModeId=TransportModeId,@rBusRouteDestinationId=BusRouteDestinationId,
			@rBloodGroupId=BloodGroupId,@rGenderId=GenderId,@rReligionId=ReligionId,@rCastCategoryId=CastCategoryId,
			@rHouseId=HouseId,@rMotherTongueId=MotherTongueId,@rNationalityId=NationalityId,@rHobby=Hobby,
			@rFatherQualification=FatherQualification,@rMotherQualification=MotherQualification,
			@rFatherOccupation=FatherOccupation,@rMotherOccupation=MotherOccupation,
			@rPreviousSchool=PreviousSchool,@rAdmissionCategoryId=AdmissionCategoryId,
			@rDOBFromDate=DOBFromDate,@rDOBToDate=DOBToDate,@rDOAFromDate=DOAFromDate,
			@rDOAToDate=DOAToDate,@rDOLFromDate=DOLFromDate,@rDOLToDate=DOLToDate,
			@rIsPysicalDeformity=IsPysicalDeformity,@rIsMajorIllness=IsMajorIllness,
			@rIsBlackList=IsBlackList,@rFromCode=FromCode,@rToCode=ToCode,
			@rCustomTagId=CustomTag,@rCustomGroupId = CustomGroup,@rClubId = Club,
			@rRepeatCount = RepeatCount,@rStudentStatusId =StudentStatusId,
			@rHostelId = Hostel,@rStudentGroupId = StudentGroup,
			@rStudentOtherGroupId = StudentOtherGroup,@rFeeExemption =FeeExemption,
			@rRecordTagId=RecordTag,@rContactNo=ContactNo,@rStopApplicationAccess=IsStopApplicationAccess
			FROM sStudent.tStudentCustomSearch WHERE Id=@rId
		END
		
		DECLARE @ListofCodes TABLE(Code nvarchar(25), ID INT IDENTITY(1,1));
			INSERT INTO @ListofCodes
	     
		SELECT q2.value from
			(SELECT cast('<x>'+replace(@rSpecificCode,',','</x><x>')+'</x>' as xml) as thexml)q1 CROSS APPLY
			(SELECT x.value('.','nvarchar(max)') as value FROM thexml.nodes('x') as f(x))q2
		
		SET @rOrderBy=Replace(@rOrderBy,'GR No','Code')
		SET @rOrderBy=Replace(@rOrderBy,'ID No','Code')
		SET @rColumnName=Replace(@rColumnName,'GR No','Code')
		SET @rColumnName=Replace(@rColumnName,'ID No','Code')
		SET @rColumnName=Replace(@rColumnName,'PhysicalDeformityRemark','PysicalDeformityRemark')
		SET @rColumnName=Replace(@rColumnName,'IsPhysicalDeformity','IsPysicalDeformity')
		SET @rOrderBy=Replace(@rOrderBy,'PhysicalDeformityRemark','PysicalDeformityRemark')
		SET @rOrderBy=Replace(@rOrderBy,'IsPhysicalDeformity','IsPysicalDeformity')
		
		DECLARE @Sql nvarchar(MAX)= ''
		
		SET @rSpecificCode = sCommon.fSearchStringGet(@rSpecificCode)
		SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
		SET @rLastName = sCommon.fSearchStringGet(@rLastName)
		SET @rCountry = sCommon.fSearchStringGet(@rCountry)
		SET @rState = sCommon.fSearchStringGet(@rState)
		
		 IF  EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='tTempStudent1')
		 BEGIN
			DROP Table sStudent.tTempStudent1
		 END
		 IF  EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='tTempStudent2')
		 BEGIN		
			DROP Table sStudent.tTempStudent2
		 END
		 IF  EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='tTempStudent3')
		 BEGIN
			DROP Table sStudent.tTempStudent3
		 END
		 IF  EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='tTempStudent4')
		 BEGIN
			DROP Table sStudent.tTempStudent4
		 END
		 IF  EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='tTempStudent5')
		 BEGIN
			DROP Table sStudent.tTempStudent5  
		 END
		 IF  EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='tTempStudent6')
		 BEGIN
			DROP Table sStudent.tTempStudent6
		 END
		 
		 IF  EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='tTempStudent7')
		 BEGIN
			DROP Table sStudent.tTempStudent7
		 END
		 
		 IF  EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='tTempStudent8')
		 BEGIN
			DROP Table sStudent.tTempStudent8
		 END
		 IF  EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='tTempStudent9')
		 BEGIN
			DROP Table sStudent.tTempStudent9
		 END
		 IF  EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='tTempStudent10')
		 BEGIN
			DROP Table sStudent.tTempStudent10
		 END
		 IF  EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='tTempStudent11')
		 BEGIN
			DROP Table sStudent.tTempStudent11
		 END
		 IF  EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='tTempStudent12')
		 BEGIN
			DROP Table sStudent.tTempStudent12
		 END
		 IF  EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='tTempStudent13')
		 BEGIN
			DROP Table sStudent.tTempStudent13
		 END
		  IF  EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='tTempStudent14')
		 BEGIN
			DROP Table sStudent.tTempStudent14
		 END
		
		SELECT  DISTINCT SM.Id AS StudentId6,
		CASE WHEN SF.IsFatherExStudent = 0 THEN 'No' WHEN SF.IsFatherExStudent = 1 THEN 'Yes' ELSE '' END AS IsFatherExStudent,
		CASE WHEN SF.IsMotherExStudent = 0 THEN 'No' WHEN SF.IsMotherExStudent = 1 THEN 'Yes' ELSE '' END AS IsMotherExStudent,
		SF.FatherOrganization, SF.FatherDesignation, SF.MotherOrganization, SF.MotherDesignation, SF.RelativeOrganization, SF.RelativeDesignation
		INTO sStudent.tTempStudent11
		FROM sStudent.tStudentMaster SM
			 INNER JOIN sStudent.tAcademic A ON A.StudentId = SM.Id AND ((SM.OrgId = @rOrgId) OR (@rOrgId=0)) AND ((A.BatchId=@BatchId) OR (@BatchId = 0))
			 INNER JOIN sStudent.tStudentFamily SF ON SF.StudentId = SM.Id
	
		-- For Left Detail
		SELECT DISTINCT  SA.StudentId AS StudentId12,InactiveDate,InActiveReason,LCBook,--LeftStandardId,
		CM.Title AS LeftStandard,
		CONVERT(VARCHAR(10),LCDate,111) AS LCDate,LCCopy,LeftReason,LCProgress,
		LCConduct,LCRemark 
		INTO sStudent.tTempStudent12
		FROM sStudent.tStudentAdmission SA
		     INNER JOIN sStudent.tAcademic A ON A.StudentId = SA.StudentId AND ((A.OrgId = @rOrgId) OR (@rOrgId = 0)) AND ((A.BatchId=@BatchId) OR (@BatchId=0))
		     LEFT JOIN sSetup.tClassMaster CM ON CM.Id = SA.LeftStandardId
		
		-- For Custom Tag
		IF (@rCustomTagId <> '')
		BEGIN
			SELECT DISTINCT SM.Id AS StudentId1
			INTO sStudent.tTempStudent5
			FROM sStudent.tStudentMaster SM
			INNER JOIN sStudent.tStudentCustomTag SCT ON SCT.StudentId=SM.Id
			INNER JOIN sStudent.tAcademic A ON A.StudentId = SM.Id
			WHERE ((SM.OrgId = @rOrgId) OR (@rOrgId = 0))  AND ((A.BatchId = @BatchId) OR (@BatchId = 0))
			AND (ISNULL(SCT.CustomTagId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rCustomTagId,','))OR @rCustomTagId='')
		END
		ELSE
		BEGIN
			SELECT DISTINCT NULL AS StudentId1
			INTO sStudent.tTempStudent5
		END
		
		-- For Custom Group
		IF (@rCustomGroupId <> '')
		BEGIN
			SELECT DISTINCT SM.Id AS StudentId2
			INTO sStudent.tTempStudent6
			FROM sStudent.tStudentMaster SM
			INNER JOIN sStudent.tAcademic A ON A.StudentId = SM.Id
			INNER JOIN sCommunication.tCustomGroupMember CGM ON CGM.SourceId = A.Id AND CGM.SourceTypeId=2001
			WHERE ((SM.OrgId = @rOrgId) OR (@rOrgId = 0))  AND ((A.BatchId = @BatchId) OR (@BatchId = 0))
			AND (ISNULL(CGM.CustomGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rCustomGroupId,','))OR @rCustomGroupId='')
		END
		ELSE
		BEGIN
			SELECT DISTINCT NULL AS StudentId2
			INTO sStudent.tTempStudent6
		END
		
		-- For Club Group
		IF (@rClubId <> '')
		BEGIN
			SELECT DISTINCT SM.Id AS StudentId3
			INTO sStudent.tTempStudent7
			FROM sStudent.tStudentMaster SM
			INNER JOIN sStudent.tAcademic A ON A.StudentId = SM.Id
			INNER JOIN sActivity.tAssignClub AC ON AC.AcademicId = A.Id
			WHERE ((SM.OrgId = @rOrgId) OR (@rOrgId = 0))  AND ((A.BatchId = @BatchId) OR (@BatchId = 0))
			AND (ISNULL(AC.ClubId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClubId,','))OR @rClubId='')
		END
		ELSE
		BEGIN
			SELECT DISTINCT NULL AS StudentId3
			INTO sStudent.tTempStudent7
		END
		
		-- For Hostel
		IF (@rHostelId <> '')
		BEGIN
			SELECT DISTINCT SM.Id AS StudentId4
			INTO sStudent.tTempStudent9
			FROM sStudent.tStudentMaster SM
			INNER JOIN sStudent.tAcademic A ON A.StudentId = SM.Id
			INNER JOIN sHostel.tAssignRoom AR ON AR.SourceId = A.StudentId
			AND ((AR.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
			INNER JOIN sHostel.tRoomMaster RM ON RM.Id = AR.RoomId
			WHERE((SM.OrgId = @rOrgId) OR (@rOrgId = 0))  
			AND (ISNULL(RM.HostelId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rHostelId,','))OR @rHostelId='')
		END
		ELSE
		BEGIN
			SELECT DISTINCT NULL AS StudentId4
			INTO sStudent.tTempStudent9
		END
		
		--Transport
		IF (@rBusRouteId <> '')
		BEGIN
			SELECT DISTINCT SM.Id AS StudentId5
			INTO sStudent.tTempStudent10
			FROM sStudent.tStudentMaster SM
			INNER JOIN sStudent.tAcademic A ON A.StudentId = SM.Id
			INNER JOIN sTransport.tAssignRoute AT ON AT.SourceId = A.StudentId
			INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id = AT.PickupDestinationId
			INNER JOIN sTransport.tBusRouteMaster BRM ON BRM.Id = BM.BusRouteId
			AND ((BRM.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
			WHERE ((SM.OrgId = @rOrgId) OR (@rOrgId = 0)) 
			AND (ISNULL(BRM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rBusRouteId,','))OR @rBusRouteId='')
		END
		ELSE
		BEGIN
			SELECT DISTINCT NULL AS StudentId5
			INTO sStudent.tTempStudent10
			
			
		END
		-- For Record Tag
		IF (@rRecordTagId <> '')
		BEGIN
			SELECT DISTINCT SM.Id AS StudentId14		
			INTO sStudent.tTempStudent14
			FROM sStudent.tStudentMaster SM
			INNER JOIN sStudent.tAcademic A ON A.StudentId = SM.Id
			WHERE ((SM.OrgId = @rOrgId) OR (@rOrgId = 0))  AND ((A.BatchId = @BatchId) OR (@BatchId = 0))
			AND (ISNULL(SM.RecordStatusId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rRecordTagId,','))OR @rRecordTagId='')
		END
		ELSE
		BEGIN
		
			SELECT DISTINCT NULL AS StudentId14
			INTO sStudent.tTempStudent14
		END
		
		SET @rColumnName=Replace(@rColumnName,'GR No','Code')
		SET @rColumnName=Replace(@rColumnName,'ID No','Code')
		--if @rColumnName <> ''
		--begin
		--	select @rColumnName = left(@rColumnName,len(@rColumnName)-1)
		--end
		--print 'asdasda'
		    DECLARE @lAvailableStudentColumns nvarchar(max)=''
			DECLARE @lAvailableStudentCustomRes nvarchar(max)=''
			Declare @Title as nvarchar(max)
			DECLARE @cols AS NVARCHAR(MAX),@query  AS NVARCHAR(MAX)
		
          --BEGIN  
		   
		   --drop table sStudent.tTempStudent13

             
			--print @BatchId
			--print @rOrgId
            DECLARE @rOrgGroupId smallint
             SET @rOrgGroupId = (Select orggroupid from sSetup.tOrganizationMaster where Id=@rOrgId)           
             
			SET @lAvailableStudentColumns=   STUFF((SELECT ',' + QUOTENAME(PP.FieldTitle,'[]'), '' AS FieldTitle, '' AS SalaryMonth
								from sStudent.tStudentCustomFieldMaster PP  WHERE PP.OrgGroupId = @rOrgGroupId  
						FOR XML PATH(''), TYPE
						).value('.', 'NVARCHAR(MAX)') 
					,1,1,'')
					Print @lAvailableStudentColumns
	        IF(@lAvailableStudentColumns IS NOT NULL)
	        BEGIN
				set @query = 'SELECT  StudentId AS StudentId13 ,' + @lAvailableStudentColumns + ' into sStudent.tTempStudent13 from 
					 (
						select PPE.FieldTitle,PP.StudentId,FieldData 
						FROM
						sStudent.tStudentCustomFieldData PP 
							INNER JOIN sStudent.tStudentCustomFieldMaster PPE ON PPE.Id = PP.StudentCustomFieldId AND PPE.IsObsolete=0
							INNER JOIN sStudent.tStudentMaster SM ON SM.Id = PP.StudentId						
							INNER JOIN sStudent.tAcademic A ON A.StudentId = SM.Id AND A.BatchId='+convert(varchar(20),@BatchId)+' 
							WHERE SM.OrgId='''+convert(varchar(20),@rOrgId)+''' 
					) x 
					pivot 
					(
						Max(FieldData)
						for FieldTitle in (' +@lAvailableStudentColumns  + ')
					) p'
					
				 print @query
                execute(@query)
		   
		   
		
		Select * into sStudent.tTempStudent
		FROM sStudent.vStudentCustomSearch SCS
		INNER JOIN sStudent.tTempStudent5 T5 ON SCS.StudentId = T5.StudentId1 OR @rCustomTagId = ''
		INNER JOIN sStudent.tTempStudent6 T6 ON SCS.StudentId = T6.StudentId2 OR @rCustomGroupId = ''
		INNER JOIN sStudent.tTempStudent7 T7 ON SCS.StudentId = T7.StudentId3 OR @rClubId = ''
		INNER JOIN sStudent.tTempStudent9 T9 ON SCS.StudentId = T9.StudentId4 OR @rHostelId = ''
		INNER JOIN sStudent.tTempStudent10 T10 ON SCS.StudentId = T10.StudentId5 OR @rBusRouteId = ''
		LEFT JOIN sStudent.tTempStudent11 T11 ON SCS.StudentId = T11.StudentId6
		LEFT JOIN  sStudent.tTempStudent12 T12 ON SCS.StudentId= T12.StudentId12 
		LEFT JOIN  sStudent.tTempStudent13 T13 ON SCS.StudentId= T13.StudentId13 
		INNER JOIN sStudent.tTempStudent14 T14 ON SCS.StudentId = T14.StudentId14 OR @rRecordTagId = ''
		WHERE ((SCS.OrgId = @rOrgId) OR (@rOrgId = 0)) 
		AND ((SCS.BatchId = @BatchId) OR (@BatchId = 0))
		--AND ((SCS.Code Like @rCode + '%') OR (@rCode = ''))
		AND ((SCS.FirstName Like @rFirstName  + '%') OR (@rFirstName = ''))
		AND ((SCS.LastName Like @rLastName + '%')OR(@rLastName = ''))
		AND ((SCS.Hobby Like '%' + @rHobby + '%') OR (@rHobby = ''))
		AND ((ISNULL(SCS.PermanentCountry,'') Like @rCountry + '%') OR(@rCountry = ''))
		AND ((ISNULL(SCS.PermanentState,'') Like @rState + '%')OR(@rState = ''))
		AND ((ISNULL(SCS.DateOfBirth,'0001-01-01') >= @rDOBFromDate) OR (ISNULL(@rDOBFromDate,'') = ''))
		AND ((ISNULL(SCS.DateOfBirth,'9999-12-31') <= @rDOBToDate) OR (ISNULL(@rDOBToDate,'') = ''))
		AND ((ISNULL(SCS.AdmissionDate,'0001-01-01') >= @rDOAFromDate) OR (ISNULL(@rDOAFromDate,'') = ''))
		AND ((ISNULL(SCS.AdmissionDate,'9999-12-31') <= @rDOAToDate) OR (ISNULL(@rDOAToDate,'') = ''))
		AND ((ISNULL(SCS.LeftDate,'0001-01-01') >= @rDOLFromDate) OR (ISNULL(@rDOLFromDate,'') = ''))
		AND ((ISNULL(SCS.LeftDate,'9999-12-31') <= @rDOLToDate) OR (ISNULL(@rDOLToDate,'') = ''))
		AND (ISNULL(SCS.PermanentCity,0) IN( SELECT item FROM  sCommon.fnsplit(@rCity,','))OR @rCity='')
		AND (ISNULL(SCS.PermanentStreetThree,0) IN( SELECT item FROM  sCommon.fnsplit(@rArea,','))OR @rArea='')
		AND (SCS.DivisionId In( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionId,','))OR @rDivisionId='')
		AND (SCS.StatusId In( SELECT cast(item as int) FROM  sCommon.fnsplit(@rStatusId,','))OR @rStatusId='')
		AND (SCS.TransportModeId In( SELECT cast(item as int) FROM  sCommon.fnsplit(@rTransportModeId,','))OR @rTransportModeId='')
		AND (ISNULL(SCS.BloodGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rBloodGroupId,','))OR @rBloodGroupId='')
		AND (ISNULL(SCS.GenderId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rGenderId,','))OR (@rGenderId=''))
		AND (ISNULL(SCS.ReligionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rReligionId,','))OR @rReligionId='')
		AND (ISNULL(SCS.CastCategoryId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rCastCategoryId,','))OR @rCastCategoryId='')
		AND (ISNULL(SCS.HouseId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rHouseId,','))OR @rHouseId='')
		AND (ISNULL(SCS.MotherTongueId,0) IN ( SELECT cast(item as int) FROM  sCommon.fnsplit(@rMotherTongueId,','))OR @rMotherTongueId='')
		AND (ISNULL(SCS.NationalityId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rNationalityId,','))OR @rNationalityId='')
		AND (ISNULL(SCS.BusRouteDestinationId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rBusRouteDestinationId,','))OR @rBusRouteDestinationId='')
		AND (ISNULL(SCS.FatherQualification,'') IN( SELECT item FROM  sCommon.fnsplit(@rFatherQualification,','))OR @rFatherQualification='')
		AND (ISNULL(SCS.FatherOccupation,'') IN( SELECT item FROM  sCommon.fnsplit(@rFatherOccupation,','))OR @rFatherOccupation='')
		AND (ISNULL(SCS.MotherQualification,'') IN( SELECT item FROM  sCommon.fnsplit(@rMotherQualification,','))OR @rMotherQualification='')
		AND (ISNULL(SCS.MotherOccupation,'') IN( SELECT item FROM  sCommon.fnsplit(@rMotherOccupation,','))OR @rMotherOccupation='')
		AND (ISNULL(SCS.AdmissionCategoryId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rAdmissionCategoryId,','))OR @rAdmissionCategoryId='')
		AND (ISNULL(SCS.PreviousSchool,'') IN( SELECT item FROM  sCommon.fnsplit(@rPreviousSchool,','))OR @rPreviousSchool='')
		AND (ISNULL(SCS.RepeatCount,0) IN( SELECT item FROM  sCommon.fnsplit(@rRepeatCount,','))OR @rRepeatCount='')
		AND (ISNULL(SCS.StudentStatusId,0) IN( SELECT item FROM  sCommon.fnsplit(@rStudentStatusId,','))OR @rStudentStatusId='')
		AND (ISNULL(SCS.StudentGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rStudentGroupId,','))OR @rStudentGroupId='')
		AND (ISNULL(SCS.StudentOtherGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rStudentOtherGroupId,','))OR @rStudentOtherGroupId='')
		AND ((SCS.IsPysicalDeformity=@rIsPysicalDeformity) OR (@rIsPysicalDeformity=0))
		AND ((SCS.IsMajorIllness=@rIsMajorIllness) OR (@rIsMajorIllness=0))
		AND ((SCS.IsBlackList=@rIsBlackList) OR (@rIsBlackList=0))
		AND ((SCS.Code >= @rFromCode) OR (@rFromCode=''))
		AND ((SCS.Code <= @rToCode) OR (@rToCode=''))
		AND ((SCS.Code IN(SELECT Code FROM @ListofCodes)) OR (ISNULL(@rSpecificCode,'') = ''))
		AND ((SCS.StatusId = @rDropDownStatusId) OR (@rDropDownStatusId=0))
		AND ((SCS.ClassId = @rDropDownClassId) OR (@rDropDownClassId=0))
		AND ((SCS.DivisionId = @rDropDownDivisionId) OR (@rDropDownDivisionId=0))
		AND (ISNULL(SCS.BusRouteId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rBusRouteId,','))OR @rBusRouteId='')
		AND (ISNULL(SCS.ExemptionTypeId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeExemption,','))OR @rFeeExemption='')
		AND ((SCS.PresentContactNo=@rContactNo) OR (SCS.PermanentContactNo=@rContactNo) OR (SCS.EmergencyContactNo=@rContactNo) OR (SCS.ParentContactno=@rContactNo) OR (SCS.StudentContactNo=@rContactNo) OR (SCS.FatherContactNo=@rContactNo) OR (SCS.MotherContactNo=@rContactNo) OR (@rContactNo=''))
		AND (( DAY(CONVERT(date,SCS.DateOfBirth)) = @rBirthDay) OR (@rBirthDay = 0))
	    AND (( MONTH(CONVERT(date,SCS.DateOfBirth)) = @rDateOfMonth) OR (@rDateOfMonth = 0))
		--AND (ISNULL(SCS.CustomTagId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rCustomTagId,','))OR @rCustomTagId='')
		--Select * from sStudent.tTempStudent return	
		AND ((SCS.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))
		AND ((SCS.IsStopApplicationAccess = @rStopApplicationAccess) OR (@rStopApplicationAccess = -1))
				
		set @sql = 'SELECT '+ @rColumnName+' FROM sStudent.tTempStudent ORDER BY '+@rOrderBy
		
		if(@rColumnName='ID No')
		BEGIN
			SET @sql=Replace(@sql,'SELECT Code','SELECT Code AS [ID No]')
		END
		if(@rColumnName='GR No')
		BEGIN
			SET @sql=Replace(@sql,'SELECT Code','SELECT Code AS [GR No]')
		END
		
		exec(@Sql)
			
		DROP Table sStudent.tTempStudent
		DROP Table sStudent.tTempStudent5
		DROP Table sStudent.tTempStudent6
		DROP Table sStudent.tTempStudent7
		DROP Table sStudent.tTempStudent9
		DROP Table sStudent.tTempStudent10
		DROP Table sStudent.tTempStudent12
		DROP Table sStudent.tTempStudent13
		DROP Table sStudent.tTempStudent14
 
	END 
	 
	ELSE
	BEGIN
	    Select * into sStudent.tTempStudent
		FROM sStudent.vStudentCustomSearch SCS
		INNER JOIN sStudent.tTempStudent5 T5 ON SCS.StudentId = T5.StudentId1 OR @rCustomTagId = ''
		INNER JOIN sStudent.tTempStudent6 T6 ON SCS.StudentId = T6.StudentId2 OR @rCustomGroupId = ''
		INNER JOIN sStudent.tTempStudent7 T7 ON SCS.StudentId = T7.StudentId3 OR @rClubId = ''
		INNER JOIN sStudent.tTempStudent9 T9 ON SCS.StudentId = T9.StudentId4 OR @rHostelId = ''
		INNER JOIN sStudent.tTempStudent10 T10 ON SCS.StudentId = T10.StudentId5 OR @rBusRouteId = ''
		LEFT JOIN sStudent.tTempStudent11 T11 ON SCS.StudentId = T11.StudentId6
		LEFT JOIN  sStudent.tTempStudent12 T12 ON SCS.StudentId= T12.StudentId12 
		INNER JOIN sStudent.tTempStudent14 T14 ON SCS.StudentId = T14.StudentId14 OR @rRecordTagId = ''
		
		WHERE ((SCS.OrgId = @rOrgId) OR (@rOrgId = 0)) 
		AND ((SCS.BatchId = @BatchId) OR (@BatchId = 0)) 
		--AND ((SCS.Code Like @rCode + '%') OR (@rCode = ''))
		AND ((SCS.FirstName Like @rFirstName  + '%') OR (@rFirstName = ''))
		AND ((SCS.LastName Like @rLastName + '%')OR(@rLastName = ''))
		AND ((SCS.Hobby Like '%' + @rHobby + '%') OR (@rHobby = ''))
		AND ((ISNULL(SCS.PermanentCountry,'') Like @rCountry + '%') OR(@rCountry = ''))
		AND ((ISNULL(SCS.PermanentState,'') Like @rState + '%')OR(@rState = ''))
		AND ((ISNULL(SCS.DateOfBirth,'0001-01-01') >= @rDOBFromDate) OR (ISNULL(@rDOBFromDate,'') = ''))
		AND ((ISNULL(SCS.DateOfBirth,'9999-12-31') <= @rDOBToDate) OR (ISNULL(@rDOBToDate,'') = ''))
		AND ((ISNULL(SCS.AdmissionDate,'0001-01-01') >= @rDOAFromDate) OR (ISNULL(@rDOAFromDate,'') = ''))
		AND ((ISNULL(SCS.AdmissionDate,'9999-12-31') <= @rDOAToDate) OR (ISNULL(@rDOAToDate,'') = ''))
		AND ((ISNULL(SCS.LeftDate,'0001-01-01') >= @rDOLFromDate) OR (ISNULL(@rDOLFromDate,'') = ''))
		AND ((ISNULL(SCS.LeftDate,'9999-12-31') <= @rDOLToDate) OR (ISNULL(@rDOLToDate,'') = ''))
		AND (ISNULL(SCS.PermanentCity,0) IN( SELECT item FROM  sCommon.fnsplit(@rCity,','))OR @rCity='')
		AND (ISNULL(SCS.PermanentStreetThree,0) IN( SELECT item FROM  sCommon.fnsplit(@rArea,','))OR @rArea='')
		AND (SCS.DivisionId In( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionId,','))OR @rDivisionId='')
		AND (SCS.StatusId In( SELECT cast(item as int) FROM  sCommon.fnsplit(@rStatusId,','))OR @rStatusId='')
		AND (SCS.TransportModeId In( SELECT cast(item as int) FROM  sCommon.fnsplit(@rTransportModeId,','))OR @rTransportModeId='')
		AND (ISNULL(SCS.BloodGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rBloodGroupId,','))OR @rBloodGroupId='')
		AND (ISNULL(SCS.GenderId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rGenderId,','))OR (@rGenderId=''))
		AND (ISNULL(SCS.ReligionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rReligionId,','))OR @rReligionId='')
		AND (ISNULL(SCS.CastCategoryId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rCastCategoryId,','))OR @rCastCategoryId='')
		AND (ISNULL(SCS.HouseId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rHouseId,','))OR @rHouseId='')
		AND (ISNULL(SCS.MotherTongueId,0) IN ( SELECT cast(item as int) FROM  sCommon.fnsplit(@rMotherTongueId,','))OR @rMotherTongueId='')
		AND (ISNULL(SCS.NationalityId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rNationalityId,','))OR @rNationalityId='')
		AND (ISNULL(SCS.BusRouteDestinationId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rBusRouteDestinationId,','))OR @rBusRouteDestinationId='')
		AND (ISNULL(SCS.FatherQualification,'') IN( SELECT item FROM  sCommon.fnsplit(@rFatherQualification,','))OR @rFatherQualification='')
		AND (ISNULL(SCS.FatherOccupation,'') IN( SELECT item FROM  sCommon.fnsplit(@rFatherOccupation,','))OR @rFatherOccupation='')
		AND (ISNULL(SCS.MotherQualification,'') IN( SELECT item FROM  sCommon.fnsplit(@rMotherQualification,','))OR @rMotherQualification='')
		AND (ISNULL(SCS.MotherOccupation,'') IN( SELECT item FROM  sCommon.fnsplit(@rMotherOccupation,','))OR @rMotherOccupation='')
		AND (ISNULL(SCS.AdmissionCategoryId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rAdmissionCategoryId,','))OR @rAdmissionCategoryId='')
		AND (ISNULL(SCS.PreviousSchool,'') IN( SELECT item FROM  sCommon.fnsplit(@rPreviousSchool,','))OR @rPreviousSchool='')
		AND (ISNULL(SCS.RepeatCount,0) IN( SELECT item FROM  sCommon.fnsplit(@rRepeatCount,','))OR @rRepeatCount='')
		AND (ISNULL(SCS.StudentStatusId,0) IN( SELECT item FROM  sCommon.fnsplit(@rStudentStatusId,','))OR @rStudentStatusId='')
		AND (ISNULL(SCS.StudentGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rStudentGroupId,','))OR @rStudentGroupId='')
		AND (ISNULL(SCS.StudentOtherGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rStudentOtherGroupId,','))OR @rStudentOtherGroupId='')
		AND ((SCS.IsPysicalDeformity=@rIsPysicalDeformity) OR (@rIsPysicalDeformity=0))
		AND ((SCS.IsMajorIllness=@rIsMajorIllness) OR (@rIsMajorIllness=0))
		AND ((SCS.IsBlackList=@rIsBlackList) OR (@rIsBlackList=0))
		AND ((SCS.Code >= @rFromCode) OR (@rFromCode=''))
		AND ((SCS.Code <= @rToCode) OR (@rToCode=''))
		AND ((SCS.Code IN(SELECT Code FROM @ListofCodes)) OR (ISNULL(@rSpecificCode,'') = ''))
		AND ((SCS.StatusId = @rDropDownStatusId) OR (@rDropDownStatusId=0))
		AND ((SCS.ClassId = @rDropDownClassId) OR (@rDropDownClassId=0))
		AND ((SCS.DivisionId = @rDropDownDivisionId) OR (@rDropDownDivisionId=0))
		AND (ISNULL(SCS.BusRouteId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rBusRouteId,','))OR @rBusRouteId='')
		AND (ISNULL(SCS.ExemptionTypeId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeExemption,','))OR @rFeeExemption='')
		AND ((SCS.PresentContactNo=@rContactNo) OR (SCS.PermanentContactNo=@rContactNo) OR (SCS.EmergencyContactNo=@rContactNo) OR (SCS.ParentContactno=@rContactNo) OR (SCS.StudentContactNo=@rContactNo) OR (SCS.FatherContactNo=@rContactNo) OR (SCS.MotherContactNo=@rContactNo) OR (@rContactNo=''))
		--AND (ISNULL(SCS.CustomTagId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rCustomTagId,','))OR @rCustomTagId='')
		--Select * from sStudent.tTempStudent return	
		AND ((SCS.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))
		AND (( DAY(CONVERT(date,SCS.DateOfBirth)) = @rBirthDay) OR (@rBirthDay = 0))
	    AND (( MONTH(CONVERT(date,SCS.DateOfBirth)) = @rDateOfMonth) OR (@rDateOfMonth = 0))
		AND ((SCS.IsStopApplicationAccess = @rStopApplicationAccess) OR (@rStopApplicationAccess = -1))		
				--Select * From sStudent.tTempStudent
		set @sql = 'SELECT '+ @rColumnName+' FROM sStudent.tTempStudent ORDER BY '+@rOrderBy
		
		
		if(@rColumnName='ID No')
		BEGIN
			SET @sql=Replace(@sql,'SELECT Code','SELECT Code AS [ID No]')
		END
		if(@rColumnName='GR No')
		BEGIN
			SET @sql=Replace(@sql,'SELECT Code','SELECT Code AS [GR No]')
		END
		
		exec(@Sql)
			
		DROP Table sStudent.tTempStudent
		DROP Table sStudent.tTempStudent5
		DROP Table sStudent.tTempStudent6
		DROP Table sStudent.tTempStudent7
		DROP Table sStudent.tTempStudent9
		DROP Table sStudent.tTempStudent10
		DROP Table sStudent.tTempStudent12
		
	    
	    
	END 
	 
	 
END
GO
PRINT N'Altering [sStudent].[pUserControlStudentSearchGet]...';


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

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

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

	SELECT @lOrgGroupId = OGBM.OrgGroupId FROM sSetup.tBatchMaster BM INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id = BM.OrgGroupBatchId WHERE BM.Id=@rBatchId
	SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 480 AND SourceTypeId = 2010 AND SourceId = @rOrgId
	
	IF (@lIsStudentCommonSearchBatchWise = 'True')
	BEGIN
		IF(@rRollNo IS NULL)  
		BEGIN  
			SELECT   
			  SA.AcademicId,  
			  SA.StudentId,  
			  SA.FirstName,  
			  SA.LastName,  
			  SA.MiddleName,  
			  SA.Name,  
			  SA.Code,  
			  SA.ClassId,  
			  SA.ClassName,  
			  SA.DivisionId,  
			  SA.DivisionName,  
			  SA.Number,  
			  SA.RollNo,  
			  SA.StatusId,  
			  SA.StatusName,  
			  SA.OrgId,  
			  ISNULL(SA.AdmissionCategoryId,0) AS AdmissionCategoryId,  
			  SA.BatchId,  
			  SA.SUId,  
			  ISNULL(So.GenderId,0) AS GenderId,
			  ISNULL(SC.ParentContactNo,'') AS ParentContactNo
			   
			 FROM   
			         sStudent.vStudentAcademic SA  
			          LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=SA.StudentId  
					  LEFT JOIN sStudent.tStudentCommunication SC ON SA.StudentId = SC.StudentId
			 WHERE   
			  
			 ((SA.ClassId=@rClassId)OR(@rClassId=0))  
			 AND((SA.DivisionId=@rDivisionId)OR(@rDivisionId=0))  
			 AND((SA.Code=@rCode) OR (ISNULL(@rCode,'') = ''))   
			 AND((SA.FirstName like @rFirstName) OR (ISNULL(@rFirstName,'') = ''))   
			 AND((SA.LastName like @rLastName) OR (ISNULL(@rLastName,'') = ''))   
			 AND((SA.StatusId=@rStatusId)OR(@rStatusId=0))   
			 AND(SA.OrgId=@rOrgId OR @rOrgId = 0)  
			 AND ( OrgGroupBatchId = @rOrgGroupBatchId or @rOrgGroupBatchId = 0)   
			 AND(SA.BatchId=@rBatchId or @rBatchId = 0)  
			 AND((SA.SUId=@rSUId) OR (ISNULL(@rSUId,'') = ''))  
			 
			ORDER BY SA.ClassId,SA.DivisionId,SA.RollNo  
		END  
		ELSE  
		BEGIN  
			SELECT   
			  SA.AcademicId,  
			  SA.StudentId,  
			  SA.FirstName,  
			  SA.LastName,  
			  SA.MiddleName,  
			  SA.Name,  
			  SA.Code,  
			  SA.ClassId,  
			  SA.ClassName,  
			  SA.DivisionId,  
			  SA.DivisionName,  
			  SA.Number,  
			  SA.RollNo,  
			  SA.StatusId,  
			  SA.StatusName,  
			  SA.OrgId,
			  ISNULL(SA.AdmissionCategoryId,0) AS AdmissionCategoryId ,  
			  SA.SUId,  
			  ISNULL(So.GenderId,0) AS GenderId,
			  ISNULL(SC.ParentContactNo,'') AS ParentContactNo

			 FROM   
			         sStudent.vStudentAcademic SA      
			          LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=SA.StudentId           
					  LEFT JOIN sStudent.tStudentCommunication SC ON SA.StudentId = SC.StudentId
			 WHERE   
			  
			 ((SA.ClassId=@rClassId)OR(@rClassId=0))  
			 AND((SA.DivisionId=@rDivisionId)OR(@rDivisionId=0))  
			 AND((SA.Code=@rCode) OR (ISNULL(@rCode,'') = ''))   
			 AND((SA.FirstName like @rFirstName) OR (ISNULL(@rFirstName,'') = ''))   
			 AND((SA.LastName like @rLastName) OR (ISNULL(@rLastName,'') = ''))   
			 AND(SA.RollNo=@rRollNo)  
			 AND((SA.StatusId=@rStatusId)OR(@rStatusId=0))   
			 AND((SA.OrgId=@rOrgId) OR (@rOrgId=0))  
			 AND ( OrgGroupBatchId = @rOrgGroupBatchId or @rOrgGroupBatchId = 0)   
			 AND(SA.BatchId=@rBatchId or @rBatchId = 0) 
			 AND((SA.SUId=@rSUId) OR (ISNULL(@rSUId,'') = ''))    
			 
			ORDER BY SA.ClassId,SA.DivisionId,SA.RollNo  
		END  
	END

	ELSE
	BEGIN
		IF (@lConfigValue IS NULL) OR (@lConfigValue = 'False')
		SET @lIsInContext = 1
		ELSE
		SET @lIsInContext = 0

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

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


GO
ALTER PROCEDURE [sStudent].[pValidateImportAdmissionInquiry]

	@rOrgGroupId int,
    @rOrgId int,
	@rXmldoc [nvarchar](max)
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
DECLARE @lCount INT
DECLARE @lInterrorCode INT,
		@intDoc INT,
        
        @lClass nvarchar(100),
        @lInquiryDate nvarchar(15),
		@lInquiryStatus nvarchar(50),
        @lDOB nvarchar(15),             
        @1ReturnCode int = 1,
        @1ValidInquiryDate nvarchar(max)='',
        @1ValidDOB nvarchar(max) = '' 
       
       
EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc
 
CREATE TABLE #tTable1 
 (
		Id bigint identity,
        FirstName nvarchar(100),
        MiddleName nvarchar(100),
        LastName nvarchar(100),
		Class nvarchar(100),
		
		InquiryDate nvarchar(15), 
        InquiryStatus nvarchar(50),
        DOB nvarchar(15),
        Gender nvarchar(10),
		InquiryMode nvarchar(50)  
	 
 
  )
  INSERT INTO #tTable1
	(
	    
	    FirstName,
	    MiddleName,
	    LastName,
	    Class,
	    InquiryDate,
	    InquiryStatus,
	    DOB,
	    Gender,
		InquiryMode
	    
    ) 
   SELECT
       
	    FirstName,
	    MiddleName,
	    LastName,
	    Class,
	    InquiryDate,
	    InquiryStatus,
	    DOB,
	    Gender,
		InquiryMode
	  
   
   FROM OPENXML (@intDoc, '/Table/ImportStudent', 1)
   With
   (
        
        FirstName nvarchar(100) '@FirstName',
        MiddleName  nvarchar(100) '@MiddleName',
        LastName nvarchar(100) '@LastName',
		Class nvarchar(100) '@Class',
		InquiryDate nvarchar(15) '@InquiryDate',
		InquiryStatus nvarchar(50) '@InquiryStatus',
		DOB nvarchar(15) '@DOB',
		Gender nvarchar(10) '@Gender' ,
		InquiryMode nvarchar(50) '@InquiryMode'
   )   
EXEC sp_xml_removedocument @intDoc
		
SELECT @lCount =  COUNT(Id) FROM #tTable1
 
WHILE @lCount > 0 
  BEGIN
  
    IF(ISDATE(@lInquiryDate) = 0 AND @lInquiryDate!='')
	BEGIN    
		SET @1ValidInquiryDate = @1ValidInquiryDate + @lInquiryDate+','
	END
	IF(ISDATE(@lDOB) = 0 AND @lDOB!='')
	BEGIN
		SET @1ValidDOB=@1ValidDOB +   @lDOB+','
	END
     SET @lCount = @lCount - 1	
   END	
    
   
   SELECT @lCount =  COUNT(Id) FROM #tTable1
 
	WHILE @lCount > 0 
		BEGIN
			SELECT         
			 @lClass = Class 
			FROM #tTable1 WHERE Id = @lCount

			IF NOT EXISTS (SELECT 1 FROM  
					 sSetup.tClassMaster CM  
						WHERE CM.Title COLLATE DATABASE_DEFAULT =@lClass COLLATE DATABASE_DEFAULT  )	
			BEGIN
				
				SELECT 'Enter proper value for Class ' + @lClass   AS StudentCode
				RETURN
			END
			SET @lCount = @lCount - 1	
		END
   	
		   
		 
		  IF EXISTS(SELECT 1 FROM #tTable1 WHERE LastName IS NULL OR LastName COLLATE DATABASE_DEFAULT ='' COLLATE DATABASE_DEFAULT)
		BEGIN
			SELECT 'Surname Should not be empty' AS StudentCode
		END
		ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE FirstName IS NULL OR FirstName COLLATE DATABASE_DEFAULT ='' COLLATE DATABASE_DEFAULT)
		BEGIN
			SELECT 'First Name Should not be empty' AS StudentCode
		END
		ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE MiddleName IS NULL OR MiddleName COLLATE DATABASE_DEFAULT ='' COLLATE DATABASE_DEFAULT)
		BEGIN
			SELECT 'Middle Name Should not be empty' AS StudentCode
		END
		ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE Class IS NULL OR Class COLLATE DATABASE_DEFAULT ='' COLLATE DATABASE_DEFAULT)
		BEGIN
			SELECT 'Class Should not be empty' AS StudentCode
		END
		 
	 
		ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE Gender IS NULL OR Gender COLLATE DATABASE_DEFAULT ='' COLLATE DATABASE_DEFAULT)
		BEGIN
			SELECT 'Gender Should not be empty' AS StudentCode
		END
 
		ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE Class  COLLATE DATABASE_DEFAULT NOT IN(SELECT Title FROM sSetup.tClassMaster WHERE OrgId=@rOrgId))
		BEGIN
			SELECT 'Enter proper value for Class as per Institute Setup > Class Master' AS StudentCode
		END				
		 
		ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE Gender COLLATE DATABASE_DEFAULT !='' COLLATE DATABASE_DEFAULT AND Gender NOT IN(SELECT Title FROM sCommon.tGenderMaster))
		BEGIN
			SELECT 'Enter proper value / Check spelling for gender ( Male / Female )' AS StudentCode
		END
		--ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE AdmissionCategory!='' AND AdmissionCategory NOT IN(SELECT Title FROM sStudent.tAdmissionCategoryMaster))
		--BEGIN
		--	SELECT 'Enter proper value for Cast Category (Indian,NRI,General)' AS StudentCode
		--END
			 
		Else if Exists(Select 1 from #tTable1 where InquiryStatus COLLATE DATABASE_DEFAULT !='' COLLATE DATABASE_DEFAULT AND InquiryStatus NOT IN (Select Title from sAdmission.tInquiryStatusMaster))
		Begin
			Select 'Enter proper Value or check Spelling for Inquiry Status' AS StudentCode
		End
		ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE InquiryStatus IS NULL OR InquiryStatus COLLATE DATABASE_DEFAULT ='' COLLATE DATABASE_DEFAULT)
		BEGIN
			SELECT 'Inquiry Status Should not be empty ' AS StudentCode
		END
		ELSE IF NOT EXISTS(SELECT 1 FROM #tTable1 WHERE InquiryMode IN(SELECT Title FROM sAdmission.tInquiryModeMaster ) OR InquiryMode='')
		BEGIN
			SELECT 'Inquiry Mode is not proper as per Inquiry Mode Master' AS StudentCode
		END

		ELSE
			
		BEGIN
			IF((@1ValidInquiryDate IS NULL OR @1ValidInquiryDate = '') AND (@1ValidDOB IS NULL OR @1ValidDOB = ''))
		BEGIN
			SELECT '' AS StudentCode
		END
		
		 ELSE IF (@1ValidDOB IS NOT NULL AND @1ValidDOB != '')
		BEGIN
			SET @1ValidDOB = 'Wrong DOB ' + @1ValidDOB
			Select @1ValidDOB AS StudentCode
		END
		
		END
		 
END
GO
PRINT N'Altering [sTally].[pReceiptPostingGet]...';


GO

ALTER PROCEDURE [sTally].[pReceiptPostingGet]

	 @rOrgGroupBatchId int,
	 @rReceiptBookId int,
	 @rReceiptDate Date,
	 @rToReceiptDate Date,
	 @rPayTypeId int = 0,
	 @rCustomNarration nvarchar(max)='',
	 @rIsCustomNarration bit=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	
	DECLARE @lTallyPostingType nVarchar(100)
	DECLARE @lOrgGroupId INT
	
	SELECT @lOrgGroupId = OrgGroupId from sSetup.tOrgGroupBatchMaster Where Id=@rOrgGroupBatchId
	
	SELECT @lTallyPostingType = CASE WHEN CS.ItemValue IS NULL THEN C.ItemValue ELSE CS.ItemValue END 
		FROM sConfig.tConfigurationMaster C
        INNER JOIN sConfig.tConfigurationLevelMaster CM ON CM.Id = C.ConfigurationLevelId
        LEFT JOIN sConfig.tConfigurationSetup CS ON CS.ConfigurationId = C.Id AND CS.SOURCEID= @lOrgGroupId
        WHERE  C.ItemKey = 'Tally.PostingType'
        
		
        IF @lTallyPostingType = 'FeeHeadWise' 
        BEGIN
			   SELECT	ReceiptDate,
						ISNULL(FHM.Title,'') AS FeeName,
						PM.Title AS PayType,
						Sum(FRD.Amount) AS Amount,
						Case when @rIsCustomNarration=1 then STUFF((SELECT ','  +Replace(replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					replace(
																					@rCustomNarration,'[Class]',isnull(SM1.ClassName,'')
																					),'[Division]',Isnull(SM1.DivisionName,'')
																					),'[StudentsName]',isnull(SM1.Name,'')
																					), '[RollNumber]',isnull(convert(nvarchar(200),SM1.RollNo),'0')
																					),'[Batch]',isnull(SM1.BatchName,'')
																					), '[ReceiptNumber]', isnull(Convert(nvarchar(100),FR1.ReceiptNumber),'')
																					), '[ReceiptDate]',isnull(Convert(nvarchar(100),FR1.ReceiptDate),'')
																					), '[ReceiptAmount]',isnull(Convert(nvarchar(100),FR1.ReceiptAmount),'')
																					), '[ChequeNo]',isnull(Convert(nvarchar(100),FR1.ChequeNo),'')
																					),'[BankName]',isnull(FR1.BankName,'')
																					),'[FeeName]',isnull(FM1.Title,'')
																					), '[FeeAmount]',isnull(Convert(nvarchar(100),Sum(FRD.Amount)),'0.00')
																					),'[FeeHeadName]',ISNULL(FHM.Title,'')
																					), '[FeeHeadAmount]',isnull(Convert(nvarchar(100),Sum(FRD.Amount)),'0.00')
																					), '[CollectionGroupName]',isNull(CGM1.Title,'')
																					),'[ReceiptFromNumber]',isnull(Convert(nvarchar(10),(Select Min(ReceiptNumber) from sFee.tReceipt where   FR.ReceiptDate =ReceiptDate)),'')
																					), '[ReceiptToNumber]',isnull(Convert(nvarchar(10),(Select Max(ReceiptNumber) from sFee.tReceipt Where FR.ReceiptDate = ReceiptDate)),''))
						from sFee.tReceipt FR1  INNER JOIN sFee.tReceiptDetail FRD1 ON FR1.Id = FRD1.ReceiptId
						INNER JOIN sFee.tFeeSetup FS1 ON FS1.Id = FRD1.FeeSetupId 
						INNER JOIN sStudent.vStudentAcademic SM1 ON SM1.ACademicId = FR1.SourceID AND SM1.OrgGRoupBatchId = FR1.OrgGRoupBatchId 						
						INNER JOIN sFee.tFeeMaster FM1 ON FM1.Id = FS1.FeeId --AND FRD.ReceiptId=FRD1.ReceiptId
						LEFT JOIN sFee.tCollectionGroupMaster CGM1 ON CGM1.Id = FS1.CollectionGroupId
						INNER JOIN sFee.tFeeHeadMaster FHM1 ON FHM1.Id = FM1.FeeHeadId AND FHM1.Id=FHM.Id where  FR.ReceiptDate=FR1.ReceiptDate FOR XML PATH('')),1,1,'') else
						 'Receipt generated for Batch : ' + (Select Title from sSetup.tOrgGroupBatchMaster Where Id= @rOrgGroupBatchId) +
						' Receipt Date : ' +  Convert(nvarchar(10),ReceiptDate) + ' and Receipt Number From ' + Convert(nvarchar(10),(Select Min(ReceiptNumber) from sFee.tReceipt where   FR.ReceiptDate =ReceiptDate AND IsObsolete = 0 )) + ' -  ' + 
						Convert(nvarchar(10),(Select Max(ReceiptNumber) from sFee.tReceipt Where FR.ReceiptDate = ReceiptDate AND IsObsolete = 0)) end as Narration,						
						FR.PayTypeId AS PayTypeId, 
						FHM.Id AS FeeId,
						0 AS ReceiptId
				FROM sFee.tReceipt FR 
					INNER JOIN sFee.tReceiptDetail FRD ON FR.Id = FRD.ReceiptId
					INNER JOIN sFee.tFeeSetup FS ON FS.Id = FRD.FeeSetupId
					INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
					INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FM.FeeHeadId
					INNER JOIN sFinanceCommon.tPayTypeMaster PM ON PM.Id = FR.PayTypeId
					WHERE	FR.ReceiptBookId = @rReceiptBookId 
							AND FR.IsObsolete = 0 
							AND FR.OrgGroupBatchId = @rOrgGroupBatchId
							AND FR.ReceiptDate >= @rReceiptDate AND FR.ReceiptDate <= @rToReceiptDate
							AND (FR.PayTypeId = @rPayTypeId OR @rPayTypeId = 0)
				group by ReceiptDate,FHM.Title,PM.Title,FHM.Id,FR.PayTypeId
				Order By ReceiptDate Desc
			END				
       ELSE IF @lTallyPostingType = 'FeeHeadWiseCustom' 
        BEGIN
			   SELECT	ReceiptDate,
						FR.Id AS FeeName,
						PM.Title AS PayType,
						Sum(FRD.Amount) AS Amount,
						Case when @rIsCustomNarration=1 then  STUFF((SELECT ','  +Replace(replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					replace(
																					@rCustomNarration,'[Class]',isnull(SM1.ClassName,'')
																					),'[Division]',Isnull(SM1.DivisionName,'')
																					),'[StudentsName]',isnull(SM1.Name,'')
																					), '[RollNumber]',isnull(convert(nvarchar(200),SM1.RollNo),'0')
																					),'[Batch]',isnull(SM1.BatchName,'')
																					), '[ReceiptNumber]', isnull(Convert(nvarchar(100),FR1.ReceiptNumber),'')
																					), '[ReceiptDate]',isnull(Convert(nvarchar(100),FR1.ReceiptDate),'')
																					), '[ReceiptAmount]',isnull(Convert(nvarchar(100),FR1.ReceiptAmount),'')
																					), '[ChequeNo]',isnull(Convert(nvarchar(100),FR1.ChequeNo),'')
																					),'[BankName]',isnull(FR1.BankName,'')
																					),'[FeeName]',isnull(FM1.Title,'')
																					), '[FeeAmount]',isnull(Convert(nvarchar(100),Sum(FRD.Amount)),'0.00')
																					),'[FeeHeadName]',ISNULL(FHM1.Title,'')
																					), '[FeeHeadAmount]',isnull(Convert(nvarchar(100),Sum(FRD.Amount)),'0.00')
																					), '[CollectionGroupName]',isNull(CGM1.Title,'')
																					),'[ReceiptFromNumber]',isnull(Convert(nvarchar(10),(Select Min(ReceiptNumber) from sFee.tReceipt where   FR.ReceiptDate =ReceiptDate AND IsObsolete = 0)),'')
																					), '[ReceiptToNumber]',isnull(Convert(nvarchar(10),(Select Max(ReceiptNumber) from sFee.tReceipt Where FR.ReceiptDate = ReceiptDate AND IsObsolete = 0)),''))
						from sFee.tReceipt FR1  INNER JOIN sFee.tReceiptDetail FRD1 ON FR1.Id = FRD1.ReceiptId
						INNER JOIN sFee.tFeeSetup FS1 ON FS1.Id = FRD1.FeeSetupId 
						INNER JOIN sStudent.vStudentAcademic SM1 ON SM1.ACademicId = FR1.SourceID AND SM1.OrgGRoupBatchId = FR1.OrgGRoupBatchId 						
						INNER JOIN sFee.tFeeMaster FM1 ON FM1.Id = FS1.FeeId --AND FRD.ReceiptId=FRD1.ReceiptId
						LEFT JOIN sFee.tCollectionGroupMaster CGM1 ON CGM1.Id = FS1.CollectionGroupId
						INNER JOIN sFee.tFeeHeadMaster FHM1 ON FHM1.Id = FM1.FeeHeadId  where   FR.ReceiptDate=FR1.ReceiptDate AND FR.Id=FR1.Id AND FR1.IsObsolete = 0  FOR XML PATH('')),1,1,'') else
						SM.Name + '(' + ClassName + ':' + DivisionName + ') ' + ' # Cheque No. :' + ISNULL(FR.ChequeNo,'') + ' BankName :' + ISNULL(FR.BankName,'') end as Narration,						
						FR.PayTypeId AS PayTypeId, 
						0 AS FeeId,
						FR.Id AS ReceiptId
				FROM sFee.tReceipt FR 
					INNER JOIN sFee.tReceiptDetail FRD ON FR.Id = FRD.ReceiptId
					INNER JOIN sStudent.vStudentAcademic SM ON SM.ACademicId = FR.SourceID AND SM.OrgGRoupBatchId = FR.OrgGRoupBatchId 
					INNER JOIN sFee.tFeeSetup FS ON FS.Id = FRD.FeeSetupId
					INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
					INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FM.FeeHeadId
					INNER JOIN sFinanceCommon.tPayTypeMaster PM ON PM.Id = FR.PayTypeId
					INNER JOIN sSetup.tOrganizationMaster OM ON  OM.Id=SM.OrgId
					LEFT JOIN sSetup.tOrgSubGroupMaster OSM ON OSM.id=OM.OrgSubGroupId

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

       ELSE IF @lTallyPostingType = 'OrgMainGroupWise' 
        BEGIN
			   SELECT	ReceiptDate,
						SM.AcademicId AS FeeName,
						PM.Title AS PayType,
						Sum(FRD.Amount) AS Amount,
						Case when @rIsCustomNarration=1 then  STUFF((SELECT ','  +Replace(replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					replace(
																					@rCustomNarration,'[Class]',isnull(SM1.ClassName,'')
																					),'[Division]',Isnull(SM1.DivisionName,'')
																					),'[StudentsName]',isnull(SM1.Name,'')
																					), '[RollNumber]',isnull(convert(nvarchar(200),SM1.RollNo),'0')
																					),'[Batch]',isnull(SM1.BatchName,'')
																					), '[ReceiptNumber]', isnull(Convert(nvarchar(100),FR1.ReceiptNumber),'')
																					), '[ReceiptDate]',isnull(Convert(nvarchar(100),FR1.ReceiptDate),'')
																					), '[ReceiptAmount]',isnull(Convert(nvarchar(100),FR1.ReceiptAmount),'')
																					), '[ChequeNo]',isnull(Convert(nvarchar(100),FR1.ChequeNo),'')
																					),'[BankName]',isnull(FR1.BankName,'')
																					),'[FeeName]',isnull(FM1.Title,'')
																					), '[FeeAmount]',isnull(Convert(nvarchar(100),Sum(FRD.Amount)),'0.00')
																					),'[FeeHeadName]',ISNULL(FHM1.Title,'')
																					), '[FeeHeadAmount]',isnull(Convert(nvarchar(100),Sum(FRD.Amount)),'0.00')
																					), '[CollectionGroupName]',isNull(CGM1.Title,'')
																					),'[ReceiptFromNumber]',isnull(Convert(nvarchar(10),FR1.ReceiptNumber),'')
																					), '[ReceiptToNumber]',isnull(Convert(nvarchar(10),FR1.ReceiptNumber),''))
						from sFee.tReceipt FR1  INNER JOIN sFee.tReceiptDetail FRD1 ON FR1.Id = FRD1.ReceiptId
						INNER JOIN sFee.tFeeSetup FS1 ON FS1.Id = FRD1.FeeSetupId 
						INNER JOIN sStudent.vStudentAcademic SM1 ON SM1.ACademicId = FR1.SourceID AND SM1.OrgGRoupBatchId = FR1.OrgGRoupBatchId 						
						INNER JOIN sFee.tFeeMaster FM1 ON FM1.Id = FS1.FeeId --AND FRD.ReceiptId=FRD1.ReceiptId
						LEFT JOIN sFee.tCollectionGroupMaster CGM1 ON CGM1.Id = FS1.CollectionGroupId
						INNER JOIN sFinanceCommon.tPayTypeMaster PM1 ON PM1.Id = FR1.PayTypeId
						INNER JOIN sFee.tFeeHeadMaster FHM1 ON FHM1.Id = FM1.FeeHeadId  where  FR.ReceiptDate=FR1.ReceiptDate AND PM.Title=PM1.Title AND SM.AcademicId=SM1.AcademicId AND  FR.PayTypeId=FR1.PayTypeId AND FR1.IsObsolete = 0  FOR XML PATH('')),1,1,'') else
						SM.Name + '(' + ClassName + ':' + DivisionName + ') ' + ' # Cheque No. :' + ISNULL(FR.ChequeNo,'') + ' BankName :' + ISNULL(FR.BankName,'') end as Narration,						
						FR.PayTypeId AS PayTypeId, 
						FR.Id AS FeeId,
						SM.AcademicId AS ReceiptId
				FROM sFee.tReceipt FR 
					INNER JOIN sFee.tReceiptDetail FRD ON FR.Id = FRD.ReceiptId
					INNER JOIN sStudent.vStudentAcademic SM ON SM.ACademicId = FR.SourceID AND SM.OrgGRoupBatchId = FR.OrgGRoupBatchId 
					INNER JOIN sFee.tFeeSetup FS ON FS.Id = FRD.FeeSetupId
					INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
					INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FM.FeeHeadId
					INNER JOIN sFinanceCommon.tPayTypeMaster PM ON PM.Id = FR.PayTypeId
					INNER JOIN sSEtup.tOrganizationMaster OM ON OM.OrgSubGRoupID =  @rReceiptBookId AND OM.ID = SM.OrgId					
					WHERE	FR.IsObsolete = 0 
							AND FR.OrgGroupBatchId = @rOrgGroupBatchId
							AND FR.ReceiptDate >= @rReceiptDate AND FR.ReceiptDate <= @rToReceiptDate
							AND FR.PayTypeID = 2
							AND (FR.PayTypeId = @rPayTypeId OR @rPayTypeId = 0)
				group by ReceiptDate,PM.Title,SM.AcademicId ,FR.PayTypeId,FR.Id,SM.Name + '(' + ClassName + ':' + DivisionName + ') ' + ' # Cheque No. :' + ISNULL(FR.ChequeNo,'') + ' BankName :' + ISNULL(FR.BankName,'')
				Order By FR.Id,ReceiptDate Desc
			END	
	ELSE IF @lTallyPostingType = 'ReceiptWise' 
			BEGIN	
				SELECT	ReceiptDate,						
						ISNULL(SLM.LedgerName,'') AS FeeName,
						PM.Title AS PayType,						
						FR.ReceiptAmount AS Amount,
						Case when @rIsCustomNarration=1 then  STUFF((SELECT ','+  +Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					replace(
																					@rCustomNarration,'[Class]',isnull(SM1.ClassName,'')
																					),'[Division]',Isnull(SM1.DivisionName,'')
																					),'[StudentsName]',isnull(SM1.Name,'')
																					), '[RollNumber]',isnull(convert(nvarchar(200),SM1.RollNo),'0')
																					),'[Batch]',isnull(SM1.BatchName,'')
																					), '[ReceiptNumber]', isnull(Convert(nvarchar(100),FR1.ReceiptNumber),'')
																					), '[ReceiptDate]',isnull(Convert(nvarchar(100),FR1.ReceiptDate),'')
																					), '[ReceiptAmount]',isnull(Convert(nvarchar(100),FR1.ReceiptAmount),'')
																					), '[ChequeNo]',isnull(Convert(nvarchar(100),FR1.ChequeNo),'')
																					),'[BankName]',isnull(FR1.BankName,'')
																					),'[FeeName]',isnull(FM1.Title,'')
																					), '[FeeAmount]',isnull(Convert(nvarchar(100),Sum(FRD.Amount)),'0.00')
																					),'[FeeHeadName]',ISNULL(FHM1.Title,'')
																					), '[FeeHeadAmount]',isnull(Convert(nvarchar(100),Sum(FRD.Amount)),'0.00')
																					), '[CollectionGroupName]',isNull(CGM1.Title,'')
																					),'[ReceiptFromNumber]',isnull(Convert(nvarchar(10),FR1.ReceiptNumber),'')
																					), '[ReceiptToNumber]',isnull(Convert(nvarchar(10),FR1.ReceiptNumber),''))
						from sFee.tReceipt FR1  INNER JOIN sFee.tReceiptDetail FRD1 ON FR1.Id = FRD1.ReceiptId
						INNER JOIN sFee.tFeeSetup FS1 ON FS1.Id = FRD1.FeeSetupId 
						INNER JOIN sStudent.vStudentAcademic SM1 ON SM1.ACademicId = FR1.SourceID AND SM1.OrgGRoupBatchId = FR1.OrgGRoupBatchId 						
						INNER JOIN sFee.tFeeMaster FM1 ON FM1.Id = FS1.FeeId --AND FRD.ReceiptId=FRD1.ReceiptId
						LEFT JOIN sFee.tCollectionGroupMaster CGM1 ON CGM1.Id = FS1.CollectionGroupId
						INNER JOIN sFinanceCommon.tPayTypeMaster PM1 ON PM1.Id = FR1.PayTypeId
						INNER JOIN sFee.tFeeHeadMaster FHM1 ON FHM1.Id = FM1.FeeHeadId
						LEFT JOIN sTally.tStudentLedgerMapping SLM1 ON SLM1.StudentId = SM1.StudentId AND SLM1.ReceiptBookid = FR1.ReceiptBookId AND SLM.LedgerName=SLM1.LedgerName where  FR1.ReceiptDate=FR.ReceiptDate   AND FR1.PayTypeId=FR.PayTypeId AND  A.StudentId=SM1.StudentId AND FR.ReceiptAmount=FR1.ReceiptAmount AND FR1.IsObsolete = 0  FOR XML PATH('')),1,1,'') else
						case When FR.PayTypeId = 1 then
						'Std-' + ClassName + ':' + DivisionName + ' RollNo :' + convert(nvarchar(20),RollNo) + ' ' + BatchName + '-->' +
						STUFF((SELECT ','  + convert(nvarchar(20),isnull(FRD1.Amount,'')) + '-' + isnull(FM1.Title ,'') 
						from sFee.tReceipt FR1  INNER JOIN sFee.tReceiptDetail FRD1 ON FR1.Id = FRD1.ReceiptId
						INNER JOIN sFee.tFeeSetup FS1 ON FS1.Id = FRD1.FeeSetupId 						
						INNER JOIN sFee.tFeeMaster FM1 ON FM1.Id = FS1.FeeId AND FRD.ReceiptId=FRD1.ReceiptId  FOR XML PATH('')),1,1,'') 
						when FR.PayTypeId <> 1 then 
						'Std-' + ClassName + ':' + DivisionName + ' RollNo :' + convert(nvarchar(20),RollNo) + ' ' + BatchName + '-->' +
						STUFF((SELECT ','  + convert(nvarchar(20),isnull(FRD1.Amount,'')) + '-' + isnull(FM1.Title ,'') 
						from sFee.tReceipt FR1  INNER JOIN sFee.tReceiptDetail FRD1 ON FR1.Id = FRD1.ReceiptId
						INNER JOIN sFee.tFeeSetup FS1 ON FS1.Id = FRD1.FeeSetupId 						
						INNER JOIN sFee.tFeeMaster FM1 ON FM1.Id = FS1.FeeId AND FRD.ReceiptId=FRD1.ReceiptId  FOR XML PATH('')),1,1,'') + '  Cheque No. :' + ISNULL(FR.ChequeNo,'') + ' BankName :' + ISNULL(FR.BankName,'')  ENd
						end AS Narration,
						--A.Name+', '+ClassName + '-' + DivisionName+', '+A.OrganizationName+', ('+BatchName+')'
						--AS Narration,					
						FR.PayTypeId AS PayTypeId,									
						A.StudentId AS FeeId,
						FRD.ReceiptId					 
				FROM sFee.tReceipt FR 
					INNER JOIN sFee.tReceiptDetail FRD ON FR.Id = FRD.ReceiptId
					INNER JOIN sFee.tFeeSetup FS ON FS.Id = FRD.FeeSetupId
					INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
					INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FM.FeeHeadId
					INNER JOIN sFinanceCommon.tPayTypeMaster PM ON PM.Id = FR.PayTypeId
					INNER JOIN sStudent.vStudentAcademic A ON A.AcademicId = FR.SourceId AND A.OrgGRoupBatchId = FR.OrgGRoupBatchId
					LEFT JOIN sTally.tStudentLedgerMapping SLM ON SLM.StudentId = A.StudentId AND SLM.ReceiptBookid = FR.ReceiptBookId
					WHERE							
							FR.ReceiptBookId = @rReceiptBookId 
							AND FR.IsObsolete = 0 
							AND FR.OrgGroupBatchId = @rOrgGroupBatchId
							AND FR.ReceiptDate >= @rReceiptDate	And FR.ReceiptDate <= @rToReceiptDate
							AND (FR.PayTypeId = @rPayTypeId OR @rPayTypeId = 0)
				group by 
				ReceiptDate,PM.Title,
				SLM.LedgerName,FR.PayTypeId,A.StudentId,
				FRD.ReceiptId,Isnull(FR.ChequeNo,''),ISNull(FR.BankName,''),
				--A.Name+', '+ClassName + '-' + DivisionName+', '+A.OrganizationName+', ('+BatchName+')',
				'Std-' + ClassName + ':' + DivisionName + ' RollNo :' + convert(nvarchar(20),RollNo) + ' ' + BatchName,
				FR.ReceiptAmount			
				Order By ReceiptDate desc
			END		
			
	ELSE IF @lTallyPostingType = 'FeeHeadAndReceiptBookWise' 
			BEGIN	
				SELECT	ReceiptDate,						
						ISNULL(SLM.LedgerName,'') AS FeeName,
						PM.Title AS PayType,						
						FR.ReceiptAmount AS Amount,
						Case when @rIsCustomNarration=1 then STUFF((SELECT ','  +Replace(replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					replace(
																					@rCustomNarration,'[Class]',isnull(SM1.ClassName,'')
																					),'[Division]',Isnull(SM1.DivisionName,'')
																					),'[StudentsName]',isnull(SM1.Name,'')
																					), '[RollNumber]',isnull(convert(nvarchar(200),SM1.RollNo),'0')
																					),'[Batch]',isnull(SM1.BatchName,'')
																					), '[ReceiptNumber]', isnull(Convert(nvarchar(100),FR1.ReceiptNumber),'')
																					), '[ReceiptDate]',isnull(Convert(nvarchar(100),FR1.ReceiptDate),'')
																					), '[ReceiptAmount]',isnull(Convert(nvarchar(100),FR1.ReceiptAmount),'')
																					), '[ChequeNo]',isnull(Convert(nvarchar(100),FR1.ChequeNo),'')
																					),'[BankName]',isnull(FR1.BankName,'')
																					),'[FeeName]',isnull(FM1.Title,'')
																					), '[FeeAmount]',isnull(Convert(nvarchar(100),Sum(FRD.Amount)),'0.00')
																					),'[FeeHeadName]',ISNULL(FHM1.Title,'')
																					), '[FeeHeadAmount]',isnull(Convert(nvarchar(100),Sum(FRD.Amount)),'0.00')
																					), '[CollectionGroupName]',isNull(CGM1.Title,'')
																					),'[ReceiptFromNumber]',isnull(Convert(nvarchar(10),FR1.ReceiptNumber),'')
																					), '[ReceiptToNumber]',isnull(Convert(nvarchar(10),FR1.ReceiptNumber),''))
						from sFee.tReceipt FR1  INNER JOIN sFee.tReceiptDetail FRD1 ON FR1.Id = FRD1.ReceiptId
						INNER JOIN sFee.tFeeSetup FS1 ON FS1.Id = FRD1.FeeSetupId 
						INNER JOIN sStudent.vStudentAcademic SM1 ON SM1.ACademicId = FR1.SourceID AND SM1.OrgGRoupBatchId = FR1.OrgGRoupBatchId 						
						INNER JOIN sFee.tFeeMaster FM1 ON FM1.Id = FS1.FeeId --AND FRD.ReceiptId=FRD1.ReceiptId
						LEFT JOIN sFee.tCollectionGroupMaster CGM1 ON CGM1.Id = FS1.CollectionGroupId
						INNER JOIN sFinanceCommon.tPayTypeMaster PM1 ON PM1.Id = FR1.PayTypeId
						INNER JOIN sFee.tFeeHeadMaster FHM1 ON FHM1.Id = FM1.FeeHeadId 
						LEFT JOIN sTally.tStudentLedgerMapping SLM1 ON SLM1.StudentId = SM1.StudentId AND SLM1.ReceiptBookid = FR1.ReceiptBookId AND SLM.LedgerName=SLM1.LedgerName where  FR1.ReceiptDate=FR.ReceiptDate AND PM1.Title=PM.Title  AND FR1.PayTypeId=FR.PayTypeId AND A.StudentId=SM1.StudentId AND FR.ReceiptAmount=FR1.ReceiptAmount AND FR1.IsObsolete = 0  FOR XML PATH('')),1,1,'') else
						case When FR.PayTypeId = 1 then
						'Receiptno-'  + CONVERT(nvarchar,isnull(FR.ReceiptNumber,'')) + 
						STUFF((SELECT ','  + convert(nvarchar(20),isnull(FM1.title,'')) 
						from sFee.tReceipt FR1  INNER JOIN sFee.tReceiptDetail FRD1 ON FR1.Id = FRD1.ReceiptId And FRD1.ReceiptId = FRD.ReceiptId 
						INNER JOIN sFee.tFeeSetup FS1 ON FS1.Id = FRD1.FeeSetupId 						
						INNER JOIN sFee.tFeeMaster FM1 ON FM1.Id = FS1.FeeId AND FRD.ReceiptId=FRD1.ReceiptId  FOR XML PATH('')),1,1,'') 
						when FR.PayTypeId <> 1 then 
						'Receiptno-'  +  CONVERT(nvarchar,isnull(FR.ReceiptNumber,'')) +
						STUFF((SELECT ','  + convert(nvarchar(20),isnull(FM1.title,'')) 
						from sFee.tReceipt FR1  INNER JOIN sFee.tReceiptDetail FRD1 ON FR1.Id = FRD1.ReceiptId And FRD1.ReceiptId = FRD.ReceiptId 
						INNER JOIN sFee.tFeeSetup FS1 ON FS1.Id = FRD1.FeeSetupId 						
						INNER JOIN sFee.tFeeMaster FM1 ON FM1.Id = FS1.FeeId AND FRD.ReceiptId=FRD1.ReceiptId  FOR XML PATH('')),1,1,'') 
						+ '  Cheque No. :' + ISNULL(FR.ChequeNo,'') + ' BankName :' + ISNULL(FR.BankName,'')  ENd
						end AS Narration,
						FR.PayTypeId AS PayTypeId,									
						A.StudentId AS FeeId,
						FRD.ReceiptId		
									 
				FROM sFee.tReceipt FR 
					INNER JOIN sFee.tReceiptDetail FRD ON FR.Id = FRD.ReceiptId
					INNER JOIN sFee.tFeeSetup FS ON FS.Id = FRD.FeeSetupId
					INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
					INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FM.FeeHeadId
					INNER JOIN sFinanceCommon.tPayTypeMaster PM ON PM.Id = FR.PayTypeId
					INNER JOIN sStudent.vStudentAcademic A ON A.AcademicId = FR.SourceId AND A.OrgGRoupBatchId = FR.OrgGRoupBatchId
					LEFT JOIN sTally.tStudentLedgerMapping SLM ON SLM.StudentId = A.StudentId AND SLM.ReceiptBookid = FR.ReceiptBookId
					WHERE							
							FR.ReceiptBookId = @rReceiptBookId 
							AND FR.IsObsolete = 0 
							AND FR.OrgGroupBatchId = @rOrgGroupBatchId
							AND FR.ReceiptDate >= @rReceiptDate	And FR.ReceiptDate <= @rToReceiptDate
							AND (FR.PayTypeId = @rPayTypeId OR @rPayTypeId = 0)
				group by 
				ReceiptDate,PM.Title,
				SLM.LedgerName,FR.PayTypeId,A.StudentId,
				FRD.ReceiptId,
				Isnull(FR.ChequeNo,''),ISNull(FR.BankName,''),
				'Std-' + ClassName + ':' + DivisionName + ' RollNo :' + convert(nvarchar(20),RollNo) + ' ' + BatchName,FR.ReceiptAmount,FR.ReceiptNumber
				--,FHM.Title
				
				Order By ReceiptDate desc	
			END	
	ELSE IF @lTallyPostingType = 'FeeHeadWiseReceipt_AllDetail' 
        BEGIN
			   SELECT	ReceiptDate,
						FR.Id AS FeeName,
						PM.Title AS PayType,
						Sum(FRD.Amount) AS Amount,
						Case when @rIsCustomNarration=1 then  STUFF((SELECT ','  +Replace(replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					replace(
																					@rCustomNarration,'[Class]',isnull(SM1.ClassName,'')
																					),'[Division]',Isnull(SM1.DivisionName,'')
																					),'[StudentsName]',isnull(SM1.Name,'')
																					), '[RollNumber]',isnull(convert(nvarchar(200),SM1.RollNo),'0')
																					),'[Batch]',isnull(SM1.BatchName,'')
																					), '[ReceiptNumber]', isnull(Convert(nvarchar(100),FR1.ReceiptNumber),'')
																					), '[ReceiptDate]',isnull(Convert(nvarchar(100),FR1.ReceiptDate),'')
																					), '[ReceiptAmount]',isnull(Convert(nvarchar(100),FR1.ReceiptAmount),'')
																					), '[ChequeNo]',isnull(Convert(nvarchar(100),FR1.ChequeNo),'')
																					),'[BankName]',isnull(FR1.BankName,'')
																					),'[FeeName]',isnull(FM1.Title,'')
																					), '[FeeAmount]',isnull(Convert(nvarchar(100),Sum(FRD.Amount)),'0.00')
																					),'[FeeHeadName]',ISNULL(FHM1.Title,'')
																					), '[FeeHeadAmount]',isnull(Convert(nvarchar(100),Sum(FRD.Amount)),'0.00')
																					), '[CollectionGroupName]',isNull(CGM1.Title,'')
																					),'[ReceiptFromNumber]',isnull(Convert(nvarchar(10),(Select Min(ReceiptNumber) from sFee.tReceipt where   FR.ReceiptDate =ReceiptDate AND IsObsolete = 0)),'')
																					), '[ReceiptToNumber]',isnull(Convert(nvarchar(10),(Select Max(ReceiptNumber) from sFee.tReceipt Where FR.ReceiptDate = ReceiptDate AND IsObsolete = 0)),''))
						from sFee.tReceipt FR1  INNER JOIN sFee.tReceiptDetail FRD1 ON FR1.Id = FRD1.ReceiptId
						INNER JOIN sFee.tFeeSetup FS1 ON FS1.Id = FRD1.FeeSetupId 
						INNER JOIN sStudent.vStudentAcademic SM1 ON SM1.ACademicId = FR1.SourceID AND SM1.OrgGRoupBatchId = FR1.OrgGRoupBatchId 						
						INNER JOIN sFee.tFeeMaster FM1 ON FM1.Id = FS1.FeeId --AND FRD.ReceiptId=FRD1.ReceiptId
						LEFT JOIN sFee.tCollectionGroupMaster CGM1 ON CGM1.Id = FS1.CollectionGroupId
						INNER JOIN sFee.tFeeHeadMaster FHM1 ON FHM1.Id = FM1.FeeHeadId  where   FR.ReceiptDate=FR1.ReceiptDate AND FR.Id=FR1.Id AND FR1.IsObsolete = 0  FOR XML PATH('')),1,1,'') else
						SM.Name + '(' + ClassName + ':' + DivisionName + ') ' + ' # Cheque No. :' + ISNULL(FR.ChequeNo,'') + ' BankName :' + ISNULL(FR.BankName,'') end as Narration,						
						FR.PayTypeId AS PayTypeId, 
						FR.Id  AS FeeId,
						FR.Id AS ReceiptId
				FROM sFee.tReceipt FR 
					INNER JOIN sFee.tReceiptDetail FRD ON FR.Id = FRD.ReceiptId
					INNER JOIN sStudent.vStudentAcademic SM ON SM.ACademicId = FR.SourceID AND SM.OrgGRoupBatchId = FR.OrgGRoupBatchId 
					INNER JOIN sFee.tFeeSetup FS ON FS.Id = FRD.FeeSetupId
					INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
					INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FM.FeeHeadId
					INNER JOIN sFinanceCommon.tPayTypeMaster PM ON PM.Id = FR.PayTypeId
					INNER JOIN sSetup.tOrganizationMaster OM ON  OM.Id=SM.OrgId
					LEFT JOIN sSetup.tOrgSubGroupMaster OSM ON OSM.id=OM.OrgSubGroupId

					WHERE	FR.ReceiptBookId= @rReceiptBookId 
							AND FR.IsObsolete = 0 
							AND FR.OrgGroupBatchId = @rOrgGroupBatchId
							AND FR.ReceiptDate >= @rReceiptDate AND FR.ReceiptDate <= @rToReceiptDate
							AND (FR.PayTypeId = @rPayTypeId OR @rPayTypeId = 0)
				group by ReceiptDate,PM.Title,FR.PayTypeId,FR.Id,SM.Name + '(' + ClassName + ':' + DivisionName + ') ' + ' # Cheque No. :' + ISNULL(FR.ChequeNo,'') + ' BankName :' + ISNULL(FR.BankName,'')
				Order By FR.Id,ReceiptDate Desc
			END			
			
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'Creating [sAdmission].[pRptAdmissionInquiryBlankFieldGet]...';


GO
CREATE PROCEDURE [sAdmission].[pRptAdmissionInquiryBlankFieldGet]

	@rClassId int = 0,
	@rBatchId int = 0
	
AS
SET NOCOUNT ON

BEGIN 
	SELECT
		AIF.ClassId,
		AIF.BatchId,
		AIF.FieldGroup,
		AIF.FieldRemark
	FROM  
		sAdmission.tAdmissionInquiryForm AIF
	WHERE 	
		AIF.ClassId = @rClassId
		AND AIF.BatchId = @rBatchId
END
GO
PRINT N'Creating [sAdmission].[pRptAdmissionInquiryBlankGet]...';


GO
CREATE PROCEDURE [sAdmission].[pRptAdmissionInquiryBlankGet]
	
	 @rClassId int = 0,
	 @rBatchId int = 0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	
	SELECT 
		ISNULL(AIC.AgeCutOffDate,'') AS AgeCutOffDate,
		AIC.ClassId,
		AIC.BatchId

	FROM
        sAdmission.tAdmissionInquiryCriteria AIC
		INNER JOIN sSetup.tClassMaster CM ON CM.Id = AIC.ClassId
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AIC.BatchId
	WHERE  
	   ((AIC.ClassId = @rClassId) OR (@rClassId = 0))
		AND ((AIC.BatchId = @rBatchId) OR (@rBatchId = 0))
END
GO
PRINT N'Creating [sAlert].[pBookIssueListGet]...';


GO

CREATE PROCEDURE [sAlert].[pBookIssueListGet]
	 	 
		 --@rBookIssueId bigint,
		 @rOrgId int,
		 @rBatchId int,
		 @rDepartmentId int,
		 @rClassId int,
		 @rDivisionId int,	 	 	 	
	 	 @rLibraryId int,
		 @rIssueDate date,
	 	 @rTemplate nvarchar(max),	 	
	 	 @rMailSubject nvarchar(500)=''
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	Select 

			SC.OrgGroupId,
			SC.OrgId,
			SC.AcademicId,
			SC.Code,
			SC.Name,
			SC.ParentContactNo AS MobileNo,	
			SC.ParentEmail AS EmailId,
			ISNULL(SC.StudentContactNo,'') AS StudentContactNo,
			ISNULL(SC.StudentEmail,'') AS StudentEmail,
			ISNULL(SC.FatherContactNo,'') AS FatherContactNo,
			ISNULL(SC.FatherMail,'') AS FatherMail,
			ISNULL(SC.MotherContactNo,'') AS MotherContactNo,
			ISNULL(SC.MotherMail,'') AS MotherMail,
			replace (
			replace (
			replace (
			replace (
			replace(@rTemplate,'[Name]',SC.Name),			
			'[BookCode]',BM.Code),
			'[BookName]',BM.Title),
			'[LibraryName]',LM.Title),
			'[IssueDate]',BL.LogDate)
			 AS Template,
			replace (
			replace (
			replace (
			replace (
			replace(@rTemplate,'[Name]',SC.Name),			
			'[BookCode]',BM.Code),
			'[BookName]',BM.Title),
			'[LibraryName]',LM.Title),
			'[IssueDate]',BL.LogDate)
			 AS MsgText,
			'2003' AS SourceTypeId,
			SC.StudentId AS SourceId,
			@rMailSubject AS Subject,
			2003 AS ReceiverSourceTypeId,
			SC.StudentId AS ReceiverSourceId,
			BM.Code AS BookCode,
			BM.Title AS BookName,
			LM.Title AS LibraryName,
			BL.LogDate AS IssueDate,
			SC.WhatsAppContactNo
		
		
	From 
		sStudent.vStudentCommunication SC
		INNER JOIN sLibrary.tBookLog BL ON BL.ReaderSourceId=SC.StudentId AND BL.ReaderSourceTypeId=2003 AND SC.OrgId = BL.OrgId
		AND BL.IsCurrentStatus=1 
		AND BL.StatusId=523 
		INNER JOIN sLibrary.tLibraryMaster LM on LM.Id=BL.LibraryId
		INNER JOIN sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId AND BL.ResourceSourceTypeId=2009
	WHERE
		(SC.OrgId = @rOrgId)
		AND (SC.BatchId = @rBatchId)
		AND ((SC.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		AND ((SC.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SC.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND BL.LibraryId=@rLibraryId
		AND BL.LogDate <= @rIssueDate
		AND (SC.StatusId=1) AND SC.IsBlockAllAlert=0	
	
END
GO


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