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

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


GO
ALTER TABLE [sAcademic].[tLessonPlan]
    ADD [AssessmentQuestion]  NVARCHAR (1000) NULL,
        [TeacherExample]      NVARCHAR (1000) NULL,
        [GuidedPractice]      NVARCHAR (1000) NULL,
        [IndependentPractice] NVARCHAR (1000) NULL;


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


GO
ALTER TABLE [sFee].[tReceipt]
    ADD [PaymentTransactionId] BIGINT NULL;


GO
PRINT N'Altering [sOp].[tGatewayConfiguration]...';


GO
ALTER TABLE [sOp].[tGatewayConfiguration]
    ADD [ContactUs] NVARCHAR (MAX) NULL,
        [AboutUs]   NVARCHAR (MAX) NULL;


GO
PRINT N'Altering [sOp].[tGatewayProduct]...';


GO
ALTER TABLE [sOp].[tGatewayProduct]
    ADD [CCAvenueSubAccountId] NVARCHAR (100) NULL;


 
     

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


GO
CREATE TABLE [dbo].[QtrData] (
    [ID]     INT NULL,
    [Qtr]    INT NULL,
    [Yr]     INT NULL,
    [Metric] INT NULL
);


GO
PRINT N'Creating [sSecurity].[tOrgGroupMobileAppDetail]...';


GO
CREATE TABLE [sSecurity].[tOrgGroupMobileAppDetail] (
    [OrgGroupId]              INT            NOT NULL,
    [ApplicationName]         NVARCHAR (100) NULL,
    [PrivacyPolicyURL]        NVARCHAR (300) NULL,
    [AndroidPackageName]      NVARCHAR (200) NULL,
    [AndroidLink]             NVARCHAR (300) NULL,
    [AndroidStatus]           INT            NULL,
    [AndroidLastVersionCode]  INT            NULL,
    [AndroidLastVersionName]  NVARCHAR (20)  NULL,
    [AndroidLastRealeaseDate] DATE           NULL,
    [iOSBundleIdentifier]     NVARCHAR (200) NULL,
    [iOSLink]                 NVARCHAR (300) NULL,
    [iOSStatus]               INT            NULL,
    [iOSLastVersionCode]      INT            NULL,
    [iOSLastVersionName]      NVARCHAR (20)  NULL,
    [iOSLastRealeaseDate]     DATE           NULL,
    [iOSExpireDate]           DATE           NULL
);


GO
PRINT N'Creating PK_tOrgGroupMobileAppDetail...';


GO
ALTER TABLE [sSecurity].[tOrgGroupMobileAppDetail]
    ADD CONSTRAINT [PK_tOrgGroupMobileAppDetail] PRIMARY KEY CLUSTERED ([OrgGroupId] ASC) WITH (ALLOW_PAGE_LOCKS = ON, ALLOW_ROW_LOCKS = ON, PAD_INDEX = OFF, IGNORE_DUP_KEY = OFF, STATISTICS_NORECOMPUTE = OFF);

GO

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


GO


CREATE 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,
		 OrgId smallint 
)  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 
   
	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
	 	
	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,
		
		  
		   @rOrgId AS OrgId
		  
	 
    RETURN  
    
END
GO

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


GO
ALTER PROCEDURE [sAcademic].[pLessonPlanAdd]
	 
        @rId bigint=0,
        @rTopicId int,
        @rDivisionId int, 
        @rNoOfPeriodRequired smallint,
        @rObjective nvarchar(200),
        @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)	
  
	
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
	
	
	
	 
	 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
		)
	VALUES
		(
			@lNextNumber,
			@rTopicId,
			@rDivisionId,
			@rNoOfPeriodRequired,
			@rObjective,
			@rIndicativeHomework,
			@rSummary,
			@rStartDate,
			@rEndDate,
			@rIsCompleted,
			@rEmployeeId,
			@rBatchId,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rLearningExperience,
			@rToolsAndTechniques,
			@rEssentialMaterial,
			@rAssessmentQuestion,
			@rTeacherExample,
			@rGuidedPractice,
			@rIndependentPractice
			
		)
		    SELECT 1 AS Result
	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	
	      WHERE Id = @rId
	      SELECT 11 AS Result
	 END  	

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


GO
ALTER PROCEDURE [sAcademic].[pLessonPlanGet]

	 @rId bigint,
	 @rClassId int,
	 @rSubjectId int,
	 @rDivisionId int,
	 @rIsCompleted bit=0,
	 @rBatchId int,
	 @rEmployeeId bigint,
	 @rDepartmentid int=0
	
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

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,
			LP.IsCompleted,
			LP.EmployeeId,
			LP.BatchId,
			LP.CreatedUserId,
			LP.CreatedDateTime,
			TM.Title AS TopicName,
			vTSD.ClassTitle+' - '+ vTSD.DivisionTitle AS ClassDivisionName,
			 
			vTSD.SubjectName,
			ISNULL(EM.FirstName,'') + ' ' + ISNULL(EM.LastName,'') AS  EmployeeName,
			LP.LearningExperience,
			LP.ToolsAndTechniques,
			LP.EssentialMaterial,
			LP.AssessmentQuestion,
			LP.TeacherExample,
			LP.GuidedPractice,
			LP.IndependentPractice
	FROM 
			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) 
		AND ((LP.EmployeeId = @rEmployeeId) OR (@rEmployeeId=0))
		AND ((LP.Id = @rId) OR (@rId = 0))
		AND ((TM.ClassId = @rClassId) OR (@rClassId = 0))
		AND ((vTSD.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))
		 Order by id 
END
GO
PRINT N'Altering [sAcademic].[pRptLessonPlanGet]...';


GO
ALTER PROCEDURE [sAcademic].[pRptLessonPlanGet]

	 
	 @rClassId int,
	 @rSubjectId int,
	 @rDivisionId int,
	 @rIsCompleted bit ,
	  @rBatchId int,
	 @rEmployeeId bigint
	
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 

	SELECT 
			LP.Id,
			TM.ClassId,
			LP.DivisionId,
			TM.SubjectId,
			LP.TopicId,
			LP.NoOfPeriodRequired,
			LP.Objective,
			LP.IndicativeHomework,
			LP.Summary,
			LP.StartDate,
			LP.EndDate,
			LP.IsCompleted,
			LP.EmployeeId,
			LP.BatchId,
			LP.CreatedUserId,
			LP.CreatedDateTime,
			TM.Title AS TopicName,
			vTSD.ClassTitle+' - '+ vTSD.DivisionTitle AS ClassDivisionName,
			vTSD.SubjectName,
			--ISNULL(EM.FirstName,'') + ' ' + ISNULL(EM.LastName,'') AS  EmployeeName,
			LP.LearningExperience,
			LP.ToolsAndTechniques,
			LP.EssentialMaterial,
			LP.AssessmentQuestion 
			
	FROM 
			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
	WHERE 
		(LP.BatchId = @rBatchId) 
		AND ((LP.EmployeeId = @rEmployeeId) OR (@rEmployeeId = 0))
		--AND ((LP.Id = @rId) OR (@rId = 0))
		AND ((TM.ClassId = @rClassId) OR (@rClassId = 0))
		AND ((vTSD.DivisionId = @rDivisionId) OR (@rDivisionId = 0))
		AND ((TM.SubjectId = @rSubjectId) OR (@rSubjectId = 0))
		AND ((LP.IsCompleted='False') OR (LP.IsCompleted=@rIsCompleted))
		
END
GO
PRINT N'Altering [sAccounting].[pVoucherListGet]...';


GO

ALTER PROCEDURE [sAccounting].[pVoucherListGet]

	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rVoucherTypeId int = 0,
	 @rTransactionDate Date,
	 @rTransactionDateTo Date,
	 @rVoucherNumber int,
	 @rVoucherNumberTo int,
	 @rLedgerId int,
	 @rNarration nvarchar(100),
	 @rAmount int,
	 @rAccountingYearId int = 0,
	 @rIsApproved bit=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

	  BEGIN
			SET @rNarration = sCommon.fSearchStringGet(@rNarration)
	  END
	 
  SELECT   @rBuilder1 AS Builder1
		  ,@rBuilder2 AS Builder2
		  ,T.Id
		  ,VTM.Title AS VoucherType
		  ,T.VoucherNumber AS VoucherNo
		  ,T.TransactionDate AS VoucherDate
		  ,LM.Title AS Ledger
		  ,CASE WHEN ISNULL(TD.Amount,0) < 0 THEN ISNULL(TD.Amount,0) * -1 ELSE 0 END AS Credit
		  ,CASE WHEN ISNULL(TD.Amount,0) > 0 THEN ISNULL(TD.Amount,0) ELSE 0 END AS Debit
		  ,T.Narration AS Narration
		  ,AM.ReportOrgTitle As OrgTitle
		  ,AM.SmallAddress1 AS SmallAddress1
		  ,AM.SmallAddress2 AS SmallAddress2,
		  T.TransactionApproveId	  	      
  FROM 
          sAccounting.tTransaction T
          INNER JOIN sAccounting.tTransactionDetail TD ON T.Id=TD.TransactionId
          INNER JOIN sAccounting.tVoucherTypeMaster VTM ON VTM.Id = T.VoucherTypeId
          INNER JOIN sAccounting.tLedgerMaster LM ON LM.Id=TD.LedgerId 
          INNER JOIN sAccounting.tAccountMaster AM ON AM.Id=T.AccountId            
  WHERE 
				(T.VoucherTypeId=@rVoucherTypeId OR @rVoucherTypeId = 0) 
			AND ((T.Narration like @rNarration) OR (ISNULL(@rNarration,'') = '')) 		
			AND (T.TransactionDate >= @rTransactionDate OR ISNULL(@rTransactionDate,'') = '') 
			And (T.TransactionDate <= @rTransactionDateTo OR ISNULL(@rTransactionDateTo,'') = '')
			AND (T.VoucherNumber >= @rVoucherNumber OR @rVoucherNumber=0) 
			AND (T.VoucherNumber <=@rVoucherNumberTo OR @rVoucherNumberTo=0)
			AND (TD.LedgerId = @rLedgerId OR @rLedgerId=0)
			AND (TD.Amount = @rAmount OR ISNULL(@rAmount,0) = 0)
			AND LM.AccountingYearId = @rAccountingYearId
			AND T.AccountingYearId = @rAccountingYearId
			AND ((@rIsApproved=1 AND  ISNULL(T.TransactionApproveId,0) !=0) OR (@rIsApproved = 0) )
			
            Order By T.VoucherTypeId,T.TransactionDate,T.VoucherNumber,Credit,Debit
END
GO
PRINT N'Altering [sAlert].[pAssociateRecipientGet]...';


GO
 ALTER  PROCEDURE [sAlert].[pAssociateRecipientGet]
	 
		@rForUserId	bigint=0,
		@rEventId	nvarchar(max)='',
		@rAutoId int=0,
		@rRoleId int=0,
		@rOrgId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	Select A.*,SR.Title As RoleName,U.DisplayTitle AS UserName,R.RoleId,
 	EM.Title As EventType
	 From sAlert.tAssociateRecipient A
	INNER JOIN sSecurity.tUserRole R ON R.UserId=A.ForUserId AND R.IsObsolete = 0
	INNER JOIN sSecurity.tRole SR ON SR.Id=R.RoleId AND SR.IsObsolete = 0
	INNER JOIN sSecurity.tUser U ON U.Id=R.UserId AND U.IsObsolete = 0
	Inner JOIN [sAlert].[tEventMaster] EM ON EM.Id=A.EventId
	Where 
	--(EventId=@rEventId OR @rEventId=0)
	 (ISNULL(EventId,'') IN( SELECT cast(item as nvarchar(max)) FROM  sCommon.fnsplit(@rEventId,',')) OR @rEventId='') 
	AND (ForUserId=@rForUserId OR @rForUserId=0)
	AND (AutoId=@rAutoId OR @rAutoId=0)
	AND (R.RoleId=@rRoleId OR @rRoleId=0)
	AND U.OrgId=@rOrgId
END
GO
PRINT N'Altering [sAlert].[pEmployeeLeaveGet]...';


GO
ALTER PROCEDURE [sAlert].[pEmployeeLeaveGet]
	
	 	 @rLeaveId bigint,
	 	 @rTemplate nvarchar(max),
	 	 @rEmployeeId bigint,
         @rBatchId int,
         @rOrgId int,
         @rStatusId int,
         @rSubject nvarchar(100)
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	DECLARE @lUserId bigint=0
	SELECT @lUserId = Id FROM sSecurity.tUser WHERE SourceId = @rEmployeeId AND SourceTypeId = 95
	
	SELECT 
			EM.EmployeeId,
			EM.Code,
			EM.EmployeeName,
			EM.MobileNumber AS MobileNo,	
			CASE
		    WHEN ISNULL(EM.CompanyEmail,'') +','+ [sAlert].[fAssociateRecipientMobileNoAndEmailGet](@lUserId,37,1) LIKE ',%,' THEN stuff(stuff(ISNULL(vEM.CompanyEmail,'') +','+ [sAlert].[fAssociateRecipientMobileNoAndEmailGet](@lUserId,37,1), 1, 1, ''),LEN(stuff(ISNULL(vEM.CompanyEmail,'') +','+ [sAlert].[fAssociateRecipientMobileNoAndEmailGet](@lUserId,37,1), 1, 1, '')),1,'')
            WHEN ISNULL(EM.CompanyEmail,'') +','+ [sAlert].[fAssociateRecipientMobileNoAndEmailGet](@lUserId,37,1) LIKE ',%' THEN stuff(ISNULL(vEM.CompanyEmail,'') +','+ [sAlert].[fAssociateRecipientMobileNoAndEmailGet](@lUserId,37,1), 1, 1, '')
			WHEN ISNULL(EM.CompanyEmail,'') +','+ [sAlert].[fAssociateRecipientMobileNoAndEmailGet](@lUserId,37,1) LIKE '%,' THEN stuff(ISNULL(vEM.CompanyEmail,'') +','+ [sAlert].[fAssociateRecipientMobileNoAndEmailGet](@lUserId,37,1), LEN(ISNULL(vEM.CompanyEmail,'') +','+ [sAlert].[fAssociateRecipientMobileNoAndEmailGet](@lUserId,37,1)), 1, '')
			ELSE ISNULL(EM.CompanyEmail,'') +','+ [sAlert].[fAssociateRecipientMobileNoAndEmailGet](@lUserId,37,1)
			END AS EmailId,
			replace (
			replace (
			replace (
			replace (
			replace (
			replace(@rTemplate,'[Name]',EM.EmployeeName),
			'[EmployeeManagerName]',ISNULL(vEM.EmployeeName,'')),
			'[FromDate]',L.FromDate),
			'[ToDate]',L.ToDate),
			'[LeaveRemark]',ISNULL(L.LeaveRemark,'')),
			'[LeaveReason]',ISNULL(L.LeaveReason,''))
			 AS MsgText,
			@rSubject AS Subject
	FROM 
		sHrm.vEmployeeCommonDetail EM
	INNER JOIN [sHrm].[tLeave] L ON  EM.EmployeeId = L.EmployeeId
	LEFT JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = L.EmployeeId
    LEFT JOIN sHrm.vEmployeeCommonDetail vEM  ON  vEM.EmployeeId = EJD.EmployeeManagerId	
	WHERE
		L.Id = @rLeaveId 
		AND L.EmployeeId=@rEmployeeId
		AND L.OrgId=@rOrgId
		AND L.BatchId=@rBatchId
		AND ((L.StatusId = @rStatusId) OR (@rStatusId = 0))
END
GO
PRINT N'Altering [sAssessment].[pCSExamScoreGet]...';


GO
ALTER PROCEDURE [sAssessment].[pCSExamScoreGet]
	  @rAcademicId bigint=0
	  ,@rOrgId int
	  ,@rExamId int
	  ,@rBatchId int
	  
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 	
BEGIN TRY
			SELECT 		
				ISNULL(CGM.Title,'') AS CSGroup,
				ISNULL(CM.Title,'') AS CS,				
				ISNULL(CC.Grade,'')  AS Grade,
				ISNULL(CC.GradeIndicator,'') AS Indicator,
				ISNULL(CC.DescriptiveIndicator,'')  AS DescriptiveIndicator,			
				ISNULL(SA.AcademicId,0) AS AcademicId,
				ISNULL(CC.IndicatorIds,'') AS IndicatorIds,
				CGM.GradeSetId,
				CM.Id as CMID,
				ISNULL(CC.ConvertedMark,0) AS ConvertedMark,
				SA.batchid,
				SA.DivisionID,
				Sa.ClassID
						
			FROM    
				sAssessment.tCCECSMaster CM 
				INNER JOIN sAssessment.tCCECSGroupMaster CGM ON CGM.Id=CM.CCECAGroupId AND CM.OrgId=@rOrgId
				INNER JOIN sAssessment.tCCECSClass CL ON CL.CCECSGroupId = CGM.Id AND CL.BatchID=@rBatchID			
				INNER JOIN sStudent.vStudentAcademic SA ON   SA.ClassId = CL.ClassId 
				INNER JOIN  sAssessment.tCCECSForClass CFC ON CFC.CCECSID=CM.Id AND CL.ClassId =CFC.ClassId AND CFC.BatchID=@rBatchID
				LEFT JOIN   sAssessment.tCCECSExamScore CC  ON CC.CCECSID=CM.ID  
				
				AND CC.AcademicId = SA.AcademicId AND ExamId=@rExamId	AND CC.AcademicId = @rAcademicId	
				WHERE ((SA.AcademicId = @rAcademicId) OR (@rAcademicId=0))
		
			ORDER BY CM.OrderIndex
			SELECT 1 AS RESULT
END TRY
BEGIN CATCH
	SELECT -1 AS RESULT
END CATCH
END
GO
PRINT N'Altering [sAssessment].[pGeneralExamCustomSearchGet]...';


GO
ALTER PROCEDURE [sAssessment].[pGeneralExamCustomSearchGet]
(
	@rOrgId smallint,
	@rBatchId int,
	@rOrderBy nvarchar(max) = 'RollNo',
	@rCode [nvarchar](20) = '',
	@rFirstName [nvarchar](50) = '',	
	@rLastName [nvarchar](50) = '',
	@rPageIndex int = null,
	@rDivisionId nvarchar(max) = '',
	@rExamId nvarchar(max) = '',
	@rFromMarks decimal(5,2),
	@rToMarks decimal(5,2),
	@rFromGradePoint decimal(6,2),
	@rToGradePoint decimal(6,2),
	@rFromRankNumber int,
	@rToRankNumber int,
	@rFromPercentage decimal(5,2),
	@rToPercentage decimal(5,2),
	@rFromPercentile decimal(5,2),
	@rToPercentile decimal(5,2),
	@rResultGrade nvarchar(10),
	@rCreatedUserId bigint,
	@rDropDownStatusId int,
	@rDropDownClassId int,
	@rDropDownDivisionId int,
	@rDropDownExamSubGroupId int,
	@rDepartmentId int=0
 )
AS
SET NOCOUNT ON
BEGIN
	SET @rOrderBy=Replace(@rOrderBy,'GR No','Code')
	SET @rOrderBy=Replace(@rOrderBy,'ID No','Code')
	DECLARE @Sql nvarchar(MAX)
	
	SET @rCode = sCommon.fSearchStringGet(@rCode)
	SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
	SET @rLastName = sCommon.fSearchStringGet(@rLastName)
	SET @rResultGrade = sCommon.fSearchStringGet(@rResultGrade)
	
	SELECT * into sAssessment.tTempGeneralExam1
	FROM sAssessment.vGeneralExamCustomSearch ECS
	WHERE (ECS.OrgId = @rOrgId) AND (ECS.BatchId = @rBatchId)
	AND ((ECS.Code Like @rCode + '%') OR (@rCode = ''))
	AND ((ECS.FirstName Like @rFirstName  + '%') OR (@rFirstName = ''))
	AND ((ECS.LastName Like @rLastName + '%')OR(@rLastName = ''))
	AND ((ECS.TotalObtain >= @rFromMarks) OR (@rFromMarks=0))
	AND ((ECS.TotalObtain <= @rToMarks) OR (@rToMarks=0))
	AND ((ECS.ResultGradePoint >= @rFromGradePoint) OR (@rFromGradePoint=0))
	AND ((ECS.ResultGradePoint <= @rToGradePoint) OR (@rToGradePoint=0))
	AND ((ECS.RankNumber >= @rFromRankNumber) OR (@rFromRankNumber=0))
	AND ((ECS.RankNumber <= @rToRankNumber) OR (@rToRankNumber=0))
	AND ((ECS.Percentage >= @rFromPercentage) OR (@rFromPercentage=0))
	AND ((ECS.Percentage <= @rToPercentage) OR (@rToPercentage=0))
	AND ((ECS.Percentile >= @rFromPercentile) OR (@rFromPercentile=0))
	AND ((ECS.Percentile <= @rToPercentile) OR (@rToPercentile=0))
	AND ((ECS.ResultGrade Like @rResultGrade + '%')OR(@rResultGrade = ''))
	AND (ECS.DivisionId In( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionId,','))OR @rDivisionId='')
	AND (ECS.ExamId In( SELECT cast(item as int) FROM  sCommon.fnsplit(@rExamId,','))OR @rExamId='')
	AND ((ECS.StatusId = @rDropDownStatusId) OR (@rDropDownStatusId=0))
	AND ((ECS.ClassId = @rDropDownClassId) OR (@rDropDownClassId=0))
	AND ((ECS.DivisionId = @rDropDownDivisionId) OR (@rDropDownDivisionId=0))
	AND ((ECS.ExamSubGroupId = @rDropDownExamSubGroupId) OR (@rDropDownExamSubGroupId=0))
	AND ((ECS.DepartmentId =@rDepartmentId) OR (@rDepartmentId =0))
	
	SET @sql='SELECT Code AS Code,Name,ClassName,RollNo,TotalMarks,TotalObtain,
	ResultStatus,ResultGrade,ResultGradePoint,RankNumber,Percentage,Percentile,
	ResultReMark,OtherRemark1,ExamName FROM sAssessment.tTempGeneralExam1 ORDER BY ' + @rOrderBy
	
	exec(@Sql)
	
	create table #TEMPExam
	(
		tid int identity(1,1),t_AcedemicId bigint
	)
	SET @sql='insert into #TEMPExam SELECT AcademicId FROM sAssessment.tTempGeneralExam1 ORDER BY ' + @rOrderBy
	
	exec (@sql)
	
	declare @lTotalRecords int,@lPageSize int = 10,@lPaging varchar(max)='',@lResult varchar(max)=''
	
	select @lTotalRecords = count(*) from #TEMPExam
	select @lPaging = @lPaging + dbo.fnc_searchpagingformat(@rPageIndex,@lTotalRecords,@lPageSize)
	
	select @lResult = @lResult + '<tr><td>' + isnull(Code,'') + '</td><td>' + isnull(Name,'') + '</td>
	<td>' + isnull(convert(varchar,RollNo),'') + '</td><td>' + isnull(ExamName,'') + '</td>
	<td>' + isnull(convert(varchar,TotalMarks),'') + '</td><td>' + isnull(convert(varchar,TotalObtain),'') + '</td>
	<td>' + isnull(ResultStatus,'') + '</td><td>' + isnull(ResultGrade,'') + '</td>
	<td>' + isnull(convert(varchar,ResultGradePoint),'') + '</td><td>' + isnull(convert(varchar,RankNumber),'') + '</td>
	<td>' + isnull(convert(varchar,Percentage),'') + '</td><td>' + isnull(convert(varchar,Percentile),'') + '</td>
	<td>' + isnull(ResultReMark,'') + '</td><td>' + isnull(OtherRemark1,'') + '</td></tr>'
	from sAssessment.tTempGeneralExam1,#TEMPExam
	where AcademicId = t_AcedemicId
	
	select @lResult as StudentList,@lPaging as Paging,@lTotalRecords as TotalRecords
	
	DROP table #TEMPExam
	DROP Table sAssessment.tTempGeneralExam1
END
GO
PRINT N'Altering [sAssessment].[pRptAllClassOverallGradeAnalysis]...';


GO
 

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

BEGIN 
	--select
	
	--	'' AS Grade1,
	--	'' AS Grade2,
	--	'' AS Grade3,
	--	'' AS Grade4,
	--	'' AS Grade5,
	--	'' AS Grade6,
	--	'' AS Grade7,
	--	'' AS Grade8,
	--	'' AS Grade9,
	--	'' AS Grade10,
	--	0 AS GradeCount1,
	--	0 AS GradeCount2,
	--	0 AS GradeCount3,
	--	0 AS GradeCount4,
	--	0 AS GradeCount5,
	--	0 AS GradeCount6,
	--	0 AS GradeCount7,
	--	0 AS GradeCount8,
	--	0 AS GradeCount9,
	--	0 AS GradeCount10,
	--	0 AS ClassId,
	--	'' AS ClassName,
	--	'' AS DivisionName,
	--	0 AS DivisionId,
	--	0 AS NoOfStudent,
	--	0.00 AS HighestPerMark,
	--	0.00 AS AveragePerMark,
	--	0.00 AS LowestPerMark,
	    --'' AS Builder1
		
		
 
	 DECLARE @GradeSetId int
	 Declare @G1 nvarchar(20),@G2 nvarchar(20),@G3 nvarchar(20),@G4 nvarchar(20),@G5 nvarchar(20),@G6 nvarchar(20),@G7 nvarchar(20),@G8 nvarchar(20),@G9 nvarchar(20),@G10 nvarchar(20)	
		
	 Set @GradeSetId =(select TOP(1)GradeSetId from sAssessment.tExamMaster  where ExamSubGroupId = @rExamSubGroupId AND BatchId=@rBatchId AND ((ClassId = @rClassId) OR (@rClassId=0)))
		  
	CREATE Table #Temp
	(
		Id Int Identity (1,1),
		GradeCode nvarchar(20),
		MinimumScore decimal(6,2),
	)
	Insert into #Temp
	
		select GradeCode,MinimumScore from  sAssessment.tGradeSetDetail where GradeSetId=@GradeSetId
	 
	 	 Set @G1=(Select GradeCode from #Temp where Id=1) 
	 	 Set @G2=(Select GradeCode from #Temp where Id=2) 
	 	 Set @G3=(Select GradeCode from #Temp where Id=3) 
	 	 Set @G4=(Select GradeCode from #Temp where Id=4) 
	     Set @G5=(Select GradeCode from #Temp where Id=5) 
         Set @G6=(Select GradeCode from #Temp where Id=6) 
	     Set @G7=(Select GradeCode from #Temp where Id=7) 
	 	 Set @G8=(Select GradeCode from #Temp where Id=8) 
	 	 Set @G9=(Select GradeCode from #Temp where Id=9) 
		 Set @G10=(Select GradeCode from #Temp where Id=10)  
	   
	 select 
		@rBuilder1 AS Builder1,
		BC.ClassId As ClassId,
		Dm.id As DivisionId,
		BC.ClassName As Classname,
		DM.DisplayTitle As DivisionName,
	  (select COUNT(R.Academicid) from sAssessment.tResult R INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	  INNER JOIN sAssessment.tExamMaster EM ON R.ExamId = EM.Id 
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) ) AS NoOfStudent,
	  
	 

	  (select MAX(R.Percentage) from sAssessment.tResult R INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	  INNER JOIN sAssessment.tExamMaster EM ON R.ExamId = EM.Id 
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND ((A.StatusId=@rStatusId) OR (@rStatusId=0))) AS HighestPerMark,

	  (select AVG(R.Percentage) from sAssessment.tResult R INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	  INNER JOIN sAssessment.tExamMaster EM ON R.ExamId = EM.Id 
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) ) AS AveragePerMark,
	  
	  (select MIN(R.Percentage) from sAssessment.tResult R INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	  INNER JOIN sAssessment.tExamMaster EM ON R.ExamId = EM.Id 
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND ((A.StatusId=@rStatusId) OR (@rStatusId=0))) AS LowestPerMark ,
	  
	  (Select COUNT(R.AcademicId) from sAssessment.tResult R INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	  INNER JOIN sAssessment.tExamMaster EM ON R.ExamId = EM.Id 
	  where 	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND  ResultGrade = @G1 AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) )AS GradeCount1,
  
	  (Select COUNT(R.AcademicId) from sAssessment.tResult R INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	  INNER JOIN sAssessment.tExamMaster EM ON R.ExamId = EM.Id 
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND  ResultGrade = @G2 AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) )AS GradeCount2,
	 

  (Select COUNT(R.AcademicId) from sAssessment.tResult R INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	  INNER JOIN sAssessment.tExamMaster EM ON R.ExamId = EM.Id 
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND  ResultGrade = @G3 AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)))AS GradeCount3,
	 

  (Select COUNT(R.AcademicId) from sAssessment.tResult R INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	  INNER JOIN sAssessment.tExamMaster EM ON R.ExamId = EM.Id 
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND  ResultGrade = @G4 AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)))AS GradeCount4,
	 
  (Select COUNT(R.AcademicId) from sAssessment.tResult R INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	  INNER JOIN sAssessment.tExamMaster EM ON R.ExamId = EM.Id 
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND  ResultGrade = @G5 AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)))AS GradeCount5,
	 
  (Select COUNT(R.AcademicId) from sAssessment.tResult R INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	  INNER JOIN sAssessment.tExamMaster EM ON R.ExamId = EM.Id 
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND  ResultGrade = @G6 AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)))AS GradeCount6,
	 
  (Select COUNT(R.AcademicId) from sAssessment.tResult R INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	  INNER JOIN sAssessment.tExamMaster EM ON R.ExamId = EM.Id 
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND  ResultGrade = @G7 AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)))AS GradeCount7,
	 
  (Select COUNT(R.AcademicId) from sAssessment.tResult R INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	  INNER JOIN sAssessment.tExamMaster EM ON R.ExamId = EM.Id 
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND  ResultGrade = @G8 AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)))AS GradeCount8,
	 
  (Select COUNT(R.AcademicId) from sAssessment.tResult R INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	  INNER JOIN sAssessment.tExamMaster EM ON R.ExamId = EM.Id 
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND  ResultGrade = @G9 AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) )AS GradeCount9,
	 
  (Select COUNT(R.AcademicId) from sAssessment.tResult R INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	  INNER JOIN sAssessment.tExamMaster EM ON R.ExamId = EM.Id 
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND  ResultGrade = @G10 AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)))AS GradeCount10,
	  
	  
   
	  ISNULL(@G1,'*') AS Grade1,
	  ISNULL(@G2,'*') AS Grade2,
	  ISNULL(@G3,'*') AS Grade3,
	  ISNULL(@G4,'*') AS Grade4,
	  ISNULL(@G5,'*') As Grade5,
	  ISNULL(@G6,'*') As Grade6,
	  ISNULL(@G7,'*') AS Grade7,
	  ISNULL(@G8,'*') AS Grade8,
	  ISNULL(@G9,'*') AS Grade9,
	 ISNULL(@G10,'*')  AS Grade10
	  

	 from
	 ssetup.tDivisionMaster DM
	 --INNER JOIN sSetup.tClassMaster CM ON CM.Id = DM.ClassId
	INNER JOIN sSetup.vBatchClass BC ON BC.ClassId = DM.ClassId
	
	--INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = BC.ClassId 
	INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=@rExamSubGroupId
		WHERE 
			(DM.ID=@rDivisionId OR @rDivisionId=0)
			AND (Dm.ClassId=@rClassId OR @rClassId=0)
			AND BC.BatchId=@rBatchId
			--AND ESGM.Id =@rExamSubGroupId
			 AND (ISNULL(Dm.ClassId,0) IN( SELECT item FROM  sCommon.fnsplit(@rClass,','))OR @rClass='')
	
  
	
END
GO
PRINT N'Altering [sAssessment].[pRptAllClassSubjectGradeAnalysis]...';


GO


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

BEGIN 
	--select
	
	--	'' AS Grade1,
	--	'' AS Grade2,
	--	'' AS Grade3,
	--	'' AS Grade4,
	--	'' AS Grade5,
	--	'' AS Grade6,
	--	'' AS Grade7,
	--	'' AS Grade8,
	--	'' AS Grade9,
	--	'' AS Grade10,
	--	0 AS GradeCount1,
	--	0 AS GradeCount2,
	--	0 AS GradeCount3,
	--	0 AS GradeCount4,
	--	0 AS GradeCount5,
	--	0 AS GradeCount6,
	--	0 AS GradeCount7,
	--	0 AS GradeCount8,
	--	0 AS GradeCount9,
	--	0 AS GradeCount10,
	--	0 AS ClassId,
	--	'' AS ClassName,
	--	'' AS DivisionName,
	--	0 AS DivisionId,
	--	0 AS NoOfStudent,
	--	0.00 AS HighestPerMark,
	--	0.00 AS AveragePerMark,
	--	0.00 AS LowestPerMark,
	--    '' AS Builder1,
	--    0 AS SubjectId,
	--    '' AS SubjectName,
	--0 AS OrderIndex
		
		
 
	 DECLARE @GradeSetId int
	 Declare @G1 nvarchar(20),@G2 nvarchar(20),@G3 nvarchar(20),@G4 nvarchar(20),@G5 nvarchar(20),@G6 nvarchar(20),@G7 nvarchar(20),@G8 nvarchar(20),@G9 nvarchar(20),@G10 nvarchar(20)	
		
	 Set @GradeSetId =(select TOP(1)GradeSetId from sAssessment.tExamMaster  where ExamSubGroupId = @rExamSubGroupId AND BatchId=@rBatchId)
		  
	CREATE Table #Temp
	(
		Id Int Identity (1,1),
		GradeCode nvarchar(20),
		MinimumScore decimal(6,2),
	)
	Insert into #Temp
	
		select GradeCode,MinimumScore from  sAssessment.tGradeSetDetail where GradeSetId=@GradeSetId
	 
	 	 Set @G1=(Select GradeCode from #Temp where Id=1) 
	 	 Set @G2=(Select GradeCode from #Temp where Id=2) 
	 	 Set @G3=(Select GradeCode from #Temp where Id=3) 
	 	 Set @G4=(Select GradeCode from #Temp where Id=4) 
	     Set @G5=(Select GradeCode from #Temp where Id=5) 
         Set @G6=(Select GradeCode from #Temp where Id=6) 
	     Set @G7=(Select GradeCode from #Temp where Id=7) 
	 	 Set @G8=(Select GradeCode from #Temp where Id=8) 
	 	 Set @G9=(Select GradeCode from #Temp where Id=9) 
		 Set @G10=(Select GradeCode from #Temp where Id=10)  
	   
	 select 
		@rBuilder1 AS Builder1,
		Cm.Classid As ClassId,
		Dm.id As DivisionId,
		Cm.ClassName As Classname,
		DM.DisplayTitle As DivisionName,
		
		 
	  
	  (select COUNT(RD.Id) from    sAssessment.tResultDetail RD INNER JOIN  sAssessment.tResult R ON RD.ResultId = R.Id  
	  INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	  INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
	  	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND CS.SubjectId=SM.Id AND ((A.StatusId=@rStatusId) OR (@rStatusId=0))) AS NoOfStudent,
	  
	 

	  (select MAX(RD.Obtain) from  sAssessment.tResultDetail RD INNER JOIN  sAssessment.tResult R ON RD.ResultId = R.Id  
	  INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	   INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
	  	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND CS.SubjectId=SM.Id AND ((A.StatusId=@rStatusId) OR (@rStatusId=0))) AS HighestPerMark,

	  (select AVG(RD.Obtain) from  sAssessment.tResultDetail RD INNER JOIN  sAssessment.tResult R  ON RD.ResultId = R.Id   
	    INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	   INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
	  	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND CS.SubjectId=SM.Id AND ((A.StatusId=@rStatusId) OR (@rStatusId=0))) AS AveragePerMark,
	  
	  (select MIN(RD.Obtain) from sAssessment.tResultDetail RD INNER JOIN  sAssessment.tResult R ON RD.ResultId = R.Id 
	  INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	    INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
	  	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND CS.SubjectId=SM.Id AND ((A.StatusId=@rStatusId) OR (@rStatusId=0))) AS LowestPerMark ,
	  
	  (Select COUNT(R.AcademicId) from sAssessment.tResultDetail RD INNER JOIN  sAssessment.tResult R ON RD.ResultId = R.Id  
	  INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	 INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
		INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND  SubjectGrade = @G1  AND CS.SubjectId=SM.Id AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)))AS GradeCount1,
	  
  (Select COUNT(R.AcademicId) from sAssessment.tResultDetail RD INNER JOIN  sAssessment.tResult R   ON RD.ResultId = R.Id   
  INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	  INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
	  INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND  SubjectGrade = @G2  AND CS.SubjectId=SM.Id AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) )AS GradeCount2,
	 

  (Select COUNT(R.AcademicId)from sAssessment.tResultDetail RD INNER JOIN  sAssessment.tResult R   ON RD.ResultId = R.Id   
  INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	 INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
	  INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND  SubjectGrade = @G3  AND CS.SubjectId=SM.Id AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)))AS GradeCount3,
	 

  (Select COUNT(R.AcademicId) from sAssessment.tResultDetail RD INNER JOIN  sAssessment.tResult R  ON RD.ResultId = R.Id  
  INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	  INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
	  INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND  SubjectGrade = @G4  AND CS.SubjectId=SM.Id AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)))AS GradeCount4,
	 
  (Select COUNT(R.AcademicId) from sAssessment.tResultDetail RD INNER JOIN  sAssessment.tResult R ON RD.ResultId = R.Id   
  INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	  INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
	  INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND  SubjectGrade = @G5  AND CS.SubjectId=SM.Id AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)))AS GradeCount5,
	 
  (Select COUNT(R.AcademicId) from sAssessment.tResultDetail RD INNER JOIN  sAssessment.tResult R ON RD.ResultId = R.Id  
  INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	 INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
	  INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND  SubjectGrade = @G6  AND CS.SubjectId=SM.Id AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)))AS GradeCount6,
	 
  (Select COUNT(R.AcademicId) from sAssessment.tResultDetail RD INNER JOIN  sAssessment.tResult R ON RD.ResultId = R.Id  
  INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	  INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
	  INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND  SubjectGrade = @G7  AND CS.SubjectId=SM.Id  AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)))AS GradeCount7,
	 
  (Select COUNT(R.AcademicId) from sAssessment.tResultDetail RD INNER JOIN  sAssessment.tResult R ON RD.ResultId = R.Id   
  INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	   INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
	  INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND  SubjectGrade = @G8  AND CS.SubjectId=SM.Id AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) )AS GradeCount8,
	 
  (Select COUNT(R.AcademicId) from sAssessment.tResultDetail RD INNER JOIN  sAssessment.tResult R  ON RD.ResultId = R.Id  
  INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	   INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
	  INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND  SubjectGrade = @G9  AND CS.SubjectId=SM.Id AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) )AS GradeCount9,
	 
  (Select COUNT(R.AcademicId) from sAssessment.tResultDetail RD INNER JOIN  sAssessment.tResult R ON RD.ResultId = R.Id   
  INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	 INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
	  INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND  SubjectGrade = @G10  AND CS.SubjectId=SM.Id AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)))AS GradeCount10,
	  
	  
   
	  ISNULL(@G1,'*') AS Grade1,
	  ISNULL(@G2,'*') AS Grade2,
	  ISNULL(@G3,'*') AS Grade3,
	  ISNULL(@G4,'*') AS Grade4,
	  ISNULL(@G5,'*') As Grade5,
	  ISNULL(@G6,'*') As Grade6,
	  ISNULL(@G7,'*') AS Grade7,
	  ISNULL(@G8,'*') AS Grade8,
	  ISNULL(@G9,'*') AS Grade9,
	 ISNULL(@G10,'*')  AS Grade10,
	 Sm.Id AS SubjectId,
	  SM.Title AS SubjectName,
	  CS.OrderIndex AS OrderIndex 
	  

	 from
	 ssetup.tDivisionMaster DM
	 INNER JOIN sSetup.vBatchClass CM ON CM.ClassId = DM.ClassId
	INNER JOIN sSetup.tClassSubject CS ON CS.ClassId=CM.ClassId	
	INNER JOIN sSetup.tSubjectMaster   SM ON SM.Id = CS.SubjectId
	INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.ClassId
		WHERE 
			DM.ID=@rDivisionId or @rDivisionId=0
			AND Dm.ClassId=@rClassId or @rClassId=0
			AND CM.BatchId=@rBatchId
			AND EM.ExamSubGroupId =@rExamSubGroupId
			 AND (ISNULL(Dm.ClassId,0) IN( SELECT item FROM  sCommon.fnsplit(@rClass,','))OR @rClass='')
	
  
	
END
GO
PRINT N'Altering [sAssessment].[pRptBrightStudentAnalysisListGet]...';


GO


ALTER  PROCEDURE [sAssessment].[pRptBrightStudentAnalysisListGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
 
	 @rBatchId int,
	 @rClassId int,
	 @rDivisionId int,
	 
	 @rExamSubGroupId int=0,
	 @rCode nvarchar(20)='',
	 @rFromRollNo int=0,
	 @rToRollNo int=0,
	 --@rFromRank int=0,
	 --@rToRank int=0,
	 --@rGrade nvarchar(20)='',
	 --@rAcademicId bigint=0,
	 @rFromPercentage decimal(5,2)=0,
	 @rToPercentage decimal(5,2)=0,
	 @rGroupId int=0,
	 @rTop int=0,
	 @rClass NVARCHAR(MAX)='',
	 @rStatusId int = 0
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
SELECT r1.*
FROM
(	SELECT 	
			 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			
			ROW_NUMBER() OVER(PARTITION BY 
				CASE WHEN @rGroupId=1 THEN DM.Id 
				WHEN @rGroupId=2 THEN CM.Id 
				WHEN @rGroupId =3 THEN Dept.Id 
				WHEn @rGroupId =4 THEN OM.Id END  ORDER BY R.Percentage DESC) rn,
			
			
			ESGM.Title AS Exam,
			SM.Code,
			SM.FirstName + ' ' + SM.MiddleName + ' ' + SM.LastName  AS Name,
			
			A.RollNo,
			R.AcademicId,
			CM.DisplayTitle+'/'+DM.DisplayTitle AS Class,
			DM.DisplayTitle AS Division,
			DM.Id AS DivisionId,
			DM.OrderIndex AS DivisinOrderIndex,
			R.Percentage,
			EM.IsMarksInDecimal,
			
			CASE WHEN @rGroupId=1 THEN DM.Id 
				WHEN @rGroupId=2 THEN CM.Id 
				WHEN @rGroupId =3 THEN Dept.Id 
				WHEn @rGroupId =4 THEN OM.Id END AS GroupId,
				
			CASE WHEN @rGroupId=1 THEN CM.DisplayTitle+'/'+DM.DisplayTitle
				WHEN @rGroupId=2 THEN CM.DisplayTitle
				WHEN @rGroupId=3 THEN Dept.Title 
				WHEN @rGroupId=4 THEN OM.Title END AS GroupName,
				
			CASE WHEN @rGroupId=1 THEN Dm.OrderIndex
				WHEN @rGroupId=2  THEN Cm.OrderIndex
				WHEN @rGroupId=3  THEN Dept.Id
				WHen @rGroupId=4 THen OM.OrderIndex  END AS OrderIndex,
				
			CASE WHEN @rGroupId=1 THEN 'Class/Division'
				WHEN @rGroupId=2  THEN 'Class'
				WHEN @rGroupId=3  THEN 'Department'
				WHen @rGroupId=4 THen  'Organization'  END AS GroupTitle,
			R.TotalMarks,
			R.TotalObtain,
			R.ResultGrade 
			 
			  
	FROM 
			sAssessment.tExamMaster EM
			INNER JOIN sAssessment.tResult R ON EM.Id=R.ExamId			
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId
			INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId=A.AcademicId
			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 A.DivisionId=DM.Id
			  INNER JOIN sSetup.tDepartmentMaster Dept ON Dept.Id=CM.DepartmentId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=Dept.OrgId
	WHERE 
			
		      EM.BatchId = @rBatchId 
		AND ((A.ClassId=@rClassId) OR (@rClassId=0)) 
		AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		 AND ((ESGM.Id=@rExamSubGroupId )	OR (@rExamSubGroupId = 0))
		AND ((SM.Code=@rCode) OR (@rCode=''))
		AND ((R.Percentage >=@rFromPercentage) OR (@rFromPercentage=0))
		AND ((R.Percentage <=@rToPercentage) OR (@rToPercentage=0))		
		AND (ISNULL(A.ClassId,0) IN( SELECT item FROM  sCommon.fnsplit(@rClass,','))OR @rClass='')
		AND ((A.StatusId=@rStatusId) OR (@rStatusId=0))
	)r1
	WHERE ((r1.rn <= @rTop) Or (@rTop = 0))
END
GO
PRINT N'Altering [sAssessment].[pRptBrightStudentAnalysisListSubjectWiseGet]...';


GO


ALTER PROCEDURE [sAssessment].[pRptBrightStudentAnalysisListSubjectWiseGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
 
	 @rBatchId int,
	 @rClassId int,
	 @rDivisionId int,
	 
	 @rExamSubGroupId int=0,
	 @rCode nvarchar(20)='',
	 @rFromRollNo int=0,
	 @rToRollNo int=0,
	 @rSubjectId int=0,
	 --@rFromPercentage decimal(5,2)=0,
	 --@rToPercentage decimal(5,2)=0,
	 @rGroupId int=0,
	 @rTop int=0,
	 @rClass nvarchar(max)='',
	  @rStatusId int = 0
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
SELECT r1.*
FROM
(	SELECT 	
			 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			
			ROW_NUMBER() OVER(PARTITION BY 
				CASE WHEN @rGroupId=1 THEN DM.Id 
				WHEN @rGroupId=2 THEN CM.Id 
				WHEN @rGroupId =3 THEN Dept.Id 
				WHEn @rGroupId =4 THEN OM.Id END  ORDER BY RD.Obtain DESC) rn,
			
			
			ESGM.Title AS Exam,
			SM.Code,
			SM.FirstName + ' ' + SM.MiddleName + ' ' + SM.LastName  AS Name,
			
			A.RollNo,
			R.AcademicId,
			CM.DisplayTitle+'/'+DM.DisplayTitle AS Class,
			DM.DisplayTitle AS Division,
			DM.Id AS DivisionId,
			DM.OrderIndex AS DivisinOrderIndex,
			R.Percentage,
			EM.IsMarksInDecimal,
			
			CASE WHEN @rGroupId=1 THEN DM.Id 
				WHEN @rGroupId=2 THEN CM.Id 
				WHEN @rGroupId =3 THEN Dept.Id 
				WHEn @rGroupId =4 THEN OM.Id END AS GroupId,
				
			CASE WHEN @rGroupId=1 THEN CM.DisplayTitle+'/'+DM.DisplayTitle
				WHEN @rGroupId=2 THEN CM.DisplayTitle
				WHEN @rGroupId=3 THEN Dept.Title 
				WHEN @rGroupId=4 THEN OM.Title END AS GroupName,
				
			CASE WHEN @rGroupId=1 THEN Dm.OrderIndex
				WHEN @rGroupId=2  THEN Cm.OrderIndex
				WHEN @rGroupId=3  THEN Dept.Id
				WHen @rGroupId=4 THen OM.OrderIndex  END AS OrderIndex,
				
			CASE WHEN @rGroupId=1 THEN 'Class/Division'
				WHEN @rGroupId=2  THEN 'Class'
				WHEN @rGroupId=3  THEN 'Department'
				WHen @rGroupId=4 THen  'Organization'  END AS GroupTitle,
			Sub.Title AS SubjectName,
			Sub.Id AS SubjectId,
			RD.Obtain ,
			R.TotalMarks,
			ED.Maximum,
			RD.SubjectGrade
			  
	FROM 
			sAssessment.tExamMaster EM
			INNER JOIN sAssessment.tResult R ON EM.Id=R.ExamId		
			INNER JOIN sAssessment.tResultDetail RD ON RD.ResultId =R.Id	
			INNER JOIN sAssessment.tExamDetail ED ON ED.Id = RD.ExamDetailId
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId
			INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId=A.AcademicId
			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 A.DivisionId=DM.Id
			INNER JOIN sSetup.tDepartmentMaster Dept ON Dept.Id=CM.DepartmentId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=Dept.OrgId
			INNER JOIN sSetup.tClassSubject CS ON ED.ClassSubjectId = CS.Id 
			INNER JOIN sSetup.tSubjectMaster SUB ON CS.SubjectId =  SUB.Id
	WHERE 
			
		      EM.BatchId = @rBatchId 
		AND ((A.ClassId=@rClassId) OR (@rClassId=0)) 
		AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		 AND ((ESGM.Id=@rExamSubGroupId )	OR (@rExamSubGroupId = 0))
		AND ((SM.Code=@rCode) OR (@rCode=''))
		 AND SUB.Id=@rSubjectId
		AND (ISNULL(A.ClassId,0) IN( SELECT item FROM  sCommon.fnsplit(@rClass,','))OR @rClass='')
		AND ((A.StatusId=@rStatusId) OR (@rStatusId=0))
	)r1
	WHERE ((r1.rn <= @rTop) Or (@rTop = 0))
END
GO
PRINT N'Altering [sAssessment].[pRptFASAAnalysisGet]...';


GO


ALTER PROCEDURE [sAssessment].[pRptFASAAnalysisGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rSubjectId int = 0,
	 @rBatchId int=0,
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rExamSubGroupId int,
	 @rStatusId int =0
	-- @rClass nvarchar(max)=''
	 --@rCode nvarchar(20)='',
	 --@rFromRollNo int=0,
	 --@rToRollNo int=0,
	 --@rFromRank int=0,
	 --@rToRank int=0,
	 --@rGrade nvarchar(20)='',
	 --@rResultId bigint=0,
	 --@rStatusId int=0,
	 --@rAcademicId bigint=0
	 --,@rcolumn_visible bit
	 
	

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
 begin
 
--SELECT 
--	@rBuilder1 AS Builder1,
--	'' AS SubjectName,
--	0 as DivisionId,
--	'' as DivisionName,
--	0 AS ClassSubjectId,
--'' AS FA0SA0,
--'' AS FA0SA7,
--'' AS FA0SA13,
--'' AS FA0SA19,
--'' AS FA0SA25,
--'' AS FA5SA0,
--'' AS FA5SA7,
--'' AS FA5SA13,
--'' AS FA5SA19,
--'' AS FA5SA25,
--'' AS FA9SA0,
--'' AS FA9SA7,
--'' AS FA9SA13,
--'' AS FA9SA19,
--'' AS FA9SA25,
--'' AS FA13SA0,
--'' AS FA13SA7,
--'' AS FA13SA13,
--'' AS FA13SA19,
--'' AS FA13SA25,
--'' AS FA17SA0,
--'' AS FA17SA7,
--'' AS FA17SA13,
--'' AS FA17SA19,
--'' AS FA17SA25

DECLARE   @lExamId Bigint
DECLARE   @IsIncludeSubExam bit

SELECT @lExamId = Id FRom sAssessment.tExamMaster where ExamSubGroupId = @rExamSubGroupId AND ClassId =@rClassId
SELECT  @IsIncludeSubExam = ISNULL(IsIncludeSubExam,0)  FROM sAssessment.tExamMaster WHERE Id = @lExamId
 
 
 
CREATE TABLE #TempAllExam
	(
		
		AcademicId bigint,
		RollNo int,
		Obtain1 decimal(8,2),
		Obtain2 decimal(8,2),
		Obtain3 decimal(8,2),
		Obtain4 decimal(8,2),
		Obtain5 decimal(8,2),
		Obtain6 decimal(8,2),
		ResultId bigint,
		ClassSubjectID int ,
		ExamId int,
		SubjectName nvarchar(50),
		
		DivisionId int,
		DivisionName nvarchar(200)
	
	)
	
	
	
--	CREATE TABLE #TempExam
--(
--	Id int IDENTITY,
--	ExamSubGroupId int
--	)
--INSERT INTO #TempExam
--(
--	ExamSubGroupId
--)
--select ExamSubGroupId from sAssessment.tExamMaster 

-- DECLARE @lCount2 int,@lExamSubGroupId int
-- --select @lCount2= MAX(Id) from #TempExam
  
-- while (@lCount2>0)
-- begin
 
--	select @lExamSubGroupId=ExamSubGroupId from #TempExam

		INSERT into #TempAllExam
			(
				AcademicId,
				RollNo,
				--Obtain,
				ResultId,
				ClassSubjectID,
				ExamId,
				SubjectName,
				DivisionId,
				DivisionName
				
			)
			
			
		SELECT
			A.Id,
			A.RollNo,
			--RD.Obtain,
			R.Id AS ResultId,
			ED.ClassSubjectId,
			Ed.ExamId,
			Sm.Title AS SubjectName,
			Dm.Id AS DivisionId,
			DM.DisplayTitle AS DivisionName
			
			
		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 sStudent.tAcademic A ON A.Id=R.AcademicId	
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId
			
			 INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
			inner join sStudent.tStudentMaster STM ON STM.Id = A.StudentId 
		WHERE
			 R.ExamId = @lExamId 
				AND ((CS.Id=@rSubjectId) OR (@rSubjectId=0))
				AND ((A.ClassId =  @rClassId) OR (@rClassId=0))	
				 AND ((DM.Id =  @rDivisionId) OR (@rDivisionId=0))	 
				AND ((A.BatchId =  @rBatchId) OR (@rBatchId=0))
				and((STM.StatusId=@rStatusId) or (@rStatusId=0))
				  
				
	
	create TABLE #tempcombineExam
	(	Id int IDENTITY,
		ExamID int )

	IF (@IsIncludeSubExam = 0)
	BEGIN	
	INSERT INTO #tempcombineExam (ExamID) 
	SELECT SUBEXAMID FROM sAssessment.tExamCombine   WHERE ExamId  = @lExamId Order By ExamOrder ASC
 	END
 	ELSE
 	BEGIN
 	 
 	INSERT INTO #tempcombineExam (ExamID) 
	SELECT C.SUBEXAMID FROM sAssessment.tExamCombine C
	INNER JOIN (SELECT SUBEXAMID,ExamOrder FROM sAssessment.tExamCombine WHERE ExamId  = @lExamId) E
	ON C.ExamId = E.SubExamId
	ORDER BY E.ExamOrder,C.ExamOrder
	END
	
	DECLARE @lCount int,@query  AS NVARCHAR(MAX),@lSubExamId int,@lCount1 int
  
	Select @lCount = MAX(Id) from #tempcombineExam
	 
	DECLARE @ExamTitle nvarchar(150)
	while (@lCount > 0)
	begin
	select @lSubExamId = ExamID from #tempcombineExam Where Id = @lCount	
	
		set @query ='update T SET
					  --MaximumMark' + convert(nvarchar(15),@lCount)+ '=ED.Maximum,
					 Obtain' + convert(nvarchar(15),@lCount)+'=RD.Obtain
					  										
				 From
					sAssessment.tResultDetail RD
						INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
						execute(@query)
			set @lCount = @lCount -1
		end
		
		--set @lcount2=@lCount2-1
		-- END
 
		
	 
	SELECT  
		
		@rBuilder1 AS Builder1,
		DM.Title AS DivisionName,
		DM.Id AS DivisionId,
		 CS.ID AS ClassSubjectId,
		SM.Title AS SubjectName,
		--(Select  COALESCE( @rollno + ',','') + CAST(RollNo AS Varchar(200)) from  #TempAllExam   where (Obtain1+Obtain2>=0 AND Obtain1+Obtain2<=4) AND (Obtain3>=0 and Obtain3<=6) )
	 
		--Select @rollno AS FA0SA0,
		 
		(SELECT  
			(select stuff((select ',' +CAST(RollNo AS Varchar(200)) from  #TempAllExam  T 
		 		where ED.ClassSubjectId=T.ClassSubjectId   and T.DivisionId=Dm.Id
		 		AND ED.ExamId=T.ExamId AND (Obtain1+Obtain2>=0 AND Obtain1+Obtain2<=4) 
		 		AND (Obtain3>=0 and Obtain3<=6) FOR XML Path('')),1,1,'')) 
		 ) AS FA0SA0,
		 --(select stuff((select CAST(RollNo AS Varchar(200 ))+ ',' from  #TempAllExam  
			--where (Obtain1+Obtain2>=0 AND Obtain1+Obtain2<=4) AND (Obtain3>=7 and Obtain3<=12) FOR XML Path('')),1,1,'')) AS FA0SA7,
	    (SELECT  
			(select stuff((select ',' +CAST(RollNo AS Varchar(200)) from  #TempAllExam  T 
		 		where ED.ClassSubjectId=T.ClassSubjectId  AND ED.ExamId=T.ExamId and T.DivisionId=Dm.Id AND (Obtain1+Obtain2>=0 AND Obtain1+Obtain2<=4) AND (Obtain3>=7 and Obtain3<=12) FOR XML Path('')),1,1,'')) 
		 )AS FA0SA7,
	    
	    (SELECT  
			(select stuff((select ',' +CAST(RollNo AS Varchar(200)) from  #TempAllExam  T 
		 		where ED.ClassSubjectId=T.ClassSubjectId  AND ED.ExamId=T.ExamId and T.DivisionId=Dm.Id AND (Obtain1+Obtain2>=0 AND Obtain1+Obtain2<=4) AND (Obtain3>=13 and Obtain3<=18) FOR XML Path('')),1,1,'')) 
		 ) AS FA0SA13,
		(SELECT  
			(select stuff((select ',' +CAST(RollNo AS Varchar(200)) from  #TempAllExam  T 
		 		where ED.ClassSubjectId=T.ClassSubjectId  AND ED.ExamId=T.ExamId and T.DivisionId=Dm.Id AND (Obtain1+Obtain2>=0 AND Obtain1+Obtain2<=4) AND (Obtain3>=19 and Obtain3<=24) FOR XML Path('')),1,1,'')) 
		 ) AS FA0SA19,
		(SELECT  
			(select stuff((select ',' +CAST(RollNo AS Varchar(200)) from  #TempAllExam  T 
		 		where ED.ClassSubjectId=T.ClassSubjectId AND ED.ExamId=T.ExamId and T.DivisionId=Dm.Id AND (Obtain1+Obtain2>=0 AND Obtain1+Obtain2<=4) AND (Obtain3>=25 and Obtain3<=30) FOR XML Path('')),1,1,'')) 
		 ) AS FA0SA25,
		
		 (SELECT  
			(select stuff((select ',' +CAST(RollNo AS Varchar(200)) from  #TempAllExam  T 
		 		where ED.ClassSubjectId=T.ClassSubjectId  AND ED.ExamId=T.ExamId and T.DivisionId=Dm.Id AND (Obtain1+Obtain2>=5 AND Obtain1+Obtain2<=8) AND (Obtain3>=0 and Obtain3<=6) FOR XML Path('')),1,1,'')) 
		 ) AS FA5SA0,
		 	
		(SELECT  
			(select stuff((select ',' +CAST(RollNo AS Varchar(200)) from  #TempAllExam  T 
		 		where ED.ClassSubjectId=T.ClassSubjectId AND ED.ExamId=T.ExamId and T.DivisionId=Dm.Id AND (Obtain1+Obtain2>=5 AND Obtain1+Obtain2<=8) AND (Obtain3>=7 and Obtain3<=12) FOR XML Path('')),1,1,'')) 
		 )AS FA5SA7,
			
		(SELECT  
			(select stuff((select ',' +CAST(RollNo AS Varchar(200)) from  #TempAllExam  T 
		 		where ED.ClassSubjectId=T.ClassSubjectId AND ED.ExamId=T.ExamId and T.DivisionId=Dm.Id AND (Obtain1+Obtain2>=5 AND Obtain1+Obtain2<=8) AND (Obtain3>=13 and Obtain3<=18) FOR XML Path('')),1,1,'')) 
		 ) AS FA5SA13,
		(SELECT  
			(select stuff((select ',' +CAST(RollNo AS Varchar(200)) from  #TempAllExam  T 
		 		where ED.ClassSubjectId=T.ClassSubjectId   AND ED.ExamId=T.ExamId and T.DivisionId=Dm.Id  AND (Obtain1+Obtain2>=5 AND Obtain1+Obtain2<=8) AND (Obtain3>=19 and Obtain3<=24) FOR XML Path('')),1,1,'')) 
		 ) AS FA5SA19,
		(SELECT  
			(select stuff((select ',' +CAST(RollNo AS Varchar(200)) from  #TempAllExam  T 
		 		where ED.ClassSubjectId=T.ClassSubjectId   AND ED.ExamId=T.ExamId and T.DivisionId=Dm.Id AND (Obtain1+Obtain2>=5 AND Obtain1+Obtain2<=8) AND (Obtain3>=25 and Obtain3<=30) FOR XML Path('')),1,1,'')) 
		 ) AS FA5SA25,
		
		(SELECT  
			(select stuff((select ',' +CAST(RollNo AS Varchar(200)) from  #TempAllExam  T 
		 		where ED.ClassSubjectId=T.ClassSubjectId AND ED.ExamId=T.ExamId and T.DivisionId=Dm.Id AND (Obtain1+Obtain2>=9 AND Obtain1+Obtain2<=12) AND (Obtain3>=0 and Obtain3<=6) FOR XML Path('')),1,1,'')) 
		 ) AS FA9SA0,
		(SELECT  
			(select stuff((select ',' +CAST(RollNo AS Varchar(200)) from  #TempAllExam  T 
		 		where ED.ClassSubjectId=T.ClassSubjectId AND  T.ExamId=@lExamId and T.DivisionId=Dm.Id AND (Obtain1+Obtain2>=9 AND Obtain1+Obtain2<=12) AND (Obtain3>=7 and Obtain3<=12) FOR XML Path('')),1,1,'')) 
		 ) AS FA9SA7,
		(SELECT  
			(select stuff((select ',' +CAST(RollNo AS Varchar(200)) from  #TempAllExam  T 
		 		where  ED.ClassSubjectId=T.ClassSubjectId  AND ED.ExamId=T.ExamId and T.DivisionId=Dm.Id AND (Obtain1+Obtain2>=9 AND Obtain1+Obtain2<=12) AND (Obtain3>=13 and Obtain3<=18) FOR XML Path('')),1,1,'')) 
		 ) AS FA9SA13,
		(SELECT  
			(select stuff((select ',' +CAST(RollNo AS Varchar(200)) from  #TempAllExam  T 
		 		where ED.ClassSubjectId=T.ClassSubjectId  AND ED.ExamId=T.ExamId and T.DivisionId=Dm.Id AND (Obtain1+Obtain2>=9 AND Obtain1+Obtain2<=12) AND (Obtain3>=19 and Obtain3<=24) FOR XML Path('')),1,1,'')) 
		 ) AS FA9SA19,
		(SELECT  
			(select stuff((select ',' +CAST(RollNo AS Varchar(200)) from  #TempAllExam  T 
		 		where ED.ClassSubjectId=T.ClassSubjectId AND ED.ExamId=T.ExamId and T.DivisionId=Dm.Id  AND (Obtain1+Obtain2>=9 AND Obtain1+Obtain2<=12) AND (Obtain3>=25 and Obtain3<=30) FOR XML Path('')),1,1,'')) 
		 ) AS FA9SA25,
		
		(SELECT  
			(select stuff((select ',' +CAST(RollNo AS Varchar(200)) from  #TempAllExam  T 
		 		where ED.ClassSubjectId=T.ClassSubjectId AND ED.ExamId=T.ExamId and T.DivisionId=Dm.Id AND (Obtain1+Obtain2>=13 AND Obtain1+Obtain2<=16) AND (Obtain3>=0 and Obtain3<=6)
		 		 FOR XML Path('')),1,1,'')) 
		 ) AS FA13SA0,
		(SELECT  
			(select stuff((select ',' +CAST(RollNo AS Varchar(200)) from  #TempAllExam  T 
		 		where ED.ClassSubjectId=T.ClassSubjectId AND ED.ExamId=T.ExamId and T.DivisionId=Dm.Id AND (Obtain1+Obtain2>=13 AND Obtain1+Obtain2<=16) AND (Obtain3>=7 and Obtain3<=12) 
		 		FOR XML Path('')),1,1,'')) 
		 ) AS FA13SA7,
		(SELECT  
			(select stuff((select ',' +CAST(RollNo AS Varchar(200)) from  #TempAllExam  T 
		 		where  ED.ClassSubjectId=T.ClassSubjectId  AND ED.ExamId=T.ExamId and T.DivisionId=Dm.Id AND (Obtain1+Obtain2>=13 AND Obtain1+Obtain2<=16) AND (Obtain3>=13 and Obtain3<=18)
		 		 FOR XML Path('')),1,1,'')) 
		 ) AS FA13SA13,
		(SELECT  
			(select stuff((select ',' +CAST(RollNo AS Varchar(200)) from  #TempAllExam  T 
		 		where ED.ClassSubjectId=T.ClassSubjectId  AND ED.ExamId=T.ExamId and T.DivisionId=Dm.Id AND (Obtain1+Obtain2>=13 AND Obtain1+Obtain2<=16) AND (Obtain3>=19 and Obtain3<=24)
		 		 FOR XML Path('')),1,1,'')) 
		 ) AS FA13SA19,
		(SELECT  
			(select stuff((select ',' +CAST(RollNo AS Varchar(200)) from  #TempAllExam  T 
		 		where ED.ClassSubjectId=T.ClassSubjectId  AND ED.ExamId=T.ExamId and T.DivisionId=Dm.Id AND (Obtain1+Obtain2>=13 AND Obtain1+Obtain2<=16) AND (Obtain3>=25 and Obtain3<=30) 
		 		FOR XML Path('')),1,1,'')) 
		 ) AS FA13SA25,
		
		(SELECT  
			(select stuff((select ',' +CAST(RollNo AS Varchar(200)) from  #TempAllExam  T 
		 		where ED.ClassSubjectId=T.ClassSubjectId  AND ED.ExamId=T.ExamId and T.DivisionId=Dm.Id AND (Obtain1+Obtain2>=17 AND Obtain1+Obtain2<=20) AND (Obtain3>=0 and Obtain3<=6)
		 		 FOR XML Path('')),1,1,'')) 
		 ) AS FA17SA0, 
		(SELECT  
			(select stuff((select ',' +CAST(RollNo AS Varchar(200)) from  #TempAllExam  T 
		 		where  ED.ClassSubjectId=T.ClassSubjectId AND ED.ExamId=T.ExamId and T.DivisionId=Dm.Id AND (Obtain1+Obtain2>=17 AND Obtain1+Obtain2<=20) AND (Obtain3>=7 and Obtain3<=12)
		 		 FOR XML Path('')),1,1,'')) 
		 )AS FA17SA7,
		(SELECT  
			(select stuff((select ',' +CAST(RollNo AS Varchar(200)) from  #TempAllExam  T 
		 		where ED.ClassSubjectId=T.ClassSubjectId  AND ED.ExamId=T.ExamId  and T.DivisionId=Dm.Id AND (Obtain1+Obtain2>=17 AND Obtain1+Obtain2<=20) AND (Obtain3>=13 and Obtain3<=18)
		 		 FOR XML Path('')),1,1,'')) 
		 )AS FA17SA13,
		(SELECT  
			(select stuff((select ',' +CAST(RollNo AS Varchar(200)) from  #TempAllExam  T 
		 		where  ED.ClassSubjectId=T.ClassSubjectId and T.ExamId=Ed.ExamId and T.DivisionId=Dm.Id AND (Obtain1+Obtain2>=17 AND Obtain1+Obtain2<=20) AND 
		 			(Obtain3>=19 and Obtain3<=24) FOR XML Path('')),1,1,'')) 
		 ) AS FA17SA19,
		(SELECT  
			(select stuff((select ',' +CAST(RollNo AS Varchar(200)) from  #TempAllExam  T 
		 		where 
		 		ED.ClassSubjectId=T.ClassSubjectId AND  T.ExamId=Ed.ExamId and T.DivisionId=Dm.Id
		 	    AND (Obtain1+Obtain2>=17 
		 		AND Obtain1+Obtain2<=20) AND (Obtain3>=25 and Obtain3<=30) FOR XML Path('')),1,1,'')) 
		 ) AS FA17SA25
		
		
			 
	
 FROM  sAssessment.tExamMaster EM INNER JOIN sAssessment.tExamDetail ED ON EM.Id = ED.ExamId
 INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
 
 INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId	
 INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId=CS.ClassId
 WHERE EM.Id = @lExamId
 AND (CS.Id = @rSubjectId OR @rSubjectId=0)
 AND (DM.Id=@rDivisionId OR @rDivisionId=0) 
 
	 
		
	-- drop table #tempcombineExam
	-- Drop table #TempAllExam


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


GO


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

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

	  (select COUNT(RD.Id) from  sAssessment.tResultDetail RD INNER JOIN  sAssessment.tResult R ON RD.ResultId = R.Id  
	  INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	   INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
	  	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND CS.SubjectId=SM.Id AND RD.Obtain>=ED.Minimum AND ((A.StatusId=@rStatusId) OR (@rStatusId=0))) AS PassStudent,
  
	(select COUNT(RD.Id) from  sAssessment.tResultDetail RD 
	INNER JOIN  sAssessment.tResult R ON RD.ResultId = R.Id  
	INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	   INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
	  	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND 
	  EM.BatchId = @rBatchId AND CS.SubjectId=SM.Id AND RD.Obtain<ED.Minimum AND ((A.StatusId=@rStatusId) OR (@rStatusId=0))) AS FailStudent 
	  
	  
	 from
	 ssetup.tDivisionMaster DM
	 INNER JOIN sSetup.vBatchClass CM ON CM.ClassId = DM.ClassId
	INNER JOIN sSetup.tClassSubject CS ON CS.ClassId=CM.ClassId	
	INNER JOIN sSetup.tSubjectMaster   SM ON SM.Id = CS.SubjectId
	INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.ClassId

		WHERE 
			((DM.ID=@rDivisionId) or (@rDivisionId=0))
			AND ((Dm.ClassId=@rClassId) or (@rClassId=0))
			AND CM.BatchId=@rBatchId
			AND EM.ExamSubGroupId = @rExamSubGroupId
			AND EM.BatchId = @rBatchId
			AND (ISNULL(Dm.ClassId,0) IN( SELECT item FROM  sCommon.fnsplit(@rClass,','))OR @rClass='')
			AND (ISNULL(SM.Id,0) IN( SELECT item FROM  sCommon.fnsplit(@rSubject,','))OR @rSubject='')
	
  UNION ALL
  
  
  	 select 
		@rBuilder1 AS Builder1,
		DM.Classid As ClassId,
		Dm.id As DivisionId,
		Cm.ClassName As Classname,
		DM.DisplayTitle As DivisionName,
		0 AS ClassSubjectId,
		0 AS SubjectId,
		'Over All' AS SubjectName,
		0 As SubjectOrderIndex,
		0 AS DivisionOrderIndex,
		0 AS ClassOrderIndex,
	 

		(select COUNT(R.AcademicId) from   sAssessment.tResult R  INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 	    
	  	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId		 
		where 
		A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId  AND R.ResultStatus='PASS' AND ((A.StatusId=@rStatusId) OR (@rStatusId=0))) AS PassStudent,
	  
		(select COUNT(R.AcademicId) from   sAssessment.tResult R   INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 	    
	  	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId		 
		where 
		A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND R.ResultStatus='FAIL' AND ((A.StatusId=@rStatusId) OR (@rStatusId=0))) AS FailStudent 
	  
		 from
		 ssetup.tDivisionMaster DM
		 INNER JOIN sSetup.vBatchClass CM ON CM.ClassId = DM.ClassId
		 INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.ClassId
			WHERE 
				((DM.ID=@rDivisionId) or (@rDivisionId=0))
				AND ((Dm.ClassId=@rClassId) or (@rClassId=0))
				AND CM.BatchId=@rBatchId
				AND EM.ExamSubGroupId = @rExamSubGroupId
				AND EM.BatchId = @rBatchId
				 AND (ISNULL(Dm.ClassId,0) IN( SELECT item FROM  sCommon.fnsplit(@rClass,','))OR @rClass='')
	
END
GO
PRINT N'Altering [sAssessment].[pRptPassFailOverAllAnalysis]...';


GO


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

BEGIN 
--create table #Temphead
-- (Id Int Identity (1,1),
--  HEADID int,
--  PassStudent int,
--  FailStudent int
--  )
--  INSERT INTO #Temphead
--  (select COUNT(R.AcademicId) from   sAssessment.tResult R  INNER JOIN sStudent.tAcademic AC ON R.AcademicId = AC.Id 
--  	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
--  	  WHERE EM.ExamSubGroupId = @rExamSubGroupId 
--	  AND EM.BatchId = @rBatchId 
--	  AND AC.BatchId = @rBatchId 
--	  AND R.ResultStatus='PASS') AS PassStudent,
--	  (select COUNT(R.AcademicId) from   sAssessment.tResult R   INNER JOIN sStudent.tAcademic AC ON R.AcademicId = AC.Id 
--	  	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
--	  	 WHERE EM.ExamSubGroupId = @rExamSubGroupId 
--	  AND EM.BatchId = @rBatchId 
--	  AND AC.BatchId = @rBatchId 
--	  AND R.ResultStatus='FAIL' AND AC.BatchId = @rBatchId ) AS FailStudent
	  	
	  
		
--	FROM sAssessment.tResult R
--      INNER JOIN sStudent.tAcademic A  ON R.AcademicId = A.Id  INNER JOIN sAssessment.tExamMaster EM ON R.ExamId = EM.Id
--      INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
--      INNER JOIN sSetup.tDepartmentMaster Dept ON Dept.Id=CM.DepartmentId
--      WHERE (A.DivisionId=@rDivisionId OR @rDivisionId=0)
--		AND (A.ClassId=@rClassId OR @rClassId=0)
--		AND EM.BatchId=@rBatchId
--		AND EM.ExamSubGroupId =@rExamSubGroupId
--		GROUP BY CASE WHEN @rGroupByid=1 THEN A.DivisionId 
--		WHEN @rGroupByid=2 THEN A.ClassId
--		WHEN @rGroupByid =3 THEN Dept.Id
--		WHEN @rGroupByid =4 THEN A.OrgId 
--		ELSE 0 END 
 

  SELECT A.GroupId,A.Builder1,A.ClassId,A.DivisionId,A.Classname,A.DivisionName,A.DivisionOrderIndex,A.ClassOrderIndex,A.TotalPassStudent,A.TotalFailStudent,A.GroupName,A.GroupTitle,A.OrderIndex,
  
  (select COUNT(R.AcademicId) from   sAssessment.tResult R  
  
  INNER JOIN sStudent.vStudentAcademic AC ON R.AcademicId = AC.AcademicId 
  INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
  INNER JOIN sSetup.tClassMaster CM ON CM.Id = EM.ClassId
  INNER JOIN sSetup.tDepartmentMaster Dept ON Dept.Id=CM.DepartmentId

	  where
	
	 CASE WHEN @rGroupId = 4  THEN AC.OrgId
                 WHEN @rGroupId = 2 THEN AC.ClassId 
                  WHEN @rGroupId = 3 THEN Dept.Id 
                 ELSE AC.DivisionId 
            END = A.GroupId
         --AND
	
	   
	 --((@rGroupId = 3 AND AC.OrgId = A.GroupId)  OR (1 = 1) )
	 --AND ((@rGroupId = 2 AND AC.ClassId = A.GroupId) OR (1 = 1)    )
  --   AND ((@rGroupId = 1 AND AC.DivisionId = A.GroupId) OR (1 = 1) )
      

	  -------- AND ((A.GroupId = 1 AND AC.DivisionId = A.GroupId) OR 1 = 1)
	
	  
	  AND EM.ExamSubGroupId = @rExamSubGroupId 
	  AND EM.BatchId = @rBatchId 
	  AND AC.BatchId = @rBatchId 
	  AND R.ResultStatus='PASS'
	  AND ((AC.ClassId=@rClassId ) or (@rClassId=0))
	AND ((AC.DivisionId=@rDivisionId) or (@rDivisionId=0))
	  AND ((Ac.StatusId=@rStatusId) OR (@rStatusId=0)) 
	  	 
	  ) AS PassStudent,
	  
	  
	  (select COUNT(R.AcademicId) from   sAssessment.tResult R   INNER JOIN sStudent.vStudentAcademic AC ON R.AcademicId = AC.AcademicId
	  	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
	  	INNER JOIN sSetup.tClassMaster CM ON CM.ID = EM.ClassId
        INNER JOIN sSetup.tDepartmentMaster Dept ON Dept.Id=CM.DepartmentId
	   where  CASE WHEN @rGroupId = 4  THEN AC.OrgId
                 WHEN @rGroupId = 2 THEN AC.ClassId 
                  WHEN @rGroupId = 3 THEN Dept.Id 
                 ELSE AC.DivisionId 
            END = A.GroupId
	   AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND R.ResultStatus='FAIL' AND AC.BatchId = @rBatchId 
	     AND ((AC.ClassId=@rClassId ) or (@rClassId=0))
	       AND ((AC.DivisionId=@rDivisionId ) or (@rDivisionId=0))
	       AND ((Ac.StatusId=@rStatusId) OR (@rStatusId=0))
	   ) AS FailStudent
   FROM 
   (
	 select 
		@rBuilder1 AS Builder1,
		Cm.Classid As ClassId,
		Dm.id As DivisionId,
		Cm.ClassName As Classname,
		DM.DisplayTitle As DivisionName,
		 
		DM.OrderIndex AS DivisionOrderIndex,
		CM.OrderIndex AS ClassOrderIndex,
	 
 (select COUNT(R.AcademicId) from   sAssessment.tResult R  INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 	    
	  	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
	  			 
	  where 
	 A.ClassId = Cm.ClassId AND 
	 EM.ExamSubGroupId = @rExamSubGroupId 
	 AND EM.BatchId = @rBatchId  
	 AND R.ResultStatus='PASS'
	 AND ((A.StatusId=@rStatusId) OR (@rStatusId=0))
	 ) AS TotalPassStudent,
	  
  
  (select COUNT(R.AcademicId) from   sAssessment.tResult R   INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId
	    
	  	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
		 
	  where 
	  A.ClassId = CM.ClassId AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND R.ResultStatus='FAIL' AND ((A.StatusId=@rStatusId) OR (@rStatusId=0))) AS TotalFailStudent ,
	  
	  
	  
	--(select COUNT(R.AcademicId) from   sAssessment.tResult R   INNER JOIN sStudent.tAcademic A ON R.AcademicId = A.Id 
	    
	--  	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
		 
	--  where 
	--  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND R.ResultStatus='FAIL') AS FailStudent ,
	  CASE WHEN @rGroupId=1 THEN DM.Id 
				WHEN @rGroupId=2 THEN CM.ClassId 
				WHEN @rGroupId =3 THEN Dept.Id 
				WHEN @rGroupId =4 THEN OM.Id END AS GroupId,
				
			CASE WHEN @rGroupId=1 THEN CM.ClassName+'/'+DM.DisplayTitle
				WHEN @rGroupId=2 THEN CM.ClassName
				WHEN @rGroupId=3 THEN Dept.Title 
				WHEN @rGroupId=4 THEN OM.Title END AS GroupName,
				
			CASE WHEN @rGroupId=1 THEN DM.OrderIndex
				WHEN @rGroupId=2  THEN CM.OrderIndex
				WHEN @rGroupId=3  THEN Dept.Id
				WHEN @rGroupId=4 THen OM.OrderIndex  END AS OrderIndex,
				
			CASE WHEN @rGroupId=1 THEN 'Class/Division'
				WHEN @rGroupId=2  THEN 'Class'
				WHEN @rGroupId=3  THEN 'Department'
				WHEN @rGroupId=4 THen  'Organization'  END AS GroupTitle
				
	 from
	 ssetup.tDivisionMaster DM
	 INNER JOIN sSetup.vBatchClass CM ON CM.ClassId = DM.ClassId
INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.ClassId
INNER JOIN sSetup.tDepartmentMaster Dept ON Dept.Id=CM.DepartmentId
INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=Dept.OrgId
		WHERE 
			((DM.ID=@rDivisionId) or (@rDivisionId=0))
			AND ((Dm.ClassId=@rClassId ) or (@rClassId=0))
			AND CM.BatchId=@rBatchId
			AND EM.BatchId = @rBatchId
			AND EM.ExamSubGroupId = @rExamSubGroupId
				 AND (ISNULL(Dm.ClassId,0) IN( SELECT item FROM  sCommon.fnsplit(@rClass,','))OR @rClass='')
	) A
  
	
END
GO
PRINT N'Altering [sAssessment].[pRptResultListAnalysisGet]...';


GO


ALTER PROCEDURE [sAssessment].[pRptResultListAnalysisGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 --@rOrgId smallint,
	 @rBatchId int=0,
	 @rClassId int,
	 @rDivisionId int,
	 @rExamId int=0,
	 @rExamSubGroupId int=0,
	 @rCode nvarchar(20)='',
	 @rFromRollNo int=0,
	 @rToRollNo int=0,
	 @rFromRank int=0,
	 @rToRank int=0,
	 @rGrade nvarchar(20)='',
	 @rAcademicId bigint=0,
	 @rGroupId int=0,
	 @rClass nvarchar(MAX)='',
	 @rSubject nvarchar(max)='',
	 @rStatusId int =0
	 
	 
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

	SELECT  
	
			
			@rBuilder1 AS Builder1,
	 		A.RollNo,
	 		R.AcademicId,
			CM.DisplayTitle+'/'+DM.DisplayTitle AS Class,
			 DM.DisplayTitle AS Division,
			DM.Id AS DivisionId,
			DM.OrderIndex AS DivisinOrderIndex,
			R.TotalMarks,
			R.TotalObtain,
		 
			--CM.DisplayTitle AS Class,
			
			ED.ClassSubjectId AS ClassSubjectId,
			RD.Obtain AS SubjectObtain,
			Subj.Id AS SubjectId,
			 
			Subj.Code AS SubjectCode,
			
			Subj.Title AS SubjectName,
			BM.Title,
			BM.Id AS Batch,
			 Subj.OrderIndex AS SubjectOrderIndex,
			 BM.OrderIndex AS BatchOrderIndex,
			--CM.OrderIndex AS ClassOrderIndex ,
			RD.SubjectGrade,
			
			CASE WHEN @rGroupId=1 THEN DM.Id 
				WHEN @rGroupId=2 THEN CM.Id 
				WHEN @rGroupId =3 THEN Dept.Id 
				WHEn @rGroupId =4 THEN OM.Id END AS GroupId,
				
			CASE WHEN @rGroupId=1 THEN CM.DisplayTitle+'/'+DM.DisplayTitle
				WHEN @rGroupId=2 THEN CM.DisplayTitle
				WHEN @rGroupId=3 THEN Dept.Title 
				WHEN @rGroupId=4 THEN OM.Title END AS GroupName,
				
			CASE WHEN @rGroupId=1 THEN Dm.OrderIndex
				WHEN @rGroupId=2  THEN Cm.OrderIndex
				WHEN @rGroupId=3  THEN Dept.Id
				WHen @rGroupId=4 THen OM.OrderIndex  END AS OrderIndex,
				
			CASE WHEN @rGroupId=1 THEN 'Class/Division'
				WHEN @rGroupId=2  THEN 'Class'
				WHEN @rGroupId=3  THEN 'Department'
				WHen @rGroupId=4 THen  'Organization'  END AS GroupTitle,	
				
				Dept.Title AS DepartmentName,
				OM.Title AS OraganizationName
      
	FROM 
			
			sAssessment.tResultDetail RD 
			INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
			INNER JOIN sStudent.tAcademic A ON R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
			INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId			
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sSetup.tSubjectMaster Subj ON Subj.Id=CS.SubjectId			
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId			
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = EM.BatchId
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDivisionMaster DM ON A.DivisionId=DM.Id
			INNER JOIN sSetup.tDepartmentMaster Dept ON Dept.Id=CM.DepartmentId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=Dept.OrgId
			inner join sStudent.tStudentMaster STM ON STM.Id = A.StudentId 
			
			 
	WHERE 
			
		 ((EM.batchId = @rBatchId  ) OR (@rBatchId=0))
	    AND ((A.ClassId=@rClassId) OR (@rClassId=0)) 
		AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		 
		AND (( EM.ExamSubGroupId = @rExamSubGroupId )	OR (@rExamSubGroupId = 0))
		AND ((A.Id =@rAcademicId) OR (@rAcademicId=0))
		 AND (ISNULL(EM.ClassId,0) IN( SELECT item FROM  sCommon.fnsplit(@rClass,','))OR @rClass='')
		AND (ISNULL(Subj.Id,0) IN( SELECT item FROM  sCommon.fnsplit(@rSubject,','))OR @rSubject='')
		and((STM.StatusId=@rStatusId) or (@rStatusId=0))
		 
END
GO
PRINT N'Altering [sAssessment].[pRptResultStatistics]...';


GO


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

BEGIN 

	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			--ESGM.Title AS Exam,
			--StuM.Code,
			--StuM.FirstName+' '+StuM.LastName AS Name,
			--A.RollNo,
			--R.AcademicId,
			--RD.Obtain,
			--R.ResultStatus,
			CM.ClassName AS Class,
			CM.ClassId AS ClassId,
			CM.OrderIndex AS ClassOrderIndex,
			DM.DisplayTitle AS Division,
			DM.Id AS DivisionId,
			DM.OrderIndex AS DivisinOrderIndex,
			(SELECT COUNT(A.AcademicId) FROM sStudent.vStudentAcademic A WHERE A.DivisionId = DM.Id AND A.BatchId = @rBatchId AND ((A.StatusId=@rStatusId) or (@rStatusId=0))) AS TotalStudents,
			(SELECT COUNT(A.AcademicId) FROM sStudent.vStudentAcademic A INNER JOIN 
			 sAssessment.tResult R ON A.AcademicId = R.AcademicId  INNER JOIN 
			 sAssessment.tExamMaster E ON R.ExamId = E.Id 
			 WHERE A.DivisionId = DM.Id AND A.BatchId = @rBatchId AND E.ExamSubGroupId = @rExamSubGroupId AND ((A.StatusId=@rStatusId) or (@rStatusId=0))) AS AppearedStudents,
			 (SELECT COUNT(A.AcademicId) FROM sStudent.vStudentAcademic A INNER JOIN 
			 sAssessment.tResult R ON A.AcademicId = R.AcademicId  INNER JOIN 
			 sAssessment.tExamMaster E ON R.ExamId = E.Id 
			 WHERE A.DivisionId = DM.Id AND A.BatchId = @rBatchId AND E.ExamSubGroupId = @rExamSubGroupId AND R.ResultStatus = 'FAIL' AND ((A.StatusId=@rStatusId) or (@rStatusId=0))) AS FailedStudents,			 			 
			(SELECT COUNT(A.AcademicId) FROM sStudent.vStudentAcademic A INNER JOIN 
			 sAssessment.tResult R ON A.AcademicId = R.AcademicId  INNER JOIN 
			 sAssessment.tExamMaster E ON R.ExamId = E.Id 
			 WHERE A.DivisionId = DM.Id AND A.BatchId = @rBatchId AND E.ExamSubGroupId = @rExamSubGroupId AND R.ResultStatus = 'PASS' AND ((A.StatusId=@rStatusId) or (@rStatusId=0))) AS PassedStudents,			 	 
			'0' AS TotalResult,		 
			'0' AS ResultOnAppearedStudents,
			'0' AS GracedStudents,
			'0' AS RepeatorStudents
 
	FROM 
	
	sSetup.tDivisionMaster DM
	--INNER JOIN sSetup.tClassMaster CM ON CM.Id = DM.ClassId
	 INNER JOIN sSetup.vBatchClass CM ON CM.ClassId = DM.ClassId
	INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.ClassId
	
	WHERE 	
 
		((CM.ClassId=@rClassId) OR (@rClassId=0))		 
		AND ((DM.Id=@rDivisionId) OR (@rDivisionId=0))
		AND DM.OrgId = @rOrgId
		AND Cm.BatchId = @rBatchId
		AND EM.ExamSubGroupId =@rExamSubGroupId
		
		AND    (ISNULL(Cm.ClassId,0) IN( SELECT item FROM  sCommon.fnsplit(@rClass,','))OR @rClass='')
 
		
END
GO
PRINT N'Altering [sAssessment].[pRptResultWithAllSubjectListGet]...';


GO


ALTER PROCEDURE [sAssessment].[pRptResultWithAllSubjectListGet]
	 
   	 @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
	 
	
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			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.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
      
	FROM 
	
	sStudent.tAcademic A 
	INNER JOIN sAssessment.tResult R ON A.Id=R.AcademicId    
	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.tExamMaster EM ON EM.Id=R.ExamId AND	((EM.Id=@rExamId )	OR (@rExamId = 0))AND EM.BatchId = @rBatchId	
	INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId AND ((ESGM.Id = @rExamSubGroupId) OR (@rExamSubGroupId = 0))
	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 ED.Id=RD.ExamDetailId 
		AND ((SM.Id=@rSubjectId) OR (RD.ExamDetailId=@rSubjectId) OR (@rSubjectId=0)) 
		AND R.Id = RD.ResultId
	
			
	WHERE 
	     
	   --(CS.ClassId=@rClassId OR @rClassId=0) 
		 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 
		order by A.RollNo,CS.OrderIndex 

		
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
	 
	
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			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
      
	FROM 
			sAssessment.tResultDetail RD
			INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
			INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
			INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId	
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId		
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId					 
			INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
			INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
			INNER JOIN sSetup.tOrganizationMaster OM ON StuM.OrgId = OM.Id
			
		
			
	WHERE 
			
		EM.BatchId = @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 RD.IsPresent = 0
		order by A.RollNo,CS.OrderIndex 

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


GO


ALTER PROCEDURE [sAssessment].[pRptStudentAllBatchResultGet]
	 
	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='', 
    @rSubjectId int=0,
	--@rBatchId int,
	@rClassId int=0,
	@rDivisionId int=0,
	@rExamSubGroupId int=0,
	@rCode nvarchar(20)='',
	@rFromRollNo int=0,
	@rToRollNo int=0,
	@rFromRank int=0,
	@rToRank int=0,
	@rGrade nvarchar(20)='',
	@rFromPercentage decimal(5,2)=0,
	@rToPercentage decimal(5,2)=0,
@rExamSubGroup nvarchar(MAX)='',
 @rStatusId int = 0
	 
	
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
SELECT
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		--R.AcademicId,
		ESGM.Title AS ExamName,
		 [sStudent].[fStudentNameGet](StuM.FirstName , StuM.MiddleName, StuM.LastName,OM.StudentNameFormatId ) AS Name,
		StuM.Id AS StudentId,
		A.RollNo,
		CM.DisplayTitle AS Class,
		DM.DisplayTitle AS Division,
		CM.OrderIndex AS ClassOrderIndex,
		R.Percentage,
		StuM.Code,
	--	CM.Title AS ClassTitle,
	--	DM.Title AS DivisionTitle,
	--	a.CreatedDateTime,
		BM.Title AS BatchName,
		R.ResultGrade
		
	
FROM 
			sAssessment.tResult R 
			INNER JOIN sStudent.vStudentAcademic A ON A.AcademicId=R.AcademicId
			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 sAssessment.tExamMaster E ON R.ExamId = E.Id
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = E.ExamSubGroupId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
			INNER JOIN sSetup.tOrganizationMaster OM  ON StuM.OrgId = OM.Id
			
	WHERE 
	
	
			
	--	E.BatchId = @rBatchId 
		-- (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))
		 ((R.RankNumber >= @rFromRank) OR (@rFromRank=0))
		AND ((R.RankNumber <= @rToRank) OR (@rToRank=0))
		AND E.IsProcessResult = 1
		
		AND ((R.Percentage>=@rFromPercentage) OR(@rFromPercentage=0))
		AND((R.Percentage<=@rToPercentage)OR(@rToPercentage=0))
		----AND ((R.ResultGrade = @rGrade) OR (@rGrade=''))
		
		AND ((ESGM.Id = @rExamSubGroupId) OR (@rExamSubGroupId =0))
		
		
		
		AND ((StuM.Code=@rCode) OR (@rCode=''))
		AND (ISNULL(ESGM.Id,0) IN (Select item from sCommon.fnsplit(@rExamSubGroup,','))OR @rExamSubGroup='')
		 AND ((A.StatusId=@rStatusId) OR (@rStatusId=0))
	
	
		
END
GO
PRINT N'Altering [sAssessment].[pRptStudentAllExamResultGet]...';


GO


ALTER PROCEDURE [sAssessment].[pRptStudentAllExamResultGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rSubjectId int=0,
	 @rBatchId int,
	 @rClassId int=0,
	 @rDivisionId int=0,
	  @rExamId int=0,
	 @rExamSubGroupId int=0,
	 @rCode nvarchar(20)='',
	 @rFromRollNo int=0,
	 @rToRollNo int=0,
	 @rFromRank int=0,
	 @rToRank int=0,
	 @rGrade nvarchar(20)='',
	 @rFromPercentage decimal(5,2)=0,
	 @rToPercentage decimal(5,2)=0,
	 @rExamSubGroup nvarchar(MAX)='',
	 @rStatusId int = 0
	 
	
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
SELECT
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		R.AcademicId,
		ESGM.Title AS Exam,
		  [sStudent].[fStudentNameGet](StuM.FirstName , StuM.MiddleName, StuM.LastName,OM.StudentNameFormatId ) AS Name,
		A.RollNo,
		CM.DisplayTitle AS Class,
		DM.DisplayTitle AS Division,
		R.Percentage,
		StuM.Code,
		CM.Title,
		DM.Title
	
FROM 
			sAssessment.tResult R 
			INNER JOIN sStudent.vStudentAcademic A ON A.AcademicId=R.AcademicId
			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 sAssessment.tExamMaster E ON R.ExamId = E.Id
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = E.ExamSubGroupId
			INNER JOIN sSetup.tOrganizationMaster OM ON StuM.OrgId = OM.Id
			
	WHERE 
			
		E.BatchId = @rBatchId 
		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 E.IsProcessResult = 1
		
		AND ((R.Percentage >= @rFromPercentage) OR (@rFromPercentage=0))
		AND ((R.Percentage<=@rToPercentage) OR (@rToPercentage=0))
		--AND ((R.ResultGrade = @rGrade) OR (@rGrade=''))
		
		--AND ((R.ExamId = @rExamId) OR (@rExamId =0))
		AND ((ESGM.Id=@rExamSubGroupId) OR (@rExamSubGroupId=0))
		AND ((E.Id=@rExamId )	OR (@rExamId = 0))
		
		 AND (ISNULL(ESGM.Id,0) IN( SELECT item FROM  sCommon.fnsplit(@rExamSubGroup,','))OR @rExamSubGroup='')
		  AND ((A.StatusId=@rStatusId) OR (@rStatusId=0))
		order by ESGM.OrderIndex
		--AND ((StuM.Code=@rCode) OR (@rCode=''))
		
		--order by A.RollNo,CS.OrderIndex 
		--AND A.id = 1005000000007
		
END
GO
PRINT N'Altering [sAssessment].[pRptStudentGradeAnalysisGenderCatagoryWise]...';


GO



ALTER PROCEDURE [sAssessment].[pRptStudentGradeAnalysisGenderCatagoryWise]
	 
	  --@rAcademicId bigint=0,
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rBatchId int =0,
	 @rExamSubGroupId int=0,
	 @rBuilder1 nvarchar(max)='',
	 @rClass nvarchar(MAX)='',
	 @rStatusId int =0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 
		
	
	select 
	@rBuilder1 AS Builder1,
 
	
		 count(R.id),
		GM.Title AS Gender,
		R.ResultGrade,
		ISNULL(CCM.Title,'') AS CastCatagory,
		A.ClassId,
		A.DivisionId,
		CM.Title AS ClassName,
		DM.Title AS DivisionName
	 
		 
 from sAssessment.tResult  R
		INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
		INNER JOIN sStudent.tAcademic A ON R.AcademicId = A.Id 
		Inner join sSetup.tClassMaster CM ON CM.Id=A.ClassId
		INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
		INNER JOIN sStudent.tStudentMaster SM ON SM.Id = A.StudentId 
		INNER JOIN sStudent.tStudentOther SO ON SO.StudentId = A.StudentId 	
		INNER JOIN sCommon.tGenderMaster GM ON GM.Id=SO.GenderId
		LEFT  JOIN sCommon.tCastCategoryMaster CCM ON CCM.Id=SO.CastCategoryId
		
	where (A.ClassId=@rClassId OR @rClassId=0)
		AND (A.DivisionID=@rDivisionId Or @rDivisionId=0)
		and A.BatchId=@rBatchId
		and EM.ExamSubGroupId=@rExamSubGroupId
		AND    (ISNULL(A.ClassId,0) IN( SELECT item FROM  sCommon.fnsplit(@rClass,','))OR @rClass='')
		and ((sm.StatusId=@rStatusId) or (@rStatusId=0))

		 Group by R.ResultGrade, GM.Title,CCM.Title,A.ClassId,A.DivisionId,CM.Title,DM.Title 
		 
END
GO
PRINT N'Altering [sAssessment].[pRptStudentGradeAnalysisSubjectWise]...';


GO


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

BEGIN 
	 
		
	
	select 
		
		 count(RD.id),
		 
		@rBuilder1 AS Builder1,
		 
		RD.SubjectGrade,
		SM.Title AS SubjectName,
		CS.IsOptional ,
		DM.Id AS DivisionId,
		Dm.DisplayTitle as DivisionName,
		Cm.Id AS ClassId,
		CM.DisplayTitle AS ClassName,
		ISNULL(GD.MarkRange,'') AS MarkRange,
		SM.OrderIndex AS SubjectOrderIndex,
		GM.Title AS Gender,
		GM.Id AS GenderId,
		GD.GradeSetId,
		GD.Minimumscore
		 
		 
		 
 
		 
from sAssessment.tResultDetail  RD
   
		 Inner join sAssessment.tResult R ON R.Id=Rd.ResultId
		 INNER JOIN sStudent.tAcademic A ON R.AcademicId = A.Id 
		 	INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
		INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
		
		INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
		INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId 
		INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId 
		
		INNER JOIN sStudent.tStudentOther SO ON SO.StudentId = A.StudentId 	
		INNER JOIN sStudent.tStudentMaster STM ON STM.Id = A.StudentId 	
		INNER JOIN sCommon.tGenderMaster GM ON GM.Id=SO.GenderId
		
		LEFT JOIN  sAssessment.tGradeSetDetail GD ON
		GD.GradeSetId = ED.GradeSetId AND RD.SubjectGrade = GD.GradeCode
		 
		
	where 
		  EM.ExamSubGroupId=@rExamSubGroupId
		and EM.BatchId=@rBatchId
		and ((CM.Id=@rClassId)  OR (@rClassId=0))
		AND ((DM.ID=@rDivisionId) OR (@rDivisionId=0))
		  AND (ISNULL(Cm.Id,0) IN( SELECT item FROM  sCommon.fnsplit(@rClass,','))OR @rClass='')
		  and((STM.StatusId=@rStatusId) or (@rStatusId=0))
		 Group by RD.SubjectGrade,GD.MarkRange,SM.Title,CS.IsOptional ,DM.Id,DM.DisplayTitle,CM.Id,CM.DisplayTitle,SM.OrderIndex,GM.Title,GM.Id,GD.GradeSetId,GD.Minimumscore
	
END
GO
PRINT N'Altering [sAssessment].[pRptStudentWiseGradeList]...';


GO


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

BEGIN 
	 
		
	
	select 
		
		 count(RD.id),
		 
		@rBuilder1 AS Builder1,
		 
		RD.SubjectGrade,
		SM.Title AS SubjectName,
		CS.IsOptional ,
		DM.Id AS DivisionId,
		Dm.DisplayTitle as DivisionName,
		Cs.Id AS ClassId,
		CM.DisplayTitle AS ClassName,
		ISNULL(GD.MarkRange,'') AS MarkRange,
		SM.OrderIndex AS SubjectOrderIndex, 
		CM.OrderIndex AS ClassOrderIndex,
		(select count(A.Id) from sStudent.tAcademic A  
		
		INNER JOIN sAssessment.tResult R1 ON A.Id = R1.AcademicId 
	    INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R1.ExamId
		INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
		INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
		  
		where  A.BatchId =  @rBatchId AND  EM.ExamSubGroupId=@rExamSubGroupId
		and EM.BatchId=@rBatchId
		and (CM.Id=@rClassId OR @rClassId=0)
		AND (DM.ID=@rDivisionId OR @rDivisionId=0)
	 
		
		) AS DivisionCount
		 
		 
 
		 
from sAssessment.tResultDetail  RD
   
		 Inner join sAssessment.tResult R ON R.Id=Rd.ResultId
		 INNER JOIN sStudent.tAcademic A ON R.AcademicId = A.Id 
		 	INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
		INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
		
		
		INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
		INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId 
		INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId 
		inner join sStudent.tStudentMaster STM ON STM.Id = A.StudentId 	
		 
		LEFT JOIN  sAssessment.tGradeSetDetail GD ON
		GD.GradeSetId = ED.GradeSetId AND RD.SubjectGrade = GD.GradeCode
		 
		
	where 
		  EM.ExamSubGroupId=@rExamSubGroupId
		and EM.BatchId=@rBatchId
		and (CM.Id=@rClassId OR @rClassId=0)
		AND (DM.ID=@rDivisionId OR @rDivisionId=0)
		AND SM.Id=@rSubjectId
		  AND (ISNULL(Cm.Id,0) IN( SELECT item FROM  sCommon.fnsplit(@rClass,','))OR @rClass='')
		   and((STM.StatusId=@rStatusId) or (@rStatusId=0))
		 Group by RD.SubjectGrade,GD.MarkRange,SM.Title,CS.IsOptional ,DM.Id,DM.DisplayTitle,Cs.Id,CM.DisplayTitle,SM.OrderIndex,CM.OrderIndex 
	
END
GO
PRINT N'Altering [sAssessment].[pRptSubjectActivityExamDetailGet]...';


GO

ALTER PROCEDURE [sAssessment].[pRptSubjectActivityExamDetailGet]
	 
		@rOrgId int=0,
		@rExamId int=0,
		@rClass int=0,
		@rDivisionId int=0,
		@rBatchId int=0,
		@rBuilder1 nvarchar(max)='',
		@rAcademicId bigint=0,
		@rCode nvarchar(20)='',
		@rFromRollNo int=0,
		@rToRollNo int=0
	 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON 
BEGIN 	 
Declare @GradeString nvarchar(500),@GradeSetId int
SELECT @GradeSetId = GradesetId FROM sAssessment.tExamMaster WHERE Id = @rExamId
SELECT @GradeString = [sAssessment].[fGradeStringGet](@GradeSetId)

	SELECT 			 
			Convert(nvarchar(20),SA.AcademicId) AS AcademicIdText,	
			CONVERT (nvarchar(20),@rExamId) AS ExamIdText, 
			@rBuilder1 AS Builder1,
			SA.AcademicId,
			SA.RollNo,
			SA.Number,
			SA.Name,
			AIS.Grade,
			SAM.Title AS SubjectActivityTitle,
			SSA.Title AS SubjectSubActivityTitle,
			SAM.Id AS ActivityId,
			SSA.Id AS SubjectSubActivityId,
			SAM.OrderIndex AS ActivityOrderIndex,
			SSA.OrderIndex AS SubjectSubActivityOrderIndex ,
			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.IsDisplayGradeString,
			EM.IsDisplayParentName,
			SA.FirstName + ' ' +SA.MiddleName +' ' +SA.LastName AS Name,
			SO.DateOfBirth,
			CMM.Title AS ClassName,
			SA.code,
			SR.PresentDays,			
			SR.TotalDays,
			SR.StudentHeight,
			SR.StudentWeight,
			SF.FatherName,
			SF.MotherName,
			SAM.ClassSubjectId ,
			SM.Title AS SubjectName,
			SM.OrderIndex AS SubjectOrderIndex,
			CMM.DisplayTitle AS Class,
			DM.DisplayTitle AS Division,
			SR.ResultRemark1,
			SR.ResultRemark2,						 
			SI.StudentPhoto , 
			ISNULL(AIS.DescriptiveIndicator,'') AS DescriptiveIndicator,
			CASE WHEN CS.OrderIndex % 2 = 0 THEN 2 
			ELSE 1 END AS ColumnSubjectCount,
			CS.OrderIndex,
			EM.SubjectGroupPerPage,
			AIS.GradeIndicator,
			EM.IsCoScholasticGradeIndicator,
			EI.EmployeeSign,
			Em.IsDisplayPrincipalSign,
			EM.IsDisplayTeacherSign,
			EM.IsCoScholasticGradeDesIndicator,
			EM.IsCoScholasticGrade,
			Em.IsDisplayParentName,
			(CASE EM.IsDisplayImageHeader WHEN 1 THEN
			OI.CertificateHeaderA4 
			ELSE NULL END)AS MarksheetHeaderA4,
			ISNULL(EM.IsDisplayImageHeader,0) AS IsImageHeader,
			RD.Remark,
			SR.ClassTeacherRemark,
			SR.HouseRemark,
			HM.Title AS House,
			BM.Title AS BAtch ,
			[sAttendance].[fSubjectTeacherGet](SA.DivisionId,SM.ID) AS TEacherName,
			ED.IsShowSubjectGrade,
			@GradeString AS GradeString,
			Convert(nvarchar(20),ISNULL(Em.IsDisplayMonthlyAttendance,0)) As IsDisplayMonthlyAttendanceText,
			TeacherSignCaption,
			PrincipalSignCaption,
			ParentSignCaption,
			SR.ResultRemark3
			FROM 
			sAssessment.tCCESubjectActivityMaster SAM 	
			INNER JOIN sAssessment.tCCESubjectSubActivityMaster SSA ON SAM.Id=SSA.SubjectActivityId 
			INNER JOIN sAssessment.vCCEExamClassSubject CS ON CS.ClassSubjectId=SAM.ClassSubjectId
			INNER JOIN sSetup.tClassMaster CMM ON CMM.Id=CS.ClassId 
			INNER JOIN sStudent.vStudentAcademic SA ON SA.ClassId = CS.ClassId 
			INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=SA.StudentId			 
			LEFT JOIN sAssessment.tCCESubjectSubActivityExamScore AIS ON AIS.AcademicId =SA.AcademicId AND AIS.SubjectSubActivityId= SSA.Id 	
			LEFT JOIN sAssessment.tExamMaster EM ON EM.Id=AIS.ExamId
			LEFT JOIN sAssessment.tExamDetail ED ON EM.Id=ED.ExamId	AND ED.ClassSubjectId = CS.ClassSubjectId 		 
			LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=SA.StudentId
			LEFT JOIN sActivity.tHouseMaster HM ON HM.Id=SO.HouseId
			LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=SA.StudentId	
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId	
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=SA.divisionId
			LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = Dm.InchargeEmployeeId
			LEFT JOIN sAcademic.tTeacherSubjectDivision TSD ON TSD.DivisionId = DM.Id AND TSD.SubjectId = SM.Id 
			LEFT JOIN sHrm.tEmployeeMaster EMP ON EMP.Id = TSD.EmployeeId
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SA.StudentId
			LEFT JOIN sAssessment.tStudentRemark SR ON SA.AcademicId = SR.AcademicId	AND EM.Id = SR.ExamId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = Stum.OrgId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id= SA.BatchID
			LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = Om.Id
			LEFT JOIN sAssessment.tResultDetailOther RD ON RD.AcademicId = SA.AcademicId AND EM.ID=RD.ExamId AND CS.ClassSubjectId=RD.ClassSubjectID 
		WHERE
			((SA.AcademicId=@rAcademicId) OR(@rAcademicId=0))
			AND ((CS.ClassId=@rClass) OR (@rClass=0))
			And ((SA.DivisionId =@rDivisionId) or(@rDivisionId=0))	
			And ((SA.BatchId =@rBatchId) OR (@rBatchId=0))
			and ((SA.OrgId=@rOrgId) OR (@rOrgId=0))
			And AIS.ExamId=@rExamId
			AND ((STum.Code = @rCode) OR(@rCode=''))
			AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
			AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
			AND SA.StatusId = 1
		ORDER BY 
			SA.RollNo ASC,
			SAM.OrderIndex ASC,
			SSA.OrderIndex ASC;
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
	 
	
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

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

CREATE TABLE #TempExam
(
	SubExamId int, 
	ExamOrderIndex int,
	TermExamId int,
	AnnualExamId int, 
	Exam nvarchar(50) 
)
--INSERT INTO #TempExam
--(
--	SubExamId,	 
--	ExamOrderIndex,
--	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 

INSERT INTO #TempExam
(
	 SubExamId,
	 ExamOrderIndex,
	 TermExamId,
	 AnnualExamId,
	 Exam 
	
)
Select  
	EC.SubExamId,
	EC.ExamOrder,
	EC.ExamId AS TermExamId,
	@rExamId AS AnnualExamId,
	ES.Title AS Exam	
	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  )
	
	
 
		
	
	
	
--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
			
	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 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 
			
			--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))
		--order by A.RollNo,CS.OrderIndex 
		
	 drop table #TempExam
		
END
GO
PRINT N'Altering [sAssessment].[pRptWeekStudentAnalysisListGet]...';


GO


ALTER  PROCEDURE [sAssessment].[pRptWeekStudentAnalysisListGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
 
	 @rBatchId int,
	 @rClassId int,
	 @rDivisionId int,
	 
	 @rExamSubGroupId int=0,
	 @rCode nvarchar(20)='',
	 @rFromRollNo int=0,
	 @rToRollNo int=0,
	 --@rFromRank int=0,
	 --@rToRank int=0,
	 --@rGrade nvarchar(20)='',
	 --@rAcademicId bigint=0,
	 @rFromPercentage decimal(5,2)=0,
	 @rToPercentage decimal(5,2)=0,
	 @rGroupId int=0,
	 @rTop int=0,
	 @rClass nvarchar(MAX)='',
	  @rStatusId int = 0
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

SELECT r1.* from 
(
	SELECT 
	 
			 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
		 
			ROW_NUMBER() OVER(PARTITION BY 
							CASE WHEN @rGroupId=1 THEN DM.Id 
							WHEN @rGroupId=2 THEN CM.Id 
							WHEN @rGroupId =3 THEN Dept.Id 
							WHEn @rGroupId =4 THEN OM.Id END  
					 ORDER BY R.Percentage ASC) rn,
			
			ESGM.Title AS Exam,
			SM.Code,
			SM.FirstName + ' ' + SM.MiddleName + ' ' + SM.LastName  AS Name,
			
			A.RollNo,
			R.AcademicId,
			CM.DisplayTitle+'/'+DM.DisplayTitle AS Class,
			DM.DisplayTitle AS Division,
			DM.Id AS DivisionId,
			DM.OrderIndex AS DivisinOrderIndex,
			R.Percentage,
			EM.IsMarksInDecimal,
			
			CASE WHEN @rGroupId=1 THEN DM.Id 
				WHEN @rGroupId=2 THEN CM.Id 
				WHEN @rGroupId =3 THEN Dept.Id 
				WHEn @rGroupId =4 THEN OM.Id END AS GroupId,
				
			CASE WHEN @rGroupId=1 THEN CM.DisplayTitle+'/'+DM.DisplayTitle
				WHEN @rGroupId=2 THEN CM.DisplayTitle
				WHEN @rGroupId=3 THEN Dept.Title 
				WHEN @rGroupId=4 THEN OM.Title END AS GroupName,
				
			CASE WHEN @rGroupId=1 THEN Dm.OrderIndex
				WHEN @rGroupId=2  THEN Cm.OrderIndex
				WHEN @rGroupId=3  THEN Dept.Id
				WHen @rGroupId=4 THen OM.OrderIndex  END AS OrderIndex,
				
			CASE WHEN @rGroupId=1 THEN 'Class/Division'
				WHEN @rGroupId=2  THEN 'Class'
				WHEN @rGroupId=3  THEN 'Department'
				WHen @rGroupId=4 THen  'Organization'  END AS GroupTitle,
			R.TotalMarks,
			R.TotalObtain,
			R.ResultGrade 
			  
	FROM 
			sAssessment.tExamMaster EM
			INNER JOIN sAssessment.tResult R ON EM.Id=R.ExamId			
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId
			INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId=A.AcademicId
			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 A.DivisionId=DM.Id
			  INNER JOIN sSetup.tDepartmentMaster Dept ON Dept.Id=CM.DepartmentId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=Dept.OrgId
	WHERE 
			
		      EM.BatchId = @rBatchId 
		AND (A.ClassId=@rClassId OR @rClassId=0) 
		AND (A.DivisionId=@rDivisionId OR @rDivisionId=0)
		AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		 AND ((ESGM.Id=@rExamSubGroupId )	OR (@rExamSubGroupId = 0))
		AND ((SM.Code=@rCode) OR (@rCode=''))
		AND ((R.Percentage >=@rFromPercentage) OR (@rFromPercentage=0))
		AND ((R.Percentage <=@rToPercentage) OR (@rToPercentage=0))
		AND (ISNULL(A.ClassId,0) IN( SELECT item FROM  sCommon.fnsplit(@rClass,','))OR @rClass='')
		AND ((A.StatusId=@rStatusId) OR (@rStatusId=0))
		) r1
		
	WHERE ( r1.rn <= @rTop Or @rTop = 0)
END
GO
PRINT N'Altering [sAssessment].[pRptWeekStudentAnalysisListSubjectWiseGet]...';


GO


ALTER PROCEDURE [sAssessment].[pRptWeekStudentAnalysisListSubjectWiseGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
 
	 @rBatchId int,
	 @rClassId int,
	 @rDivisionId int,
	                           
	 @rExamSubGroupId int=0,
	 @rCode nvarchar(20)='',
	 @rFromRollNo int=0,
	 @rToRollNo int=0,
	 @rSubjectId int=0,
	 --@rFromPercentage decimal(5,2)=0,
	 --@rToPercentage decimal(5,2)=0,
	 @rGroupId int=0,
	 @rTop int=0,
	 @rClass nvarchar(max)='',
	 @rStatusId int = 0
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
SELECT r1.*
FROM
(	SELECT 	
			 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			
			ROW_NUMBER() OVER(PARTITION BY 
				CASE WHEN @rGroupId=1 THEN DM.Id 
				WHEN @rGroupId=2 THEN CM.Id 
				WHEN @rGroupId =3 THEN Dept.Id 
				WHEn @rGroupId =4 THEN OM.Id END  ORDER BY RD.Obtain ASC) rn,
			
			
			ESGM.Title AS Exam,
			SM.Code,
			SM.FirstName + ' ' + SM.MiddleName + ' ' + SM.LastName  AS Name,
			
			A.RollNo,
			R.AcademicId,
			CM.DisplayTitle+'/'+DM.DisplayTitle AS Class,
			DM.DisplayTitle AS Division,
			DM.Id AS DivisionId,
			DM.OrderIndex AS DivisinOrderIndex,
			R.Percentage,
			EM.IsMarksInDecimal,
			
			CASE WHEN @rGroupId=1 THEN DM.Id 
				WHEN @rGroupId=2 THEN CM.Id 
				WHEN @rGroupId =3 THEN Dept.Id 
				WHEn @rGroupId =4 THEN OM.Id END AS GroupId,
				
			CASE WHEN @rGroupId=1 THEN CM.DisplayTitle+'/'+DM.DisplayTitle
				WHEN @rGroupId=2 THEN CM.DisplayTitle
				WHEN @rGroupId=3 THEN Dept.Title 
				WHEN @rGroupId=4 THEN OM.Title END AS GroupName,
				
			CASE WHEN @rGroupId=1 THEN Dm.OrderIndex
				WHEN @rGroupId=2  THEN Cm.OrderIndex
				WHEN @rGroupId=3  THEN Dept.Id
				WHen @rGroupId=4 THen OM.OrderIndex  END AS OrderIndex,
				
			CASE WHEN @rGroupId=1 THEN 'Class/Division'
				WHEN @rGroupId=2  THEN 'Class'
				WHEN @rGroupId=3  THEN 'Department'
				WHen @rGroupId=4 THen  'Organization'  END AS GroupTitle,
			Sbj.Title AS SubjectName,
			Sbj.Id AS SubjectId,
			RD.Obtain ,
			R.TotalMarks,
			ED.Maximum,
			RD.SubjectGrade
			  
	FROM 
			sAssessment.tExamMaster EM
			INNER JOIN sAssessment.tResult R ON EM.Id=R.ExamId		
			INNER JOIN sAssessment.tResultDetail RD ON RD.ResultId =R.Id	
			INNER JOIN sAssessment.tExamDetail ED ON ED.Id = RD.ExamDetailId
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId
			INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId=A.AcademicId
			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 A.DivisionId=DM.Id
			  INNER JOIN sSetup.tDepartmentMaster Dept ON Dept.Id=CM.DepartmentId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=Dept.OrgId
			INNER JOIN sSetup.tClassSubject CS ON ED.ClassSubjectId = CS.Id 
			
			INNER JOIN sSetup.tSubjectMaster Sbj ON Sbj.Id  = CS.SubjectId
	WHERE 
			
		      EM.BatchId = @rBatchId 
		AND (A.ClassId=@rClassId OR @rClassId=0) 
		AND (A.DivisionId=@rDivisionId OR @rDivisionId=0)
		AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		 AND ((ESGM.Id=@rExamSubGroupId )	OR (@rExamSubGroupId = 0))
		AND ((SM.Code=@rCode) OR (@rCode=''))
		 AND Sbj.Id=@rSubjectId
		 AND (ISNULL(A.ClassId,0) IN( SELECT item FROM  sCommon.fnsplit(@rClass,','))OR @rClass='')
		 AND ((A.StatusId=@rStatusId) OR (@rStatusId=0))
		 	
	)r1
	WHERE (r1.rn <= @rTop Or @rTop = 0)
END
GO
PRINT N'Altering [sCertificate].[pRptFirstTrialCertificateGet]...';


GO
 


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

DECLARE @lIsDisplayImageHeader bit = 0

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

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

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

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


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

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

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


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


SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 178 AND SourceTypeId = 1016 AND SourceId = @rOrgId
	
	IF (@lConfigValue IS NULL) OR (@lConfigValue = 'Default')
	BEGIN
	SET @lIsOnPrePrinted = 0
	SET @lIsDisplayImageHeader = 0
	END
	ELSE IF (@lConfigValue = 'Blank')
	BEGIN
	SET @lIsOnPrePrinted = 1
	SET @lIsDisplayImageHeader = 0
	END
	ELSE IF (@lConfigValue = 'Image')
	BEGIN
	SET @lIsOnPrePrinted = 0
	SET @lIsDisplayImageHeader = 1
	END
	
	SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 157 AND SourceTypeId = 1016 AND SourceId = @rOrgId
	
	IF (@lConfigValue IS NULL) OR (@lConfigValue = 'False')
	SET @lIsDisplayReligion = 0
	ELSE
	SET @lIsDisplayReligion = 1
	
	
	
	--SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 158 AND SourceTypeId = 1016 AND SourceId = @rOrgId
	
	--IF (@lConfigValue IS NULL) OR (@lConfigValue = 'False')
	--SET @lIsDisplayImageHeader = 0
	--ELSE
	--SET @lIsDisplayImageHeader = 1	
	
	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			--MR.PresentCount AS PresentDays ,
			--MR.TotalCount AS TotalDays ,
			L.Id,
			--(SELECT SUM(MR.PresentCount) FROM sAttendance.tMonthlyRegister MR WHERE MR.AcademicId=A.Id) AS PresentDaysSum ,
			--(SELECT SUM(MR.TotalCount) FROM sAttendance.tMonthlyRegister MR WHERE MR.AcademicId=A.Id) AS TotalDaysSum ,
			SM.Code,
			L.AcademicId,
			SM.FirstName,SM.MiddleName,SM.LastName,
			[sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Name,
			ISNULL(SF.FatherName,'') As FatherName,
			ISNULL(SF.MotherName,'') As MotherName,
			ISNULL(CTM.Nationality,'') AS Nationality,
			--0 As CastCategoryId,
			--ISNULL(SO.CastCategoryId,0) As CastCategoryId,
			ISNULL(RM.Title,'') AS Religion,
			ISNULL(so.BirthPlace,'') AS BirthPlace,
			ISNULL(SO.BirthTaluka,'') AS BirthTaluka,
			ISNULL(SO.BirthDistrict,'') AS BirthDistrict,
			SO.DateOfBirth,
			ISNULL(SO.BirthDateInWord,'') AS BirthDateInWord,
			SA.PreviousSchool,
			SA.AdmissionDate,
			L.LCNumber,
			L.LeftDate,
			L.LCReason,
			L.LCProgress,
			L.LCConduct,
			L.LCRemark,
			L.LCDate,
			SO.GenderId,
			ISNULL(SO.FamilySubCast,'') AS SubCaste,
			ISNULL(SO.FamilyCast,'') AS Caste,
			ISNULL(OM.CityName,'') AS City,
			ISNULL(OM.StateName,'') AS CityState,
			CM.DisplayTitle AS AdmissionStandard,
			CMS.DisplayTitle AS CurrentStandard,
			CMS.Title AS CurrentStandardTitle,
			--'' AS CurrentStandardInWords,
			SM.StatusId,
			L.LastExamName AS Result,
			L.LastExamResult AS FailOrPass,
			L.SubjectStudied AS SubjectNAme,
			--ISNULL(SubM.Title,'') AS SubjectNAme,
			'' AS PromotedorNot,
			L.PromoteToClass  AS PromotedToClass,
			L.FeeDetail AS LastFeesPaid,
			L.FeeConcessionDetail AS AnyConcession,
			L.NCCScoutDetail  AS NCCScoutDetail,
			L.ExtraCurricularActivities AS GamesPlayed,
			OM.OrgLogo,
			OM.Title AS OrgTitle,
			OM.StreetOne+' '+OM.StreetTwo+' '+OM.StreetThree AS OrgAddress,
			OM.PhoneNo,
			vSA.RollNo,
			DM.OrderIndex AS DivisionOrder,
			OM.SmallAddress1,
			OM.SmallAddress2,
			OM.RegistrationDetail,
			@lIsOnPrePrinted AS IsOnPrePrinted,
			@lIsDisplayReligion AS IsDisplayReligion,
			AD.PresentDaysAnnual AS PresentDaysSum,
			AD.TotalDaysAnnual AS TotalDaysSum,
			vSA.ClassName AS ClassName,
			vSA.DivisionName AS DivisionName,
			@lIsDisplayImageHeader AS IsDisplayImageHeader,
			OI.CertificateHeaderA4  ,
			isnull(MainCastCategoryId,0) AS CastCategoryId,
			ISNULL(L.ToCollege,'') AS ToCollege ,
			ISNULL(L.ToCollegeAddress,'')AS ToCollegeAddress,
			ISNULL(OM.University,'')AS University,
			@lSchoolRemark1 AS SchoolRemark1 ,
			@lSchoolRemark2 AS SchoolRemark2 ,
			@lSchoolRemark3 AS SchoolRemark3 ,
			@lSchoolRequiredSignature AS SchoolRequiredSignature,
			ISNULL(CSG.Inword,'')AS CurrentStandardInWords,
			SO.MotherTongue,
			SO.AdhaarNumber,
			vSA.SUId,
			CASE WHEN isnull(BM.FromDate,'')>Isnull(SA.AdmissionDate,'') THEN BM.FromDate ELSE SA.AdmissionDate END AS BatchDate,
			SO.BirthState,
			SO.BirthCountry,
			SD.BankAccountNumber,
			SO.UIDNumber,
			SD.BankName,
			SD.BankIFSCCode,
			SA.PreviousStandard 
			,L.TermsInInstitute,
			@lIDConfigValue AS ItemValue 
			,L.LCCopy
		--sFinanceCommon.fNumberToWords(ISNULL(CM.ClassGroupId,0),'',OM.OrgGroupId) AS CurrentStandardInWords
		--CASE WHEN @rIsTransferCerti=1
		--THEN ISNULL(MR.PresentCount,0)
		--WHEN @rIsTransferCerti=0
		--THEN SUM(ISNULL(MR.PresentCount,0))
		--END AS Presentdays,
		--CASE WHEN @rIsTransferCerti=1
		--THEN ISNULL(MR.TotalCount,0)
		--WHEN @rIsTransferCerti=0
		--THEN SUM(ISNULL(MR.TotalCount,0))
		--END AS TotalCount
	FROM 
			sCertificate.tLeaving L
			INNER JOIN sStudent.vStudentAcademic vSA ON vSA.AcademicId=L.AcademicId
			--INNER JOIN sStudent.tAcademic A ON L.AcademicId=A.Id
			LEFT JOIN sStudent.tStudentAdmission SA ON SA.StudentId=vSA.StudentId
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=vSA.StudentId			
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=vSA.OrgId 
			LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=vSA.StudentId 
			LEFT JOIN sCommon.tReligionMaster RM ON SO.ReligionId=RM.Id
			--LEFT JOIN  sAttendance.tMonthlyRegister MR ON MR.AcademicId=A.Id 
			LEFT JOIN sSetup.tClassMaster CM ON CM.Id=SA.AdmissionStandardId
			INNER JOIN sSetup.tDivisionMaster DM ON vSA.DivisionId = DM.Id  
			INNER JOIN sSetup.tClassMaster CMS ON CMS.Id= DM.ClassId 
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId=vSA.StudentId
			LEFT JOIN sCommon.tCountryMaster CTM ON CTM.Id=SO.NationalityId
			LEFT JOIN sStudent.tAcademicDetail AD ON AD.AcademicId=vSA.AcademicId
			--LEFT JOIN sSetup.tClassSubject CS ON CS.ClassId=A.ClassId
			--LEFT JOIN sSetup.tSubjectMaster SubM ON SM.Id=CS.SubjectId
			LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = OM.Id
			LEFT JOIN sCommon.tCastCategoryMaster CSM ON CSM.Id=SO.CastCategoryId
			LEFT JOIN sSetup.tClassGroupMaster CSG ON CSG.Id=CMS.ClassGroupId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id=vSA.BatchId 
			--AND BM.OrgGroupBatchId=vSA.OrgGroupBatchId
			LEFT JOIN sStudent.tStudentAdditional SD ON SD.StudentId=vSA.StudentId

	WHERE 
				L.OrgId=@rOrgId
				AND	vSA.BatchId = @rBatchId 
				AND ((SM.Code = @rCode) OR (ISNULL(@rCode,'') = ''))
				AND ((SM.FirstName = @rName) OR (ISNULL(@rName,'') = ''))
				--AND ((L.LCNumber=@rNumber) OR (@rNumber=''))
				AND ((L.LCDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
				AND ((L.LCDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
				--AND ((L.LCDate=@rLCDate) OR (ISNULL(@rLCDate,'')=''))
				--AND ((L.LeftDate=@rLeftDate) OR (ISNULL(@rLeftDate,'')=''))
				--AND ((L.LCCopy=@rLCCopy) OR (@rLCCopy=0))
				--AND ((L.LCBookNumber=@rLCBookNumber) OR (@rLCBookNumber=''))
				AND ((vSA.ClassId=@rClassId) OR(@rClassId=0))
				AND ((vSA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
				AND ((L.LCNumber=@rLCNumber) OR (@rLCNumber=''))
				AND ((L.LCNumber >= @rFromNo) OR (@rFromNo=''))
				AND ((L.LCNumber <= @rToNo) OR (@rToNo=''))
				--group by MR.PresentCount,MR.TotalCount, SubM.Title, SM.Code,L.AcademicId,SM.FirstName,SM.LastName,SM.MiddleName,SF.FatherName,SF.MotherName,NM.Title,
				--SO.CastCategoryId,RM.Title,so.BirthPlace,SO.BirthTaluka,SO.BirthDistrict,SO.DateOfBirth,SO.BirthDateInWord,SA.PreviousSchool,
				--	SA.AdmissionDate,L.LeftDate,L.LCReason,L.LCProgress,L.LCConduct,L.LCRemark,L.LCDate,SO.GenderId,
				--	OM.CityName,OM.StateName,CM.DisplayTitle,CMS.DisplayTitle,SM.StatusId,OM.OrgLogo,OM.PhoneNo,OM.Title,OM.StreetOne,OM.StreetTwo,OM.StreetThree
END
GO
PRINT N'Altering [sCommon].[pOrgGroupSetupRemove]...';


GO

ALTER PROCEDURE [sCommon].[pOrgGroupSetupRemove]
	 
	 @rOrgGroupId smallint
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
    BEGIN TRY
	
	IF EXISTS(SELECT TOP 1 1 FROM sSetup.tOrganizationMaster WHERE OrgGroupId = @rOrgGroupId)
	BEGIN
	SELECT -101 AS Result
	RETURN
	END
	
	
	BEGIN TRANSACTION
	 
	EXEC sp_msforeachtable "ALTER TABLE ? NOCHECK CONSTRAINT all"
    




DELETE FROM sAccounting.tAccountingYearMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sAccounting.tAccountMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sAccounting.tLedgerGroupMaster  WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sAccounting.tLedgerMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sAccounting.tTransaction WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sAccounting.tTransactionDetail WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sActivity.tActivityTypeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sActivity.tClubMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sActivity.tImmunizationChart WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sAdmission.tInquiryReferenceMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sAttendance.tAbsentReasonMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCertificate.tLeavingConductMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCertificate.tLeavingProgressMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCertificate.tLeavingReasonMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCertificate.tLeavingRemarkMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tAreaMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tBirthPlaceMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tCityMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tCountryMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tDistrictMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tHobbyMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tHostelMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tMotherTongueMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tNationalityMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tOccupationMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tPreviousSchoolMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tReligionMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tStateMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tSurnameMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommunication.tBehaviourTypeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommunication.tBlog WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommunication.tBlogComment WHERE CAST(LEFT(BlogId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sCommunication.tBlogFavorite WHERE CAST(LEFT(BlogId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sCommunication.tBlogScope WHERE CAST(LEFT(BlogId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sCommunication.tCircular WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommunication.tCircularScope WHERE CAST(LEFT(CircularId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sCommunication.tCircularView WHERE CAST(LEFT(CircularId, 4) AS BIGINT) =@rOrgGroupId
DELETE FROM sCommunication.tNews WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommunication.tNewsComment WHERE CAST(LEFT(NewsId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sCommunication.tNewsScope WHERE CAST(LEFT(NewsId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sCommunication.tPhotoCategoryMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommunication.tPoll WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommunication.tPollAnswer WHERE CAST(LEFT(PollId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sCommunication.tPollMember WHERE CAST(LEFT(PollId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sCommunication.tPollResult WHERE CAST(LEFT(PollId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sCommunication.tQuery WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommunication.tQueryCategoryAssignedTo WHERE CAST(LEFT(QueryCategoryId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sCommunication.tQueryCategoryMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommunication.tQueryComment WHERE CAST(LEFT(QueryId, 4) AS BIGINT) =  @rOrgGroupId
DELETE FROM sEExam.tDataBankMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sEExam.tDataSubjectMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sEExam.tDataTopicMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sEExam.tDataTopicTypeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sEExam.tQuestionMaster WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sEExam.tQuestionOption WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sEExam.tQuestionParagraph WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sEExam.tTestTemplateMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sEExam.tTestTemplateQuestion WHERE CAST(LEFT(TestTemplateId, 4) AS INT) = @rOrgGroupId
DELETE FROM sFee.tChargeCategoryMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sFee.tChargeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sFee.tFeeHeadMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sFee.tFeeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sFee.tReceiptBookMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sFinanceCommon.tBankMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sFinanceCommon.tStockUomMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sGSEB.tActivityGroupMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sGSEB.tActivityIndicatorMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sGSEB.tActivityMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sHostel.tHostelMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sHostel.tRoomCategoryMaster WHERE CAST(LEFT(HostelId, 4) AS int) = @rOrgGroupId
DELETE FROM sHostel.tRoomMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sHrm.tQualificationMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sIp.tItemMainGroupMaster WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sIp.tItemSubGroupMaster WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sIp.tStockItemCategoryMaster WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sIp.tStockItemMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sIp.tStoreLocationMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sLibrary.tBookAgeGroupMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sLibrary.tBookAuthorMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sLibrary.tBookLanguageMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sLibrary.tBookLocationMaster WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sLibrary.tBookMaster WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sLibrary.tBookPublisherMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sLibrary.tBookSubjectMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sLibrary.tBookSupplierMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sLibrary.tBookTagMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sLibrary.tLibraryMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sPayroll.tEsiProcess WHERE CAST(LEFT(PayProcessElementId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sPayroll.tEsiSetup WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sPayroll.tPayElement WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sPayroll.tPayProcess WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sPayroll.tPayProcessElement WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sPayroll.tPayProcessEmployee WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sPayroll.tPaySetup WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sPayroll.tPaySetupDependent WHERE CAST(LEFT(PaySetupId, 4) AS INT) = @rOrgGroupId
DELETE FROM sPayroll.tPfProcess WHERE CAST(LEFT(PayProcessElementId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sPayroll.tPfProcessCharge WHERE CAST(LEFT(PayProcessElementId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sPayroll.tPfSetup WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sPayroll.tProfessionalTaxRange WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sProcurement.tVendorCategoryMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sProcurement.tVendorMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sSecurity.tModulePermission WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sSecurity.tOrganizationTask WHERE CAST(LEFT(OrgGroupId, 4) AS SMALLINT) = @rOrgGroupId
DELETE FROM sSecurity.tPermission WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sSecurity.tPermissionUser WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sSecurity.tRole WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId

 
DELETE FROM sStudent.tAdmissionCategoryMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sTax.tTaxGroupMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sTransport.tBusRouteDestinationMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sTransport.tBusRouteMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sTransport.tVehicleMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tFamiliyCastMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sFee.tDepositHeadMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sScholarship.tScholarshipTypeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sSetup.tOrgMainGroupMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sSetup.tOrgSubGroupMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sFee.tFeeMainGroupOrgGroupwise WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sHostel.tVisitorGatePass WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sFee.tChargeReceiptBookMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sPayroll.tPayrollGroupMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sPayroll.tPayrollMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sPayroll.tPayrollYearMaster WHERE OrgGroupId = @rOrgGroupId

DELETE FROM sActivity.tEventTypeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sSecurity.tRoleDashlet WHERE CAST(LEFT(RoleId, 4) AS INT) = @rOrgGroupId


DELETE FROM sCommon.tFrequencyMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tRangeDetail WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sCommon.tRangeMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sCommunication.tCircularTypeMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sFinanceCommon.tCurrencyMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sFrontOffice.tCourierDispatch WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sFrontOffice.tCourierReceive WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sHostel.tBuildingMaster WHERE CAST(LEFT(HostelId, 4) AS INT) = @rOrgGroupId
DELETE FROM sHostel.tChangeRoom WHERE CAST(LEFT(RoomId, 4) AS INT) = @rOrgGroupId
DELETE FROM sHostel.tHostelAdmission WHERE CAST(LEFT(Hosteld, 4) AS INT) = @rOrgGroupId

DELETE FROM sLibrary.tLibraryAttendance WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sLibrary.tMagazineMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sLibrary.tMagazineReceive WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sTransport.tExpenseTypeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sTransport.tFuelLogs WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sTransport.tFuelTypeMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sTransport.tVehicleDocumentMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId

DELETE FROM sStudent.tCustomTagMaster WHERE OrgGroupId = @rOrgGroupId

DELETE FROM sTransport.tVehicleDocuments WHERE CAST(LEFT(VehicleId, 4) AS INT) = @rOrgGroupId
DELETE FROM sTransport.tVehicleMaintenance WHERE CAST(LEFT(VehicleId, 4) AS INT) = @rOrgGroupId
DELETE FROM sTransport.tVehicleMaintenanceDetail WHERE CAST(LEFT(VehicleMaintenanceId, 4) AS INT) = @rOrgGroupId
DELETE FROM sTransport.tVehicleTypeMaster WHERE OrgGroupId = @rOrgGroupId

--DELETE FROM sTimetable.tAssignSchoolRoom WHERE CAST(LEFT(TimeTableSchemaId, 4) AS INT) = @rOrgGroupId
DELETE FROM sTimetable.tDivisionTimeOff WHERE CAST(LEFT(TimeTableSchemaId, 4) AS INT) = @rOrgGroupId
--DELETE FROM sTimetable.tSchoolBuildingMaster WHERE  OrgGroupId = @rOrgGroupId
--DELETE FROM sTimetable.tSchoolRoomMaster WHERE  CAST(LEFT(SchoolBuildingId, 4) AS INT) = @rOrgGroupId
--DELETE FROM sTimetable.tSchoolRoomTimeOff WHERE  CAST(LEFT(TimeTableSchemaId, 4) AS INT) = @rOrgGroupId
DELETE FROM sTimetable.tTeacherTimeOff WHERE  CAST(LEFT(TimeTableSchemaId, 4) AS INT) = @rOrgGroupId

DELETE FROM sCommunication.tEbook WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommunication.tEbookScope WHERE  CAST(LEFT(EbookId, 4) AS BIGINT) = @rOrgGroupId

DELETE FROM sActivity.tClubTypeMaster WHERE  OrgGroupId = @rOrgGroupId
DELETE FROM sActivity.tHouseGroupMaster WHERE  OrgGroupId = @rOrgGroupId
DELETE FROM sAdmission.tInquiryStatusMaster WHERE  OrgGroupId = @rOrgGroupId
DELETE FROM sCommunication.tCustomGroup WHERE  OrgGroupId = @rOrgGroupId
DELETE FROM sCommunication.tCustomGroupMember WHERE  CAST(LEFT(CustomGroupId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sTally.tFeeLedgerMapping WHERE CAST(LEFT(FeeId, 4) AS INT) = @rOrgGroupId
DELETE FROM sTally.tReceiptBookCompanyMapping WHERE CAST(LEFT(OrgGroupBatchId, 4) AS INT) = @rOrgGroupId
DELETE FROM sTally.tReceiptPosting WHERE CAST(LEFT(OrgGroupBatchId, 4) AS INT) = @rOrgGroupId
DELETE FROM sTimetable.tClassRoom WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sTimetable.tClassRoomTimeOff WHERE CAST(LEFT(ClassRoomId, 4) AS INT) = @rOrgGroupId
DELETE FROM sTimetable.tSchoolBuilding WHERE  OrgGroupId = @rOrgGroupId
 DELETE FROM sCommon.tCastCategoryMaster WHERE  OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tQuotaMaster WHERE  OrgGroupId = @rOrgGroupId
DELETE FROM sTransport.tTransportMaster WHERE  OrgGroupId = @rOrgGroupId

DELETE FROM sAlert.tOtherGroupDetail WHERE  CAST(LEFT(OtherGroupId, 4) AS INT) = @rOrgGroupId
DELETE FROM sAlert.tOtherGroupMaster WHERE  OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tAdmissionQuotaMaster WHERE  OrgGroupId = @rOrgGroupId
DELETE FROM sFee.tCollectionGroupMaster WHERE  CAST(LEFT(OrgGroupBatchId, 4) AS INT) = @rOrgGroupId

DELETE FROM sHrm.tWorkAreaMaster WHERE  OrgGroupId = @rOrgGroupId
DELETE FROM sIp.tUniformItem WHERE  OrgGroupId = @rOrgGroupId
DELETE FROM sIp.tUniformItemSize WHERE  CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sSetup.tShiftMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sTimetable.tAssignClassRoom WHERE CAST(LEFT(ClassRoomId, 4) AS INT) = @rOrgGroupId
DELETE FROM sIp.tUniformStock WHERE  CAST(LEFT(UniformSizeId, 4) AS INT) = @rOrgGroupId

DELETE FROM sSetup.tShiftMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sTimetable.tAssignClassRoom WHERE CAST(LEFT(ClassRoomId, 4) AS INT) = @rOrgGroupId
DELETE FROM sCommon.tReportOrgGroup WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sFee.tExemptionTypeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sOp.tGatewayConfiguration WHERE OrgGroupId = @rOrgGroupId
DELETE FROM  sTimetable.tDivisionClassRoom WHERE CAST(LEFT(TimeTableSchemaId, 4) AS INT) = @rOrgGroupId
DELETE FROM  sTimetable.tSubjectClassRoom WHERE CAST(LEFT(TimeTableSchemaId, 4) AS INT) = @rOrgGroupId
DELETE FROM  sTimetable.tTimeTableDetail WHERE CAST(LEFT(TimetableId, 4) AS INT) = @rOrgGroupId
DELETE FROM sFee.tExemptionTypeDetail WHERE CAST(LEFT(ExemptionTypeId, 4) AS INT) = @rOrgGroupId
DELETE FROM sSecurity.tRoleModulePermission WHERE CAST(LEFT(RoleId, 4) AS INT) = @rOrgGroupId

/* -- Date : 13/06/2016 -- */
DELETE FROM sAlert.tNotificationLog WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sAlert.tNotificationLog WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sCanteen.tCanteenIssueDetail WHERE CAST(LEFT(CanteenIssueId, 4) AS INT) = @rOrgGroupId
DELETE FROM sCanteen.tCanteenMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCanteen.tFoodItemMaster WHERE CAST(LEFT(CanteenId, 4) AS INT) = @rOrgGroupId
DELETE FROM sFrontOffice.tLostFoundRegister WHERE OrgGroupId = @rOrgGroupId

DELETE FROM sHostel.tAssetTypeMaster WHERE CAST(LEFT(HostelId, 4) AS INT) = @rOrgGroupId
DELETE FROM sHostel.tAssignRoomAsset WHERE CAST(LEFT(HostelId, 4) AS INT) = @rOrgGroupId
DELETE FROM sHostel.tRoomAssetMaster WHERE CAST(LEFT(HostelId, 4) AS INT) = @rOrgGroupId
DELETE FROM sHrm.tLeaveReasonMaster WHERE OrgGroupId = @rOrgGroupId

DELETE FROM sSetup.tOrgGroupSetting WHERE OrgGroupId = @rOrgGroupId
 
DELETE FROM sStudent.tSUIdConfig WHERE OrgGroupId = @rOrgGroupId

DELETE FROM sTimetable.tAssignDivision WHERE CAST(LEFT(TimeTableSchemaId, 4) AS INT) = @rOrgGroupId

/* -- Date : 12/08/2016 -- */
DELETE FROM sHostel.tHostelDepositAdd WHERE CAST(LEFT(HostelId, 4) AS INT) = @rOrgGroupId
DELETE FROM sHostel.tHostelDepositAdjustment WHERE CAST(LEFT(HostelId, 4) AS INT) = @rOrgGroupId
DELETE FROM sHostel.tHostelDepositHeadMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sHostel.tHostelDepositRefund WHERE CAST(LEFT(HostelId, 4) AS INT) = @rOrgGroupId
DELETE FROM sSystem.tExceptionLog WHERE OrgGroupId = @rOrgGroupId

/* -- Date : 17/09/2016 -- */
DELETE FROM sCommon.tReportClient WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommunication.tTempCircularScope WHERE CAST(LEFT(TempCircularId, 4) AS BIGINT) = @rOrgGroupId

DELETE FROM sErp.tCustomerMaster WHERE OrgGroupId = @rOrgGroupId

/* -- Date : 05/10/2016 -- */
DELETE FROM sHostel.tAttendanceRegister WHERE CAST(LEFT(HostelId, 4) AS INT) = @rOrgGroupId
DELETE FROM sRecruitment.tCandidateCommunications WHERE CAST(LEFT(CandidateId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sRecruitment.tCandidateImages WHERE CAST(LEFT(CandidateId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sRecruitment.tCandidateMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sRecruitment.tCandidatePreviousEmployment WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sRecruitment.tCandidateQualification WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sRecruitment.tCandidateVacancyCriteriaScore WHERE CAST(LEFT(CandidateId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sRecruitment.tInterviewCriteria WHERE CAST(LEFT(VacancyId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sRecruitment.tRecruitmentStatusLog WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sRecruitment.tVacancy WHERE OrgGroupId = @rOrgGroupId

/* -- Date : 24/11/2016 -- */

DELETE FROM siTax.tAssessmentYear WHERE OrgGroupId = @rOrgGroupId
DELETE FROM siTax.tForm16 WHERE OrgGroupId = @rOrgGroupId
DELETE FROM siTax.tForm16Detail WHERE CAST(LEFT(Form16Id, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM siTax.tIncomeTaxChallan WHERE CAST(LEFT(AssesmentYearId, 4) AS INT) = @rOrgGroupId
DELETE FROM siTax.tIncomeTaxGroup WHERE OrgGroupId = @rOrgGroupId
DELETE FROM siTax.tIncomeTaxSlab WHERE OrgGroupId = @rOrgGroupId
DELETE FROM siTax.tIncomeTaxSubGroup WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sSetup.tBatchGroupMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sActivity.tPlacementCompanyMaster WHERE OrgGroupId = @rOrgGroupId


DELETE FROM sAppraisal.tConductTypeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sErp.tCustomerActivationLog WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sSecurity.tIpPolicy WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sSecurity.tIpPolicyDetail WHERE  CAST(LEFT(IpPolicyId, 4) AS int) = @rOrgGroupId
DELETE FROM sSecurity.tTimePolicy WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sSecurity.tUserPolicy WHERE  CAST(LEFT(TimePolicyId, 4) AS int) = @rOrgGroupId


DELETE FROM sAppraisal.tKPATemplateDetail WHERE CAST(LEFT(KPATemplateId, 4) AS int) = @rOrgGroupId
DELETE FROM sAppraisal.tKPATemplateMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sOp.tGatewayProduct WHERE CAST(LEFT(GatewayConfigurationId, 4) AS int) = @rOrgGroupId
DELETE FROM sOp.tGatewayProductReceiptBookMapping WHERE CAST(LEFT(ReceiptBookId, 4) AS int) = @rOrgGroupId
DELETE FROM sProcurement.tSstockIssueTypeMaster WHERE OrgGroupId = @rOrgGroupId

DELETE FROM sFee.tFeeDepositExpenseTypeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sHostel.tHostelAttendanceTypeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sHostel.tHostelExpenseSubTypeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sHostel.tHostelExpenseTypeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sHostel.tHostelGatePassReasonMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sIp.tUniformOrderItem WHERE CAST(LEFT(StockItemId, 4) AS int) = @rOrgGroupId
DELETE FROM sProcurement.tStockIssueReturn WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sProcurement.tStockIssueReturnBatch WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sStudent.tStudentGroupMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sStudent.tStudentOtherGroupMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sStudent.tStudentUIdMaster WHERE OrgGroupId = @rOrgGroupId


DELETE FROM sAssetManagement.tAssetCheck WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sAssetManagement.tAssetInchargeUser WHERE CAST(LEFT(AssetId, 4) AS int) = @rOrgGroupId
DELETE FROM sCanteen.tBreakTypeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCanteen.tDailyMenu WHERE CAST(LEFT(CanteenId, 4) AS int) = @rOrgGroupId

DELETE FROM sAlert.tAdVendorMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sFee.tChargeAccountMapping WHERE CAST(LEFT(ChargeId, 4) AS int) = @rOrgGroupId
DELETE FROM sFee.tChargeAccountPosting WHERE CAST(LEFT(ReceiptBookId, 4) AS int) = @rOrgGroupId
DELETE FROM sFee.tDepositeAccountMapping WHERE CAST(LEFT(DepositeHeadId, 4) AS int) = @rOrgGroupId
DELETE FROM sFee.tDepositeAccountPosting WHERE CAST(LEFT(DepositeHeadId, 4) AS int) = @rOrgGroupId

DELETE FROM sCommunication.tFeedback WHERE CAST(LEFT(OrgGroupBatchId, 4) AS int) = @rOrgGroupId
DELETE FROM sCommunication.tFeedbackAnswerTypeDetail WHERE CAST(LEFT(FeedbackAnswerTypeId, 4) AS int) = @rOrgGroupId
DELETE FROM sCommunication.tFeedbackAnswerTypeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommunication.tFeedbackAssign WHERE CAST(LEFT(FeedbackId, 4) AS bigint) = @rOrgGroupId
DELETE FROM sCommunication.tFeedbackFor WHERE CAST(LEFT(FeedbackId, 4) AS bigint) = @rOrgGroupId
DELETE FROM sCommunication.tFeedbackQuestionResponse WHERE CAST(LEFT(FeedbackResponseId, 4) AS bigint) = @rOrgGroupId
DELETE FROM sCommunication.tFeedbackResponse WHERE CAST(LEFT(Id, 4) AS bigint) = @rOrgGroupId
DELETE FROM sCommunication.tFeedbackTemplate WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommunication.tFeedbackTemplateQuestion WHERE CAST(LEFT(FeedbackTemplateId, 4) AS bigint) = @rOrgGroupId
DELETE FROM sProcurement.tStockReset WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sProcurement.tStockResetBatch WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sSystem.tBackupLog WHERE CAST(LEFT(CreatedUserId, 4) AS bigint) = @rOrgGroupId
DELETE FROM sSystem.tPortalSync WHERE OrgGroupId = @rOrgGroupId

DELETE FROM sAccounting.tBudget WHERE CAST(LEFT(LedgerId, 4) AS int) = @rOrgGroupId
DELETE FROM sAccounting.tTransactionApprove WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sAccounting.tTransactionApproveDetail WHERE CAST(LEFT(LedgerId, 4) AS bigint) = @rOrgGroupId
DELETE FROM sSetup.tScreenMandatoryFeild WHERE OrgGroupId = @rOrgGroupId


DELETE FROM sCommunication.tPhotoCategoryScope WHERE CAST(LEFT(PhotoCategoryId, 4) AS int) = @rOrgGroupId
DELETE FROM sTool.tTestCase WHERE CAST(LEFT(Id, 4) AS int) = @rOrgGroupId

DELETE FROM sLibrary.tMagazineTypeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sSecurity.tOrgGroupMobileAppDetail WHERE OrgGroupId = @rOrgGroupId



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

	-- special case will come orgwise and orggroupwise

DELETE FROM sCommon.tTableRowId WHERE OrgId = @rOrgGroupId 
DELETE FROM sConfig.tConfigurationSetup WHERE SourceTypeId = 2010 AND SourceId = @rOrgGroupId
DELETE FROM sSetup.tOrgGroupBatchMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sSetup.tOrgGroupMaster WHERE Id=@rOrgGroupId


DELETE FROM sCanteen.tGuestRequest WHERE CAST(LEFT(CanteenId, 4) AS int) = @rOrgGroupId
DELETE FROM sSecurity.tPermissionUser WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sSystem.tLimitLog WHERE OrgGroupId = @rOrgGroupId
	
EXEC sp_msforeachtable "ALTER TABLE ? WITH CHECK CHECK CONSTRAINT all"

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


GO
ALTER PROCEDURE [sCommunication].[pQueryQueueGet]
	 
	 @rQueryCategoryId int = 0,
	 --@rCreatedUserId bigint,
	 @rOrgGroupBatchId int,
	 @rOrgGroupId smallint,
	 @rQueryId bigint,
	 @rUserSourceId bigint,
	 @rMyList bit,
	 @rStatusId int = 0,
	 @rSourceId bigint = 0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
		
BEGIN 
IF(@rMyList=0)
BEGIN
	SELECT 
			QCM.Id AS QueryCategoryId,
			ISNULL(QCM.Title,'') AS QueryCategoryMaster,
			QM.Title,
			QM.Remark,
			QM.CreatedDateTime,
			QM.StatusId,
			ISNULL(sm.Title,'') AS StatusMaster,
			QM.Id AS QueryId,
			QM.IsUserView,
			QM.IsAssigneeView,
			ODM.Title AS Department,
			U.DisplayTitle AS SourceName, 
			U.SourceTypeId, 
			'Employee' AS SourceType,
			QM.CreatedUserId AS QueryCreatedUserId,
			OM.DisplayTitle AS OrgName,
			EM.Code AS Code,
			(SELECT TOP 1 U.DisplayTitle AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND  QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserName,
			(SELECT TOP 1 CONVERT(NVARCHAR,QC.CreatedDateTime,103) AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserDate
	FROM 
			sCommunication.tQuery QM
		INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QM.QueryCategoryId=QCM.Id
        INNER JOIN sCommon.tStatusMaster SM ON SM.Id=QM.StatusId
        INNER JOIN sSecurity.tUser U ON U.Id=QM.CreatedUserId
        INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = U.SourceId AND U.SourceTypeId = 95
        INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = U.SourceId AND U.SourceTypeId = 95
        INNER JOIN sSetup.tDepartmentMaster ODM ON EJD.OrganizationDepartmentId=ODM.Id  
        INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = ODM.OrgId
        
	WHERE 
  
			((QCM.Id = @rQueryCategoryId) OR (@rQueryCategoryId = 0))
		AND ((QM.Id = @rQueryId) OR (@rQueryId = 0)) 
		AND (QCM.OrgGroupId = @rOrgGroupId) 
		AND (QM.OrgGroupBatchId = @rOrgGroupBatchId)
	    AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))
	    AND ((EJD.EmployeeId=@rSourceId) OR (@rSourceId=0))
	UNION 

	SELECT 
			QCM.Id AS QueryCategoryId,
			ISNULL(QCM.Title,'') AS QueryCategoryMaster,
			QM.Title,
			QM.Remark,
			QM.CreatedDateTime,
			QM.StatusId,
			ISNULL(sm.Title,'') AS StatusMaster,
			QM.Id AS QueryId,
			QM.IsUserView,
			QM.IsAssigneeView,
			SA.ClassName + ' ' + SA.DivisionName  AS Department,
			U.DisplayTitle AS SourceName,
			U.SourceTypeId,
			'Student' AS SourceType,
			QM.CreatedUserId AS QueryCreatedUserId,
			OM.DisplayTitle AS OrgName,
			SA.Code,
			(SELECT TOP 1 U.DisplayTitle AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND  QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserName,
			(SELECT TOP 1 CONVERT(NVARCHAR,QC.CreatedDateTime,103) AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserDate
			
	FROM 
			sCommunication.tQuery QM
        INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QM.QueryCategoryId=QCM.Id
        INNER JOIN sCommon.tStatusMaster SM ON SM.Id=QM.StatusId
        INNER JOIN sSecurity.tUser U ON U.Id=QM.CreatedUserId
        INNER JOIN sStudent.vStudentAcademic SA ON SA.StudentId = U.SourceId AND U.SourceTypeId = 2003 AND SA.OrgGroupBatchId = @rOrgGroupBatchId
        INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
	WHERE 
			((QCM.Id = @rQueryCategoryId) OR (@rQueryCategoryId = 0))
		AND ((QM.Id = @rQueryId) OR (@rQueryId = 0)) 
		AND (QCM.OrgGroupId=@rOrgGroupId)  
		AND (QM.OrgGroupBatchId=@rOrgGroupBatchId)
		AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))
		AND ((SA.StudentId=@rSourceId) OR (@rSourceId=0))
END
ELSE IF(@rMyList=1)
BEGIN

	SELECT 
			QCM.Id AS QueryCategoryId,
			ISNULL(QCM.Title,'') AS QueryCategoryMaster,
			QM.Title,
			QM.Remark,
			QM.CreatedDateTime,
			QM.StatusId,
			ISNULL(sm.Title,'') AS StatusMaster,
			QM.Id AS QueryId,
			QM.IsUserView,
			QM.IsAssigneeView,
			ODM.Title AS Department,
			U.DisplayTitle AS SourceName, 
			U.SourceTypeId, 
			'Employee' AS SourceType,
			QM.CreatedUserId AS QueryCreatedUserId,
			OM.DisplayTitle AS OrgName,
			EM.Code,
			(SELECT TOP 1 U.DisplayTitle AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND  QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserName,
			(SELECT TOP 1 CONVERT(NVARCHAR,QC.CreatedDateTime,103) AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserDate
			
	FROM 
			sCommunication.tQuery QM
		INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QM.QueryCategoryId=QCM.Id
        INNER JOIN sCommon.tStatusMaster SM ON SM.Id=QM.StatusId
        INNER JOIN sSecurity.tUser U ON U.Id=QM.CreatedUserId
        INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = U.SourceId AND U.SourceTypeId = 95
        INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = U.SourceId AND U.SourceTypeId = 95
        INNER JOIN sSetup.tDepartmentMaster ODM ON EJD.OrganizationDepartmentId=ODM.Id 
        INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = ODM.OrgId
	WHERE 
			((QCM.Id = @rQueryCategoryId) OR (@rQueryCategoryId = 0))
		AND ((QM.Id = @rQueryId) OR (@rQueryId = 0)) 
		AND (QCM.OrgGroupId = @rOrgGroupId)
		AND (QM.OrgGroupBatchId = @rOrgGroupBatchId)
	    AND QueryCategoryId IN (select QueryCategoryId FROM sCommunication.tQueryCategoryAssignedTo where  SourceId = @rUserSourceId)
	    AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))
	    AND (( EJD.EmployeeId=@rSourceId) OR (@rSourceId=0))
	UNION 

	SELECT 
			QCM.Id AS QueryCategoryId,
			ISNULL(QCM.Title,'') AS QueryCategoryMaster,
			QM.Title,
			QM.Remark,
			QM.CreatedDateTime,
			QM.StatusId,
			ISNULL(sm.Title,'') AS StatusMaster,
			QM.Id AS QueryId,
			QM.IsUserView,
			QM.IsAssigneeView,
			SA.ClassName + ' ' + SA.DivisionName  AS Department,
			U.DisplayTitle AS SourceName,
			U.SourceTypeId,
			'Student' AS SourceType,
			QM.CreatedUserId AS QueryCreatedUserId,
			OM.DisplayTitle AS OrgName,
			SA.Code,
			(SELECT TOP 1 U.DisplayTitle AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND  QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserName,
			(SELECT TOP 1 CONVERT(NVARCHAR,QC.CreatedDateTime,103) AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserDate
			
	FROM 
		sCommunication.tQuery QM
        INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QM.QueryCategoryId=QCM.Id
        INNER JOIN sCommon.tStatusMaster SM ON SM.Id=QM.StatusId
        INNER JOIN sSecurity.tUser U ON U.Id=QM.CreatedUserId
        INNER JOIN sStudent.vStudentAcademic SA ON SA.StudentId = U.SourceId AND U.SourceTypeId = 2003 AND SA.OrgGroupBatchId = @rOrgGroupBatchId
        INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
	WHERE 
			((QCM.Id = @rQueryCategoryId) OR (@rQueryCategoryId = 0))
		AND ((QM.Id = @rQueryId) OR (@rQueryId = 0)) 
		AND (QCM.OrgGroupId=@rOrgGroupId)  
		AND (QM.OrgGroupBatchId=@rOrgGroupBatchId)
		AND QueryCategoryId IN (select QueryCategoryId FROM sCommunication.tQueryCategoryAssignedTo where  SourceId = @rUserSourceId AND SourceTypeId <> 2015)
		AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))
		AND ((SA.StudentId=@rSourceId) OR (@rSourceId=0))
	UNION 

	SELECT 
			QCM.Id AS QueryCategoryId,
			ISNULL(QCM.Title,'') AS QueryCategoryMaster,
			QM.Title,
			QM.Remark,
			QM.CreatedDateTime,
			QM.StatusId,
			ISNULL(sm.Title,'') AS StatusMaster,
			QM.Id AS QueryId,
			QM.IsUserView,
			QM.IsAssigneeView,
			SA.ClassName + ' ' + SA.DivisionName  AS Department,
			U.DisplayTitle AS SourceName,
			U.SourceTypeId,
			'Student' AS SourceType,
			QM.CreatedUserId AS QueryCreatedUserId,
			OM.DisplayTitle AS OrgName,
			SA.Code,
			(SELECT TOP 1 U.DisplayTitle AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND  QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserName,
			(SELECT TOP 1 CONVERT(NVARCHAR,QC.CreatedDateTime,103) AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserDate
			
	FROM 
		sCommunication.tQuery QM
        INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QM.QueryCategoryId=QCM.Id
        INNER JOIN sCommon.tStatusMaster SM ON SM.Id=QM.StatusId
        INNER JOIN sSecurity.tUser U ON U.Id=QM.CreatedUserId
        INNER JOIN sStudent.vStudentAcademic SA ON SA.StudentId = U.SourceId AND U.SourceTypeId = 2003 AND SA.OrgGroupBatchId = @rOrgGroupBatchId 
					AND SA.DivisionId IN (SELECT Id FROM sSetup.tDivisionMaster WHERE InchargeEmployeeId=@rUserSourceId)
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId			
	WHERE 
			((QCM.Id = @rQueryCategoryId) OR (@rQueryCategoryId = 0))
		AND ((QM.Id = @rQueryId) OR (@rQueryId = 0)) 
		AND (QCM.OrgGroupId=@rOrgGroupId)  
		AND (QM.OrgGroupBatchId=@rOrgGroupBatchId)
		AND QueryCategoryId IN (select QueryCategoryId FROM sCommunication.tQueryCategoryAssignedTo where  RIGHT(SourceId,2) = 24 AND SourceTypeId = 2015)
		AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))
		AND ((SA.StudentId=@rSourceId) OR (@rSourceId=0))
	UNION 

	SELECT 
			QCM.Id AS QueryCategoryId,
			ISNULL(QCM.Title,'') AS QueryCategoryMaster,
			QM.Title,
			QM.Remark,
			QM.CreatedDateTime,
			QM.StatusId,
			ISNULL(sm.Title,'') AS StatusMaster,
			QM.Id AS QueryId,
			QM.IsUserView,
			QM.IsAssigneeView,
			SA.ClassName + ' ' + SA.DivisionName  AS Department,
			U.DisplayTitle AS SourceName,
			U.SourceTypeId,
			'Student' AS SourceType,
			QM.CreatedUserId AS QueryCreatedUserId,
			OM.DisplayTitle AS OrgName,
			SA.Code,
			(SELECT TOP 1 U.DisplayTitle AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND  QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserName,
			(SELECT TOP 1 CONVERT(NVARCHAR,QC.CreatedDateTime,103) AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserDate
			
	FROM 
		sCommunication.tQuery QM
        INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QM.QueryCategoryId=QCM.Id
        INNER JOIN sCommon.tStatusMaster SM ON SM.Id=QM.StatusId
        INNER JOIN sSecurity.tUser U ON U.Id=QM.CreatedUserId
        INNER JOIN sStudent.vStudentAcademic SA ON SA.StudentId = U.SourceId AND U.SourceTypeId = 2003 AND SA.OrgGroupBatchId = @rOrgGroupBatchId 
        INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
	WHERE 
			((QCM.Id = @rQueryCategoryId) OR (@rQueryCategoryId = 0))
		AND ((QM.Id = @rQueryId) OR (@rQueryId = 0)) 
		AND (QCM.OrgGroupId=@rOrgGroupId)  
		AND (QM.OrgGroupBatchId=@rOrgGroupBatchId)
		AND QueryCategoryId IN (select QueryCategoryId FROM sCommunication.tQueryCategoryAssignedTo where  RIGHT(SourceId,2) = 25 AND SourceTypeId = 2015)
		AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))
		AND ((SA.StudentId=@rSourceId) OR (@rSourceId=0))
END
END


SELECT Q.CreatedUserId FROM sCommunication.tQueryCategoryMaster QCM INNER JOIN sCommunication.tQuery Q ON Q.QueryCategoryId = QCM.Id
GO
PRINT N'Altering [sConfig].[pDisplayFieldOrgAdd]...';


GO
ALTER PROCEDURE [sConfig].[pDisplayFieldOrgAdd]
	@rDisplayFieldOrgDetailXml [nvarchar](max),
	@rOrgId smallint,
	@rFieldSource nvarchar(100)
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rDisplayFieldOrgDetailXml
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION 
	 BEGIN	

	 Delete D FROM sConfig.tDisplayFieldOrg D  INNER  JOIN [sConfig].[tDisplayFieldMaster] DF
     ON DF.id=D.DisplayFieldId and FieldSource=@rFieldSource
				 WHERE OrgId=@rOrgId 
			
	 --DELETE FROM sConfig.tDisplayFieldOrg
		--		 WHERE OrgId=@rOrgId 
	 
	 INSERT INTO sConfig.tDisplayFieldOrg
		(
			DisplayFieldId,
			OrgId
			
			)
		SELECT
		
			DisplayFieldId,
			OrgId
		FROM OPENXML (@loDoc, '/Table/DisplayFieldOrgDetail', 1)
		WITH ( 
				DisplayFieldId smallint,
				OrgId smallint
			
			  ) 
		
        SELECT 1 AS Result
	 END	
	
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sFee].[pFeeCustomSearchGet]...';


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

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


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


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

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

DECLARE @lItemValue nvarchar(20) = ''
SELECT @lItemValue = CASE WHEN CS.Id IS NOT NULL THEN ISNULL(CS.ItemValue,'') ELSE ISNULL(CM.ItemValue,'') END
FROM sConfig.tConfigurationMaster CM
LEFT JOIN sConfig.tConfigurationSetup CS ON CM.Id = CS.ConfigurationId
AND SourceTypeId = 1016 AND SourceId = @rOrgId WHERE CM.Id = 239

-- GST
DECLARE @lAmountAfterDiscount decimal(12,2) = NULL
DECLARE @lCGSTPercentage decimal(12,2)  = NULL
DECLARE @lSGSTPercentage decimal(12,2)  = NULL
DECLARE @lCGSTAmount decimal(12,2)  = NULL
DECLARE @lSGSTAmount decimal(12,2)  = NULL

IF(@lItemValue='True' AND @rPayTypeId = 1)
	BEGIN 
		SET @lAmountAfterDiscount = 0
		SET @lCGSTAmount = 0
		SET @lSGSTAmount = 0
		SET @lCGSTPercentage = 0
		SET @lSGSTPercentage = 0
	END
ELSE
	BEGIN 		
		SET @lAmountAfterDiscount = @rTotalReceiptAmount - @rDiscountAmount
		SELECT @lCGSTPercentage = CGSTPercentage,@lSGSTPercentage = SGSTPercentage FROM sFee.tReceiptBookMaster WHERE Id = @rReceiptBookId
		SET @lCGSTAmount = @rReceiptAmount*@lCGSTPercentage / 100
		SET @lSGSTAmount = @rReceiptAmount*@lSGSTPercentage / 100
		SET @rReceiptAmount = @lAmountAfterDiscount + @lCGSTAmount + @lSGSTAmount
	END
-- GST
	
DECLARE @loDoc INT
DECLARE @lIsCreated INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rReceiptDetailXml

BEGIN
	BEGIN TRY

	  SELECT @rOrgGroupBatchId = OrgGroupBatchId FROM sSetup.tBatchMaster where Id = @rBatchId
	
	IF(@rReceiptNumber <> 0)
	BEGIN
		IF EXISTS(SELECT 1 from sFee.tReceipt where ReceiptNumber=@rReceiptNumber AND ReceiptBookId=@rReceiptBookId AND OrgGroupBatchId = @rOrgGroupBatchId)
		BEGIN
			SELECT -102 AS Result
			RETURN
		END
	END
	ELSE	
		SET @rReceiptNumber = sFee.fReceiptNumberGet(@rReceiptBookId,@rOrgGroupBatchId)

EXECUTE [sFee].[pReceiptAddValidate] @rSourceId,'',@rReceiptDetailXml,@rIsCreated = @lIsCreated OUTPUT
 	IF(@lIsCreated = 1)
 		BEGIN
			SELECT -501 AS Result
			RETURN
		END
 
	 BEGIN TRANSACTION	
 IF(@rId = 0)	
BEGIN

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


	INSERT INTO sFee.tReceipt
		(
		   Id,
		   SourceTypeId,
		   SourceId,
		   ReceiptNumber,
		   ReceiptDate,
		   ReceiptAmount,
		   TotalReceiptAmount,
		   DiscountAmount,
		   PayTypeId,
		   ChequeNo,
		   BankName,
		   ReceiptBookId,
		   Remark,
		   IsObsolete,
		   BatchId,
		   CreatedUserId,
		   CreatedDateTime,
		   OrgGroupBatchId,
		   ChequeDate,
		   FeeInvoiceId,
		   CollectionGroupId,
		   AmountAfterDiscount,
		   CGSTPercentage,
		   SGSTPercentage,
		   CGSTAmount,
		   SGSTAmount,
		   PaymentTransactionId
        )
	VALUES
		(
			@lNextNumber,
			@rSourceTypeId,
			@rSourceId,
		    @rReceiptNumber,
		    @rReceiptDate,
		    @rReceiptAmount,
		    @rTotalReceiptAmount,
		    @rDiscountAmount,
		    @rPayTypeId,
		    @rChequeNo,
		    @rBankName,
		    @rReceiptBookId,
		    @rRemark,
		    @rIsObsolete,
		    @rBatchId,
		    @rCreatedUserId,
		    sCommon.fGetDate(),
		    @rOrgGroupBatchId,
		    @rChequeDate,
		    @rFeeInvoiceId,
		    @rCollectionGroupId,
		    @lAmountAfterDiscount,
		    @lCGSTPercentage,
		    @lSGSTPercentage,
		    @lCGSTAmount,
		    @lSGSTAmount,
		    @rPaymentTransactionId
		)
		
		INSERT INTO sFee.tReceiptDetail
		(
		   ReceiptId,
		   FeeSetupId,
		   Amount
        )
        SELECT  	
		  @lNextNumber,
		  FeeSetupId,
		  Amount
		
	FROM OPENXML (@loDoc, '/Table/ReceiptDetail', 1)
		WITH ( 
				FeeSetupId int,
				Amount decimal(12,2)
			  ) 
		
		SELECT @lNextNumber AS Result
		EXEC sp_xml_removedocument @loDoc
		
		IF (@rCharge > 0)
		BEGIN
		EXEC [sFee].[pReceiptChargeAdd] @rSourceTypeId,@rSourceId,@lNextNumber,@rCreatedUserId,@rOrgId,@rBatchId,@rCharge,@rReceiptBookId
		END
	
		DECLARE @lIsServiceTaxApplicable bit
	    DECLARE @lServiceTaxPercentage decimal(6,2)
	
	    SELECT @lIsServiceTaxApplicable = ISNULL(IsServiceTaxApplicable,0),@lServiceTaxPercentage = ISNULL(ServiceTaxPercentage,0) FROM sFee.tReceiptBookMaster where Id = @rReceiptBookId
		
		IF (@lIsServiceTaxApplicable > 0 AND @lServiceTaxPercentage > 0)
		BEGIN
		EXEC [sFee].[pReceiptServiceTaxAdd] @rSourceTypeId,@rSourceId,@lNextNumber,@rCreatedUserId,@rOrgId,@rBatchId,@lServiceTaxPercentage
		END
 END 
	ELSE
	BEGIN
		UPDATE sFee.tReceipt SET
			ReceiptDate=@rReceiptDate,
			PayTypeId=@rPayTypeId,
			ChequeDate=@rChequeDate,
		    ChequeNo=@rChequeNo,
		    BankName=@rBankName,
		    Remark=@rRemark
		WHERE Id=@rId
	SELECT @rId AS RESULT
	END 
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sFee].[pReceiptAdd]...';


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

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

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

BEGIN
	BEGIN TRY

	  SELECT @rOrgGroupBatchId = OrgGroupBatchId FROM sSetup.tBatchMaster where Id = @rBatchId
	
	IF(@rReceiptNumber <> 0)
	BEGIN
		IF EXISTS(SELECT 1 from sFee.tReceipt where ReceiptNumber=@rReceiptNumber AND ReceiptBookId=@rReceiptBookId AND OrgGroupBatchId = @rOrgGroupBatchId)
		BEGIN
			SELECT -102 AS Result
			RETURN
		END
	END
	ELSE	
		SET @rReceiptNumber = sFee.fReceiptNumberGet(@rReceiptBookId,@rOrgGroupBatchId)

EXECUTE [sFee].[pReceiptAddValidate] @rSourceId,'',@rReceiptDetailXml,@rIsCreated = @lIsCreated OUTPUT
 	IF(@lIsCreated = 1)
 		BEGIN
			SELECT -501 AS Result
			RETURN
		END
 
	 BEGIN TRANSACTION	
 IF(@rId = 0)	
BEGIN

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


	INSERT INTO sFee.tReceipt
		(
		   Id,
		   SourceTypeId,
		   SourceId,
		   ReceiptNumber,
		   ReceiptDate,
		   ReceiptAmount,
		   TotalReceiptAmount,
		   DiscountAmount,
		   PayTypeId,
		   ChequeNo,
		   BankName,
		   ReceiptBookId,
		   Remark,
		   IsObsolete,
		   BatchId,
		   CreatedUserId,
		   CreatedDateTime,
		   OrgGroupBatchId,
		   ChequeDate,
		   FeeInvoiceId,
		   CollectionGroupId,
		   DepositedLedgerId,
		   PaymentTransactionId
        )
	VALUES
		(
			@lNextNumber,
			@rSourceTypeId,
			@rSourceId,
		    @rReceiptNumber,
		    @rReceiptDate,
		    @rReceiptAmount,
		    @rTotalReceiptAmount,
		    @rDiscountAmount,
		    @rPayTypeId,
		    @rChequeNo,
		    @rBankName,
		    @rReceiptBookId,
		    @rRemark,
		    @rIsObsolete,
		    @rBatchId,
		    @rCreatedUserId,
		    sCommon.fGetDate(),
		    @rOrgGroupBatchId,
		    @rChequeDate,
		    @rFeeInvoiceId,
		    @rCollectionGroupId,
		    @rDepositedLedgerId,
		    @rPaymentTransactionId
		)
		
		INSERT INTO sFee.tReceiptDetail
		(
		   ReceiptId,
		   FeeSetupId,
		   Amount
        )
        SELECT  	
		  @lNextNumber,
		  FeeSetupId,
		  Amount
		
	FROM OPENXML (@loDoc, '/Table/ReceiptDetail', 1)
		WITH ( 
				FeeSetupId int,
				Amount decimal(12,2)
			  ) 
		
		SELECT @lNextNumber AS Result
		EXEC sp_xml_removedocument @loDoc
		
		IF (@rCharge > 0)
		BEGIN
		EXEC [sFee].[pReceiptChargeAdd] @rSourceTypeId,@rSourceId,@lNextNumber,@rCreatedUserId,@rOrgId,@rBatchId,@rCharge,@rReceiptBookId
		END
	
		DECLARE @lIsServiceTaxApplicable bit
	    DECLARE @lServiceTaxPercentage decimal(6,2)
	
	    SELECT @lIsServiceTaxApplicable = ISNULL(IsServiceTaxApplicable,0),@lServiceTaxPercentage = ISNULL(ServiceTaxPercentage,0) FROM sFee.tReceiptBookMaster where Id = @rReceiptBookId
		
		IF (@lIsServiceTaxApplicable > 0 AND @lServiceTaxPercentage > 0)
		BEGIN
		EXEC [sFee].[pReceiptServiceTaxAdd] @rSourceTypeId,@rSourceId,@lNextNumber,@rCreatedUserId,@rOrgId,@rBatchId,@lServiceTaxPercentage
		END
 END 
	ELSE
	BEGIN
		UPDATE sFee.tReceipt SET
			ReceiptDate=@rReceiptDate,
			PayTypeId=@rPayTypeId,
			ChequeDate=@rChequeDate,
		    ChequeNo=@rChequeNo,
		    BankName=@rBankName,
		    Remark=@rRemark
		WHERE Id=@rId
	SELECT @rId AS RESULT
	END 
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sFee].[pRptFeeReceiptDetailsGet]...';


GO
ALTER PROCEDURE [sFee].[pRptFeeReceiptDetailsGet]
			
			
			@rReportId int=0,
			@rReceiptId bigint = 0,
			@rOrgGroupId int = 0,
			@rReceiptBookId int = 0,
			@rFromReceiptNo int=0,
			@rToReceiptNo int=0,
			@rOrgId int = 0,
			@rBatchId int = 0,
			@rReceiptDate Date=''

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 	

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

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

	SELECT 
			FRD.ReceiptId,
			FR.ReceiptNumber,
			FR.ReceiptDate,
			SA.AcademicId,
			--SA.FirstName+' '+SA.MiddleName+' '+SA.LastName AS Name,
			SA.Name AS Name,
			SA.Code,
			SA.RollNo,
			SA.ClassId,
			SA.DivisionId,
			SA.ClassName,
			SA.DivisionName,
			SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
			FM.FeeHeadId,
			FHM.Title AS FeeHead,
			FM.Id AS FeeId,
			FM.Title AS FeeName,
			FRD.Amount AS PaidAmount,
			PTM.Id AS PayTypeId,
			PTM.Title AS PayType,
			CASE WHEN ISNULL(FR.ChequeNo,'') != '' THEN FR.ChequeNo ELSE CONVERT(nvarchar(20),FR.PaymentTransactionId) END AS ChequeNo,
			--ISNULL(FR.ChequeNo,'') AS ChequeNo,
			ISNULL(FR.BankName,'') AS BankName,
			ISNULL(RBM.Address1,'') AS Address1,
			ISNULL(RBM.Address2,'') AS Address2,
			ISNULL(RBM.FullTitle,'') AS FullTitle,
			ISNULL(FR.TotalReceiptAmount,0.00) AS TotalReceiptAmount,
			ISNULL(FR.ReceiptAmount,0.00) AS ReceiptAmount,			
			
			(CASE WHEN @rOrgGroupId = 0 -- For Single Receipt
					THEN @lAmountInWord 
				  WHEN @rOrgGroupId != 0 -- For Bulk Receipt
					THEN sFinanceCommon.fNumberToWordsWithDecimal(ISNULL(FR.ReceiptAmount,0.00),1,2,@rOrgGroupId)
			END) AS ReceiptAmountInWords,
			
			ISNULL(FR.DiscountAmount,0.00) AS DiscountAmount,
			FR.Remark,
			ISNULL(U.DisplayTitle,'') AS UserName,
			OM.OrgLogo,
			RBM.Remark1,
			RBM.Remark2,			 
			ISNULL(RBM.IsOnPrePrinted,0) AS IsOnPrePrinted,
			ISNULL(RBM.IsSupressLogo,0) AS IsSupressLogo,
			ISNULL(RBM.IsDisplaySchoolName,0) AS IsDisplaySchoolName,
			RBM.ReportId,
			OM.Title AS OrganizationName,
			--(CASE  WHEN (RBM.ReportId = 20775 OR RBM.ReportId = 20777 OR RBM.ReportId = 20874 OR RBM.ReportId =20427 OR RBM.ReportId =20890 OR RBM.ReportId =20901 OR RBM.ReportId =20902) AND ISNULL(RBM.IsMonthDetailOnly,0) = 0  THEN 
			--	[sFee].[fFeeHeadMonthDetailGet](FR.ID,FHM.Id) -- Fee name in detail	
				  
			  
			(CASE WHEN  RBM.ReportId = 20576 
			  THEN -- HM patel report
				[sFee].[fReceiptMonthDetailGet](FR.ID)	
				
			WHEN ISNULL(RBM.IsMonthDetailOnly,0) = 1  THEN				
				 [sFee].[fFeeHeadMonthNameGet](FR.ID,FHM.Id) -- Month name in detail
	
			ELSE '' END) AS MonthDetail,    
			
			DM.Title AS DepartmentName,
			FM.OrderIndex AS FeeOrderIndex,
			FHM.OrderIndex AS FeeHeadOrderIndex,
			FR.IsObsolete AS IsCancelReceipt,
			@lCurrencyCode AS CurrencyCode,
			@lCurrencyTitle AS CurrencyTitle,
			BM.Title AS Batch,
			FR.ChequeDate AS ChequeDate,
			ISNULL(RBM.IsMonthDetailOnly,0) AS IsMonthDetailOnly,
	        ISNULL(RBM.IsFeeInvoiceHeadwise,0) AS IsFeeInvoiceHeadwise,
	        ISNULL(RBM.GroupTitle,'') AS GroupTitle,
	        ISNULL(RBM.IsSuppressFeeDetail,0) AS IsSuppressFeeDetail,
	        ISNULL(CGM.Title,'') AS CollectionGroupName,
	        ISNULL(FI.InvoiceNumber,0) AS InvoiceNumber,
	        SA.SUID,
	        CASE
				 WHEN RBM.IsOnPrePrinted=1       
				 THEN 2
				 ELSE  ISNULL(RBM.HeaderDisplayId,1)
				END AS HeaderDisplayId,
	        RBM.ReceiptBookHeader,
	        RBM.ServiceTaxPercentage,
	        ISNULL(FR.AmountAfterDiscount,0) AS AmountAfterDiscount,
	        (CASE WHEN  FR.CGSTPercentage IS NULL THEN RBM.CGSTPercentage ELSE FR.CGSTPercentage END) AS CGSTPercentage,
	        (CASE WHEN  FR.SGSTPercentage IS NULL THEN RBM.SGSTPercentage ELSE FR.SGSTPercentage END) AS SGSTPercentage,
	        ISNULL(FR.CGSTAmount,0) AS CGSTAmount,
	        ISNULL(FR.SGSTAmount,0) AS SGSTAmount,
	        ISNULL(OOM.GSTINNo,'') AS GSTINNo,
	        ISNULL(OOM.HSNSACCode,'') AS HSNSACCode,
	        @lIDConfigValue AS ItemValue ,
	        SF.FatherName
	FROM 
	
			sFee.tReceipt FR				
			INNER JOIN sFee.tReceiptDetail FRD
				ON FR.Id=FRD.ReceiptId AND FR.SourceTypeId=2001				
			INNER JOIN sFee.tFeeSetup FS
				ON FRD.FeeSetupId = FS.Id				
			INNER JOIN sFee.tFeeMaster FM
				ON FS.FeeId=FM.Id						
			INNER JOIN sFee.tFeeHeadMaster FHM
				ON FHM.Id=FM.FeeHeadId
			INNER JOIN sStudent.vStudentAcademic SA
				ON SA.AcademicId = FR.SourceId
			INNER JOIn sFinanceCommon.tPayTypeMaster PTM
				ON PTM.Id=FR.PayTypeId
			--LEFT JOIN sFee.tFeeAllocation FA
			--	ON FA.FeeSetupId=FS.Id
			INNER JOIN sFee.tReceiptBookMaster RBM 
				ON RBM.Id=FR.ReceiptBookId
			LEFT JOIN sSecurity.tUser U
				ON U.Id=FR.CreatedUserId
			INNER JOIN sSetup.tDepartmentMaster DM
				ON SA.DepartmentId =DM.Id
			LEFT JOIN sSetup.tOrganizationMaster OM
				ON OM.Id=DM.OrgId
			LEFT JOIN sSetup.tOrganizationOtherDetail OOM
				ON OM.Id=OOM.OrgId	
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = FR.BatchId
			LEFT JOIN sFee.tCollectionGroupMaster CGM
				ON CGM.Id=FR.CollectionGroupId
			LEFT JOIN sFee.tFeeInvoice FI
				ON FI.Id=FR.FeeInvoiceId
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SA.StudentId
	WHERE 
	 ((FR.Id=@rReceiptId) OR (@rReceiptId = 0))
	 AND ((RBM.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId = 0))
	 AND ((FR.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId = 0))
	 AND ((FR.ReceiptNumber >= @rFromReceiptNo) OR (@rFromReceiptNo = 0))
	 AND ((FR.ReceiptNumber <= @rToReceiptNo) OR (@rToReceiptNo = 0))
	 AND ((FR.BatchId = @rBatchId) OR (@rBatchId = 0))
	 AND ((BM.OrgId = @rOrgId) OR (@rOrgId = 0))
	 AND ((FR.ReceiptDate = @rReceiptDate) OR (ISNULL(@rReceiptDate,'') = ''))
	  
ORDER BY FS.StartDate,FHM.OrderIndex,FM.OrderIndex ASC

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


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


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


GO
ALTER PROCEDURE [sHostel].[pHostelYearProcessGet]
           @rHostelId int,
           @rOrgGroupBatchId int,
           @rFromOrgGroupBatchId int,
           @rRoomId int,
           @rBuildingId int
AS
SET NOCOUNT ON
--SELECT 
--		RM.Id AS RoomId,
--		RM.Title AS Room,
--	    RCM.Title AS RoomCategory,
--	     CASE WHEN SM.ReferenceSourceId is null THEN VA.Code ElSE SM.Code  END AS Code,
--	     CASE WHEN SM.ReferenceSourceId is null THEN VA.Name ElSE SMA.Name   END AS Name,
--	    CASE WHEN SM.ReferenceSourceId is null THEN AR.SourceId ElSE SM.Id  END AS SourceId,
--	    Isnull(AR.BedNumber,'') AS BedNumber ,
--	    CASE WHEN SM.ReferenceSourceId is null THEN (VA.ClassName +'-' +va.DivisionName) ElSE (SMA.ClassName +'-' +SMA.DivisionName) END AS ClassName,
--	    AR.SourceId As StudentId,
--	    AR.RoomId,
--	    CASE WHEN SM.ReferenceSourceId is null THEN VA.AcademicId ElSE SMA.AcademicId   END AS AcademicId,
--	    CASE WHEN SM.ReferenceSourceId is null THEN VA.suId ElSE SM.suId  END AS suId ,
--	    [sHostel].[fAssignRoomStudentGet] (@rOrgGroupBatchId,CASE WHEN SM.ReferenceSourceId is null THEN AR.SourceId ElSE SM.Id END) AS Status
--	   -- CASE WHEN @rOrgGroupBatchId  in (select OrgGroupBatchId from sHostel.tAssignRoom where SourceTypeId=2003  AND  AR.SourceId=  CASE WHEN SM.ReferenceSourceId is null THEN AR.SourceId ElSE SM.Id END)THEN 'Transfer' ElSE 'Available'  END AS Status
	   
--	   FROM  sHostel.tAssignRoom AR 
--		  INNER JOIN sHostel.tRoomMaster  RM ON RM.Id=AR.RoomId 
--		  INNER JOIN sHostel.tHostelMaster HM ON HM.Id=RM.HostelId
--		  INNER JOIN sHostel.tRoomCategoryMaster RCM ON RCM.HostelId=HM.Id AND RCM.Id = RM.RoomCateGoryId
--		  INNER JOIN sStudent.vStudentAcademic VA On VA.StudentId= AR.SourceId  AND VA.OrgGroupBatchId=@rOrgGroupBatchId
--		  LEFT JOIN sStudent.tStudentMaster SM ON AR.SourceId=SM.ReferenceSourceId
--		  LEFT JOIN sStudent.vStudentAcademic SMA ON SM.Id = SMA.StudentId AND SMA.OrgGroupBatchId=@rOrgGroupBatchId 
--WHERE 
--      AR.SourceTypeId=2003 
--     AND AR.OrgGroupBatchId=@rFromOrgGroupBatchId
--    -- AND VA.OrgGroupBatchId=@rOrgGroupBatchId
--     AND RM.HostelId=@rHostelId
--     AND RM.IsObsolete=0
	 
	SELECT RM.Id AS RoomId,
		   RM.Title AS Room,
	       RCM.Title AS RoomCategory,
	       V.Code,
	       V.Name,
	       AR.SourceId AS SourceId ,
	       AR.BedNumber,
	       (V.ClassName + '-' +V.DivisionName) AS ClassName,
	       AR.SourceId As StudentId,
	       AR.RoomId,
	       V.AcademicId AS  AcademicId,
	       V.SUID ,
	       [sHostel].[fAssignRoomStudentGet] (@rOrgGroupBatchId, AR.SourceId) AS Status
	        from sHostel.tAssignRoom AR
	        INNER JOIN sHostel.tRoomMaster  RM ON RM.Id=AR.RoomId
	        INNER JOIN sHostel.tHostelMaster HM ON HM.Id=RM.HostelId
	        INNER JOIN sHostel.tRoomCategoryMaster RCM ON RCM.HostelId=HM.Id AND RCM.Id = RM.RoomCateGoryId
				INNER JOIN
			(SELECT StudentId,Code,Name,AcademicId,SUId,ClassName,DivisionName FROM sStudent.vstudentAcademic V
			WHERE OrgGroupBatchId=@rOrgGroupBatchId AND StatusId=1
			) V ON AR.SourceId = V.StudentId
			LEFT JOIN sHostel.tBuildingMaster BM ON BM.HostelId=HM.Id AND BM.Id = RM.BuildingId
			WHERE 
			AR.SourceTypeId=2003 
			AND AR.OrgGroupBatchId=@rFromOrgGroupBatchId
			AND ((RM.Id = @rRoomId) OR (ISNULL(@rRoomId,0) = 0))
            AND ((BM.Id=@rBuildingId )OR (@rBuildingId=0))
    UNION ALL
	SELECT RM.Id AS RoomId,
		   RM.Title AS Room,
	       RCM.Title AS RoomCategory,
	       V.Code,
	       V.Name,
	       V.StudentId AS SourceId ,
	       AR.BedNumber,
	      (V.ClassName + '-' +V.DivisionName) AS ClassName,
	       V.ReferenceSourceId As StudentId ,
	       AR.RoomId,
	       V.AcademicId AS  AcademicId,
	       V.SUID ,
	       [sHostel].[fAssignRoomStudentGet] (@rOrgGroupBatchId,  V.StudentId) AS Status
	        from sHostel.tAssignRoom AR
	        INNER JOIN sHostel.tRoomMaster  RM ON RM.Id=AR.RoomId
	        INNER JOIN sHostel.tHostelMaster HM ON HM.Id=RM.HostelId
	        INNER JOIN sHostel.tRoomCategoryMaster RCM ON RCM.HostelId=HM.Id AND RCM.Id = RM.RoomCateGoryId
	       INNER JOIN
           (SELECT ReferenceSourceId,StudentId,Code,Name,AcademicId,SUId,ClassName,DivisionName FROM sStudent.vstudentAcademic V
           WHERE OrgGroupBatchId=@rOrgGroupBatchId AND StatusId=1
            ) V ON AR.SourceId = V.ReferenceSourceId
            LEFT JOIN sHostel.tBuildingMaster BM ON BM.HostelId=HM.Id AND BM.Id = RM.BuildingId
	       WHERE 
	       AR.SourceTypeId=2003 
           AND AR.OrgGroupBatchId=@rFromOrgGroupBatchId
           AND ((RM.Id = @rRoomId) OR (ISNULL(@rRoomId,0) = 0))
           AND ((BM.Id=@rBuildingId )OR (@rBuildingId=0))
           
	--FROM  sHostel.tAssignRoom AR 
	--INNER JOIN sHostel.tRoomMaster  RM ON RM.Id=AR.RoomId 
	--INNER JOIN sHostel.tHostelMaster HM ON HM.Id=RM.HostelId
	--INNER JOIN sHostel.tRoomCategoryMaster RCM ON RCM.HostelId=HM.Id AND RCM.Id = RM.RoomCateGoryId
	--INNER JOIN sStudent.vStudentAcademic VA On VA.StudentId= AR.SourceId  AND VA.OrgGroupBatchId=@rOrgGroupBatchId
GO
PRINT N'Altering [sHrm].[pEmployeeDocumentSubmitGet]...';


GO

ALTER PROCEDURE [sHrm].[pEmployeeDocumentSubmitGet]
	 
        @rEmployeeId bigint,
		@rOrgId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
 
	BEGIN
			SELECT Isnull(D.Id,0) AS DocumentId,ISNULL(D.DocumentName,'') AS DocumentName,
			CASE WHEN  S.SubmitDocumentMasterId Is null THEN 'False' ELSE 'True'END AS IsCheck
		 	FROM sCommon.tSubmitDocumentMaster D
			LEFT Join [sHrm].[tEmployeeDocument]  S ON S.SubmitDocumentMasterId=D.id AND S.EmployeeId=@rEmployeeId
			WHERE OrgId=@rOrgId AND SubmitDocumentFunctionalityId='2'
END
GO
PRINT N'Altering [sHrm].[pExportLeave]...';


GO
ALTER PROCEDURE [sHrm].[pExportLeave]
	
	@rFromBatchId int,
	@rToBatchId int,
	@rOrgId int,
	@rIsDelete bit,
	@rUserId bigint = 0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
BEGIN TRY 

	IF (@rIsDelete=1)
	BEGIN
		DELETE FROM sHrm.tLeaveBalance WHERE BatchId = @rToBatchId
		SELECT 101 AS RESULT
		RETURN
	END

	IF EXISTS (SELECT 1 FROM sHrm.tLeaveBalance WHERE BatchId = @rToBatchId)
	BEGIN
		SELECT -101 AS RESULT
		RETURN
	END
	
	BEGIN TRANSACTION
	
	DECLARE @lCount int
	
	-- Leave Balance Temp Table
	
	CREATE TABLE #TempLeaveBalance
	(
	[AutoId] int IDENTITY,
	[EmployeeId] bigint NOT NULL,
	[LeaveTypeId] int NOT NULL,
	[BatchId] int NOT NULL,
	[PendingNoOfLeave] decimal(5,2) NOT NULL,
	[MaximumCarryForward] int NOT NULL,
	[OldSettingNoOfLeave] int NOT NULL,
	[NewSettingNoOfLeave] int NOT NULL,
	[EmployeeNoOfLeave] decimal(5,2) NOT NULL,
	[MaxInMonth] decimal(5,2) NULL
	)
	
	-- End Create Table
	
	INSERT INTO #TempLeaveBalance 
	SELECT 
		EM.Id,
		--EM.Code,
		--EM.FirstName +' '+EM.LastName,
		ISNULL(B.LeaveTypeId,0),
		@rToBatchId,
		(CASE WHEN (ISNULL(LB.BalanceLeave,0)-ISNULL(A.NoOfLeave,0)) > 0 
		   THEN ISNULL(LB.BalanceLeave,0)-ISNULL(A.NoOfLeave,0)
		   ELSE 0
		END) AS NoOfLeave,	
		ISNULL(B.MaximumCarryForward,0), 
		ISNULL(LB.BalanceLeave,0),
		ISNULL(B.NoOfLeave,0),
		ISNULL(A.NoOfLeave,0),
		ISNULL(LB.MaxInMonth,0)
	FROM 
		sHrm.tEmployeeMaster EM
		INNER JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id = EJD.EmployeeId AND StatusId=7
		LEFT JOIN 
		(
			SELECT L.EmployeeId,L.LeaveTypeId,SUM(L.NoOfLeave) AS NoOfLeave,LTM.MaximumCarryForward  FROM sHrm.tLeave L
			INNER JOIN sHrm.tLeaveTypeMaster LTM ON L.LeaveTypeId = LTM.Id 
			AND IsCarryForward=1 AND IsLWP = 0 AND StatusId=550
			WHERE L.BatchId=@rFromBatchId AND L.OrgId = @rOrgId AND LTM.IsCarryForward = 1
			GROUP BY L.EmployeeId,L.LeaveTypeId,LTM.MaximumCarryForward 
		)A ON A.EmployeeId=EM.Id
		LEFT JOIN 
		(
		    SELECT LeaveTypeId,EmployeeGradeId,NoOfLeave,LTM.MaximumCarryForward FROM sHrm.tLeaveTypeGradeSettings LTGS
		    INNER JOIN sHrm.tLeaveTypeMaster LTM ON LTM.Id = LTGS.LeaveTypeId
		    WHERE LTGS.OrgId = @rOrgId AND LTM.IsCarryForward = 1
		)B ON B.EmployeeGradeId = EJD.EmployeeGradeId --AND A.LeaveTypeId=B.LeaveTypeId
		
		LEFT JOIN  sHrm.tLeaveBalance LB ON LB.EmployeeId = EM.Id AND LB.LeaveTypeId=B.LeaveTypeId
		WHERE EM.OrgID = @rOrgId AND LB.BatchId=@rFromBatchId
		
	
	--SELECT * FROM #TempLeaveBalance 
		
	SELECT @lCount = COUNT(EmployeeId) FROM #TempLeaveBalance

	DECLARE @lBatchName nvarchar(100)
	SELECT @lBatchName = Title FROM sSetup.tBatchMaster WHERE Id = @rFromBatchId
	
	WHILE (@lCount > 0)
	BEGIN
		
		-- Leave Balance Entry
		
		INSERT INTO sHrm.tLeaveBalance 
		SELECT 
				EmployeeId,
				LeaveTypeId,
				(
				CASE 
					WHEN (PendingNoOfLeave >= MaximumCarryForward) THEN NewSettingNoOfLeave + MaximumCarryForward
					WHEN (PendingNoOfLeave <= MaximumCarryForward) THEN NewSettingNoOfLeave + PendingNoOfLeave
					ELSE NewSettingNoOfLeave
				END
				) AS NoOfLeave,
				BatchId,
				MaxInMonth
		FROM #TempLeaveBalance WHERE AutoId = @lCount
		
		-- Add Leave Balance Log
		INSERT INTO sHrm.tLeaveBalanceLog 
		SELECT 
				EmployeeId,
				LeaveTypeId,
				NewSettingNoOfLeave,
				1,
				CASE 
					WHEN (PendingNoOfLeave >= MaximumCarryForward) THEN MaximumCarryForward
					WHEN (PendingNoOfLeave <= MaximumCarryForward) THEN PendingNoOfLeave
					ELSE 0
				END AS TransactionLeave,
				'Carry Forward leave from ('+@lBatchName+')',
				BatchId,
				@rUserId,
				sCommon.fGetDate()
		FROM #TempLeaveBalance WHERE AutoId = @lCount
		
		-- END Leave Balance Entry
		
		SET @lCount = @lCount -1
	END

	DROP Table #TempLeaveBalance
	SELECT 1 AS Result
	COMMIT TRANSACTION
END TRY

BEGIN CATCH 
		DROP TABLE #TempLeaveBalance 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
END CATCH	
END
GO
PRINT N'Altering [sHrm].[pGetDropDowns]...';


GO
-- exec [sHrm].[pGetDropDowns]
-- drop proc [sHrm].[pGetDropDowns]
ALTER proc [sHrm].[pGetDropDowns]
@rOrgId int,
@rUserId bigint,
@rOrgGroupId int = null,
@rPayrollYearId int = null
as
begin
	declare @lStatusRes varchar(max)='',@lColumnRes varchar(max)='',@lReportList varchar(max)=''
	declare @lOrganizationRes varchar(max) = '',@lPayRollYear varchar(max) = '',@lPayrollColumn varchar(max) = ''
	declare @lPayrollReportList varchar(max) = ''
	
	select @lOrganizationRes = @lOrganizationRes + '<option value="0"> -- ALL -- </option>'
	select @lOrganizationRes = @lOrganizationRes + '<option value="' + convert(varchar,Id) + '">' + DisplayTitle + '</option>'
	from sSetup.vUserOrganization where IsObsolete = 0 AND OrgGroupId = isnull(@rOrgGroupId,0) and UserId = @rUserId
	order by OrderIndex
	
	select @lPayRollYear = @lPayRollYear + '<option value="0"> -- Select -- </option>'
	select top 1 @lPayRollYear = @lPayRollYear + '<option value="' + convert(varchar,YearNumber) + '">' + convert(varchar,YearNumber) + '</option>'
	from sPayroll.fMonthYearForPayrollGet(@rPayrollYearId)
	
	select @lStatusRes = @lStatusRes + '<option value="0"> -- ALL -- </option>'
	select @lStatusRes = @lStatusRes + '<option value="7">Active</option>'
	select @lStatusRes = @lStatusRes + '<option value="9">Left</option>'
	select @lStatusRes = @lStatusRes + '<option value="8">Suspended</option>'
	select @lStatusRes = @lStatusRes + '<option value="8">Unknown</option>'
	
	select @lColumnRes = @lColumnRes + '<option value="' + COLUMN_NAME + '">' + COLUMN_NAME + '</option>'
	from INFORMATION_SCHEMA.COLUMNS where TABLE_SCHEMA='sHrm' AND TABLE_NAME='vEmployeeColumnName'
	
	select @lPayrollColumn = @lPayrollColumn + '<option value="' + COLUMN_NAME + '">' + COLUMN_NAME + '</option>'
	from INFORMATION_SCHEMA.COLUMNS where TABLE_SCHEMA='sPayroll' AND TABLE_NAME='vPayrollColumnName'
	
	select @lReportList = @lReportList + '<tr><td style="width:100px; word-wrap:break-word;">' + SCS.Title + '</td>
	<td style="width:700px; word-wrap:break-word;">' + SCS.ColumnName + '</td>
	<td style="width:50px; word-wrap:break-word;"></td>
	<td style="width:100px; word-wrap:break-word;">' + U.DisplayTitle + '</td>	
	<td style="width:50px; word-wrap:break-word;"><a onclick="DeleteReport(' + convert(varchar,SCS.Id) + ');"><i class="fa fa-trash" aria-hidden="true"></i></a></td></tr>'
	from sHrm.tEmployeeCustomSearch SCS
	INNER JOIN sSecurity.tUser U ON U.Id=SCS.CreatedUserId
	WHERE (SCS.CreatedUserId = @rUserId OR SCS.IsCommon = 1)
	AND SCS.OrgId = @rOrgId
	
	select @lPayrollReportList = @lPayrollReportList + '<tr><td style="width:100px; word-wrap:break-word;">' + SCS.Title + '</td>
	<td style="width:700px; word-wrap:break-word;">' + SCS.ColumnName + '</td>
	<td style="width:50px; word-wrap:break-word;"></td>
	<td style="width:100px; word-wrap:break-word;">' + U.DisplayTitle + '</td>	
	<td style="width:50px; word-wrap:break-word;"><a onclick="DeleteReport(' + convert(varchar,SCS.Id) + ');"><i class="fa fa-trash" aria-hidden="true"></i></a></td></tr>'
	from sPayroll.tPayrollCustomSearch SCS
	INNER JOIN sSecurity.tUser U ON U.Id=SCS.CreatedUserId
	WHERE (SCS.CreatedUserId = @rUserId OR SCS.IsCommon = 1)
	AND SCS.OrgId = @rOrgId
	
	select @lStatusRes as StatusRes,@lColumnRes as AvailableRes,@lReportList as ReportList,
	@lOrganizationRes as OrganizationRes,@lPayRollYear as PayRollYear,@lPayrollColumn as PayrollColumn,
	@lPayrollReportList as PayrollReportList
end
GO
PRINT N'Altering [sOp].[pGatewayConfigurationAdd]...';


GO
ALTER PROCEDURE [sOp].[pGatewayConfigurationAdd]
	
	@rId int,
	@rOrgGroupId smallint,
	@rPaymentGatewayId smallint,
	@rGatewayURL nvarchar(1000),
	@rServerPort nvarchar(50),
	@rLoginId nvarchar(50),
	@rLoginPassword nvarchar(50),
	@rProductId nvarchar(100),
	@rTermsCondition nvarchar(max)='',
	@rPrivacyPolicy nvarchar(max)='',
	@rPaymentPolicy nvarchar(max)='',
	@rDisclaimer nvarchar(max)='',
	@rContactUs nvarchar(max)='',
	@rAboutUs nvarchar(max)=''
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	BEGIN TRY
	BEGIN TRANSACTION	
	
	DECLARE @lNextNumber INT     
	IF(@rId = 0)	
	BEGIN
		
		EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sOp.tGatewayConfiguration', 0, 1, 1,@outNextNumber = @lNextNumber output

		INSERT INTO sOp.tGatewayConfiguration
			(
				Id,
				OrgGroupId,
				PaymentGatewayId,
				GatewayURL,
				ServerPort,
				LoginId,
				LoginPassword,
				ProductId,
				TermsCondition,
				PrivacyPolicy,
				PaymentPolicy,
				Disclaimer,
				ContactUs,
				AboutUs
			)
		VALUES
			(
				@lNextNumber,
				@rOrgGroupId,
				@rPaymentGatewayId,
				@rGatewayURL,
				@rServerPort,
				@rLoginId,
				@rLoginPassword,
				@rProductId,
				@rTermsCondition,
				@rPrivacyPolicy,
				@rPaymentPolicy,
				@rDisclaimer,
				@rContactUs,
				@rAboutUs
			)

	END 
	ELSE
	BEGIN

		SET @lNextNumber = @rId
	    UPDATE  sOp.tGatewayConfiguration
	    SET
			PaymentGatewayId=@rPaymentGatewayId,
			GatewayURL=@rGatewayURL,
			ServerPort=@rServerPort,
			LoginId=@rLoginId,
			LoginPassword=@rLoginPassword,
			ProductId=@rProductId,
			TermsCondition=@rTermsCondition,
			PrivacyPolicy=@rPrivacyPolicy,
			PaymentPolicy=@rPaymentPolicy,
			Disclaimer=@rDisclaimer,
			ContactUs=@rContactUs,
			AboutUs=@rAboutUs
	     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 [sOp].[pGatewayConfigurationGet]...';


GO
ALTER PROCEDURE [sOp].[pGatewayConfigurationGet]
	 
	 @rOrgGroupId smallint
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			
BEGIN 
	SELECT
			ISNULL(GC.Id,0) AS Id,
			GC.OrgGroupId,
			GC.PaymentGatewayId,
			GC.GatewayURL,
			GC.ServerPort,
			GC.LoginId,
			GC.LoginPassword,
			GC.ProductId,
			ISNULL(TermsCondition,'') AS TermsCondition,
			ISNULL(PrivacyPolicy,'') AS PrivacyPolicy,
			ISNULL(PaymentPolicy,'') AS PaymentPolicy,
			ISNULL(Disclaimer,'') AS Disclaimer,
			ISNULL(ContactUs,'') AS ContactUs,
			ISNULL(AboutUs,'') AS AboutUs
	FROM
			sOp.tGatewayConfiguration GC
	WHERE 
			GC.OrgGroupId=@rOrgGroupId
END
GO
PRINT N'Altering [sOp].[pGatewayProductAdd]...';


GO
ALTER PROCEDURE [sOp].[pGatewayProductAdd]
	 
        @rId int,
	    @rGatewayConfigurationId int,
		@rTitle nvarchar(150),
		@rGatewayURL nvarchar(1000),
		@rServerPort nvarchar(50),
		@rLoginId nvarchar(50),
		@rLoginPassword nvarchar(50),
		@rProductId nvarchar(100),
		@rOrgGroupId int,
		@rCCAvenueMerchantID nvarchar(50)='',
		@rCCAvenueAccessCode nvarchar(100)='',
		@rCCAvenueWorkingKey nvarchar(100)='',
		@rCCAvenueWhitelistURL nvarchar(500)='',
		@rCCAvenueSubAccountId nvarchar(100)=''
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY

	IF(@rId = 0)	
	BEGIN
		IF EXISTS(SELECT Id FROM [sOp].[tGatewayProduct] WHERE GatewayConfigurationId=@rGatewayConfigurationId AND Title=@rTitle AND ProductId = @rProductId)
		BEGIN
			SELECT -101 AS Result
			RETURN
		END 
	END
	ELSE
	BEGIN
		IF  EXISTS(SELECT Id FROM [sOp].[tGatewayProduct] WHERE GatewayConfigurationId=@rGatewayConfigurationId AND Title=@rTitle AND ProductId = @rProductId AND Id<>@rId)
		BEGIN
			SELECT -101 AS Result
			RETURN
		END
	END	

	BEGIN TRANSACTION	
	DECLARE @lNextNumber INT     
	IF(@rId = 0)	
	BEGIN

	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sOp.tGatewayProduct', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO [sOp].[tGatewayProduct]
		(
			[Id],
			[GatewayConfigurationId],
			[Title],
			[GatewayURL],
			[ServerPort],
			[LoginId],
			[LoginPassword],
			[ProductId],
			[CCAvenueMerchantID],
			[CCAvenueAccessCode],
			[CCAvenueWorkingKey],
			[CCAvenueWhitelistURL],
			[CCAvenueSubAccountId]
		)
	VALUES
		(
			@lNextNumber,
			@rGatewayConfigurationId,
			@rTitle,
			@rGatewayURL,
			@rServerPort,
			@rLoginId,
			@rLoginPassword,
			@rProductId,
			@rCCAvenueMerchantID,
			@rCCAvenueAccessCode,
			@rCCAvenueWorkingKey,
			@rCCAvenueWhitelistURL,
			@rCCAvenueSubAccountId
		)
		    SELECT 1 AS Result
	END	 
ELSE
	 BEGIN
		SET @lNextNumber = @rId
	    UPDATE  [sOp].[tGatewayProduct]
	    SET
			[GatewayConfigurationId]=@rGatewayConfigurationId,
			[Title]=@rTitle,
			[GatewayURL]=@rGatewayURL,
			[ServerPort]=@rServerPort,
			[LoginId]=@rLoginId,
			[LoginPassword]=@rLoginPassword,
			[ProductId]=@rProductId,
			[CCAvenueMerchantID]=@rCCAvenueMerchantID,
			[CCAvenueAccessCode]=@rCCAvenueAccessCode,
			[CCAvenueWorkingKey]=@rCCAvenueWorkingKey,
			[CCAvenueWhitelistURL]=@rCCAvenueWhitelistURL,
			[CCAvenueSubAccountId]=@rCCAvenueSubAccountId
	    WHERE Id = @rId
	    SELECT 11 AS Result
	 END  	

	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END
GO
PRINT N'Altering [sOp].[pGatewayProductGet]...';


GO
ALTER PROCEDURE [sOp].[pGatewayProductGet]

	 @rId int,
	 @rGatewayConfigurationId int,
	 @rTitle nvarchar(150),
	 @rOrgGroupId int
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	BEGIN
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
	END
	
	SELECT 
			GP.Id,
			GP.GatewayConfigurationId,
			PGM.Title AS PaymentGatewayName,
			GP.Title AS GatewayProductName,
			ISNULL(GP.GatewayURL,'') AS GatewayURL,
			ISNULL(GP.ServerPort,'') AS ServerPort,
			ISNULL(GP.LoginId,'') AS LoginId,
			ISNULL(GP.LoginPassword,'') AS LoginPassword,
			ISNULL(GP.ProductId,'') AS ProductId,
			
			ISNULL(GP.CCAvenueMerchantID,'') AS CCAvenueMerchantID,
			ISNULL(GP.CCAvenueAccessCode,'') AS CCAvenueAccessCode,
			ISNULL(GP.CCAvenueWorkingKey,'') AS CCAvenueWorkingKey,
			ISNULL(GP.CCAvenueWhitelistURL,'') AS CCAvenueWhitelistURL,
			ISNULL(GP.CCAvenueSubAccountId,'') AS CCAvenueSubAccountId
	FROM 
			[sOp].[tGatewayProduct] GP
			INNER JOIN [sOp].[tGatewayConfiguration] GC ON GC.Id = GP.GatewayConfigurationId
			INNER JOIN [sOp].[tPaymentGatewayMaster] PGM ON PGM.Id = GC.PaymentGatewayId
	WHERE 
			(GC.OrgGroupId = @rOrgGroupId)
			AND	((GP.Id = @rId) OR (@rId = 0))
			AND	((GP.GatewayConfigurationId = @rGatewayConfigurationId) OR (@rGatewayConfigurationId = 0))
			AND ((GP.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
END
GO
PRINT N'Altering [sPayroll].[pPayrollCustomSearchGet]...';


GO
-- exec [sPayroll].[pPayrollCustomSearchGet]
-- drop proc [sPayroll].[pPayrollCustomSearchGet]
ALTER PROCEDURE [sPayroll].[pPayrollCustomSearchGet] 
	@rOrgId smallint,
	@rOrderBy nvarchar(max) = 'Code',
	@rCode [nvarchar](20) = '',
	@rFirstName [nvarchar](50) = '',	
	@rLastName[nvarchar](50) = '',
	@rEmployeeTypeId[nvarchar](50) = '',
	@rStatusId[nvarchar](50) = '',
	@rOrganizationDepartmentId[nvarchar](50) = '',
	@rReligionId[nvarchar](50) = '',
	@rMaritalStatusId[nvarchar](50) = '',
	@rQualification[nvarchar](50) = '',
	@rGenderId[nvarchar](50) = '',
	@rEmployeeDesignationId[nvarchar](50) = '',
	@rBloodGroupId[nvarchar](50) = '',
	@rEmployeeGroupId[nvarchar](50)='',
	@rDOBFromDate Date = '0001-01-01',
	@rDOBToDate Date = '9999-12-31',
	@rDOJFromDate Date = '0001-01-01',
	@rDOJToDate Date = '9999-12-31',
	@rDropDownStatusId int,
	@rPayrollId int,
	@rPageIndex int = null
AS
SET NOCOUNT ON
BEGIN
	DECLARE @Sql nvarchar(MAX)
	SET @rCode = sCommon.fSearchStringGet(@rCode)
	SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
	SET @rLastName = sCommon.fSearchStringGet(@rLastName)
	SET @rQualification = sCommon.fSearchStringGet(@rQualification)
	
	SELECT PCS.*
	into sPayroll.tTempPayroll1
	FROM sPayroll.vPayrollCustomSearch PCS
	WHERE ((PCS.OrgId = @rOrgId) OR (@rOrgId = 0))
	AND PCS.PayrollId = @rPayrollId
	AND ((PCS.Code Like @rCode + '%') OR (@rCode = ''))
	AND ((PCS.FirstName Like @rFirstName  + '%') OR (@rFirstName = ''))
	AND ((PCS.LastName Like @rLastName + '%')OR(@rLastName = ''))
	AND ((ISNULL(PCS.Qualification,'') Like @rQualification + '%')OR(@rQualification = ''))
	AND ((PCS.DateOfBirth >= @rDOBFromDate) OR (ISNULL(@rDOBFromDate,'') = ''))
	AND ((PCS.DateOfBirth <= @rDOBToDate) OR (ISNULL(@rDOBToDate,'') = ''))
	AND ((PCS.DateOfJoining >= @rDOJFromDate) OR (ISNULL(@rDOJFromDate,'') = ''))
	AND ((PCS.DateOfJoining <= @rDOJToDate) OR (ISNULL(@rDOJToDate,'') = ''))
	AND (ISNULL(PCS.OrganizationDepartmentId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrganizationDepartmentId,','))OR @rOrganizationDepartmentId='')
	AND (ISNULL(PCS.StatusId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rStatusId,','))OR @rStatusId='')
	AND (ISNULL(PCS.EmployeeTypeId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rEmployeeTypeId,','))OR @rEmployeeTypeId='')
	AND (ISNULL(PCS.EmployeeDesignationId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rEmployeeDesignationId,','))OR @rEmployeeDesignationId='')
	AND (ISNULL(PCS.EmployeeGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rEmployeeGroupId,','))OR @rEmployeeGroupId='')
	AND (ISNULL(PCS.BloodGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rBloodGroupId,','))OR @rBloodGroupId='')
	AND (ISNULL(PCS.ReligionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rReligionId,','))OR @rReligionId='')
	AND (ISNULL(PCS.MaritalStatusId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rMaritalStatusId,','))OR @rMaritalStatusId='')
	AND (ISNULL(PCS.GenderId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rGenderId,','))OR @rGenderId='')
	AND ((PCS.StatusId = @rDropDownStatusId) OR (@rDropDownStatusId=0))
	
	SET @rOrderBy=Replace(@rOrderBy,'Code','Code')
	SET @sql='SELECT EmployeeId,Code AS Code,Name,EmployeeType,
	OrganizationDepartment AS OrganizationDepartment,StatusName,
	OrgName,0 AS SalaryMonth
	FROM sPayroll.tTempPayroll1 ORDER BY '+@rOrderBy
	
	exec(@Sql)
	
	create table #TEMPPay
	(
		tid int identity(1,1),t_EmpId bigint
	)
	SET @sql='insert into #TEMPPay SELECT EmployeeId FROM sPayroll.tTempPayroll1 ORDER BY '+ @rOrderBy
	exec(@Sql)
	
	select @rPageIndex = case when isnull(@rPageIndex,0) = 0 then 1 else @rPageIndex end
	declare @lPageSize int = 10,@lTotalRecords int,@lPaging varchar(max)='',@lResult varchar(max)=''
	
	select @lTotalRecords = count(1) from #TEMPPay
	select @lPaging = @lPaging + dbo.fnc_SearchPagingFormat(@rPageIndex,@lTotalRecords,@lPageSize)
	
	select @lResult = @lResult + '<tr><td>' + isnull(OrgName,'') + '</td><td>' + isnull(OrganizationDepartment,'') + '</td>
	<td>' + isnull(Code,'') + '</td><td>' + isnull(Name,'') + '</td><td>' + isnull(EmployeeType,'') + '</td>
	<td>' + isnull(StatusName,'') + '</td></tr>'
	from sPayroll.tTempPayroll1,#TEMPPay where EmployeeId = t_EmpId
	and tid between ((@lPageSize * (@rPageIndex - 1)) + 1) AND (@lPageSize * @rPageIndex)
	
	select @lTotalRecords as TotalRecords,@lResult as EmpList,@lPaging as Paging
	
	DROP Table sPayroll.tTempPayroll1
END
GO
PRINT N'Altering [sStudent].[pGetDropDownLists]...';


GO
-- exec sStudent.pGetDropDownLists
-- drop proc sStudent.pGetDropDownLists
ALTER proc [sStudent].[pGetDropDownLists]
@rBatchId int,
@rOrgId int,
@rUserId bigint,
@rDepartmentId int
as
begin
	declare @lStatusRes varchar(max)='',@lClassRes varchar(max)='',@lEnrollmentStatusRes varchar(max)=''
	declare @lDepartmentRes varchar(max)='',@lDivisionRes varchar(max)='',@lAvailableRes varchar(max)=''
	declare @lReportList varchar(max)='',@lExamRes varchar(max)='',@lGeneralExamRes varchar(max)=''
	declare @lExamReportList varchar(max)=''
		
	select @lDivisionRes = @lDivisionRes + '<option value="0"> -- ALL -- </option>'
	
	select @lStatusRes = @lStatusRes + '<option value="0"> -- ALL -- </option>'
	select @lStatusRes = @lStatusRes + '<option value="1">Active</option>'
	select @lStatusRes = @lStatusRes + '<option value="2">InActive</option>'
	select @lStatusRes = @lStatusRes + '<option value="3">Left</option>'
	
	select @lClassRes = @lClassRes + '<option value="0"> -- ALL -- </option>'
	select @lClassRes = @lClassRes + '<option value="' + convert(varchar,ClassId) + '">' + ClassName + '</option>'
	from sSetup.vBatchClass where IsObsolete = 0 and BatchId = @rBatchId order by OrderIndex
	
	select @lEnrollmentStatusRes = @lEnrollmentStatusRes + '<option value="0"> -- ALL -- </option>'
	select @lEnrollmentStatusRes = @lEnrollmentStatusRes + '<option value="' + convert(varchar,Id) + '">' + Title + '</option>'
	from sStudent.tEnrollmentStatusMaster where IsObsolete = 0 order by Title
	
	select @lDepartmentRes = @lDepartmentRes + '<option value="0"> -- ALL -- </option>'
	select @lDepartmentRes = @lDepartmentRes + '<option value="' + convert(varchar,Id) + '">' + Title + '</option>'
	from sSetup.vDepartment where IsObsolete = 0 AND OrgId = @rOrgId and UserId = @rUserId
	and (Id = @rDepartmentId or @rDepartmentId = 0) order by Title
	
	select @lAvailableRes = @lAvailableRes + '<option value="' + COLUMN_NAME + '">' + COLUMN_NAME + '</option>'
	from INFORMATION_SCHEMA.COLUMNS where TABLE_SCHEMA='sStudent' AND TABLE_NAME='vStudentColumnName' AND COLUMN_NAME <> 'GR No'
	
	select @lGeneralExamRes = @lGeneralExamRes + '<option value="' + COLUMN_NAME + '">' + COLUMN_NAME + '</option>'
	from INFORMATION_SCHEMA.COLUMNS where TABLE_SCHEMA='sAssessment' AND TABLE_NAME='vGeneralExamColumnName'
	
	select @lReportList = @lReportList + '<tr><td style="width:100px; word-wrap:break-word;">' + SCS.Title + '</td>
	<td style="width:700px; word-wrap:break-word;">' + SCS.ColumnName + '</td>
	<td style="width:50px; word-wrap:break-word;"></td>
	<td style="width:100px; word-wrap:break-word;">' + U.DisplayTitle + '</td>	
	<td style="width:50px; word-wrap:break-word;"><a onclick="DeleteReport(' + convert(varchar,SCS.Id) + ');"><i class="fa fa-trash" aria-hidden="true"></i></a></td></tr>'
	from sStudent.tStudentCustomSearch SCS
	INNER JOIN sSecurity.tUser U ON U.Id=SCS.CreatedUserId
	WHERE (SCS.CreatedUserId = @rUserId OR SCS.IsCommon = 1)
	AND SCS.OrgId = @rOrgId
	
	select @lExamReportList = @lExamReportList + '<tr><td style="width:100px; word-wrap:break-word;">' + SCS.Title + '</td>
	<td style="width:700px; word-wrap:break-word;">' + SCS.ColumnName + '</td>
	<td style="width:50px; word-wrap:break-word;"></td>
	<td style="width:100px; word-wrap:break-word;">' + U.DisplayTitle + '</td>	
	<td style="width:50px; word-wrap:break-word;"><a onclick="DeleteReport(' + convert(varchar,SCS.Id) + ');"><i class="fa fa-trash" aria-hidden="true"></i></a></td></tr>'
	from sAssessment.tGeneralExamCustomSearch SCS
	INNER JOIN sSecurity.tUser U ON U.Id=SCS.CreatedUserId
	WHERE (SCS.CreatedUserId = @rUserId OR SCS.IsCommon = 1)
	AND SCS.OrgId = @rOrgId
	
	select @lExamRes = @lExamRes + '<option value="0"> -- ALL -- </option>'
	select @lExamRes = @lExamRes + '<option value="' + convert(varchar,Id) + '">' + Title + '</option>'
	from sAssessment.tExamSubGroupMaster where OrgId = @rOrgId
	
	select @lStatusRes as StatusRes,@lClassRes as ClassRes,@lDivisionRes as DivisionRes,
	@lEnrollmentStatusRes as EnrollStatusRes,@lDepartmentRes as DepartmentRes,
	@lAvailableRes as AvailableRes,@lReportList as ReportList,@lExamRes as ExamRes,
	@lGeneralExamRes as GeneralExamAvailRes,@lExamReportList as ExamReportList
end
GO
PRINT N'Altering [sStudent].[pRptStudentIcardGet]...';


GO


ALTER PROCEDURE [sStudent].[pRptStudentIcardGet]
	 
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rOrgId smallint,
	 @rBatchId int,
	 @rStrCode nvarchar(max),
	 @rClassId int,
	 @rDivisionId int,
	 @rStudentId bigint,
	 @rFromRollNo int,
	 @rToRollNo int,
	 @rStatusId int,
	 @rDateOfBirth int,
	 @rDepartmentId int,
	 @rHouseGroupId int=0,
	 @rIsShowBarcode bit=0,
	 @rOrgGroupBatchId int
	 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

DECLARE @lIcardBorder nvarchar(10)
DECLARE @lSUIdBarcode nvarchar(50)
--DECLARE @lIsBarcodeBasedOnSUId bit = 0
DECLARE @lOrgGroupId int = 0
Declare @lIDConfigValue nvarchar(50)=''
SELECT @lOrgGroupId=OrgGroupId FROM sSetup.tOrganizationMaster WHERE Id = @rOrgId

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

SELECT @lIcardBorder = ItemValue FROM sConfig.tConfigurationSetup WHERE configurationId = 130 AND SourceTypeId = 1016 AND SourceId = @rOrgId --ItemKey = 'sConfig.tConfigurationSetup' 
SELECT @lSUIdBarcode = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 168 AND SourceTypeId = 2010 AND SourceId = @lOrgGroupId
	
	--IF (@lSUIdBarcode IS NULL) OR (@lSUIdBarcode = 'False')
	--SET @lIsBarcodeBasedOnSUId = 0
	--ELSE
	--SET @lIsBarcodeBasedOnSUId = 1	
	
	SELECT			 
			SD.AcademicId,
			SD.StudentId, 
			SD.ClassId,
			SD.DivisionId,
			SD.ClassName,
			SD.DivisionName,
			SD.ClassDivision,
			SD.Batch,
			SD.Code,
			SD.Number AS StudentNumber,
			SD.RegistrationNumber,	
			SD.RollNo,				
			SD.FirstName,
			SD.MiddleName,			
			SD.LastName,
			[sStudent].[fStudentNameGet](SD.FirstName , SD.MiddleName, SD.LastName,OM.StudentNameFormatId ) AS Name,	
			--SD.FirstName + ' ' + SD.MiddleName + ' ' + SD.LastName As Name,		 
			SD.StatusId,
			SD.DateOfBirth,		
			SD.BloodGroup,
			ISNULL(SD.PresentStreetone,'') AS PresentStreetone,
			ISNULL(SD.PresentStreetTwo,'') AS PresentStreetTwo,
			ISNULL(SD.PresentStreetThree,'') AS PresentStreetThree,
		    ISNULL(SD.PresentCity,'') AS PresentCity,
		    ISNULL(SD.PresentZipCode,'') AS PresentZipCode,
			SD.PresentContactNo,						 
			SD.ParentContactNo AS ParentContactNo,
			SD.StudentContactNo,			
			SD.StudentPhoto,
			SD.AdmissionCategory, 
			SD.DivisionOrder,		 
			OM.Title AS OrgName,	
			ISNULL(HM.Title,'') AS HouseName,	
			OM.PrincipalSignature,
			ISNULL(ICO.ICardOrgTitle,'') AS ICardOrgTitle,
			ISNULL(ICO.ICardAddress1,'') AS ICardAddress1,
			ISNULL(ICO.ICardAddress2,'') AS ICardAddress2,
			ISNULL(ICO.ICardAddress3,'') AS ICardAddress3,			
			OM.OrgLogo AS ICardLogo,
			
			--ISNULL(ICO.ICardBackground,0) AS ICardBackground,	
			--ISNULL(ICO.ICardBackBackground,0) AS ICardBackBackground,	
			
			 ICO.ICardBackground  AS ICardBackground,	
			 ICO.ICardBackBackground  AS ICardBackBackground,						
			  
			ISNULL(ICO.LabelColor,'Black') AS LabelColor,
			ISNULL(ICO.DetailColor,'Black') AS DetailColor,
			ISNULL(ICO.HeaderColor,'Black') AS HeaderColor,
			ISNULL(SF.FatherName,'') AS FatherName,
			ISNULL(SF.FatherContactNo,'') AS FatherContactNo,
			ISNULL(SF.MotherName,'') AS MotherName,
			ISNULL(SF.MotherContactNo,'') AS MotherContactNo,
			ISNULL(RT.RouteName,'') AS RouteName,
			ISNULL(RT.PickupPoint,'') AS PickupPoint,
			ISNULL(RT.DropPoint,'') AS DropPoint,
			
			@lIcardBorder AS IcardBorder,
			HM.ColorCode,
			OM.OrgLogo,
			OM.SmallAddress1,
			--@lSUIdBarcode AS IsBarcodeBasedOnSUId,
			CASE WHEN @lSUIdBarcode = 'True' THEN SD.SUId  ELSE SD.Code END AS BarcodeNumber,
			 ISNULL(SD.EmergencyStreetOne,'') AS EmergencyStreetOne,
	         ISNULL(SD.EmergencyStreetTwo,'') AS EmergencyStreetTwo,
	        ISNULL(SD.EmergencyStreetThree,'') AS EmergencyStreetThree,
	        ISNULL(SD.EmergencyCountry,'') AS EmergencyCountry,
	        ISNULL(SD.EmergencyState,'') As EmergencyState,
	        ISNULL(SD.EmergencyCity,'') AS EmergencyCity,
	        ISNULL(SD.EmergencyZipCode,'') as EmergencyZipCode,
	        SD.EmergencyContactNo AS EmergencyContactNo,
			ISNULL(SD.SUId,'') As SUId,
			ISNULL(RT.RouteNumber,0) AS RouteNumber,
			@rIsShowBarcode As IsShowBarcode,
			SD.Name,
			SM.Title AS Stream,
			SD.AdmissionDate,
			ISNULL(DM.Title,'') AS DepartmentName,
			SD.FatherPhoto,
			SD.MotherPhoto,
			SD.RelativePhoto,
			@lIDConfigValue AS ItemValue 
			
	FROM 
			sStudent.vStudentAllDetail SD
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=SD.OrgId
			--INNER JOIN sStudent.tStudentOther SO ON SD.StudentId = So.StudentId 			
			LEFT JOIN sActivity.tHouseMaster HM ON SD.HouseId = HM.Id 
			LEFT JOIN sActivity.tHouseGroupMaster HGM ON HGM.Id=HM.HouseGroupId
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SD.StudentId 
			 LEFT JOIN
			(SELECT AT.SourceId,BRM.Title As RouteName,BRDM.Title As PickupPoint,ISNULL(BRM.RouteNumber,0) AS RouteNumber,ISNULL(BRDM1.Title,'')As DropPoint FROM sTransport.tAssignRoute AT 
			INNER JOIN sTransport.tBusRouteDestinationMaster BRDM ON BRDM.Id=AT.PickupDestinationId
			LEFT JOIN sTransport.tBusRouteDestinationMaster BRDM1 ON BRDM1.Id=AT.DropDestinationId
			INNER JOIN sTransport.tBusRouteMaster BRM ON BRM.Id=BRDM.BusRouteId AND  AT.SourceTypeId=2003 AND ((BRM.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))AND BRM.Id=BRDM1.BusRouteId) RT
			ON RT.SourceId = SD.StudentId AND ((SD.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
		 
			--LEFT JOIN sTransport.tAssignRoute AR ON AR.SourceId =SD.StudentId 
			--LEFT JOIN sTransport.tBusRouteDestinationMaster BRDM ON BRDM.Id =AR.PickupDestinationId 
			--LEFT JOIN sTransport.tBusRouteMaster BRM ON BRM.Id =BRDM.BusRouteId  AND(( BRM.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
			LEFT JOIN sStudent.tICardOrg ICO ON SD.OrgId = ICO.OrgId
			LEFT JOIN sSetup.tStreamMaster SM ON SM.Id=SD.StreamId
			LEFT JOIN sSetup.tDepartmentMaster DM ON DM.Id=SD.DepartmentId
			
			
	
			--LEFT JOIN sSetup.tOrganizationConfiguration OC ON OM.Id = OC.OrgId 
			
	WHERE 
		SD.OrgId=@rOrgId
		AND	SD.BatchId = @rBatchId 
		AND (ISNULL(SD.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rStrCode,',')) OR @rStrCode='') 
		AND ((SD.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SD.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((SD.StudentId=@rStudentId) OR (@rStudentId=0))
		AND ((SD.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((SD.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((SD.StatusId=@rStatusId)OR(@rStatusId=0))
		AND ((SD.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		AND ((HGM.Id=@rHouseGroupId)OR(@rHouseGroupId=0))
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,
	 @rDateOfBirth int,
	 @rDepartmentId int
	 
	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
	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= @rBatchId
			
	WHERE 
			SD.OrgId=@rOrgId
		AND	SD.BatchId = @rBatchId 
		AND (ISNULL(SD.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rStrCode,',')) OR @rStrCode='') 
		AND ((SD.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SD.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((SD.StudentId=@rStudentId) OR (@rStudentId=0))
		AND ((SD.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((SD.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((SD.StatusId=@rStatusId)OR(@rStatusId=0))
		AND ((MONTH(SD.DateOfBirth)=@rDateOfBirth OR @rDateOfBirth=0))
	    AND ((SD.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
	 Order by
	 SD.RollNo
END
GO
PRINT N'Altering [sStudent].[pRptStudentStrengthDivisionWiseGet]...';


GO


 
ALTER PROCEDURE [sStudent].[pRptStudentStrengthDivisionWiseGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rOrgId smallint,
	 @rBatchId int,
	 @rClassId int,
	 @rDivisionId int,
	 @rDepartmentId int,
	 @rStudentCode varchar(20)='',
	 @rReportId int=0,
	 @rOrggroupBatchID int=0
	 ,@rAsOnDate Date 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
  DECLARE @lCount Int
	SELECT 
	
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			CM.DisplayTitle AS Class,
			DM.DisplayTitle AS Division,
			A.ClassId,
			A.DivisionId,
			CM.DisplayTitle+' - '+DM.DisplayTitle AS ClassDivision,
			DM.OrderIndex AS DivisionOrder,
			Cm.OrderINdex AS ClassOrderIndex  ,
		    ISNUll(AR.SourceId,0) AS HostelStudent,
			ISNUll(RT.SourceId,0) AS TransportStudent,
			A.StudentId 
			FROM 
			sStudent.tAcademic A		
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId	
			LEFT JOIN sStudent.tStudentOther SO ON A.StudentId=SO.StudentId
			LEFT JOIN sStudent.tStudentAdmission SA ON SA.StudentId=A.StudentId
			LEFT JOIN sCommon.tGenderMaster GM ON GM.Id=SO.GenderId
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
			LEFT JOIN sCommon.tCastCategoryMaster CCM ON CCM.Id=SO.CastCategoryId
			LEFT JOIN sCommon.tReligionMaster RM ON RM.Id=SO.ReligionId
			LEFT JOIN sCommon.tBloodGroupMaster BGM ON BGM.Id=SO.BloodGroupId
			LEFT JOIN sStudent.tAdmissionCategoryMaster SCM ON SCM.Id=SM.AdmissionCategoryId
			LEFT JOIN sHostel.tAssignRoom AR ON AR.SourceId=A.StudentId AND AR.SourceTypeId=2003 
			AND  ((AR.OrggroupBatchID=@rOrggroupBatchID) OR (@rOrggroupBatchID=0))
			 LEFT JOIN
			(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
			INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
			INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
			ON RT.SourceId = A.StudentId
			INNER JOIN sSetup.tBatchClass BC ON BC.ClassID =  CM.Id and BC.BatchId= @rBatchId
    
	WHERE 
		A.OrgId=@rOrgId
		AND	A.BatchId = @rBatchId 
		AND ((A.ClassId=@rClassId) OR (@rClassId=0))
		AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		--AND SM.StatusId = 1
		AND ((SM.Code=@rStudentCode) OR (@rStudentCode=''))
		AND ((CM.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		AND ((SA.LeftDate > @rAsOnDate) OR (SA.LeftDate Is null AND SM.StatusId = 1))
	   END
GO
PRINT N'Altering [sStudent].[pStudentDocumentSubmitGet]...';


GO

ALTER PROCEDURE [sStudent].[pStudentDocumentSubmitGet]
	 
        @rStudentId bigint,
		@rOrgId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
 
	BEGIN
			SELECT Isnull(D.Id,0) AS DocumentId,ISNULL(D.DocumentName,'') AS DocumentName,
			CASE WHEN  S.SubmitDocumentMasterId Is null THEN 'False' ELSE 'True'END AS IsCheck
		 	FROM sCommon.tSubmitDocumentMaster D
			LEFT Join sStudent.tStudentDocument  S ON S.SubmitDocumentMasterId=D.id AND S.StudentId=@rStudentId
			WHERE OrgId=@rOrgId AND SubmitDocumentFunctionalityId='1'
END
GO
PRINT N'Altering [sStudent].[pXMLStudentImportAdd]...';


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

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

	BEGIN TRY
	BEGIN TRANSACTION
	DECLARE @lCount INT
	DECLARE @lNextNumber BIGINT 
	Declare @lExistCode nvarchar(max)
	DECLARE @MaxCode AS bigint
	
 
 
	IF EXISTS(SELECT SM.Code
	from
	(
			SELECT StudentId FROM
			OPENXML (@loDoc, '/Table/StudentImportDetail', 1)
			WITH (
					StudentId bigint)	
	)E
	INNER JOIN sStudent.tStudentMaster SM ON SM.ReferenceSourceId=E.StudentId AND SM.OrgId=@rToOrgId	
	)
	BEGIN
		SELECT @lExistCode  = COALESCE(@lExistCode ,'') + CONVERT(VARCHAR(15),E.Code) + ' , ' 
		from
		(
				SELECT StudentId,Code FROM
				OPENXML (@loDoc, '/Table/StudentImportDetail', 1)
				WITH (
						StudentId bigint,
						Code nvarchar(20)
						)
		)E
		INNER JOIN sStudent.tStudentMaster SM ON SM.ReferenceSourceId=E.StudentId AND SM.OrgId=@rToOrgId	
		SELECT @lExistCode
		RETURN
	END
	
	
	EXECUTE sCommon.pTableRowIdGet @rToOrgId, 'sStudent.tStudentMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	SELECT @MaxCode = MAX(Number) FROM sStudent.tStudentMaster WHERE OrgId = @rToOrgId
	--SET @MaxCode = ISNULL(@MaxCode,0) + 1
	
	SELECT 
			@lNextNumber + ROW_NUMBER() OVER(ORDER BY E.StudentId)AS NewStudentId,
			E.StudentId,
			ISNULL(@MaxCode,0) + ROW_NUMBER() OVER(ORDER BY E.StudentId)AS Code
	INTO 
			sStudent.tTempStudentId
	from
	(
			SELECT StudentId FROM
			OPENXML (@loDoc, '/Table/StudentImportDetail', 1)
			WITH (
					StudentId bigint)	
	)E

	SELECT @lCount = COUNT(1) FROM OPENXML (@loDoc, '/Table/StudentImportDetail', 1)
				 WITH ( Id int )
	SET @lNextNumber  = @lCount + @lNextNumber 
	
	EXECUTE sCommon.pTableRowIdModify @rToOrgId, @rTableTitle = 'sStudent.tStudentMaster', @rCurrentNumber = @lNextNumber 
		
	--Insert Into Student Master
	INSERT INTO sStudent.tStudentMaster
	(
			Id,
			Code,
			Number,
			FirstName,
			MiddleName,
			LastName,
			OrgId,
			StatusId,
			RecordStatusId,
			CreatedUserId,
			CreatedDateTime,
			ReferenceSourceId,
			AdmissionCategoryId,
			RegistrationNumber,
			IsBlackList,
			BlackListReason,
			SUId
		
	)
	SELECT 
			TS.NewStudentId,
			TS.Code,
			TS.Code,
			SM.FirstName,
			SM.MiddleName,
			SM.LastName,
			@rToOrgId,
			1,
			502,
			@rCreatedUserId,
			sCommon.fGetDate(),
			TS.StudentId,
			SM.AdmissionCategoryId,
			SM.RegistrationNumber,
			SM.IsBlackList,
			SM.BlackListReason,
			SM.SUId
	FROM
			sStudent.tTempStudentId TS	
		INNER JOIN sStudent.tStudentMaster SM ON SM.ID=TS.StudentId
		
	--Insert Into Academic
		
	EXECUTE sCommon.pTableRowIdGet @rToOrgId, 'sStudent.tAcademic', 0, 1, 1,@outNextNumber = @lNextNumber output
 
	INSERT INTO sStudent.tAcademic
	(
			Id,
			StudentId,
			ClassId,
			BatchId,
			DivisionId,
			RollNo,
			OrgId,
			CreatedUserId,
			CreatedDateTime
	)
	SELECT
			@lNextNumber+ ROW_NUMBER() OVER(ORDER BY StudentId),
			NewStudentId,
			@rToClassId,
			@rToBatchId,
			@rToDivisionId,
			0,
			@rToOrgId,
			@rCreatedUserId,
			sCommon.fGetDate()
	FROM 
			sStudent.tTempStudentId
		
	SELECT @lCount = COUNT(1) FROM OPENXML (@loDoc, '/Table/StudentImportDetail', 1)
			 WITH ( Id int )
	SET @lNextNumber  = @lCount + @lNextNumber 
	
	EXECUTE sCommon.pTableRowIdModify @rToOrgId, @rTableTitle = 'sStudent.tAcademic', @rCurrentNumber = @lNextNumber 
	
	--Insert Into Student Other
	INSERT INTO sStudent.tStudentOther
	(
		   [StudentId]
		  ,[UIDNumber]
		  ,[DateOfBirth]
		  ,[BirthDateInWord]
		  ,[TransportModeId]
		  ,[GenderId]
		  ,[BloodGroupId]
		  ,[BirthPlace]
		  ,[BirthTaluka]
		  ,[BirthDistrict]
		  ,[FamilyCast]
		  ,[FamilySubCast]
		  ,[CastCategoryId]
		  ,[ReligionId]
		  ,[HouseId]
		  ,[MotherTongueId]
		  ,[NationalityId]
		  ,[Hobby]		   
		  ,[CreatedUserId]
		  ,[CreatedDateTime]
		  ,ReferenceRemark
		  ,AdhaarNumber
		  ,MotherTongue
		  ,QuotaId
	)
	SELECT 
		   TS.NewStudentId
		  ,SO.[UIDNumber]
		  ,SO.[DateOfBirth]
		  ,SO.[BirthDateInWord]
		  ,SO.[TransportModeId]
		  ,SO.[GenderId]
		  ,SO.[BloodGroupId]
		  ,SO.[BirthPlace]
		  ,SO.[BirthTaluka]
		  ,SO.[BirthDistrict]
		  ,SO.[FamilyCast]
		  ,SO.[FamilySubCast]
		  ,SO.[CastCategoryId]
		  ,SO.ReligionId		   
		  ,NULL
		  ,so.MotherTongueId
		  ,So.NationalityId		 
		  ,SO.[Hobby] 
		  ,@rCreatedUserId
		  ,sCommon.fGetDate()
		  ,ReferenceRemark
		  ,AdhaarNumber
		  ,MotherTongue
		  ,QuotaId
	FROM
			sStudent.tTempStudentId TS	
		INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=TS.StudentId
	
	--Insert Into Student Admission
	INSERT INTO sStudent.tStudentAdmission
	(
		   [StudentId]
		  ,[PreviousStudentId]
		  ,[AdmissionStandardId]
		  ,[AdmissionDate]
		  ,[AdmissionYear]
		  ,[BatchId]
		  ,[CreatedUserId]
		  ,[CreatedDateTime]
		  ,PreviousSchool
	)
	SELECT 
		   TS.NewStudentId
		  ,TS.StudentId
		  ,@rToClassId
		  ,@rAdmissionDate
		  ,YEAR(GETDATE())
		  ,@rToBatchId
		  ,@rCreatedUserId
		  ,sCommon.fGetDate()
		  ,PreviousSchool
	FROM
			sStudent.tTempStudentId TS	
		INNER JOIN sStudent.tStudentAdmission SA ON SA.StudentId=TS.StudentId
	
	
INSERT INTO [sStudent].[tStudentCommunication]
           ([StudentId]
           ,[PresentStreetOne]
           ,[PresentStreetTwo]
           ,[PresentStreetThree]
           ,[PresentCountry]
           ,[PresentState]
           ,[PresentCity]
           ,[PresentZipCode]
           ,[PresentContactNo]
           ,[PermanentStreetOne]
           ,[PermanentStreetTwo]
           ,[PermanentStreetThree]
           ,[PermanentCountry]
           ,[PermanentState]
           ,[PermanentCity]
           ,[PermanentZipCode]
           ,[PermanentContactNo]
           ,[EmergencyStreetOne]
           ,[EmergencyStreetTwo]
           ,[EmergencyStreetThree]
           ,[EmergencyCountry]
           ,[EmergencyState]
           ,[EmergencyCity]
           ,[EmergencyZipCode]
           ,[EmergencyContactNo]
           ,[ParentContactNo]
           ,[ParentEmail]
           ,[StudentContactNo]
           ,[StudentEmail]
           ,[CreatedUserId]
           ,[CreatedDateTime])
 
 SELECT 
			TS.NewStudentId
           ,[PresentStreetOne]
           ,[PresentStreetTwo]
           ,[PresentStreetThree]
           ,[PresentCountry]
           ,[PresentState]
           ,[PresentCity]
           ,[PresentZipCode]
           ,[PresentContactNo]
           ,[PermanentStreetOne]
           ,[PermanentStreetTwo]
           ,[PermanentStreetThree]
           ,[PermanentCountry]
           ,[PermanentState]
           ,[PermanentCity]
           ,[PermanentZipCode]
           ,[PermanentContactNo]
           ,[EmergencyStreetOne]
           ,[EmergencyStreetTwo]
           ,[EmergencyStreetThree]
           ,[EmergencyCountry]
           ,[EmergencyState]
           ,[EmergencyCity]
           ,[EmergencyZipCode]
           ,[EmergencyContactNo]
           ,[ParentContactNo]
           ,[ParentEmail]
           ,[StudentContactNo]
           ,[StudentEmail]
           ,@rCreatedUserId
           ,sCommon.fGetDate()
        
	FROM
			sStudent.tTempStudentId TS	
		INNER JOIN [sStudent].[tStudentCommunication] SA ON SA.StudentId=TS.StudentId          
	
	
	
	INSERT INTO  [sStudent].[tStudentFamily]
           ([StudentId]
           ,[FatherName]
           ,[FatherDateOfBirth]
           ,[FatherOccupation]
           ,[FatherQualification]
           ,[FatherContactNo]
           ,[FatherMail]
           ,[FatherOfficeAddress]
           ,[FatherIncome]
           ,[MotherName]
           ,[MotherDateOfBirth]
           ,[MotherOccupation]
           ,[MotherQualification]
           ,[MotherContactNo]
           ,[MotherMail]
           ,[MotherOfficeAddress]
           ,[MotherIncome]
           ,[RelationshipName]
           ,[RelativeName]
           ,[RelativeDateOfBirth]
           ,[RelativeOccupation]
           ,[RelativeQualification]
           ,[RelativeContactNo]
           ,[RelativeMail]
           ,[RelativeOfficeAddress]
           ,[RelativeIncome]
           ,[CreatedUserId]
           ,[CreatedDateTime]
           ,[FatherPhoto]
           ,[MotherPhoto]
           ,[RelativePhoto]
           ,[MarriageAnniversaryDate])
     SELECT    
			TS.NewStudentId
           ,[FatherName]
           ,[FatherDateOfBirth]
           ,[FatherOccupation]
           ,[FatherQualification]
           ,[FatherContactNo]
           ,[FatherMail]
           ,[FatherOfficeAddress]
           ,[FatherIncome]
           ,[MotherName]
           ,[MotherDateOfBirth]
           ,[MotherOccupation]
           ,[MotherQualification]
           ,[MotherContactNo]
           ,[MotherMail]
           ,[MotherOfficeAddress]
           ,[MotherIncome]
           ,[RelationshipName]
           ,[RelativeName]
           ,[RelativeDateOfBirth]
           ,[RelativeOccupation]
           ,[RelativeQualification]
           ,[RelativeContactNo]
           ,[RelativeMail]
           ,[RelativeOfficeAddress]
           ,[RelativeIncome]
           ,@rCreatedUserId
           ,sCommon.fGetDate()
           ,[FatherPhoto]
           ,[MotherPhoto]
           ,[RelativePhoto]
           ,[MarriageAnniversaryDate]
   	FROM
			sStudent.tTempStudentId TS	
		INNER JOIN sStudent.tStudentFamily SA ON SA.StudentId=TS.StudentId    


INSERT INTO  [sStudent].[tStudentHealth]
           ([StudentId]
           ,[IdentificationMark1]
           ,[IdentificationMark2]
           ,[IsPysicalDeformity]
           ,[PysicalDeformityRemark]
           ,[IsMajorIllness]
           ,[MajorIllnessRemark]
           ,[IsAllergy]
           ,[AllergyRemark]
           ,[IsPastHistory]
           ,[PastHistoryRemark]
           ,[FamilyDoctorName]
           ,[FamilyDoctorContactNo]
           ,[UpdatedUserId]
           ,[UpdatedDateTime])
SELECT

			TS.NewStudentId
           ,[IdentificationMark1]
           ,[IdentificationMark2]
           ,[IsPysicalDeformity]
           ,[PysicalDeformityRemark]
           ,[IsMajorIllness]
           ,[MajorIllnessRemark]
           ,[IsAllergy]
           ,[AllergyRemark]
           ,[IsPastHistory]
           ,[PastHistoryRemark]
           ,[FamilyDoctorName]
           ,[FamilyDoctorContactNo]
           ,@rCreatedUserId
           ,sCommon.fGetDate()

   	FROM
			sStudent.tTempStudentId TS	
		INNER JOIN sStudent.tStudentHealth SA ON SA.StudentId=TS.StudentId 
		
		
		INSERT INTO  [sStudent].[tStudentImages]
           ([StudentId]
           ,[StudentPhoto]
           ,[FatherPhoto]
           ,[MotherPhoto]
           ,[RelativePhoto]
           ,[UpdatedDateTime])
           
           SELECT           
            TS.NewStudentId
           ,[StudentPhoto]
           ,[FatherPhoto]
           ,[MotherPhoto]
           ,[RelativePhoto]
           ,sCommon.fGetDate()
         	FROM
			sStudent.tTempStudentId TS	
		INNER JOIN sStudent.tStudentImages SA ON SA.StudentId=TS.StudentId      
	    
	    -- for update hostel 
	    -- Start
		--UPDATE A SET A.SourceId = T.NewStudentId 
		--FROM sHostel.tAssignRoom A JOIN sStudent.tTempStudentId T ON A.SourceId = T.StudentId AND A.SourceTypeId = 2003
		
		--UPDATE A SET A.SourceId = T.NewStudentId 
		--FROM sHostel.tAssignRoomAsset A JOIN sStudent.tTempStudentId T ON A.SourceId = T.StudentId AND A.SourceTypeId = 2003
		
		--UPDATE A SET A.StudentId = T.NewStudentId 
		--FROM sHostel.tAttendanceRegister A JOIN sStudent.tTempStudentId T ON A.StudentId = T.StudentId
		
		--UPDATE A SET A.SourceId = T.NewStudentId 
		--FROM sHostel.tChangeRoom A JOIN sStudent.tTempStudentId T ON A.SourceId = T.StudentId AND A.SourceTypeId = 2003
		
		--UPDATE A SET A.SourceId = T.NewStudentId 
		--FROM sHostel.tHostelAdmission A JOIN sStudent.tTempStudentId T ON A.SourceId = T.StudentId AND A.SourceTypeId = 2003
		
		--UPDATE A SET A.StudentId = T.NewStudentId 
		--FROM sHostel.tHostelDepositAdd A JOIN sStudent.tTempStudentId T ON A.StudentId = T.StudentId
		
		--UPDATE A SET A.StudentId = T.NewStudentId 
		--FROM sHostel.tHostelDepositAdjustment A JOIN sStudent.tTempStudentId T ON A.StudentId = T.StudentId
		
		--UPDATE A SET A.StudentId = T.NewStudentId 
		--FROM sHostel.tHostelDepositRefund A JOIN sStudent.tTempStudentId T ON A.StudentId = T.StudentId
		
		--UPDATE A SET A.StudentId = T.NewStudentId 
		--FROM sHostel.tStudentGatePass A JOIN sStudent.tTempStudentId T ON A.StudentId = T.StudentId
		
		--UPDATE A SET A.WhomToMeetSourceId = T.NewStudentId 
		--FROM sHostel.tVisitorGatePass A JOIN sStudent.tTempStudentId T ON A.WhomToMeetSourceId = T.StudentId AND WhomToMeetSourceTypeId = 2003
		-- End
		
		
		-- for update transport
		-- Start
		--UPDATE A SET A.SourceId = T.NewStudentId 
		--FROM sTransport.tAssignRoute A JOIN sStudent.tTempStudentId T ON A.SourceId = T.StudentId AND A.SourceTypeId = 2003
		
		--UPDATE A SET A.SourceId = T.NewStudentId 
		--FROM sTransport.tAttendanceRegister A JOIN sStudent.tTempStudentId T ON A.SourceId = T.StudentId AND A.SourceTypeId = 2003
		-- End
		
		-- for update Library
		-- Start
		UPDATE A SET A.ReaderSourceId = T.NewStudentId 
		FROM sLibrary.tBookLog A JOIN sStudent.tTempStudentId T ON A.ReaderSourceId = T.StudentId AND A.ReaderSourceTypeId = 2003
		
		UPDATE A SET A.SourceId = T.NewStudentId 
		FROM sLibrary.tLibraryAttendance A JOIN sStudent.tTempStudentId T 
		ON A.SourceId = T.StudentId AND A.SourceTypeId = 2003
		-- End
		
		-- for update Canteen
		-- Start
		UPDATE A SET A.SourceId = T.NewStudentId 
		FROM sCanteen.tCanteenIssue A JOIN sStudent.tTempStudentId T 
		ON A.SourceId = T.StudentId AND A.SourceTypeId = 2003
		
		-- End
	
	DROP TABLE sStudent.tTempStudentId
	
    SELECT 1 AS Result
	
	COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT Error_message()
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Creating [dbo].[spInsertQuarterlyData]...';


GO
CREATE PROC dbo.spInsertQuarterlyData 
   @Dt datetime
AS

DECLARE @CurrQtrDt DATETIME
DECLARE @RangeStartDt DATETIME
DECLARE @RangeEndDt DATETIME

SELECT @CurrQtrDt = DATEADD(qq, DATEDIFF(qq, 0, @Dt), 0)
SELECT @RangeStartDt = DATEADD(mm,-15,@CurrQtrDt)
SELECT @RangeEndDt = DATEADD(dd,-1,DATEADD(mm,-3,@CurrQtrDt))

INSERT INTO QtrData( ID, Qtr, Yr, Metric )
SELECT 
   ID,
   DATEPART(qq,@CurrQtrDt)-1,
   DATEPART(yyyy,@CurrQtrDt),
   SUM(Metric)
FROM Table_1
WHERE [Month] BETWEEN @RangeStartDt AND @RangeEndDt
GROUP BY ID
GO
PRINT N'Creating [sAcademic].[pRptLessonPlanAddGet]...';


GO
CREATE PROCEDURE [sAcademic].[pRptLessonPlanAddGet]

	 
	 @rClassId int,
	 @rSubjectId int,
	 @rDivisionId int,
	 @rIsCompleted bit ,
	 @rBatchId int,
	 @rEmployeeId bigint,
	 @rOrgId smallint ,
	 @rId  bigint
	
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	
	SELECT 
			LP.Id,
			TM.ClassId,
			LP.DivisionId,
			TM.SubjectId,
			LP.TopicId,
			LP.NoOfPeriodRequired,
			LP.Objective,
			LP.IndicativeHomework,
			LP.Summary,
			LP.StartDate,
			LP.EndDate,
			LP.IsCompleted,
			LP.EmployeeId,
			LP.BatchId,
			LP.CreatedUserId,
			LP.CreatedDateTime,
			TM.Title AS TopicName,
			vTSD.ClassTitle+' - '+ vTSD.DivisionTitle AS ClassDivisionName,
			vTSD.SubjectName,
			--ISNULL(EM.FirstName,'') + ' ' + ISNULL(EM.LastName,'') AS  EmployeeName,
			LP.LearningExperience,
			LP.ToolsAndTechniques,
			LP.EssentialMaterial ,
			LP.AssessmentQuestion ,
			LP.TeacherExample,
			LP.GuidedPractice,
			LP.IndependentPractice,
			
			----lesson plan
			
			
			--- lesson plan fuction
			
		   ISNULL(DFl.IsObjective,0)AS IsObjective,
		   ISNULL(DFl.IsSummary,0)AS IsSummary,
		   ISNULL(DFl.IsLearningExperience,0)AS IsLearningExperience,
		   ISNULL(DFl.IsEssentialMaterial,0)AS IsEssentialMaterial,
		   ISNULL(DFl.IsToolsTechniques,0)AS IsToolsTechniques,
		   ISNULL(DFl.IsIndicativeHomework,0)AS IsIndicativeHomework,
		   ISNULL(DFl.IsAssessmentQuestion,0)AS IsAssessmentQuestion,
		   ISNULL(DFl.IsTeacherExample,0)AS IsTeacherExample,
		   ISNULL(DFl.IsGuidedPractice,0)AS IsGuidedPractice,
		   ISNULL(DFl.IsIndependentPractice,0)AS IsIndependentPractice
		 
	
	FROM 
			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
			 LEFT JOIN sConfig.fDisplayFieldLessionGet(@rOrgId) AS DFl ON DFl.OrgId=vTSD.OrgId
			--AND vTSD.ClassId = TM.ClassId 
			--AND vTSD.SubjectId = TM.SubjectId 
			--AND vTSD.EmployeeId = LP.EmployeeId
	WHERE 
		(LP.BatchId = @rBatchId) 
		AND ((LP.EmployeeId = @rEmployeeId) OR (@rEmployeeId = 0))
		AND ((LP.Id = @rId) OR (@rId = 0))
		AND ((TM.ClassId = @rClassId) OR (@rClassId = 0))
		AND ((vTSD.DivisionId = @rDivisionId) OR (@rDivisionId = 0))
		AND ((TM.SubjectId = @rSubjectId) OR (@rSubjectId = 0))
		AND ((LP.IsCompleted='False') OR (LP.IsCompleted=@rIsCompleted))
		AND((DFl.OrgId=@rOrgId) OR (@rOrgId = 0))
		
		
		
END
GO
PRINT N'Creating [sAcademic].[pRptLessonPlanYearlyGet]...';


GO
CREATE PROCEDURE [sAcademic].[pRptLessonPlanYearlyGet]

	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 

--declare @startdate datetime = '2018-01-01'
--declare @enddate datetime = '2018-12-01'

--declare @tmp table(mnt nvarchar(50),[days] int,[year] int,Objective nvarchar(1000))

--while (@startdate<=@enddate)
--begin
--	insert into @tmp values (datename(MONTH,@startdate),datediff(day, @startdate, dateadd(month, 1, @startdate)),year(@startdate),null)
--	set @startdate = DATEADD(month,1,@startdate)
--end
--select * from @tmp

declare @startdate datetime = '2018-01-01'
declare @enddate datetime = '2018-12-01'
SElect datepart(MONTH,Lp.StartDate) AS MonthId,datename(MONTH,Lp.StartDate) AS MONTH,LP.Objective,StartDate,EndDate
 from sAcademic.tLessonPlan LP
 WHERE StartDate between @startdate AND @enddate
 ORDER BY  datepart(MONTH,Lp.StartDate)  


END
--EXEC [sAcademic].[pRptLessonPlanYearlyGet]
GO
PRINT N'Creating [sAssessment].[pGenerateResultSheetStandardMultiExam]...';


GO

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

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
 begin
 

  --select * from sAssessment.tTempAllExam
-- --drop table sAssessment.tTempAllExam

 
  
DECLARE @GradeString nvarchar(1000)
DECLARE @GradeStringRemark nvarchar(500),
@GradeSetId int , @IsIncludeSubExam bit,@GradeStringHtml nvarchar(500)
SELECT @GradeSetId = GradesetId,
	   @IsIncludeSubExam = ISNULL(IsIncludeSubExam,0)  FROM sAssessment.tExamMaster WHERE Id = @rExamId
SELECT @GradeString = [sAssessment].[fGradeStringGet](@GradeSetId)

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

 

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

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


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

		ISNULL(EM.Remark1,'') AS Remark1,
		ISNULL(EM.Remark2,'') AS Remark2,
		ISNULL(EM.Remark3,'') AS Remark3,
		EM.DisplayTitle,
		EM.IsRankNo, 
		EM.IsGrade,
		EM.IsPercentile,
		EM.IsPercentage,
		EM.IsSubjectPercentile,
		EM.IsProcessResult,
		EM.IsNegativeMarks,
		EM.IsIncludeCoScholastic,
		EM.IsOnPrePrinted,
		EM.IsDisplayPhoto,
		EM.IsDisplayBirthDate,
		EM.IsLockForEdit,
		EM.IsDisplaySchoolName,			
		EM.IsDisplayAttendance,
		EM.IsDisplayHeightWeight,
		EM.IsResultStatus,
		REPLICATE(',',EM.FooterAdjustment) AS FooterAdjustmentText,
		REPLICATE(',',EM.DetailAdjustment) AS DetailAdjustmentText,
		EM.FooterAdjustment,
		EM.DetailAdjustment,
		ISNULL(R.ResultRemark,'') AS ResultRemark,
		SO.DateOfBirth,
		AD.HeightTerm1,
		AD.WeightTerm1,
		AD.HeightTerm2,
		AD.WeightTerm2,
		AD.HeightAnnual,
		AD.WeightAnnual,
		AD.PresentDaysTerm1,
		AD.PresentDaysTerm2,
		AD.PresentDaysAnnual,
		AD.TotalDaysTerm1,
		AD.TotalDaysTerm2,
		AD.TotalDaysAnnual,
		EM.TermScopeId,
		(CASE EM.IsDisplayPhoto WHEN 1 THEN
			SI.StudentPhoto
		ELSE NULL END)AS StudentPhoto,
		CASE @GradeStringRemark WHEN '' THEN @GradeString ELSE @GradeStringRemark END AS GradeString,
		EM.IsDisplayGradeString,
		ED.IsDisplayInMarksheet,
		ED.IsShowSubjectGrade,
		ED.IsIncludeInTotal,
	    ED.ClassSubjectId,
		CS.SubjectId AS SubjectId,
		--ED.Maximum,
		(CASE ISNULL(ED.DisplayOrder,0)
		WHEN 0 THEN CS.OrderIndex
		ELSE ED.DisplayOrder END) AS SubjectOrderIndex,
		
		--SM.OrderIndex AS SubjectOrderIndex,
		RD.SubjectGrade,
		SM.Title AS SubjectName,
		ISNULL(SM.Code,'') AS SubjectCode,
		ED.Minimum,
		ED.Maximum,
		RD.Obtain,
		SR.ResultRemark1,
		SR.ResultRemark2,
		SR.TotalDays,
		SR.PresentDays,
		SR.StudentHeight,
		SR.StudentWeight,
		SR.ExamSeatNo,
		@rExamId,
		ISNULL(ESGM.Code,'') AS ExamCode,
		EM.IsDisplayParentName,
		SF.FatherName,
		SF.MotherName,
		ED.IsShowSubjectMark,
		--EMP.FirstName
		(CASE ISNULL(OS.AcademicId,0)
		WHEN 0 THEN 0
		ELSE 1 END) AS IsOptionalSubject,
		EM.CoScholasticScopeId,
		EM.IsDisplayPrincipalSign,
		Em.IsDisplayTeacherSign,
		(CASE Em.IsDisplayTeacherSign WHEN 1 THEN
			EI.EmployeeSign
			ELSE NULL END ) AS EmployeeSign,
		BM.Title AS Batch,
		EMP.FirstName + ' ' + EMP.LastName AS ClassTeacherName,
		Stum.FirstName,
		Stum.LastName,
		 
		ISNULL(EM.IsDisplayMonthlyAttendance,0) AS IsDisplayMonthlyAttendance,
		(CASE EM.IsDisplayImageHeader WHEN 1 THEN
			OI.CertificateHeaderA4 
			ELSE NULL END)AS  MarksheetHeaderA4,
		ISNULL(EM.IsDisplayImageHeader,0) AS IsImageHeader,
		ISNULL(SR.MyGoal,'') AS MyGoal,
		ISNULL(SR.AreaOfInterest,'') AS AreaOfInterest,
		ISNULL(SR.Responsibility,'') AS Responsibility,
		ISNULL(SR.MyInterestHobby,'') AS MyInterestHobby,
		ISNULL(SR.MyStrength,'') AS MyStrength,
		ISNULL(SR.Achievements,'') AS Achievements,
		ISNULL(SR.DentalHygiene,'') AS DentalHygiene,
		ISNULL(SR.VisionLeft,'') AS VisionLeft,
		ISNULL(SR.VisionRight,'') AS VisionRight,
		@rIsDetail AS IsDetail,
		ISNULL(SM.SubjectGroupId,0) AS SubjectGroupId,
		ISNULL(SG.Title,'')AS SubjectGroupTitle,
		ISNULL(SG.Code,'') AS SubjectGroupCode,
		ISNULL(EM.DecimalFormat,0) AS DecimalFormat,
		ISNULL(RD.Remark,'') AS SubjectRemark,
		RD.GraceMark,
		@GradeStringHtml,
		SR.ResultRemark3,
		EM.IsDisplayTotalMark,
		ISNULL(SC.ParentContactNo,'') AS ContactNo,
		ISNULL(SC.PresentStreetOne,'')+' '+ISNULL(SC.PresentStreetTwo,'')+' '+ISNULL(SC.PresentStreetThree,'')+' '+ISNULL(SC.PresentCity,'')+' '+ISNULL(SC.PresentState,'') AS PresentAddress,
		ISNULL(EM.TeacherSignCaption,'') AS TeacherSignCaption,
		ISNULL(EM.PrincipalSignCaption,'') AS PrincipalSignCaption,
		ISNULL(Em.ParentSignCaption,'') As ParentSignCaption,
		ISNULL(SR.ImprovementArea,'') As ImprovementArea,
		ISNULL(SR.ProgressArea,'') AS ProgressArea,
		ISNULL(SR.GeneralRemark,'') As GeneralRemark,
		ISNULL(SR.MyActivity,'') AS MyActivity,
		ISNULL(SR.ClassTeacherRemark,'') As ClassTeacherRemark,
		ISNULL(Sr.HouseRemark,'') As HouseRemark,
		ISNULL(BGM.Title,'') AS BloodGroup,
		Convert(nvarchar(20),@rBatchId),
		@rIsShowWithDetail AS IsShowWithDetail,
		IsPresent,
		GradeTitle ,
		RAD.SubjectHighestDivisionGrade,
		RAD.SubjectHighestDivisionMark 
FROM 
	sAssessment.tResultDetail RD
	INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
	INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId		
	INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
	INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId	
	LEFT JOIN sSetup.tSubjectGroupMaster SG ON SG.Id = Sm.SubjectGroupId				 
	INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId
	LEFT JOIN sSetup.tOrgImages OI ON OI.Orgid = OM.Id
	INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
	INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
	INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
	INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
	LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = Dm.InchargeEmployeeId
	LEFT JOIN sHrm.tEmployeeMaster EMP ON EMP.Id = DM.InchargeEmployeeId
	INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.EXAMSUBGROUPID
	LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=StuM.Id
	LEFT JOIN sStudent.tAcademicDetail AD ON AD.AcademicId=A.Id
	LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=StuM.Id
	LEFT JOIN sAssessment.tStudentRemark SR ON R.AcademicId = SR.AcademicId AND R.ExamId = SR.ExamId
	LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = StuM.Id
	LEFT JOIN sAssessment.tOptionalSubject OS ON OS.AcademicId = R.AcademicId AND OS.ClassSubjectId = ED.ClassSubjectId  AND ED.ExamId = R.ExamId
	LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=A.StudentId
	LEFT JOIN 	sCommon.tBloodGroupMaster BGM ON BGM.Id=So.BloodGroupId
	LEFT JOIN sAssessment.tGradeSetDetail GS ON GS.GradeSetId=ED.GradeSetId AND ED.GradeSetId = @GradeSetId and RD.SubjectGrade = GS.GradeCode
	 LEFT JOIN sAssessment.tResultAnalysisDivisionDetail RAD ON RAD.ClassSubjectId = CS.Id AND RAD.DivisionId = A.DivisionId AND RAD.ExamId = Em.Id
			  
	--LEFT JOIN sAcademic.tTeacherSubjectDivision TSD ON TSD.SubjectId=SM.Id AND TSD.DivisionId = A.DivisionId
	--LEFT JOIN sHrm.tEmployeeMaster EMP ON TSD.EmployeeId = EMP.Id
	
	 WHERE
		R.ExamId = @rExamId 
		AND ((A.DivisionId =  @rDivisionId) OR (@rDivisionId=0))
		AND ((A.ClassId =  @rClassId) OR (@rClassId=0))		 
		AND ((A.BatchId =  @rBatchId) OR (@rBatchId=0))
		AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((R.RankNumber >= @rFromRank) OR (@rFromRank=0))
		AND ((R.RankNumber <= @rToRank) OR (@rToRank=0))
		AND ((R.ResultGrade = @rGrade) OR (@rGrade=''))
		AND ((StuM.Code=@rCode) OR (@rCode=''))	
		AND ((R.Id = @rResultId) OR (@rResultId = 0))	
		AND ((StuM.StatusId=@rStatusId)OR(@rStatusId=0))
		AND((A.Id=@rAcademicId)OR (@rAcademicId=0))
		AND ((CS.SubjectId=@rSubjectId) OR(@rSubjectId=0) ) 
		AND ((R.Percentage>=@rFromPercentage) OR (@rFromPercentage=0))
		AND ((R.Percentage<=@rToPercentage) OR (@rToPercentage=0))
		 
	 
	Order By ED.DisplayOrder
 
 --print 'temp insert'
  --SET @IsIncludeSubExam = 1
	create TABLE #tempcombineExam
	(	Id int IDENTITY,
		ExamID int )

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

	IF (@IsIncludeSubExam = 1)
	BEGIN	
		select @lSubExamId = SubExamId from sAssessment.tExamCombine  Where ExamId  = @rExamId AND ExamOrder = 1
		--select @ExamTitle = Title from sAssessment.tExamMaster Where Id = @lSubExamId	
		
		
			set @query ='update T set					 
					SubjectGradeTerm1=RD.SubjectGrade,
					SubjectObtainTerm1 = RD.Obtain,
					 SubjectMaxTerm1 = ED.Maximum
							 
					 From
						 sAssessment.tResultDetail RD
						INNER JOIN  sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
		
				execute(@query)
				
		set @query ='update T set					 
					 
					TotalMarkTerm1 = R.TotalMarks,
					TotalObtainTerm1=R.TotalObtain,
					PercentageTerm1=R.Percentage,
					RankNumberTerm1=R.RankNumber,
					ResultGradeTerm1=R.ResultGrade,
					PercentileTerm1 = R.Percentile,
					ResultStatusTerm1 = R.ResultStatus,
					ExamNameTerm1 = ESGM.Code					 
					 From
						sAssessment.tResult  R 				
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id = R.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON  T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
						
		 	
						
		execute(@query)
		
					select @lSubExamId = SubExamId from sAssessment.tExamCombine  Where ExamId  = @rExamId AND ExamOrder = 2
		--select @ExamTitle = Title from sAssessment.tExamMaster Where Id = @lSubExamId	
		set @query ='update T set					 
					SubjectGradeTerm2=RD.SubjectGrade,
					SubjectObtainTerm2 = RD.Obtain,
					SubjectMaxTerm2= ED.Maximum				 
					 From
						sAssessment.tResultDetail RD
						INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
		execute(@query)
		
		
				set @query ='update T set
 
					TotalMarkTerm2 = R.TotalMarks,
					TotalObtainTerm2=R.TotalObtain,
					PercentageTerm2=R.Percentage,
					RankNumberTerm2=R.RankNumber,
					ResultGradeTerm2=R.ResultGrade,
					PercentileTerm2 = R.Percentile,
					ResultStatusTerm2 = R.ResultStatus,
					ExamNameTerm2 = ESGM.Code			
					 From						 
					   sAssessment.tResult R  				 
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON  T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
		execute(@query)
		
		select @lSubExamId = SubExamId from sAssessment.tExamCombine  Where ExamId  = @rExamId AND ExamOrder = 3
		set @query ='update T set					 
					SubjectGradeTerm3=RD.SubjectGrade,
					SubjectObtainTerm3 = RD.Obtain,
					SubjectMaxTerm3= ED.Maximum				 
					 From
						sAssessment.tResultDetail RD
						INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
		execute(@query)
		set @query ='update T set
 
					TotalMarkTerm3 = R.TotalMarks,
					TotalObtainTerm3=R.TotalObtain,
					PercentageTerm3=R.Percentage,
					RankNumberTerm3=R.RankNumber,
					ResultGradeTerm3=R.ResultGrade,
					PercentileTerm3 = R.Percentile,
					ResultStatusTerm3 = R.ResultStatus,
					ExamNameTerm3 = ESGM.Code			
					 From						 
					   sAssessment.tResult R  				 
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON  T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
		execute(@query)
	END
	
	
	
	
	
	--WHILE (@lCount1 <= 6)
	--BEGIN
	--	set @query ='ALTER TABLE #TempAllExam DROP COLUMN MaximumMark' + convert(nvarchar(15),@lCount1)
	--	execute(@query)
	--	set @query ='ALTER TABLE #TempAllExam DROP COLUMN Exam' + convert(nvarchar(150),@lCount1)+ 'Name'
	--	execute(@query)
	--	set @query ='ALTER TABLE #TempAllExam DROP COLUMN SubjectGrade' + convert(nvarchar(150),@lCount1)
	--	execute(@query)		
	--	set @query ='ALTER TABLE #TempAllExam DROP COLUMN Obtain' + convert(nvarchar(15),@lCount1)
	--	execute(@query)
	--	set @query ='ALTER TABLE #TempAllExam DROP COLUMN ExamMaximum' + convert(nvarchar(15),@lCount1)
	--	execute(@query)
	--	SET @lCount1 = @lCount1 + 1
	--END
	
	SELECT @rBuilder1,@rBuilder2, T.*
	FROM #TempAllExam T
	
	--INNER JOIN SSETUP.TCLASSSUBJECT CS ON CS.ID = T.CLASSSUBJECTID
	--WHERE
	--	((T.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
	--	AND ((T.RollNo <= @rToRollNo) OR (@rToRollNo=0))
	--	AND ((T.RankNumber >= @rFromRank) OR (@rFromRank=0))
	--	AND ((T.RankNumber <= @rToRank) OR (@rToRank=0))
	--	AND ((T.ResultGrade = @rGrade) OR (@rGrade=''))
	--	AND ((T.StudCode=@rCode) OR (@rCode=''))		
		--order by T.RollNo,CS.ORDERINDEX
		
	drop table #tempcombineExam
	Drop table #TempAllExam
	END

  --end
GO
PRINT N'Creating [sAssessment].[pGenerateResultSheetStandardMultiExamNEW]...';


GO
--exec [sAssessment].[pRptResultSheetStandardMultiExamGet] @rFromRank=0,@rGrade=N'',@rBuilder2=N'',@rCode=N'',@rFromRollNo=0,@rToRollNo=0,@rBuilder1=N'<b>Exam : </b>FA_U_1<br><br>',@rBatchId=110100101,@rClassId=110100001,@rDivisionId=110100001,@rSubjectId=0,@rExamId=110100164,@rStatusId=1

--EXEC [sAssessment].[pGenerateResultSheetStandardMultiExamNEW] @rBatchId=110100101,@rClassId=110100001,@rDivisionId=110100001,@rExamId=110100164,@rStatusId=1
 
CREATE PROCEDURE [sAssessment].[pGenerateResultSheetStandardMultiExamNEW]
	 
		@rBatchId int=0,
		@rClassId int=0,
		@rDivisionId int=0,
		@rExamId int,
		@rStatusId int=0
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
 begin
DECLARE @GradeString nvarchar(1000)
DECLARE @GradeStringRemark nvarchar(500),
@GradeSetId int , @IsIncludeSubExam bit,@GradeStringHtml nvarchar(500)
SELECT @GradeSetId = GradesetId,
	   @IsIncludeSubExam = ISNULL(IsIncludeSubExam,0)  FROM sAssessment.tExamMaster WHERE Id = @rExamId
SELECT @GradeString = [sAssessment].[fGradeStringGet](@GradeSetId)

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

DELETE FROM sAssessment.tTempAllExam 
--#TempAllExam  	
	INSERT INTO  sAssessment.tTempAllExam 
	(
	AcademicIdText,
	ExamIdText,
	CoScholasticScopeIdText,
	IsDisplayMonthlyAttendanceText,
	ClassIdText,
	AcademicId,
	ExamName,
	StudCode,
	StudentName,
	RollNo,
	ResultStatus,
	ClassName,
	Division,
	TotalMark,
	TotalObtain,
	Percentage,
	RankNumber,
	ResultGrade,
	IsMarksInDecimal,
	column_visible,
	Percentile,
	ResultDetailId,
	ResultId,
	Remark1,
	Remark2,
    Remark3,
	DisplayTitle,
	IsRankNo, 
	IsGrade,
	IsPercentile,
	IsPercentage,
	IsSubjectPercentile,
	IsProcessResult,
	IsNegativeMarks,
	IsIncludeCoScholastic,
	IsOnPrePrinted,
	IsDisplayPhoto,
	IsDisplayBirthDate,
	IsLockForEdit,
	IsDisplaySchoolName,			
	IsDisplayAttendance,
	IsDisplayHeightWeight,
	IsResultStatus,
	FooterAdjustmentText,
	DetailAdjustmentText,
	FooterAdjustment,
	DetailAdjustment,
	ResultRemark,
	DateOfBirth,
	HeightTerm1,
	WeightTerm1,
	HeightTerm2,
	WeightTerm2,
	HeightAnnual,
	WeightAnnual,
	PresentDaysTerm1,
	PresentDaysTerm2,
	PresentDaysAnnual,
	TotalDaysTerm1,
	TotalDaysTerm2,
	TotalDaysAnnual,
	TermScopeId,
	StudentPhoto,
	GradeString,
	IsDisplayGradeString,	 
	IsDisplayInMarksheet,
	IsShowSubjectGrade,
	IsIncludeInTotal,
	ClassSubjectID,
	SubjectId,
	SubjectOrderIndex,
	SubjectGrade,
	SubjectName,
	SubjectCode,
	SubjectMinimum,
	SubjectMaximum,
	SubjectObtain,
	ResultRemark1,
	ResultRemark2,
	TotalDays,
	PresentDays,
	StudentHeight,
	StudentWeight,
	ExamSeatNo,
	ExamId,
	ExamCode,
	IsDisplayParentName,
	FatherName,
	MotherName,
	IsShowSubjectMark,
	--IsOptionalSubject,
	CoScholasticScopeId,
	IsDisplayPrincipalSign,
	IsDisplayTeacherSign,
	EmployeeSign,
	Batch,
	ClassTeacherName,
	FirstName,
	LastName,
	IsDisplayMonthlyAttendance,
	MarksheetHeaderA4,
	IsImageHeader,
	MyGoal,
	AreaOfInterest,
	Responsibility,
	MyInterestHobby,
	MyStrength,
	Achievements, 
	DentalHygiene,
	VisionLeft,
	VisionRight,
	IsDetail,
	SubjectGroupId,
	SubjectGroupTitle,
	SubjectGroupCode,
	DecimalFormat,
	--SubjectRemark,
	GraceMark,
	GradeStringHtml,
	ResultRemark3,
	IsDisplayTotalMark,
	ContactNo,
	PresentAddress,
	TeacherSignCaption,
	PrincipalSignCaption,
	ParentSignCaption,
	ImprovementArea,
	ProgressArea,
	GeneralRemark,
	MyActivity,
	ClassTeacherRemark,
	HouseRemark,
	BloodGroup,
	BatchIdText,
   IsShowWithDetail,
	 IsPresent,
	 GradeTitle,
	 SubjectHighestDivisionGrade,
	 SubjectHighestDivisionMark
	)
	SELECT 
		Convert(nvarchar(20),A.Id),
		Convert(nvarchar(20),@rExamId),
		Convert(nvarchar(20),EM.CoScholasticScopeId),
		Convert(nvarchar(20),ISNULL(EM.IsDisplayMonthlyAttendance,0)),
		Convert(nvarchar(50),@rClassId),
		A.Id,
		ISNULL(ESGM.Title,'') AS EXAMNAME,
		StuM.Code AS StudCode,
		[sStudent].[fStudentNameGet](stum.FirstName , StuM.MiddleName, StuM.LastName,OM.StudentNameFormatId ) AS Name,
		A.RollNo,
		ISNULL(R.ResultStatus,'') AS ResultStatus,
		CM.DisplayTitle AS ClassName,
		DM.DisplayTitle AS Division,
		R.TotalMarks AS TotalMark,
		R.TotalObtain,
		ISNULL(R.Percentage,0) As Percentage,
		R.RankNumber,
		ISNULL(R.ResultGrade,'') AS ResultGrade,
		EM.IsMarksInDecimal,
		1,
		R.Percentile,
		RD.Id AS ResultDetailId,
		R.Id AS ResultId,
		ISNULL(EM.Remark1,'') AS Remark1,
		ISNULL(EM.Remark2,'') AS Remark2,
		ISNULL(EM.Remark3,'') AS Remark3,
		EM.DisplayTitle,
		EM.IsRankNo, 
		EM.IsGrade,
		EM.IsPercentile,
		EM.IsPercentage,
		EM.IsSubjectPercentile,
		EM.IsProcessResult,
		EM.IsNegativeMarks,
		EM.IsIncludeCoScholastic,
		EM.IsOnPrePrinted,
		EM.IsDisplayPhoto,
		EM.IsDisplayBirthDate,
		EM.IsLockForEdit,
		EM.IsDisplaySchoolName,			
		EM.IsDisplayAttendance,
		EM.IsDisplayHeightWeight,
		EM.IsResultStatus,
		REPLICATE(',',EM.FooterAdjustment) AS FooterAdjustmentText,
		REPLICATE(',',EM.DetailAdjustment) AS DetailAdjustmentText,
		EM.FooterAdjustment,
		EM.DetailAdjustment,
		ISNULL(R.ResultRemark,'') AS ResultRemark,
		SO.DateOfBirth,
		AD.HeightTerm1,
		AD.WeightTerm1,
		AD.HeightTerm2,
		AD.WeightTerm2,
		AD.HeightAnnual,
		AD.WeightAnnual,
		AD.PresentDaysTerm1,
		AD.PresentDaysTerm2,
		AD.PresentDaysAnnual,
		AD.TotalDaysTerm1,
		AD.TotalDaysTerm2,
		AD.TotalDaysAnnual,
		EM.TermScopeId,
		(CASE EM.IsDisplayPhoto WHEN 1 THEN SI.StudentPhoto ELSE NULL END)AS StudentPhoto,
		CASE @GradeStringRemark WHEN '' THEN @GradeString ELSE @GradeStringRemark END AS GradeString,
		EM.IsDisplayGradeString,
		ED.IsDisplayInMarksheet,
		ED.IsShowSubjectGrade,
		ED.IsIncludeInTotal,
	    ED.ClassSubjectId,
		CS.SubjectId AS SubjectId,
		(CASE ISNULL(ED.DisplayOrder,0) WHEN 0 THEN CS.OrderIndex	ELSE ED.DisplayOrder END) AS SubjectOrderIndex,
				RD.SubjectGrade,
		SM.Title AS SubjectName,
		ISNULL(SM.Code,'') AS SubjectCode,
		ED.Minimum,
		ED.Maximum,
		RD.Obtain,
		SR.ResultRemark1,
		SR.ResultRemark2,
		SR.TotalDays,
		SR.PresentDays,
		SR.StudentHeight,
		SR.StudentWeight,
		SR.ExamSeatNo,
		@rExamId,
		ISNULL(ESGM.Code,'') AS ExamCode,
		EM.IsDisplayParentName,
		SF.FatherName,
		SF.MotherName,
		ED.IsShowSubjectMark,
		EM.CoScholasticScopeId,
		EM.IsDisplayPrincipalSign,
		Em.IsDisplayTeacherSign,
		(CASE Em.IsDisplayTeacherSign WHEN 1 THEN EI.EmployeeSign ELSE NULL END ) AS EmployeeSign,
		BM.Title AS Batch,
		EMP.FirstName + ' ' + EMP.LastName AS ClassTeacherName,
		Stum.FirstName,
		Stum.LastName,
		ISNULL(EM.IsDisplayMonthlyAttendance,0) AS IsDisplayMonthlyAttendance,
		(CASE EM.IsDisplayImageHeader WHEN 1 THEN	OI.CertificateHeaderA4 ELSE NULL END)AS  MarksheetHeaderA4,
		ISNULL(EM.IsDisplayImageHeader,0) AS IsImageHeader,
		ISNULL(SR.MyGoal,'') AS MyGoal,
		ISNULL(SR.AreaOfInterest,'') AS AreaOfInterest,
		ISNULL(SR.Responsibility,'') AS Responsibility,
		ISNULL(SR.MyInterestHobby,'') AS MyInterestHobby,
		ISNULL(SR.MyStrength,'') AS MyStrength,
		ISNULL(SR.Achievements,'') AS Achievements,
		ISNULL(SR.DentalHygiene,'') AS DentalHygiene,
		ISNULL(SR.VisionLeft,'') AS VisionLeft,
		ISNULL(SR.VisionRight,'') AS VisionRight,
		0 AS IsDetail,
		ISNULL(SM.SubjectGroupId,0) AS SubjectGroupId,
		ISNULL(SG.Title,'')AS SubjectGroupTitle,
		ISNULL(SG.Code,'') AS SubjectGroupCode,
		ISNULL(EM.DecimalFormat,0) AS DecimalFormat,
		RD.GraceMark,
		@GradeStringHtml,
		SR.ResultRemark3,
		EM.IsDisplayTotalMark,
		ISNULL(SC.ParentContactNo,'') AS ContactNo,
		ISNULL(SC.PresentStreetOne,'')+' '+ISNULL(SC.PresentStreetTwo,'')+' '+ISNULL(SC.PresentStreetThree,'')+' '+ISNULL(SC.PresentCity,'')+' '+ISNULL(SC.PresentState,'') AS PresentAddress,
		ISNULL(EM.TeacherSignCaption,'') AS TeacherSignCaption,
		ISNULL(EM.PrincipalSignCaption,'') AS PrincipalSignCaption,
		ISNULL(Em.ParentSignCaption,'') As ParentSignCaption,
		ISNULL(SR.ImprovementArea,'') As ImprovementArea,
		ISNULL(SR.ProgressArea,'') AS ProgressArea,
		ISNULL(SR.GeneralRemark,'') As GeneralRemark,
		ISNULL(SR.MyActivity,'') AS MyActivity,
		ISNULL(SR.ClassTeacherRemark,'') As ClassTeacherRemark,
		ISNULL(Sr.HouseRemark,'') As HouseRemark,
		ISNULL(BGM.Title,'') AS BloodGroup,
		Convert(nvarchar(20),@rBatchId),
		0 AS IsShowWithDetail,
		IsPresent,
		GradeTitle ,
		RAD.SubjectHighestDivisionGrade,
		RAD.SubjectHighestDivisionMark 
FROM 
	sAssessment.tResultDetail RD
	INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
	INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId		
	INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
	INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId	
	LEFT JOIN sSetup.tSubjectGroupMaster SG ON SG.Id = Sm.SubjectGroupId				 
	INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId
	LEFT JOIN sSetup.tOrgImages OI ON OI.Orgid = OM.Id
	INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
	INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
	INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
	INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
	LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = Dm.InchargeEmployeeId
	LEFT JOIN sHrm.tEmployeeMaster EMP ON EMP.Id = DM.InchargeEmployeeId
	INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.EXAMSUBGROUPID
	LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=StuM.Id
	LEFT JOIN sStudent.tAcademicDetail AD ON AD.AcademicId=A.Id
	LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=StuM.Id
	LEFT JOIN sAssessment.tStudentRemark SR ON R.AcademicId = SR.AcademicId AND R.ExamId = SR.ExamId
	LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = StuM.Id
	LEFT JOIN sAssessment.tOptionalSubject OS ON OS.AcademicId = R.AcademicId AND OS.ClassSubjectId = ED.ClassSubjectId  AND ED.ExamId = R.ExamId
	LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=A.StudentId
	LEFT JOIN 	sCommon.tBloodGroupMaster BGM ON BGM.Id=So.BloodGroupId
	LEFT JOIN sAssessment.tGradeSetDetail GS ON GS.GradeSetId=ED.GradeSetId AND ED.GradeSetId = @GradeSetId and RD.SubjectGrade = GS.GradeCode
	 LEFT JOIN sAssessment.tResultAnalysisDivisionDetail RAD ON RAD.ClassSubjectId = CS.Id AND RAD.DivisionId = A.DivisionId AND RAD.ExamId = Em.Id
	 WHERE
		R.ExamId = @rExamId 
	AND ((A.DivisionId =  @rDivisionId) OR (@rDivisionId=0))
	AND ((A.ClassId =  @rClassId) OR (@rClassId=0))		 
	AND ((A.BatchId =  @rBatchId) OR (@rBatchId=0))
	AND ((StuM.StatusId=@rStatusId)OR(@rStatusId=0))
	Order By ED.DisplayOrder
 
	create TABLE #tempcombineExam
	(	Id int IDENTITY,
		ExamID int )

	IF (@IsIncludeSubExam = 0)
	BEGIN	
	INSERT INTO #tempcombineExam (ExamID) 
	SELECT SUBEXAMID FROM sAssessment.tExamCombine WHERE ExamId  = @rExamId Order By ExamOrder ASC
 	END
 	ELSE
 	BEGIN
 	-- if we want to display result for both the term with all exam select this option
 	INSERT INTO #tempcombineExam (ExamID) 
	SELECT C.SUBEXAMID FROM sAssessment.tExamCombine C
	INNER JOIN (SELECT SUBEXAMID,ExamOrder FROM sAssessment.tExamCombine WHERE ExamId  = @rExamId) E
	ON C.ExamId = E.SubExamId
	ORDER BY E.ExamOrder,C.ExamOrder
	END
	
	DECLARE @lCount int,@query  AS NVARCHAR(MAX),@lSubExamId int,@lCount1 int
  
	Select @lCount = MAX(Id) from #tempcombineExam

	DECLARE @ExamTitle nvarchar(150)
	while (@lCount > 0)
	begin
		select @lSubExamId = ExamID from #tempcombineExam Where Id = @lCount
		
		set @query ='update T SET
					 MaximumMark' + convert(nvarchar(15),@lCount)+ '=ED.Maximum,
					 Obtain' + convert(nvarchar(15),@lCount)+'=RD.Obtain,
					 IsPresent' + convert(nvarchar(15),@lCount)+'=RD.IsPresent,	
					 SubjectGrade' + convert(nvarchar(15),@lCount)+ '=RD.SubjectGrade,
					  TotalDays'+convert(nvarchar(15),@lCount)+'=SR.TotalDays,
					 PresentDays'+convert(nvarchar(15),@lCount)+'=SR.PresentDays										
					 From
						sAssessment.tResultDetail RD
						INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	sAssessment.tTempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId	
						LEFT JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND T.AcademicId = SR.AcademicId 									
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
						
	
	 execute(@query)
	
						
			set @query ='update T set 
				    TotalMarks' + convert(nvarchar(15),@lCount)+ '=R.TotalMarks,
					TotalObtain' + convert(nvarchar(15),@lCount)+ '=R.TotalObtain,
					Percentage' + convert(nvarchar(15),@lCount)+ '=R.Percentage,
					RankNumber' + convert(nvarchar(15),@lCount)+'=R.RankNumber,
					ResultGrade' + convert(nvarchar(15),@lCount)+'=R.ResultGrade,
					Percentile' + convert(nvarchar(15),@lCount)+'=R.Percentile,
					ResultStatus' + convert(nvarchar(15),@lCount)+'=R.ResultStatus,
					Exam' + convert(nvarchar(15),@lCount)+ 'Name=ESGM.Title,
					Exam' + convert(nvarchar(15),@lCount)+ 'Code=ESGM.Code,
					ExamMaximum' + convert(nvarchar(15),@lCount)+'=ISNULL(EM.ExamMaximum,0)
					 From						
						sAssessment.tResult R						
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	sAssessment.tTempAllExam  T ON  T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
						
		execute(@query)
	set @lCount = @lCount -1
	end
	

	IF (@IsIncludeSubExam = 1)
	BEGIN	
		select @lSubExamId = SubExamId from sAssessment.tExamCombine  Where ExamId  = @rExamId AND ExamOrder = 1
		
			set @query ='update T set					 
					SubjectGradeTerm1=RD.SubjectGrade,
					SubjectObtainTerm1 = RD.Obtain,
					 SubjectMaxTerm1 = ED.Maximum
							 
					 From
						 sAssessment.tResultDetail RD
						INNER JOIN  sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	sAssessment.tTempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
		
				execute(@query)
				
		set @query ='update T set					 
					 
					TotalMarkTerm1 = R.TotalMarks,
					TotalObtainTerm1=R.TotalObtain,
					PercentageTerm1=R.Percentage,
					RankNumberTerm1=R.RankNumber,
					ResultGradeTerm1=R.ResultGrade,
					PercentileTerm1 = R.Percentile,
					ResultStatusTerm1 = R.ResultStatus,
					ExamNameTerm1 = ESGM.Code					 
					 From
						sAssessment.tResult  R 				
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id = R.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	sAssessment.tTempAllExam  T ON  T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
						
		 	
						
		execute(@query)
		
					select @lSubExamId = SubExamId from sAssessment.tExamCombine  Where ExamId  = @rExamId AND ExamOrder = 2
		set @query ='update T set					 
					SubjectGradeTerm2=RD.SubjectGrade,
					SubjectObtainTerm2 = RD.Obtain,
					SubjectMaxTerm2= ED.Maximum				 
					 From
						sAssessment.tResultDetail RD
						INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	sAssessment.tTempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
		execute(@query)
		
		
				set @query ='update T set
 
					TotalMarkTerm2 = R.TotalMarks,
					TotalObtainTerm2=R.TotalObtain,
					PercentageTerm2=R.Percentage,
					RankNumberTerm2=R.RankNumber,
					ResultGradeTerm2=R.ResultGrade,
					PercentileTerm2 = R.Percentile,
					ResultStatusTerm2 = R.ResultStatus,
					ExamNameTerm2 = ESGM.Code			
					 From						 
					   sAssessment.tResult R  				 
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	sAssessment.tTempAllExam  T ON  T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
		execute(@query)
		
		select @lSubExamId = SubExamId from sAssessment.tExamCombine  Where ExamId  = @rExamId AND ExamOrder = 3
		set @query ='update T set					 
					SubjectGradeTerm3=RD.SubjectGrade,
					SubjectObtainTerm3 = RD.Obtain,
					SubjectMaxTerm3= ED.Maximum				 
					 From
						sAssessment.tResultDetail RD
						INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	sAssessment.tTempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
		execute(@query)
		set @query ='update T set
 
					TotalMarkTerm3 = R.TotalMarks,
					TotalObtainTerm3=R.TotalObtain,
					PercentageTerm3=R.Percentage,
					RankNumberTerm3=R.RankNumber,
					ResultGradeTerm3=R.ResultGrade,
					PercentileTerm3 = R.Percentile,
					ResultStatusTerm3 = R.ResultStatus,
					ExamNameTerm3 = ESGM.Code			
					 From						 
					   sAssessment.tResult R  				 
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	sAssessment.tTempAllExam  T ON  T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
		execute(@query)
	END
	SELECT  T.*	FROM sAssessment.tTempAllExam  T
		
	drop table #tempcombineExam
	--Drop table TempAllExam
	END

  --end
GO
PRINT N'Creating [sSecurity].[pOrgGroupMobileAppDetailAdd]...';


GO
CREATE PROCEDURE [sSecurity].[pOrgGroupMobileAppDetailAdd]
	@rOrgGroupId	int,
	@rApplicationName	nvarchar(100),
	@rPrivacyPolicyURL	nvarchar(300),
	@rAndroidPackageName	nvarchar(200),
	@rAndroidLink	nvarchar(300),
	@rAndroidStatus	bit,
	@rAndroidLastVersionCode	int,
	@rAndroidLastVersionName	nvarchar(20),
	@rAndroidLastRealeaseDate	date,
	@riOSBundleIdentifier	nvarchar(200),
	@riOSLink	nvarchar(300),
	@riOSStatus	bit,
	@riOSLastVersionCode	int,
	@riOSLastVersionName	nvarchar(20),
	@riOSLastRealeaseDate	date,
	@riOSExpireDate	date
	   	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
			 BEGIN TRANSACTION	

	If NOT Exists(select 1 from [sSecurity].[tOrgGroupMobileAppDetail] where OrgGroupId=@rOrgGroupId)
	BEGIN
	INSERT INTO sSecurity.tOrgGroupMobileAppDetail
		(
			OrgGroupId,
			ApplicationName,
			PrivacyPolicyURL,
			AndroidPackageName,
			AndroidLink,
			AndroidStatus,
			AndroidLastVersionCode,
			AndroidLastVersionName,
			AndroidLastRealeaseDate,
			iOSBundleIdentifier,
			iOSLink,
			iOSStatus,
			iOSLastVersionCode,
			iOSLastVersionName,
			iOSLastRealeaseDate,
			iOSExpireDate
		)
	VALUES
		(
			@rOrgGroupId,
			@rApplicationName,
			@rPrivacyPolicyURL,
			@rAndroidPackageName,
			@rAndroidLink,
			@rAndroidStatus,
			@rAndroidLastVersionCode,
			@rAndroidLastVersionName,
			@rAndroidLastRealeaseDate,
			@riOSBundleIdentifier,
			@riOSLink,
			@riOSStatus,
			@riOSLastVersionCode,
			@riOSLastVersionName,
			@riOSLastRealeaseDate,
			@riOSExpireDate
		)
		    SELECT 1 AS Result
	END	 

ELSE
	 BEGIN
	 UPDATE  sSecurity.tOrgGroupMobileAppDetail
	    SET 
	      
			ApplicationName=@rApplicationName,
			PrivacyPolicyURL=@rPrivacyPolicyURL,
			AndroidPackageName=@rAndroidPackageName,
			AndroidLink=@rAndroidLink,
			AndroidStatus=@rAndroidStatus,
			AndroidLastVersionCode=@rAndroidLastVersionCode,
			AndroidLastVersionName=@rAndroidLastVersionName,
			AndroidLastRealeaseDate=@rAndroidLastRealeaseDate,
			iOSBundleIdentifier=@riOSBundleIdentifier,
			iOSLink=@riOSLink,
			iOSStatus=@riOSStatus,
			iOSLastVersionCode=@riOSLastVersionCode,
			iOSLastVersionName=@riOSLastVersionName,
			iOSLastRealeaseDate=@riOSLastRealeaseDate,
			iOSExpireDate=@riOSExpireDate
	      WHERE OrgGroupId = @rOrgGroupId
	      SELECT 11 AS Result
	 END  	

	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Creating [sSecurity].[pOrgGroupMobileAppDetailDelete]...';


GO
CREATE PROCEDURE [sSecurity].[pOrgGroupMobileAppDetailDelete]
	 @rOrgGroupId bigint
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	BEGIN TRY
		BEGIN TRANSACTION	
			Delete from [sSecurity].[tOrgGroupMobileAppDetail] where OrgGroupId=@rOrgGroupId
			select 1
		COMMIT TRANSACTION	
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
	END CATCH	
END
GO
PRINT N'Creating [sSecurity].[pOrgGroupMobileAppDetailGet]...';


GO
 
CREATE PROCEDURE  [sSecurity].[pOrgGroupMobileAppDetailGet]

		@rOrgGroupId int,
		@rPrivacyPolicyURL nvarchar(300), 
		@rApplicationName nvarchar(100)
	 
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
		BEGIN
		SET @rApplicationName = sCommon.fSearchStringGet(@rApplicationName)
		SET @rPrivacyPolicyURL = sCommon.fSearchStringGet(@rPrivacyPolicyURL)
	END
	
	SELECT 
			OGM.*
	FROM 
		sSecurity.tOrgGroupMobileAppDetail  OGM
	
	WHERE 
	
			 ((OGM.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId= 0))
				AND ((OGM.ApplicationName like @rApplicationName) OR (ISNULL(@rApplicationName,'') = ''))
		AND ((OGM.PrivacyPolicyURL like @rPrivacyPolicyURL) OR (ISNULL(@rPrivacyPolicyURL,'') = ''))
    order by OGM.OrgGroupId desc
END
GO
 
  
GO
INSERT INTO [sSystem].[tVersionUpdate] ([VersionNumber],[VersionId],[Status],[UpdateScript],[StartDateTime],[EndDateTime],[OrgGroupId])
VALUES('18.04.26',180426,'END','Script',sCommon.fGetDate(),sCommon.fGetDate(),0)
GO