
PRINT N'Creating [sClient]...';


GO
CREATE SCHEMA [sClient]
    AUTHORIZATION [dbo];


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


GO
ALTER TABLE [sAssessment].[tCCEResult]
    ADD [Term1CGPA] DECIMAL (6, 2) NULL,
        [Term2CGPA] DECIMAL (6, 2) NULL;


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


GO
ALTER TABLE [sAssessment].[tTempAllExam]
    ADD [SubjectGroupId]    INT           NULL,
        [SubjectGroupTitle] NVARCHAR (50) NULL,
        [DecimalFormat]     NVARCHAR (10) NULL;


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


GO
ALTER TABLE [sFee].[tCollectionGroupMaster]
    ADD [IsDisplayCashDetailInFolio] BIT NULL;


GO
PRINT N'Altering [sHostel].[tAssetTypeMaster]...';


GO
ALTER TABLE [sHostel].[tAssetTypeMaster]
    ADD [OrgGroupId] INT NULL;


GO
PRINT N'Altering [sPayroll].[tPayElementDefault]...';


GO
ALTER TABLE [sPayroll].[tPayElementDefault]
    ADD [IsIncludeInTotal] BIT NULL;


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


GO
ALTER TABLE [sStudent].[tStudentMaster]
    ADD [EnrollmentStatusId] INT NULL;


GO
PRINT N'Creating [sAssessment].[tExamCombineSubject]...';


GO
CREATE TABLE [sAssessment].[tExamCombineSubject] (
    [ExamId]           INT            NOT NULL,
    [SubExamId]        INT            NOT NULL,
    [ClassSubjectId]   INT            NOT NULL,
    [SubjectWeightage] DECIMAL (5, 2) NOT NULL
);


GO
PRINT N'Creating [sAssessment].[tResultDetailOther]...';


GO
CREATE TABLE [sAssessment].[tResultDetailOther] (
    [ExamId]         INT             NOT NULL,
    [AcademicId]     BIGINT          NOT NULL,
    [ClassSubjectId] INT             NOT NULL,
    [Remark]         NVARCHAR (1000) NULL
);


GO
PRINT N'Creating [sCommon].[tReportRemarkGroupMaster]...';


GO
CREATE TABLE [sCommon].[tReportRemarkGroupMaster] (
    [Id]                       SMALLINT       NOT NULL,
    [Code]                     NVARCHAR (10)  NOT NULL,
    [Title]                    NVARCHAR (100) NOT NULL,
    [DefaultRemark1]           NVARCHAR (500) NULL,
    [DefaultRemark2]           NVARCHAR (500) NULL,
    [DefaultRemark3]           NVARCHAR (500) NULL,
    [DefaultRequiredSignature] NVARCHAR (500) NULL,
    [IsObsolete]               BIT            NOT NULL
);


GO
PRINT N'Creating PK_tReportRemarkGroupMaster...';


GO
ALTER TABLE [sCommon].[tReportRemarkGroupMaster]
    ADD CONSTRAINT [PK_tReportRemarkGroupMaster] PRIMARY KEY CLUSTERED ([Id] ASC) WITH (ALLOW_PAGE_LOCKS = ON, ALLOW_ROW_LOCKS = ON, PAD_INDEX = OFF, IGNORE_DUP_KEY = OFF, STATISTICS_NORECOMPUTE = OFF);


GO
PRINT N'Creating [sCommon].[tReportRemarkGroupOrg]...';


GO
CREATE TABLE [sCommon].[tReportRemarkGroupOrg] (
    [ReportRemarkGroupId]     SMALLINT       NOT NULL,
    [ReportId]                INT            NULL,
    [OrgId]                   SMALLINT       NOT NULL,
    [SchoolRemark1]           NVARCHAR (500) NULL,
    [SchoolRemark2]           NVARCHAR (500) NULL,
    [SchoolRemark3]           NVARCHAR (500) NULL,
    [SchoolRequiredSignature] NVARCHAR (500) NULL
);


GO
PRINT N'Creating [sHostel].[tHostelDepositAdd]...';


GO
CREATE TABLE [sHostel].[tHostelDepositAdd] (
    [Id]                  BIGINT          NOT NULL,
    [HostelDepositHeadId] INT             NOT NULL,
    [StudentId]           BIGINT          NOT NULL,
    [Amount]              DECIMAL (12, 2) NOT NULL,
    [DepositDate]         DATE            NOT NULL,
    [PayTypeId]           TINYINT         NOT NULL,
    [ChequeNo]            NVARCHAR (20)   NULL,
    [BankName]            NVARCHAR (200)  NULL,
    [Remark]              NVARCHAR (200)  NULL,
    [CreatedUserId]       BIGINT          NOT NULL,
    [CreatedDateTime]     DATETIME        NOT NULL,
    [UpdatedUserId]       BIGINT          NULL,
    [UpdatedDateTime]     DATETIME        NULL,
    [HostelId]            INT             NULL
);


GO
PRINT N'Creating [sHostel].[tHostelDepositAdjustment]...';


GO
CREATE TABLE [sHostel].[tHostelDepositAdjustment] (
    [Id]                  BIGINT          NOT NULL,
    [HostelDepositHeadId] INT             NOT NULL,
    [StudentId]           BIGINT          NOT NULL,
    [Amount]              DECIMAL (12, 2) NOT NULL,
    [AdjustmentDate]      DATE            NOT NULL,
    [Remark]              NVARCHAR (200)  NULL,
    [CreatedUserId]       BIGINT          NOT NULL,
    [CreatedDateTime]     DATETIME        NOT NULL,
    [UpdatedUserId]       BIGINT          NULL,
    [UpdatedDateTime]     DATETIME        NULL,
    [HostelId]            INT             NULL
);


GO
PRINT N'Creating [sHostel].[tHostelDepositHeadMaster]...';


GO
CREATE TABLE [sHostel].[tHostelDepositHeadMaster] (
    [OrgGroupId]      SMALLINT       NOT NULL,
    [HostelId]        INT            NOT NULL,
    [Id]              INT            NOT NULL,
    [Number]          INT            NOT NULL,
    [Code]            NVARCHAR (20)  NOT NULL,
    [Title]           NVARCHAR (100) NOT NULL,
    [CreatedUserId]   BIGINT         NOT NULL,
    [CreatedDateTime] DATETIME       NOT NULL,
    [OrderIndex]      SMALLINT       NOT NULL,
    [IsObsolete]      BIT            NOT NULL,
    [UpdatedUserId]   BIGINT         NULL,
    [UpdatedDateTime] DATETIME       NULL
);


GO
PRINT N'Creating [sHostel].[tHostelDepositRefund]...';


GO
CREATE TABLE [sHostel].[tHostelDepositRefund] (
    [HostelDepositHeadId] INT             NOT NULL,
    [StudentId]           BIGINT          NOT NULL,
    [RefundAmount]        DECIMAL (12, 2) NOT NULL,
    [RefundDate]          DATE            NOT NULL,
    [PayTypeId]           TINYINT         NOT NULL,
    [ChequeNo]            NVARCHAR (20)   NULL,
    [BankName]            NVARCHAR (200)  NULL,
    [Remark]              NVARCHAR (200)  NULL,
    [CreatedUserId]       BIGINT          NOT NULL,
    [CreatedDateTime]     DATETIME        NOT NULL,
    [UpdatedUserId]       BIGINT          NULL,
    [UpdatedDateTime]     DATETIME        NULL,
    [HostelId]            INT             NULL
);


GO
PRINT N'Creating [sSetup].[tDivisionInchargeEmployee]...';


GO
CREATE TABLE [sSetup].[tDivisionInchargeEmployee] (
    [DivisionId] INT    NOT NULL,
    [EmployeeId] BIGINT NOT NULL,
    [BatchId]    INT    NOT NULL
);


GO
PRINT N'Creating [sSetup].[tDivisionInchargeEmployee].[UK_tDivisionInchargeEmployee]...';


GO
CREATE NONCLUSTERED INDEX [UK_tDivisionInchargeEmployee]
    ON [sSetup].[tDivisionInchargeEmployee]([DivisionId] ASC, [EmployeeId] ASC, [BatchId] ASC) WITH (ALLOW_PAGE_LOCKS = ON, ALLOW_ROW_LOCKS = ON, PAD_INDEX = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, IGNORE_DUP_KEY = OFF, STATISTICS_NORECOMPUTE = OFF, ONLINE = OFF, MAXDOP = 0)
    ON [PRIMARY];


GO
PRINT N'Creating [sStudent].[tEnrollmentStatusMaster]...';


GO
CREATE TABLE [sStudent].[tEnrollmentStatusMaster] (
    [Id]         INT           NOT NULL,
    [Code]       NVARCHAR (50) NOT NULL,
    [Title]      NVARCHAR (50) NOT NULL,
    [StatusId]   SMALLINT      NOT NULL,
    [IsObsolete] BIT           NOT NULL
);


GO
PRINT N'Creating PK_tEnrollmentStatusMaster...';


GO
ALTER TABLE [sStudent].[tEnrollmentStatusMaster]
    ADD CONSTRAINT [PK_tEnrollmentStatusMaster] PRIMARY KEY CLUSTERED ([Id] ASC) WITH (ALLOW_PAGE_LOCKS = ON, ALLOW_ROW_LOCKS = ON, PAD_INDEX = OFF, IGNORE_DUP_KEY = OFF, STATISTICS_NORECOMPUTE = OFF);


GO
PRINT N'Creating [sStudent].[tEnrollmentStatusOrg]...';


GO
CREATE TABLE [sStudent].[tEnrollmentStatusOrg] (
    [EnrollmentStatusId] INT      NULL,
    [OrgId]              SMALLINT NULL
);


GO
PRINT N'Creating [sStudent].[tEnrollmentStatusStudent]...';


GO
CREATE TABLE [sStudent].[tEnrollmentStatusStudent] (
    [Id]                 BIGINT         NULL,
    [AcademicId]         BIGINT         NOT NULL,
    [StatusDate]         DATE           NULL,
    [Remark]             NVARCHAR (200) NULL,
    [EnrollmentStatusId] INT            NULL,
    [CreatedUserId]      BIGINT         NULL,
    [CreatedDateTime]    DATETIME       NULL
);


GO
PRINT N'Creating [sStudent].[tLinkSibling]...';


GO
CREATE TABLE [sStudent].[tLinkSibling] (
    [StudentId]       BIGINT NOT NULL,
    [LinkedStudentId] BIGINT NOT NULL
);


GO
PRINT N'Creating [sSystem].[tExceptionLog]...';


GO
CREATE TABLE [sSystem].[tExceptionLog] (
    [Id]                       BIGINT          IDENTITY (1, 1) NOT NULL,
    [OrgGroupId]               SMALLINT        NULL,
    [MachineName]              NVARCHAR (200)  NULL,
    [AppDomainName]            NVARCHAR (200)  NULL,
    [ExceptionType]            NVARCHAR (1000) NULL,
    [ExceptionMessage]         NVARCHAR (MAX)  NOT NULL,
    [ExceptionSource]          NVARCHAR (MAX)  NULL,
    [ExceptionStackTrace]      NVARCHAR (MAX)  NULL,
    [InnerExceptionType]       NVARCHAR (1000) NULL,
    [InnerExceptionMessage]    NVARCHAR (MAX)  NULL,
    [InnerExceptionSource]     NVARCHAR (MAX)  NULL,
    [InnerExceptionStackTrace] NVARCHAR (MAX)  NULL,
    [ExceptionDetail]          NVARCHAR (MAX)  NULL,
    [CreatedDateTime]          DATETIME        NOT NULL,
    [CreatedUserId]            BIGINT          NULL
);


GO
PRINT N'Creating PK_tAlertModeMaster...';


GO
ALTER TABLE [sAlert].[tAlertModeMaster]
    ADD CONSTRAINT [PK_tAlertModeMaster] PRIMARY KEY CLUSTERED ([Id] ASC) WITH (ALLOW_PAGE_LOCKS = ON, ALLOW_ROW_LOCKS = ON, PAD_INDEX = OFF, IGNORE_DUP_KEY = OFF, STATISTICS_NORECOMPUTE = OFF);


GO
PRINT N'Creating PK_tFeeInvoice...';


GO
ALTER TABLE [sFee].[tFeeInvoice]
    ADD CONSTRAINT [PK_tFeeInvoice] PRIMARY KEY CLUSTERED ([Id] ASC) WITH (ALLOW_PAGE_LOCKS = ON, ALLOW_ROW_LOCKS = ON, PAD_INDEX = OFF, IGNORE_DUP_KEY = OFF, STATISTICS_NORECOMPUTE = OFF);


GO
PRINT N'Creating [sFee].[tFeeInvoice].[UK_tFeeInvoice]...';


GO
CREATE NONCLUSTERED INDEX [UK_tFeeInvoice]
    ON [sFee].[tFeeInvoice]([SourceId] ASC, [CollectionGroupId] ASC, [ReceiptBookId] ASC, [BatchId] ASC) WITH (ALLOW_PAGE_LOCKS = ON, ALLOW_ROW_LOCKS = ON, PAD_INDEX = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, IGNORE_DUP_KEY = OFF, STATISTICS_NORECOMPUTE = OFF, ONLINE = OFF, MAXDOP = 0)
    ON [PRIMARY];


GO
PRINT N'Creating [sFee].[tFeeInvoiceDetail].[UK_tFeeInvoiceDetail]...';


GO
CREATE NONCLUSTERED INDEX [UK_tFeeInvoiceDetail]
    ON [sFee].[tFeeInvoiceDetail]([FeeInvoiceId] ASC, [FeeSetupId] ASC) WITH (ALLOW_PAGE_LOCKS = ON, ALLOW_ROW_LOCKS = ON, PAD_INDEX = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, IGNORE_DUP_KEY = OFF, STATISTICS_NORECOMPUTE = OFF, ONLINE = OFF, MAXDOP = 0)
    ON [PRIMARY];


GO
PRINT N'Creating [sSecurity].[tOrganizationTask].[UK_tOrganizationTask]...';


GO
CREATE NONCLUSTERED INDEX [UK_tOrganizationTask]
    ON [sSecurity].[tOrganizationTask]([OrgGroupId] ASC, [TaskId] ASC) WITH (ALLOW_PAGE_LOCKS = ON, ALLOW_ROW_LOCKS = ON, PAD_INDEX = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, IGNORE_DUP_KEY = OFF, STATISTICS_NORECOMPUTE = OFF, ONLINE = OFF, MAXDOP = 0)
    ON [PRIMARY];


GO



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


GO
CREATE FUNCTION [sAttendance].[fHolidayForMonthGet](@rForMonth int,@rForYear int,@rBatchId int,@rDivisionId int)
RETURNS nvarchar(50) WITH EXECUTE AS CALLER
AS 
BEGIN
  DECLARE @day int,@day1 int,@day2 int,@str varchar(50)='' 
	 
	select @day1=DATEPART(DD,FromDate) 
	from
	 	sActivity.tEventSchedule ES
		INNER JOIN sActivity.tEventAssign EA ON EA.EventScheduleID = ES.Id 
	where 
		IsHoliday=1 
		AND BatchId =@rBatchId 
		AND @rForMonth=DATEPART(MM,FromDate) 
		AND @rForYear<=DATEPART(YYYY,FromDate)  
		AND @rForYear>=DATEPART(YYYY,Todate)
		AND EA.SourceId = @rDivisionId
		
	select 
		@day2=DATEPART(DD,ToDate) 
	from 
		sActivity.tEventSchedule ES
		INNER JOIN sActivity.tEventAssign EA ON EA.EventScheduleID = ES.Id 
	where 
		IsHoliday=1  
		AND @rForMonth=DATEPART(MM,FromDate) 
		AND @rForYear<=DATEPART(YYYY,FromDate)  
		AND @rForYear>=DATEPART(YYYY,Todate)
		AND BatchId =@rBatchId
		AND EA.SourceId = @rDivisionId
	 
	While @day1<=@day2
	BEGIN
		select @str = @str + convert(varchar,@day1) + ','
		select @day1=@day1 + 1
	END
	if isnull(@str,'')=''
	begin
		select @str=''
	end
	else
	begin		
		select @str=LEFT(@str,LEN(@str)-1)
	end
	return  @str
	
	
	
END
GO
PRINT N'Creating [sAttendance].[fSubjectTeacherGet]...';


GO
CREATE FUNCTION [sAttendance].[fSubjectTeacherGet](@rDivisionId int,@rSubjectId int)
RETURNS nvarchar(200) WITH EXECUTE AS CALLER
AS 
BEGIN
	DECLARE @lName nvarchar(200)=''
  
	Select @lName=COALESCE( Em.FirstName + ' ' +Em.LastName + '/ ' ,'') 
	FROM sHrm.tEmployeeMaster EM 
	 
	INNER JOIN sAcademic.tTeacherSubjectDivision TSD ON TSD.EmployeeId= EM.Id 
	
	WHERE TSD.DivisionId = @rDivisionId  AND TSD.SubjectId =@rSubjectId
	
	if isnull(@lName,'')=''
	begin
		select @lName=''
	end	
	else
	begin		
		select @lName=LEFT(@lName,LEN(@lName)-1)
	end
	return  @lName
END
GO
PRINT N'Creating [sHostel].[fAssignRoomAssetGet]...';


GO

CREATE FUNCTION [sHostel].[fAssignRoomAssetGet](@rHostelId int,@rRoomId int,@rStudentId bigint)
RETURNS nvarchar(max) WITH EXECUTE AS CALLER
AS 
BEGIN	 
declare @rAssestList nvarchar(max)=''

Select @rAssestList=@rAssestList + isnull(AT.Code,'') + ' ' + ':' + ' ' + isnull(RM.AssetNumber,'') + ','

FROM sHostel.tAssignRoomAsset AR 
          INNER JOIN sHostel.tRoomAssetMaster RM ON RM.Id=Ar.RoomAssetId  AND (AR.SourceId = @rStudentId OR ISNULL(@rStudentId,0) = 0) AND AR.SourceTypeId=2003
          INNER JOIN sHostel.tAssetTypeMaster AT ON AT.Id=RM.AssetTypeId
          WHERE 
          ((RM.HostelId=@rHostelId)OR (@rHostelId=0))
          AND ((RM.RoomId=@rRoomId)OR ( @rRoomId =0))
        IF (RIGHT(@rAssestList, 1) = ',')
   set @rAssestList = LEFT(@rAssestList, LEN(@rAssestList) - 1)
   
      RETURN  isnull(@rAssestList,'')
END
GO
PRINT N'Creating [sHostel].[fHostelWardenGet]...';


GO

CREATE FUNCTION [sHostel].[fHostelWardenGet](@rHostelId int)
RETURNS nvarchar(max) WITH EXECUTE AS CALLER
AS 
BEGIN	 
declare @rWardenList nvarchar(max)=''

Select @rWardenList=@rWardenList + ISNULL(EM.FirstName,'')+' '+ISNULL(EM.LastName,'') +' '+','

FROM sHostel.tHostelWarden HW 
INNER JOIN sHrm.tEmployeeMaster EM ON HW.EmployeeId=EM.Id
          WHERE 
          ((HW.HostelId=@rHostelId)OR (@rHostelId=0))
          
   --     IF (RIGHT(@rWardenList, 1) = ',')
   --set @rWardenList = LEFT(@rWardenList, LEN(@rWardenList) - 1)
   
      RETURN  isnull(@rWardenList,'')
END
GO
PRINT N'Creating [sHostel].[fRemainAssignRoomAssetGet]...';


GO

CREATE FUNCTION [sHostel].[fRemainAssignRoomAssetGet](@rHostelId int,@rRoomId int,@rAssetTypeId int)
RETURNS nvarchar(max) WITH EXECUTE AS CALLER
AS 
BEGIN	 
declare @rAssestList nvarchar(max)=''

Select @rAssestList= @rAssestList+isnull(RM.AssetNumber,'') + ','
FROM sHostel.tRoomAssetMaster RM 
          LEFT JOIN sHostel.tAssetTypeMaster AT ON AT.Id=RM.AssetTypeId
          WHERE ((RM.HostelId=@rHostelId)OR (@rHostelId=0))
          AND ((RM.RoomId=@rRoomId)OR ( @rRoomId =0))
          AND RM.Id NoT IN(SELECT RoomAssetId FROM sHostel.tAssignRoomAsset 
          WHERE ((HostelId=@rHostelId)OR (ISNULL(@rHostelId,0)=0))  AND ((RoomId=@rRoomId)OR (ISNULL(@rRoomId,0)=0))) 
          AND RM.AssetTypeId=@rAssetTypeId
           group by RM.AssetNumber
        IF (RIGHT(@rAssestList, 1) = ',')
   set @rAssestList = LEFT(@rAssestList, LEN(@rAssestList) - 1)
  
      RETURN  isnull(@rAssestList,'')
END
GO
PRINT N'Altering [sAcademic].[vExamTeacherSubjectDivision]...';


GO




/******************************************************************************  
 Purpose          : To get Batch Wise  Class
 Created date     : 21 Nov 2013
 Author           : Kundan Patel 
 Copyright©       : Copyright © Sapphire Software Solutions
 ******************************************************************************/  
ALTER VIEW [sAcademic].[vExamTeacherSubjectDivision]  
  
AS  
  
SELECT 	
	  SM.Id AS SubjectId,
	  SM.Code AS SubjectCode,
	  SM.Title AS SubjectName,	  
	  SM.Number,
	  SM.OrderIndex,
	  SM.OrgId,
	  SM.IsObsolete,
	  TS.EmployeeId,
	  DM.Id AS DivisionId,
	  DM.Title AS DivisionTitle,
	  DM.OrderIndex AS DivisionOrderIndex,
	  CM.Id AS ClassId,
	  CM.Title AS ClassTitle,
	  CM.OrderIndex AS ClassOrderIndex,
	  ED.Id AS ExamDetailId,
	  EM.Id As ExamId,
	  CS.Id AS ClassSubjectId
	  
	  
  FROM 
	sSetup.tSubjectMaster SM
	INNER JOIN sAcademic.tTeacherSubject TS ON TS.SubjectId= SM.Id
	INNER JOIN sAcademic.tTeacherSubjectDivision TSD ON TS.SubjectId = TSD.SubjectId AND TS.EmployeeId = TSD.EmployeeId
	INNER JOIN sSetup.tDivisionMaster DM ON TSD.DivisionId = DM.Id
	INNER JOIN sSetup.tClassMaster CM ON DM.ClassId = CM.Id
	INNER JOIN sSetup.tClassSubject CS ON CS.ClassId = CM.Id AND CS.SubjectId = SM.Id
	INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
	INNER JOIN sAssessment.tExamDetail ED ON Ed.ExamId = EM.Id AND ED.ClassSubjectId = CS.Id
GO
PRINT N'Altering [sEExam].[vClassSubjectTopicType]...';


GO










/******************************************************************************  
 Purpose          : To get Batch Wise  Class
 Created date     : 21 Nov 2013
 Author           : Kundan Patel 
 Copyright©       : Copyright © Sapphire Software Solutions
 ******************************************************************************/  
ALTER VIEW [sEExam].[vClassSubjectTopicType]  
  
AS  
  
SELECT 	
	  CS.Id AS ClassSubjectId,
	  SM.Id AS SubjectId,
	  --SM.Title as SubjectName,
	  TTM.IsObsolete,
	  TTM.OrderIndex,
	  TTM.Id AS TopicTypeId,
	  TTM.Title AS TopicTypeTitle,
	  TTM.OrgGroupId
  FROM 
  		sSetup.tClassSubject CS
	INNER JOIN sSetup.tSubjectMaster SM
		ON SM.Id=CS.SubjectId
	INNER JOIN sEExam.tDataTopicTypeMaster TTM
		on TTM.DataSubjectId=SM.Id
GO
PRINT N'Altering [sSetup].[vBatchClass]...';


GO



 
/******************************************************************************  
 Purpose          : To get Batch Wise  Class
 Created date     : 21 Nov 2013
 Author           : Kundan Patel 
 Copyright©       : Copyright © Sapphire Software Solutions
 ******************************************************************************/  
ALTER VIEW [sSetup].[vBatchClass]  
  
AS  
  
SELECT 	
	  CM.Id as ClassId,
	  BC.BatchId as BatchId,
	  CM.DisplayTitle as ClassName,
	  CM.IsObsolete,
	 Cm.ClassGroupId,
	  CM.OrderIndex,
	  CM.DepartmentId,
	  CM.OrgId
	  	   
  FROM 
  
	sSetup.tBatchClass BC
	INNER JOIN sSetup.tClassMaster CM
		ON CM.Id=BC.ClassId 
	INNER JOIN sSetup.tBatchMaster BM
		ON BM.Id=BC.BatchId AND BM.OrgId = CM.OrgId
GO
PRINT N'Altering [sSetup].[vBatchClassDivision]...';


GO













/******************************************************************************  
 Purpose          : To get Batch Wise  Class
 Created date     : 21 Nov 2013
 Author           : Kundan Patel 
 Copyright©       : Copyright © Sapphire Software Solutions
 ******************************************************************************/  
ALTER VIEW [sSetup].[vBatchClassDivision]  
  
AS  
  
SELECT 	
	  DM.Id as DivisionId,
	  ISNULL(CM.Id,0) AS ClassId,
	  BC.BatchId as BatchId,
	  CM.DisplayTitle AS ClassName,
	  DM.Title AS DivisionName,
	  ISNULL(CM.DisplayTitle,'')+'-'+ISNULL(DM.Title,'') as ClassDivisionName,
	  CM.IsObsolete,
	  CM.OrderIndex,
	  DM.OrgId,
	  DM.IsObsolete AS DivisionIsObsolete	  
  FROM 
	sSetup.tDivisionMaster DM
	INNER JOIN sSetup.tClassMaster CM ON CM.Id=DM.ClassId
	INNER JOIN sSetup.tBatchClass BC ON CM.Id=BC.ClassId
GO


GO
PRINT N'Altering [dbo].[fnd]...';


GO
-- exec fnd 'val1,val2'  
-- drop proc fnd  
ALTER proc [dbo].[fnd]  
@text varchar(200)  
as  
begin
declare @t varchar(10)=''
select @t = ''''
SELECT @t + ROUTINE_SCHEMA + '.' + ROUTINE_NAME + @t as Name FROM INFORMATION_SCHEMA.ROUTINES   
WHERE ROUTINE_DEFINITION LIKE '%' + @text + '%'   
AND ROUTINE_TYPE='PROCEDURE'  
end
GO
PRINT N'Altering [sAcademic].[pClassworkGet]...';


GO
ALTER PROCEDURE [sAcademic].[pClassworkGet]

	 @rId bigint,	 
	 @rSubjectId int,
	 @rClassId int,
	 @rEmployeeId bigint,
	 @rDivisionid int,
	 @rFromDate datetime,
     @rToDate datetime,
     @rOrgId int,
     @rBatchId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	
	
	SELECT 
			 AC.Id,
			 AC.EmployeeId,
			 AC.ClassId,
			 AC.DivisionId,
			 AC.SubjectId,
			AC.ClassWorkDate,
		    AC.Classwork,
		    AC.Homework,
		    --AC.HomeWorkEndDate,
		    ISNULL(AC.HomeWorkEndDate,'') AS HomeWorkEndDate,
		    AC.CreatedDateTime,
		    AC.BatchId,
   
		    ISNULL(SM.Title,'') as SubjectName,
		    ISNULL(EM.FirstName + EM.LastName,'') AS TeacherName,
		    ISNULL(CM.Title,'') AS ClassName,
		    ISNULL(DM.Title,'') AS DivisionName
	FROM 
			--sAcademic.tTeacherSubjectDivision TSD		
			sAcademic.tClasswork AC
			INNER JOIN sSetup.tSubjectMaster SM ON AC.SubjectId = SM.Id
			INNER JOIN sSetup.tDivisionMaster DM ON AC.DivisionId = DM.Id
			INNER JOIN sSetup.tClassMaster CM On AC.ClassId = CM.Id
			INNER JOIN sHrm.tEmployeeMaster EM On  AC.EmployeeId = EM.Id
	 
			
	WHERE 
	     AC.BatchId = @rBatchId
		AND ((AC.Id = @rId) OR (@rId = 0))
		AND ((AC.EmployeeId= @rEmployeeId) OR (@rEmployeeId = 0))
		AND	((AC.ClassId = @rClassId) OR (@rClassId = 0))
		AND	((DM.OrgId = @rOrgId) OR (@rOrgId = 0))
		AND ((AC.SubjectId =@rSubjectId) OR (@rSubjectId=0))
		AND ((AC.DivisionId =@rDivisionId) OR (@rDivisionId=0))
		AND (AC.ClassWorkDate>=@rFromDate OR ISNULL(@rFromDate,'')='')
		AND (AC.ClassWorkDate<=@rToDate OR ISNULL(@rToDate,'')='')
		order by AC.ClassWorkDate DESC
END
GO
PRINT N'Altering [sAcademic].[pClassworkStudentGet]...';


GO
ALTER PROCEDURE [sAcademic].[pClassworkStudentGet]
	 @rStudentId bigint,
	 @rBatchId int,	 
	 @rFromDate date,
     @rToDate date	 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	DECLARE @lDivisionId int
	SELECT @lDivisionId = DivisionId FROM sStudent.tAcademic WHERE StudentId = @rStudentId AND BatchId = @rBatchId
	
	SELECT 
			AC.Id,
			AC.EmployeeId,
			AC.ClassId,
			AC.DivisionId,
			AC.SubjectId,
		    AC.Classwork,
		    AC.Homework,
		    AC.ClassWorkDate,
		    AC.HomeWorkEndDate,
		    --ISNULL(AC.HomeWorkEndDate,'') AS HomeWorkEndDate,
		    ISNULL(SM.Title,'') as SubjectName,
		    ISNULL(EM.FirstName +' ' + EM.LastName,'') AS TeacherName,
		    ISNULL(CM.Title,'') AS ClassName,
		    ISNULL(DM.Title,'') AS DivisionName,
		    DM.OrgId
	FROM 
			sAcademic.tClasswork AC			 
			INNER Join sSetup.tSubjectMaster SM On SM.Id=AC.SubjectId
			INNER Join sHrm.tEmployeeMaster EM On EM.Id = AC.EmployeeId
			INNER Join sSetup.tClassMaster CM On CM.Id = AC.ClassId
			INNER Join sSetup.tDivisionMaster DM On DM.Id = AC.DivisionId
			
	WHERE 
	    AC.DivisionId = @lDivisionId		 
		AND (AC.ClassWorkDate>=@rFromDate OR ISNULL(@rFromDate,'')='')
		AND (AC.ClassWorkDate<=@rToDate OR ISNULL(@rToDate,'')='')
		order by  AC.CreatedDateTime desc
END
GO
PRINT N'Altering [sActivity].[pActivityGet]...';


GO
ALTER PROCEDURE [sActivity].[pActivityGet]
	 @rId int = 0,
	 @rTitle nvarchar(100),
	 @rActivityTypeId int,
	 @rFromDate date,
	 @rToDate date,
	 @rBatchId int,
	 @rIsSearch bit = 1
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 IF @rIsSearch = 1
		BEGIN
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		END
	
	SELECT 
	
			A.Id as ActivityId,
			A.Title,
			A.ActivityTypeId,
			ATM.Title AS ActivityType,
			A.FromDate,
			A.ToDate,
		    A.Remark,
		    A.IsGroup
		    
      
  FROM 
            sActivity.tActivity A
       INNER JOIN sActivity.tActivityTypeMaster ATM ON ATM.Id=A.ActivityTypeId
  WHERE 
  
      ((A.Id = @rId) OR (@rId = 0))
	AND ((A.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
	AND ((A.ActivityTypeId = @rActivityTypeId) OR (@rActivityTypeId = 0))
	AND ((A.FromDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	AND ((A.ToDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
	AND A.BatchId=@rBatchId
	ORDER BY A.CreatedDateTime DESC
END
GO
PRINT N'Altering [sActivity].[pEventAttendanceListGet]...';


GO

ALTER PROCEDURE [sActivity].[pEventAttendanceListGet]
	 
	@rClassId int=0,
	@rDivisionId int=0,
	@rOrgId int,
	@rCode nvarchar(20)='',
	@rFirstName nvarchar(100)='',
	@rBatchId int = 0,
	@rDepartmentId int=0,
	@rEventTypeId int = 0,
	@rEventId int=0,
	@rFromDate date='',
	@rToDate date='',
	@rAcademicId bigint=0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON			 

BEGIN 	 
		BEGIN
			SET @rCode= sCommon.fSearchStringGet(@rCode)
			SET @rFirstName= sCommon.fSearchStringGet(@rFirstName)
		END
	SELECT 
			SA.AcademicId,
			SA.FirstName,
			SA.Name,
			SA.Code,
			SA.ClassId,
			SA.ClassName+'-'+SA.DivisionName AS DivDept,
			--SA.DivisionId,
			SA.RollNo,
			SA.OrgId,
			ISNULL (EA.IsSelfPresent,0) AS IsSelfPresent,
			ISNULL (EA.IsMotherPresent,0) AS IsMotherPresent,
			ISNULL (EA.IsFatherPresent,0) AS IsFatherPresent,
			ISNULL (EA.IsGuardianPresent,0) AS IsGuardianPresent,
			ES.FromDate,
			ES.ToDate,
			EM.Title AS EventTypeName,
			ES.Title AS EventName,
			ES.EventTypeId AS EventTypeId,
			ISNULL (EA.EventScheduleId,0) as EventScheduleId,
		
			
			ISNULL (EA.SchoolFeedback,'') AS SchoolFeedback,
			ISNULL (EA.ParentFeedback,'') AS ParentFeedback,
			ISNULL (EA.ParentAction,'') AS ParentAction,
			ISNULL (EA.SchoolAction,'') AS SchoolAction,
		ISNULL (EA.IsTrackForReview,0) AS IsTrackForReview,
		SA.DepartmentName,
		SA.BatchName
			
		
			
  FROM 
			sStudent.vStudentAcademic SA 
			INNER JOIN sActivity.tEventAttendance EA ON  SA.AcademicId = EA.SourceId AND EA.SourceTypeId = 2001
			INNER JOIN sActivity.tEventSchedule ES ON EA.EventScheduleId=ES.Id 
			INNER JOIN sActivity.tEventTypeMaster EM ON EM.Id = ES.EventTypeId
  WHERE 
			((SA.ClassId=@rClassId)OR(@rClassId=0))
			AND((SA.DivisionId=@rDivisionId)OR(@rDivisionId=0))
			AND((SA.Code like @rCode) OR (ISNULL(@rCode,'') = '')) 
			AND((SA.FirstName like @rFirstName) OR (ISNULL(@rFirstName,'') = '')) 
			AND(SA.OrgId=@rOrgId)
			AND(SA.BatchId=@rBatchId or @rBatchId = 0)
			AND(SA.DepartmentId=@rDepartmentId or @rDepartmentId = 0)
			AND ((ES.EventTypeId = @rEventTypeId) OR (@rEventTypeId = 0))
			AND ((ES.Id = @rEventId) OR (@rEventId = 0))
			AND ((ES.FromDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((ES.ToDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
				AND((SA.AcademicId=@rAcademicId)OR(@rAcademicId=0)) 
			ORDER BY SA.ClassId,SA.DivisionId
END
GO
PRINT N'Altering [sActivity].[pEventScheduleGet]...';


GO
ALTER PROCEDURE [sActivity].[pEventScheduleGet]

	 @rId int = 0,
	 @rTitle nvarchar(100),
	 @rFromDate date,
	 @rToDate date,
	 @rBatchId int,
	 @rIsSearch bit = 1,
	 @rEventTypeId int = 0
	 --@rSyncedEventScheduleId int = 0
	 
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 IF @rIsSearch = 1
		BEGIN
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		END
	
	SELECT 
	
			ES.Id as EventScheduleId,
			ES.Title,
			ES.FromDate,
			ES.ToDate,
		    ES.Remark,
		    ES.IsCommonForAll,
		    ES.IsHoliday,
		    ES.IsEnrollment,
		    ISNULL(ES.EventTypeId,0) AS EventTypeId,
		    ISNULL(EM.Title,'') AS EventType,
		    EM.HighlightColor,
		    EM.Title AS EventTypeName,
		    OM.Id as OrgId,
		    OM.WeekOffs
      
  FROM 
            sActivity.tEventSchedule ES
            LEFT JOIN sActivity.tEventTypeMaster EM ON EM.Id = ES.EventTypeId
            INNER JOIN sSetup.tBatchMaster BM ON BM.Id = ES.BatchId
            INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
			--LEFT JOIN sSetup.tOrganizationMaster OM ON OM. = ES.BatchId
  WHERE 
  
      ((ES.Id = @rId) OR (@rId = 0))
	AND ((ES.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
	AND ((ES.FromDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	AND ((ES.ToDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
	AND ES.BatchId=@rBatchId
	--AND ( ES.Id > @rSyncedEventScheduleId OR @rSyncedEventScheduleId = 0)
	AND (( ES.EventTypeId = @rEventTypeId) OR (@rEventTypeId = 0))

	ORder by ES.FromDate desc	
END
GO
PRINT N'Altering [sAdmission].[pAdmissionInquiryAdd]...';


GO
ALTER PROCEDURE [sAdmission].[pAdmissionInquiryAdd]
		 @rId bigint
		,@rFirstName nvarchar(100)
		,@rMiddleName nvarchar(100)
		,@rLastName nvarchar(100)
		,@rForClassId int
		,@rForBatchId	int =0
		--,@rForBatch	nvarchar(20)
		,@rDateOfBirth date
		,@rOrgId smallint
		--,@rStatusId	smallint
		,@rInquiryStatusMasterId int
		,@rStreetOne nvarchar(50)
		,@rStreetTwo nvarchar(50)
		,@rStreetThree nvarchar(50)
		,@rCountry nvarchar(50)
		,@rState nvarchar(50)
		,@rCity	nvarchar(50)
		,@rZipCode nvarchar(20)
		,@rContactNo nvarchar(20)
		,@rContactEmail	nvarchar(50)
		,@rRemark nvarchar(200)
		,@rInquiryModeId tinyint
		,@rInquiryReferenceId int
		,@rAdmissionCategoryId int
		,@rPreviousSchool nvarchar(200)
		,@rMeritMarks decimal(10,2) 
		,@rMeritGrade nvarchar(20)
		,@rMeritMarksBreakup nvarchar(100)
		,@rGenderId tinyint
		,@rFollowupDate date
		,@rFollowupRemark nvarchar(150)
		,@rCreatedUserId bigint
		,@rInquiryDate date
		,@rNumber bigint 
		,@rHandledBy nvarchar 
		,@rOrgGroupId int,
		@rCastCategoryId int=0,
		@rIsHostelRequired bit=0,
		@rIsTransportRequired bit=0,
		@rIsValidateInquiryAsPerAdmission bit=0 
	 
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	-- BEGIN TRY
	Declare @lStatusId smallint,@lIsValidateBirthdate bit,@lFromDateOfBirth date,@lToDateOfBirth date
	SET @lStatusId=0
	 
	 
	if(@rIsValidateInquiryAsPerAdmission=1)
	Begin
		Select @lIsValidateBirthdate=IsValidateBirthdate,@lFromDateOfBirth=FromDateOfBirth,@lToDateOfBirth=ToDateOfBirth from  sAdmission.tAdmissionCriteria where ClassId=@rForClassId AND BatchID=@rForBatchId
		
		if(@lIsValidateBirthdate=1 AND @rDateOfBirth NOT between @lFromDateOfBirth And @lToDateOfBirth)
		BEGIN
			Select  -101 AS Result
			return
		End
	End
	 
 BEGIN TRANSACTION	
IF(@rId = 0)	
	BEGIN	

 DECLARE @lNextNumber BIGINT 
 EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAdmission.tAdmissionInquiry', 0, 1, 1,@outNextNumber = @lNextNumber output
			
	INSERT INTO sAdmission.tAdmissionInquiry
		(
			 Id
			,FirstName
			,MiddleName
			,LastName
			,ForClassId			 
			,ForBatchId
			,DateOfBirth
			,OrgId
			,StatusId
			,StreetOne
			,StreetTwo
			,StreetThree
			,Country
			,State
			,City
			,ZipCode
			,ContactNo
			,ContactEmail
			,Remark
			,InquiryModeId
			,InquiryReferenceId
			,AdmissionCategoryId
			,PreviousSchool
			,MeritMarks
			,MeritGrade
			,MeritMarksBreakup
			,GenderId
			,FollowupDate
			,FollowupRemark
			,CreatedUserId
			,CreatedDateTime
			,InquiryDate
			,Number
			,HandledBy
			,OrgGroupId
			,InquiryStatusId,
			CastCategoryId,
			IsHostelRequired,
			IsTransportRequired
		)
	VALUES
		(
			 @lNextNumber
			,@rFirstName
			,@rMiddleName
			,@rLastName
			,@rForClassId
			,@rForBatchId			 
			,@rDateOfBirth
			,@rOrgId
			,@lStatusId
			,@rStreetOne
			,@rStreetTwo
			,@rStreetThree
			,@rCountry
			,@rState
			,@rCity
			,@rZipCode
			,@rContactNo
			,@rContactEmail
			,@rRemark
			,@rInquiryModeId
			,@rInquiryReferenceId
			,@rAdmissionCategoryId
			,@rPreviousSchool
			,@rMeritMarks
			,@rMeritGrade
			,@rMeritMarksBreakup
			,@rGenderId
			,@rFollowupDate
			,@rFollowupRemark
			,@rCreatedUserId
			,sCommon.fGetDate()
			,@rInquiryDate
			,@rNumber
			,@rHandledBy
			,@rOrgGroupId
			,@rInquiryStatusMasterId,
			@rCastCategoryId,
			@rIsHostelRequired,
			@rIsTransportRequired
		)
		    SELECT 1 AS Result         
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sAdmission.tAdmissionInquiry
	    SET
			 FirstName=@rFirstName
			,MiddleName=@rMiddleName
			,LastName=@rLastName
			,ForClassId=@rForClassId
			,ForBatchId = @rForBatchId		 
			,DateOfBirth=@rDateOfBirth
			,OrgId=@rOrgId
			,StatusId=@lStatusId
			,StreetOne=@rStreetOne
			,StreetTwo=@rStreetTwo
			,StreetThree=@rStreetThree
			,Country=@rCountry
			,State=@rState
			,City=@rCity
			,ZipCode=@rZipCode
			,ContactNo=@rContactNo
			,ContactEmail=@rContactEmail
			,Remark=@rRemark
			,InquiryModeId=@rInquiryModeId
			,InquiryReferenceId=@rInquiryReferenceId 
			,AdmissionCategoryId=@rAdmissionCategoryId
			,PreviousSchool=@rPreviousSchool
			,MeritMarks=@rMeritMarks
			,MeritGrade=@rMeritGrade
			,MeritMarksBreakup=@rMeritMarksBreakup
			,GenderId=@rGenderId
			,FollowupDate=@rFollowupDate
			,FollowupRemark=@rFollowupRemark
			,UpdatedUserId=@rCreatedUserId
			,UpdatedDateTime=sCommon.fGetDate()
			,InquiryDate=@rInquiryDate
			,HandledBy=@rHandledBy
			,InquiryStatusId = @rInquiryStatusMasterId,
			CastCategoryId = @rCastCategoryId,
			IsHostelRequired=@rIsHostelRequired,
			IsTransportRequired=@rIsTransportRequired
			
	      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 [sAlert].[pNotificationLogGet]...';


GO
 

ALTER PROCEDURE [sAlert].[pNotificationLogGet]

		@rOSTypeId tinyint,
		@rUserId bigint,
		@rUserSourceTypeId smallint,
		@rUserSourceId bigint,
		@rSyncedNotificationId bigint
			 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	
	DECLARE @lAcademicId bigint
	DECLARE @lEmployeeId bigint
	DECLARE @lStudentId bigint
	DECLARE @lDivisionId int
	DECLARE @lClassId int
	DECLARE @lDepartmentId int
	DECLARE @lOrgId int
	
	IF(@rUserSourceTypeId=2003)
	BEGIN
		SELECT 
		@lAcademicId=AcademicId,
		@lStudentId=StudentId,
		@lDivisionId=DivisionId,
		@lClassId=ClassId,
		@lDepartmentId=DepartmentId,
		@lOrgId=OrgId
		FROM sStudent.vStudentAcademic WHERE StudentId = @rUserSourceId AND IsActiveBatch=1
	
		SELECT 
				NL.Id AS NotificationId,
				NL.EventId,
				NL.DocumentId,
				NL.MessageTitle,
				NL.NotificationMessage AS 'Message',
				CONVERT(VARCHAR(25), NL.CreatedDateTime, 100) AS CreatedDateTime
		FROM 
			sAlert.tNotificationLog NL
		WHERE 
		(
		(NL.SourceId=@lAcademicId) AND (NL.SourceTypeId=2001)
		OR (NL.SourceId=@lStudentId) AND (NL.SourceTypeId=2003)
		OR (NL.SourceId=@lDivisionId) AND (NL.SourceTypeId=2005)
		OR (NL.SourceId=@lClassId) AND (NL.SourceTypeId=2016)
		OR (NL.SourceId=@lDepartmentId) AND (NL.SourceTypeId=2017)
		OR (NL.SourceId=@lOrgId) AND (NL.SourceTypeId=2021)	
		) AND Id > @rSyncedNotificationId AND OSTypeId=@rOSTypeId
	END
		
	IF(@rUserSourceTypeId=95)
	BEGIN
	
		SELECT 
		@lEmployeeId=EmployeeId,
		@lDepartmentId=OrganizationDepartmentId,
		@lOrgId=OrgId
		FROM sHrm.tEmployeeJobDetail WHERE EmployeeId = @rUserSourceId
		SELECT 
				NL.Id AS NotificationId,
				NL.EventId,
				NL.DocumentId,
				NL.MessageTitle,
				NL.NotificationMessage AS 'Message',
				CONVERT(VARCHAR(25), NL.CreatedDateTime, 100) AS CreatedDateTime
		FROM 
			sAlert.tNotificationLog NL
		WHERE 
		(
		(NL.SourceId=@lEmployeeId) AND (NL.SourceTypeId=95)
		OR (NL.SourceId=@lDepartmentId) AND (NL.SourceTypeId=2017)
		OR (NL.SourceId=@lOrgId) AND (NL.SourceTypeId=2021)	
		) AND Id > @rSyncedNotificationId AND OSTypeId=@rOSTypeId
	END
	
END
GO
PRINT N'Altering [sAlert].[pOtherGroupDetailGet]...';


GO
 
ALTER PROCEDURE [sAlert].[pOtherGroupDetailGet]
	 
	 @rOtherGroupId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 		
		
	SELECT 
			OGM.Title,
			OGM.Code,
			OGM.IsObsolete,
			ISNULL(OGM.Id,0) AS OtherGroupId,
			ISNULL(OGD.MobileNo,'') AS MobileNo,
			ISNULL(OGD.Email,'') AS Email,
			ISNULL(OGD.Title,'') AS OtherGroupDetailTitle
  FROM 
			sAlert.tOtherGroupMaster OGM
			LEFT JOIN sAlert.tOtherGroupDetail OGD ON OGD.OtherGroupId=OGM.Id
WHERE 
			OGM.Id=@rOtherGroupId
END
GO
PRINT N'Altering [sAssessment].[pCCEExamCombineGet]...';


GO
ALTER PROCEDURE [sAssessment].[pCCEExamCombineGet]
	 @rClassId int
	,@rCCEExamId SMALLINT
	,@rBatchId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 		
	SELECT 
	 EC.SubExamId AS SubExamId,
	EM.ClassId AS ClassId ,
	 ISNULL(EC.Weightage,0) AS Weightage,
	 ISNULL(ExamOrder,0) AS ExamOrder
  FROM 
			[sAssessment].[tExamMaster] EM
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=EM.ClassId
			
			 INNER JOIN sAssessment.tExamCombine EC ON EC.ExamId=EM.Id
			 INNER JOIN sAssessment.tCCEExamSetting CS ON CS.CLASSID = CM.ID 
			AND CS.ExamSubGroupId = EM.ExamSubGroupId
WHERE 
			((EM.ClassId=@rClassId) OR (@rClassId=0))  
			AND ((EM.BatchId = @rBatchId) Or (@rBatchId = 0))
			 AND CS.CCEExamId = @rCCEExamId
		
			ORDER BY EM.ExamSubGroupId ASC
		
END
GO
PRINT N'Altering [sAssessment].[pCCEResultAdd]...';


GO


ALTER PROCEDURE [sAssessment].[pCCEResultAdd] 
	        @rAcademicId bigint
		   ,@rUpdatedUserId bigint
		   ,@rOrgId int
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	--BEGIN TRY
	
	 --BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 
	 DECLARE @lCCEResultId  BIGINT

SELECT @lCCEResultId = ISNULL(AcademicId,0) FROM sAssessment.tCCEResult WHERE AcademicId=@rAcademicId	 

--SET @lCCEResultId = ISNULL(@rAcademicId,0)

IF(ISNULL(@lCCEResultId,0) = 0)	
BEGIN
	--EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAssessment.tCCEResult', 0, 1, 1,@outNextNumber = @lNextNumber output
	INSERT INTO [sAssessment].[tCCEResult]
			   (
			  [AcademicId]
			   ,[UpdatedUserId]
			   ,[UpdatedDateTime]
			   )
		 VALUES
			   (
				@rAcademicId
			   ,@rUpdatedUserId		   
			   ,sCommon.fGetDate()
			   )
		    --SELECT 1 AS Result
	
		--COMMIT TRANSACTION         
	END	 
--ELSE
--	 BEGIN
	 --SET @lNextNumber = @lCCEResultId
	 --   UPDATE  [sAssessment].[tCCEResult]
	 --   SET		 
		--		UpdatedUserId =@rUpdatedUserId
		--	 ,UpdatedDateTime=sCommon.fGetDate()
	 --     WHERE AcademicId = @rAcademicId
	      --SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION
	 --END  
		
	--END
--END	
--COMMIT TRANSACTION		
--	END TRY
	
--	BEGIN CATCH 
--		ROLLBACK TRANSACTION
--		SELECT -1 AS Result
--	END CATCH	
		
END
GO
PRINT N'Altering [sAssessment].[pCCEResultDetailAdd]...';


GO


ALTER PROCEDURE [sAssessment].[pCCEResultDetailAdd]
	 
	     
            @rAcademicId bigint
		   ,@rClassSubjectId int
		   ,@rObtain decimal(6,2)		
		   ,@rExamOrder int
		   ,@rCCEExamId INT  -- CCEId
		   ,@rSubExamId INT  -- CCEId
		   ,@rOrgId int
		   ,@rIsPresent bit = null,
		   @rCCEGradePointMarks decimal(6,2)=0,
		   @rClassId int=0
		 
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	--BEGIN TRY
	
	-- BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 
	 DECLARE @lMaxiMark decimal(6,2)
	 SELECT  @lMaxiMark = Maximum FROM sAssessment.tExamDetail Where ExamId = @rSubExamId AND ClassSubjectId = @rClassSubjectId
	 DECLARE @lCCEResultDetailId BIGINT

SELECT @lCCEResultDetailId= ISNULL(AcademicId,0) From sAssessment.tCCEResultDetail Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
--Select @rObtain
 
IF ISNULL(@lCCEResultDetailId,0) = 0
	 BEGIN

	--EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAssessment.tCCEResultDetail', 0, 1, 1,@outNextNumber = @lNextNumber output	
	 
	INSERT INTO [sAssessment].[tCCEResultDetail]
			   (
				[AcademicId] 
			   ,[ClassSubjectId]
			   ,[GradePointFA1]
			   ,[GradePointFA2]
			   ,[GradePointSA1]
			   ,[GradePointFA3]
			   ,[GradePointFA4]
			   ,[GradePointSA2]
			   ,[UpdatedUserId]
			   ,[UpdatedDateTime]
			   )
		 VALUES
			   (
			    @rAcademicId
			   ,@rClassSubjectId
			   ,0.00
			   ,0.00
			   ,0.00
			   ,0.00
			   ,0.00
			   ,0.00
			   ,0
			   ,sCommon.fGetDate()
			   )
  
			 
     			IF(@rExamOrder=1) UPDATE [sAssessment].[tCCEResultDetail] SET [FA1]=ISNULL(@rObtain,0),IsPresentFA1=@rIsPresent,GRADEPOINTFA1 =(@rCCEGradePointMarks *ISNULL(@rObtain,0))/@lMaxiMark Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
			ELSE IF(@rExamOrder=2) UPDATE [sAssessment].[tCCEResultDetail] SET [FA2]=ISNULL(@rObtain,0),IsPresentFA2=@rIsPresent,GradePointFA2 =(@rCCEGradePointMarks * ISNULL(@rObtain,0))/@lMaxiMark Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
			ELSE IF(@rExamOrder=3) UPDATE [sAssessment].[tCCEResultDetail] SET [SA1]=ISNULL(@rObtain,0),IsPresentSA1=@rIsPresent,GradePointSA1 =(@rCCEGradePointMarks *ISNULL(@rObtain,0) )/@lMaxiMark Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
			ELSE IF(@rExamOrder=4) UPDATE [sAssessment].[tCCEResultDetail] SET [FA3]=ISNULL(@rObtain,0),IsPresentFA3=@rIsPresent,GradePointFA3 = (@rCCEGradePointMarks * ISNULL(@rObtain,0))/@lMaxiMark  Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
			ELSE IF(@rExamOrder=5) UPDATE [sAssessment].[tCCEResultDetail] SET [FA4]=ISNULL(@rObtain,0),IsPresentFA4=@rIsPresent,GradePointFA4 =(@rCCEGradePointMarks * ISNULL(@rObtain,0))/@lMaxiMark Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
			ELSE IF(@rExamOrder=6) UPDATE [sAssessment].[tCCEResultDetail] SET [SA2]=ISNULL(@rObtain,0),IsPresentSA2=@rIsPresent,GradePointSA2 =(@rCCEGradePointMarks *ISNULL(@rObtain,0) )/@lMaxiMark  Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
	
			UPDATE [sAssessment].[tCCEResultDetail] SET [FA]= ISNULL(FA1,0)+ISNULL(FA2,0)+ISNULL(FA3,0)+ISNULL(FA4,0),FAGradePoint=ROUND(GradePointFA1+GradePointFA2+GradePointFA3 +GradePointFA4,0) Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
			UPDATE [sAssessment].[tCCEResultDetail] SET [SA]=ISNULL(SA1,0)+ISNULL(SA2,0),SAGradePoint = ROUND( GradePointSA1+GradePointSA2  ,0) Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
			UPDATE [sAssessment].[tCCEResultDetail] SET [Term1]= ISNULL(FA1,0)+ISNULL(FA2,0)+ISNULL(SA1,0), Term1GradePoint = ROUND( GradePointFA1+GradePointFA2+GradePointSA1 ,0) Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
			UPDATE [sAssessment].[tCCEResultDetail] SET [Term2]=ISNULL(FA3,0)+ISNULL(FA4,0)+ISNULL(SA2,0),Term2GradePoint = ROUND( GradePointFA3+GradePointFA4+GradePointSA2 ,0) Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
			UPDATE [sAssessment].[tCCEResultDetail] SET [TOTAL]=ISNULL(FA1,0)+ISNULL(FA2,0)+ISNULL(FA3,0)+ISNULL(FA4,0)+ISNULL(SA1,0)+ISNULL(SA2,0) Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
		    SELECT @rAcademicId AS Result
	
		--COMMIT TRANSACTION         
	END	 
ELSE
	 BEGIN
	
	    --UPDATE  [sAssessment].[tCCEResultDetail]
	    --SET  
	    --     [UpdatedDateTime]=sCommon.fGetDate()
	    --  WHERE [AcademicId] =@rAcademicId
	     	 
	     
	        IF(@rExamOrder=1) UPDATE [sAssessment].[tCCEResultDetail] SET [FA1]=ISNULL(@rObtain,0),IsPresentFA1=@rIsPresent,GRADEPOINTFA1 =(@rCCEGradePointMarks *ISNULL(@rObtain,0))/@lMaxiMark Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
			ELSE IF(@rExamOrder=2) UPDATE [sAssessment].[tCCEResultDetail] SET [FA2]=ISNULL(@rObtain,0),IsPresentFA2=@rIsPresent,GradePointFA2 =(@rCCEGradePointMarks * ISNULL(@rObtain,0))/@lMaxiMark Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
			ELSE IF(@rExamOrder=3) UPDATE [sAssessment].[tCCEResultDetail] SET [SA1]=ISNULL(@rObtain,0),IsPresentSA1=@rIsPresent,GradePointSA1 =(@rCCEGradePointMarks *ISNULL(@rObtain,0) )/@lMaxiMark Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
			ELSE IF(@rExamOrder=4) UPDATE [sAssessment].[tCCEResultDetail] SET [FA3]=ISNULL(@rObtain,0),IsPresentFA3=@rIsPresent,GradePointFA3 = (@rCCEGradePointMarks * ISNULL(@rObtain,0))/@lMaxiMark  Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
			ELSE IF(@rExamOrder=5)UPDATE [sAssessment].[tCCEResultDetail] SET [FA4]=ISNULL(@rObtain,0),IsPresentFA4=@rIsPresent,GradePointFA4 =(@rCCEGradePointMarks * ISNULL(@rObtain,0))/@lMaxiMark Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
			ELSE UPDATE [sAssessment].[tCCEResultDetail] SET [SA2]=ISNULL(@rObtain,0),IsPresentSA2=@rIsPresent,GradePointSA2 =(@rCCEGradePointMarks *ISNULL(@rObtain,0) )/@lMaxiMark  Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
			
			UPDATE [sAssessment].[tCCEResultDetail] SET [FA]= ISNULL(FA1,0)+ISNULL(FA2,0)+ISNULL(FA3,0)+ISNULL(FA4,0),FAGradePoint=ROUND(GradePointFA1+GradePointFA2+GradePointFA3 +GradePointFA4,0) Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
			UPDATE [sAssessment].[tCCEResultDetail] SET [SA]=ISNULL(SA1,0)+ISNULL(SA2,0),SAGradePoint = ROUND( GradePointSA1+GradePointSA2  ,0) Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
			UPDATE [sAssessment].[tCCEResultDetail] SET [Term1]= ISNULL(FA1,0)+ISNULL(FA2,0)+ISNULL(SA1,0),Term1GradePoint = ROUND( GradePointFA1+GradePointFA2+GradePointSA1 ,0) Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
			UPDATE [sAssessment].[tCCEResultDetail] SET [Term2]=ISNULL(FA3,0)+ISNULL(FA4,0)+ISNULL(SA2,0),Term2GradePoint = ROUND( GradePointFA3+GradePointFA4+GradePointSA2 ,0) Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
			UPDATE [sAssessment].[tCCEResultDetail] SET [TOTAL]=ISNULL(FA1,0)+ISNULL(FA2,0)+ISNULL(FA3,0)+ISNULL(FA4,0)+ISNULL(SA1,0)+ISNULL(SA2,0) Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
			 
		 
			--SELECT @rAcademicId AS Result
	
	 END  
		
--Grade Evaluation
DECLARE @MinimumScore decimal(5,2)
DECLARE @GradeTitle nvarchar(10)
DECLARE @GradePoint decimal(6,2)
DECLARE @lCount int
DECLARE @lDataSetID INT  
--DECLARE @lClassId int

DECLARE @lTempMark decimal(6,2)
 

--SELECT @lDataSetID=GradeSetId FROM sAssessment.tExamDetail WHERE ExamId = @rCCEExamId AND ClassSubjectId = @rClassSubjectId
  --SELECT @lClassId = ClassId From sStudent.tAcademic Where Id =  @rAcademicId 	
  SELECT @lDataSetID=GradeSetId  FROM sAssessment.tCCEExamSetting WHERE CCEExamId = @rCCEExamId AND ClassId = @rClassId

CREATE TABLE #tempGradeSetDetail
	(
		Id INT IDENTITY (1, 1),
		MinimumScore decimal(5,2),
		GradeTitle nvarchar(10),
		GradePoint decimal(6,2) 					 
	) 
	INSERT INTO #tempGradeSetDetail
	SELECT MinimumScore,GradeCode,GradePoint		
	FROM sAssessment.tGradeSetDetail where GradesetId=@lDataSetID
	order by MinimumScore DESC

SELECT @lCount =  COUNT(Id) FROM #tempGradeSetDetail
DECLARE @lloopCount int
--set @lloopCount=1
while ( @lCount > 0 )
BEGIN
		SELECT @MinimumScore =MinimumScore,@GradeTitle=GradeTitle,@GradePoint=GradePoint
		FROM #tempGradeSetDetail WHERE Id = @lCount
		 
		IF @rExamOrder = 1 
		BEGIN				
			Update sAssessment.tCCEResultDetail  Set GradeFA1 = @GradeTitle,FA1Max=@lMaxiMark WHERE AcademicId=@rAcademicId AND ClassSubjectID=@rClassSubjectId AND (FA1 * 100)/@lMaxiMark  >= @MinimumScore 
			
		END
		IF @rExamOrder = 2 
		BEGIN							
			Update sAssessment.tCCEResultDetail  Set GradeFA2 = @GradeTitle,FA2Max=@lMaxiMark WHERE AcademicId=@rAcademicId AND ClassSubjectID=@rClassSubjectId AND (FA2 * 100)/@lMaxiMark >= @MinimumScore 
			
		END
		IF @rExamOrder = 3 
		BEGIN				
			Update sAssessment.tCCEResultDetail  Set GradeSA1 = @GradeTitle,SA1Max=@lMaxiMark WHERE AcademicId=@rAcademicId AND ClassSubjectID=@rClassSubjectId AND (SA1 * 100)/@lMaxiMark >= @MinimumScore 
			 
		END
		IF @rExamOrder = 4 
		BEGIN				
			Update sAssessment.tCCEResultDetail  Set GradeFA3 = @GradeTitle,FA3Max=@lMaxiMark WHERE AcademicId=@rAcademicId AND ClassSubjectID=@rClassSubjectId AND (FA3 * 100)/@lMaxiMark >= @MinimumScore 
			
		END
		IF @rExamOrder = 5 
		BEGIN				
			Update sAssessment.tCCEResultDetail  Set GradeFA4 = @GradeTitle,FA4Max=@lMaxiMark WHERE AcademicId=@rAcademicId AND ClassSubjectID=@rClassSubjectId AND (FA4 * 100)/@lMaxiMark >= @MinimumScore 
			 
		END
		IF @rExamOrder = 6 
		BEGIN		
			Update sAssessment.tCCEResultDetail  Set GradeSA2 = @GradeTitle,SA2Max=@lMaxiMark WHERE AcademicId=@rAcademicId AND ClassSubjectID=@rClassSubjectId AND (SA2 * 100)/@lMaxiMark >= @MinimumScore 
			 
		END
			SELECT @lTempMark = ISNULL(FA1MAX,0)+ISNULL(FA2MAX,0)+ISNULL(FA3MAX,0)+ISNULL(FA4MAX,0) FROM sAssessment.tCCEResultDetail WHERE AcademicId=@rAcademicId AND ClassSubjectID=@rClassSubjectId 
			IF @lTempMark <> 0 
			BEGIN
				Update sAssessment.tCCEResultDetail  Set FAGRADE = @GradeTitle WHERE AcademicId=@rAcademicId AND ClassSubjectID=@rClassSubjectId 
				AND (FA * 100)/@lTempMark >= @MinimumScore 
			END

SELECT @lTempMark = ISNULL(FA1MAX,0)+ISNULL(FA2MAX,0) FROM sAssessment.tCCEResultDetail WHERE AcademicId=@rAcademicId AND ClassSubjectID=@rClassSubjectId 
			IF @lTempMark <> 0 
			BEGIN
				Update sAssessment.tCCEResultDetail  Set [FATerm1] = @GradeTitle WHERE AcademicId=@rAcademicId AND ClassSubjectID=@rClassSubjectId 
				AND ((FA1+FA2) * 100)/@lTempMark >= @MinimumScore 
			END

SELECT @lTempMark = ISNULL(FA3MAX,0)+ISNULL(FA4MAX,0) FROM sAssessment.tCCEResultDetail WHERE AcademicId=@rAcademicId AND ClassSubjectID=@rClassSubjectId 
			IF @lTempMark <> 0 
			BEGIN
				Update sAssessment.tCCEResultDetail  Set [FATerm2] = @GradeTitle WHERE AcademicId=@rAcademicId AND ClassSubjectID=@rClassSubjectId 
				AND ((FA3+FA4) * 100)/@lTempMark >= @MinimumScore 
			END
			
			SELECT @lTempMark = ISNULL(SA1MAX,0)+ISNULL(SA2MAX,0) FROM sAssessment.tCCEResultDetail WHERE AcademicId=@rAcademicId AND ClassSubjectID=@rClassSubjectId 
			IF @lTempMark <> 0 
			BEGIN
				Update sAssessment.tCCEResultDetail  Set SAGRADE = @GradeTitle WHERE AcademicId=@rAcademicId AND ClassSubjectID=@rClassSubjectId 
				AND (SA * 100)/@lTempMark >= @MinimumScore 
			END
			
			SELECT @lTempMark = ISNULL(FA1MAX,0)+ISNULL(FA2MAX,0)+ISNULL(SA1MAX,0) FROM sAssessment.tCCEResultDetail WHERE AcademicId=@rAcademicId AND ClassSubjectID=@rClassSubjectId 
			IF @lTempMark <> 0 
			BEGIN
				Update sAssessment.tCCEResultDetail  Set Term1Grade = @GradeTitle WHERE AcademicId=@rAcademicId AND ClassSubjectID=@rClassSubjectId 
				AND (TERM1 * 100)/@lTempMark >= @MinimumScore 
			END
			
			SELECT @lTempMark = ISNULL(FA3MAX,0)+ISNULL(FA4MAX,0)+ISNULL(SA2MAX,0) FROM sAssessment.tCCEResultDetail WHERE AcademicId=@rAcademicId AND ClassSubjectID=@rClassSubjectId 
			IF @lTempMark <> 0 
			BEGIN	
				Update sAssessment.tCCEResultDetail  Set Term2Grade = @GradeTitle WHERE AcademicId=@rAcademicId AND ClassSubjectID=@rClassSubjectId 
				AND (TERM2 * 100)/@lTempMark >= @MinimumScore 
			END
		
			SELECT @lTempMark = ISNULL(FA1MAX,0)+ISNULL(FA2MAX,0)+ISNULL(SA1MAX,0)+ISNULL(FA1MAX,0)+ISNULL(FA2MAX,0)+ISNULL(SA1MAX,0) FROM sAssessment.tCCEResultDetail WHERE AcademicId=@rAcademicId AND ClassSubjectID=@rClassSubjectId 
			IF @lTempMark <> 0  
			BEGIN
				Update sAssessment.tCCEResultDetail  Set Grade = @GradeTitle WHERE AcademicId=@rAcademicId AND ClassSubjectID=@rClassSubjectId 
				AND (TOTAL * 100)/@lTempMark >= @MinimumScore 
			END 
		SET @lCount = @lCount - 1
 END
	--End Grade Evaluation	
--END	
--COMMIT TRANSACTION		
--	END TRY
	
--	BEGIN CATCH 
--		ROLLBACK TRANSACTION
--		SELECT -1 AS Result
--	END CATCH	
		
END
GO
PRINT N'Altering [sAssessment].[pCCEResultDetailSubjectGradeUpdate]...';


GO
ALTER PROCEDURE [sAssessment].[pCCEResultDetailSubjectGradeUpdate]
	  
	
	  @rExamOrder INT
	 ,@rCCEExamId INT
	 ,@rSubExamId INT
	 ,@rBatchId INT
	 ,@rClassId INT,
	 @rDivisionId int
	
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 	
--BEGIN TRY
-- BEGIN TRANSACTION		
		DECLARE @MinimumScore decimal(5,2)
		DECLARE @GradeTitle nvarchar(10)
		DECLARE @GradePoint decimal(6,2)
		DECLARE @lCount int
		DECLARE @lDataSetID INT
		DECLARE @lMaxiMark Decimal(5,2)
		--SELECT @lDataSetID=GradeSetId FROM sAssessment.tExamMaster WHERE Id = @rCCEExamId 
	--	 SELECT @lDataSetID=GradeSetId FROM sAssessment.tCCEExamSetting WHERE CCEExamId = @rCCEExamId AND ClassId = @rClassId
		
	--	CREATE TABLE #tempGradeSetDetail
	--		(
	--			Id INT IDENTITY (1, 1),
	--			MinimumScore decimal(5,2),
	--			GradeTitle nvarchar(10),
	--			GradePoint decimal(6,2) 					 
	--		) 
	--		INSERT INTO #tempGradeSetDetail
	--		SELECT MinimumScore,GradeCode,GradePoint		
	--		FROM sAssessment.tGradeSetDetail where GradesetId=@lDataSetID
	--		order by Id Asc

	--	SELECT @lCount =  COUNT(Id) FROM #tempGradeSetDetail
	--	DECLARE @lloopCount int
	--	set @lloopCount=1
	--	SELECT @lCount =  COUNT(Id) FROM #tempGradeSetDetail
 --set @lloopCount=1
 --while (@lloopCount <= @lCount )
 --BEGIN
	--SELECT
	--	@MinimumScore =MinimumScore,
	--	@GradeTitle=GradeTitle,
	--	@GradePoint=GradePoint
	--	FROM #tempGradeSetDetail WHERE Id = @lloopCount
			
		
		 
	--	SET @lloopCount = @lloopCount + 1
		
 --END
 	   
 	--    Update sAssessment.tCCEResultDetail  Set FA = ROUND((FA1+FA2+FA3 +FA4),0) WHERE AcademicId IN (Select Id From sStudent.tAcademic Where ClassId=@rClassId And BatchId=@rBatchId)
		--Update sAssessment.tCCEResultDetail  Set SA = ROUND((SA1+SA2),0) WHERE AcademicId IN (Select Id From sStudent.tAcademic Where ClassId=@rClassId And BatchId=@rBatchId)
		--Update sAssessment.tCCEResultDetail  Set Term1 = ROUND((FA1+FA2+SA1),0) WHERE AcademicId IN (Select Id From sStudent.tAcademic Where ClassId=@rClassId And BatchId=@rBatchId)
		--Update sAssessment.tCCEResultDetail  Set Term2 = ROUND((FA3+FA4+SA2),0)  WHERE AcademicId IN (Select Id From sStudent.tAcademic Where ClassId=@rClassId And BatchId=@rBatchId)
		--Update sAssessment.tCCEResultDetail  Set TOTAL = ROUND((FA1+FA2+FA3 +FA4 + SA1 +SA2),0) WHERE AcademicId IN (Select Id From sStudent.tAcademic Where ClassId=@rClassId And BatchId=@rBatchId)
		
		--Update sAssessment.tCCEResultDetail  Set FAGradePoint = ROUND((GradePointFA1+GradePointFA2+GradePointFA3 +GradePointFA4)/4,0) WHERE AcademicId IN (Select Id From sStudent.tAcademic Where ClassId=@rClassId And BatchId=@rBatchId)
		--Update sAssessment.tCCEResultDetail  Set SAGradePoint = ROUND((GradePointSA1+GradePointSA2/2),0) WHERE AcademicId IN (Select Id From sStudent.tAcademic Where ClassId=@rClassId And BatchId=@rBatchId)
		--Update sAssessment.tCCEResultDetail  Set Term1GradePoint = ROUND((GradePointFA1+GradePointFA2+GradePointSA1)/3,0) WHERE AcademicId IN (Select Id From sStudent.tAcademic Where ClassId=@rClassId And BatchId=@rBatchId)
		--Update sAssessment.tCCEResultDetail  Set Term2GradePoint = ROUND((GradePointFA3+GradePointFA4+GradePointSA2)/3,0) WHERE AcademicId IN (Select Id From sStudent.tAcademic Where ClassId=@rClassId And BatchId=@rBatchId)
		
		--Update sAssessment.tCCEResultDetail  Set GRADEPOINT = ROUND((GradePointFA1+GradePointFA2+GradePointFA3)/3,0) WHERE Term2GradePoint = 0 AND AcademicId IN (Select Id From sStudent.tAcademic Where ClassId=@rClassId And BatchId=@rBatchId)
		--Update sAssessment.tCCEResultDetail  Set GRADEPOINT = ROUND((GradePointFA1+GradePointFA2+GradePointFA3 +GradePointFA4+GradePointSA1+GradePointSA2)/6,0) WHERE AcademicId IN (Select Id From sStudent.tAcademic Where ClassId=@rClassId And BatchId=@rBatchId)
		--AND Term2GradePoint <> 0 AND Term1GradePoint <> 0
	if(@rCCEExamId=9)
	BEGIN
		update CR set cgpa =  (CRD.GradePoint) from  sAssessment.tCCEResult CR 
		Inner Join (select Avg(GradePoint) AS GradePoint,AcademicId From sAssessment.tCCEResultDetail Group By ACademicId ) CRD 
		ON CR.AcademicId = CRD.AcademicId
		INNER JOIN sStudent.tAcademic A ON CR.AcademicId = A.Id
		AND A.ClassId=@rClassId And A.BatchId=@rBatchId AND A.DivisionId=@rDivisionId
		 --AND CR.AcademicId IN (Select Id From sStudent.tAcademic Where ClassId=@rClassId And BatchId=@rBatchId AND DivisionId=@rDivisionId)
	END
	if (@rCCEExamId=7)
	begin
	update CR set Term1CGPA =  (CRD.GradePoint) from  sAssessment.tCCEResult CR 
		Inner Join (select Avg(Term1GradePoint) AS GradePoint,AcademicId From sAssessment.tCCEResultDetail Group By ACademicId ) CRD 
		ON CR.AcademicId = CRD.AcademicId 
		INNER JOIN sStudent.tAcademic A ON CR.AcademicId = A.Id
		AND A.ClassId=@rClassId And A.BatchId=@rBatchId AND A.DivisionId=@rDivisionId
		--AND CR.AcademicId IN (Select Id From sStudent.tAcademic Where ClassId=@rClassId And BatchId=@rBatchId AND DivisionId=@rDivisionId)
	END
	if(@rCCEExamId=8)
	BEGIN
	update CR set Term2CGPA =  (CRD.GradePoint) from  sAssessment.tCCEResult CR 
		Inner Join (select Avg(Term2GradePoint) AS GradePoint,AcademicId From sAssessment.tCCEResultDetail Group By ACademicId ) CRD 
		ON CR.AcademicId = CRD.AcademicId 
		INNER JOIN sStudent.tAcademic A ON CR.AcademicId = A.Id
		AND A.ClassId=@rClassId And A.BatchId=@rBatchId AND A.DivisionId=@rDivisionId
		--AND CR.AcademicId IN (Select Id From sStudent.tAcademic Where ClassId=@rClassId And BatchId=@rBatchId AND DivisionId=@rDivisionId)
	
	END
		--SELECT 1 AS Result
	--COMMIT TRANSACTION		
	--END TRY
	
	--BEGIN CATCH 
	--	ROLLBACK TRANSACTION
	--	SELECT -1 AS Result
	--END CATCH	
END
GO
PRINT N'Altering [sAssessment].[pCCEResultGenerate]...';


GO

ALTER PROCEDURE [sAssessment].[pCCEResultGenerate]
	
	@rClassId int,
	@rExamId int,
	@rBatchId int,
	@rOrgId int,
	@rExamOrder int,
	@rCCEExamId int,
	@rDivisionId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	DECLARE @lCount_MarkEntryStudent int
	DECLARE @lAcademicId bigint
	Declare @lCCESettingMaxMark decimal(6,2)
	
	SELECT @lCCESettingMaxMark=MaxMark  FROM sAssessment.tCCEExamSetting WHERE CCEExamId = @rExamOrder AND ClassId = @rClassId
	 
	CREATE TABLE #TempMarkEntryStudent(
	[AutoId] [int] identity,
	[AcademicId] [bigint] NOT NULL,
	[ExamId] [int] NULL,
	[OrgId] [int] NULL,
	[ClassId] [int] NULL,
	)
	 
	INSERT INTO #TempMarkEntryStudent 
	SELECT  
		SA.AcademicId,
		EM.Id AS ExamId,
		SA.OrgId,
		EM.ClassId
    FROM  
		sStudent.vStudentAcademic SA 
		INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = SA.ClassId 
		INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=SA.AcademicId
		--LEFT JOIN sAssessment.tCCEResult CR ON CR.AcademicId = SA.AcademicId
	WHERE 
		(EM.ClassId = @rClassId OR @rClassId = 0 )    
		AND (EM.Id=@rExamId OR @rExamId = 0)
		AND (EM.BatchId = @rBatchId or @rBatchId=0)
		AND SA.StatusId=1
		AND SA.BatchId=@rBatchId
		AND SA.DivisionId=@rDivisionId
    
    SET @lCount_MarkEntryStudent = 0
    SELECT @lCount_MarkEntryStudent = COUNT(AutoId) FROM #TempMarkEntryStudent
     
    --SELECT * FROM #TempMarkEntryStudent
    
	CREATE TABLE #TempCCEMarkEntry (
	[AutoId] [int] identity,
	[AcademicId] [bigint] NOT NULL ,
	[ResultDetailId] [bigint] NULL,
	[ClassSubjectId] [int] NULL,
	[Obtain] [decimal](5,2) NULL,
	[IsPresent] [bit] NULL,
	[ExamId] [int] NULL
	)
	
	WHILE (@lCount_MarkEntryStudent > 0)
	BEGIN
		
		SET @lAcademicId = 0
		SELECT @lAcademicId = AcademicId FROM #TempMarkEntryStudent WHERE AutoId = @lCount_MarkEntryStudent
	    EXEC sAssessment.pCCEResultAdd @rAcademicId=@lAcademicId,@rUpdatedUserId=0,@rOrgId=@rOrgId
			
		INSERT INTO #TempCCEMarkEntry 
		SELECT 
			SA.AcademicId,
			ISNULL(RD.ID,0) AS ResultDetailId,
			ED.ClassSubjectId AS ClassSubjectId,
			ISNULL(RD.Obtain,0) AS Obtain,
			RD.IsPresent,
			@rExamId
		FROM sAssessment.tResultDetail RD 
			INNER JOIN sAssessment.tResult R ON R.Id= RD.ResultId
			INNER JOIN 	sStudent.vStudentAcademic SA ON SA.AcademicId = R.AcademicId
			INNER JOIN sAssessment.tExamMaster EM ON  EM.Id=R.ExamId 	
			INNER JOIN sAssessment.tExamDetail ED ON  RD.ExamDetailId = ED.Id		
		WHERE
			(SA.ClassId = @rClassId)    
			AND SA.StatusId=1
			AND SA.BatchId=@rBatchId
			AND R.ExamId = @rExamId
			AND R.AcademicId = @lAcademicId
			AND SA.DivisionId =@rDivisionId
			--SELECT * FROM #TempCCEMarkEntry 
			
			DECLARE @lCount int
			SET @lCount = 0
			SELECT @lCount = COUNT(AcademicId) FROM #TempCCEMarkEntry
				WHILE (@lCount > 0)
				BEGIN
					DECLARE @lClassSubjectId int
				    DECLARE @lObtain decimal(5,2)
				    DECLARE @lIsPresent bit
				    DECLARE @rIsPresent bit
					SELECT @lClassSubjectId = ClassSubjectId, @lObtain = Obtain,@lIsPresent = IsPresent  FROM #TempCCEMarkEntry WHERE AcademicId = @lAcademicId AND ExamId = @rExamId AND AutoId = @lCount
					EXEC sAssessment.pCCEResultDetailAdd @rAcademicId=@lAcademicId,@rClassSubjectId=@lClassSubjectId,@rObtain=@lObtain,@rExamOrder=@rExamOrder,@rCCEExamId=@rCCEExamId,@rSubExamId=@rExamId,@rOrgId=@rOrgId,@rIsPresent=@lIsPresent,@rCCEGradePointMarks=@lCCESettingMaxMark,@rClassId=@rClassId
					SET @lCount = @lCount -1
				END
				TRUNCATE TABLE #TempCCEMarkEntry
				--DELETE FROM #TempCCEMarkEntry
				--DBCC CHECKIDENT (#TempCCEMarkEntry, RESEED, 1);
		SET @lCount_MarkEntryStudent = @lCount_MarkEntryStudent -1
	    EXEC sAssessment.pCCEResultDetailSubjectGradeUpdate @rExamOrder,@rCCEExamId,@rExamId,@rBatchId,@rClassId,@rDivisionId
	END
	DROP TABLE #TempMarkEntryStudent
	DROP TABLE #TempCCEMarkEntry
		SELECT 1 AS Result
END
GO
PRINT N'Altering [sAssessment].[pCCERptFirstTermResultGet]...';


GO


ALTER PROCEDURE [sAssessment].[pCCERptFirstTermResultGet] 
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	-- @rOrgId int,
	 @rBatchId int=0,
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rClassSubjectId int=0,
	 @rCCEExamId int=0,
	@rAcademicId bigint=0,
	 @rStatus int =0 ,
	@rCode nvarchar(20)='',
	@rFromRollNo int=0,	
	@rToRollNo int=0 

	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 


--DECLARE @GradeString nvarchar(1000),
--@GradeSetId int 
--SELECT @GradeSetId = GradesetId FROM sAssessment.tExamMaster WHERE Id = @rCCEExamId
--SELECT @GradeString = [sAssessment].[fGradeStringGet](@GradeSetId)

--DECLARE @rExamId int,@rCSGradeSetId int
--	SELECT @rExamId = EM.Id FROM	sAssessment.tCCEExamSetting CS INNER JOIN sAssessment.tExamMaster EM
--	ON CS.ExamSubGroupId = 	EM.ExamSubGroupId AND CS.ClassId = EM.ClassId AND CS.BatchId = EM.BatchId
--	  WHERE Cs.CCEExamId = @rCCEExamId AND CS.BatchId = @rBatchId AND Cs.ClassId = @rClassId
		
--		SELECT Distinct @rCSGradeSetId = CG.GradeSetId  from  sAssessment.tCCECSExamScore ES INNER JOIN sAssessment.tCCECSMaster CM ON ES.cceCsId = CM.Id
--		INNER JOIN sAssessment.tCCECSGroupMaster CG ON CM.CCECAGroupId = CG.Id WHERE ES.ExamId = @rExamId
Declare @GradeString nvarchar(500),@GradeSetId int  
SELECT @GradeSetId = GradesetId  FROM sAssessment.tCCEExamSetting WHERE CCEExamId = @rCCEExamId
SELECT @GradeString = [sAssessment].[fGradeStringGet](@GradeSetId)


BEGIN 
	SELECT 
		
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2
			,
			
			SM.Code,
			   [sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Name,
			ISNULL(SF.FatherName,'') AS FatherName,
			ISNULL(SF.MotherName,'')AS MotherName,
			A.RollNo,
			CCER.AcademicId,
			CONVERT(NVARCHAR,CCER.AcademicId) AS AcademicIdText,
			CONVERT(NVARCHAR,EM.Id)AS ExamIdText,
			CONVERT(NVARCHAR,@rCCEExamId) AS CCEExamIdText,
			
			Convert(nvarchar(20),EM.CoScholasticScopeId)AS CoScholasticScopeIdText,--added 
			 CONVERT (nvarchar(20),EM.GradeSetId) AS GradeSetIdText,
			 REPLICATE(',',EM.FooterAdjustment) AS FooterAdjustmentText,
		REPLICATE(',',EM.DetailAdjustment) AS DetailAdjustmentText,
		ED.IsIncludeInTotal,
	
	 
		
			ISNULL(SC.ParentContactNo,'') AS ContactNo,
			ISNULL(SC.PresentStreetONe,'')+' '+ISNULL(SC.PresentStreetTwo,'')+' '+ISNULL(SC.PresentStreetThree,'')+' '+ISNULL(SC.PresentCity,'')+' '+ISNULL(SC.PresentState,'') AS PresentAddress,
			--SO.DateOfBirth,
			CONVERT(VARCHAR(10),SO.DateOfBirth,103) AS DateOfBirth,
			CM.DisplayTitle AS Class,
			DM.DisplayTitle AS Division,
			ISNULL(HM.Title,'') AS House,
			ISNULL(CCERD.GradeFA1,'') AS GradeFA1,
			ISNULL(CCERD.GradeFA2,'') AS GradeFA2,
			ISNULL(CCERD.GradeFA3,'')AS GradeFA3,
			ISNULL(CCERD.GradeFA4,'') AS GradeFA4,
			ISNULL(CCERD.GradeSA1,'') AS GradeSA1,
			ISNULL(CCERD.GradeSA2,'') AS GradeSA2,
			ISNULL(CCERD.FAGrade,'') AS FAGrade,
			ISNULL(CCERD.SAGrade,'') AS SAGrade,
			ISNULL(CCERD.GradePoint,0) AS OverallGrade,
			ISNULL(CCERD.Grade,'') AS Grade,
			ISNULL(CCER.AttendanceTerm1,0) AS AttendanceTerm1,
			ISNULL(CCER.AttendanceTerm2,0) AS AttendanceTerm2,
			ISNULL(CCER.WorkingDaysTerm1,0) AS WorkingDaysTerm1,
			ISNULL(CCER.WorkingDaysTerm2,0) AS WorkingDaysTerm2,
			ISNULL(CCER.Height,0) AS Height,
			ISNULL(CCER.Weight,0) AS Weight,
			 
			SubM.Title As ClassSubject,
			SubM.OrderIndex AS SubjectOrderIndex,
			Subm.Code AS SubjectCode,
			ISNULL(BGM.Title,'') AS BloodGroup,
			ISNULL(CCERD.Term1GradePoint,0) AS Term1GradePoint,
			ISNULL(CCERD.Term1Grade,'') AS Term1Grade,
			ISNULL(CCERD.Term2GradePoint,0) AS Term2GradePoint,
			ISNULL(CCERD.Term2Grade,'') AS Term2Grade,
			--ISNULL(SI.StudentPhoto,CONVERT(varbinary(max),SI.StudentPhoto,1)) AS StudentPhoto
			--SI.StudentPhoto AS StudentPhoto 
		--CASE WHEN ISNULL(IsResultStatus,0) = 0 THEN 'No' ELSE 'Yes' END AS IsDisplayResultStatus,
			CCERD.FA1,
			CCERD.FA2,
			CCERD.FA3,
			CCERD.FA4,
			CCERD.SA1,
			CCERD.SA2,
			CCERD.TERM1,
			CCERD.TERM2,
			CCERD.TOTAL,
			EM.IsOnPrePrinted,
			EM.IsDisplayBirthDate,
			EM.IsDisplayPhoto,
			EM.IsDisplaySchoolName,			
			EM.IsLockForEdit,
			EM.IsIncludeCoScholastic,
			EM.IsDisplayAttendance,
			EM.IsDisplayHeightWeight,
			EM.IsResultStatus,	
			EM.Remark1,
			EM.Remark2,
			EM.Remark3,
			EM.ExamSubGroupId,
 
			ESM.Code AS ExamSubGroupTitle,	
			EM.DisplayTitle,
			SI.StudentPhoto,
			ISNULL(EM.ExamMaximum,0) AS ExamMaximum,
			ISNULL(EM.FooterAdjustment,0) AS FooterAdjustment,
			ISNULL(EM.DetailAdjustment,0) AS DetailAdjustment,
			ISNULL(EM.TermScopeId,0) AS TermScopeId,	
			TSM.Title AS TermScopeTitle,
		ISNULL(EM.ReportId,0) as ReportId,
		@GradeString AS GradeString,
			A.BatchId,
			BM.Title,
			CS.OrderIndex AS ClassSubjectOrderIndex,
			SR.TotalDays,
		SR.PresentDays,
		SR.StudentHeight,
		SR.StudentWeight,
		EM.IsDisplayGradeString,
		CCERD.IspresentFA1,
		CCERD.IsPresentFA2,
		CCERD.IspresentSA1,
		CCERD.IspresentFA3,
		CCERD.IsPresentFA4,
		CCERD.IspresentSA2,
		SR.ResultRemark1,
		SR.ResultRemark2,
		CCERD.GradePoint,
		CCERD. FATerm1,
		CCERD.FATerm2,
		CS.IsOptional,
		EM.IsDisplayPrincipalSign,
		Em.IsDisplayTeacherSign,
		EI.EmployeeSign,
		AD.TotalDaysTerm1,
		AD.PresentDaysTerm1,
		AD.TotalDaysTerm2,
		AD.PresentDaysTerm2,
		 
		CCER.CGPA,
		ISNULL(SR.AreaOfInterest,'')As AreaOfInterest,
		ISNULL(SR.Responsibility,'') AS Responsibility,
		ISNULL(SR.MyGoal,'')AS MyGoal,
		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,
		 ISNULL(CCER.Term1Grade,'') Term1OverAllGrade,
		 ISNULL( CCER.Term2Grade,'') Term2OverAllGrade,
		 ISNULL(CCER.AnnualGrade,'') AnnualOverAllGrade,
		  CONVERT (nvarchar(20),EM.CoScholasticGradeSetId) AS CoScholasticGradeSetIdText,
		EM.IsMarksInDecimal,
		
		CCERD.FA,
		CCERD.SA,
		
		ISNULL(CCER.Term1TotalMarks,0) AS Term1TotalMarks,
		ISNULL(CCER.Term1TotalObtain,0) AS Term1TotalObtain,
		ISNULL(CCER.Term2TotalMarks,0) AS Term2TotalMarks,
		ISNULL(CCER.Term2TotalObtain,0) AS Term2TotalObtain,
		ISNULL(CCER.AnnualTotalMarks,0) AS AnnualTotalMarks,
		ISNULL(CCER.AnnualTotalObtain,0) AS AnnualTotalObtain,
		Em.IsDisplayParentName,
		(CASE EM.IsDisplayImageHeader WHEN 1 THEN
			OI.CertificateHeaderA4 
			ELSE NULL END)AS  MarksheetHeaderA4,
			ISNULL(EM.IsDisplayImageHeader,0) AS IsImageHeader,
		EM.DecimalFormat,
		CCER.Term1CGPA,
		CCER.Term2CGPA,
		CCERD.GradePointFA1,
		CCERD.GradePointFA2,
		CCERD.GradePointSA1,
		CCERD.GradePointFA3,
		CCERD.GradePointFA4,
		CCERD.GradePointSA2,
		CCERD.FAGradePoint,
		CCERD.SAGradePoint,
		SubM.Code As SubjectCode
		 
		
			
	--		--CASE WHEN ED.ClassSubjectId=CS.Id THEN 'Yes' ELSE 'false' END AS Selected
      
	FROM 
	
			sAssessment.tCCEResultDetail CCERD
			
			INNER JOIN sAssessment.tCCEResult CCER  ON CCERD.AcademicId=CCER.AcademicId
			INNER JOIN sStudent.tAcademic A ON CCER.AcademicId=A.Id
			LEFT JOIN sStudent.tAcademicDetail AD ON AD.AcademicId = A.Id
		
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId
			left Join sStudent.tStudentFamily SF ON SF.StudentId =SM.Id
			LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=A.StudentId
			
			LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=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 sActivity.tHouseMaster HM ON HM.Id=SO.HouseId
			LEFT JOIN sSetup.tClassSubject CS ON CS.Id=CCERD.ClassSubjectId
			INNER JOIN sSetup.tSubjectMaster SubM ON SubM.Id=CS.SubjectId
			LEFT JOIN sCommon.tBloodGroupMaster BGM ON BGM.Id=SO.BloodGroupId
			LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=SM.Id
			INNER JOIN sAssessment.tCCEExamSetting CE ON CE.ClassId = CM.Id AND CE.CCEExamId = @rCCEExamId AND CE.BatchId = @rBatchId 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ExamSubGroupId = CE.ExamSubGroupId AND EM.ClassId = CE.ClassId AND EM.BatchId = @rBatchId 
			Inner Join sAssessment.tExamSubGroupMaster ESM ON ESM.Id=EM.ExamSubGroupId
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id
		
			 
			LEFT JOIN sAssessment.tStudentRemark SR ON CCERD.AcademicId = SR.AcademicId AND ED.ExamId = SR.ExamId 
			
			
			
			LEFT JOIN sSetup.tTermScopeMaster TSM ON TSM.Id = EM.TermScopeId

			Inner Join sSetup.tBatchMaster BM ON BM.Id=A.BatchId
			INNER JOIN sSetup.tOrganizationMaster OM ON SM.OrgId = OM.Id
			LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = OM.Id
			
			  
	WHERE 
			
    A.BatchId = @rBatchId 
		
	AND (A.DivisionId=@rDivisionId OR @rDivisionId=0)
	AND (A.ClassId=@rClassId OR @rClassId=0) 
	AND (CCERD.ClassSubjectId=@rClassSubjectId OR @rClassSubjectId=0)
	AND(CE.CCEExamId = @rCCEExamId OR @rCCEExamId=0)
	AND ( CCER.AcademicId=@rAcademicId OR @rAcademicId=0)
	AND (SM.StatusId=@rStatus OR @rStatus=0) 
	AND ((SM.Code=@rCode) OR (@rCode=''))
	AND((A.RollNo >= @rFromRollNo) OR (@rFromRollNo = 0))
	AND((A.RollNo <= @rToRollNo) OR (@rToRollNo = 0))
	ORDER BY A.RollNo,CS.OrderIndex	
END
GO
PRINT N'Altering [sAssessment].[pConvertMarkentryDifferentSubjectGet]...';


GO
ALTER PROCEDURE [sAssessment].[pConvertMarkentryDifferentSubjectGet]

	 
	 @rClassId int,
	 @rBatchId int, 
	 @rDestinatinExamDetailId int

	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 	
 
					 
	SELECT 
		 ESGM.Title AS Exam,		 
		 ED.Id AS ExamDetailId,
		 SM.Title AS SubjectName
	FROM  
			  sAssessment.tExamMaster EM  
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId
			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
			
  WHERE		(EM.ClassId=@rClassId OR @rClassId =0) 			
			AND EM.BatchId=@rBatchId						 
			--AND ED.ClassSubjectId=@lClassSubjectId
			 AND ED.ID <> @rDestinatinExamDetailId
			
 ORDER BY  ESGM.Title ASC
		
END
GO
PRINT N'Altering [sAssessment].[pConvertMarkentrySubjectGet]...';


GO
ALTER PROCEDURE [sAssessment].[pConvertMarkentrySubjectGet]

	 
	 @rClassId int,
	 @rBatchId int, 
	 @rDestinatinExamDetailId int

	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 	

DECLARE @lClassSubjectId int
select @lClassSubjectId =  ClassSubjectId from sAssessment.tExamDetail	 where Id = @rDestinatinExamDetailId
					 
	SELECT 
		 ESGM.Title AS Exam,		 
		 ED.Id AS ExamDetailId ,	
		 '' As SubjectName
	FROM  
			  sAssessment.tExamMaster EM  
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId = EM.Id
		 
  WHERE		(EM.ClassId=@rClassId OR @rClassId =0) 			
			AND EM.BatchId=@rBatchId						 
			AND ED.ClassSubjectId=@lClassSubjectId
			AND ED.ID <> @rDestinatinExamDetailId
			
 ORDER BY  ESGM.Title ASC
		
END
GO
PRINT N'Altering [sAssessment].[pCSExamGradeGet]...';


GO
ALTER PROCEDURE [sAssessment].[pCSExamGradeGet]
	  @rClassId bigint,
	  @rDivisionID Bigint,
	  @rExamId int,
	  @rOrgId int,
	  @rCCECSGroupId int,
	  @rBatchId int,
	  @rCCECSId int=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 	

	DECLARE @cols AS NVARCHAR(MAX),
@query  AS NVARCHAR(MAX),@query1  AS NVARCHAR(MAX),@query2  AS NVARCHAR(MAX),@query3 AS NVARCHAR(MAX)
select @cols = STUFF((SELECT  ',' + QUOTENAME(CM.Title) FROM sAssessment.tCCECSGroupMaster CGM
					INNER JOIN sAssessment.tCCECSMaster CM ON CM.CCECAGroupId=CGM.Id AND ((CM.Id=@rCCECSId) OR (@rCCECSId=0))
					INNER JOIN sAssessment.tCCECSClass CC ON CC.CCECSGroupId=CGM.Id 
					AND CC.ClassId = @rClassId AND CGM.OrgId = @rOrgId 
					AND CGM.Id=@rCCECSGroupId 
					
					Order by CM.OrderIndex
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')
       
	SET @query = 'Select AcademicId,RollNo,Number,Name,  ' + @cols + '
	FROM
	(
		SELECT SA.AcademicId,SA.RollNo,SA.Number,SA.Name,  AM.Title, ISNULL(AIS.Grade,'''') AS Term1Indicator
	FROM sStudent.vStudentAcademic SA
	INNER JOIN sAssessment.tCCECSClass CA ON CA.ClassId = SA.ClassId AND SA.StatusId = 1 AND CA.CCECSGroupId='+CONVERT(nvarchar,@rCCECSGroupId) +'
	
	INNER JOIN sAssessment.tCCECSMaster AM ON CA.CCECSGroupId=AM.CCECAGroupId
	LEFT JOIN sAssessment.tCCECSExamScore AIS ON AIS.AcademicId =SA.AcademicId AND AIS.CCECSId= AM.Id AND AIS.ExamId= ' + Convert(nvarchar,@rExamId) +'
	WHERE SA.ClassId=' + CONVERT(nvarchar,@rClassId) + ' 
	And SA.DivisionId = ' + CONVERT(nvarchar,@rDivisionID) + '	
	And SA.BatchId = ' + CONVERT(nvarchar,@rBatchId) + ' 
	And AM.CCECAGroupId= ' + CONVERT(nvarchar,@rCCECSGroupId) + '
	AND ((AIS.CCECSID = '+ CONVERT(nvarchar,@rCCECSId) +') OR ('+CONVERT(nvarchar,@rCCECSId)+'=0))
	) MAIN
	PIVOT
	(
		max(Term1Indicator)
	FOR Title IN (' + @cols + ')
	)pvt Order by RollNo,Number,Academicid'

 --print @query
EXECUTE(@query)

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


GO


ALTER PROCEDURE [sAssessment].[pCSExamScoreConvertTo]
	 	
	@rStrXml [nvarchar](max),
	@rOrgId int,
	@rExamId int=0,
	@rCSGroupId int=0
 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

SET @rStrXml=REPLACE(@rStrXml,'&','AND')
DECLARE @loDoc INT,@lIsMarkIndecimal bit,@lDecimalPlace nvarchar(10),@lGradeSetId int

EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml
Select @lIsMarkIndecimal = IsMarksInDecimal from sAssessment.tExamMaster where id= @rExamId
Select @lDecimalPlace = DecimalFormat from sAssessment.tExamMaster where id= @rExamId
 
Select  @lGradeSetId=GradeSetId FROM sAssessment.tCCECSMaster CSM 
 INNER JOIN OPENXML (@loDoc, '/Table/CSExamGrade', 1)
			WITH ( 				
						 
						CCECSId int 
					  
									
				  ) A 	ON CSM. Id = A.CCECSId  
 INNER JOIN sAssessment.tCCECSGroupMaster CGM ON CGM.ID = CSM.CCECAGroupId
  
WHERE CGM.Id =  @rCSGroupId AND CSM.Id = A. CCECSId AND CGM.OrgId =@rOrgId
			 
			 
Select @lIsMarkIndecimal, @lDecimalPlace
BEGIN
	BEGIN TRY
	 BEGIN	
		UPDATE AI 
		SET  
				AI.ConvertedMark =ROund( ( A.TotalMarks * CC.ConvertToMark)/CC.TotalMark,0)
				--(CASE WHEN @lIsMarkIndecimal=1 AND @lDecimalPlace ='0.0'
									--THEN  ROund(( A.TotalMarks* CC.ConvertToMark)/CC.TotalMark,1)
									--  WHEN @lIsMarkIndecimal=1 AND @lDecimalPlace ='0.00'
									--THEN ROund( ( A.TotalMarks  * CC.ConvertToMark)/CC.TotalMark,2)
									--ELSE 
									--	ROund( ( A.TotalMarks * CC.ConvertToMark)/CC.TotalMark,0)
									--END 
								 -- )
		 FROM sAssessment.tCCECSExamScore AI
		 
		 INNER JOIN OPENXML (@loDoc, '/Table/CSExamGrade', 1)
			WITH ( 				
						AcademicId bigint,	
						CCECSId int,
						ExamId int,
						TotalMarks decimal(12,2),
						 ClassId int
						--GradeTitle nvarchar(50)
									
				  ) A 	ON AI.AcademicId = A.AcademicId AND AI.ExamId=A.ExamId
				  
		AND A.CCECSId = AI.CCECSId 
		INNER JOIN sAssessment.tCCECSForClass CC ON CC.CCECSId = AI.CCECSId AND CC.ClassId = A.ClassId	
		WHERE A.TotalMarks = AI.ObtianMark 
		 
		 Update AI 
			Set Grade = GS.GradeCode
			from  sAssessment.tCCECSExamScore AI 
			INNER JOIN OPENXML (@loDoc, '/Table/CSExamGrade', 1)
			WITH ( 				
						AcademicId bigint,	
						CCECSId int,
						ExamId int,
						TotalMarks decimal(12,2) 
						 
				)A ON AI.AcademicId = A.AcademicId AND AI.ExamId=A.ExamId AND A.CCECSId = AI.CCECSId 
				INNER JOIN sAssessment.tCCECSMaster CSM ON CSM.Id = A.CCECSId
				INNER JOIN sAssessment.tCCECSGroupMaster CGM ON CGM.ID = CSM.CCECAGroupId
				INNER JOIN sAssessment.tGradeSetDetail GS ON GS.GradeSetId = CGM.GradeSetId
		 
		WHERE  CGM.GradeSetId = @lGradeSetId AND AI.ConvertedMark >=GS.MinimumScore 
				 
 	 SELECT  @lGradeSetId AS Result
	END		
	END TRY
	
	BEGIN CATCH 
	
		
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sAssessment].[pExamCombineMarkEntryExcludeAbsentGet]...';


GO
ALTER PROCEDURE [sAssessment].[pExamCombineMarkEntryExcludeAbsentGet]
	
	 @rExamId int,
	 @rAcademicId bigint
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 		

IF EXISTS (SELECT ID from sAssessment.tExamCombine where ExamId = @rExamId)
BEGIN
select  
(case WHEN A.Maxi = 0 then 0
else
ISNULL((A.Obtain*ED.Maximum)/A.Maxi,0) END) AS Obtain,


@rAcademicId AS AcademicId,
ED.Id AS ExamDetailID,
ED.ExamId,
CONVERT(bit, 1) AS  IsPresent
--ISNULL((select IsPresent from sAssessment.tResultDetail rd1 
--		   inner join sAssessment.tResult r1 on r1.Id=rd1.ResultId and r1.ExamId=@rExamId and r1.AcademicId=@rAcademicId
--		   and rd1.ExamDetailId=ED.Id ),0)  AS IsPresent

from
(SELECT
	CASE WHEN   ECS.ExamId IS nULL THEN
		Sum(Obtain*weightage/100)  
	ELSE
		Sum(Obtain*Subjectweightage/100)
	END AS Obtain,
	CASE WHEN ECS.ExamId IS nULL THEN
		Sum(Maximum*weightage/100)  
	ELSE
		Sum(Maximum*Subjectweightage/100)
		END AS Maxi,
		RM.AcademicId,
		ED.ClassSubjectId
FROM sAssessment.tResult RM 
	INNER JOIN sAssessment.tResultDetail RD ON RD.ResultId=RM.Id
	INNER JOIN sAssessment.tExamDetail ED ON RD.ExamDetailId=ED.Id
	INNER JOIN sAssessment.tExamCombine EC ON ED.ExamId=EC.SubExamId
	INNER JOIN sSetup.vClassSubject V ON V.ClassSubjectId = Ed.ClassSubjectId  	
	LEFT JOIN sAssessment.tExamCombineSubject ECS ON ECS.ExamId  = EC.ExamId AND ECS.SubExamId = EC.SubExamId AND ECS.ClassSubjectId = ED.ClassSubjectId 	
	
	WHERE EC.ExamId=@rExamId 
	AND RD.IsPresent = 1
	
GROUP BY RM.AcademicId,ED.ClassSubjectId,ECS.ExamId  having RM.AcademicId=@rAcademicId) AS A
INNER JOIN sAssessment.tExamDetail ED ON ED.ClassSubjectId=A.ClassSubjectId
Where ED.ExamId =@rExamId
END
		
END
GO
PRINT N'Altering [sAssessment].[pExamCombineMarkEntryGet]...';


GO
ALTER PROCEDURE [sAssessment].[pExamCombineMarkEntryGet]
	
	 @rExamId int,
	 @rAcademicId bigint
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 		

IF EXISTS (SELECT ID from sAssessment.tExamCombine where ExamId = @rExamId)
BEGIN
select  
(case WHEN A.Maxi = 0 then 0
else
ISNULL((A.Obtain*ED.Maximum)/A.Maxi,0) END) AS Obtain,


@rAcademicId AS AcademicId,
ED.Id AS ExamDetailID,
ED.ExamId,
CONVERT(bit, 1) AS  IsPresent
--ISNULL((select IsPresent from sAssessment.tResultDetail rd1 
--		   inner join sAssessment.tResult r1 on r1.Id=rd1.ResultId and r1.ExamId=@rExamId and r1.AcademicId=@rAcademicId
--		   and rd1.ExamDetailId=ED.Id ),0)  AS IsPresent

from
(SELECT 
	CASE WHEN ECS.ExamId IS nULL THEN
		Sum(Obtain*weightage/100) 
	ELSE
		Sum(Obtain*Subjectweightage/100) 
	END  AS Obtain,
	CASE WHEN ECS.ExamId IS nULL THEN
		Sum(Maximum*weightage/100) 
	ELSE
		Sum(Maximum*Subjectweightage/100) 
	END	AS Maxi,
	
RM.AcademicId,ED.ClassSubjectId
FROM sAssessment.tResult RM 
	INNER JOIN sAssessment.tResultDetail RD ON RD.ResultId=RM.Id
	INNER JOIN sAssessment.tExamDetail ED ON RD.ExamDetailId=ED.Id
	INNER JOIN sAssessment.tExamCombine EC ON ED.ExamId=EC.SubExamId
	INNER JOIN sSetup.vClassSubject V ON V.ClassSubjectId = Ed.ClassSubjectId  	
    LEFT JOIN sAssessment.tExamCombineSubject ECS ON ECS.ExamId  = EC.ExamId AND ECS.SubExamId = EC.SubExamId AND ECS.ClassSubjectId = ED.ClassSubjectId 	
	WHERE EC.ExamId=@rExamId 
	
GROUP BY RM.AcademicId,ED.ClassSubjectId,ECS.ExamId having RM.AcademicId=@rAcademicId) AS A
INNER JOIN sAssessment.tExamDetail ED ON ED.ClassSubjectId=A.ClassSubjectId
Where ED.ExamId =@rExamId
END
		
END
GO
PRINT N'Altering [sAssessment].[pMarkEntryConvertForDifferentSubject]...';


GO


ALTER PROCEDURE [sAssessment].[pMarkEntryConvertForDifferentSubject]  
	 	
	 
	@rClassId int, 
	@rDivisionId int,
	@rSourceExamDetailIdList nvarchar(500),
	@rOrgId smallint,
	@rBatchId int,
	@rDestinationExamDetailId  int=0 	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

DECLARE @loDoc INT,@lIsMarksInDecimal bit
Declare @lDecimalFormat nvarchar(10)
select @lDecimalFormat = DecimalFormat from sAssessment.tExamMaster where Id =(Select ExamId  from sAssessment.tExamDetail WHere Id = @rDestinationExamDetailId)
select @lIsMarksInDecimal = IsMarksInDecimal from sAssessment.tExamMaster where Id= (Select ExamId  from sAssessment.tExamDetail WHere Id = @rDestinationExamDetailId)
BEGIN
	 
	 BEGIN	
	 
	 
	--select @lDecimalFormat = DecimalFormat from sAssessment.tExamMaster where Id =@rExamId;
	 
	 CREATE Table #MarkEntrySubjectWise_CTE ( AcademicId  bigint,  SourceObtain decimal(5,2),SourceMaximum decimal(5,2))
 
-- Define the CTE query.
	INSERT INTO #MarkEntrySubjectWise_CTE 
	(
		AcademicId,
	 
		SourceObtain,
		SourceMaximum
	)
	
   Select 			
		
		R.AcademicId,	
		 	 
		SUM(RD.Obtain)AS SourceObtain,
		SUM(ED.Maximum) AS SourceMaximum		
	 
	From 
			sAssessment.tResultDetail RD 
			INNER JOIN sAssessment.tResult R ON R.Id=RD.ResultId  	
			INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId 
			INNER JOIN sAssessment.tExamMaster EM ON EM.Id = R.ExamId
			INNER JOIN sAssessment.tExamDetail ED ON RD.ExamDetailId=ED.Id AND ED.ExamId = EM.Id			 			 			  			 			 
			 Where
			 A.ClassId = @rClassId AND A.BatchId=@rbatchId 
			 AND ED.Id IN (SELECT  cast(item as int) AS ExamDetailID FROM  sCommon.fnsplit( REPLACE(REPLACE(@rSourceExamDetailIdList,'(',''),')','') ,','))  
			Group By R.AcademicId 
		 
		--Select * from #MarkEntrySubjectWise_CTE 
	  UPDATE RD SET RD.OBTAIN  =
								(CASE WHEN  (@lIsMarksInDecimal = 1 AND @lDecimalFormat='0.0') THEN
									Round((MC.SourceObtain * ED.Maximum)/MC.SourceMaximum,1) 
								WHEN ( @lIsMarksInDecimal = 1 AND @lDecimalFormat='0.00' ) THEN
									CONVERT(Decimal(5,2),(MC.SourceObtain * ED.Maximum)/MC.SourceMaximum) 
								ELSE			  
									ROUND((MC.SourceObtain * ED.Maximum)/MC.SourceMaximum,0)
								END)
	  
	   --Convert(Decimal(5,2),(MC.SourceObtain * ED.Maximum)/MC.SourceMaximum)
	  FROM	  
			sAssessment.tResultDetail RD 
			INNER JOIN sAssessment.tResult R ON RD.ResultId = R.Id 
			INNER JOIN sAssessment.tExamDetail  ED ON RD.ExamDetailId = ED.Id
			INNER JOIN #MarkEntrySubjectWise_CTE MC ON R.AcademicId = MC.AcademicId 
			AND RD.ExamDetailId = @rDestinationExamDetailId 
	 
	
   Select 1 AS Result
END

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


GO
ALTER PROCEDURE [sAssessment].[pMarkEntryGet]
	 @rClassId int,
	 @rDivisionId int,
	 @rExamId int,
	 @rExamDetailId int,
	 @rBatchId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 		


SELECT 
	 EM.ClassId
	,DM.Id AS DivisionId
	,EM.Id AS ExamId
	,ED.ClassSubjectId AS ClassSubjectId
	,ISNULL(RD.Id,0) AS ResultDetailId
	,ISNULL(R.Id,0) AS ResultId  
	,SA.AcademicId
	,SA.Name AS StudentName
	,SA.Code 
	,SA.RollNo
	,ISNULL(RD.Obtain,0) AS Obtain
	,ISNULL(RD.IsPresent,'true') as IsPresent
	,ED.Id AS ExamDetailId
	,CONVERT(INT,ISNULL(ED.Maximum,0)) AS MaximumMark
	,ISNULL(EM.IsMarksInDecimal,0) AS IsMarkInDecimal,
		ISNULL(SI.StudentPhoto, CONVERT(VARBINARY(MAX), 0)) AS StudentPhoto
from sStudent.vStudentAcademic SA 
	LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId = SA.StudentId
	INNER JOIN sSetup.tClassMaster CM ON SA.ClassId=CM.Id 
	INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId=CM.Id AND SA.DivisionId=DM.Id
	INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id  
	LEFT JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=SA.AcademicId
	INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
	LEFT JOIN sSetup.vClassSubject V ON V.ClassSubjectId = Ed.ClassSubjectId  
	LEFT JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
	LEFT JOIN sAssessment.tOptionalSubject o on o.AcademicId=SA.AcademicId and o.ClassSubjectId=V.ClassSubjectId

Where  (DM.Id=@rDivisionId OR @rDivisionId = 0)
	   AND (EM.ClassId = @rClassId OR @rClassId = 0)  
	   AND (ED.Id=@rExamDetailId OR @rExamDetailId = 0 )
	   AND (EM.Id=@rExamId OR @rExamId = 0)
	   AND SA.StatusId=1 AND SA.BatchId=@rBatchId
	   AND ((V.IsOptional = 1 AND    isnull(o.AcademicId,0) <> 0) OR (V.IsOptional = 0))	  
Order By SA.RollNo


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


GO

/****** Object:  StoredProcedure [sAssessment].[pMarkEntryMasterUpdate]    Script Date: 02/23/2016 11:58:02 ******/
 

ALTER PROCEDURE [sAssessment].[pMarkEntryMasterUpdate]	 
           @rExamId int,
           @rDivisionId int,
           @rBatchId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	 
	 
	 DECLARE @lIsExcludeAbsentTotal bit
	 
	 SELECT @lIsExcludeAbsentTotal = IsExcludeAbsentTotal FROM sAssessment.tExamMaster EM
	 WHERE EM.Id = @rExamId AND BatchId = @rBatchId
	 
		   UPDATE RD SET	SubjectGrade='',
							SubjectGradePoint=0,
							Percentile=0.00,
							Remark=''
			FROM sAssessment.tResultDetail RD  
			INNER JOIN sAssessment.tResult R ON RD.ResultId = R.Id 
			INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = R.AcademicId AND R.ExamId = @rExamId AND SA.DivisionId=@rDivisionId 
			
			UPDATE R SET	TotalMarks=0,
							TotalObtain=0,
							ResultStatus='',
							ResultGrade='',
							ResultGradePoint = 0,
							RankNumber =0,
							Percentage = 0.00,
							Percentile =0.00,
							resultRemark=''			
			FROM sAssessment.tResult R 
			INNER JOIN sStudent.vStudentAcademic  SA ON SA.AcademicId=R.AcademicId AND ExamId = @rExamId AND DivisionId=@rDivisionId 
	 
	 DECLARE @lIsMarksInDecimal bit,@lDecimalFormat nvarchar(10)
	 select @lDecimalFormat = DecimalFormat from sAssessment.tExamMaster where Id =@rExamId
	select @lIsMarksInDecimal = IsMarksInDecimal from sAssessment.tExamMaster where Id= @rExamId
	
	IF @lIsExcludeAbsentTotal = 0
	BEGIN  
	UPDATE sAssessment.tResult SET TotalMarks= A.Maximum, 
					TotalObtain=A.Obtain,
	Percentage = (A.Obtain/A.Maximum)*100
	FROM 
	(SELECT
		CASE WHEN  (@lIsMarksInDecimal = 1 AND @lDecimalFormat='0.0') THEN
				Round(SUM(Obtain) ,1)
			WHEN ( @lIsMarksInDecimal= 1 AND @lDecimalFormat='0.00' ) THEN
				ROUND(SUM(Obtain),2) 	
			ELSE			  
				ROUND(SUM(Obtain),0) 
			END  AS Obtain,
		  
		  --round(SUM(Obtain),0) AS Obtain,
		  SUM(Maximum) AS Maximum,R.Id 
	FROM sAssessment.tResultDetail RD
	INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId --AND RD.IsPresent =1
	INNER JOIN sAssessment.tExamMaster EM ON EM.Id = R.ExamId
	INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id AND ED.Id=RD.ExamDetailId
	INNER JOIN sStudent.vStudentAcademic SA ON SA.ClassId = EM.ClassId AND R.AcademicId=SA.AcademicId AND EM.BatchId=SA.BatchId
	WHERE (R.ExamId = @rExamId OR @rExamId = 0) AND (SA.DivisionId=@rDivisionId or @rDivisionId=0) AND  ED.IsIncludeInTotal=1
	AND EM.BatchId = @rBatchId AND SA.BatchId = @rBatchId
	GROUP BY R.Id ) AS A 	
	WHERE (ExamId = @rExamId OR @rExamId = 0) AND A.Id=sAssessment.tResult.Id
	END
	ELSE
	BEGIN
	
	UPDATE sAssessment.tResult SET TotalMarks= A.Maximum, 
	TotalObtain=A.Obtain,
	Percentage = (A.Obtain/A.Maximum)*100
	FROM 
	(SELECT  
		CASE WHEN  (@lIsMarksInDecimal = 1 AND @lDecimalFormat='0.0') THEN
				Round(SUM(Obtain) ,1)
			WHEN ( @lIsMarksInDecimal= 1 AND @lDecimalFormat='0.00' ) THEN
				ROUND(SUM(Obtain),2) 
			ELSE			  
				ROUND(SUM(Obtain),0) 
			END  AS Obtain,
		--round(SUM(Obtain),0) AS Obtain,
		SUM(Maximum) AS Maximum,R.Id 
	FROM sAssessment.tResultDetail RD
	INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId AND RD.IsPresent = 1
	INNER JOIN sAssessment.tExamMaster EM ON EM.Id = R.ExamId
	INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id AND ED.Id=RD.ExamDetailId
	INNER JOIN sStudent.vStudentAcademic SA ON SA.ClassId = EM.ClassId AND R.AcademicId=SA.AcademicId AND EM.BatchId=SA.BatchId
	WHERE (R.ExamId = @rExamId OR @rExamId = 0) AND (SA.DivisionId=@rDivisionId or @rDivisionId=0) AND  ED.IsIncludeInTotal=1
	AND EM.BatchId = @rBatchId AND SA.BatchId = @rBatchId
	GROUP BY R.Id ) AS A 	
	WHERE (ExamId = @rExamId OR @rExamId = 0) AND A.Id=sAssessment.tResult.Id
	
	END
	--- Update Result Status	
	

	
	UPDATE R
	SET ResultStatus='' 
	FROM sAssessment.tResult R INNER JOIN sStudent.tAcademic A
	ON R.AcademicId = A.Id
	WHERE R.ExamId = @rExamId 
	AND A.DivisionId = @rDivisionId
	AND A.BatchId = @rBatchId
	
	--UPDATE R
	--SET ResultStatus='FAIL' 
	--FROM sAssessment.tResult R INNER JOIN sStudent.tAcademic A ON R.AcademicId = A.Id
	--INNER JOIN
	--(
	--SELECT DISTINCT R.ID FROM sAssessment.tResultDetail RD 
	--INNER JOIN sAssessment.tExamDetail ED ON RD.ExamDetailId = ED.Id
	--INNER JOIN sAssessment.tResult R ON R.Id =RD.ResultId 
	--INNER JOIN sStudent.tAcademic A ON R.AcademicId=A.Id 
	--AND R.ExamId = @rExamId AND A.DivisionId =@rDivisionId 	
	--AND A.BatchId = @rBatchId
	--INNER JOIN sAssessment.tOptionalSubject OS ON OS.ClassSubjectId = ED.ClassSubjectId AND OS.AcademicId = R.AcademicId
	--WHERE
	---- ClassSubjectId
	----NOT IN (SELECT ClassSubjectId FROM sAssessment.tOptionalSubject WHERE AcademicId=A.Id) 
	----AND 
	--RD.Obtain < Minimum
	-- ) D ON R.Id = D.Id	
	--WHERE R.ExamId = @rExamId	 
	--AND A.DivisionId = @rDivisionId 
	--AND A.BatchId = @rBatchId	

	
	--UPDATE R
	--SET ResultStatus='PASS' 
	--FROM sAssessment.tResult R INNER JOIN sStudent.tAcademic A
	--ON R.AcademicId = A.Id
	--WHERE R.ExamId = @rExamId 
	--AND R.ResultStatus = ''
	--AND A.DivisionId = @rDivisionId 
	--AND A.BatchId = @rBatchId
	
	
	--	UPDATE sAssessment.tResult SET ResultStatus='' 
	--WHERE ExamId = @rExamId
	--AND AcademicId IN (SELECT Id FROM sStudent.tAcademic WHERE
	--DivisionId = @rDivisionId AND BatchId = @rBatchId)
	
	IF @lIsExcludeAbsentTotal = 0
	BEGIN  
	
	UPDATE sAssessment.tResult SET ResultStatus='FAIL' WHERE ID IN (
	SELECT DISTINCT R.ID FROM sAssessment.tResultDetail RD 
	INNER JOIN sAssessment.tExamDetail ED ON RD.ExamDetailId = ED.Id
	INNER JOIN sAssessment.tResult R ON R.Id =RD.ResultId 
	INNER JOIN sStudent.tAcademic A ON R.AcademicId=A.Id 
	AND R.ExamId = @rExamId AND A.DivisionId =@rDivisionId 	
	AND A.BatchId = @rBatchId	
	WHERE 
	--ClassSubjectId
	--NOT IN (SELECT ClassSubjectId FROM sAssessment.tOptionalSubject WHERE AcademicId=A.Id) 
	--AND 
	RD.Obtain < Minimum
	 
	)
	END
	ELSE
	BEGIN
	
	UPDATE sAssessment.tResult SET ResultStatus='FAIL' WHERE ID IN (
	SELECT DISTINCT R.ID FROM sAssessment.tResultDetail RD 
	INNER JOIN sAssessment.tExamDetail ED ON RD.ExamDetailId = ED.Id
	INNER JOIN sAssessment.tResult R ON R.Id =RD.ResultId 
	INNER JOIN sStudent.tAcademic A ON R.AcademicId=A.Id 
	AND R.ExamId = @rExamId AND A.DivisionId =@rDivisionId 	
	AND A.BatchId = @rBatchId
	AND RD.IsPresent = 1
	WHERE
	-- ClassSubjectId
	--NOT IN (SELECT ClassSubjectId FROM sAssessment.tOptionalSubject WHERE AcademicId=A.Id) 
	--AND
	 RD.Obtain < Minimum	
   
	)
	END
	
	UPDATE sAssessment.tResult SET ResultStatus='PASS' 
	WHERE ExamId = @rExamId AND ResultStatus <> 'FAIL'
	AND AcademicId IN (SELECT Id FROM sStudent.tAcademic WHERE
	DivisionId = @rDivisionId AND BatchId = @rBatchId)
	

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


GO


ALTER PROCEDURE [sAssessment].[pRptResultListGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 --@rOrgId smallint,
	 @rBatchId int,
	 @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,
	 @rFromPercentage decimal(5,2)=0,
	 @rToPercentage decimal(5,2)=0,
	 @rDepartmentid int=0
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			Convert(nvarchar(20),A.Id) AS   AcademicIdText,	
	CONVERT (nvarchar(20),@rExamId) AS ExamIdText,
	CONVERT (nvarchar(20),EM.GradeSetId) AS GradeSetIdText,
			
			ESGM.Title AS Exam,
			SM.Code,
			  [sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) 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.TotalMarks,
			R.TotalObtain,
			R.Percentage,
			R.RankNumber,
			R.ResultGrade,
			EM.IsMarksInDecimal,
			SI.StudentPhoto,
			EM.DisplayTitle,
			OM.SmallAddress1,
			R.ResultRemark,
			R.OtherRemark1,
			EM.Remark1,
			EM.Remark2,
			EM.Remark3,
			SR.ResultRemark2,
			Em.GradeSetId,
			R.ResultStatus,
			SR.ResultRemark1,
			REPLICATE(',',EM.FooterAdjustment) AS FooterAdjustmentText,
			EI.EmployeeSign,
			EM.IsDisplayPrincipalSign,
			EM.IsDisplayTeacherSign,
			EM.IsOnPrePrinted,
			Em.IsDisplayPhoto,
			SR.PresentDays ,			
			SR.TotalDays
			
			 
		 
			
      
	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.tAcademic A ON R.AcademicId=A.Id
			 
			INNER JOIN sStudent.tStudentMaster SM ON A.StudentId=SM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=EM.ClassId
			INNER JOIN sSetup.tDivisionMaster DM ON A.DivisionId=DM.Id
			LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = DM.InchargeEmployeeId
			LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=SM.Id
			LEFT JOIN sAssessment.tStudentRemark SR ON SR.AcademicId=A.Id AND SR.ExamId = EM.Id
			
			 
	WHERE 
			
		      EM.BatchId = @rBatchId 
		AND (EM.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 ((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 ((SM.Code=@rCode) OR (@rCode=''))
		AND ((A.Id =@rAcademicId) OR (@rAcademicId=0))
		
		AND ((R.Percentage >=@rFromPercentage) OR (@rFromPercentage=0))
		AND ((R.Percentage <=@rToPercentage) OR (@rToPercentage=0))
		AND ((CM.DepartmentId = @rDepartmentId) OR (@rDepartmentId=0))
		
END
GO
PRINT N'Altering [sAssessment].[pRptResultSheetStandardMultiExamGet]...';


GO


ALTER PROCEDURE [sAssessment].[pRptResultSheetStandardMultiExamGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rSubjectId int = 0,
	 @rBatchId int=0,
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rExamId int,
	 @rCode nvarchar(20)='',
	 @rFromRollNo int=0,
	 @rToRollNo int=0,
	 @rFromRank int=0,
	 @rToRank int=0,
	 @rGrade nvarchar(20)='',
	 @rResultId bigint=0,
	 @rStatusId int=0,
	 @rAcademicId bigint=0,
	 @rFromPercentage decimal(5,2)=0,
	 @rToPercentage decimal(5,2)=0,
	 @rIsDetail 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),
@GradeSetId int , @IsIncludeSubExam bit
SELECT @GradeSetId = GradesetId,
	   @IsIncludeSubExam = ISNULL(IsIncludeSubExam,0)  FROM sAssessment.tExamMaster WHERE Id = @rExamId
SELECT @GradeString = [sAssessment].[fGradeStringGet](@GradeSetId)
 
--#TempAllExam
	CREATE TABLE #TempAllExam
	(
		AcademicIdText nvarchar(20),
		ExamIdText nvarchar(20),
		CoScholasticScopeIdText nvarchar(20),
		IsDisplayMonthlyAttendanceText nvarchar(20),
		
		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),
		IsMarksInDecimal bit,
		column_visible bit,
		--Obtain decimal(5,2),
		Percentile decimal(5,2),
		--ClassSubject nvarchar(100),
		ResultDetailId bigint,
		ResultId bigint,	
		Remark1 nvarchar(150),
		Remark2 nvarchar(150),
		Remark3 nvarchar(150),
		DisplayTitle nvarchar(150),		
		IsRankNo bit, 
		IsGrade bit,
		IsPercentile bit,
		IsPercentage bit,
		IsSubjectPercentile bit,
		IsProcessResult bit,
		IsNegativeMarks bit,
		IsIncludeCoScholastic bit,
		IsOnPrePrinted bit,
		IsDisplayPhoto bit,
		IsDisplayBirthDate bit,
		IsLockForEdit bit,
		IsDisplaySchoolName bit,			
		IsDisplayAttendance bit,
		IsDisplayHeightWeight bit,
		IsResultStatus bit,
		FooterAdjustmentText nvarchar(max),
		DetailAdjustmentText nvarchar(max),
		FooterAdjustment smallint,
		DetailAdjustment smallint,
		ResultRemark nvarchar(200),
		DateOfBirth date,
		HeightTerm1 decimal(5,2),
		WeightTerm1 decimal(5,2),
		HeightTerm2 decimal(5,2),
		WeightTerm2 decimal(5,2),
		HeightAnnual decimal(5,2),
		WeightAnnual decimal(5,2),
		PresentDaysTerm1 smallint,
		PresentDaysTerm2 smallint,
		PresentDaysAnnual smallint,
		TotalDaysTerm1 smallint,
		TotalDaysTerm2 smallint,
		TotalDaysAnnual smallint,
		TotalMarkTerm1 decimal(8,2),
		TotalObtainTerm1 decimal(8,2),
		PercentageTerm1 decimal(8,2),
		RankNumberTerm1 int,
		ResultGradeTerm1 NVarchar(50),
		PercentileTerm1 decimal(8,2),
		ResultStatusTerm1 Nvarchar(20),		   
		TotalMarkTerm2 decimal(8,2),
		TotalObtainTerm2 decimal(8,2),
		PercentageTerm2 decimal(8,2),
		RankNumberTerm2 int,
		ResultGradeTerm2 NVarchar(50),
		PercentileTerm2 decimal(8,2),
		ResultStatusTerm2 Nvarchar(20), 
		TermScopeId tinyint,		 
		StudentPhoto varbinary(max),
		GradeString nvarchar(1000),
		IsDisplayGradeString bit,		 
		IsDisplayInMarksheet bit,
		IsShowSubjectGrade bit,
		IsIncludeInTotal bit,
		ClassSubjectID int,
		SubjectId int,
		--Maximum decimal(5,2),
		SubjectOrderIndex smallint,
		SubjectGrade NVarchar(50),
		SubjectName NVarchar(150),
		SubjectCode Nvarchar(50),	
		SubjectMinimum decimal(8,2),		
		SubjectMaximum decimal(8,2),
		SubjectObtain  decimal(8,2),
		
		Exam1Name Nvarchar(150),		
		TotalMarks1 decimal(8,2),		
		TotalObtain1 decimal(8,2),
		Percentage1 decimal(8,2),
		RankNumber1 int,
		ResultGrade1 NVarchar(50),
		Percentile1 decimal(8,2),
		ResultStatus1 Nvarchar(20),
		
		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),
		
		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) ,
		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),
		DecimalFormat nvarchar(10),
		SubjectRemark nvarchar(1000)
		 
		
	)	
	 --print 'temp created'    	
	INSERT INTO  #TempAllExam 
	(
	AcademicIdText,
	ExamIdText,
	CoScholasticScopeIdText,
	IsDisplayMonthlyAttendanceText,
	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,
	DecimalFormat,
	SubjectRemark
	
 
 
	 
	)
	SELECT 
		Convert(nvarchar(20),A.Id),
		Convert(nvarchar(20),@rExamId),
		Convert(nvarchar(20),EM.CoScholasticScopeId),
		Convert(nvarchar(20),ISNULL(EM.IsDisplayMonthlyAttendance,0)),
		A.Id,
		ISNULL(ESGM.Title,'') AS EXAMNAME,
		StuM.Code AS StudCode,
		StuM.FirstName+' '+StuM.MiddleName+' '+StuM.LastName AS Name,
		A.RollNo,
		R.ResultStatus,
		CM.DisplayTitle AS ClassName,
		DM.DisplayTitle AS Division,
		R.TotalMarks AS TotalMark,
		R.TotalObtain,
		R.Percentage,
		R.RankNumber,
		R.ResultGrade,


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

		ISNULL(EM.Remark1,'') AS Remark1,
		ISNULL(EM.Remark2,'') AS Remark2,
		ISNULL(EM.Remark3,'') AS Remark3,
		EM.DisplayTitle,
		EM.IsRankNo, 
		EM.IsGrade,
		EM.IsPercentile,
		EM.IsPercentage,
		EM.IsSubjectPercentile,
		EM.IsProcessResult,
		EM.IsNegativeMarks,
		EM.IsIncludeCoScholastic,
		EM.IsOnPrePrinted,
		EM.IsDisplayPhoto,
		EM.IsDisplayBirthDate,
		EM.IsLockForEdit,
		EM.IsDisplaySchoolName,			
		EM.IsDisplayAttendance,
		EM.IsDisplayHeightWeight,
		EM.IsResultStatus,
		REPLICATE(',',EM.FooterAdjustment) AS FooterAdjustmentText,
		REPLICATE(',',EM.DetailAdjustment) AS DetailAdjustmentText,
		EM.FooterAdjustment,
		EM.DetailAdjustment,
		ISNULL(R.ResultRemark,'') AS ResultRemark,
		SO.DateOfBirth,
		AD.HeightTerm1,
		AD.WeightTerm1,
		AD.HeightTerm2,
		AD.WeightTerm2,
		AD.HeightAnnual,
		AD.WeightAnnual,
		AD.PresentDaysTerm1,
		AD.PresentDaysTerm2,
		AD.PresentDaysAnnual,
		AD.TotalDaysTerm1,
		AD.TotalDaysTerm2,
		AD.TotalDaysAnnual,
		EM.TermScopeId,
		(CASE EM.IsDisplayPhoto WHEN 1 THEN
			SI.StudentPhoto
		ELSE NULL END)AS StudentPhoto,
		@GradeString 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(EM.DecimalFormat,0) AS DecimalFormat,
		ISNULL(RD.Remark,'') AS SubjectRemark
		
		
		 
			
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 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										
					 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 
				    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)+'=EM.ExamMaximum
					 From						
						sAssessment.tResult R						
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON  T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
						
		execute(@query)
		
		
	set @lCount = @lCount -1
	end
	

	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
							 
					 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					 
					 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)
		
	
	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'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 	 
	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 	
				
				
				 
			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 sStudent.tStudentOther SO ON SO.StudentId=SA.StudentId
		    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 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
			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
	 
END
GO
PRINT N'Altering [sAttendance].[pAttenanceRegisterGet]...';


GO
 
 -- exec [sAttendance].[pAttenanceRegisterGet] '','',1,1001,6,2014,100100001,100100001,100100001,'',0,0
ALTER PROCEDURE [sAttendance].[pAttenanceRegisterGet]
 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rAttendanceTypeId smallint,
	 @rOrgId int,
	 @rForMonth smallint,
	 @rForYear smallint,
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rBatchId int = 0,
	 @rStudentCode nvarchar(20)='',
	 @rDepartmentId int = 0,
	 @rAcademicId bigint = 0,
	 @PageIndex int=0,
	 @rStatus int=0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
DECLARE @lFirstDate Date
	DECLARE @lResult nvarchar(max)
	DECLARE @li int 
	SET @li=1
	SET @lFirstDate = CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'/'+CONVERT(NVARCHAR(2),@rForMonth)+'/01'))	
	
	
DECLARE @lOrgId  int
--DECLARE @lSchoolRemark1  nvarchar(500)
--DECLARE @lSchoolRemark2  nvarchar(500)
--DECLARE @lSchoolRemark3  nvarchar(500)
DECLARE @lSchoolRequiredSignature  nvarchar(500)

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=1 where RGM.Id=1
 
-- select @lSchoolRequiredSignature as sig
 	
BEGIN 
	 CREATE Table #AttendanceRegistertempTable
(
	TID int identity(1,1),
	ClassDivisionTitle Nvarchar(50),
	Code nvarchar(50),
	RollNo int,
	AcademicId bigint,
	Name nvarchar(50),
	AttendanceTypeId int,
	ForYear int,
	ForMonth int,
	ForMonthInWord nvarchar(100),
	ClassId int,
	DivisionId int,
	ClassName nvarchar(50),
	DivisionName nvarchar(50),
	IsPresent bit,
	DayPart int,
	LeftDate date,
	ClassOrderIndex int,
	DivisionOrderIndex int,
	FooterSignature nvarchar(500),
	StatusId int,
	AttendanceDate date,
	AttendanceTagId int ,
	EmployeeName nvarchar(100)
)
Insert INTO #AttendanceRegistertempTable
(	
	ClassDivisionTitle,
	Code ,
	RollNo,
	AcademicId,
	Name,
	AttendanceTypeId,
	ForYear,
	ForMonth,
	ForMonthInWord,
	ClassId,
	DivisionId,
	ClassName,
	DivisionName,
	IsPresent,
	DayPart,
	LeftDate,
	ClassOrderIndex,
	DivisionOrderIndex,
	FooterSignature,
	StatusId,
	AttendanceDate,
	AttendanceTagId,
	EmployeeName
)
Select	    
	ISNULL(SA.ClassName + '-' + SA.DivisionName,'') AS ClassDivisionTitle,
	SA.Code,
	SA.RollNo,
	SA.AcademicId,
	SA.Name,
	SR.AttendanceTypeId ,
	YEAR(SR.AttendanceDate) AS ForYear,
	MONTH(SR.AttendanceDate) AS ForMonth,
	DATENAME(month, SR.AttendanceDate) AS ForMonthInWord,
	SA.ClassId,
	SA.DivisionId,
	SA.ClassName,Sa.DivisionName,
  
	--(CASE SR.IsPresent WHEN 1 THEN 'P' 
	--	WHEN 0 THEN 'A'
	--ELSE  ' ' END )AS  IsPresent,		
	SR.IsPresent,
	 day(SR.AttendanceDate) AS DayPart,
	 
	 A.LeftDate,
	 CM.OrderIndex AS ClassOrderIndex,
	 DM.OrderIndex As DivisionOrderIndex,
	@lSchoolRequiredSignature AS FooterSignature,
	 SA.StatusId,
	 SR.AttendanceDate As AttendanceDate,
	 SR.AttendanceTagId,
	 EM.FirstName+' ' + EM.LastName AS EmployeeName
	 --,
	 --SR.IsPresent
	 
	 
    from
            sStudent.vStudentAcademic SA 
            INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.AcademicId 
            INNER JOIN sStudent.tStudentAdmission A ON SA.StudentId = A.StudentId
            INNER JOIN sSetup.tClassMaster CM ON CM.Id = SA.ClassId
            INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = CM.OrgId
            INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=SA.DivisionId
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId
            
			
            
             WHERE  
	        ((SR.AttendanceTypeId=@rAttendanceTypeId) OR (@rAttendanceTypeId= 0))
	         AND ((SA.OrgId=@rOrgId) OR (@rOrgId= 0))
	          AND ((SA.BatchId=@rBatchId) OR (@rBatchId= 0))
	          AND ((YEAR(SR.AttendanceDate)=@rForYear) OR (@rForYear= 0))
	          AND ((MONTH(SR.AttendanceDate)=@rForMonth) OR (@rForMonth= 0))
	           AND ((SA.ClassId=@rClassId) OR (@rClassId= 0))
	           AND ((SA.Code=@rStudentCode) OR (@rStudentCode=''))
	           AND ((SA.AcademicId=@rAcademicId) OR (@rAcademicId=0))	           
				AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
	           AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId= 0))
	           AND ((SA.StatusId=@rStatus)OR (@rStatus=0))

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

SELECT 
@li AS DayPart,
 [sAttendance].[fWeekHOffHolidayGet](@rForYear,@rForMonth,@li,@rBatchId,@rDivisionId,'',@rOrgId) 
SET @li = @li + 1
END

 

SELECT  
			@lFirstDate AS LastDate,
			LeftDate,
            @rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			PivotTable.AcademicId,
			ClassDivisionTitle,isnull(Code,'') as Code,isnull(RollNo,0) as RollNo,
			isnull(Name,'') as Name,isnull(AttendanceTypeId,0) as AttendanceTypeId,ForYear,
			ForMonth,ClassId,ClassName,DivisionId,
			DivisionName,
			 
			ForMonthInWord,
			(ISNULL(TC.TCount,0) - ISNULL(AC.ACount,0)) AS PresentCount,
			 ISNULL(TC.TCount,0) AS AttendanceCount,
		      ISNULL(AC.ACount,0) As  AbsentCount,
		       ISNULL(PC.PCount,0) As  PresentUpto,
		       ClassOrderIndex,
		       DivisionOrderIndex,
		       FooterSignature,				 
			0 AS TotalPresent ,
	 		 isnull([1],'') AS P1,
			isnull([2],'') AS P2,
			isnull([3],'') AS P3,
			isnull([4],'') AS P4,
			isnull([5],'') AS P5,
			isnull([6],'') AS P6,
			isnull([7],'') AS P7,
			isnull([8],'') AS P8,
			isnull([9],'') AS P9,
			isnull([10],'') AS P10,
			isnull([11],'') AS P11,
			isnull([12],'') AS P12,
			isnull([13],'') AS P13,
			isnull([14],'') AS P14,
			isnull([15],'') AS P15,
			isnull([16],'') AS P16,
			isnull([17],'') AS P17,
			isnull([18],'') AS P18,
			isnull([19],'') AS P19,
			isnull([20],'') AS P20,
			isnull([21],'') AS P21,
			isnull([22],'') AS P22,
			isnull([23],'') AS P23,
			isnull([24],'') AS P24,
			isnull([25],'') AS P25,
			isnull([26],'') AS P26,
			isnull([27],'') AS P27,
			isnull([28],'') AS P28,
			isnull([29],'') AS P29,
			isnull([30],'') AS P30,
			isnull([31],'') AS P31, 
			 EmployeeName ,
 
sCommon.fGetDaysInMonth ( @rForMonth,@rForYear) AS DaysInMonth 
--,
--AttendanceTagId

 
FROM
(
	Select --TID, 
		ISNULL(ClassName + '-' + DivisionName,'') AS ClassDivisionTitle,
		Code,
		RollNo,
		AcademicId,
		Name,
		AttendanceTypeId ,
		YEAR(ST.AttendanceDate) AS ForYear,
		MONTH(ST.AttendanceDate) AS ForMonth,
		DATENAME(month, ST.AttendanceDate) AS ForMonthInWord,
		ClassId,
		DivisionId,
		ClassName,
		DivisionName,
		(
			CASE  WHEN IsPresent = 1 AND ST.AttendanceTagId = 1 THEN 'LC' 
				  WHEN IsPresent = 1 AND ST.AttendanceTagId = 2 THEN 'EL' 
			      WHEN IsPresent = 1  THEN 'P' 
				  WHEN IsPresent = 0 THEN 'A'
				  ELSE  DT.Value END 
		)AS  IsPresent,		
		day(ST.AttendanceDate) AS DayPart,
		LeftDate
		,
		ClassOrderIndex,
		DivisionOrderIndex,
		FooterSignature,EmployeeName
      -- DO NOT ADD ANY FIELD HERE WITHOUT PERMISSION OF RAJENDRA
	 FROM 
		#AttendanceRegistertempTable ST 
		INNER JOIN #TempDaysTempTable DT ON DT.DayPart = ST.DayPart
	 WHERE
		((LeftDate >= @lFirstDate) OR ISNULL(LeftDate,'') = '')
) AS SourceTable 
 
	           
	        
PIVOT
(	
MIN(IsPresent)
FOR DayPart IN ([0], [1], [2], [3], [4],[5],[6],[7],[8],[9],[10],[11],[12],[13],[14],[15],[16],[17],[18],[19],[20],[21],[22],[23],[24],[25],[26],[27],[28],[29],[30],[31])
) AS PivotTable
	LEFT JOIN
	(
		Select  AcademicId AS AcademicId, COUNT(1) AS TCount 
		   FROM  
				#AttendanceRegistertempTable
		    
			GROUP BY  AcademicId
    ) TC ON TC.AcademicId = PivotTable.AcademicId
    
	LEFT JOIN
	(
		Select AcademicId AS AcademicId, COUNT(1) AS ACount 
		   FROM  #AttendanceRegistertempTable
		    WHERE   IsPresent = 0	 		
            
			GROUP BY  AcademicId
    ) AC ON AC.AcademicId = PivotTable.AcademicId
	LEFT JOIN
	(
			SELECT SR.AcademicId AS AcademicId, COUNT(1) AS PCount  
			 from sAttendance.tStudentRegister SR
			  INNER JOIN #AttendanceRegistertempTable AT
			 ON SR.AcademicId = AT.AcademicId 
			 WHERE SR.AttendanceDate < (convert(date,CONVERT(nvarchar(10), @rForYear)+ '/' +  CONVERT(nvarchar(10), @rForMonth) + '/' + '01' ))
				AND  SR.IsPresent = 1	    	
			GROUP BY SR.AcademicId
    ) PC ON PC.AcademicId = PivotTable.AcademicId
 
 
    ORDER BY RollNo;
 

select * from #TempDaysTempTable
 

drop table #AttendanceRegistertempTable	  
drop table #TempDaysTempTable
	
	
END
GO
PRINT N'Altering [sAttendance].[pAttenanceRegisterGetNew]...';


GO
 -- exec [sAttendance].[pAttenanceRegisterGetNew] '','',1,1001,7,2016,100100001,100100001,100100114,0,0,1
ALTER PROCEDURE [sAttendance].[pAttenanceRegisterGetNew]
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rAttendanceTypeId smallint,
	 @rOrgId int,
	 @rForMonth smallint,
	 @rForYear smallint,
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rBatchId int = 0,
	 @rStudentCode nvarchar(20)='',
	 @rDepartmentId int = 0,
	 @rAcademicId bigint = 0,
	 @PageIndex int=0
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	DECLARE @lFirstDate Date
	DECLARE @lResult nvarchar(max)
	DECLARE @li int 
	SET @li=1
	SET @lFirstDate = CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'/'+CONVERT(NVARCHAR(2),@rForMonth)+'/01'))	
BEGIN 
CREATE Table #AttendanceRegistertempTable
(
	 
	ClassDivisionTitle Nvarchar(50),
	Code nvarchar(50),
	RollNo int,
	AcademicId bigint,
	Name nvarchar(50),
	AttendanceTypeId int,
	ForYear int,
	ForMonth int,
	ForMonthInWord nvarchar(100),
	ClassId int,
	DivisionId int,
	ClassName nvarchar(50),
	DivisionName nvarchar(50),
	IsPresent bit,
	DayPart int,
	LeftDate date,
	ClassOrderIndex int,
	DivisionOrderIndex int,
	FooterSignature nvarchar(500),
	StatusId int,
	AttendanceDate date,
	AttendanceTagId int 
 
)
Insert INTO #AttendanceRegistertempTable
(	
	ClassDivisionTitle,
	Code ,
	RollNo,
	AcademicId,
	Name,
	AttendanceTypeId,
	ForYear,
	ForMonth,
	ForMonthInWord,
	ClassId,
	DivisionId,
	ClassName,
	DivisionName,
	IsPresent,
	DayPart,
	LeftDate,
	ClassOrderIndex,
	DivisionOrderIndex,
	FooterSignature,
	StatusId,
	AttendanceDate,
	AttendanceTagId
  
)
Select	    
	ISNULL(SA.ClassName + '-' + SA.DivisionName,'') AS ClassDivisionTitle,
	SA.Code,
	SA.RollNo,
	SA.AcademicId,
	SA.Name,
	SR.AttendanceTypeId ,
	YEAR(SR.AttendanceDate) AS ForYear,
	MONTH(SR.AttendanceDate) AS ForMonth,
	DATENAME(month, SR.AttendanceDate) AS ForMonthInWord,
	SA.ClassId,
	SA.DivisionId,
	SA.ClassName,Sa.DivisionName,
  
	--(CASE SR.IsPresent WHEN 1 THEN 'P' 
	--	WHEN 0 THEN 'A'
	--ELSE  ' ' END )AS  IsPresent,		
	SR.IsPresent,
	 day(SR.AttendanceDate) AS DayPart,
	 
	 A.LeftDate,
	 CM.OrderIndex AS ClassOrderIndex,
	 DM.OrderIndex As DivisionOrderIndex,
	 OM.FooterSignature AS FooterSignature,
	 SA.StatusId,
	 SR.AttendanceDate As AttendanceDate,
	 SR.AttendanceTagId
	 
	 --,
	 --SR.IsPresent
	 
	 
    from
            sStudent.vStudentAcademic SA 
            INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.AcademicId 
            INNER JOIN sStudent.tStudentAdmission A ON SA.StudentId = A.StudentId
            INNER JOIN sSetup.tClassMaster CM ON CM.Id = SA.ClassId
            INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = CM.OrgId
            INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=SA.DivisionId
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId
            
			
            
             WHERE  
	        ((SR.AttendanceTypeId=@rAttendanceTypeId) OR (@rAttendanceTypeId= 0))
	         AND ((SA.OrgId=@rOrgId) OR (@rOrgId= 0))
	          AND ((SA.BatchId=@rBatchId) OR (@rBatchId= 0))
	          AND ((YEAR(SR.AttendanceDate)=@rForYear) OR (@rForYear= 0))
	          AND ((MONTH(SR.AttendanceDate)=@rForMonth) OR (@rForMonth= 0))
	           AND ((SA.ClassId=@rClassId) OR (@rClassId= 0))
	           AND ((SA.Code=@rStudentCode) OR (@rStudentCode=''))
	           AND ((SA.AcademicId=@rAcademicId) OR (@rAcademicId=0))	           
				AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
	           AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId= 0))

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

SELECT 
@li AS DayPart,
 [sAttendance].[fWeekHOffHolidayGet](@rForYear,@rForMonth,@li,@rBatchId,@rDivisionId,'',@rOrgId) 
SET @li = @li + 1
END

--DECLARE @TotalRecords int,@lpaging varchar(max)='',@PageSize int =100
--SELECT @TotalRecords = count(*)	 from #AttendanceRegistertempTable
--SELECT @lpaging = @lpaging + dbo.fnc_SearchPagingFormat(@PageIndex,@TotalRecords,@PageSize)

SELECT  
			@lFirstDate AS LastDate,
			LeftDate,
            @rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			PivotTable.AcademicId,
			ClassDivisionTitle,isnull(Code,'') as Code,isnull(RollNo,0) as RollNo,
			isnull(Name,'') as Name,isnull(AttendanceTypeId,0) as AttendanceTypeId,ForYear,
			ForMonth,ClassId,ClassName,DivisionId,
			DivisionName,
			 
			ForMonthInWord,
			(ISNULL(TC.TCount,0) - ISNULL(AC.ACount,0)) AS PresentCount,
			 ISNULL(TC.TCount,0) AS AttendanceCount,
				
		      ISNULL(AC.ACount,0) As  AbsentCount,
		       ISNULL(PC.PCount,0) As  PresentUpto,
		       ClassOrderIndex,
		       DivisionOrderIndex,
		       FooterSignature,				 
			0 AS TotalPresent ,
	 		isnull([1],'') AS P1,
			isnull([2],'') AS P2,
			isnull([3],'') AS P3,
			isnull([4],'') AS P4,
			isnull([5],'') AS P5,
			isnull([6],'') AS P6,
			isnull([7],'') AS P7,
			isnull([8],'') AS P8,
			isnull([9],'') AS P9,
			isnull([10],'') AS P10,
			isnull([11],'') AS P11,
			isnull([12],'') AS P12,
			isnull([13],'') AS P13,
			isnull([14],'') AS P14,
			isnull([15],'') AS P15,
			isnull([16],'') AS P16,
			isnull([17],'') AS P17,
			isnull([18],'') AS P18,
			isnull([19],'') AS P19,
			isnull([20],'') AS P20,
			isnull([21],'') AS P21,
			isnull([22],'') AS P22,
			isnull([23],'') AS P23,
			isnull([24],'') AS P24,
			isnull([25],'') AS P25,
			isnull([26],'') AS P26,
			isnull([27],'') AS P27,
			isnull([28],'') AS P28,
			isnull([29],'') AS P29,
			isnull([30],'') AS P30,
			isnull([31],'') AS P31, 
 
sCommon.fGetDaysInMonth ( @rForMonth,@rForYear) AS DaysInMonth
,0 Ispresent,
0 AS AttendanceTagId
  
--,AttendanceTagId

 
FROM
(
	Select --TID, 
		ISNULL(ClassName + '-' + DivisionName,'') AS ClassDivisionTitle,
		Code,
		RollNo,
		AcademicId,
		Name,
		AttendanceTypeId ,
		YEAR(ST.AttendanceDate) AS ForYear,
		MONTH(ST.AttendanceDate) AS ForMonth,
		DATENAME(month, ST.AttendanceDate) AS ForMonthInWord,
		ClassId,
		DivisionId,
		ClassName,
		DivisionName,
		(
			CASE 
			 WHEN IsPresent = 1 AND ST.AttendanceTagId = 1 THEN 'LA' 
				  WHEN IsPresent = 1 AND ST.AttendanceTagId = 2 THEN 'ED' 
			      WHEN IsPresent = 1  THEN 'P' 
				  WHEN IsPresent = 0 THEN 'A'
				  ELSE  DT.Value END 
		)AS  IsPresent,		
		day(ST.AttendanceDate) AS DayPart,
		LeftDate,
		ClassOrderIndex,
		DivisionOrderIndex,
		FooterSignature 
		 -- DO NOT ADD ANY FIELD HERE WITHOUT PERMISSION OF RAJENDRA
		
	 FROM 
		#AttendanceRegistertempTable ST 
		INNER JOIN #TempDaysTempTable DT ON DT.DayPart = ST.DayPart
	 WHERE
		((LeftDate >= @lFirstDate) OR ISNULL(LeftDate,'') = '')
) AS SourceTable 
	           
	        
PIVOT
(	
MIN(IsPresent)
FOR DayPart IN ([0], [1], [2], [3], [4],[5],[6],[7],[8],[9],[10],[11],[12],[13],[14],[15],[16],[17],[18],[19],[20],[21],[22],[23],[24],[25],[26],[27],[28],[29],[30],[31])
) AS PivotTable
	LEFT JOIN
	(
		Select  AcademicId AS AcademicId, COUNT(1) AS TCount
		--,IsPresent,AttendanceTagId 
		   FROM  
				#AttendanceRegistertempTable
		    
			GROUP BY  AcademicId
			--,IsPresent,AttendanceTagId
    ) TC ON TC.AcademicId = PivotTable.AcademicId
    
	LEFT JOIN
	(
		Select AcademicId AS AcademicId, COUNT(1) AS ACount 
		   FROM  #AttendanceRegistertempTable
		    WHERE   IsPresent = 0	 		
             --AND ( StatusId = 1)
			GROUP BY  AcademicId
    ) AC ON AC.AcademicId = PivotTable.AcademicId
	LEFT JOIN
	(
		SELECT A.Id AS AcademicId, COUNT(1) AS PCount  FROM sAttendance.tStudentRegister SR 
			INNER JOIN sStudent.tAcademic A ON SR.AcademicId = A.Id 
		   INNER JOIN sStudent.tStudentMaster SA ON A.StudentId = SA.Id
		   INNER JOIN sSetup.tClassMaster CM ON A.ClassId = CM.Id
			WHERE  
			 SR.AttendanceDate < (convert(date,CONVERT(nvarchar(10), @rForYear)+ '/' +  CONVERT(nvarchar(10), @rForMonth) + '/' + '01' ))
			AND SR.IsPresent = 1	    		
            --AND (SA.StatusId = 1)
	        AND ((SR.AttendanceTypeId=@rAttendanceTypeId) OR (@rAttendanceTypeId= 0))
	        AND ((SA.OrgId=@rOrgId) OR (@rOrgId= 0))
	        AND ((A.BatchId=@rBatchId) OR (@rBatchId= 0))	          
	        AND ((A.ClassId=@rClassId) OR (@rClassId= 0))
	        AND ((SA.Code=@rStudentCode) OR (@rStudentCode=''))
	        AND ((A.Id=@rAcademicId) OR (@rAcademicId=0))	           
			AND ((CM.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))				
	        AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId= 0))
			GROUP BY A.Id
    ) PC ON PC.AcademicId = PivotTable.AcademicId
    ORDER BY RollNo;
    
select * from #TempDaysTempTable
--select '' as paging

drop table #AttendanceRegistertempTable	  
drop table #TempDaysTempTable
END
GO
PRINT N'Altering [sAttendance].[pAttendanceListGet]...';


GO
ALTER PROCEDURE [sAttendance].[pAttendanceListGet]
	 	 
	 	 @rClassId int,
	 	 @rDivisionId int,
	 	 @rStudentCode nvarchar(20),
	 	 @rAttendanceTypeId tinyint,
	 	 @rSubjectId int,
	 	 @rRepeatCount tinyint,
	 	 @rPresent tinyint,
		 @rFromAttendanceDate date,
		 @rToAttendanceDate date,
	 	 @rBatchId int,
	 	 @rOrgId int,
	 	 @rAttendanceTag smallint=0,
	 	 @rStatus int=0,
	 	 @rFromRollNo int=0,
	 	 @rToRollNo int=0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	SELECT 
			SA.AcademicId,
			SA.Code AS StudentCode,
			ISNULL(SA.RollNo,0) as StudentRollNo,
			SA.Name,
			SA.ClassName + '-' + SA.DivisionName AS ClassName,
			SR.AttendanceTypeId,
			ATM.Title AS AttendanceTypeName,
			SR.AttendanceDate,
			SR.SubjectId,
			CASE AttendanceTypeId WHEN 1 THEN '' ELSE SR.RepeatCount END AS RepeatCount,
			--SR.RepeatCount,
			ISNULL(SR.IsPresent,'true') as IsPresent,
			ISNULL(SR.AbsentReasonId,0) as AbsentReasonId,
			ARM.Title AS AbsentReasonName,
			SM.Title As SubjectName,
			EM.EmployeeId,
			EM.Code AS EmployeeCode,
			EM.EmployeeName,
			SR.AttendanceTagId
	 FROM 
			sStudent.vStudentAcademic SA 
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.AcademicId 
			LEFT JOIN sAttendance.tAttendanceTypeMaster ATM ON ATM.Id=SR.AttendanceTypeId
			LEFT JOIN sAttendance.tAbsentReasonMaster ARM ON ARM.Id=SR.AbsentReasonId
			LEFT JOIN sSetup.tSubjectMaster SM ON SM.Id=SR.SubjectId
			LEFT JOIN sHrm.vExtEmployeeMaster EM ON EM.EmployeeId=SA.InchargeEmployeeId
			
  WHERE 
	 ((SA.ClassId=@rClassId) OR (@rClassId=0))
	  AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
	  AND ((SA.Code=@rStudentCode) OR (@rStudentCode=''))
	  AND ((SR.AttendanceTypeId=@rAttendanceTypeId) OR (@rAttendanceTypeId=0))
	  AND ((SR.SubjectId=@rSubjectId) OR (@rSubjectId=0))
	  AND ((SR.RepeatCount=@rRepeatCount) OR (@rRepeatCount=0))
	  AND ((SR.IsPresent=@rPresent) OR (@rPresent=2))
	  AND ((SR.AttendanceDate >= @rFromAttendanceDate) OR (ISNULL(@rFromAttendanceDate,'') = ''))
	  AND ((SR.AttendanceDate <= @rToAttendanceDate) OR (ISNULL(@rToAttendanceDate,'') = ''))
      AND (SA.OrgId = @rOrgId)
      AND (SA.BatchId = @rBatchID)
      AND ((SR.AttendanceTagId =@rAttendanceTag)OR (@rAttendanceTag=0))
      AND ((SA.StatusId =@rStatus)OR (@rStatus=0))
      ANd ((SA.RollNo>=@rFromRollNo) OR (@rFromRollNo=0))
      AND ((SA.RollNo<=@rToRollNo) OR (@rToRollNo=0))
      --AND (SA.StatusId != 3)
      ORDER BY SA.DivisionOrder, SA.RollNo, SR.AttendanceDate DESC
END
GO
PRINT N'Altering [sAttendance].[pEmployeeAttendanceRegisterXMLAdd]...';


GO
ALTER PROCEDURE [sAttendance].[pEmployeeAttendanceRegisterXMLAdd]
	(
		@rXmlDoc nvarchar(MAX)
	)
AS

SET NOCOUNT ON

BEGIN
SET @rXmlDoc=REPLACE(@rXmlDoc,'&','AND')
DECLARE @lInterrorCode INT,
			@intDoc INT
BEGIN TRY
BEGIN TRANSACTION	
	EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc
	
	DECLARE @lBatchId int
	SELECT @lBatchId= BM.Id From sSetup.tBatchMaster BM 
	INNER JOIN sSetup.tOrganizationMaster OM ON BM.OrgId = OM.Id And ISActive =1
	INNER JOIN sHRM.tEmployeeMaster EM ON EM.OrgId = OM.Id
	INNER JOIN (SELECT EmployeeId FROM OPENXML (@intDoc, '/Table/EmployeeAttendace', 1)
	WITH
	(		
		EmployeeId BigINT '@EmployeeId'
	))A ON  A.EmployeeId = EM.Id
		
	-----------------------
	DELETE SA FROM sHrm.tEmployeeAttendanceRegister SA INNER JOIN 
	(SELECT EmployeeId,AttendanceDate FROM OPENXML (@intDoc, '/Table/EmployeeAttendace', 1)
	WITH
	(		
		EmployeeId BigINT '@EmployeeId',
		AttendanceDate DateTime '@AttendanceDate'
	))A ON  SA.EmployeeId = A.EmployeeId AND SA.AttendanceDate=A.AttendanceDate 
		
	
	INSERT INTO sHrm.tEmployeeAttendanceRegister
	(
		EmployeeId,
		AttendanceDate,
		IsPresent,
		AbsentReasonId,
		UpdatedUserId,
		UpdatedDateTime,
		BatchId	
	)
	SELECT
		EmployeeId,
		AttendanceDate,
		IsPresent,
		1,
		1,
		GETDATE(),
		@lBatchId
		
	FROM OPENXML (@intDoc, '/Table/EmployeeAttendace', 1)
	WITH
	(		
		EmployeeId BigINT '@EmployeeId',
		AttendanceDate DateTime '@AttendanceDate',
		IsPresent Smallint '@IsPresent'
	)A
	
	
	EXEC sp_xml_removedocument @intDoc
	COMMIT TRANSACTION
	SELECT 1
	END TRY
	BEGIN CATCH
	SELECT -1
	END CATCH

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


GO

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

BEGIN 

	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			SA.AcademicId,
			SA.ClassId,
			SA.DivisionId,
			SA.ClassName,
			SA.DivisionName,
			SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
			SA.Code,
			SA.RollNo,			
			SA.Name,
			ISNULL(SO.DateOfBirth,NULL) AS DateOfBirth,
			SA.DivisionOrder
	FROM 
			sStudent.vStudentAcademic SA
        INNER JOIN sStudent.tStudentOther SO ON SA.StudentId = SO.StudentId 			
	WHERE 
			(SA.OrgId=@rOrgId)
		AND	(SA.BatchId = @rBatchId) 
		AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((SA.StatusId=@rStatus) OR (@rStatus=0))
END
GO
PRINT N'Altering [sAttendance].[pStudentRegisterGet]...';


GO
ALTER PROCEDURE [sAttendance].[pStudentRegisterGet]
	 	 
	 	 @rClassId int,
	 	 @rDivisionId int,
	 	 @rAttendanceTypeId tinyint,
		 @rAttendanceDate date,
		 @rSubjectId int,
		 @rSubjectBatchId int,
		 @rRepeatCount tinyint,
	 	 @rBatchId int,
	 	 @rOrgId int
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
IF @rSubjectBatchId=0
BEGIN
	IF @rRepeatCount=0
	BEGIN
	SELECT 
			SA.AcademicId,
			ISNULL(SA.RollNo,0) as RollNo,
			SA.Name,
			SA.Code,
			ISNULL(SR.IsPresent,'true') as IsPresent,
			ISNULL(SR.AbsentReasonId,0) as AbsentReasonId,
			case when SR.CreatedUserId IS NULL then 'false' else 'true' end as IsDeleted,
			SR.RepeatCount,
			EM.EmployeeId,
			EM.Code AS EmployeeCode,
			EM.EmployeeName,
			ISNULL(SR.AttendanceTagId,0) AS AttendanceTagId
		 
			
  FROM 
            sStudent.vStudentAcademic SA 
            INNER JOIN sStudent.tStudentAdmission AD ON SA.StudentId = AD.StudentId
        LEFT JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.AcademicId 
			AND (SR.AttendanceTypeId=@rAttendanceTypeId)
			AND (SR.AttendanceDate=@rAttendanceDate)
			AND (ISNULL(SR.SubjectId,0)=@rSubjectId)
			AND (ISNULL(SR.RepeatCount,0)=@rRepeatCount)
		LEFT JOIN sHrm.vExtEmployeeMaster EM ON EM.EmployeeId=SA.InchargeEmployeeId
  WHERE 
		  ((SA.ClassId=@rClassId) OR (@rClassId=0))
	  AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
      AND (SA.OrgId = @rOrgId)
      AND (SA.BatchId = @rBatchID)
      --AND (SA.StatusId != 3)
      AND (AD.LeftDate > @rAttendanceDate OR ISNULL(AD.LeftDate,'')= '')
      AND (AD.AdmissionDate <= @rAttendanceDate)
      ORDER BY RollNo
  END
  ELSE
  BEGIN
	SELECT 
			SA.AcademicId,
			ISNULL(SA.RollNo,0) as RollNo,
			SA.Name,
			SA.Code,
			ISNULL(SR.IsPresent,'true') as IsPresent,
			ISNULL(SR.AbsentReasonId,0) as AbsentReasonId,
			case when SR.CreatedUserId IS NULL then 'false' else 'true' end as IsDeleted,
			SR.RepeatCount,
			EM.EmployeeId,
			EM.Code AS EmployeeCode,
			EM.EmployeeName,
			ISNULL(SR.AttendanceTagId,0) AS AttendanceTagId 
			
  FROM 
            sStudent.vStudentAcademic SA 
            INNER JOIN sStudent.tStudentAdmission AD ON SA.StudentId = AD.StudentId
        LEFT JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.AcademicId 
			AND (SR.AttendanceTypeId=@rAttendanceTypeId)
			AND (SR.AttendanceDate=@rAttendanceDate)
			AND ((ISNULL(SR.SubjectId,0)=@rSubjectId) OR (@rSubjectId=0))
			AND ((ISNULL(SR.RepeatCount,0)=@rRepeatCount) OR (@rRepeatCount=0))
		LEFT JOIN sHrm.vExtEmployeeMaster EM ON EM.EmployeeId=SA.InchargeEmployeeId
  WHERE 
		  ((SA.ClassId=@rClassId) OR (@rClassId=0))
	  AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
      AND (SA.OrgId = @rOrgId)
      AND (SA.BatchId = @rBatchID)
      --AND (SA.StatusId != 3)
       AND (AD.LeftDate > @rAttendanceDate OR ISNULL(AD.LeftDate,'')= '')
       AND (AD.AdmissionDate <= @rAttendanceDate)
      ORDER BY RollNo
  END
END
ELSE
BEGIN
	IF @rRepeatCount=0
	BEGIN
	SELECT 
			SA.AcademicId,
			ISNULL(SA.RollNo,0) as RollNo,
			SA.Name,
			SA.Code,
			ISNULL(SR.IsPresent,'true') as IsPresent,
			ISNULL(SR.AbsentReasonId,0) as AbsentReasonId,
			case when SR.CreatedUserId IS NULL then 'false' else 'true' end as IsDeleted,
			SR.RepeatCount,
			EM.EmployeeId,
			EM.Code AS EmployeeCode,
			EM.EmployeeName,
			ISNULL(SR.AttendanceTagId,0) AS AttendanceTagId 
			
  FROM 
            sStudent.vStudentAcademic SA
             INNER JOIN sStudent.tStudentAdmission AD ON SA.StudentId = AD.StudentId 
        LEFT JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.AcademicId 
			AND (SR.AttendanceTypeId=@rAttendanceTypeId)
			AND (SR.AttendanceDate=@rAttendanceDate)
			AND (ISNULL(SR.SubjectId,0)=@rSubjectId)
			AND (ISNULL(SR.RepeatCount,0)=@rRepeatCount)
		INNER JOIN sAttendance.tSubjectBatchStudent SBS ON SBS.AcademicId=SA.AcademicId 
			AND SBS.BatchId=@rBatchId AND SBS.SubjectBatchId=@rSubjectBatchId
		LEFT JOIN sHrm.vExtEmployeeMaster EM ON EM.EmployeeId=SA.InchargeEmployeeId
  WHERE 
		  ((SA.ClassId=@rClassId) OR (@rClassId=0))
	  AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
      AND (SA.OrgId = @rOrgId)
      AND (SA.BatchId = @rBatchID)
      --AND (SA.StatusId != 3)
       AND (AD.LeftDate > @rAttendanceDate OR ISNULL(AD.LeftDate,'')= '')
      AND (AD.AdmissionDate <= @rAttendanceDate)
      ORDER BY RollNo
  END
  ELSE
  BEGIN
	SELECT 
			SA.AcademicId,
			ISNULL(SA.RollNo,0) as RollNo,
			SA.Name,
			SA.Code,
			ISNULL(SR.IsPresent,'true') as IsPresent,
			ISNULL(SR.AbsentReasonId,0) as AbsentReasonId,
			case when SR.CreatedUserId IS NULL then 'false' else 'true' end as IsDeleted,
			SR.RepeatCount,
			EM.EmployeeId,
			EM.Code AS EmployeeCode,
			EM.EmployeeName,
			ISNULL(SR.AttendanceTagId,0) AS AttendanceTagId
			
  FROM 
            sStudent.vStudentAcademic SA 
             INNER JOIN sStudent.tStudentAdmission AD ON SA.StudentId = AD.StudentId
        LEFT JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.AcademicId 
			AND (SR.AttendanceTypeId=@rAttendanceTypeId)
			AND (SR.AttendanceDate=@rAttendanceDate)
			AND ((ISNULL(SR.SubjectId,0)=@rSubjectId) OR (@rSubjectId=0))
			AND ((ISNULL(SR.RepeatCount,0)=@rRepeatCount) OR (@rRepeatCount=0))
		INNER JOIN sAttendance.tSubjectBatchStudent SBS ON SBS.AcademicId=SA.AcademicId 
			AND SBS.BatchId=@rBatchId AND SBS.SubjectBatchId=@rSubjectBatchId
		LEFT JOIN sHrm.vExtEmployeeMaster EM ON EM.EmployeeId=SA.InchargeEmployeeId
  WHERE 
		  ((SA.ClassId=@rClassId) OR (@rClassId=0))
	  AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
      AND (SA.OrgId = @rOrgId)
      AND (SA.BatchId = @rBatchID)
      --AND (SA.StatusId != 3)
       AND (AD.LeftDate > @rAttendanceDate OR ISNULL(AD.LeftDate,'')= '')
      AND (AD.AdmissionDate <= @rAttendanceDate)
      ORDER BY RollNo
  END
END
END
GO
PRINT N'Altering [sAttendance].[pStudentRegisterXMLInsert]...';


GO
 
ALTER PROCEDURE [sAttendance].[pStudentRegisterXMLInsert]
	
	@rStrXml nvarchar(MAX),
    @rOrgId int,
    @rClassId int=0,
    @rDivisionId int,
    @rAttendanceDate date='',
    @rAttendanceTypeId tinyint,
    @rCreatedUserId bigint,
    @rSubjectId int=0,
    @rRepeatCount tinyint=0,
    @rBatchId int=0 
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET @rStrXml=REPLACE(@rStrXml,'&','AND')
DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION 
	 BEGIN
	 
	 DELETE SR FROM sAttendance.tStudentRegister SR 
	 INNER JOIN sStudent.tAcademic SA ON SA.Id = SR.AcademicId
	 --INNER JOIN (SELECT AcademicId FROM OPENXML(@loDoc, '/Table/RowData', 1)
	 --WITH
	 --(AcademicId bigint))A ON SR.AcademicId = A.AcademicId 
	    WHERE 
	    SR.AttendanceTypeId = @rAttendanceTypeId AND SR.AttendanceDate = @rAttendanceDate
	    --AND SA.ClassId = @rClassId 
	    AND SA.DivisionId=@rDivisionId 
	    AND SA.OrgId = @rOrgId 
	    AND ((ISNULL(SR.SubjectId,0) = ISNULL(@rSubjectId,0)) OR ( ISNULL(@rSubjectId,0)=0))
	    AND ((ISNULL(SR.RepeatCount,0) = ISNULL(@rRepeatCount,0)) OR (ISNULL(@rRepeatCount,0)=0))
	     AND SA.BatchId =@rBatchId
	 
	 INSERT INTO sAttendance.tStudentRegister 
		(
			AcademicId,
			EmployeeId,
			AttendanceTypeId,
			AttendanceDate,
			SubjectId,
			RepeatCount,
			IsPresent,
			AbsentReasonId,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime,
			AttendanceTagId
			)
		SELECT	
		DISTINCT	
			AcademicId,
			EmployeeId,
			@rAttendanceTypeId,
			@rAttendanceDate,
			ISNULL(@rSubjectId,0),
			ISNULL(@rRepeatCount,0),
			IsPresent,
			ISNULL(AbsentReasonId,0),
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rCreatedUserId,
			sCommon.fGetDate(),
			ISNULL(AttendanceTagId,0)
						
		FROM OPENXML (@loDoc, '/Table/RowData', 1)
		WITH ( 
				AcademicId bigint,
				EmployeeId bigint,
				IsPresent bit,
				AbsentReasonId int,
				AttendanceTagId 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 [sAttendance].[pStudetntAttendanceGet]...';


GO

ALTER PROCEDURE [sAttendance].[pStudetntAttendanceGet]
	 	 
	 	  @rForMonth smallint,
	      @rForYear smallint,
	      @rAcademicId bigint,
	      @rAttendanceTypeId smallint,
	      @rBatchId int = 0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	Select 
	
	        DAY(SR.AttendanceDate) AS DayNo,
			
			CASE  WHEN SR.IsPresent = 1 AND SR.AttendanceTagId = 1 THEN 'LA' 
				  WHEN SR.IsPresent = 1 AND SR.AttendanceTagId = 2 THEN 'ED' 
			      WHEN SR.IsPresent = 1  THEN 'P' 
				  WHEN SR.IsPresent = 0 THEN 'A'
				  ELSE  '' END AS  Presence,
			--(CASE SR.IsPresent WHEN 1 THEN 'P' 
			--	WHEN 0 THEN 'A'
			--	END )AS  Presence,
			OM.WeekOffs,
			sAttendance.fHolidayForMonthGet(@rForMonth,@rForYear,@rBatchId,SA.DivisionId)  As Holidays
			
			--DAY(SR.AttendanceDate) AS DayNo,
			--(CASE SR.IsPresent WHEN 1 THEN 'P' 
			--	WHEN 0 THEN 'A'
			--	END )AS  Presence,
			--OM.WeekOffs
			
		
	From  
			sStudent.vStudentAcademic SA
            INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.AcademicId
            INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
	
	WHERE
			SR.AttendanceTypeId=@rAttendanceTypeId
		AND SR.AcademicId=@rAcademicId
		AND YEAR(SR.AttendanceDate)=@rForYear
		AND MONTH(SR.AttendanceDate)=@rForMonth
		AND SA.BatchId=@rBatchId
		
		ORDER BY DayNo ASC
	
END
GO
PRINT N'Altering [sCertificate].[pRptBonafiedCertificateGet]...';


GO


ALTER PROCEDURE [sCertificate].[pRptBonafiedCertificateGet]
	 
	 @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 @lIsShowPhoto bit = 0
DECLARE @lIsOnPrePrinted bit = 0
DECLARE @lIsDisplayReligion bit=0
DECLARE @lIsDisplayImageHeader bit=0

DECLARE @lConfigValue nvarchar(50)

	 SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 124 AND SourceTypeId = 1016 AND SourceId = @rOrgId
	
	if (@lConfigValue IS NULL) OR (@lConfigValue = 'False')
	SET @lIsShowPhoto = 0
	ELSE
	SET @lIsShowPhoto = 1
	
	SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 177 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,
			B.Id,
			B.Number,
			B.AcademicId,
			SM.Code,
			SM.FirstName+' '+SM.MiddleName+' '+SM.LastName AS Name,
			CM.DisplayTitle+' - '+DM.DisplayTitle AS Class,
			BM.Title AS Batch,
			SO.DateOfBirth,
			ISNULL(SO.BirthDateInWord,'') AS DOBInWords,
			ISNULL(SO.BirthPlace,'') AS BirthPlace,
			ISNULL(SO.BirthTaluka,'') AS Taluka,
			ISNULL(SO.BirthDistrict,'')	AS District,		
			B.BonafideDate,
			ISNULL(SO.FamilyCast,'') AS Caste,
			ISNULL(SO.FamilySubCast,'') AS SubCaste,
			ISNULL(OM.CityName,'') AS City,
			ISNULL(OM.StateName,'') AS CityState,
			SO.GenderId,
			SI.StudentPhoto,
			OM.OrgLogo,
			OM.Title AS OrgTitle,
			--OM.StreetOne+' '+OM.StreetTwo+' '+OM.StreetThree AS OrgAddress,
			--OM.PhoneNo,
			SM.StatusId,
			A.RollNo,
			DM.OrderIndex AS DivisionOrder,
			ATM.Title AS AffiliationType,
			OM.ReportOrgTitle,
			OM.SmallAddress1,
			OM.SmallAddress2,
			OM.RegistrationDetail,
			ISNULL(RM.Title,'') AS ReligionName,
			@lIsShowPhoto AS IsShowPhoto,
			@lIsOnPrePrinted AS IsOnPrePrinted,
			@lIsDisplayReligion AS IsDisplayReligion,
			B.Remark AS ReceiptNo,
			SF.FatherName,
			SA.AdmissionDate,
			DP.Title AS DepartmentName,
			ISNULL(OM.DegreeAwarded,'') AS DegreeAwarded,
			@lIsDisplayImageHeader AS IsDisplayImageHeader,
			OI.CertificateHeaderA4,
			REPLICATE(',',OM.LetterHeadMargin)    AS LetterHeadMargin,
			ISNULL(B.BonafiedReason,'') AS BonafiedReason,
			CT.Title AS Category
	
	FROM 
			sCertificate.tBonafide B
			INNER JOIN sStudent.tAcademic A ON B.AcademicId=A.Id
			LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=A.StudentId
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId
			LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
			INNER JOIN sSetup.tDivisionMaster DM ON A.DivisionId = DM.Id  
			INNER JOIN sSetup.tClassMaster CM ON CM.Id= DM.ClassId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id=A.BatchId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId
			left JOIN sSetup.tOrgImages OI ON OI.OrgId = OM.Id
			INNER JOIN sSetup.tAffiliationMaster AM ON OM.AffiliationId = AM.Id
			INNER JOIN sSetup.tAffiliationTypeMaster ATM ON AM.AffiliationTypeId = ATM.Id
			LEFT JOIN sCommon.tReligionMaster RM ON SO.ReligionId=RM.Id
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SM.Id
			INNER JOIN sStudent.tStudentAdmission SA ON SA.StudentId = SM.Id
			INNER JOIN sSetup.tDepartmentMaster DP ON CM.DepartmentId = DP.Id
			LEFT JOIN sCommon.tCastCategoryMaster CT ON CT.Id = SO.CastCategoryId
			
			--INNER JOIN sSetup.tTermMaster TM ON  TM.ID=
	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 ((B.BonafideDate=@rBonafiedDate) OR (ISNULL(@rBonafiedDate,'')=''))
		AND ((B.Number=@rNumber) OR (@rNumber=''))
		AND ((B.Number >= @rFromNo) OR (@rFromNo=''))
		AND ((B.Number <= @rToNo) OR (@rToNo=''))
		AND ((B.BonafideDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((B.BonafideDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		--Group By B.AcademicId,SM.Code,SM.FirstName,SM.LastName,SM.MiddleName,CM.DisplayTitle,BM.Title,SO.DateOfBirth,SO.BirthDateInWord,
		--SO.BirthPlace,SO.BirthTaluka,SO.BirthDistrict,B.BonafideDate,OM.CityName,OM.StateName,SO.FamilyCast,SO.FamilySubCast,SO.GenderId,SI.StudentPhoto,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)

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 AS Name,
			ISNULL(SF.FatherName,'') As FatherName,
			ISNULL(SF.MotherName,'') As MotherName,
			ISNULL(CTM.Title,'') 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,
			'' AS CurrentStandardInWords,
			SM.StatusId,
			'' AS Result,
			'' AS FailOrPass,
			'' AS SubjectNAme,
			--ISNULL(SubM.Title,'') AS SubjectNAme,
			'' AS PromotedorNot,
			'' AS PromotedToClass,
			'' AS LastFeesPaid,
			'' AS AnyConcession,
			'' AS NCCScoutDetail,
			'' 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 
			--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 
			INNER 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
			
			
	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].[pMaxCodeWithPrefixGet]...';


GO
ALTER PROCEDURE [sCommon].[pMaxCodeWithPrefixGet]
	 
	 @rPrefixFunctionalityId smallint,
	 @rOrgId smallint,
	 @rDepartmentId int,
	 @rEmployeeTypeId int=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 
BEGIN TRY
	
	DECLARE @lSourceTypeId int
	DECLARE @lOutCode nvarchar(20)
	DECLARE @lPrefix nvarchar(10)
	DECLARE @lNumberLength tinyint
	
	IF @rPrefixFunctionalityId=2007 -- Student
	BEGIN
		SELECT @lSourceTypeId=SourceTypeId FROM sCommon.tPrefixConfig WHERE PrefixFunctionalityId = @rPrefixFunctionalityId AND OrgId =@rOrgId
			IF @lSourceTypeId IS NOT NULL
			BEGIN
				IF @lSourceTypeId = 2021 -- Organization
				BEGIN
					SELECT @lPrefix=Prefix,@lNumberLength=NumberLength FROM sCommon.tPrefixConfig WHERE PrefixFunctionalityId = @rPrefixFunctionalityId AND SourceId = @rOrgId
					SELECT @lOutCode=MAX(Code) FROM sStudent.tStudentMaster WHERE OrgId = @rOrgId
				END
				IF @lSourceTypeId = 2017 -- Department
				BEGIN
					SELECT @lPrefix=Prefix,@lNumberLength=NumberLength FROM sCommon.tPrefixConfig WHERE PrefixFunctionalityId = @rPrefixFunctionalityId AND SourceId = @rDepartmentId
					SELECT @lOutCode=MAX(SM.Code) FROM sStudent.tStudentMaster SM INNER JOIN sStudent.tAcademic A ON A.StudentId = SM.Id
					INNER JOIN sSetup.tClassMaster CM ON CM.Id = A.ClassId WHERE SM.OrgId = @rOrgId AND CM.DepartmentId = @rDepartmentId
				END
				
				IF CHARINDEX(@lPrefix,@lOutCode) > 0
				BEGIN
					SELECT @lOutCode = RIGHT(@lOutCode, LEN(@lOutCode)-LEN(@lPrefix))
					SELECT @lOutCode = (CONVERT(bigint, @lOutCode)+1)
					SELECT @lOutCode = RIGHT(REPLICATE('0', @lNumberLength), @lNumberLength-LEN(@lPrefix)-LEN(@lOutCode))+@lOutCode
					SELECT @lOutCode = @lPrefix + @lOutCode
				END
				ELSE
				BEGIN
					SELECT @lOutCode = 1
					IF @lNumberLength != 0
					BEGIN
						SELECT @lOutCode = RIGHT(REPLICATE('0', @lNumberLength), @lNumberLength-LEN(@lPrefix)-LEN(@lOutCode))+@lOutCode
					END
					SELECT @lOutCode = @lPrefix + @lOutCode
				END
			END
	END
	IF @rPrefixFunctionalityId=2008 -- Employee
	BEGIN
		SELECT @lSourceTypeId=SourceTypeId FROM sCommon.tPrefixConfig WHERE PrefixFunctionalityId = @rPrefixFunctionalityId AND OrgId =@rOrgId
			IF @lSourceTypeId IS NOT NULL
			BEGIN
				IF @lSourceTypeId = 2021 -- Organization
				BEGIN
					SELECT @lPrefix=Prefix,@lNumberLength=NumberLength FROM sCommon.tPrefixConfig WHERE PrefixFunctionalityId = @rPrefixFunctionalityId AND SourceId = @rOrgId
					SELECT @lOutCode=MAX(Code) FROM sHrm.tEmployeeMaster WHERE OrgId = @rOrgId
				END
				
				IF @lSourceTypeId = 2017 -- Department
				BEGIN
					SELECT @lPrefix=Prefix,@lNumberLength=NumberLength FROM sCommon.tPrefixConfig WHERE PrefixFunctionalityId = @rPrefixFunctionalityId AND SourceId = @rDepartmentId
					SELECT @lOutCode=MAX(EM.Code) FROM sHrm.tEmployeeMaster EM INNER JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id = EJD.EmployeeId
					WHERE EM.OrgId = @rOrgId AND EJD.OrganizationDepartmentId = @rDepartmentId
				END
				
				IF CHARINDEX(@lPrefix,@lOutCode) > 0
				BEGIN
					SELECT @lOutCode = RIGHT(@lOutCode, LEN(@lOutCode)-LEN(@lPrefix))
					SELECT @lOutCode = (CONVERT(bigint, @lOutCode)+1)
					SELECT @lOutCode = RIGHT(REPLICATE('0', @lNumberLength), @lNumberLength-LEN(@lPrefix)-LEN(@lOutCode))+@lOutCode
					SELECT @lOutCode = @lPrefix + @lOutCode
				END
				ELSE
				BEGIN
					SELECT @lOutCode = 1
					IF @lNumberLength != 0
					BEGIN
						SELECT @lOutCode = RIGHT(REPLICATE('0', @lNumberLength), @lNumberLength-LEN(@lPrefix)-LEN(@lOutCode))+@lOutCode
					END
					SELECT @lOutCode = @lPrefix + @lOutCode
				END
			END
	END
	
	IF @rPrefixFunctionalityId=2009 -- Organization
	BEGIN
		SELECT @lSourceTypeId=SourceTypeId FROM sCommon.tPrefixConfig WHERE PrefixFunctionalityId = @rPrefixFunctionalityId AND SourceId =@rOrgId
			IF @lSourceTypeId IS NOT NULL
			BEGIN
				IF @lSourceTypeId = 2021 -- Organization
				BEGIN
					SELECT @lPrefix=Prefix,@lNumberLength=NumberLength FROM sCommon.tPrefixConfig WHERE PrefixFunctionalityId = @rPrefixFunctionalityId AND SourceId = @rOrgId
					SELECT @lOutCode=MAX(SUId) FROM sStudent.tStudentMaster WHERE OrgId = @rOrgId
				END
				
				IF CHARINDEX(@lPrefix,@lOutCode) > 0
				BEGIN
					SELECT @lOutCode = RIGHT(@lOutCode, LEN(@lOutCode)-LEN(@lPrefix))
					SELECT @lOutCode = (CONVERT(bigint, @lOutCode)+1)
					SELECT @lOutCode = RIGHT(REPLICATE('0', @lNumberLength), @lNumberLength-LEN(@lPrefix)-LEN(@lOutCode))+@lOutCode
					SELECT @lOutCode = @lPrefix + @lOutCode
				END
				ELSE
				BEGIN
					SELECT @lOutCode = 1
					IF @lNumberLength != 0
					BEGIN
						SELECT @lOutCode = RIGHT(REPLICATE('0', @lNumberLength), @lNumberLength-LEN(@lPrefix)-LEN(@lOutCode))+@lOutCode
					END
					SELECT @lOutCode = @lPrefix + @lOutCode
				END
			END
	END
	END TRY
	BEGIN CATCH
	SET @lOutCode = ''
	END CATCH
	SELECT @lOutCode Result
END
GO
PRINT N'Altering [sCommon].[pOrganizationSetupRemove]...';


GO


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

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


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

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

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

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

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

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

DELETE FROM sTimetable.tAssignOrg WHERE OrgId = @rOrgId

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

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

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

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

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

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


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

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

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

	SELECT 1 AS Result
 
 COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
		
	END CATCH
END
GO
PRINT N'Altering [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.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

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

	-- 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



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


GO
ALTER PROCEDURE [sCommunication].[pCircularListGet]
	 
	 @rOrgGroupBatchId int,
	 @rUserId bigint,
	 @rUserSourceId bigint,
	 @rUserSourceTypeId int,
	 @rSyncedCircularId bigint = 0
	 	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

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

	
	if @rUserSourceTypeId   = 95 -- For Employee Login
	
	BEGIN
	
		--DECLARE @lDepartmentId int,@lOrgId int,@lDepartmentId int
		
		SELECT @lDepartmentId=EJD.OrganizationDepartmentId,@lOrgId = EM.OrgId,@lEmployeeId = EM.Id FROM sHrm.tEmployeeMaster EM INNER JOIN sHrm.tEmployeeJobDetail EJD
			 ON EJD.EmployeeId = EM.Id WHERE EM.Id=@rUserSourceId
		
	SELECT 	
			C.Id as CircularId,
			C.Title,
			C.Remark,
			C.StartDate,
			ISNULL(CV.UserId,0) AS UserId,
			U.DisplayTitle as CreatedUserName,
			CTM.HighlightColor,
			CTM.Title AS CircularTypeTitle,
			C.OrgGroupId
			  
	 FROM 
            sCommunication.tCircular C 
            INNER JOIN sCommunication.tCircularTypeMaster CTM
				ON CTM.Id=C.CircularTypeId
            LEFT JOIN sCommunication.tCircularView CV ON CV.CircularId=C.Id AND UserId=@rUserId           
            INNER JOIN (SELECT CS.CircularId FROM sCommunication.tCircularScope CS
             WHERE ((CS.SourceTypeId = 2021 AND CS.SourceId =@lOrgId) OR
            (CS.SourceTypeId = 2017 AND CS.SourceId =@lDepartmentId) OR
            (CS.SourceTypeId = 95 AND CS.SourceId =@lEmployeeId))
              AND (CS.CircularId > @rSyncedCircularId OR @rSyncedCircularId = 0)) D
				ON D.CircularId= C.Id
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=C.OrgGroupBatchId AND OGBM.Id=@rOrgGroupBatchId
            INNER JOIN sSecurity.tUser U ON U.Id=C.CreatedUserId
            WHERE ( c.Id > @rSyncedCircularId OR @rSyncedCircularId = 0)
            AND C.AssigneeId IN (1,3) 
           	ORDER BY C.StartDate DESC
			
	
 END
 ELSE IF @rUserSourceTypeId   = 2003 -- For Student Login
 BEGIN
 
 
 SELECT @lAcademicId = A.Id,@lStudentId = A.StudentId,@lClassId = A.ClassId, @lDivisionId = A.DivisionId, @lOrgId= A.OrgId, @lDepartmentId=CM.DepartmentId
  FROM sStudent.tAcademic A INNER JOIN sSetup.tBatchMaster BM
	ON A.BatchId = BM.Id AND BM.IsActive = 1 
	INNER JOIN sSetup.tClassMaster CM ON CM.Id = A.ClassId
 WHERE StudentId = @rUserSourceId AND BM.OrgGroupBatchId = @rOrgGroupBatchId
  
 	SELECT 	
			C.Id as CircularId,
			C.Title,
			C.Remark,
			C.StartDate,
			ISNULL(CV.UserId,0) AS UserId,
			U.DisplayTitle as CreatedUserName,
			CTM.HighlightColor,
			CTM.Title AS CircularTypeTitle,
			C.OrgGroupId
	 FROM 
            sCommunication.tCircular C 
            INNER JOIN sCommunication.tCircularTypeMaster CTM
				ON CTM.Id=C.CircularTypeId      
            LEFT JOIN sCommunication.tCircularView CV ON CV.CircularId=C.Id AND UserId=@rUserId
            INNER JOIN (SELECT CS.CircularId FROM sCommunication.tCircularScope CS
            WHERE ((CS.SourceTypeId = 2021 AND CS.SourceId =@lOrgId) OR
            (CS.SourceTypeId = 2017 AND CS.SourceId =@lDepartmentId) OR
            (CS.SourceTypeId = 2016 AND CS.SourceId =@lClassId) OR
            (CS.SourceTypeId = 2005 AND CS.SourceId =@lDivisionId) OR
            (CS.SourceTypeId = 2003 AND CS.SourceId =@lStudentId) OR
            (CS.SourceTypeId = 2001 AND CS.SourceId =@lAcademicId) )
            AND (CS.CircularId > @rSyncedCircularId OR @rSyncedCircularId = 0)) D
				ON D.CircularId= C.Id
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=C.OrgGroupBatchId AND OGBM.Id=@rOrgGroupBatchId
            INNER JOIN sSecurity.tUser U ON U.Id=C.CreatedUserId
            WHERE ( c.Id > @rSyncedCircularId OR @rSyncedCircularId = 0)
            AND C.AssigneeId IN (1,2) 
            ORDER BY C.StartDate DESC

 END
 ELSE
  --For Other Users
 BEGIN
 
 SELECT 	
			C.Id as CircularId,
			C.Title,
			C.Remark,
			C.StartDate,
			ISNULL(CV.UserId,0) AS UserId,
			U.DisplayTitle as CreatedUserName,
			CTM.HighlightColor,
			CTM.Title AS CircularTypeTitle,
			C.OrgGroupId
	 FROM 
            sCommunication.tCircular C     
            INNER JOIN sCommunication.tCircularTypeMaster CTM
				ON CTM.Id=C.CircularTypeId  
            LEFT JOIN sCommunication.tCircularView CV ON CV.CircularId=C.Id AND UserId=@rUserId     
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=C.OrgGroupBatchId AND OGBM.Id=@rOrgGroupBatchId
            INNER JOIN sSecurity.tUser U ON U.Id=C.CreatedUserId
            WHERE ( C.Id > @rSyncedCircularId OR @rSyncedCircularId = 0)
             AND C.AssigneeId IN (1,2,3) 
            ORDER BY C.StartDate DESC

 
 	--SELECT 	
		--	C.Id as CircularId,
		--	C.Title,
		--	C.Remark,
		--	C.StartDate,
		--	CV.UserId,
		--	U.DisplayTitle as CreatedUserName	    
	 --FROM 
  --          sCommunication.tCircular C       
  --          LEFT JOIN sCommunication.tCircularView CV ON CV.CircularId=C.Id AND UserId=@rUserId     
  --          INNER JOIN sCommunication.tCircularScope CS ON CS.CircularId=C.Id 
  --          INNER JOIN ( SELECT A.DivisionId FROM sStudent.tAcademic A            
  --           WHERE A.StudentId = @rUserSourceId ) D
  --          ON D.DivisionId =  CS.SourceId AND CS.SourceTypeId = 2005
  --          INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=C.OrgGroupBatchId AND OGBM.Id=@rOrgGroupBatchId
  --          INNER JOIN sSecurity.tUser U ON U.Id=C.CreatedUserId
  --          WHERE ( C.Id > @rSyncedCircularId OR @rSyncedCircularId = 0)
  --          Order by C.CreatedDateTime DESC


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


GO


ALTER PROCEDURE [sCommunication].[pMyResultViewDetailGet]
	 
	@rStudentId bigint =0,
	@rAcademicId bigint = 0,
	@rBatchId int = 0,
	@rResultId bigint=0,
	@rExamId int=0,
	@rExamTypeId tinyint = 0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
SELECT
		VR.ResultId, 
		VR.ExamId,
		0 AS ReportId,
		VR.ExamName AS ExamName,
		StuM.FirstName+' '+StuM.LastName AS StudentName,
		StuM.Id AS StudentId,
		A.RollNo,
		DM.DisplayTitle AS Division,
		VR.TotalMarks,
		VR.TotalObtain,
		ISNULL(VR.ResultStatus,'') AS ResultStatus,
		VR.ResultGrade,
		VR.RankNumber,
		VR.Percentage,
		VR.Percentile,	
		0 AS ExamSubGroupId,
		BM.Id AS BatchId,
		BM.Title AS BatchName,
		VRD.Maximum,
		VRD.Minimum,
		VRD.Obtain,
		VRD.SubjectCode AS SubjectCode, 
		VRD.SubjectName AS SubjectName, 
		CASE WHEN (ISNULL(VRD.SubjectGrade,'') = '') THEN '-' ELSE VRD.SubjectGrade END AS SubjectGrade,
		--ISNULL(VRD.SubjectGrade,'-') AS SubjectGrade,
		VRD.ExamTypeId
FROM 
		sCommunication.tViewResult VR 
		INNER JOIN sCommunication.tViewResultDetail VRD ON VRD.ResultId=VR.ResultId 
		AND VR.ExamId = VRD.ExamId AND VR.ExamTypeId=VRD.ExamTypeId AND VR.ResultId = VRD.ResultId
		INNER JOIN sStudent.tAcademic A ON A.Id=VR.AcademicId
		INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
		INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
	WHERE 	
		((StuM.Id = @rStudentId) or(@rStudentId=0))
		AND ((A.Id = @rAcademicId) OR (@rAcademicId =0))
		AND ((BM.Id = @rBatchId) OR (@rBatchId =0))
		AND ((VR.ResultId=@rResultId)OR(@rResultId=0))
		AND ((VR.ExamId=@rExamId)OR(@rExamId=0))
		AND ((VRD.ExamTypeId=@rExamTypeId)OR(@rExamTypeId=0))
	    ORDER BY VRD.SubjectOrder DESC
END
GO
PRINT N'Altering [sCommunication].[pPollGet]...';


GO

ALTER PROCEDURE [sCommunication].[pPollGet]
	 @rId bigint = 0,
	 @rOrgGroupBatchId int,
	 @rCreatedUserId bigint,
	 @rSourceTypeId smallint
	 
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
If(@rSourceTypeId = 95)
BEGIN	 
	SELECT 
	
			P.Id as PollId,
			P.Title AS PollTitle,
			P.Remark AS PollRemark,
			P.IsOwnAnswer,
			P.IsOpen,
			P.CreatedDateTime AS PollCreatedDateTime,
			ISNULL(PR.CreatedUserId,0) AS PollResultUserId,
			(SELECT  ISNULL(Count(1),0) FROM sCommunication.tPollResult PR WHERE PR.PollId=P.Id) AS TotalPollVote
  FROM 
            sCommunication.tPoll P
         INNER JOIN sCommunication.tPollMember PM ON PM.PollId=P.Id AND PM.SourceTypeId=2017 
         INNER JOIN sSetup.tDepartmentMaster ODM ON ODM.Id=PM.SourceId
         INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.OrganizationDepartmentId=ODM.Id
         INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id=EJD.EmployeeId
         INNER JOIN sSecurity.tUser U ON U.SourceId=EM.Id AND U.SourceTypeId=@rSourceTypeId AND U.Id=@rCreatedUserId
         LEFT JOIN sCommunication.tPollResult PR ON P.Id = PR.PollId AND  PR.CreatedUSerId = @rCreatedUserId
  WHERE 
  
      ((P.Id = @rId) OR (@rId = 0))
	AND ((P.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	
	
	--UNION
	
	--SELECT 
	
	--		P.Id as PollId,
	--		P.Title AS PollTitle,
	--		P.Remark AS PollRemark,
	--		P.IsOwnAnswer,
	--		P.IsOpen,
	--		P.CreatedDateTime AS PollCreatedDateTime,
	--		ISNULL(PR.CreatedUserId,0) AS PollResultUserId,
	--		(SELECT  ISNULL(Count(1),0) FROM sCommunication.tPollResult PR WHERE PR.PollId=P.Id) AS TotalPollVote
 -- FROM 
 --           sCommunication.tPoll P
 --           LEFT JOIN sCommunication.tPollResult PR ON P.Id = PR.PollId AND  PR.CreatedUSerId = @rCreatedUserId
 -- WHERE 
  
 --     ((P.Id = @rId) OR (@rId = 0))
 --   AND ((P.CreatedUserId = @rCreatedUserId) OR (@rCreatedUserId = 0))
	--AND ((P.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	
	
END
ELSE IF(@rSourceTypeId = 2003)
BEGIN
	SELECT 
	
			P.Id as PollId,
			P.Title AS PollTitle,
			P.Remark AS PollRemark,
			P.IsOwnAnswer,
			P.IsOpen,
			P.CreatedDateTime AS PollCreatedDateTime,
			ISNULL(PR.CreatedUserId,0) AS PollResultUserId,
			(SELECT  ISNULL(Count(1),0) FROM sCommunication.tPollResult PR WHERE PR.PollId=P.Id) AS TotalPollVote
		
  FROM 
            sCommunication.tPoll P
         INNER JOIN sCommunication.tPollMember PM ON PM.PollId=P.Id AND PM.SourceTypeId=2005
         INNER JOIN sStudent.vStudentAcademic SA ON SA.DivisionId=PM.SourceId AND SA.IsActiveBatch = 1
         INNER JOIN sSecurity.tUser U ON U.SourceId=SA.StudentId AND U.SourceTypeId=@rSourceTypeId AND U.Id=@rCreatedUserId
         LEFT JOIN sCommunication.tPollResult PR ON P.Id = PR.PollId AND  PR.CreatedUSerId = @rCreatedUserId
         
  WHERE 
  
      ((P.Id = @rId) OR (@rId = 0))
	AND ((P.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	
	
	--UNION
	
	--SELECT 
	
	--		P.Id as PollId,
	--		P.Title AS PollTitle,
	--		P.Remark AS PollRemark,
	--		P.IsOwnAnswer,
	--		P.IsOpen,
	--		P.CreatedDateTime AS PollCreatedDateTime,
	--		ISNULL(PR.CreatedUserId,0) AS PollResultUserId,
	--		(SELECT  ISNULL(Count(1),0) FROM sCommunication.tPollResult PR WHERE PR.PollId=P.Id) AS TotalPollVote
 -- FROM 
 --           sCommunication.tPoll P
 --            LEFT JOIN sCommunication.tPollResult PR ON P.Id = PR.PollId AND  PR.CreatedUSerId = @rCreatedUserId
 -- WHERE 
  
 --     ((P.Id = @rId) OR (@rId = 0))
 --    AND ((P.CreatedUserId = @rCreatedUserId) OR (@rCreatedUserId = 0))
	--AND ((P.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	
	
END

ELSE 

BEGIN
	--SELECT 
	
	--		P.Id as PollId,
	--		P.Title AS PollTitle,
	--		P.Remark AS PollRemark,
	--		P.IsOwnAnswer,
	--		P.IsOpen,
	--		P.CreatedDateTime AS PollCreatedDateTime,
	--		ISNULL(PR.CreatedUserId,0) AS PollResultUserId,
	--		(SELECT  ISNULL(Count(1),0) FROM sCommunication.tPollResult PR WHERE PR.PollId=P.Id) AS TotalPollVote
			
 -- FROM 
 --           sCommunication.tPoll P
 --        INNER JOIN sCommunication.tPollMember PM ON PM.PollId=P.Id AND PM.SourceTypeId=2005
 --        INNER JOIN sStudent.vStudentAcademic SA ON SA.DivisionId=PM.SourceId
 --        INNER JOIN sSecurity.tUser U ON U.SourceId=SA.StudentId AND U.SourceTypeId=@rSourceTypeId AND U.Id=@rCreatedUserId
 --         LEFT JOIN sCommunication.tPollResult PR ON P.Id = PR.PollId AND  PR.CreatedUSerId = @rCreatedUserId
 -- WHERE 
  
 --     ((P.Id = @rId) OR (@rId = 0))
	--AND ((P.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	
	
	--UNION
	
	SELECT 
	
			P.Id as PollId,
			P.Title AS PollTitle,
			P.Remark AS PollRemark,
			P.IsOwnAnswer,
			P.IsOpen,
			P.CreatedDateTime AS PollCreatedDateTime,
			ISNULL(PR.CreatedUserId,0) AS PollResultUserId,
			(SELECT  ISNULL(Count(1),0) FROM sCommunication.tPollResult PR WHERE PR.PollId=P.Id) AS TotalPollVote
  FROM 
            sCommunication.tPoll P
            LEFT JOIN sCommunication.tPollResult PR ON P.Id = PR.PollId AND  PR.CreatedUSerId = @rCreatedUserId
  WHERE 
  
      ((P.Id = @rId) OR (@rId = 0))
    AND ((P.CreatedUserId = @rCreatedUserId) OR (@rCreatedUserId = 0))
	AND ((P.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	
	
END


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


GO
ALTER PROCEDURE [sCommunication].[pPollMemberGet]
	 
	 @rPollId bigint,
	 @rOrgId smallint,
	 @rOrgGroupId smallint
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 		
		
	SELECT 
			DM.Id  as SourceId,
			CM.Title+'-'+DM.Title as ClassDept,
			2005 as SourceTypeId,
			CASE WHEN PM.SourceId IS NULL OR PM.PollId!=@rPollId THEN 0 ELSE 1 END AS IsObsolete,
			OM.DisplayTitle AS Organization,
			CM.OrderIndex+DM.OrderIndex AS OrderIndex
  FROM 
			sSetup.tDivisionMaster DM
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=DM.ClassId
			LEFT JOIN sCommunication.tPollMember PM ON PM.SourceId=DM.Id AND PM.SourceTypeId=2005 AND PM.PollId=@rPollId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=DM.OrgId AND OM.OrgGroupId=@rOrgGroupId
	 WHERE
		((DM.OrgId=@rOrgId) OR (@rOrgId=0))
		UNION
	SELECT 
			ODM.Id  as SourceId,
			ODM.Title as ClassDept,
			2004 as SourceTypeId,
			CASE WHEN PM.SourceId IS NULL OR PM.PollId!=@rPollId THEN 0 ELSE 1 END AS IsObsolete,
			OM.DisplayTitle AS Organization,
			0 AS OrderIndex
  FROM 
			sSetup.tDepartmentMaster ODM
			LEFT JOIN sCommunication.tPollMember PM ON PM.SourceId=ODM.Id AND PM.SourceTypeId=2017 AND PM.PollId=@rPollId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=ODM.OrgId AND OM.OrgGroupId=@rOrgGroupId
	WHERE
		((ODM.OrgId=@rOrgId) OR (@rOrgId=0))
END
GO
PRINT N'Altering [sCommunication].[pPollResultAdd]...';


GO

ALTER PROCEDURE [sCommunication].[pPollResultAdd]
	 
        @rPollAnswerId bigint,
        @rPollId bigint,
		@rRemark nvarchar(500),
		@rCreatedUserId bigint,
		@rOrgGroupId smallint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	--Edited by Parth -13/07/2016
	----START----
	IF EXISTS(SELECT 1 FROM sCommunication.tPollResult WHERE PollId=@rPollId AND CreatedUserId=@rCreatedUserId)
	BEGIN
		SELECT Id as Result FROM sCommunication.tPollResult WHERE PollId=@rPollId AND CreatedUserId=@rCreatedUserId 
		RETURN
	END
	----END----
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sCommunication.tPollResult', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sCommunication.tPollResult
		(
			Id,
			PollId,
			PollAnswerId,
			Remark,
			CreatedUserId,
			CreatedDateTime
		)
	VALUES
		(
			@lNextNumber,
			@rPollId,
			@rPollAnswerId,
			@rRemark,
			@rCreatedUserId,
			sCommon.fGetDate()
		)
		    SELECT @lNextNumber AS Result
	
	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sCommunication].[pQueryAdd]...';


GO

ALTER PROCEDURE [sCommunication].[pQueryAdd]
	 
	@rOrgGroupId smallint,
	@rOrgGroupBatchId int,
	@rQueryCategoryId int,
	@rId AS bigint,
	@rTitle nvarchar(100),
	@rRemark nvarchar(200),
	@rIsUserView bit,
	@rIsAssigneeView bit,
	@rStatusId tinyint,
	@rCreatedUserId bigint,
	@rCreatedDateTime datetime
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	BEGIN TRANSACTION
		IF(@rId = 0)
BEGIN
DECLARE @lNextNumber BIGINT     
	
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sCommunication.tQuery', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sCommunication.tQuery
		(
			OrgGroupId,
			OrgGroupBatchId,
			QueryCategoryId,
			Id,
			Title,
			Remark,
			IsUserView,
			IsAssigneeView,
			StatusId,
			CreatedUserId,
			CreatedDateTime
		)
	VALUES
		(
			@rOrgGroupId,
			@rOrgGroupBatchId,
			@rQueryCategoryId,
			@lNextNumber,
			@rTitle,
			@rRemark,
			@rIsUserView,
			@rIsAssigneeView,
			@rStatusId,
			@rCreatedUserId,
			sCommon.fGetDate()
		)
		select 1 as result
END
ELSE
BEGIN
		UPDATE sCommunication.tQuery 
		SET IsUserView = @rIsUserView,
		IsAssigneeView=@rIsAssigneeView
		
		 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 [sCommunication].[pRegisteredUsersGet]...';


GO
 

ALTER PROCEDURE [sCommunication].[pRegisteredUsersGet]

		@rSourceTypeId smallint = 0,
		@rSourceId bigint = 0,
		@rOSTypeId tinyint = 0,
		@rUserSourceTypeId smallint = 0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	
	SELECT 
			ISNULL(DeviceToken,'') AS DeviceToken
	FROM 
		sCommunication.tRegisteredUsers RU 
		INNER JOIN sStudent.vStudentAcademic SA ON RU.UserSourceId = SA.StudentId AND RU.UserSourceTypeId=2003 AND IsActiveBatch=1
	WHERE 
		(
		(SA.AcademicId=@rSourceId) AND (@rSourceTypeId=2001)
		OR (SA.StudentId=@rSourceId) AND (@rSourceTypeId=2003)
		OR (SA.DivisionId=@rSourceId) AND (@rSourceTypeId=2005)
		OR (SA.ClassId=@rSourceId) AND (@rSourceTypeId=2016)
		OR (SA.DepartmentId=@rSourceId) AND (@rSourceTypeId=2017)
		OR (SA.OrgId=@rSourceId) AND (@rSourceTypeId=2021)	
		) AND RU.OSTypeId=@rOSTypeId AND RU.DeviceToken	IS NOT NULL AND RU.DeviceToken != '' 	
		AND ((RU.UserSourceTypeId=@rUserSourceTypeId) OR (@rUserSourceTypeId=0))
		
	UNION ALL		
		
	SELECT 
			ISNULL(DeviceToken,'') AS DeviceToken
	FROM 
		sCommunication.tRegisteredUsers RU
		INNER JOIN sHrm.tEmployeeJobDetail EJD ON RU.UserSourceId = EJD.EmployeeId AND RU.UserSourceTypeId=95
	WHERE 
		(
		(EJD.EmployeeId=@rSourceId) AND (@rSourceTypeId=95)
		OR (EJD.OrganizationDepartmentId=@rSourceId) AND (@rSourceTypeId=2017)
		OR (EJD.OrgId=@rSourceId) AND (@rSourceTypeId=2021)	
		) AND RU.OSTypeId=@rOSTypeId AND RU.DeviceToken	IS NOT NULL AND RU.DeviceToken != '' 
		AND ((RU.UserSourceTypeId=@rUserSourceTypeId) OR (@rUserSourceTypeId=0))		
END
GO
PRINT N'Altering [sCommunication].[pUploadResultAdd]...';


GO

ALTER PROCEDURE [sCommunication].[pUploadResultAdd]
	 
        @rId int,
        @rTitle nvarchar(100),
        @rExamDate date,
		@rDivisionId int,
		@rIsObsolete bit,
		@rBatchId int,
		@rOrgId int,
		@rCreatedUserId bigint,
		@rExamId int=null
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	IF(@rId = 0)	
	BEGIN
		If Exists(select Id from sCommunication.tUploadResult where Title=@rTitle AND DivisionId=@rDivisionId
		 AND BatchId=@rBatchId)
			BEGIN
			select -103 as Result
			RETURN
		END 
	END
	ELSE
	BEGIN
		If  Exists(select Id from sCommunication.tUploadResult where Title=@rTitle AND DivisionId=@rDivisionId 
		AND BatchId=@rBatchId AND Id<>@rId)
		Begin
			select -103 as Result
			RETURN
		End
	END
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sCommunication.tUploadResult', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sCommunication.tUploadResult
		(
			Id,
			Title,
			ExamDate,
			DivisionId,
			IsObsolete,
			BatchId,
			CreatedUserId,
			CreatedDateTime,
			ExamId
		)
	VALUES
		(
			@lNextNumber,
			@rTitle,
			@rExamDate,
			@rDivisionId,
			@rIsObsolete, 
			@rBatchId,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rExamId 
		)
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE sCommunication.tUploadResult
	    SET
			Title=@rTitle,
			ExamDate=@rExamDate,
			DivisionId=@rDivisionId,
			IsObsolete=@rIsObsolete,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate(),
			ExamId= @rExamId
	      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 [sFee].[pApplyExemptionType]...';


GO

ALTER PROCEDURE [sFee].[pApplyExemptionType]
	
	@rOrgId int,
	@rBatchId int,
	@rOrgGroupBatchId int,
	@rCreatedUserId bigint,
	@rExemptionTypeId int,
	@rAcademicId bigint
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
		
	DECLARE @lClassId int
	DECLARE @lDivisionId int
	DECLARE @lAdmissionCategoryId int
	DECLARE @lExemptionTypeId int
	DECLARE @lCalculationTypeId tinyint
	
	SELECT @lClassId=ClassId,@lDivisionId=DivisionId,@lAdmissionCategoryId=AdmissionCategoryId,@lExemptionTypeId=ExemptionTypeId 
	FROM sStudent.vStudentAcademic 
	WHERE AcademicId = @rAcademicId AND BatchId=@rBatchId AND OrgId = @rOrgId AND OrgGroupBatchId=@rOrgGroupBatchId
	
	SELECT @lCalculationTypeId=ISNULL(CalculationTypeId,0) FROM sFee.tExemptionTypeMaster WHERE Id = @lExemptionTypeId
	
	-- Exemption Type Temp Table
	CREATE TABLE #TempExemptionType
	(
		[AutoId] int identity,
		[AcademicId] bigint NULL,
		[RollNo] int NULL,
		[Name] nvarchar(500) NULL,
		[Code] nvarchar(20) NULL,
		[ClassId] int NULL,
		[DivisionId] int NULL,
		[ClassName] nvarchar(100) NULL,
		[DivisionName] nvarchar(100) NULL,
		[DivisionOrder] int NULL,
		[ClassDivision] nvarchar(200) NULL,
		[FeeSetupId] int NULL,
		[IsVariable] bit NULL,
		[Amount] decimal(12,2) NULL,
		[StartDate] date NULL,
		[EndDate] date NULL,
		[FAAmount] decimal(12,2) NULL,
		[DiscountAmount] decimal(12,2) NULL,
		[AdditionalAmount] decimal(12,2) NULL,
		[PaidAmount] decimal(12,2) NULL,
		[PendingAmount] decimal(12,2) NULL,
		[Remark] nvarchar(200) NULL,
		[FeeId] int NULL,
		[FeeName] nvarchar(100) NULL,
		[OrgId] int NULL,
		[OrgName] nvarchar(100) NULL,
		[OrgOrderIndex] int NULL,
		[ReceiptBookId] int NULL,
		[ReceiptBookTitle] nvarchar(100) NULL,
		[ReceiptOrderIndex] int NULL,
		[OrgGroupBatchId] int NULL,
		[DepartmentId] int NULL,
		[DepartmentName] nvarchar(100) NULL,
		[ParentContactNo] nvarchar(100) NULL,
		[ExemptionTypeId] int NULL,
	)
	-- End Exemption Type Temp Table
	
	
	
	INSERT INTO #TempExemptionType 
	SELECT 
		SA.AcademicId,
		SA.RollNo,
		SA.Name,
		SA.Code,
		SA.ClassId,
		SA.DivisionId,
		SA.ClassName,
		SA.DivisionName,
		SA.DivisionOrder,
		SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
		FS.Id AS FeeSetupId,
		ISNULL(FS.IsVariable,0)AS IsVariable,
		ISNULL(FS.Amount,0) + ISNULL(FA.VariableAmount,0.00) AS Amount,
		ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
		ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
		ISNULL(FA.VariableAmount,0.00)AS FAAmount,
		ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
		ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
		ISNULL(R.PaidAmount,0) AS PaidAmount,
		ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)AS PendingAmount,
		ISNULL(FA.Remark,'') AS Remark,
		FS.FeeId,
		FS.FeeName,
		SA.OrgId,
		O.Title AS OrgName,
		O.OrderIndex AS OrgOrderIndex,
		FS.ReceiptBookId,
		ISNULL(RBM.Title,'') AS ReceiptBookTitle,
		ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
		SA.OrgGroupBatchId,
		SA.DepartmentId,
		SA.DepartmentName,
		ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
		@lExemptionTypeId
  FROM 
  
			 sStudent.vStudentAcademic SA
		INNER JOIN 
		(
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName			 
			FROM sFee.tFeeSetup FS1
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
			AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@lClassId) OR (@lClassId=0)) AND ((SA1.DivisionId=@lDivisionId) OR (@lDivisionId=0))
				AND ((SA1.AdmissionCategoryId=@lAdmissionCategoryId) OR (@lAdmissionCategoryId=0))
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
			WHERE 
			    SA1.OrgGroupBatchId = @rOrgGroupBatchId
				AND	((FS1.ClassId=@lClassId) OR (@lClassId=0))				
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@lAdmissionCategoryId) OR (@lAdmissionCategoryId=0))
				AND (FS1.IsOptional=0)
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))				
				
				UNION ALL
				
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName 
				
			FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO
			ON FO.FeeSetupId=FS1.Id
	    INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
			AND ((SA1.ClassId=@lClassId) OR (@lClassId=0)) AND ((SA1.DivisionId=@lDivisionId) OR (@lDivisionId=0))
			AND ((SA1.AdmissionCategoryId=@lAdmissionCategoryId) OR (@lAdmissionCategoryId=0))
		INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
		WHERE
		        SA1.OrgGroupBatchId = @rOrgGroupBatchId
				AND ((FS1.ClassId=@lClassId) OR (@lClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@lAdmissionCategoryId) OR (@lAdmissionCategoryId=0))
				AND (FS1.IsOptional=1)
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))				
				
		) FS ON FS.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
		LEFT JOIN
		(
		    SELECT 
					ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
		    FROM
				sFee.tReceipt R 
				INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
				INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
				INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId				
				AND (SA1.ClassId=@lClassId OR @lClassId=0) 
				AND ((SA1.DivisionId=@lDivisionId) OR (@lDivisionId=0))
				AND (SA1.DivisionId=@lDivisionId OR @lDivisionId=0)
				
			WHERE		
				(R.SourceTypeId = 2001)
				AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND (R.IsObsolete = 0) 
				AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId))
				AND (R.OrgGroupBatchId = @rOrgGroupBatchId)
				AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
				GROUP BY FeeSetupId,R.SourceId
		) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
		 INNER JOIN sSetup.tOrganizationMaster O ON
		 SA.OrgId = O.Id
		 INNER JOIN sFee.tReceiptBookMaster RBM 
			ON FS.ReceiptBookId=RBM.Id
		 LEFT JOIN sStudent.tStudentCommunication SC 
			ON SC.StudentId = SA.StudentId
	WHERE	
			SA.AcademicId = @rAcademicId
			AND SA.OrgId = @rOrgId 
			AND SA.BatchId=@rBatchId
			AND SA.OrgGroupBatchId = @rOrgGroupBatchId
			AND ((SA.ExemptionTypeId=@rExemptionTypeId) OR (@rExemptionTypeId=0))
			AND (ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00) -ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00) > 0)
			
			
		DECLARE @lCode nvarchar(20)
		SELECT @lCode=A.Code FROM #TempExemptionType A
		INNER JOIN sFee.tExemptionTypeDetail ETD ON ETD.FeeId = A.FeeId AND ETD.ExemptionTypeId = @lExemptionTypeId
		WHERE AcademicId = @rAcademicId 
		AND ((@lCalculationTypeId=1 AND A.PendingAmount < (((ISNULL(A.Amount,0)) * (ISNULL(ETD.ExemptionPercentage,0)))/100)) OR (@lCalculationTypeId=2 AND A.PendingAmount < ISNULL(ETD.ExemptionPercentage,0)))
		IF @lCode IS NOT NULL
		BEGIN
				SELECT -101 AS Result,@lCode AS Code
			    RETURN
		END 
		
	BEGIN TRY 
	BEGIN TRANSACTION
	BEGIN -- Update Fee Allocation
		UPDATE AL 
		SET
		    DiscountAmount = ROUND(R.Result, 0),
			UpdatedUserId = @rCreatedUserId,
			UpdatedDateTime = sCommon.fGetDate()
		FROM
		(
		SELECT		
			 CASE
             WHEN @lCalculationTypeId= 1 THEN (((ISNULL(A.Amount,0)) * (ISNULL(ETD.ExemptionPercentage,0)))/100)
             WHEN @lCalculationTypeId = 2 THEN ISNULL(ETD.ExemptionPercentage,0)
             END AS Result,
			 ISNULL(A.Amount,0) AS Amount,
			 ISNULL(ETD.ExemptionPercentage,0) AS ExemptionPercentage,
			 A.ExemptionTypeId,
			 A.PendingAmount,
			 A.AcademicId,
			 A.FeeSetupId
		FROM #TempExemptionType A
	    INNER JOIN sFee.tExemptionTypeDetail ETD ON ETD.FeeId = A.FeeId AND ETD.ExemptionTypeId = @lExemptionTypeId
		) 
		R  INNER JOIN	sFee.tFeeAllocation AL ON AL.SourceId = R.AcademicId AND AL.FeeSetupId = R.FeeSetupId
		WHERE
		((@lCalculationTypeId=1 AND R.Amount >= (((ISNULL(R.Amount,0)) * (ISNULL(R.ExemptionPercentage,0)))/100)) OR (@lCalculationTypeId=2 AND R.Amount >= ISNULL(R.ExemptionPercentage,0)))
	END	
	
	BEGIN -- Insert Fee Allocation
		INSERT INTO sFee.tFeeAllocation
		SELECT		
			 2001,
			 A.AcademicId,
			 A.FeeSetupId,
			 0,
			 CASE
             WHEN @lCalculationTypeId= 1 THEN  ROUND((((ISNULL(A.Amount,0)) * (ISNULL(ETD.ExemptionPercentage,0)))/100),0)
             WHEN @lCalculationTypeId = 2 THEN ROUND(ISNULL(ETD.ExemptionPercentage,0),0)
             END,
			 NULL,
			 NULL,
			 NULL,
			 NULL,
			 NULL,
			 @rCreatedUserId,
			 sCommon.fGetDate(),
			 NULL,
			 NULL
		FROM #TempExemptionType A 
	    INNER JOIN sFee.tExemptionTypeDetail ETD ON ETD.FeeId = A.FeeId AND ETD.ExemptionTypeId = @lExemptionTypeId
		LEFT JOIN sFee.tFeeAllocation FA ON FA.SourceId = A.AcademicId AND FA.FeeSetupId = A.FeeSetupId 
		WHERE FA.SourceId IS NULL AND FA.FeeSetupId IS NULL
		AND 
		((@lCalculationTypeId=1 AND A.Amount >= (((ISNULL(A.Amount,0)) * (ISNULL(ETD.ExemptionPercentage,0)))/100)) OR (@lCalculationTypeId=2 AND A.Amount >= ISNULL(ETD.ExemptionPercentage,0)))
	END
	DROP TABLE #TempExemptionType
	SELECT 1 AS Result
	COMMIT TRANSACTION
END TRY
BEGIN CATCH 
		DROP TABLE #TempExemptionType
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
END CATCH	
END
GO
PRINT N'Altering [sFee].[pCollectionGroupMasterAdd]...';


GO
ALTER PROCEDURE [sFee].[pCollectionGroupMasterAdd]
	 
	 
		@rOrgGroupBatchId int,
        @rId int,
        @rCode nvarchar(20),
        @rTitle nvarchar(100),
        @rStartDate date,
        @rEndDate date,
        @rRemark nvarchar(500),
        @rIsObsolete bit,
        @rOrderIndex smallint,
        @rOrgGroupId int,
        @rReceiptBookId int=0,
        @rFooterRemark1 nvarchar(200)='',
        @rFooterRemark2 nvarchar(200)='',
        @rFeePeriod nvarchar(200)='',
        @rIsDisplayCashDetailInFolio bit=0
        
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	IF(@rId = 0)	
	BEGIN
		IF EXISTS (SELECT Id FROM sFee.tCollectionGroupMaster WHERE Code=@rCode AND OrgGroupBatchId=@rOrgGroupBatchId AND ReceiptBookId=@rReceiptBookId)
			BEGIN
			SELECT -101 as Result
			RETURN
		END 
	
		IF EXISTS (SELECT Id FROM sFee.tCollectionGroupMaster WHERE Title=@rTitle AND OrgGroupBatchId=@rOrgGroupBatchId AND ReceiptBookId=@rReceiptBookId)
			BEGIN
			SELECT -102 as Result
			RETURN
		END 
	END
	ELSE
	BEGIN
		IF EXISTS (SELECT Id FROM sFee.tCollectionGroupMaster WHERE  Code=@rCode AND OrgGroupBatchId=@rOrgGroupBatchId AND ReceiptBookId=@rReceiptBookId AND Id<>@rId)
		BEGIN
			SELECT -101 as Result
			RETURN
		END	
		IF EXISTS (SELECT Id FROM sFee.tCollectionGroupMaster WHERE  Title=@rTitle AND OrgGroupBatchId=@rOrgGroupBatchId AND ReceiptBookId=@rReceiptBookId AND Id<>@rId)
		BEGIN
			SELECT -102 as Result
			RETURN
		END 

	END
	
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sFee.tCollectionGroupMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sFee.tCollectionGroupMaster
		(
			OrgGroupBatchId,
			Id,
			Code,
			Title,
			StartDate,
			EndDate,
			Remark,
			IsObsolete,
			OrderIndex,
			ReceiptBookId,
			FooterRemark1,
			FooterRemark2,
			FeePeriod,
			IsDisplayCashDetailInFolio
		)
	VALUES
		(
			@rOrgGroupBatchId,
			@lNextNumber,
			@rCode,
			@rTitle,
			@rStartDate,
			@rEndDate,
			@rRemark,
			@rIsObsolete,
			@rOrderIndex,
			@rReceiptBookId,
			@rFooterRemark1,
			@rFooterRemark2,
			@rFeePeriod,
			@rIsDisplayCashDetailInFolio
		)
		    SELECT 1 AS Result
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sFee.tCollectionGroupMaster
	    SET
			Code=@rCode,
			Title=@rTitle,
			StartDate=@rStartDate,
			EndDate=@rEndDate,
			Remark=@rRemark,
			IsObsolete=@rIsObsolete,
			OrderIndex=@rOrderIndex,
			ReceiptBookId=@rReceiptBookId,
			FooterRemark1=@rFooterRemark1,
			FooterRemark2=@rFooterRemark2,
			FeePeriod=@rFeePeriod,
			IsDisplayCashDetailInFolio=@rIsDisplayCashDetailInFolio
	      
	      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 [sFee].[pCollectionGroupMasterGet]...';


GO
-- exec [sFee].[pCollectionGroupMasterGet] 
ALTER PROCEDURE [sFee].[pCollectionGroupMasterGet]
	 
	 @rOrgGroupBatchId int,
	 @rId int,
	 @rCode nvarchar(20),
	 @rTitle nvarchar(100),
	 @rReceiptBookId int=0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	
	BEGIN
			SET @rCode = sCommon.fSearchStringGet(@rCode)
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
	END
	
	SELECT 
			CGM.Id,
			CGM.Code,
			CGM.Title,
			CGM.StartDate,
			CGM.EndDate,
			CGM.Remark,
			CGM.IsObsolete,
			CGM.OrderIndex,
			CGM.OrgGroupBatchId,
			ISNULL(CGM.ReceiptBookId,0) AS ReceiptBookId,
			ISNULL(RBM.Title,'') AS ReceiptBook,
			ISNULL(CGM.FooterRemark1,'') AS FooterRemark1,
			ISNULL(CGM.FooterRemark2,'') AS FooterRemark2,
			ISNULL(CGM.FeePeriod,'') AS FeePeriod,
			ISNULL(CGM.IsDisplayCashDetailInFolio,0) AS IsDisplayCashDetailInFolio
	FROM 
			sFee.tCollectionGroupMaster CGM
			INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id = CGM.ReceiptBookId
	WHERE 
			(CGM.OrgGroupBatchId = @rOrgGroupBatchId)
			AND	((CGM.Id = @rId) OR (@rId = 0))
			AND ((CGM.Code like @rCode) OR (ISNULL(@rCode,'') = ''))
			AND ((CGM.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
			AND	((CGM.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId = 0))
	ORDER BY CGM.OrderIndex		
END
GO
PRINT N'Altering [sFee].[pFeeInvoiceGet]...';


GO

ALTER PROCEDURE [sFee].[pFeeInvoiceGet]
		 
		@rOrgGroupBatchId int,
		@rOrgId int=0,
		@rBatchId int=0,
		@rAdmissionCategoryId int=0,
		@rClassId int=0,
		@rDivisionId int=0,
		@rIdNo nvarchar(20)='',
		@rFirstName nvarchar(100)='',
		@rReceiptBookId int=0,
		@rFromInvoiceNumber int=0,
		@rToInvoiceNumber int=0,
		--@rCreatedUserName nvarchar(100)='',
		@rFromDate date='',
		@rToDate date='',
		@rOrgGroupId int,
		@rCreatedUserId bigint,
		@rCollectionGroupId int = 0,
		@rDepartmentId int=0
		
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
		BEGIN
			SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
			--SET @rCreatedUserName = sCommon.fSearchStringGet(@rCreatedUserName)
		END
BEGIN 		
	SELECT 
		FI.Id AS FeeInvoiceId,
		FI.SourceTypeId AS SourceTypeId,
		SA.Code AS Code,
		SA.RollNo,
		SA.ClassName+' - '+ SA.DivisionName AS Class,
		SA.Name,
		FI.InvoiceNumber,
		FI.InvoiceDate,
		ISNULL(FI.InvoiceAmount,0)AS InvoiceAmount,
		FI.ReceiptBookId,
		RBM.Title AS ReceiptBook,
		OM.DisplayTitle AS Organization,
		FI.BatchId,
		BM.Title AS Batch,
		SA.AcademicId AS SourceId,
		SA.OrgId,
		SA.BatchId,
		CASE WHEN (ISNULL(R.FeeInvoiceId,0) > 0) THEN 'Generated' ELSE 'Pending' END AS ReceiptStatus,
		ISNULL(CGM.Title,'' ) AS CollectionGroupName
		
  FROM 
			sFee.tFeeInvoice FI
		INNER JOIN sStudent.vStudentAcademic SA
			ON SA.AcademicId=FI.SourceId	AND (SA.ClassId=@rClassId OR @rClassId=0) 
				AND (SA.DivisionId=@rDivisionId OR @rDivisionId=0)
				AND (SA.AdmissionCategoryId=@rAdmissionCategoryId OR @rAdmissionCategoryId=0)
		INNER JOIN sSetup.tClassMaster Cm ON Cm.Id = SA.ClassId
		INNER JOIN sCommon.tSourceTypeMaster STM
			ON STM.Id=FI.SourceTypeId
		INNER JOIN sFee.tReceiptBookMaster RBM
			ON RBM.Id=FI.ReceiptBookId
		INNER JOIN sFee.tCollectionGroupMaster CGM
			ON CGM.Id = FI.CollectionGroupId
		INNER JOIN sSetup.tOrganizationMaster OM
			ON OM.Id=SA.OrgId AND OM.OrgGroupId=@rOrgGroupId
		INNER JOIN sSetup.tBatchMaster BM
			ON BM.Id=FI.BatchId AND BM.OrgGroupBatchId=@rOrgGroupBatchId
		LEFT JOIN sSecurity.tUser U ON U.Id=FI.CreatedUserId
		--INNER JOIN sFee.vUserReceiptBook URB ON URB.Id=RBM.Id AND URB.UserId=@rCreatedUserId
		LEFT JOIN sFee.tReceipt R ON R.SourceTypeId = 2001 AND R.SourceId = FI.SourceId AND R.ReceiptBookId=FI.ReceiptBookId AND R.BatchId = FI.BatchId AND R.OrgGroupBatchId = FI.OrgGroupBatchId
		AND R.FeeInvoiceId = FI.Id
WHERE 
	((SA.Code like @rIdNo) OR (ISNULL(@rIdNo,'')=''))
	AND (FI.SourceTypeId=2001)
	AND ((SA.FirstName like @rFirstName) OR(ISNULL(@rFirstName,'')=''))
	AND ((FI.InvoiceNumber>=@rFromInvoiceNumber)OR(@rFromInvoiceNumber=0))
	AND ((FI.InvoiceNumber<=@rToInvoiceNumber)OR(@rToInvoiceNumber=0))
	AND ((FI.ReceiptBookId=@rReceiptBookId)OR(@rReceiptBookId=0))
	AND ((FI.CollectionGroupId=@rCollectionGroupId)OR(@rCollectionGroupId=0))
	AND ((FI.InvoiceDate>=@rFromDate)OR(ISNULL(@rFromDate,'')=''))
	AND ((FI.InvoiceDate<=@rToDate)OR(ISNULL(@rToDate,'')=''))
	AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))
	AND ((FI.BatchId=@rBatchId) OR (@rBatchId=0))
	--AND ((ISNULL(U.DisplayTitle,'') like @rCreatedUserName) OR (ISNULL(@rCreatedUserName,'')=''))
	AND ((CM.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
	ORDER BY FI.InvoiceNumber DESC
END
GO
PRINT N'Altering [sFee].[pRptFeeFolioGet]...';


GO

ALTER PROCEDURE [sFee].[pRptFeeFolioGet]
		
		@rBuilder1 nvarchar(max)='',
		@rBuilder2 nvarchar(max)='',
		@rReportId int=0,
		@rIsFilter bit=0,
	    @rIsDisplayOrgGroup bit=0,
	    @rIsFeeInvoiceHeadwise bit=0,
		@rOrgGroupBatchId int=0,
		@rCommonBatch nvarchar(100)='',
		@rReceiptBookId int=0,
		@rOrgId int=0,
		@rBatchId int=0,
		@rDepartmentId int=0,
		@rAdmissionCategoryId int=0,
		@rClassId int=0,
		@rDivisionId int=0,
		@rStatusId int=0,
		@rFromRollNo int=0,
	    @rToRollNo int=0,
	    @rCode nvarchar(20)='',
	    @rCollectionGroupId int=0,
	    @rFeeHeadId nvarchar(max) = '',
	    @rFirstName nvarchar(100)='',
	    @rFromInvoiceNumber int=0,
		@rToInvoiceNumber int=0,
		@rCreatedUserName nvarchar(100)='',
		@rFeeInvoiceIds nvarchar(max)=''
	    
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			
	BEGIN
			SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
			SET @rCreatedUserName = sCommon.fSearchStringGet(@rCreatedUserName)
	END		
			 
BEGIN
	SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		@rIsFilter AS IsFilter,
		@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
		@rIsFeeInvoiceHeadwise AS IsFeeInvoiceHeadwise,
		SA.AcademicId,
		SA.Name,
		SA.ClassId,
		SA.ClassName,
		SA.DivisionId,
		SA.DivisionName,
		SA.DivisionOrder,
		SA.RollNo,
		SA.Code,
		SA.DepartmentId,
		SA.DepartmentName,
		FM.Id AS FeeId,
		FM.Title AS FeeName,
		FM.OrderIndex AS FeeOrderIndex,
		FHM.Id AS FeeHeadId,
		FHM.Title AS FeeHeadName,
		FHM.OrderIndex AS FeeHeadOrderIndex,
		RBM.Id AS ReceiptBookId,
		RBM.Title AS ReceiptBookName,
		RBM.BankName,
		RBM.BankAccountNumber,
		RBM.OrderIndex AS ReceiptBookOrderIndex,
		FID.Amount AS FeeAmount,
		CGM.Id AS CollectionGroupId,
		CGM.Title AS CollectionGroupName,
		CGM.OrderIndex AS CollectionGroupOrderIndex,
		CGM.FooterRemark1 AS FooterRemark1,
		CGM.FooterRemark2 AS FooterRemark2,
		CGM.FeePeriod AS FeePeriod,
		SA.BatchName,
		CGM.StartDate,
		CGM.EndDate,
		CGM.Remark,
		RBM.FullTitle,
		RBM.Address1,
		RBM.Address2,
		OM.OrgLogo,
		ISNULL(RBM.IsOnPrePrinted,0) AS IsOnPrePrinted,
		ISNULL(RBM.IsSupressLogo,0) AS IsSupressLogo,
		OGM.Title AS OrgGroupName,
		sFinanceCommon.fDefaultCurrencyTitleGet(OM.OrgGroupId) AS CurrencyTitle,
		ISNULL(SO.GenderId,0) AS GenderId,
		sFinanceCommon.fDefaultCurrencyCodeGet(OM.OrgGroupId) AS CurrencyCode,
		FI.InvoiceNumber,
		CASE WHEN FAL.DiscountAmount=0 THEN  null
		 ELSE FAL.DiscountAmount END AS ExemptionAmount,
		 RBM.GroupTitle,
		 SA.Suid,
		ISnull(CGM.IsDisplayCashDetailInFolio,0) AS IsDisplayCashDetailInFolio
  FROM 
		sFee.tFeeInvoiceDetail FID 
		INNER JOIN sFee.tFeeInvoice FI ON FI.Id = FID.FeeInvoiceId
		INNER JOIN sFee.tFeeSetup FS ON FS.Id = FID.FeeSetupId		
		INNER JOIN sStudent.vStudentAcademic SA ON FI.SourceTypeId = 2001 AND FI.SourceId = SA.AcademicId AND FI.BatchId=SA.BatchId AND FI.OrgGroupBatchId = SA.OrgGroupBatchId
		INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
		INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FM.FeeHeadId
		INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id = FS.ReceiptBookId
		INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = RBM.OrgGroupId
		LEFT JOIN sFee.tCollectionGroupMaster CGM ON CGM.Id = FS.CollectionGroupId AND SA.OrgGroupBatchId = CGM.OrgGroupBatchId
		LEFT JOIN sSetup.tOrganizationMaster OM ON OM.Id=SA.OrgId
		LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId = SA.StudentId
		LEFT JOIN sSecurity.tUser U ON U.Id=FI.CreatedUserId
		LEFT JOIN sFee.tFeeAllocation FAL  ON FAL.FeeSetupId  = FS.Id AND FAL.SourceId = FI.SourceId 
WHERE 
		(SA.OrgGroupBatchId = @rOrgGroupBatchId)
		AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))	
		AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0))	
		AND	((SA.AdmissionCategoryId = @rAdmissionCategoryId) OR (@rAdmissionCategoryId = 0))
		AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
		AND ((SA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))	
		AND ((SA.StatusId=@rStatusId) OR (@rStatusId=0))
		AND ((SA.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
		AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((SA.Code=@rCode) OR (@rCode=''))
		AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		AND	((FS.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId = 0))
		AND	((FS.CollectionGroupId = @rCollectionGroupId) OR (@rCollectionGroupId = 0))
		AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
		AND ((SA.FirstName like @rFirstName) OR(ISNULL(@rFirstName,'')=''))
		AND ((FI.InvoiceNumber>=@rFromInvoiceNumber)OR(@rFromInvoiceNumber=0))
		AND ((FI.InvoiceNumber<=@rToInvoiceNumber)OR(@rToInvoiceNumber=0))
		AND ((ISNULL(U.DisplayTitle,'') like @rCreatedUserName) OR (ISNULL(@rCreatedUserName,'')=''))
		AND (ISNULL(FI.Id,0) IN( SELECT cast(item as bigint) FROM  sCommon.fnsplit(@rFeeInvoiceIds,','))OR @rFeeInvoiceIds='')
END
GO
PRINT N'Altering [sFee].[pRptFeeInvoiceGet]...';


GO

ALTER PROCEDURE [sFee].[pRptFeeInvoiceGet]
		
		@rBuilder1 nvarchar(max),
		@rBuilder2 nvarchar(max),
		@rReportId int,
		@rIsFilter bit,
	    @rIsDisplayOrgGroup bit,
	    @rIsFeeInvoiceHeadwise bit,
		@rOrgGroupBatchId int,
		@rCommonBatch nvarchar(100),
		@rReceiptBookId int,
		@rOrgId int,
		@rBatchId int,
		@rDepartmentId int,
		@rAdmissionCategoryId int,
		@rClassId int,
		@rDivisionId int,
		@rStatusId int,
		@rFromRollNo int,
	    @rToRollNo int,
	    @rCode nvarchar(20),
	    @rCollectionGroupId int=0,
	    @rFeeHeadId nvarchar(max) = ''
	    
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN
	SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		@rIsFilter AS IsFilter,
		@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
		@rIsFeeInvoiceHeadwise AS IsFeeInvoiceHeadwise,
		FS.AcademicId,
		FS.Name,
		FS.ClassId,
		FS.ClassName,
		FS.DivisionId,
		FS.DivisionName,
		FS.DivisionOrder,
		FS.RollNo,
		FS.Code,
		FS.DepartmentId,
		FS.DepartmentName,
		FM.Id AS FeeId,
		FM.Title AS FeeName,
		FM.OrderIndex AS FeeOrderIndex,
		FHM.Id AS FeeHeadId,
		FHM.Title AS FeeHeadName,
		FHM.OrderIndex AS FeeHeadOrderIndex,
		RBM.Id AS ReceiptBookId,
		RBM.Title AS ReceiptBookName,
		RBM.BankName,
		RBM.BankAccountNumber,
		RBM.OrderIndex AS ReceiptBookOrderIndex,
		ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00) AS FeeAmount,
		CGM.Id AS CollectionGroupId,
		CGM.Title AS CollectionGroupName,
		CGM.OrderIndex AS CollectionGroupOrderIndex,
		CGM.FooterRemark1 AS FooterRemark1,
		CGM.FooterRemark2 AS FooterRemark2,
		CGM.FeePeriod AS FeePeriod,
		FS.BatchName,
		CGM.StartDate,
		CGM.EndDate,
		CGM.Remark,
		RBM.FullTitle,
		RBM.Address1,
		RBM.Address2,
		OM.OrgLogo,
		ISNULL(RBM.IsOnPrePrinted,0) AS IsOnPrePrinted,
		ISNULL(RBM.IsSupressLogo,0) AS IsSupressLogo,
		RBM.GroupTitle AS OrgGroupName,
		sFinanceCommon.fDefaultCurrencyTitleGet(OM.OrgGroupId) AS CurrencyTitle,
		ISNULL(SO.GenderId,0) AS GenderId,
		sFinanceCommon.fDefaultCurrencyCodeGet(OM.OrgGroupId) AS CurrencyCode,
		ISNULL(CGM.IsDisplayCashDetailInFolio,0) AS IsDisplayCashDetailInFolio
  FROM 
		sFee.tFeeMaster FM 
		INNER JOIN 
		(
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				ISNULL(FS1.CollectionGroupId,0) AS CollectionGroupId,
				SA.AcademicId,
				SA.StudentId,
				SA.Name,
				SA.ClassId,
				SA.ClassName,
				SA.DivisionId,
				SA.DivisionName,
				SA.DivisionOrder,
				SA.RollNo,
				SA.Code,
				SA.DepartmentId,
				SA.DepartmentName,
				SA.BatchName,
				SA.OrgId,
				SA.OrgGroupBatchId,
				SA.AdmissionCategoryId,
				SA.StatusId
			FROM sFee.tFeeSetup FS1
				INNER JOIN sStudent.vStudentAcademic SA ON SA.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA.ClassId = FS1.ClassId
				WHERE FS1.ClassId=SA.ClassId AND FS1.AdmissionCategoryId=SA.AdmissionCategoryId AND IsOptional=0
				AND FS1.BatchId = SA.BatchId AND ((FS1.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId=0))
				
				UNION ALL
				
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				ISNULL(FS1.CollectionGroupId,0) AS CollectionGroupId,
				SA.AcademicId,
				SA.StudentId,
				SA.Name,
				SA.ClassId,
				SA.ClassName,
				SA.DivisionId,
				SA.DivisionName,
				SA.DivisionOrder,
				SA.RollNo,
				SA.Code,
				SA.DepartmentId,
				SA.DepartmentName,
				SA.BatchName,
				SA.OrgId,
				SA.OrgGroupBatchId,
				SA.AdmissionCategoryId,
				SA.StatusId
			FROM sFee.tFeeSetup FS1
			INNER JOIN sStudent.vStudentAcademic SA ON SA.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA.ClassId = FS1.ClassId
			INNER JOIN sFee.tFeeOptional FO
				ON FO.FeeSetupId=FS1.Id AND (FO.SourceId=SA.AcademicId) AND(FO.SourceTypeId=2001)
			WHERE FS1.BatchId = SA.BatchId AND FS1.ClassId=SA.ClassId AND FS1.AdmissionCategoryId=SA.AdmissionCategoryId AND IsOptional=1 
			AND ((FS1.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId=0))
		) FS ON FS.FeeId=FM.Id
		INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FM.FeeHeadId
		INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id = FS.ReceiptBookId
		INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = RBM.OrgGroupId
		LEFT JOIN sFee.tCollectionGroupMaster CGM ON CGM.Id = FS.CollectionGroupId 
		AND FS.OrgGroupBatchId = CGM.OrgGroupBatchId
		LEFT JOIN sSetup.tOrganizationMaster OM ON OM.Id=FS.OrgId
		LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId = FS.StudentId
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=FS.Id AND (FA.SourceId=FS.AcademicId) AND(FA.SourceTypeId=2001)
WHERE 
		(FS.OrgGroupBatchId = @rOrgGroupBatchId)
		AND ((FS.OrgId=@rOrgId) OR (@rOrgId=0))	
		AND ((FS.BatchId=@rBatchId) OR (@rBatchId=0))	
		AND	((FS.AdmissionCategoryId = @rAdmissionCategoryId) OR (@rAdmissionCategoryId = 0))
		AND ((FS.ClassId = @rClassId) OR (@rClassId = 0))
		AND ((FS.DivisionId = @rDivisionId) OR (@rDivisionId = 0))	
		AND ((FS.StatusId=@rStatusId) OR (@rStatusId=0))
		AND ((FS.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
		AND ((FS.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((FS.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((FS.Code=@rCode) OR (@rCode=''))
		AND ((FS.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		AND	((FS.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId = 0))
		AND	((FS.CollectionGroupId = @rCollectionGroupId) OR (@rCollectionGroupId = 0))
		AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
		AND ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00) > 0  
END
GO
PRINT N'Altering [sFee].[pRptFeePendingDetailListGet]...';


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

	SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		@rIsDetail AS IsDetail,
		@rIsFilter As IsFilter,
		@rIsHeader As IsHeader,
		@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
		SA.AcademicId,
		SA.RollNo,
		SA.Name,
		SA.Code,
		SA.ClassId,
		SA.DivisionId,
		SA.ClassName,
		SA.DivisionName,
		SA.DivisionOrder,
		SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
		FS.Id AS FeeSetupId,
		ISNULL(FS.IsVariable,0)AS IsVariable,
		ISNULL(FS.Amount,0)AS Amount,
		ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
		ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
		ISNULL(FA.VariableAmount,0.00)AS FAAmount,
		ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
		ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
		ISNULL(R.PaidAmount,0) AS PaidAmount,
		ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)AS PendingAmount,
		ISNULL(FA.Remark,'') AS Remark,
		FS.FeeName,
		FHM.Id AS FeeHeadId,
		FHM.Title AS FeeHeadName,
		FHM.OrderIndex AS FeeHeadOrderIndex,
		SA.OrgId,
		O.Title AS OrgName,
		O.OrderIndex AS OrgOrderIndex,
		(CASE WHEN @rIsReceiptBookGroup = 0 THEN 0
			 WHEN @rIsReceiptBookGroup = 1 THEN	FS.ReceiptBookId
			 END) AS ReceiptBookId,	
		(CASE WHEN @rIsReceiptBookGroup = 0 THEN 'ALL'
			 WHEN @rIsReceiptBookGroup = 1 THEN	ISNULL(RBM.Title,'')
			 END) AS ReceiptBookTitle,
		(CASE WHEN @rIsReceiptBookGroup = 0 THEN 0
			 WHEN @rIsReceiptBookGroup = 1 THEN	ISNULL(RBM.OrderIndex,0)
			 END) AS ReceiptOrderIndex,	 
		--FS.ReceiptBookId,
		--ISNULL(RBM.Title,'') AS ReceiptBookTitle,
		--ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
		SA.OrgGroupBatchId,
		SA.DepartmentId,
		SA.DepartmentName,
		ISNULL(SC.ParentContactNo,'') AS ParentContactNo
  FROM 
  
			 sStudent.vStudentAcademic SA
		INNER JOIN 
		(
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.Id AS AcademicId,
				FM.Title AS FeeName,
				FM.FeeHeadId			 
			FROM sFee.tFeeSetup FS1
			INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId
			INNER JOIN sStudent.tStudentMaster SM ON SA1.StudentId = SM.Id			 
			AND SM.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))
				AND ((SM.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
			WHERE 
			    BM.OrgGroupBatchId = @rOrgGroupBatchId
				AND	((FS1.ClassId=@rClassId) OR (@rClassId=0))				
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=0)
				AND ((BM.Title = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))				
				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				
				UNION ALL
				
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName,
				FM.FeeHeadId
				
			FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO
			ON FO.FeeSetupId=FS1.Id
	    INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
			AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
		INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
		WHERE
		        SA1.OrgGroupBatchId = @rOrgGroupBatchId
				AND ((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=1)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))				
				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				
		) FS ON FS.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
		LEFT JOIN
		(
		    SELECT 
					ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
		    FROM
				sFee.tReceipt R 
				INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
				INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
				INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
				INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=R.SourceId
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA1.BatchId			
				AND (SA1.ClassId=@rClassId OR @rClassId=0) 
				AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))
				AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
				
			WHERE		
				(R.SourceTypeId = 2001)
				AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND (R.IsObsolete = 0) 
				AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId))
				AND (R.OrgGroupBatchId = @rOrgGroupBatchId)
				AND (R.ReceiptDate <= @rUptoDate) -- added condition after nes issue on 09/08/2016
				-- OR (@rOrgGroupBatchId = @rOrgGroupBatchId))
				AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
				AND ((BM.Title = @rCommonBatch) OR (@rCommonBatch = ''))
				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				GROUP BY FeeSetupId,R.SourceId
				
				
		
		) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
		 INNER JOIN sSetup.tOrganizationMaster O ON
		 SA.OrgId = O.Id
		 INNER JOIN sFee.tReceiptBookMaster RBM 
			ON FS.ReceiptBookId=RBM.Id
		 LEFT JOIN sStudent.tStudentCommunication SC 
			ON SC.StudentId = SA.StudentId
		INNER JOIN sFee.tFeeHeadMaster FHM
			ON FHM.Id = FS.FeeHeadId	
	WHERE	
	
			 SA.OrgGroupBatchId = @rOrgGroupBatchId
			AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0)) 
			AND (SA.StatusId = @rStatusId OR @rStatusId=0)
			AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
			AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
			AND ((SA.Code=@rCode) OR (@rCode=''))
			AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
			AND (ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00) -ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00) != 0)			
			Order by SA.RollNo
 
END
GO
PRINT N'Altering [sFee].[pXMLWinFeeDetailAdd]...';


GO
ALTER PROCEDURE [sFee].[pXMLWinFeeDetailAdd]
	(
		@rXmlDoc nvarchar(MAX),
		@rOrgId int
	)
AS

SET NOCOUNT ON

BEGIN
SET @rXmlDoc=REPLACE(@rXmlDoc,'&','AND')
DECLARE @lInterrorCode INT,
			@intDoc INT
--BEGIN TRY
--BEGIN TRANSACTION	
	EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc
	
	
	-----------------------
	
	INSERT INTO sFee.tWinfeeDetail
	(
		feeChoiceId,
		AcademicId,
		feeName,
		choice,
		Amount,
		exemption,
		paid,
		scheduleDate,
		ReceiptBookName,
		UpdatedDateTime,
		BatchId	
	)
	SELECT
		sCommon.fGetBigIntIdForOrg(convert(bigint,RIGHT(feeChoiceId,5)),@rOrgId),
		AcademicId,
		feeName,
		choice,
		Amount,
		exemption,
		paid,
		--scheduleDate,
		CASE WHEN scheduleDate = 0 THEN 01/01/1900 ELSE Convert(DATETIME, LEFT(scheduleDate, 8)) END AS scheduleDate,
		ReceiptBookName,
	--	UpdatedDateTime,
		CASE WHEN UpdatedDateTime = 0 THEN 01/01/1900 ELSE Convert(DATETIME, LEFT(UpdatedDateTime, 8)) END AS UpdatedDateTime,
		BatchId	
 
   		
		
	FROM OPENXML (@intDoc, '/Table/UploadFee', 1)
	WITH
	(
		feeChoiceId int '@feeChoiceId',
		AcademicId bigint '@AcademicId',
		feeName nvarchar(100) '@feeName',
		choice int '@choice',
		Amount decimal(12,2) '@Amount',
		exemption decimal(12,2) '@exemption',
		paid decimal(12,2) '@paid',
		scheduleDate bigint '@scheduleDate',
		ReceiptBookName nvarchar(100) '@ReceiptBookName',
		UpdatedDateTime bigint '@UpdatedDateTime',
		BatchId int '@BatchId'
	) WHERE AcademicId Not IN (Select AcademicId FRom sFee.tWinfeeDetail Where BatchId=BatchId) AND
	sCommon.fGetBigIntIdForOrg(convert(bigint,RIGHT(feeChoiceId,5)),@rOrgId) NOT IN (Select FeeChoiceId FRom sFee.tWinfeeDetail Where BatchId=BatchId) 

	
	UPDATE sFee.tWinfeeDetail 
	SET	AcademicId=A1.AcademicId,
		feeName=A1.feeName,
		choice=A1.choice,
		Amount=A1.Amount,
		exemption=A1.exemption,
		paid=A1.paid,
		scheduleDate=A1.scheduleDate,
		ReceiptBookName=A1.ReceiptBookName,
		UpdatedDateTime=A1.UpdatedDateTime,
		BatchId=A1.BatchId	
	FROM
	(
		SELECT	
		feeChoiceId,	
		AcademicId,
		feeName,
		choice,
		Amount,
		exemption,
		paid,
		--scheduleDate,
			CASE WHEN scheduleDate = 0 THEN 01/01/1900 ELSE Convert(DATETIME, LEFT(scheduleDate, 8)) END AS scheduleDate,
		ReceiptBookName,
		UpdatedDateTime,
		--CASE WHEN UpdatedDateTime = 0 THEN 01/01/1900 ELSE Convert(DATETIME, LEFT(UpdatedDateTime, 8)) END AS UpdatedDateTime,
		BatchId	
		FROM OPENXML (@intDoc, '/Table/UploadFee', 1)
		WITH
		(
			feeChoiceId int '@feeChoiceId',
			AcademicId bigint '@AcademicId',
			feeName nvarchar(100) '@feeName',
			choice int '@choice',
			Amount decimal(12,2) '@Amount',
			exemption decimal(12,2) '@exemption',
			paid decimal(12,2) '@paid',
			scheduleDate bigint '@scheduleDate',
			ReceiptBookName nvarchar(100) '@ReceiptBookName',
			UpdatedDateTime Datetime '@UpdatedDateTime',
			BatchId int '@BatchId'
		))A1 WHERE sFee.tWinfeeDetail.feeChoiceId = sCommon.fGetBigIntIdForOrg(convert(bigint,RIGHT(A1.feeChoiceId,5)),@rOrgId)


	EXEC sp_xml_removedocument @intDoc
	--COMMIT TRANSACTION
	--SELECT 1
	--END TRY
	--BEGIN CATCH
	--SELECT -1
	--END CATCH

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


GO
ALTER PROCEDURE [sFrontOffice].[pLostFoundRegisterGet]

	 @rOrgGroupId smallint=0,
	 @rId int = 0,
	 @rFoundNumber int,
	 @rOrgId smallint=0,
	 @rFromDate date,
	 @rToDate date,
	 @rLostFoundStatusId  bigint=0
	
	 	 
	WITH EXECUTE AS CALLER
AS
--SET NOCOUNT ON
--			 SET @rDispatchedTo = sCommon.fSearchStringGet(@rDispatchedTo) 

BEGIN 
	 
	
	SELECT 
	
			LF.OrgGroupId,
			LF.OrgId,
			LF.Id,
			LF.FoundNumber,
			LF.FoundDate,
			LF.ItemType,
			LF.ItemDescription,
			LF.LostFoundStatusId,
			LF.OwnerSourceTypeId,
			LF.OwnwerSourceId,
			LF.OwnerDetail,
			LF.CreatedUserId,
			LF.CreatedDateTime,
			LF.UpdatedUserId,
			LF.UpdatedDateTime,
			SM.Title,
			SM.Id,
			(CASE WHEN LF.OwnerSourceTypeId=2003 THEN  SMast.Code
			WHEN  LF.OwnerSourceTypeId=95  THEN EM.Code  ElSE ''
			 END) AS Code
			
			
      
  FROM 
            sFrontOffice.tLostFoundRegister LF INNER JOIN 
            sCommon.tStatusMaster SM ON SM.Id=LF.LostFoundStatusId 
            LEFT JOIN sStudent.vStudentLastAcademic SMast ON SMast.StudentId = LF.OwnwerSourceId  AND LF.OwnerSourceTypeId=2003
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = LF.OwnwerSourceId  AND LF.OwnerSourceTypeId=95
            
            
            
            
  WHERE 
  
      ((LF.Id = @rId) OR (@rId = 0))
     AND ((LF.FoundNumber = @rFoundNumber) OR (@rFoundNumber = 0))
	--AND ((FoundDate LIKE @rFoundDate) OR (ISNULL(@rFoundDate,'') = ''))
	AND ((LF.FoundDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	AND ((LF.FoundDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
	AND  LF.OrgGroupId=@rOrgGroupId
	AND  ((LF.LostFoundStatusId=@rLostFoundStatusId) OR (@rLostFoundStatusId = 0))
	AND ((LF.OrgId = @rOrgId) OR (@rOrgId = 0))
	
	
	Order by CreatedDateTime desc
END
GO
PRINT N'Altering [sHostel].[pAssignRoomGet]...';


GO

ALTER PROCEDURE [sHostel].[pAssignRoomGet]
          
           @rBuilder1 nvarchar(max)='',
		   @rBuilder2 nvarchar(max)='', 
           @rHostelId int,
           @rRoomCategoryId int=0,
           @rRoomId int=0
           --@rIsWildCardSearch bit
          
AS
SET NOCOUNT ON

		--IF @rIsWildCardSearch = 1
		--BEGIN
			--SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		--END

BEGIN
SELECT  
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
       'Employee' AS SourceType,
		95 AS SourceTypeId,
		ISNULL(EM.Id,0) as SourceId,
		EM.Code as SourceCode,
		EM.FirstName+' '+EM.LastName as SourceName,
		ODM.Title as ClassDivisionName,
		RM.StudentsPerRoom,
		HTM.Title as HostelType,
		HM.Title AS HostelName,
		RM.Title AS Room,
		OM.DisplayTitle AS OrgDisplayTitle,
		AR.BedNumber AS BedNumber,
		RM.RoomCategoryId,
	    ISNULL(RCM.RoomCharge,0) AS RoomCharge,
	    OM.Id AS OrgId,
	    '' AS SUId,
	    '' AS City
		
  FROM sHostel.tRoomMaster RM 
	INNER JOIN sHostel.tRoomCategoryMaster RCM ON RCM.Id=RM.RoomCategoryId AND (RCM.Id=@rRoomCategoryId OR @rRoomCategoryId=0)
	LEFT JOIN sHostel.tAssignRoom AR ON RM.Id=AR.RoomId AND AR.SourceTypeId=95
    LEFT JOIN sHrm.tEmployeeMaster EM ON AR.SourceId=EM.Id
    LEFT JOIN sHostel.tHostelMaster HM ON HM.Id=RM.HostelId
    LEFT JOIN sHostel.tHostelTypeMaster HTM ON HTM.Id=HM.HostelTypeId
    LEFT JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id = EJD.EmployeeId
    LEFT JOIN sSetup.tDepartmentMaster ODM ON ODM.Id = EJD.OrganizationDepartmentId
    LEFT JOIN sSetup.tOrganizationMaster OM ON OM.Id=EM.OrgID
  WHERE 
	--	 CCM.Id = @rId OR @rId = 0
	--AND 
		(RM.HostelId=@rHostelId OR @rHostelId=0)
	AND (RM.Id=@rRoomId OR @rRoomId=0)
	--AND  CCM.IsObsolete = 0
	UNION ALL
	
SELECT 
        @rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
       'Student' AS SourceType,
		2003 AS SourceTypeId,
		ISNULL(SA.StudentId,0) as SourceId,
		SA.Code as SourceCode,
		SA.LastName + ' ' + SA.FirstName AS SourceName,
		sStudent.fStudentCurrentDivisionGet( SA.StudentId) AS ClassDivisionName,
		--'' AS  ClassDivisionName,
		--SA.ClassName+'-'+SA.DivisionName as ClassDivisionName,
		RM.StudentsPerRoom,
		HTM.Title as HostelType,
		HM.Title AS HostelName,
		RM.Title AS Room,
		OM.DisplayTitle AS OrgDisplayTitle,
		AR.BedNumber AS BedNumber,
		RM.RoomCategoryId,
	    ISNULL(RCM.RoomCharge,0) AS RoomCharge,
	    OM.Id AS OrgId,
	    ISNULL(SA.SUId,'') AS SUId,
	    ISNULL(SC.PresentCity,'') AS City
  FROM sHostel.tRoomMaster RM 
	INNER JOIN sHostel.tRoomCategoryMaster RCM ON RCM.Id=RM.RoomCategoryId AND (RCM.Id=@rRoomCategoryId OR @rRoomCategoryId=0)
	LEFT JOIN sHostel.tAssignRoom AR ON RM.Id=AR.RoomId AND AR.SourceTypeId=2003
    LEFT JOIN sStudent.vStudentLastAcademic SA ON AR.SourceId=SA.StudentId --AND SA.IsActiveBatch = 1  
    LEFT JOIN sHostel.tHostelMaster HM ON HM.Id=RM.HostelId
    LEFT JOIN sHostel.tHostelTypeMaster HTM ON HTM.Id=HM.HostelTypeId
    LEFT JOIN sSetup.tOrganizationMaster OM ON OM.Id=SA.OrgID
    LEFT JOIN  sStudent.tStudentCommunication SC ON SC.StudentId=AR.SourceId
  WHERE 
	--	CCM.Id = @rId OR @rId = 0
	--	AND 
		(RM.HostelId=@rHostelId OR @rHostelId=0)
		AND (RM.Id=@rRoomId OR @rRoomId=0)
	--  AND  CCM.IsObsolete = 0
	
END
GO
PRINT N'Altering [sHostel].[pChangeRoomGet]...';


GO

ALTER PROCEDURE [sHostel].[pChangeRoomGet]
          
           @rHostelId int,
           @rOrgId int,
           @rSourceTypeId smallint,
           @rCode nvarchar(20),
           @rFromLogDate date,
           @rToLogDate date,
           @rSUID nvarchar(20)
          
AS
SET NOCOUNT ON

BEGIN
SELECT  
		OM.DisplayTitle AS OrganizationName,
        (CASE WHEN CR.SourceTypeId = 95 THEN	'Employee'
			 WHEN CR.SourceTypeId = 2003 THEN	'Student' END) AS SourceType,

		(CASE WHEN CR.SourceTypeId = 95 THEN	Emp.Code
			 WHEN CR.SourceTypeId = 2003 THEN	SM.Code END) AS SourceCode, 	
			 
		(CASE WHEN CR.SourceTypeId = 95 THEN	''
			 WHEN CR.SourceTypeId = 2003 THEN	SM.SUId END) AS SUId, 		 

		(CASE WHEN CR.SourceTypeId = 95 THEN Emp.EmployeeName
			WHEN CR.SourceTypeId = 2003 THEN SM.Name  END) AS SourceName,
			
		(CASE WHEN CR.SourceTypeId = 95 THEN Emp.DepartmentName
			WHEN CR.SourceTypeId = 2003 THEN (sStudent.fStudentCurrentDivisionGet(SM.StudentId)) END) AS ClassDepartmentName,	
		 RM.Title AS RoomName,
		 CR.SourceTypeId,
		 CR.SourceId,
		(CASE WHEN CR.LogDate = '1900-01-01' THEN ''
			ELSE CR.LogDate END) AS LogDate,	
		 ISNULL(CR.ChangeReason,'') AS ChangeReason

  FROM 
		sHostel.tChangeRoom CR
		INNER JOIN sHostel.tRoomMaster RM ON RM.Id = CR.RoomId
        LEFT JOIN sHrm.vExtEmployeeMaster Emp
			ON Emp.Id = CR.SourceId AND CR.SourceTypeId = 95 
		LEFT JOIN sStudent.vStudentLastAcademic SM
			ON SM.StudentId = CR.SourceId AND CR.SourceTypeId = 2003		
		LEFT JOIN sSetup.tOrganizationMaster OM ON (OM.Id = SM.OrgId) OR (OM.Id = Emp.OrgId)  	
  WHERE 
	
	(RM.HostelId=@rHostelId)
	AND ((OM.Id=@rOrgId) OR (@rOrgId=0))
	AND ((CR.SourceTypeId=@rSourceTypeId) OR (@rSourceTypeId=0))
	AND (((@rSourceTypeId =2003 OR(@rSourceTypeId=0)) AND SM.Code LIKE @rCode) OR (ISNULL(@rCode,'')='') 
        OR ((@rSourceTypeId =95 OR(@rSourceTypeId=0)) AND Emp.Code LIKE @rCode) OR (ISNULL(@rCode,'')=''))
	AND ((CR.LogDate >= @rFromLogDate) OR (ISNULL(@rFromLogDate,'') = ''))
	AND ((CR.LogDate <= @rToLogDate) OR (ISNULL(@rToLogDate,'') = ''))
	AND ((SM.SUId=@rSUID) OR (ISNULL(@rSUID,'') = ''))
END
GO
PRINT N'Altering [sHostel].[pHostelAdmissionGet]...';


GO

ALTER PROCEDURE [sHostel].[pHostelAdmissionGet]
          
           @rHostelId int,
           @rOrgId int,
           @rSourceTypeId smallint,
           @rCode nvarchar(20),
           @rFromAllocateDate date,
           @rToAllocateDate date,
           @rToVacantDate date='',
           @rFromVacantDate date='',
           @rSUID nvarchar(20)
           
          
AS
SET NOCOUNT ON

BEGIN
SELECT  
		OM.DisplayTitle AS OrganizationName,
        (CASE WHEN HA.SourceTypeId = 95 THEN	'Employee'
			 WHEN HA.SourceTypeId = 2003 THEN	'Student' END) AS SourceType,

		(CASE WHEN HA.SourceTypeId = 95 THEN	Emp.Code
			 WHEN HA.SourceTypeId = 2003 THEN	SM.Code END) AS SourceCode, 	
		
		(CASE WHEN HA.SourceTypeId = 95 THEN	''
			 WHEN HA.SourceTypeId = 2003 THEN	SM.SUId END) AS SUId, 	

		(CASE WHEN HA.SourceTypeId = 95 THEN Emp.EmployeeName
			WHEN HA.SourceTypeId = 2003 THEN SM.LastName + ' ' + SM.FirstName  END) AS SourceName,
			
		(CASE WHEN HA.SourceTypeId = 95 THEN Emp.DepartmentName
			WHEN HA.SourceTypeId = 2003 THEN (sStudent.fStudentCurrentDivisionGet(SM.StudentId)) END) AS ClassDepartmentName,		
		 
		 HA.SourceTypeId,
		 HA.SourceId,
		 HA.AllocateDate,
		(CASE WHEN HA.VacantDate = '1900-01-01' THEN ''
			ELSE HA.VacantDate END) AS VacantDate,	
		 ISNULL(HA.VacantReason,'') AS VacantReason

  FROM 
		sHostel.tHostelAdmission HA
		
        LEFT JOIN sHrm.vExtEmployeeMaster Emp
			ON Emp.Id = HA.SourceId AND HA.SourceTypeId = 95 
		LEFT JOIN sStudent.vStudentLastAcademic SM
			ON SM.StudentId = HA.SourceId AND HA.SourceTypeId = 2003		
		LEFT JOIN sSetup.tOrganizationMaster OM ON (OM.Id = SM.OrgId) OR (OM.Id = Emp.OrgId)  	
  WHERE 
	
	(HA.Hosteld=@rHostelId)
	AND ((OM.Id=@rOrgId) OR (@rOrgId=0))
	AND ((HA.SourceTypeId=@rSourceTypeId) OR (@rSourceTypeId=0))
	AND (((@rSourceTypeId =2003 OR(@rSourceTypeId=0)) AND SM.Code LIKE @rCode) OR (ISNULL(@rCode,'')='') 
        OR ((@rSourceTypeId =95 OR(@rSourceTypeId=0)) AND Emp.Code LIKE @rCode) OR (ISNULL(@rCode,'')=''))
	AND ((HA.AllocateDate >= @rFromAllocateDate) OR (ISNULL(@rFromAllocateDate,'') = ''))
	AND ((HA.AllocateDate <= @rToAllocateDate) OR (ISNULL(@rToAllocateDate,'') = ''))
	AND ((HA.VacantDate >= @rFromVacantDate) OR (ISNULL(@rFromVacantDate,'') = ''))
	AND ((HA.VacantDate <= @rToVacantDate) OR (ISNULL(@rToVacantDate,'') = ''))
	AND ((SM.SUId=@rSUID) OR (ISNULL(@rSUID,'') = ''))
END
GO
PRINT N'Altering [sHostel].[pHostelStudentGatePassAdd]...';


GO
ALTER PROCEDURE [sHostel].[pHostelStudentGatePassAdd]
	 
		@rHostelId int,
        @rId int,
        @rStudentId bigint,
        @rWhithWhom nvarchar(100),
        @rApprovedBy nvarchar(100),
        @rReason nvarchar(100),
        @rOutDate date,
        @rOutTime time(7),
        @rInDate date,
        @rInTime time(7),
        @rCreatedUserId bigint,
        @rOrgId smallint
       
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON


DECLARE @lStudentId bigint --change

BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 
	 SELECT @lStudentId= StudentId From sStudent.tAcademic Where Id=@rStudentId--change

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sHostel.tStudentGatePass', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sHostel.tStudentGatePass
		(
			HostelId,
			Id,
			StudentId,
			WhithWhom,
			ApprovedBy,
			Reason,
			OutDate,
			OutTime,
			InDate,
			InTime,
			CreatedUserId,
			CreatedDateTime
		)
	VALUES
		(
		@rHostelId,  
		@lNextNumber,	
        @rStudentId,
        @rWhithWhom, 
        @rApprovedBy, 
        @rReason, 
        @rOutDate,
        @rOutTime,
        @rInDate,
        @rInTime,
        @rCreatedUserId,
        sCommon.fGetDate()
		)
		    SELECT 1  AS Result,@lNextNumber
	END	 

ELSE
	 BEGIN
	-- SET @lNextNumber = @rId
	--SELECT @lStudentId= StudentId From sStudent.tAcademic Where Id=@rStudentId--change

	    UPDATE  sHostel.tStudentGatePass
	    SET
			HostelId=@rHostelId,
			StudentId=@rStudentId,
			WhithWhom=@rWhithWhom,
			ApprovedBy=@rApprovedBy,
			Reason=@rReason,
			OutDate=@rOutDate,
			OutTime=@rOutTime,
			InDate=@rInDate,
			InTime=@rInTime,
			CreatedUserId=@rCreatedUserId
			--CreatedDateTime=sCommon.fGetDate()
	      
	      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 [sHostel].[pHostelStudentGatePassGet]...';


GO
ALTER PROCEDURE [sHostel].[pHostelStudentGatePassGet]

	 @rId int,
	 @rStudentCode nvarchar(20),
	 @rHostelId int,
	 @rOutDate datetime,
	 @rInDate datetime
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	
	SELECT 
			SM.Code,
			--SM.FirstName+' '+SM.LastName AS StudentName,
			SM.Name AS StudentName,
			SG.WhithWhom,
			SG.ApprovedBy,
			SG.Reason,
			ISNULL(SG.OutDate,'') AS OutDate,
			ISNULL(SG.InDate,'') AS InDate,
			SG.Id,
			HM.Title AS HostelName,
			SM.Code,
			SG.StudentId,
			OutTime,
			InTime
	FROM 
			sHostel.tStudentGatePass SG
			INNER JOIN sStudent.vStudentLastAcademic SM ON SM.StudentId=SG.StudentId
			INNER JOIN sHostel.tHostelMaster HM ON HM.Id=SG.HostelId
	WHERE 
			((SG.Id = @rId) OR (@rId = 0))
		AND (SM.Code = @rStudentCode  OR ISNULL(@rStudentCode,'')='')
		AND ((SG.HostelId = @rHostelId) OR (@rHostelId = 0))
		--AND ((SG.OutDate=@rOutDate) OR (ISNULL(@rOutDate,'')=''))
		--AND ((SG.InDate=@rInDate) OR (ISNULL(@rInDate,'')=''))
		AND (SG.OutDate>=@rOutDate OR ISNULL(@rOutDate,'')='')
		AND (SG.OutDate<=@rInDate OR ISNULL(@rInDate,'')='')
		Order by SG.CreatedDateTime DESC
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(100),
	 @rClassId int,
	 @rDivisionId int,
	 @rOrgGroupBatchId int,
	 @rSUId nvarchar(20)='',
	 @rDepartmentId  int

	 	 
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.StudentContactNo,'') AS ContactNo
			FROM sHostel.tAssignRoom AR 
			INNER JOIN sStudent.vStudentLastAcademic 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
			
			Where 
			SourceTypeId = 2003
			--AND (SD.OrgGroupBatchId=@rOrgGroupBatchId)
			AND ((O.Id = @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.Name like @rStudentName + '%') OR (ISNULL(@rStudentName,'') = ''))
			AND ((SD.DepartmentId = @rDepartmentId ) OR (ISNULL(@rDepartmentId,0) = 0))
			AND ((SD.SUId like @rSUId) OR (ISNULL(@rSUId,'')=''))
END
GO
PRINT N'Altering [sHostel].[pRoomMasterAdd]...';


GO
ALTER PROCEDURE [sHostel].[pRoomMasterAdd]
	 
	@rId int,
	@rTitle nvarchar(100),
	@rRemark nvarchar(100),
	@rHostelId int,
	@rRoomCategoryId int,
	@rStudentsPerRoom smallint,
	@rCreatedUserId bigint,
	@rIsObsolete bit,
	@rAssignedEmployeeId bigint,
	@rOrgGroupId int,
	@rBuildingId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	 
	
IF(@rId = 0)	
BEGIN
	If Exists(select Id from sHostel.tRoomMaster where Title=@rTitle)
	BEGIN
		select -103 as Result
		RETURN
	END 
END
ELSE
BEGIN
	If  Exists(select Id from sHostel.tRoomMaster where Title=@rTitle AND Id<>@rId)
	BEGIN
		select -103 as Result
		RETURN
	END
	
	If  Exists(select Count(SourceId) from sHostel.tAssignRoom where RoomId=@rId having COUNT(sourceID) > @rStudentsPerRoom)
	BEGIN
		select -104 as Result
		RETURN
	END
END
	
 BEGIN TRANSACTION	
 DECLARE @lNextNumber INT 
 
 IF(@rId = 0)	
	BEGIN
	--EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sHostel.tRoomMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sHostel.tRoomMaster', 0, 1, 1,@outNextNumber = @lNextNumber output

	INSERT INTO sHostel.tRoomMaster
		(
			Id,
			Title,
			Remark,
			HostelId,
			RoomCategoryId,
			StudentsPerRoom,
			CreatedUserId,
			CreatedDateTime,
			IsObsolete,
			AssignedEmployeeId,
			BuildingId
		)
	VALUES
		(
			@lNextNumber,
			@rTitle,
			@rRemark,
			@rHostelId,
			@rRoomCategoryId,
			@rStudentsPerRoom,
			@rCreatedUserId,
			sCommon.fGetDate(), 
			@rIsObsolete,
			@rAssignedEmployeeId,
			@rBuildingId
		)
		             
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sHostel.tRoomMaster
	    SET
			Title=@rTitle,
			Remark=@rRemark,
			HostelId=@rHostelId,
			RoomCategoryId=@rRoomCategoryId,
			StudentsPerRoom=@rStudentsPerRoom,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate(), 
			IsObsolete=@rIsObsolete,
			AssignedEmployeeId=@rAssignedEmployeeId,
			BuildingId=@rBuildingId
	      
	      
	      WHERE Id = @rId 	   
	 END  
		SELECT @lNextNumber AS Result
	
		COMMIT TRANSACTION
		
	 
		
END
GO
PRINT N'Altering [sHostel].[pRptRoomwiseStudentListGet]...';


GO


ALTER PROCEDURE [sHostel].[pRptRoomwiseStudentListGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rHostelId int,
	 @rOrgGroupBatchId int,
	 @rOrgId int,
	 @rRoomId int=0,
	 @rStudentName nvarchar(100)='',
	 @rStudentCode nvarchar(100)='',
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rIsBasedOnSUId bit = 0,
	 @rDepartmentId int=0,
	  @rSUId nvarchar(20)=''
	 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 


	SELECT
        @rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
       'Student' AS SourceType,
		2003 AS SourceTypeId,
		ISNULL(SA.StudentId,0) as SourceId,
		SA.SUId AS SUId,
		SA.Code as SourceCode,
		SA.Name as SourceName,
		SA.ClassName+'-'+SA.DivisionName as ClassDivisionName,
		SA.RollNo,
		RM.StudentsPerRoom,
		HTM.Title as HostelType,
		HM.Title AS HostelName,
		RM.Title AS Room,
		SC.ParentContactNo,
		SA.OrgId,
		OM.DisplayTitle AS OrganizatinName,
		SA.DivisionId,
		SA.DivisionOrder,
		@rIsBasedOnSUId AS IsBasedOnSUId
		
	FROM sHostel.tRoomMaster RM 
		LEFT JOIN sHostel.tAssignRoom AR ON RM.Id=AR.RoomId AND AR.SourceTypeId=2003
		INNER JOIN sStudent.vStudentLastAcademic SA ON AR.SourceId=SA.StudentId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA.BatchId AND BM.IsActive = 1
		LEFT JOIN sStudent.tStudentCommunication SC ON SA.StudentId=SC.StudentId
		LEFT JOIN sHostel.tHostelMaster HM ON HM.Id=RM.HostelId
		LEFT JOIN sHostel.tHostelTypeMaster HTM ON HTM.Id=HM.HostelTypeId
    
	WHERE 
		(SA.OrgGroupBatchId = @rOrgGroupBatchId)
		AND ((SA.OrgId = @rOrgId) OR (@rOrgId=0))
		AND 
		((RM.HostelId=@rHostelId) OR (@rHostelId=0))
		AND ((RM.Id=@rRoomId) OR (@rRoomId=0))
		--AND ((RM.Id=@rRoomId) OR (@rRoomId=0))
		AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
		AND ((SA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))
		AND ((SA.Code Like @rStudentCode) OR (ISNULL(@rStudentCode,'')=''))
		AND ((SA.FirstName like @rStudentName + '%') OR (ISNULL(@rStudentName,'') = ''))
		AND ((SA.DepartmentId = @rDepartmentId ) OR (@rDepartmentId = 0))
		AND (SA.SUId like @rSUId OR ISNULL(@rSUId,'')='')
	END
GO
PRINT N'Altering [sHostel].[pVisitorGatePassAdd]...';


GO
ALTER PROCEDURE [sHostel].[pVisitorGatePassAdd]
	@rId int,
	@rHostelId int,
	@rVisitorName [nvarchar](100),
	@rNoOfVisitor [tinyint],
	@rPurposeOfVisit [nvarchar](200),
	@rWhomToMeetSourceTypeId [smallint],
	--@rEmployeeId [int],
	@rWhomToMeetSourceId bigint,
	@rWhomToMeetName nvarchar(100),
	@rInTime time,
	@rOutTime time,
	--@rVisitorPhoto varbinary(max),
	@rVisitDate date,
	@rOrgId int,
	@rCreatedUserId bigint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

	--IF(@rWhomToMeetSourceTypeId=0)
	--BEGIN
	--	SET @rWhomToMeetSourceId=NULL
	--	SET @rWhomToMeetSourceTypeId=NULL
	--END
	
	--else IF(@rWhomToMeetSourceTypeId=0)
	--BEGIN
	--SET @rWhomToMeetSourceId=NULL
	--END
	
	DECLARE @lNextNumber BIGINT	
	
	IF(@rId = 0)	
	BEGIN
	EXECUTE  sCommon.pTableRowIdGet @rOrgId, 'sHostel.tVisitorGatePass', 0, 101, 1,@outNextNumber = @lNextNumber output
	
		INSERT INTO sHostel.tVisitorGatePass
			(
				
				Id,
				HostelId,
				VisitorName,
				NoOfVisitor,
				PurposeOfVisit,
				WhomToMeetSourceTypeId,
				WhomToMeetSourceId,
				WhomToMeetName,
				InTime,
				OutTime,
				--VisitorPhoto,
				VisitDate,
				CreatedUserId,
				CreatedDateTime
			)
		VALUES
			(
				@lNextNumber,
				@rHostelId,					
				@rVisitorName,
				@rNoOfVisitor,
				@rPurposeOfVisit,
				@rWhomToMeetSourceTypeId,
				@rWhomToMeetSourceId,
				@rWhomToMeetName,
				@rInTime,
				@rOutTime,
				--@rVisitorPhoto,
				@rVisitDate,
				@rCreatedUserId,
				sCommon.fGetDate()
				 
			)
			SELECT 1 AS Result,@lNextNumber
		END	
	--		IF(@rWhomToMeetSourceTypeId=1  OR  @rWhomToMeetSourceTypeId=95)
	--			BEGIN
	--				IF NOT EXISTS(SELECT 1 FROM sSecurity.tUserOrganization WHERE UserId = @lNextNumber AND OrgId = @rOrgId)
	--					BEGIN
	--						INSERT INTO sSecurity.tUserOrganization
	--						SELECT @rOrgId,@lNextNumber
	--					END
	--			END
	--	END	
			
	--SELECT @lNextNumber AS UserId
	
	ELSE
		BEGIN
			Update sHostel.tVisitorGatePass
				set
					HostelId=@rHostelId,
					VisitorName=@rVisitorName,
					NoOfVisitor=@rNoOfVisitor,
					PurposeOfVisit=@rPurposeOfVisit,
					WhomToMeetSourceTypeId=@rWhomToMeetSourceTypeId,
					WhomToMeetSourceId=@rWhomToMeetSourceId,
					WhomToMeetName=@rWhomToMeetName,
					InTime=@rInTime,
					OutTime=@rOutTime,	
					--VisitorPhoto,
					VisitDate=@rVisitDate,
					CreatedUserId=@rCreatedUserId
					
			where Id=@rId
		SELECT 11 AS Result
	END

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


GO
ALTER PROCEDURE [sHostel].[pVisitorGatePassGet]


		   @rId int,
           @rFromVisitDate datetime,
           @rToVisitDate datetime,
           @rHostelId int,
		   --@rVisitDate date,
		   @rVisitorName nvarchar(100),
		   @rWhomToMeetSourceTypeId smallint,
		   @rWhomToMeetSourceId bigint
	 
	 --@rInDate datetime
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 

	
	
	SELECT 
			
			VG.Id,
			VG.HostelId,
			VG.VisitorName,
			VG.NoOfVisitor,
			VG.PurposeOfVisit,
			ISNULl(VG.WhomToMeetSourceTypeId,0) AS WhomToMeetSourceTypeId,
			ISNULL (VG.WhomToMeetSourceId,0) AS WhomToMeetSourceId,
			ISNULL(VG.WhomToMeetName,'') AS WhomToMeetName,
			VG.InTime,
			VG.OutTime,
			ISNULL(VG.VisitDate,'1900-01-01 00:00:00') AS VisitDate,
			ISNULL(VG.VisitorPhoto, CONVERT(VARBINARY(MAX), 0)) AS VisitorPhoto,
			HM.Title AS HostelName,
			ISNULL(SM.FirstName,'') AS StudentName,
			ISNULL(EM.FirstName,'') AS EmployeeName,
			
			CASE WhomToMeetSourceTypeId
				WHEN 95 THEN 'Employee'
				WHEN 2003 THEN 'Student'
				ELSE 'Other'
			END AS SourceType
		
		
			
	FROM 
			sHostel.tVisitorGatePass VG
			Left JOIN sCommon.tSourceTypeMaster ST ON ST.Id=VG.WhomToMeetSourceTypeId
			Left JOIN sStudent.vStudentLastAcademic SM ON SM.StudentId=VG.WhomToMeetSourceId
			Left JOIN sHrm.tEmployeeMaster EM ON EM.Id=VG.WhomToMeetSourceId
			Left JOIN sHostel.tHostelMaster HM ON HM.Id=VG.HostelId
	WHERE 
			((VG.Id = @rId) OR (@rId = 0))
		--AND ((VG.VisitorName like @rVisitorName) OR (@rVisitorName=''))
		AND (((@rWhomToMeetSourceTypeId =2003 OR(@rWhomToMeetSourceTypeId=0)) AND SM.FirstName like @rVisitorName) 
		OR (ISNULL(@rVisitorName,'')='') OR ((@rWhomToMeetSourceTypeId =95 OR(@rWhomToMeetSourceTypeId=0)) AND EM.FirstName LIKE @rVisitorName) OR (ISNULL(@rVisitorName,'')='') 
		OR ((@rWhomToMeetSourceTypeId =1 OR (@rWhomToMeetSourceTypeId=0)) AND VG.VisitorName LIKE @rVisitorName) OR (ISNULL(@rVisitorName,'')=''))
		AND ((VG.WhomToMeetSourceTypeId=@rWhomToMeetSourceTypeId) OR (@rWhomToMeetSourceTypeId = 0))
		AND (VG.VisitDate>=@rFromVisitDate OR ISNULL(@rFromVisitDate,'')='')
		AND (VG.VisitDate<=@rToVisitDate OR ISNULL(@rToVisitDate,'')='')
		AND ((VG.HostelId = @rHostelId) OR (@rHostelId = 0))
		
		order by  VG.CreatedDateTime desc
END
GO
PRINT N'Altering [sHrm].[pEmployeeForceDelete]...';


GO
 

ALTER PROCEDURE [sHrm].[pEmployeeForceDelete]
	 
           @rEmployeeId bigint,
           @rOrgId smallint 
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	 BEGIN TRY 
	 BEGIN TRANSACTION	
	 
		 --	* FrontOffice * --
		 -- LostFoundRegister
		 DELETE D FROM sFrontOffice.tLostFoundRegister D
		 INNER JOIN sHrm.tEmployeeMaster E  ON D.OwnwerSourceId = E.Id
		 WHERE E.OrgId = @rOrgId AND D.OwnwerSourceId = @rEmployeeId AND D.OwnerSourceTypeId=95
	 
		 --	* Communication * --
		 -- DiscussionGroupMember
		 DELETE D FROM sCommunication.tDiscussionGroupMember D
		 INNER JOIN sHrm.tEmployeeMaster E  ON D.SourceId = E.Id
		 WHERE E.OrgId = @rOrgId AND D.SourceId = @rEmployeeId AND D.SourceTypeId=95
		
		 --	* Academic * --
		 -- TeacherSubjectDivision
		 DELETE D FROM sAcademic.tTeacherSubjectDivision D
		 INNER JOIN sHrm.tEmployeeMaster E  ON D.EmployeeId = E.Id
		 WHERE E.OrgId = @rOrgId AND D.EmployeeId = @rEmployeeId
		 
		 -- LessonPlanResource
		 DELETE D FROM sAcademic.tLessonPlanResource D
		 INNER JOIN sAcademic.tLessonPlan DD ON DD.Id = D.LessonPlanId
		 INNER JOIN sHrm.tEmployeeMaster E  ON DD.EmployeeId = E.Id
		 WHERE E.OrgId = @rOrgId AND DD.EmployeeId = @rEmployeeId
		 
		 -- LessonPlan
		 DELETE D FROM sAcademic.tLessonPlan D
		 INNER JOIN sHrm.tEmployeeMaster E  ON D.EmployeeId = E.Id
		 WHERE E.OrgId = @rOrgId AND D.EmployeeId = @rEmployeeId
		 
		 -- Classwork
		 DELETE D FROM sAcademic.tClasswork D
		 INNER JOIN sHrm.tEmployeeMaster E  ON D.EmployeeId = E.Id
		 WHERE E.OrgId = @rOrgId AND D.EmployeeId = @rEmployeeId
	 
		 --	* Canteen * --
		 -- CanteenIssueDetail
		 DELETE D FROM sCanteen.tCanteenIssueDetail D
		 INNER JOIN sCanteen.tCanteenIssue DD ON DD.Id = D.CanteenIssueId
		 INNER JOIN sHrm.tEmployeeMaster E  ON DD.SourceId = E.Id
		 WHERE E.OrgId = @rOrgId AND DD.SourceId = @rEmployeeId AND DD.SourceTypeId=95
		 
		 -- CanteenIssue
		 DELETE D FROM sCanteen.tCanteenIssue D
		 INNER JOIN sHrm.tEmployeeMaster E  ON D.SourceId = E.Id
		 WHERE E.OrgId = @rOrgId AND D.SourceId = @rEmployeeId AND D.SourceTypeId=95
	 
		 --	* Library * --
		 -- BookLogPenalty
		 DELETE D FROM sLibrary.tBookLogPenalty D
		 INNER JOIN sLibrary.tBookLog DD ON DD.Id = D.BookLogId
		 INNER JOIN sHrm.tEmployeeMaster E  ON DD.ReaderSourceId = E.Id
		 WHERE E.OrgId = @rOrgId AND DD.ReaderSourceId = @rEmployeeId AND DD.ReaderSourceTypeId=95
		 
		 -- BookLog
		 DELETE D FROM sLibrary.tBookLog D
		 INNER JOIN sHrm.tEmployeeMaster E  ON D.ReaderSourceId = E.Id
		 WHERE E.OrgId = @rOrgId AND D.ReaderSourceId = @rEmployeeId AND D.ReaderSourceTypeId=95
	 
	
		
		 --	* TimeTable * --
		 -- AssignTeacher
		 DELETE D FROM sTimetable.tAssignTeacher D
		 INNER JOIN sHrm.tEmployeeMaster E  ON D.EmployeeId = E.Id
		 WHERE E.OrgId = @rOrgId AND D.EmployeeId = @rEmployeeId
		 
		 --	* Hostel * --
		 -- AssignRoom
		 DELETE D FROM sHostel.tAssignRoom D
		 INNER JOIN sHrm.tEmployeeMaster E  ON D.SourceId = E.Id
		 WHERE E.OrgId = @rOrgId AND D.SourceId = @rEmployeeId AND D.SourceTypeId = 95
		 
		 -- HostelWarden
		 DELETE D FROM sHostel.tHostelWarden D
		 INNER JOIN sHrm.tEmployeeMaster E  ON D.EmployeeId = E.Id
		 WHERE E.OrgId = @rOrgId AND D.EmployeeId = @rEmployeeId
		 
		 -- VisitorGatePass
		 DELETE D FROM sHostel.tVisitorGatePass D
		 INNER JOIN sHrm.tEmployeeMaster E  ON D.WhomToMeetSourceId = E.Id
		 WHERE E.OrgId = @rOrgId AND D.WhomToMeetSourceId = @rEmployeeId AND WhomToMeetSourceTypeId = 95
		
		 --	* Activity * --
		 -- ActivityParticipant
		 DELETE D FROM sActivity.tActivityParticipant D
		 INNER JOIN sHrm.tEmployeeMaster E  ON D.SourceId = E.Id
		 WHERE E.OrgId = @rOrgId AND D.SourceId = @rEmployeeId AND D.SourceTypeId = 95
		 
		 --	* Payroll * --
		 
		 -- PayProcessEmployee
		 DELETE D FROM sPayroll.tPayProcessEmployee D
		 INNER JOIN sHrm.tEmployeeMaster E  ON D.EmployeeId = E.Id
		 WHERE E.OrgId = @rOrgId AND D.EmployeeId = @rEmployeeId
	 
		 --	* Leave * --
		 
		 -- Leave
		 DELETE D FROM sHrm.tLeave D
		 INNER JOIN sHrm.tEmployeeMaster E  ON D.EmployeeId = E.Id
		 WHERE E.OrgId = @rOrgId AND D.EmployeeId = @rEmployeeId
		 
		 -- LeaveBalance
		 DELETE D FROM sHrm.tLeaveBalance D
		 INNER JOIN sHrm.tEmployeeMaster E  ON D.EmployeeId = E.Id
		 WHERE E.OrgId = @rOrgId AND D.EmployeeId = @rEmployeeId
		 
		 -- LeaveBalanceAdd
		 DELETE D FROM sHrm.tLeaveBalanceAdd D
		 INNER JOIN sHrm.tEmployeeMaster E  ON D.EmployeeId = E.Id
		 WHERE E.OrgId = @rOrgId AND D.EmployeeId = @rEmployeeId
		
		 --	* Certificate * --
		
		 -- CertificateEmployment
		 DELETE D FROM sHrm.tCertificateEmployment D
		 INNER JOIN sHrm.tEmployeeMaster E  ON D.EmployeeId = E.Id
		 WHERE E.OrgId = @rOrgId AND D.EmployeeId = @rEmployeeId
		 
		 -- CertificateExperience
		 DELETE D FROM sHrm.tCertificateExperience D
		 INNER JOIN sHrm.tEmployeeMaster E  ON D.EmployeeId = E.Id
		 WHERE E.OrgId = @rOrgId AND D.EmployeeId = @rEmployeeId
		 
		 -- CertificateRelieving
		 DELETE D FROM sHrm.tCertificateRelieving D
		 INNER JOIN sHrm.tEmployeeMaster E  ON D.EmployeeId = E.Id
		 WHERE E.OrgId = @rOrgId AND D.EmployeeId = @rEmployeeId
		 
		 
		 --	* Attendance * --
		 
		 -- EmployeeAttendance
		 DELETE D FROM sHrm.tEmployeeAttendance D
		 INNER JOIN sHrm.tEmployeeMaster E  ON D.EmployeeId = E.Id
		 WHERE E.OrgId = @rOrgId AND D.EmployeeId = @rEmployeeId
		
		 -- EmployeeAttendanceRegister
		 DELETE D FROM sHrm.tEmployeeAttendanceRegister D
		 INNER JOIN sHrm.tEmployeeMaster E  ON D.EmployeeId = E.Id
		 WHERE E.OrgId = @rOrgId AND D.EmployeeId = @rEmployeeId
			
			


		 --	* Security * --
		
		 -- UserLog
		 DELETE D FROM sSecurity.tUserLog D
		 INNER JOIN sSecurity.tUser DD ON DD.Id = D.UserId
		 INNER JOIN sHrm.tEmployeeMaster E  ON DD.SourceId = E.Id
		 WHERE E.OrgId = @rOrgId AND DD.SourceId = @rEmployeeId AND DD.SourceTypeId=95
		 
		 -- UserDashboardNotification
		 DELETE D FROM sSecurity.tUserDashboardNotification D
		 INNER JOIN sSecurity.tUser DD ON DD.Id = D.UserId
		 INNER JOIN sHrm.tEmployeeMaster E  ON DD.SourceId = E.Id
		 WHERE E.OrgId = @rOrgId AND DD.SourceId = @rEmployeeId AND DD.SourceTypeId=95
		 
		 -- UserDashlet
		 DELETE D FROM sSecurity.tUserDashlet D
		 INNER JOIN sSecurity.tUser DD ON DD.Id = D.UserId
		 INNER JOIN sHrm.tEmployeeMaster E  ON DD.SourceId = E.Id
		 WHERE E.OrgId = @rOrgId AND DD.SourceId = @rEmployeeId AND DD.SourceTypeId=95

		 -- UserPreference
		 DELETE D FROM sSecurity.tUserPreference D
		 INNER JOIN sSecurity.tUser DD ON DD.Id = D.UserId
		 INNER JOIN sHrm.tEmployeeMaster E  ON DD.SourceId = E.Id
		 WHERE E.OrgId = @rOrgId AND DD.SourceId = @rEmployeeId AND DD.SourceTypeId=95
		 
		 -- UserProfile
		 DELETE D FROM sSecurity.tUserProfile D
		 INNER JOIN sSecurity.tUser DD ON DD.Id = D.UserId
		 INNER JOIN sHrm.tEmployeeMaster E  ON DD.SourceId = E.Id
		 WHERE E.OrgId = @rOrgId AND DD.SourceId = @rEmployeeId AND DD.SourceTypeId=95
		 
		 -- UserOrganization
		 DELETE D FROM sSecurity.tUserOrganization D
		 INNER JOIN sSecurity.tUser DD ON DD.Id = D.UserId
		 INNER JOIN sHrm.tEmployeeMaster E  ON DD.SourceId = E.Id
		 WHERE E.OrgId = @rOrgId AND DD.SourceId = @rEmployeeId AND DD.SourceTypeId=95
		
		 -- UserAccess
		 DELETE D FROM sSecurity.tUserAccess D
		 INNER JOIN sSecurity.tUser DD ON DD.Id = D.UserId
		 INNER JOIN sHrm.tEmployeeMaster E  ON DD.SourceId = E.Id
		 WHERE E.OrgId = @rOrgId AND DD.SourceId = @rEmployeeId AND DD.SourceTypeId=95

		 -- User
		 DELETE D FROM sSecurity.tUser D
		 INNER JOIN sHrm.tEmployeeMaster E  ON D.SourceId = E.Id
		 WHERE E.OrgId = @rOrgId AND D.SourceId = @rEmployeeId AND D.SourceTypeId=95

      
		 
		 
		 	 --	* Setup * --
		 -- Update DivisionMaster
		 UPDATE sSetup.tDivisionMaster SET InchargeEmployeeId = 0 WHERE InchargeEmployeeId = @rEmployeeId
		 
		
				 --	* Employee * --		
		
		 -- EmployeeJobDetail
		 DELETE D FROM  sHrm.tEmployeeJobDetail D
		 INNER JOIN sHrm.tEmployeeMaster E  ON D.EmployeeId = E.Id
		 WHERE E.OrgId = @rOrgId AND D.EmployeeId = @rEmployeeId
		 		 
		 -- EmployeeImages
		 DELETE D FROM sHrm.tEmployeeImages D
		 INNER JOIN sHrm.tEmployeeMaster E  ON D.EmployeeId = E.Id
		 WHERE E.OrgId = @rOrgId AND D.EmployeeId =@rEmployeeId
		 
		 -- EmployeeFamilyDetails
		 DELETE D FROM sHrm.tEmployeeFamilyDetails D
		 INNER JOIN sHrm.tEmployeeMaster E  ON D.EmployeeId = E.Id
		 WHERE E.OrgId = @rOrgId  AND D.EmployeeId = @rEmployeeId
		 
		 -- EmployeeCommunications
		 DELETE D FROM sHrm.tEmployeeCommunications D
		 INNER JOIN sHrm.tEmployeeMaster E  ON D.EmployeeId = E.Id
		 WHERE E.OrgId = @rOrgId AND D.EmployeeId =@rEmployeeId
		 
		 -- EmployeePersonalDetail
		 DELETE D FROM sHrm.tEmployeePersonalDetail D
		 INNER JOIN sHrm.tEmployeeMaster E  ON D.EmployeeId = E.Id
		 WHERE E.OrgId = @rOrgId  AND D.EmployeeId=@rEmployeeId
		 
		 -- EmployeePreviousEmployment
		 DELETE D FROM sHrm.tEmployeePreviousEmployment D
		 INNER JOIN sHrm.tEmployeeMaster E  ON D.EmployeeId = E.Id
		 WHERE E.OrgId = @rOrgId  AND D.EmployeeId =@rEmployeeId
		 
		 -- EmployeeQualification
	     DELETE D FROM sHrm.tEmployeeQualification D
		 INNER JOIN sHrm.tEmployeeMaster E  ON D.EmployeeId = E.Id
		 WHERE E.OrgId = @rOrgId AND D.EmployeeId=@rEmployeeId
		 
		 -- EmployeeStatutoryAndOther
		 DELETE D FROM sHrm.tEmployeeStatutoryAndOther D
		 INNER JOIN sHrm.tEmployeeMaster E  ON D.EmployeeId = E.Id
		 WHERE E.OrgId = @rOrgId AND D.EmployeeId =@rEmployeeId 
		 
		    -- EmployeeMaster
		 DELETE E FROM sHrm.tEmployeeMaster E WHERE E.OrgID = @rOrgId AND E.Id =@rEmployeeId
		 
		 SELECT 1 AS Result
 
	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sHrm].[pEmployeeProfileFullGet]...';


GO
ALTER PROCEDURE [sHrm].[pEmployeeProfileFullGet]
	 
	 @rEmployeeId bigint,
	
	--newly added parameter for report 
	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='',
	@rReportId smallint = 0,
	@rOrgId smallint = 0,
	@rStrEmployeeId nvarchar(max)='',
	@rEmployeeTypeId [int] =0,
	@rDepartmentId [int]= 0,
	@rGradeId [int]= 0,
	@rGenderId [int]= 0,	
	@rDesignationId [int]= 0,	
	@rAgeFrom nvarchar(10)='',
	@rAgeTo nvarchar(10)='',
	@rEmployeeCode nvarchar(50)='',
	@rEmployeeGroupId smallint= 0,
	@rEmployeeStatusId smallint=0
	
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 
	
SELECT 
		 --Personal Details
		 EM.Id,
		 EM.Code,
		 ISNULL(EM.FirstName,'') + ' ' + ISNULL(EM.MiddleName,'') + ' ' + ISNULL(EM.LastName,'') AS EmployeeName,
		 ISNULL(EP.UIDNumber,'') AS UIDNumber,
		 ISNULL(EP.DateOfBirth,'') AS DateOfBirth,
		 ISNULL(GM.Title,'') AS Gender,
		 ISNULL(MM.Title,'') AS MeritalStatus,
		 ISNULL(BGM.Title,'') AS BloodGroup,
		 ISNULL(EP.Qualification,'') AS Qualification,
		 ISNULL(EP.FamilyCast,'') AS FamilyCast,
		 
		 --Communication
		 ISNULL(EC.PresentStreetOne,'')+' '+ISNULL(EC.PresentStreetTwo,'')+' '+ISNULL(EC.PresentStreetThree,'') AS PresentAddress,
		 ISNULL(EC.PresentCity,'') AS PresentCity,
		ISNULL(EC.PresentState,'') AS PresentState,
		ISNULL(EC.PresentCountry,'') AS PresentCountry,
		ISNULL(EC.PresentZipCode,'') AS PresentZipCode,
		ISNULL(EC.PresentContactNo,'') AS PresentContactNo,
		
		ISNULL(EC.PermanentStreetOne,'')+' '+ISNULL(EC.PermanentStreetTwo,'')+' '+ISNULL(EC.PermanentStreetThree,'') AS PermanentAddress,
		ISNULL(EC.PermanentCity,'') AS PermanentCity,
		ISNULL(EC.PermanentState,'') AS PermanentState,
		ISNULL(EC.PermanentCountry,'') AS PermanentCountry,
		ISNULL(EC.PermanentZipCode,'') AS PermanentZipCode,
		ISNULL(EC.PermanentContactNo,'') AS PermanentContactNo,
		 
		 ISNULL(EC.EmergencyStreetOne,'')+' '+ISNULL(EC.EmergencyStreetTwo,'')+' '+ISNULL(EC.EmergencyStreetThree,'') AS EmergencyAddress,
		ISNULL(EC.EmergencyCity,'') AS EmergencyCity,
		ISNULL(EC.EmergencyState,'') AS EmergencyState,
		ISNULL(EC.EmergencyCountry,'') AS EmergencyCountry,
		ISNULL(EC.EmergencyZipCode,'') AS EmergencyZipCode,
		ISNULL(EC.EmergencyContactNo,'') AS EmergencyContactNo,
		
		--Job Details
		ISNULL(EJ.DateOfJoining,'') AS DateOfJoining,		
		(COALESCE(CAST(EJ.DateOfleaving AS NVARCHAR(23)),'')) AS DateOfleaving,
		ISNULL(EJ.JobRemark,'') AS JobRemark,
		ISNULL(EJ.ReferenceRemark,'') AS ReferenceRemark,
		ISNULL(EDM.Title,'') AS EmployeeDesignation,
		ISNULL(DM.Title,'') AS OrganizationDepartment,
		ISNULL(EGM.Title,'') AS EmployeeGrade,
		ISNULL(GrpM.Title,'') AS EmployeeGroup,
		ISNULL(ETM.Title,'') AS EmployeeType,
		
		----Previous Employment
		--ISNULL(EPE.CompanyName,'') AS PrevCompanyName,
		--ISNULL(EPE.Designation,'') AS PrevDesignation,
		--ISNULL(EPE.Duration,'') AS Duration,
		--ISNULL(EPE.LastSalary,0) AS LastSalary,
		--ISNULL(EPE.ReasonForLeaving,'') AS ReasonForLeaving,
		--ISNULL(EPE.JobDescription,'') AS JobDescription,
		
		--Notification Details
		ISNULL(EC.PersonalEmail,'') As PersonalEmail,
		ISNULL(EC.MobileNumber,'') AS MobileNumber,
		ISNULL(EC.PhoneNoCompany,'') AS PhoneNoCompany,
		ISNULL(EC.ExtensionNo,'') AS ExtensionNo,
		ISNULL(EC.CompanyEmail,'') AS CompanyEmail,
		
		EI.EmployeePhoto,
		--ISNULL(EI.EmployeePhoto, CONVERT(VARBINARY(MAX), 0)) AS EmployeePhoto,
		ISNULL(ESO.AccountNumber,'') AS AccountNumber,
		ISNULL(ESO.BankName,'') AS BankName,
		ISNULL(ESO.Branch,'') AS BankBranch,
		ISNULL(ESO.PanNumber,'') AS PanNumber,
		ISNULL(ESO.EPFNumber,'') AS EPFNumber,
		ISNULL(ESO.IncrementDate,'') AS IncrementDate,
		ISNULL(ESO.BasicPay,0) AS BasicPay,
		ISNULL(EFD.Occupation,'') AS Occupation,
		convert(nvarchar(20),EM.Id) AS EmployeeIdText,
		convert(nvarchar(20),@rOrgId) AS OrgIdText,
		ISNULL(EJ.OrganizationDepartmentId,0) AS DepartmentId,
		OM.DisplayTitle AS OrgTitle
		
		      
  FROM 
		sHrm.tEmployeeMaster EM 
		LEFT JOIN sHrm.tEmployeeCommunications EC ON EM.ID = EC.EmployeeId
		INNER JOIN sHrm.tEmployeeJobDetail EJ ON EJ.EmployeeId = EM.Id
		INNER JOIN sHrm.tEmployeePersonalDetail EP ON EP.EmployeeId = EM.ID		
		--INNER JOIN sHrm.tEmployeePreviousEmployment EPE ON EPE.EmployeeId=EM.ID
		LEFT JOIN sCommon.tBloodGroupMaster BGM ON BGM.Id = EP.BloodGroupId    
		LEFT JOIN sCommon.tGenderMaster GM ON GM.Id = EP.GenderId
		LEFT JOIN sCommon.tMaritalStatusMaster MM ON MM.Id =  EP.MaritalstatusId
		--LEFT JOIN sCommon.tReligionMaster RM ON RM.Id=EJ.ReligionId
		LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = EM.Id
		LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.ID = EJ.EmployeeDesignationId
		LEFT JOIN sSetup.tDepartmentMaster DM ON DM.Id = EJ.OrganizationDepartmentId
		LEFT JOIN sHrm.tEmployeeTypeMaster ETM ON ETM.Id=EJ.EmployeeTypeId
		LEFT JOIN sHrm.tEmployeeGradeMaster EGM ON EGM.Id=EJ.EmployeeGradeId
		LEFT JOIN sHrm.tEmployeeGroupMaster GrpM ON GrpM.Id=EJ.EmployeeGroupId
		LEFT JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.EmployeeId = EM.Id
		LEFT JOIN sHrm.tEmployeeFamilyDetails EFD ON EFD.EmployeeId = EM.Id
		INNER JOIN sSetup.tOrganizationMaster OM 
			ON OM.Id=EM.OrgId  
  WHERE 
			(EM.Id=@rEmployeeId OR @rEmployeeId = 0)
			AND (ISNULL(EM.Id,0) NOT IN( SELECT cast(item as bigint) FROM  sCommon.fnsplit(@rStrEmployeeId,',')) OR @rStrEmployeeId='') 
			AND ((EM.Code LIKE @rEmployeeCode)OR @rEmployeeCode = '' )
			AND (ETM.Id = @rEmployeeTypeId OR @rEmployeeTypeId = 0)
			AND (DM.Id = @rDepartmentId OR @rDepartmentId = 0)
			AND (EM.StatusId = @rEmployeeStatusId OR @rEmployeeStatusId = 0)
			AND (GrpM.Id=@rEmployeeGroupId OR @rEmployeeGroupId=0) 
			AND (EGM.Id = @rGradeId OR @rGradeId = 0)
			AND (EDM.Id = @rDesignationId OR @rDesignationId = 0)
			AND (GM.Id = @rGenderId OR @rGenderId = 0)
			AND ((DATEDIFF(yy,EP.DateOfBirth,GETDATE()) <= @rAgeTo) OR (ISNULL(@rAgeTo,0)=0))
			AND ((DATEDIFF(yy,EP.DateOfBirth,GETDATE()) >= @rAgeFrom)OR (ISNULL(@rAgeFrom,0)=0))
			AND  ( EM.OrgId = @rOrgId OR @rOrgId = 0)
			
			 
END
GO
PRINT N'Altering [sLibrary].[pBookLogGet]...';


GO
ALTER PROCEDURE [sLibrary].[pBookLogGet]
	 @rBookLogId bigint,
	 @rResourceSourceId bigint,
	 @rStatusId smallint,
	 @rIscurrentStatus bit,
	 @rOrgId smallint,
	 @rBatchId int,
	 @rLibraryId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 	
	SELECT 
			BL.Id AS BookLogId,
			BL.ReaderSourceTypeId,
			BL.ReaderSourceId,
			SA.Code AS ReaderCode,
			SA.Name AS ReaderName,
			SA.ClassName+'-'+SA.DivisionName AS ClassDept,
			SA.ClassId As SourceId,
			BL.ResourceSourceTypeId,
			BL.ResourceSourceId,
			BM.Code AS ResourceCode,
			BM.Title AS ResourceName,
			BL.LogDate,
			BL.DueDate,
			BL.StatusId,
			BL.Remark,
			BL.IsCurrentStatus,
			IS1.PenaltyPerDay,
			BL.OrgId,
			BL.BatchId,
			ISNULL(BL.ReturnDate,'') AS ReturnDate
	FROM 
			sLibrary.tBookLog BL
			INNER JOIN sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId
			INNER JOIN sStudent.vStudentLastAcademic SA ON SA.StudentId=BL.ReaderSourceId AND BL.ReaderSourceTypeId=2003 
			INNER JOIN sLibrary.tIssueSetting IS1 ON IS1.SourceId=SA.ClassId AND IS1.SourceTypeId = 2005
	WHERE 
			((BL.ResourceSourceId=@rResourceSourceId) OR (@rResourceSourceId=0))
		AND ((BL.Id=@rBookLogId) OR (@rBookLogId=0))
		AND ((BL.IsCurrentStatus=@rIscurrentStatus) OR (@rIscurrentStatus=0))
		AND ((BL.StatusId=@rStatusId) OR (@rStatusId=0))
		AND ((BL.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((BL.BatchId=@rBatchId) OR (@rBatchId=0))
		AND (BL.LibraryId=@rLibraryId)
	
	UNION ALL
	
	SELECT 
			BL.Id AS BookLogId,
			BL.ReaderSourceTypeId,
			BL.ReaderSourceId,
			EM.Code AS ReaderCode,
			EM.FirstName+' '+EM.LastName AS ReaderName,
			ODM.Title as ClassDept,
			ODM.Id AS SourceId,
			BL.ResourceSourceTypeId,
			BL.ResourceSourceId,
			BM.Code AS ResourceCode,
			BM.Title AS ResourceName,
			BL.LogDate,
			BL.DueDate,
			BL.StatusId,
			BL.Remark,
			BL.IsCurrentStatus,
			IS1.PenaltyPerDay,
			BL.OrgId,
			BL.BatchId,
			ISNULL(BL.ReturnDate,'') AS ReturnDate
	FROM 
			sLibrary.tBookLog BL
			INNER JOIN sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id=BL.ReaderSourceId AND BL.ReaderSourceTypeId=95
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id = EJD.EmployeeId
			INNER JOIN sSetup.tDepartmentMaster ODM ON ODM.Id = EJD.OrganizationDepartmentId
			INNER JOIN sLibrary.tIssueSetting IS1 ON IS1.SourceId=ODM.Id AND IS1.SourceTypeId = 2004
	WHERE 
			((BL.ResourceSourceId=@rResourceSourceId) OR (@rResourceSourceId=0))
		AND ((BL.Id=@rBookLogId) OR (@rBookLogId=0))
		AND ((BL.IsCurrentStatus=@rIscurrentStatus) OR (@rIscurrentStatus=0))
		AND ((BL.StatusId=@rStatusId) OR (@rStatusId=0))
		AND ((BL.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((BL.BatchId=@rBatchId) OR (@rBatchId=0))
		AND (BL.LibraryId=@rLibraryId)
END
GO
PRINT N'Altering [sLibrary].[pBulkBookLogListGet]...';


GO
ALTER PROCEDURE [sLibrary].[pBulkBookLogListGet]
	 
	 @rReaderSourceTypeId smallint,
	 @rReaderCode nvarchar(20),
	 @rReaderName nvarchar(200),
	 @rResourceCode nvarchar(25),
	 @rResourceName nvarchar(100),
	 @rFromDate date,
	 @rToDate date,
	 @rStatusId int,
	 @rOrgId smallint,
	 @rBatchId int,
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='',
	 @rLibraryId int,
	 @rIsCurrentStatus bit,
	 @rOrgGroupBatchId int = 0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			
BEGIN 	
		SET @rReaderCode = sCommon.fSearchStringGet(@rReaderCode)
		SET @rReaderName = sCommon.fSearchStringGet(@rReaderName)
		SET @rResourceCode = sCommon.fSearchStringGet(@rResourceCode)
		SET @rResourceName = sCommon.fSearchStringGet(@rResourceName)
		
	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			BL.Id AS BookLogId,
			'Student' AS ReaderSourceType,
			ISNULL(BL.ReaderSourceTypeId,0) AS ReaderSourceTypeId,
			ISNULL(BL.ReaderSourceId,0) AS ReaderSourceId,
			SA.Code AS ReaderCode,
			SA.Name AS ReaderName,
			SA.ClassName+'-'+SA.DivisionName AS ClassDept,
			BL.ResourceSourceTypeId,
			BL.ResourceSourceId,
			BM.Code AS ResourceCode,
			BM.Title AS ResourceName,
			BL.LogDate,
			BL.DueDate,
			BL.StatusId,
			SM.Title AS StatusName,
			CASE WHEN BL.StatusId = 521 AND ISNULL(BL.UpdatedUserId,0)!=1 Then 'Return' WHEN BL.StatusId = 521 AND ISNULL(BL.UpdatedUserId,0)=1 Then 'Release' ELSE SM.Title END AS TransactionStatus,
			BL.IsCurrentStatus,
			BL.CreatedDateTime
	FROM 
			sLibrary.tBookLog BL
			INNER JOIN sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId
			INNER JOIN sStudent.vStudentLastAcademic SA ON SA.StudentId=BL.ReaderSourceId AND BL.ReaderSourceTypeId=2003 
			AND SA.BatchId = BL.BatchId
			--AND SA.IsActiveBatch = 1
			INNER JOIN sCommon.tStatusMaster SM ON SM.Id=BL.StatusId
	WHERE 
			(BL.ReaderSourceTypeId=@rReaderSourceTypeId OR @rReaderSourceTypeId=0)
		AND ((SA.Code Like @rReaderCode) OR (ISNULL(@rReaderCode,'') = ''))
		AND ((SA.Name Like @rReaderName) OR (ISNULL(@rReaderName,'') = ''))
		AND ((BM.Code Like @rResourceCode) OR (ISNULL(@rResourceCode,'') = ''))
		AND ((BM.Title Like @rResourceName) OR (ISNULL(@rResourceName,'') = ''))
		AND ((BL.LogDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((BL.LogDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		AND ((BL.StatusId = @rStatusId) OR (ISNULL(@rStatusId,0) = 0))
		AND ((BL.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((BL.BatchId=@rBatchId) OR (@rBatchId=0))
		AND (BL.LibraryId=@rLibraryId)
		--AND ((BL.BatchId=@rBatchId) OR (@rBatchId=0))
		

	UNION

	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			BL.Id AS BookLogId,
			'Employee' AS ReaderSourceType,
			ISNULL(BL.ReaderSourceTypeId,0) AS ReaderSourceTypeId,
			ISNULL(BL.ReaderSourceId,0) AS ReaderSourceId,
			EM.Code AS ReaderCode,
			EM.FirstName+' '+EM.LastName AS ReaderName,
			ODM.Title as ClassDept,
			BL.ResourceSourceTypeId,
			BL.ResourceSourceId,
			BM.Code AS ResourceCode,
			BM.Title AS ResourceName,
			BL.LogDate,
			BL.DueDate,
			BL.StatusId,
			SM.Title AS StatusName,
			CASE WHEN BL.StatusId = 521 AND ISNULL(BL.UpdatedUserId,0)!=1 Then 'Return' WHEN BL.StatusId = 521 AND ISNULL(BL.UpdatedUserId,0)=1 Then 'Release' ELSE SM.Title END AS TransactionStatus,
			BL.IsCurrentStatus,
			BL.CreatedDateTime 
	FROM 
			sLibrary.tBookLog BL
			INNER JOIN sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id=BL.ReaderSourceId AND BL.ReaderSourceTypeId=95
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id = EJD.EmployeeId
			INNER JOIN sSetup.tDepartmentMaster ODM ON ODM.Id = EJD.OrganizationDepartmentId
			INNER JOIN sCommon.tStatusMaster SM ON SM.Id=BL.StatusId
	WHERE 
			(BL.ReaderSourceTypeId=@rReaderSourceTypeId OR @rReaderSourceTypeId=0)
		AND ((EM.Code Like @rReaderCode) OR (ISNULL(@rReaderCode,'') = ''))
		AND ((EM.FirstName+' '+EM.LastName Like @rReaderName) OR (ISNULL(@rReaderName,'') = ''))
		AND ((BM.Code Like @rResourceCode) OR (ISNULL(@rResourceCode,'') = ''))
		AND ((BM.Title Like @rResourceName) OR (ISNULL(@rResourceName,'') = ''))
		AND ((BL.LogDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((BL.LogDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		AND ((BL.StatusId = @rStatusId) OR (ISNULL(@rStatusId,0) = 0))
		AND ((BL.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((BL.BatchId=@rBatchId) OR (@rBatchId=0))
		AND (BL.LibraryId=@rLibraryId)

	UNION 

	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			BL.Id AS BookLogId,
			'' AS ReaderSourceType,
			0 AS ReaderSourceTypeId,
			0 AS ReaderSourceId,
			'' AS ReaderCode,
			'' AS ReaderName,
			'' as ClassDept,
			BL.ResourceSourceTypeId,
			BL.ResourceSourceId,
			BM.Code AS ResourceCode,
			BM.Title AS ResourceName,
			BL.LogDate,
			BL.DueDate,
			BL.StatusId,
			SM.Title AS StatusName,
			SM.Title AS TransactionStatus,
			BL.IsCurrentStatus,
			BL.CreatedDateTime
	FROM 
			sLibrary.tBookLog BL
			INNER JOIN sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId
			INNER JOIN sCommon.tStatusMaster SM ON SM.Id=BL.StatusId
	WHERE 
			(ISNULL(BL.ReaderSourceTypeId,0)=@rReaderSourceTypeId AND @rReaderSourceTypeId=0)
		AND (('' Like @rReaderCode) OR (ISNULL(@rReaderCode,'') = ''))
		AND (('' Like @rReaderName) OR (ISNULL(@rReaderName,'') = ''))
		AND ((BM.Code Like @rResourceCode) OR (ISNULL(@rResourceCode,'') = ''))
		AND ((BM.Title Like @rResourceName) OR (ISNULL(@rResourceName,'') = ''))
		AND ((BL.LogDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((BL.LogDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		AND ((BL.StatusId = @rStatusId) OR (ISNULL(@rStatusId,0) = 0))
		AND ((BL.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((BL.BatchId=@rBatchId) OR (@rBatchId=0))
		AND (BL.LibraryId=@rLibraryId)
END
GO
PRINT N'Altering [sLibrary].[pIssueSettingDetailGet]...';


GO
ALTER PROCEDURE [sLibrary].[pIssueSettingDetailGet]
	 @rReaderSourceTypeId smallint,
	 @rReaderSourceId bigint,
	 @rOrgId smallint,
	 @rBatchId int
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	IF (@rReaderSourceTypeId = 2003)
	BEGIN
	SELECT 	
			ISNULL(IS1.NoOfBookIssuable,0) AS NoOfBookIssuable,
		    ISNULL(IS1.IssueDays,0) AS IssueDays,
		    ISNULL(IS1.PenaltyPerDay,0) AS PenaltyPerDay,
		    ISNULL(IS1.ReserveDays,0) AS ReserveDays
  FROM 
				sStudent.vStudentLastAcademic SA
            INNER JOIN sLibrary.tIssueSetting IS1 ON IS1.SourceId=SA.ClassId AND IS1.SourceTypeId=2005
  WHERE
			((SA.StudentId=@rReaderSourceId) OR (@rReaderSourceId=0))
		AND SA.OrgId=@rOrgId
		AND SA.BatchId=@rBatchId	
		
	END
	ELSE IF (@rReaderSourceTypeId = 95)
	BEGIN		
	SELECT 
			ISNULL(IS1.NoOfBookIssuable,0) AS NoOfBookIssuable,
		    ISNULL(IS1.IssueDays,0) AS IssueDays,
		    ISNULL(IS1.PenaltyPerDay,0) AS PenaltyPerDay,
		    ISNULL(IS1.ReserveDays,0) AS ReserveDays
  FROM 
				sHrm.tEmployeeMaster EM 
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.Id
			INNER JOIN sSetup.tDepartmentMaster ODM ON ODM.Id=EJD.OrganizationDepartmentId
            INNER JOIN sLibrary.tIssueSetting IS1 ON IS1.SourceId=ODM.Id AND IS1.SourceTypeId=2004
  WHERE
			((EM.Id=@rReaderSourceId) OR (@rReaderSourceId=0))
		AND ODM.OrgId=@rOrgId
	END
END
GO
PRINT N'Altering [sLibrary].[pLibraryAttendanceGet]...';


GO


ALTER PROCEDURE [sLibrary].[pLibraryAttendanceGet]
          
           @rId bigint,
           @rLibraryId int,
           @rSourceTypeId smallint,
           @rName nvarchar(200),
           @rCode nvarchar(20),
           @rFromAttendanceDate date,
           @rToAttendanceDate date,
           @rOrgGroupBatchId int,
           @rOrgId int=0
           
AS
SET NOCOUNT ON
			SET @rName = sCommon.fSearchStringGet(@rName)
			SET @rCode = sCommon.fSearchStringGet(@rCode)
BEGIN
SELECT   
	   LA.Id AS LibraryAttendanceId,
	   LA.LibraryId,
	   
		(CASE WHEN LA.SourceTypeId = 95 THEN	'Employee'
			 WHEN LA.SourceTypeId = 2003 THEN	'Student'
			 ELSE 'Other' END) AS TypeName,

		(CASE WHEN LA.SourceTypeId = 95 THEN Emp.EmployeeName
			WHEN LA.SourceTypeId = 2003 THEN vSF.Name
			ELSE
			ISNULL(LA.GuestName,'') 
			END) AS Name,
			
		(CASE WHEN LA.SourceTypeId = 95 THEN Emp.DepartmentName
			WHEN LA.SourceTypeId = 2003 THEN DM.Title
			ELSE '' END) AS DepartmentName,		 	
		 
		(CASE WHEN LA.SourceTypeId = 95 THEN	Emp.Code
			 WHEN LA.SourceTypeId = 2003 THEN	vSF.Code
			 ELSE '' END) AS Code, 	
			
		(CASE WHEN LA.SourceTypeId = 95 THEN Emp.DepartmentName
			WHEN LA.SourceTypeId = 2003 THEN (vSF.ClassName + ' - '+ vSF.DivisionName)
			ELSE '' END) AS ClassDepartmentName,	
			 	 
	   LA.SourceId,
	   LA.SourceTypeId,
	   LA.GuestName,
	   LA.AttendanceDate,
	   LA.InTime,
	   LA.OutTime,
	   LA.Remark,
	   (CASE WHEN LA.OutTime = Convert(time,'00:00:00') THEN ''
		ELSE convert(varchar(5),DateDiff(SECOND, LA.InTime, LA.OutTime)/3600)+
		':'+convert(varchar(5),DateDiff(SECOND, LA.InTime, LA.OutTime)%3600/60)+
		':'+convert(varchar(5),(DateDiff(SECOND, LA.InTime, LA.OutTime)%60))
		END) AS TotalTime,
		ISNULL(OM.Id,0) AS OrgId,
		ISNULL(OM.DisplayTitle,'') AS OrgName
	   
  FROM  sLibrary.tLibraryAttendance LA
		LEFT JOIN sHrm.vExtEmployeeMaster Emp
			ON Emp.Id = LA.SourceId AND LA.SourceTypeId = 95 
				--AND(((Emp.Code like @rCode) OR (ISNULL(@rCode,'') = '')) AND @rSourceTypeId = 95  )
				--AND(((Emp.EmployeeName like @rName) OR (ISNULL(@rName,'') = '')) AND @rSourceTypeId = 95 )
				
		LEFT JOIN sStudent.vStudentLastAcademic vSF
			ON vSF.StudentId = LA.SourceId AND LA.SourceTypeId = 2003 
				--AND(((vSF.Code like @rCode) OR (ISNULL(@rCode,'') = '')) AND @rSourceTypeId = 2003)
				--AND(((vSF.Name like @rName) OR (ISNULL(@rName,'') = '')) AND @rSourceTypeId = 2003)
				--AND(vSF.BatchId= @rBatchId)
		LEFT JOIN sSetup.tDepartmentMaster DM ON DM.Id = vSF.DepartmentId		
		LEFT JOIN sSetup.tOrganizationMaster OM ON ((OM.Id = Emp.OrgId) OR (OM.Id = vSF.OrgId))
  WHERE 
  
	LA.LibraryId=@rLibraryId
	AND LA.OrgGroupBatchId=@rOrgGroupBatchId
	AND ((LA.Id=@rId) OR (@rId=0))
	AND ((OM.Id=@rOrgId) OR (@rOrgId=0))
	AND ((LA.SourceTypeId=@rSourceTypeId) OR (@rSourceTypeId=0))
	AND (((@rSourceTypeId =2003 OR(@rSourceTypeId=0)) AND vSF.Name like @rName) 
		OR (ISNULL(@rName,'')='') OR ((@rSourceTypeId =95 OR(@rSourceTypeId=0)) AND Emp.EmployeeName LIKE @rName) OR (ISNULL(@rName,'')='') 
		OR ((@rSourceTypeId =1 OR (@rSourceTypeId=0)) AND LA.GuestName LIKE @rName) OR (ISNULL(@rName,'')=''))
    AND (((@rSourceTypeId =2003 OR(@rSourceTypeId=0)) AND vSF.Code LIKE @rCode) OR (ISNULL(@rCode,'')='') 
        OR ((@rSourceTypeId =95 OR(@rSourceTypeId=0)) AND Emp.Code LIKE @rCode) OR (ISNULL(@rCode,'')=''))
	AND (LA.AttendanceDate>=@rFromAttendanceDate OR ISNULL(@rFromAttendanceDate,'')='')
	AND (LA.AttendanceDate<=@rToAttendanceDate OR ISNULL(@rToAttendanceDate,'')='')
    ORDER BY LA.AttendanceDate,LA.InTime DESC
	
END
GO
PRINT N'Altering [sLibrary].[pMyBookLogListGet]...';


GO
ALTER PROCEDURE [sLibrary].[pMyBookLogListGet]
	 @rReaderSourceTypeId smallint,
	 @rReaderSourceId bigint,
	 @rOrgId smallint,
	 @rBatchId int,
	 @rLibraryId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 	
If(@rReaderSourceTypeId=2003)
BEGIN
	SELECT 
			BL.Id AS BookLogId,
			BM.Code AS ResourceCode,
			BM.Title AS ResourceName,
			BL.LogDate,
			BL.DueDate,
			IS1.NoOfBookIssuable,
			BL.StatusId 
	FROM 
			sLibrary.tBookLog BL
			INNER JOIN sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId
			INNER JOIN sStudent.vStudentLastAcademic SA ON SA.StudentId=BL.ReaderSourceId
			INNER JOIN sLibrary.tIssueSetting IS1 ON IS1.SourceId=SA.ClassId AND IS1.SourceTypeId=2005
	WHERE 
			((BL.ReaderSourceTypeId=@rReaderSourceTypeId) OR (@rReaderSourceTypeId=0))
		AND (BL.ReaderSourceId=@rReaderSourceId)
		AND BL.IsCurrentStatus=1
		AND ((BL.StatusId=522) OR (BL.StatusId=523))
		AND (BL.OrgId=@rOrgId)
		AND (BL.BatchId=@rBatchId)
		AND (BL.LibraryId=@rLibraryId)
END
ELSE If(@rReaderSourceTypeId=95)
BEGIN
	SELECT 
			BL.Id AS BookLogId,
			BM.Code AS ResourceCode,
			BM.Title AS ResourceName,
			BL.LogDate,
			BL.DueDate,
			IS1.NoOfBookIssuable,
			BL.StatusId   
	FROM 
			sLibrary.tBookLog BL
			INNER JOIN sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id=BL.ReaderSourceId	
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id = EJD.EmployeeId
			INNER JOIN sSetup.tDepartmentMaster ODM ON ODM.Id = EJD.OrganizationDepartmentId
			INNER JOIN sLibrary.tIssueSetting IS1 ON IS1.SourceId=ODM.Id AND IS1.SourceTypeId=2004
	WHERE 
			((BL.ReaderSourceTypeId=@rReaderSourceTypeId) OR (@rReaderSourceTypeId=0))
		AND (BL.ReaderSourceId=@rReaderSourceId)
		AND BL.IsCurrentStatus=1
		AND ((BL.StatusId=522) OR (BL.StatusId=523))
		AND (BL.OrgId=@rOrgId)
		AND (BL.BatchId=@rBatchId)
		AND (BL.LibraryId=@rLibraryId)
END
END
GO
PRINT N'Altering [sLibrary].[pReaderBookLogListGet]...';


GO
ALTER PROCEDURE [sLibrary].[pReaderBookLogListGet]
	 @rReaderSourceTypeId smallint,
	 @rReaderSourceId bigint,
	 @rOrgId smallint,
	 @rBatchId int,
	 @rLibraryId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 	
If(@rReaderSourceTypeId=2003)
BEGIN
	SELECT 
			BL.Id AS BookLogId,
			BM.Code AS ResourceCode,
			BM.Title AS ResourceName,
			BL.LogDate,
			BL.DueDate,
			IS1.NoOfBookIssuable,
			BL.StatusId 
	FROM 
			sLibrary.tBookLog BL
			INNER JOIN sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId
			INNER JOIN sStudent.vStudentLastAcademic SA ON SA.StudentId=BL.ReaderSourceId
			INNER JOIN sLibrary.tIssueSetting IS1 ON IS1.SourceId=SA.ClassId AND IS1.SourceTypeId=2005
	WHERE 
			((BL.ReaderSourceTypeId=@rReaderSourceTypeId) OR (@rReaderSourceTypeId=0))
		AND (BL.ReaderSourceId=@rReaderSourceId)
		AND BL.IsCurrentStatus=1
		AND ((BL.StatusId=522) OR (BL.StatusId=523))
		AND (BL.OrgId=@rOrgId)
		AND (BL.BatchId=@rBatchId)
		--AND  SA.IsActiveBatch = 1
		AND (BL.LibraryId=@rLibraryId)
END
ELSE If(@rReaderSourceTypeId=95)
BEGIN
	SELECT 
			BL.Id AS BookLogId,
			BM.Code AS ResourceCode,
			BM.Title AS ResourceName,
			BL.LogDate,
			BL.DueDate,
			IS1.NoOfBookIssuable,
			BL.StatusId   
	FROM 
			sLibrary.tBookLog BL
			INNER JOIN sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id=BL.ReaderSourceId	
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id = EJD.EmployeeId
			INNER JOIN sSetup.tDepartmentMaster ODM ON ODM.Id = EJD.OrganizationDepartmentId
			INNER JOIN sLibrary.tIssueSetting IS1 ON IS1.SourceId=ODM.Id AND IS1.SourceTypeId=2004
	WHERE 
			((BL.ReaderSourceTypeId=@rReaderSourceTypeId) OR (@rReaderSourceTypeId=0))
		AND (BL.ReaderSourceId=@rReaderSourceId)
		AND BL.IsCurrentStatus=1
		AND ((BL.StatusId=522) OR (BL.StatusId=523))
		AND (BL.OrgId=@rOrgId)
		AND (BL.BatchId=@rBatchId)
		AND (BL.LibraryId=@rLibraryId)
END
END
GO
PRINT N'Altering [sLibrary].[pReturnDueListGet]...';


GO

ALTER PROCEDURE [sLibrary].[pReturnDueListGet]
	 @rReaderSourceTypeId smallint,
	 @rReaderCode nvarchar(20),
	 @rReaderName nvarchar(200),
	 @rResourceCode nvarchar(25),
	 @rResourceName nvarchar(100),
	 @rDueDate date,
	 @rOrgId smallint,
	 @rBatchId int,
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='',
	 @rLibraryId int,
	 @rOrgGroupId int=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			
BEGIN 	
		
		SET @rReaderCode = sCommon.fSearchStringGet(@rReaderCode)
		SET @rReaderName = sCommon.fSearchStringGet(@rReaderName)
		SET @rResourceCode = sCommon.fSearchStringGet(@rResourceCode)
		SET @rResourceName = sCommon.fSearchStringGet(@rResourceName)
		
	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			BL.Id AS BookLogId,
			'Student' AS ReaderSourceType,
			ISNULL(BL.ReaderSourceTypeId,0) AS ReaderSourceTypeId,
			ISNULL(BL.ReaderSourceId,0) AS ReaderSourceId,
			SC.Code AS ReaderCode,
			SC.Name AS ReaderName,
			SC.ClassName+'-'+SC.DivisionName AS ClassDept,
			BL.ResourceSourceTypeId,
			BL.ResourceSourceId,
			BM.Code AS ResourceCode,
			BM.Title AS ResourceName,
			BL.LogDate,
			BL.DueDate,
			BL.StatusId,
			CASE WHEN BL.StatusId = 521 Then 'Return' ELSE SM.Title END AS StatusName,
			BL.IsCurrentStatus,
			BL.CreatedDateTime,
			SC.ParentContactNo AS MobileNo,
			SC.ParentEmail AS EmailId,
			replace (
			replace (
			replace (
			replace((SELECT E.Template FROM sAlert.tEventTemplate E WHERE E.OrgId=BL.OrgId AND E.EventId=11 AND E.AlertModeId=1),'[Name]',SC.Name),
			'[BookCode]',BM.Code),
			'[BookName]',BM.Title),
			'[DueDate]',BL.DueDate)
			 AS EmailTemplate,
			replace (
			replace (
			replace (
			replace((SELECT E.Template FROM sAlert.tEventTemplate E WHERE E.OrgId=BL.OrgId AND E.EventId=11 AND AlertModeId=2),'[Name]',SC.Name),
			'[BookCode]',BM.Code),
			'[BookName]',BM.Title),
			'[DueDate]',BL.DueDate)
			 AS SMSTemplate,
			 (SELECT E.MailSubject FROM sAlert.tEventTemplate E WHERE E.OrgId=BL.OrgId AND E.EventId=11 AND E.AlertModeId=1) AS MailSubject,
			 LM.Id AS LibraryId,
			 LM.Title AS LibraryName
	FROM 
			sLibrary.tBookLog BL
			INNER JOIN sLibrary.tLibraryMaster LM ON LM.Id = BL.LibraryId
			INNER JOIN sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId
			INNER JOIN sStudent.vStudentCommunication SC ON SC.StudentId=BL.ReaderSourceId AND BL.ReaderSourceTypeId=2003 AND BL.BatchId = SC.BatchId
			INNER JOIN sCommon.tStatusMaster SM ON SM.Id=BL.StatusId
	WHERE 
			(BL.ReaderSourceTypeId=@rReaderSourceTypeId OR @rReaderSourceTypeId=0)
		AND ((SC.Code Like @rReaderCode) OR (ISNULL(@rReaderCode,'') = ''))
		AND ((SC.Name Like @rReaderName) OR (ISNULL(@rReaderName,'') = ''))
		AND ((BM.Code Like @rResourceCode) OR (ISNULL(@rResourceCode,'') = ''))
		AND ((BM.Title Like @rResourceName) OR (ISNULL(@rResourceName,'') = ''))
		--AND ((BL.LogDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		--AND ((BL.LogDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		AND (BL.DueDate<=@rDueDate) AND (BL.IsCurrentStatus=1)
		AND (BL.StatusId = 523) 
		AND ((BL.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((BL.BatchId=@rBatchId) OR (@rBatchId=0))
		AND ((BL.LibraryId=@rLibraryId) OR (@rLibraryId=0))
		AND LM.OrgGroupId = @rOrgGroupId
	UNION ALL

	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			BL.Id AS BookLogId,
			'Employee' AS ReaderSourceType,
			ISNULL(BL.ReaderSourceTypeId,0) AS ReaderSourceTypeId,
			ISNULL(BL.ReaderSourceId,0) AS ReaderSourceId,
			EC.Code AS ReaderCode,
			EC.FirstName+' '+EC.LastName AS ReaderName,
			EC.DepartmentName as ClassDept,
			BL.ResourceSourceTypeId,
			BL.ResourceSourceId,
			BM.Code AS ResourceCode,
			BM.Title AS ResourceName,
			BL.LogDate,
			BL.DueDate,
			BL.StatusId,
			CASE WHEN BL.StatusId = 521 Then 'Return' ELSE SM.Title END AS StatusName,
			BL.IsCurrentStatus,
			BL.CreatedDateTime,
			EC.PhoneNoCompany AS MobileNo,
			EC.CompanyEmail AS EmailId,
			replace (
			replace (
			replace (
			replace((SELECT E.Template FROM sAlert.tEventTemplate E WHERE E.OrgId=BL.OrgId AND E.EventId=11 AND E.AlertModeId=1),'[Name]',EC.EmployeeName),
			'[BookCode]',BM.Code),
			'[BookName]',BM.Title),
			'[DueDate]',BL.DueDate)
			 AS EmailTemplate,
			 replace (
			replace (
			replace (
			replace((SELECT E.Template FROM sAlert.tEventTemplate E WHERE E.OrgId=BL.OrgId AND E.EventId=11 AND AlertModeId=2),'[Name]',EC.EmployeeName),
			'[BookCode]',BM.Code),
			'[BookName]',BM.Title),
			'[DueDate]',BL.DueDate)
			 AS SMSTemplate,
			 (SELECT E.MailSubject FROM sAlert.tEventTemplate E WHERE E.OrgId=BL.OrgId AND E.EventId=11 AND E.AlertModeId=1) AS MailSubject,
			 LM.Id AS LibraryId,
			 LM.Title AS LibraryName
	FROM 
			sLibrary.tBookLog BL
			INNER JOIN sLibrary.tLibraryMaster LM ON LM.Id = BL.LibraryId
			INNER JOIN sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId
			INNER JOIN sHrm.vEmployeeCommunication EC ON EC.Id=BL.ReaderSourceId AND BL.ReaderSourceTypeId=95 AND BL.OrgId=EC.OrgId
			INNER JOIN sCommon.tStatusMaster SM ON SM.Id=BL.StatusId
	WHERE 
			(BL.ReaderSourceTypeId=@rReaderSourceTypeId OR @rReaderSourceTypeId=0)
		AND ((EC.Code Like @rReaderCode) OR (ISNULL(@rReaderCode,'') = ''))
		AND ((EC.FirstName+' '+EC.LastName Like @rReaderName) OR (ISNULL(@rReaderName,'') = ''))
		AND ((BM.Code Like @rResourceCode) OR (ISNULL(@rResourceCode,'') = ''))
		AND ((BM.Title Like @rResourceName) OR (ISNULL(@rResourceName,'') = ''))
		--AND ((BL.LogDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		--AND ((BL.LogDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		AND (BL.StatusId = 523) 
		AND (BL.DueDate<=@rDueDate) AND  (BL.IsCurrentStatus=1)
		AND ((BL.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((BL.BatchId=@rBatchId) OR (@rBatchId=0))
		AND ((BL.LibraryId=@rLibraryId) OR (@rLibraryId=0))
		AND LM.OrgGroupId = @rOrgGroupId
	UNION ALL

	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			BL.Id AS BookLogId,
			'' AS ReaderSourceType,
			0 AS ReaderSourceTypeId,
			0 AS ReaderSourceId,
			'' AS ReaderCode,
			'' AS ReaderName,
			'' as ClassDept,
			BL.ResourceSourceTypeId,
			BL.ResourceSourceId,
			BM.Code AS ResourceCode,
			BM.Title AS ResourceName,
			BL.LogDate,
			BL.DueDate,
			BL.StatusId,
			SM.Title AS StatusName,
			BL.IsCurrentStatus,
			BL.CreatedDateTime,
			'' AS MobileNo,
			'' AS EmailId,
			'' AS EmailTemplate,
			'' AS SMSTemplate,
			'' AS MailSubject,
			LM.Id AS LibraryId,
			LM.Title AS LibraryName
	FROM 
			sLibrary.tBookLog BL
			INNER JOIN sLibrary.tLibraryMaster LM ON LM.Id = BL.LibraryId
			INNER JOIN sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId
			INNER JOIN sCommon.tStatusMaster SM ON SM.Id=BL.StatusId
	WHERE 
			(ISNULL(BL.ReaderSourceTypeId,0)=@rReaderSourceTypeId AND @rReaderSourceTypeId=0)
		AND (('' Like @rReaderCode) OR (ISNULL(@rReaderCode,'') = ''))
		AND (('' Like @rReaderName) OR (ISNULL(@rReaderName,'') = ''))
		AND ((BM.Code Like @rResourceCode) OR (ISNULL(@rResourceCode,'') = ''))
		AND ((BM.Title Like @rResourceName) OR (ISNULL(@rResourceName,'') = ''))
		--AND ((BL.LogDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		--AND ((BL.LogDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		AND (BL.StatusId = 523) 
		AND (BL.DueDate<=@rDueDate) AND (BL.IsCurrentStatus=1) 
		AND ((BL.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((BL.BatchId=@rBatchId) OR (@rBatchId=0))
		AND ((BL.LibraryId=@rLibraryId) OR (@rLibraryId=0))
		AND LM.OrgGroupId = @rOrgGroupId
END
GO
PRINT N'Altering [sLibrary].[pRptBookLogRegisterGet]...';


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

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


GO

ALTER PROCEDURE [sLibrary].[pRptFavouriteBooksCountGet]

	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='',
	 
	 @rLibraryId int,
	 @rFromLogDate date,
	 @rToLogDate date
	
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 	
	SELECT 
	
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			BL.Id AS BookLogId,
			BL.ReaderSourceTypeId,
			BL.ReaderSourceId,
			SA.Code AS ReaderCode,
			SA.Name AS ReaderName,
			SA.ClassName+'-'+SA.DivisionName AS ClassDiv,
			SA.ClassId,
			SA.DivisionName,
			SA.DivisionId,
			SA.ClassName,
			BL.ResourceSourceTypeId,
			BL.ResourceSourceId,			
			BL.LogDate,
			BL.DueDate,
			
			OM.DisplayTitle As OrgName,
			BL.OrgId,
			BL.BatchId,
			BM.Code AS BookCode,
			BM.Title AS BookName
	FROM 
			sLibrary.tBookLog BL
			INNER JOIN sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId
			INNER JOIN sStudent.vStudentLastAcademic SA ON SA.StudentId=BL.ReaderSourceId AND BL.ReaderSourceTypeId=2003			
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=BL.OrgId
			
			
	WHERE 
			
		
		
		BL.StatusId=523
		AND (BL.LibraryId=@rLibraryId)
		AND (BL.LogDate>=@rFromLogDate OR ISNULL(@rFromLogDate,'')='')
		AND (BL.LogDate<=@rToLogDate OR ISNULL(@rToLogDate,'')='')
		
	
END
GO
PRINT N'Altering [sLibrary].[pRptReaderBookListGet]...';


GO

ALTER PROCEDURE [sLibrary].[pRptReaderBookListGet]

	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rReaderSourceTypeId smallint,
	 --@rReaderSourceId bigint,
	 @rOrgId smallint,
	 @rBatchId int,
	 @rClassId int,
	 @rDivisionId int,
	 @rFromLogDate date,
	 @rToLogDate date,
	 @rLibraryId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
If(@rReaderSourceTypeId=2003)
BEGIN
	SELECT 
	     
	        @rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			BL.Id AS BookLogId,
			BM.Code AS ResourceCode,
			BM.Title AS ResourceName,
			BL.LogDate,
			BL.DueDate,
			IS1.NoOfBookIssuable,
			BL.StatusId ,
			SM.Title AS Status,
			SA.Name,
			SA.RollNo,
			SA.Code,
			SA.ClassName,
			SA.DivisionName
			
			
	FROM 
			sLibrary.tBookLog BL
			INNER JOIN sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId
			INNER JOIN sCommon.tStatusMaster SM ON SM.Id=BL.StatusId
			INNER JOIN sStudent.vStudentLastAcademic SA ON SA.StudentId=BL.ReaderSourceId
			INNER JOIN sLibrary.tIssueSetting IS1 ON IS1.SourceId=SA.ClassId AND IS1.SourceTypeId=2005
			INNER JOIN sSetup.tBatchMaster B ON SA.BatchId = B.Id AND B.IsActive = 1
	WHERE 
			((BL.ReaderSourceTypeId=@rReaderSourceTypeId) OR (@rReaderSourceTypeId=0))
		--AND (BL.ReaderSourceId=@rReaderSourceId OR @rReaderSourceId=0)
		AND (SA.ClassId=@rClassId OR @rClassId=0)
		AND (SA.DivisionId=@rDivisionId OR @rDivisionId=0)
		AND ((BL.LogDate >= @rFromLogDate) OR (ISNULL(@rFromLogDate,'') = ''))
		AND ((BL.LogDate <= @rToLogDate) OR (ISNULL(@rToLogDate,'') = ''))
		AND (BL.StatusId=523) 
		AND ((BL.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((BL.BatchId=@rBatchId) OR (@rBatchId=0))
		AND (BL.LibraryId=@rLibraryId)
END
ELSE If(@rReaderSourceTypeId=95)
BEGIN
	SELECT 
	
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			BL.Id AS BookLogId,
			BM.Code AS ResourceCode,
			BM.Title AS ResourceName,
			BM.BookSubject,
			BL.LogDate,
			BL.DueDate,
			IS1.NoOfBookIssuable,			
			BL.StatusId,
			SM.Title AS Status,
			BL.IsCurrentStatus ,
			EM.FirstName+' '+EM.LastName AS Name,
			EM.Code,
			ODM.Title AS EmpDept
	FROM 
			sLibrary.tBookLog BL
			LEFT JOIN sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId
			INNER JOIN sCommon.tStatusMaster SM ON SM.Id=BL.StatusId
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id=BL.ReaderSourceId	
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id = EJD.EmployeeId
			INNER JOIN sSetup.tDepartmentMaster ODM ON ODM.Id = EJD.OrganizationDepartmentId
			INNER JOIN sLibrary.tIssueSetting IS1 ON IS1.SourceId=ODM.Id AND IS1.SourceTypeId=2004
				
				WHERE 
			((BL.ReaderSourceTypeId=@rReaderSourceTypeId) OR (@rReaderSourceTypeId=0))
		--AND (BL.ReaderSourceId=@rReaderSourceId OR @rReaderSourceId=0)
		AND ((BL.LogDate >= @rFromLogDate) OR (ISNULL(@rFromLogDate,'') = ''))
		AND ((BL.LogDate <= @rToLogDate) OR (ISNULL(@rToLogDate,'') = ''))
		AND (BL.StatusId=523)
		AND ((BL.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((BL.BatchId=@rBatchId) OR (@rBatchId=0))
		AND (BL.LibraryId=@rLibraryId)
END
END
GO
PRINT N'Altering [sLibrary].[pViewBookDetailGet]...';


GO
ALTER PROCEDURE [sLibrary].[pViewBookDetailGet]
	 @rResourceSourceId bigint,
	 @rIsCurrentStatus bit,
	 @rOrgId smallint,
	 @rBatchId int,
	 @rLibraryId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	DECLARE @rReaderSourceTypeId smallint 
	Select @rReaderSourceTypeId=ReaderSourceTypeId from sLibrary.tBookLog WHERE ResourceSourceId=@rResourceSourceId AND IsCurrentStatus=@rIsCurrentStatus
	IF(@rReaderSourceTypeId IS NOT NULL)
	BEGIN
	SELECT 
			BM.Id AS ResourceSourceId,
			BM.Code AS ResourceCode,
			BM.Title AS ResourceName,
			SA.Name AS ReaderName,
			SA.ClassName+'-'+SA.DivisionName AS ClassDept,
			BL.StatusId,
			SM.Title AS StatusName,
			CASE WHEN BL.StatusId != 521 THEN BL.LogDate END AS LogDate,
			CASE WHEN BL.StatusId != 521 THEN BL.DueDate END AS DueDate
			
	FROM 
			sLibrary.tBookMaster BM 
			INNER JOIN sLibrary.tBookLog BL ON BM.Id=BL.ResourceSourceId AND BL.IsCurrentStatus=@rIsCurrentStatus AND BL.ReaderSourceTypeId=2003
			INNER JOIN sCommon.tStatusMaster SM ON SM.Id=BL.StatusId
			LEFT JOIN sStudent.vStudentLastAcademic SA ON SA.StudentId=BL.ReaderSourceId 
	WHERE 
			((BM.Id=@rResourceSourceId) OR (@rResourceSourceId=0))
		AND ((BL.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((BL.BatchId=@rBatchId) OR (@rBatchId=0))
		AND (BL.LibraryId=@rLibraryId)
		
		UNION ALL
		
		SELECT 
			BM.Id AS ResourceSourceId,
			BM.Code AS ResourceCode,
			BM.Title AS ResourceName,
			EM.FirstName+' '+EM.LastName AS ReaderName,
			ODM.Title as ClassDept,
			BL.StatusId,
			SM.Title AS StatusName,
			CASE WHEN BL.StatusId != 521 THEN BL.LogDate END AS LogDate,
			CASE WHEN BL.StatusId != 521 THEN BL.DueDate END AS DueDate
			
	FROM 
			sLibrary.tBookMaster BM 
			INNER JOIN sLibrary.tBookLog BL ON BM.Id=BL.ResourceSourceId AND BL.IsCurrentStatus=@rIsCurrentStatus AND BL.ReaderSourceTypeId=95
			INNER JOIN sCommon.tStatusMaster SM ON SM.Id=BL.StatusId
			LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id=BL.ReaderSourceId
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id = EJD.EmployeeId
			INNER JOIN sSetup.tDepartmentMaster ODM ON ODM.Id = EJD.OrganizationDepartmentId
	WHERE 
			((BM.Id=@rResourceSourceId) OR (@rResourceSourceId=0))
		AND ((BL.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((BL.BatchId=@rBatchId) OR (@rBatchId=0))
		AND (BL.LibraryId=@rLibraryId)
	END
	ELSE
	BEGIN
	
		SELECT 
			BM.Id AS ResourceSourceId,
			BM.Code AS ResourceCode,
			BM.Title AS ResourceName,
			'' AS ReaderName,
			'' AS ClassDept,
			BL.StatusId,
			SM.Title AS StatusName,
			CASE WHEN BL.StatusId != 521 THEN BL.LogDate END AS LogDate,
			CASE WHEN BL.StatusId != 521 THEN BL.DueDate END AS DueDate
			
	FROM 
			sLibrary.tBookMaster BM 
			INNER JOIN sLibrary.tBookLog BL ON BM.Id=BL.ResourceSourceId AND BL.IsCurrentStatus=@rIsCurrentStatus
			INNER JOIN sCommon.tStatusMaster SM ON SM.Id=BL.StatusId
	WHERE 
			((BM.Id=@rResourceSourceId) OR (@rResourceSourceId=0))
		AND ((BL.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((BL.BatchId=@rBatchId) OR (@rBatchId=0))
		AND (BL.LibraryId=@rLibraryId)
	END
END
GO
PRINT N'Altering [sPayroll].[pPayElementAdd]...';


GO
ALTER PROCEDURE [sPayroll].[pPayElementAdd] 
	      
			@rId int
	       ,@rCode nvarchar(20)
           ,@rTitle nvarchar(100)
           ,@rPayElementTypeId tinyint
           ,@rPaidCategoryId tinyint
           ,@rIsLwp bit
           ,@rIsEmployeeSpecific bit
           ,@rIsDepend bit
           ,@rIsAvailDuringProbation bit
           ,@rIsIncludeInPaySlip bit
           ,@rSortOrder tinyint
           ,@rIsObsolete bit
           ,@rOrgGroupId int
           ,@rCreatedUserId bigint
		   ,@rPayElementDefaultId int
		   ,@rPayrollId int
		   ,@rIsIncludeInTotal bit=0
      
        
           
          
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

	BEGIN TRY
	BEGIN TRANSACTION  
	DECLARE @lNextNumber BIGINT
  
  IF (@rId = 0)
    
    BEGIN	
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sPayroll.tPayElement', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO [sPayroll].[tPayElement]
           (
            [ID]
           ,[Code]
           ,[Title]
           ,[PayElementTypeId]
           ,[PaidCategoryId]
           ,[IsLwp]
           ,[IsEmployeeSpecific]
           ,[IsDepend]
           ,[IsAvailDuringProbation]
           ,[IsIncludeInPaySlip]
           ,[SortOrder]
           ,[IsObsolete]
           ,[CreatedUserId]
           ,[CreatedDateTime]
           ,[UpdatedUserId]
           ,[UpdatedDateTime]
           ,[PayElementDefaultId]
           ,[PayrollId]
           ,[IsIncludeInTotal]
           )
     VALUES
           (
            @lNextNumber
           ,@rCode 
           ,@rTitle 
           ,@rPayElementTypeId 
           ,@rPaidCategoryId 
           ,@rIsLwp 
           ,@rIsEmployeeSpecific 
           ,@rIsDepend 
           ,@rIsAvailDuringProbation 
           ,@rIsIncludeInPaySlip 
           ,@rSortOrder 
           ,@rIsObsolete 
           ,@rCreatedUserId 
           ,sCommon.fGetDate()  
           ,@rCreatedUserId 
           ,sCommon.fGetDate() 
           ,@rPayElementDefaultId
           ,@rPayrollId
           ,@rIsIncludeInTotal
           )
    	END
    ELSE
		BEGIN    
		     SET @lNextNumber = @rId
		    UPDATE  [sPayroll].[tPayElement]
			   SET   
			       [Code] = @rCode
				  ,[Title] = @rTitle 
				  ,[PayElementTypeId] = @rPayElementTypeId 
				  ,[PaidCategoryId] = @rPaidCategoryId 
				  ,[IsLwp] = @rIsLwp 
				  ,[IsEmployeeSpecific] = @rIsEmployeeSpecific 
				  ,[IsDepend] = @rIsDepend 
				  ,[IsAvailDuringProbation] = @rIsAvailDuringProbation 
				  ,[IsIncludeInPaySlip] = @rIsIncludeInPaySlip 
				  ,[SortOrder] = @rSortOrder 
				  ,[IsObsolete] = @rIsObsolete  
				  ,[UpdatedUserId] = @rCreatedUserId 
				  ,[UpdatedDateTime] = sCommon.fGetDate() 
				  --,[PayElementDefaultId] = @rPayElementDefaultId
				  ,[PayrollId]=@rPayrollId
				  ,[IsIncludeInTotal]=@rIsIncludeInTotal
			   WHERE Id = @rId   		     		    
			END        
	SELECT @lNextNumber AS Result	
	COMMIT TRANSACTION
	END TRY
	BEGIN CATCH
	ROLLBACK TRANSACTION
	 RAISERROR ('Error Creating Pay Element Detail', -- Message text.
               16, -- Severity.
               1 -- State.
               );
	--SELECT -1 AS RESULT
	END CATCH	
END
GO
PRINT N'Altering [sPayroll].[pPayElementGet]...';


GO
ALTER PROCEDURE [sPayroll].[pPayElementGet]
	 @rId int,
	 @rCode nvarchar(20),
	 @rTitle nvarchar(100),
	 @rPayElementTypeId int,
	 @rPaidCategoryId int,
	 @rPayrollId int,
	 @rIsWildCardSearch bit
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 		

    IF(@rIsWildCardSearch = 0)
	 BEGIN  	  
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
			SET @rCode = sCommon.fSearchStringGet(@rCode)
	  END
	

 SELECT PE.Id
      ,PE.[Code]
      ,PE.[Title]
      ,PE.[PayElementTypeId]
      ,PE.[PaidCategoryId]
      ,ISNULL(PE.[IsLwp],0) AS IsLwp 
      ,ISNULL(PE.[IsEmployeeSpecific],0) As IsEmployeeSpecific
      ,ISNULL(PE.[IsDepend],0) As IsDepend
      ,ISNULL(PE.[IsAvailDuringProbation],0) AS IsAvailDuringProbation
      ,ISNULL(PE.[IsIncludeInPaySlip],0) AS IsIncludeInPaySlip
      ,PE.[SortOrder]
      ,PE.[IsObsolete]
      ,PET.Title AS PayElementType
      ,PC.Title AS PaidCategory     
      ,ISNULL(PE.PayElementDefaultId,0) AS PayElementDefaultId
      ,PED.Code AS PayElementDefaultCode
      ,ISNULL(PE.IsIncludeInTotal,0) AS IsIncludeInTotal
     
  FROM  sPayroll.tPayElement PE 
  INNER JOIN sPayroll.tPayElementType PET 
	ON PET.Id = PE.PayElementTypeId   
  INNER JOIN sPayroll.tPaidCategory PC 
	ON PC.Id = PE.PaidCategoryId
  INNER JOIN sPayroll.tPayElementDefault PED	
	ON PED.Id = PE.PayElementDefaultId

Where 
	 PE.PayrollId = @rPayrollId  
     AND (PE.Id = @rId OR @rId = 0)
     AND (PE.Code Like @rCode OR ISNULL(@rCode,'') = '')
     AND (PE.Title Like @rTitle OR ISNULL(@rTitle,'') = '')
     AND (PE.PayElementTypeId = @rPayElementTypeId OR @rPayElementTypeId = 0)
     AND (PE.PaidCategoryId = @rPaidCategoryId OR @rPaidCategoryId = 0) 
     ORDER BY PE.SortOrder
END
GO
PRINT N'Altering [sPayroll].[pPayElementListGet]...';


GO
ALTER PROCEDURE [sPayroll].[pPayElementListGet]

           @rPayrollId int
           
AS
SET NOCOUNT ON

BEGIN

	SELECT  
			ISNULL(PE.ID,0) AS ID,
			PED.Code,
			PED.Title,
			PED.PayElementTypeId,
			PED.PaidCategoryId,
			ISNULL(PE.IsLwp,0) AS IsLwp,
			ISNULL(PE.IsEmployeeSpecific,0) AS IsEmployeeSpecific,
			ISNULL(PE.IsDepend,0) AS IsDepend,
			ISNULL(PE.IsAvailDuringProbation,0) AS IsAvailDuringProbation,
			ISNULL(PE.IsIncludeInPaySlip,0) AS IsIncludeInPaySlip,
			CASE ISNULL(PE.SortOrder,0)
				WHEN 0 THEN PED.SortOrder
				ELSE PE.SortOrder
			END AS SortOrder,
			--ISNULL(PE.SortOrder,0) AS SortOrder,
			ISNULL(PE.IsObsolete,0) AS IsObsolete,
			PE.CreatedUserId,
			PE.CreatedDateTime,
			PE.UpdatedUserId,
			PE.UpdatedDateTime,
			PED.ID AS PayElementDefaultId,
			PE.PayrollId,
			PET.Title AS PayElementType,
			ISNULL(PE.IsIncludeInTotal,0) AS IsIncludeInTotal
	FROM
			sPayroll.tPayElementDefault PED 
				INNER JOIN sPayroll.tPayElementType PET 
			ON PET.Id=PED.PayElementTypeId
				INNER JOIN sPayroll.tPayElement PE 
			ON PED.ID = PE.PayElementDefaultId AND PE.PayrollId=@rPayrollId AND PE.IsObsolete = 0
			WHERE PED.IsObsolete = 0
			
			ORDER BY PE.SortOrder
END
GO
PRINT N'Altering [sPayroll].[pPayProcessElementGet]...';


GO
ALTER PROCEDURE [sPayroll].[pPayProcessElementGet]
	  
	  @rPayProcessEmployeeId bigint
 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	     SELECT 
			 PPE.PayElementId,
			 PE.Title AS PayElement,
			 PPE.Amount,
			 PET.Title AS PayElementType,
			 PayElementTypeId,
			 PPE.PayProcessEmployeeId,
			 ISNULL(PE.IsIncludeInTotal,0) AS IsIncludeInTotal
		 FROM 
			 sPayroll.tPayProcessElement PPE 
			 INNER JOIN sPayroll.tPayElement PE ON PPE.PayElementId = PE.ID
			 INNER JOIN sPayroll.tPayElementType PET ON PET.Id = PE.PayElementTypeId
			 
		 WHERE PayProcessEmployeeId = @rPayProcessEmployeeId		
			 ORDER BY SortOrder
END
GO
PRINT N'Altering [sPayroll].[pPayProcessEmployeeAdd]...';


GO
ALTER PROCEDURE [sPayroll].[pPayProcessEmployeeAdd] 
	      	        
            @rPayProcessId int            
           ,@rOrgGroupId int
		   ,@rPayrollId int
		   ,@rPayrollYearId int
		   ,@rSalaryMonth tinyint
           ,@rSalaryYear smallint
           
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

	BEGIN TRY
	BEGIN TRANSACTION  
	DECLARE @lNextNumber BIGINT
	DECLARE @1PayProcessElementId bigint
	DECLARE @1Count int
	DECLARE @1EmployeeId bigint
	DECLARE @lPayrollGroupId int
	DECLARE @1PayElementCount int
	DECLARE @1TotalEarningAmount DECIMAL(22,6)
	DECLARE @1PaySetupId int
	DECLARE @1SourceId bigint
    DECLARE @1Percentage decimal(5,2)
	DECLARE @1Result decimal(22,6)
	DECLARE @1Amount decimal(22,6)
	DECLARE @1IsDepend bit
	DECLARE @1PayElementId int
	DECLARE @1LWPDeduction decimal(22,6) 
	DECLARE @1IsLwp Bit
	DECLARE @1PayElementTypeId int
	DECLARE @1TotalDeductionAmount DECIMAL(22,6)
	DECLARE @1EmployeeBasicPay DECIMAL(22,6)
	
	DECLARE @1WorkingDays int
	DECLARE @1Lwp Decimal(12,2)
	DECLARE @lPaidLeave Decimal(12,2)
	DECLARE @1GrossBasic Decimal(12,2)
	DECLARE @1PayElementDefaultId int
    DECLARE @lIsIncludeInTotal Bit
    
	--IF (@rId = 0)
   
    CREATE TABLE #tmpEmpDetail
	(
		Id INT IDENTITY (1, 1),
		EmployeeId  bigint,
		PayrollGroupId int
	)
	 
	INSERT INTO #tmpEmpDetail
    Select ES.EmployeeId,PayrollGroupId FROM sHrm.tEmployeeStatutoryAndOther ES
    INNER JOIN  sHrm.tEmployeeAttendance EA ON ES.EmployeeId = EA.EmployeeId
    INNER JOIN sSetup.tBatchMaster BM ON EA.BatchId = BM.Id AND BM.IsActive = 1
     Where PayrollId = @rPayrollId AND PayrollGroupId IS NOT NULL
     AND EA.ForMonth = @rSalaryMonth AND EA.ForYear = @rSalaryYear
    
    --AND EmployeeId = 1001000000039
   
   Select @1Count = COUNT(*) FROM #tmpEmpDetail 
       
   WHILE @1Count > 0 
    BEGIN	 
			--SELECT @1TotalEarningAmount
			--END	  
			EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sPayroll.tPayProcessEmployee', 0, 1, 1,@outNextNumber = @lNextNumber output	
		    SELECT @1EmployeeId = EmployeeId,@lPayrollGroupId = PayrollGroupId FROM #tmpEmpDetail WHERE ID = @1Count
		    
		    SELECT @1WorkingDays = TotalWorkingDays,@1Lwp = LWP, @lPaidLeave=ISNULL(PaidLeave,0) FROM sHrm.tEmployeeAttendance EA
		    INNER JOIN sSetup.tBatchMaster BM ON EA.BatchId = BM.Id AND BM.IsActive = 1
		     Where EA.EmployeeId=@1EmployeeId AND EA.ForYear=@rSalaryYear AND EA.ForMonth=@rSalaryMonth
				
		    --SELECT @1WorkingDays = WD.WorkingDays,@1Lwp = EA.LWP FROM sHrm.tEmployeeAttendance EA
		    --INNER JOIN sHrm.tWorkingDays WD ON WD.BatchId = EA.BatchId AND WD.ForMonth = @rSalaryMonth AND WD.ForYear = @rSalaryYear
		    --WHERE EA.EmployeeId=@1EmployeeId AND EA.ForYear=@rSalaryYear AND EA.ForMonth=@rSalaryMonth
		    
		    SELECT @1GrossBasic = PS.Amount FROM sPayroll.tPaySetup PS 
			INNER JOIN sPayroll.tPayElement PE ON PE.Id=PS.PayElementId
			Where PS.SourceTypeId = 95 
			AND PS.SourceId=@1EmployeeId 
			AND PS.PayrollId=@rPayrollId 
			AND PS.PayrollYearId = @rPayrollYearId 
			AND PE.PayElementDefaultId=1 
					  
		   INSERT INTO  [sPayroll].[tPayProcessEmployee]
				   (
				    [ID]
				   ,[PayProcessId]
				   ,[EmployeeId]
				   ,[PayrollGroupId]
				   ,TotalEarning
				   ,TotalDeduction
				   ,NetAmount
				   ,WorkingDays
				   ,Lwp
				   ,GrossBasic
				   ,PaidLeave
				   )
			 VALUES
				   (
				    @lNextNumber
				   ,@rPayProcessId
				   ,@1EmployeeId 
				   ,@lPayrollGroupId
				   ,0.0
				   ,0.0
				   ,0.0
				   ,@1WorkingDays
				   ,@1Lwp
				   ,@1GrossBasic
				   ,@lPaidLeave
				   )
				   
		      
	     -- FOR Counting Total Earning
	 
		 CREATE TABLE #tmpPaysetupElement
		(
		   Id INT IDENTITY (1, 1),
		   PaySetupId int,
		   SourceId bigint,
		   SourceTypeId int,
		   PayElementId int,
		   Amount DECIMAl(22,6) NULL,
		   Percentage DECIMAl(5,2) NULL,
		   IsDepend bit,
		   PayElementTypeId int,
		   ProcessOrder int,
		   PayElementDefaultId int  
		)  
		   
		   BEGIN
		 --IF EXISTS (select 1 from sPayroll.tpaysetup where SourceId = @1EmployeeId AND SourceTypeId = 3016) --For Pay Setup Employee
		     INSERT INTO #tmpPaysetupElement
		     SELECT PE.ID,PE.SourceId,PE.SourceTypeId,PE.PayElementId,PE.Amount,PE.Percentage,PE.IsDepend,PE.PayElementTypeId,PE.ProcessOrder,PayElementDefaultId FROM 
		     (		     
		     SELECT PS.ID,SourceId,95 AS SourceTypeId ,PayElementId,Amount,Percentage,ISNULL(IsDepend,0) AS IsDepend,PayElementTypeId,ProcessOrder,PE.PayElementDefaultId
		     FROM sPayroll.tPaySetup PS INNER JOIN sPayroll.tPayElement  PE ON PE.ID = PS.PayElementId
			 WHERE SourceId = @1EmployeeId 
			 AND SourceTypeId = 95 
			 AND PS.PayrollId=@rPayrollId 
			 AND PS.PayrollYearId = @rPayrollYearId
		 
		 --ELSE 
		     UNION ALL
		      
		     --INSERT INTO #tmpPaysetupElement
		     SELECT PS.ID,SourceId,2020 AS SourceTypeId,PayElementId,Amount,Percentage,IsDepend,PayElementTypeId,ProcessOrder ,PE.PayElementDefaultId
		     FROM sPayroll.tPaySetup  PS  INNER JOIN sPayroll.tPayElement  PE ON PE.ID = PS.PayElementId
			 WHERE SourceId = @lPayrollGroupId AND SourceTypeId = 2020 AND PS.PayrollId=@rPayrollId AND PS.PayrollYearId = @rPayrollYearId
			 AND PayElementId NOT IN (SELECT  PayElementId FROM sPayroll.tPaySetup  PS 
		     INNER JOIN sPayroll.tPayElement  PE ON PE.ID = PS.PayElementId 
		     WHERE SourceId = @1EmployeeId 
		     AND SourceTypeId = 95 
		     AND PS.PayrollId=@rPayrollId 
		     AND PS.PayrollYearId = @rPayrollYearId)  			 
			 
		     ) PE  ORDER BY ProcessOrder  DESC
		  	END	
		  	  
		    --Select * FROM #tmpPaysetupElement
		  
		  	SELECT @1PayElementCount = COUNT(*) FROM #tmpPaysetupElement
			
			SET @1TotalDeductionAmount = 0
			SET   @1TotalEarningAmount = 0
			WHILE @1PayElementCount > 0
				 BEGIN				
					SET @1PaySetupId = 0
					SET @1SourceId = 0
					SET @1Percentage = 0.0
					SET @1Result = 0.0
					SET @1Amount = 0.0 			
					SET @1PayElementId = 0
					SET @1IsLwp = 0
					SET @1LWPDeduction = 0
					SET @1PayElementDefaultId = 0
			  
			    SELECT @1PaySetupId = PaySetupId,@1SourceId = SourceId,@1PayElementId = PayElementId,@1Result = Amount,
			    @1Percentage = Percentage,@1IsDepend = IsDepend,@1PayElementTypeId=PayElementTypeId,@1PayElementDefaultId =PayElementDefaultId FROM #tmpPaysetupElement WHERE Id = @1PayElementCount
			      
			    SELECT @1IsLwp = IsLwp, @lIsIncludeInTotal=IsIncludeInTotal FROM sPayroll.tPayElement Where Id = @1PayElementId AND PayrollId = @rPayrollId
			       
			       IF(@1IsLwp = 1) 			     
			            SELECT @1LWPDeduction = [sPayroll].[fCalculateLWP] (@1EmployeeId, @rPayProcessId,ISNULL(@1Result,0))			      
			               
			     IF(@1IsDepend = 1 AND @1PayElementDefaultId NOT IN(55,56,57)) -- ESI,PF,PT seperatly calculated
			          BEGIN 
			          --SELECT 	@1PayElementId,@1Percentage
			               EXECUTE [sPayroll].[pCalculatePayrollAmount]  @1PaySetupId,@1PayElementId,@1Percentage,@1SourceId,@rOrgGroupId,@1EmployeeId,@lNextNumber,@rPayrollId,@rPayrollYearId,@1Result OUTPUT
			               --SELECT 	@1PayElementId,@1Result	-- To comment	               
			          END 
			          
			    SET @1Result =  ROUND(ISNULL(@1Result,0.0) -  ISNULL(@1LWPDeduction,0.00),0)	       
			      
			    EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sPayroll.tPayProcessElement', 0, 1, 1,@outNextNumber = @1PayProcessElementId output	
			        
			        INSERT INTO  [sPayroll].[tPayProcessElement]
						   (
						    [ID]
						   ,[PayProcessEmployeeId]
						   ,[PayElementId]
						   ,[Amount]
						   )
					 VALUES
						   (
						    @1PayProcessElementId
						   ,@lNextNumber
						   ,@1PayElementId
						   ,@1Result
						   )  
			    
			    
			     IF( @1PayElementTypeId = 1)
			     BEGIN	      	 
			      IF(@lIsIncludeInTotal = 1)
					SET @1TotalEarningAmount = ISNULL(@1TotalEarningAmount,0) + ISNULL(@1Result,0)		      
				  ELSE
					SET @1TotalEarningAmount = ISNULL(@1TotalEarningAmount,0)	      
			     END
			     
			     ELSE 
			       BEGIN 
			        IF(@lIsIncludeInTotal = 1)
						SET @1TotalDeductionAmount = ISNULL(@1TotalDeductionAmount,0) + ISNULL(@1Result,0) 	      
					ELSE
						SET @1TotalDeductionAmount = ISNULL(@1TotalDeductionAmount,0)	  
			            --- ISNULL(@1LWPDeduction,0)      
			       END   
			     		    
			    SET @1PayElementCount = @1PayElementCount -1			     
			  END	 
		    --SELECT * from #tmpPaysetupElement
			DROP TABLE #tmpPaysetupElement
		       
				   
		   EXECUTE [sPayroll].[pCalculateStaticPayElement]  @lNextNumber,@rOrgGroupId,@1TotalEarningAmount,@1SourceId,@1TotalDeductionAmount,@rPayrollId,@rPayrollYearId		 
	    
			--SELECT  TOP 1 @lTax = Tax  FROM sPayroll.tProfessionalTaxRange where Salary < @rSalary Order By Salary Desc
			 
				   
		 SET @1Count = @1Count - 1	
		END    
	--DROP TABLE #tmpPaysetupElement
	DROP TABLE #tmpEmpDetail
	SELECT @lNextNumber AS Result	
	COMMIT TRANSACTION
	END TRY
	BEGIN CATCH
	ROLLBACK TRANSACTION
	RAISERROR ('Error Creating Pay Process Employee', -- Message text.
               16, -- Severity.
               1 -- State.
               );
	--SELECT -1 AS RESULT
	END CATCH	
END
GO
PRINT N'Altering [sPayroll].[pPaySetupAdd]...';


GO
ALTER PROCEDURE [sPayroll].[pPaySetupAdd] 
	      
	        @rID int
           ,@rSourceTypeId smallint
           ,@rSourceId bigint
           ,@rPayElementId int
           ,@rAmount decimal(22,6)
           ,@rPercentage decimal(5,2)
           ,@rProcessOrder tinyint
           ,@rOrgGroupId int
           ,@rIsObsolete bit
           ,@rPayrollId int
           ,@rOrderIndex int=0
           ,@rPayrollYearId int=0
          
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

	BEGIN TRY
	BEGIN TRANSACTION  
	DECLARE @lNextNumber BIGINT
	
  IF(@rIsObsolete = 0 AND @rId > 0)
  BEGIN
    SET @lNextNumber = 1
    DELETE FROM sPayroll.tPaySetup Where SourceId = @rSourceId AND SourceTypeId = @rSourceTypeId AND PayElementId = @rPayElementId AND PayrollId = @rPayrollId
      
  END
 
  ELSE	
  
  BEGIN
  IF (@rId = 0 AND @rIsObsolete = 1)
    
    BEGIN	
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sPayroll.tPaySetup', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO [sPayroll].[tPaySetup]
           ([ID]
           ,[SourceTypeId]
           ,[SourceId]
           ,[PayElementId]
           ,[Amount]
           ,[Percentage]
           ,[ProcessOrder]
           ,[PayrollId]
           ,[OrderIndex]
           ,[PayrollYearId]
           )
     VALUES
           (
			@lNextNumber 
		   ,@rSourceTypeId 
		   ,@rSourceId 
		   ,@rPayElementId 
		   ,@rAmount 
		   ,@rPercentage 
		   ,@rProcessOrder 
		   ,@rPayrollId
		   ,@rOrderIndex
		   ,@rPayrollYearId
           )
    	END
    ELSE
		BEGIN    
		     SET @lNextNumber = @rId
		     UPDATE  [sPayroll].[tPaySetup]
			   SET       
				  [PayElementId] = @rPayElementId
				  ,[Amount] = @rAmount
				  ,[Percentage] = @rPercentage
				  ,[ProcessOrder] = @rProcessOrder
				  ,[PayrollId] = @rPayrollId
				  ,[OrderIndex] = @rOrderIndex
				  ,[PayrollYearId] = @rPayrollYearId
			WHERE Id = @rId		
		END 
		
 
		IF EXISTS(SELECT 1 FROM sPayroll.tPayElement WHERE ID=@rPayElementId  AND PayrollId =@rPayrollId AND IsEmployeeSpecific = 1   )
	 	BEGIN
			UPDATE sPayroll.tPaySetup
			   SET       
				  ProcessOrder = @rProcessOrder
			WHERE 	SourceTypeId = 95 AND PayElementId=@rPayElementId AND PayrollId =@rPayrollId AND PayrollYearId=@rPayrollYearId 
		END
		
	END       
	SELECT @lNextNumber AS Result	
	COMMIT TRANSACTION
	END TRY
	BEGIN CATCH
	ROLLBACK TRANSACTION
	 RAISERROR ('Error Creating Pay Set Detail', -- Message text.
               16, -- Severity.
               1 -- State.
               );
	--SELECT -1 AS RESULT
	END CATCH	
END
GO
PRINT N'Altering [sPayroll].[pSelectPayElementAdd]...';


GO
ALTER PROCEDURE [sPayroll].[pSelectPayElementAdd] 
	      
			@rId int
	       ,@rCode nvarchar(20)
           ,@rTitle nvarchar(100)
           ,@rPayElementTypeId tinyint
           ,@rPaidCategoryId tinyint
           ,@rIsLwp bit
           ,@rIsEmployeeSpecific bit
           ,@rIsDepend bit
           ,@rIsAvailDuringProbation bit
           ,@rIsIncludeInPaySlip bit
           ,@rSortOrder tinyint
           ,@rIsObsolete bit
           ,@rOrgGroupId int
           ,@rCreatedUserId bigint
           ,@rPayElementDefaultId int
		   ,@rPayrollId int
           ,@rIsIncludeInTotal bit=0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

	BEGIN TRY
	BEGIN TRANSACTION  
	DECLARE @lNextNumber BIGINT
  
	--IF (@rId = 0)
	IF NOT EXISTS(SELECT 1 FROM [sPayroll].[tPayElement] WHERE PayElementDefaultId = @rPayElementDefaultId AND
	PayrollId = @rPayrollId)
    
    BEGIN	
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sPayroll.tPayElement', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO [sPayroll].[tPayElement]
           (
            [ID]
           ,[Code]
           ,[Title]
           ,[PayElementTypeId]
           ,[PaidCategoryId]
           ,[IsLwp]
           ,[IsEmployeeSpecific]
           ,[IsDepend]
           ,[IsAvailDuringProbation]
           ,[IsIncludeInPaySlip]
           ,[SortOrder]
           ,[IsObsolete]
           ,[CreatedUserId]
           ,[CreatedDateTime]
           ,[UpdatedUserId]
           ,[UpdatedDateTime]
           ,[PayElementDefaultId]
           ,[PayrollId]
           ,[IsIncludeInTotal]
           )
     VALUES
           (
            @lNextNumber
           ,@rCode 
           ,@rTitle 
           ,@rPayElementTypeId 
           ,@rPaidCategoryId 
           ,@rIsLwp 
           ,@rIsEmployeeSpecific 
           ,@rIsDepend 
           ,@rIsAvailDuringProbation 
           ,@rIsIncludeInPaySlip 
           ,@rSortOrder 
           ,@rIsObsolete 
           ,@rCreatedUserId 
           ,sCommon.fGetDate()  
           ,@rCreatedUserId 
           ,sCommon.fGetDate()
           ,@rPayElementDefaultId
           ,@rPayrollId
           ,@rIsIncludeInTotal
           )
        SELECT 1 AS RESULT
    	END
    ELSE
		BEGIN    
		    SET @lNextNumber = @rId
		    UPDATE  [sPayroll].[tPayElement]
			   SET   
				   --[Title] = @rTitle 
				  --,
				  [PayElementTypeId] = @rPayElementTypeId 
				  ,[PaidCategoryId] = @rPaidCategoryId 
				  ,[IsLwp] = @rIsLwp 
				  ,[IsEmployeeSpecific] = @rIsEmployeeSpecific 
				  ,[IsDepend] = @rIsDepend 
				  ,[IsAvailDuringProbation] = @rIsAvailDuringProbation 
				  ,[IsIncludeInPaySlip] = @rIsIncludeInPaySlip 
				  ,[SortOrder] = @rSortOrder 
				  ,[IsObsolete] = @rIsObsolete  
				  ,[UpdatedUserId] = @rCreatedUserId 
				  ,[UpdatedDateTime] = sCommon.fGetDate()
				  ,[PayElementDefaultId] = @rPayElementDefaultId
				  ,[PayrollId]=@rPayrollId
				  ,[IsIncludeInTotal]=@rIsIncludeInTotal
			   WHERE PayrollId = @rPayrollId AND PayElementDefaultId = @rPayElementDefaultId    		     		    
			END        
	SELECT @lNextNumber AS Result	
	COMMIT TRANSACTION
	END TRY
	BEGIN CATCH
	ROLLBACK TRANSACTION
		SELECT -1 AS RESULT
	END CATCH	
END
GO
PRINT N'Altering [sPayroll].[pSelectPayElementGet]...';


GO
ALTER PROCEDURE [sPayroll].[pSelectPayElementGet]

           @rPayrollId int
           
AS
SET NOCOUNT ON

BEGIN

	SELECT  
			ISNULL(PE.ID,0) AS ID,
			PED.Code,
			PED.Title,
			PED.PayElementTypeId,
			PED.PaidCategoryId,
			ISNULL(PED.IsLwp,0) AS IsLwp,
			ISNULL(PED.IsEmployeeSpecific,0) AS IsEmployeeSpecific,
			ISNULL(PED.IsDepend,0) AS IsDepend,
			ISNULL(PED.IsAvailDuringProbation,0) AS IsAvailDuringProbation,
			ISNULL(PED.IsIncludeInPaySlip,0) AS IsIncludeInPaySlip,
			PED.SortOrder,
			--CASE ISNULL(PED.SortOrder,0)
			--	WHEN 0 THEN PED.SortOrder
			--	ELSE PE.SortOrder
			--END AS SortOrder,
			--ISNULL(PE.SortOrder,0) AS SortOrder,
			ISNULL(PE.IsObsolete,0) AS IsObsolete,
			PE.CreatedUserId,
			PE.CreatedDateTime,
			PE.UpdatedUserId,
			PE.UpdatedDateTime,
			PED.ID AS PayElementDefaultId,
			PE.PayrollId,
			PET.Title AS PayElementType,
			ISNULL(PED.IsIncludeInTotal,0) AS IsIncludeInTotal
	FROM
			sPayroll.tPayElementDefault PED 
				INNER JOIN sPayroll.tPayElementType PET 
			ON PET.Id=PED.PayElementTypeId
				LEFT JOIN sPayroll.tPayElement PE 
			ON PED.ID = PE.PayElementDefaultId AND PE.PayrollId=@rPayrollId AND PE.IsObsolete = 0
			WHERE PED.IsObsolete = 0
			
			ORDER BY PED.SortOrder
END
GO
PRINT N'Altering [sSetup].[pPortalDailyPresenceAdd]...';


GO
ALTER PROCEDURE [sSetup].[pPortalDailyPresenceAdd]
	
	@rStrXml nvarchar(MAX),
    @rOrgId int,
    @rDivisionId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET @rStrXml=REPLACE(@rStrXml,'&','AND')
DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION 
	 BEGIN
	 
	 DELETE SR FROM sAttendance.tStudentRegister SR 
	 INNER JOIN sStudent.tAcademic SA ON SA.Id = SR.AcademicId
	 INNER JOIN 
	 (SELECT AcademicId, AttendanceTypeId, AttendanceDate FROM OPENXML(@loDoc, '/Table/RowData', 1)
	 WITH
	 (		
		AcademicId bigint,
		AttendanceTypeId tinyint,
		AttendanceDate date
	  ))A ON SR.AcademicId = A.AcademicId 
		AND SR.AttendanceTypeId = A.AttendanceTypeId 
		AND SR.AttendanceDate = A.AttendanceDate
	    WHERE SA.DivisionId=@rDivisionId AND SA.OrgId = @rOrgId
	 
	 INSERT INTO sAttendance.tStudentRegister 
		(
			AcademicId,
			EmployeeId,
			AttendanceTypeId,
			AttendanceDate,
			SubjectId,
			RepeatCount,
			IsPresent,
			AbsentReasonId,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime,
			AttendanceTagId
			)
		SELECT		
			AcademicId,
			EmployeeId,
			AttendanceTypeId,
			AttendanceDate,
			SubjectId,
			RepeatCount,
			IsPresent,
			AbsentReasonId,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime,
			AttendanceTagId
						
		FROM OPENXML (@loDoc, '/Table/RowData', 1)
		WITH ( 
				AcademicId bigint,
			    EmployeeId bigint,
			    AttendanceTypeId tinyint,
				AttendanceDate date,
				SubjectId int,
				RepeatCount tinyint,
				IsPresent bit,
				AbsentReasonId int,
				CreatedUserId bigint,
				CreatedDateTime datetime,
				UpdatedUserId bigint,
				UpdatedDateTime datetime,
				AttendanceTagId int
			  ) 
		
        SELECT 1 AS Result
	 END	
	
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sStudent].[pStudentDelete]...';


GO
ALTER PROCEDURE [sStudent].[pStudentDelete]
	 @rId bigint
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	BEGIN TRY
		BEGIN TRANSACTION SD			 
			Delete from sStudent.tStudentAdmission where StudentId=@rId
			Delete from sStudent.tStudentCommunication where StudentId=@rId
			Delete from sStudent.tStudentImages where StudentId=@rId
			Delete from sStudent.tStudentFamily where StudentId=@rId
			Delete from sStudent.tStudentOther where StudentId=@rId
			Delete from sStudent.tStudentHealth where StudentId=@rId
			
			Delete from sStudent.tStudentAdditional where StudentId=@rId
			Delete from sStudent.tStudentSibling where StudentId=@rId
			Delete from sStudent.tCollegeDetail where StudentId=@rId
			
			Delete from sSecurity.tDivisionPermission Where UserId IN(SELECT Id FROM sSecurity.tUser Where SourceId=@rId AND SourceTypeId=2003)
			Delete from sSecurity.tUserPreference Where UserId IN(SELECT Id FROM sSecurity.tUser Where SourceId=@rId AND SourceTypeId=2003)
			Delete from sSecurity.tUserProfile Where UserId IN(SELECT Id FROM sSecurity.tUser Where SourceId=@rId AND SourceTypeId=2003)
			Delete from sSecurity.tUserRole Where UserId IN(SELECT Id FROM sSecurity.tUser Where SourceId=@rId AND SourceTypeId=2003)
			Delete from sSecurity.tUser Where SourceId=@rId AND SourceTypeId=2003
			--Delete from sStudent.tAcademic where studentId=@rId
			Delete from sStudent.tStudentMaster where Id=@rId
		COMMIT TRANSACTION	SD
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION SD
	END CATCH	
END
GO
PRINT N'Altering [sStudent].[pStudentFullProfileGet]...';


GO

ALTER PROCEDURE [sStudent].[pStudentFullProfileGet]
	 
	 @rBatchId int,
	 @rStudentId bigint,
	 @rReportId int=0,
	 @rOrgId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	
	SELECT 
			--Academic
			SA.StudentId AS Id,
			SA.FirstName + ' ' + ISNULL(SA.MiddleName,'') + ' ' + 	SA.LastName AS StudentName,
			SA.Batch AS AcademicYear,
			ISNULL(SA.Code,' - ') AS Code,
			SA.ClassDivision AS ClassDiv,			
			SA.RollNo,
			ISNULL(SM.Title,'-') AS House,
			--Other
			CASE WHEN @rReportId=0 THEN ISNULL(SA.DateOfBirth,'0001/01/01')  
			WHEN @rReportId=1 THEN  SA.DateOfBirth END  AS DateOfBirth,
			ISNULL(SA.BirthTaluka,'') AS BirthTaluka,
			ISNULL(SA.BirthPlace,'') AS BirthPlace,	
			ISNULL(SA.BirthDistrict,'') AS BirthDistrict,
			ISNULL(SA.BirthDateInWord,'') AS BirthDateInWord,                           
			ISNULL(SA.Gender,'') AS Gender,
			ISNULL(SA.Religion,'') AS Religion,
			--Admission			
			ISNULL(SA.AdmissionStandard,'') AS AdmissionStandard,
			--ISNULL(SA.AdmissionDate,'0001/01/01') AS AdmissionDate,
			CASE WHEN @rReportId=0 THEN ISNULL(SA.AdmissionDate,'0001/01/01')
			WHEN @rReportId=1 THEN  SA.AdmissionDate END AS AdmissionDate,
	
			ISNULL(SA.PreviousSchool,'') AS PreviousSchool,
			ISNULL(SA.AdmissionCategory,'') AS StudentAdmissionCategory,
			CASE WHEN @rReportId=0 THEN ISNULL(SA.LeftDate,'0001/01/01')
			WHEN @rReportId=1 THEN  SA.LeftDate END AS LeftDate,
						 
			ISNULL(SA.LeftStandard,'') AS LeftStandard,
			--ISNULL(SA.InactiveDate,'0001/01/01') AS InactiveDate,
			CASE WHEN @rReportId=0 THEN ISNULL(SA.InactiveDate,'0001/01/01')
			WHEN @rReportId=1 THEN  SA.InactiveDate END AS InactiveDate,		
			ISNULL(SA.LCNumber,'') AS LCNumber,
			--ISNULL(SA.LCDate,'0001/01/01') AS LCDate,
			 CASE WHEN @rReportId=0 THEN ISNULL(SA.LCDate,'0001/01/01')
			WHEN @rReportId=1 THEN  SA.LCDate END AS LCDate,
			--Communication
			ISNULL(SC.PresentStreetone,'') + ' ' + ISNULL(SC.PresentStreetTwo,'') + ' ' + ISNULL(SC.PresentStreetThree,'') AS PresentAddress,
			ISNULL(SC.PresentCity,'') AS PresentCity,
			ISNULL(SC.PresentState,'') AS PresentState,
			ISNULL(SC.PresentCountry,'') AS PresentCountry,
			ISNULL(SC.PresentZipCode,'') AS PresentZipCode,
			ISNULL(SC.PresentContactNo,'') AS PresentContactNo,
			
			ISNULL(SC.EmergencyStreetOne,'') + ' ' + ISNULL(SC.EmergencyStreetTwo,'') + ' ' + ISNULL(SC.EmergencyStreetThree,'') AS EmergencyAddress,
			ISNULL(SC.EmergencyCity,'') AS EmergencyCity,
			ISNULL(SC.EmergencyState,'') AS EmergencyState,
			ISNULL(SC.EmergencyCountry,'') AS EmergencyCountry,
			ISNULL(SC.EmergencyZipCode,'') AS EmergencyZipCode,
			ISNULL(SC.EmergencyContactNo,'') AS EmergencyContactNo,
			
			ISNULL(SC.PermanentStreetOne,'') + ' ' + ISNULL(SC.PermanentStreetTwo,'') + ' ' + ISNULL(SC.PermanentStreetThree,'') AS PermanentAddress,
			ISNULL(SC.PermanentCity,'') AS PermanentCity,
			ISNULL(SC.PermanentState,'') AS PermanentState,
			ISNULL(SC.PermanentCountry,'') AS PermanentCountry,
			ISNULL(SC.PermanentZipCode,'') AS PermanentZipCode,
			ISNULL(SC.PermanentContactNo,'') AS PermanentContactNo,
			--Parent Information
			ISNULL(SF.FatherName,'') AS FatherName,
			ISNULL(SF.FatherOccupation,'') AS FatherOccupation,
			ISNULL(SF.FatherQualification,'') AS FatherQualification,
			ISNULL(SF.FatherContactNo,'') AS FatherContactNo,
			ISNULL(SF.FatherMail,'') AS FatherMail,
			ISNULL(SF.FatherOfficeAddress,'') AS FatherOfficeAddress,
			
			ISNULL(SF.MotherName,'') AS MotherName,
			ISNULL(SF.MotherOccupation,'') AS MotherOccupation,
			ISNULL(SF.MotherQualification,'') AS MotherQualification,
			ISNULL(SF.MotherContactNo,'') AS MotherContactNo,
			ISNULL(SF.MotherMail,'') AS MotherMail,
			ISNULL(SF.MotherOfficeAddress,'') AS MotherOfficeAddress,
			
			ISNULL(SF.RelationshipName,'') AS RelationShip,
			ISNULL(SF.RelativeName,'') AS RelativeName,
			ISNULL(SF.RelativeOccupation,'') AS RelativeOccupation,
			ISNULL(SF.RelativeQualification,'') AS RelativeQualification,
			ISNULL(SF.RelativeContactNo,'') AS RelativeContactNo,
			ISNULL(SF.RelativeMail,'') AS RelativeMail,
			ISNULL(SF.RelativeOfficeAddress,'') AS RelativeOfficeAddress,
			
			
			--Health Information
			ISNULL(SA.BloodGroup,'') AS BloodGroup,
			ISNULL(SH.IdentificationMark1,'')+' '+ISNULL(SH.IdentificationMark2,'') as IdentificationMark,
			
			ISNULL(SH.FamilyDoctorName,'') AS FamilyDoctorName,
			ISNULL(SH.FamilyDoctorContactNo,'') AS FamilyDoctorContactNo,
			
			ISNULL(SH.IsPysicalDeformity,0) AS IsPysicalDeformity,
			ISNULL(SH.PysicalDeformityRemark,'') AS PysicalDeformityRemark,
			ISNULL(SH.IsMajorIllness,0) AS IsMajorIllness,
			ISNULL(SH.MajorIllnessRemark,'') As MajorIllnessRemark,
			ISNULL(SH.IsAllergy,0) AS IsAllergy,
			ISNULL(SH.AllergyRemark,'') As AllergyRemark,
			ISNULL(SH.IsPastHistory,0) As IsPastHistory ,
			ISNULL(SH.PastHistoryRemark,'') As PastHistoryRemark,
			--Hostel
			ISNULL(RM.Title,'') AS RoomNo,			
			ISNULL(HM.Title,'') AS Hostel,
			ISNULL(EMW.FirstName,'')+' '+ISNULL(EMW.LastName,'') AS WardenName,
			ISNULL(ECW.PhoneNoCompany,'') As WardenPhoneNo,
			ISNULL(ECW.ExtensionNo,'') AS WardenExtNo,
			ISNULL(ECW.MobileNumber,'') AS WardenMobileNo,
			ISNULL(EMA.FirstName,'')+' '+ISNULL(EMA.LastName,'') AS AssignedRoomBy,	
			ISNULL(ECA.PhoneNoCompany,'') AS AssignedRoomByPhoneNo,
			ISNULL(ECA.ExtensionNo,'') AS AssignedRoomByExtNo,
			ISNULL(ECA.MobileNumber,'') AS AssignedRoomByMobileNo,
			--Notification Details
			ISNULL(SC.ParentEmail,'') AS ParentEmail,
			ISNULL(SC.ParentContactNo,'') As ParentContactNo,
			ISNULL(SC.StudentEmail,'') AS StudentEmail,
			ISNULL(SC.StudentContactNo,'') AS StudentContactNo,
					
	   	    --ISNULL(SA.StudentPhoto, CONVERT(VARBINARY(MAX), 0))AS StudentPhoto,
	   	   -- ISNULL(SA.FatherPhoto, CONVERT(VARBINARY(MAX), 0)) AS FatherPhoto,
	   	   -- ISNULL(SA.MotherPhoto, CONVERT(VARBINARY(MAX), 0)) AS MotherPhoto,
	   	    --ISNULL(SA.RelativePhoto, CONVERT(VARBINARY(MAX), 0)) AS RelativePhoto,
	   	   CASE WHEN @rReportId=0
			THEN ISNULL(SA.StudentPhoto, CONVERT(VARBINARY(MAX), 0))
			WHEN @rReportId=1
			THEN ISNULL(SA.StudentPhoto, CONVERT(VARBINARY(MAX), ''))
			END AS StudentPhoto,
			
			CASE WHEN @rReportId=0
			THEN ISNULL(SA.MotherPhoto, CONVERT(VARBINARY(MAX), 0))
			WHEN @rReportId=1
			THEN ISNULL(SA.MotherPhoto, CONVERT(VARBINARY(MAX), ''))
			END AS MotherPhoto,
			
			CASE WHEN @rReportId=0
			THEN ISNULL(SA.FatherPhoto, CONVERT(VARBINARY(MAX), 0))
			WHEN @rReportId=1
			THEN ISNULL(SA.FatherPhoto, CONVERT(VARBINARY(MAX), ''))
			END AS FatherPhoto,
			
			CASE WHEN @rReportId=0
			THEN ISNULL(SA.RelativePhoto, CONVERT(VARBINARY(MAX), 0))
			WHEN @rReportId=1
			THEN ISNULL(SA.RelativePhoto, CONVERT(VARBINARY(MAX), ''))
			END AS RelativePhoto,
		   -- Transport Details
		    VM.Title AS VehicleName,
		    VM.RegistrationNumber AS VehicleRegistrationNumber,
		    TV.Title AS TypeOfVehicle,
		    ISNULL(BRM.Title,'') AS BusRoute,
		    BRM.DriverName,
		    BRM.DriverMobileNo,
		    BRM.ConductorName,
		    BRM.ConductorMobileNo,
		    ISNULL(BRDM.Title,'') AS BusRouteDestination,
		    
		    VM.Title AS DropVehicleName,
		    VM.RegistrationNumber AS DropVehicleRegistrationNumber,
		    TV1.Title AS DropTypeOfVehicle,
		    ISNULL(BRM1.Title,'') AS DropRoute,
		    BRM1.DriverName AS DropRouteDriverName,
		    BRM1.DriverMobileNo AS DropRouteDriverMobileNo,
		    BRM1.ConductorName AS DropRouteConductorName,
		    BRM1.ConductorMobileNo AS DropRouteConductorMobileNo,
		    ISNULL(BRDM1.Title,'') AS DropDestination,
		    
		    --ClassTeacher Details
		    ISNULL(EMT.Id,0) AS TeacherId,
		    EMT.FirstName+' '+EMT.MiddleName+' '+EMT.LastName AS TeacherFullName,
		    EDM.Title AS TeacherDesignation,
		    EPD.Qualification AS TeacherQualification,
		    ISNULL(EI.EmployeePhoto, CONVERT(VARBINARY(MAX), 0)) AS TeacherPhoto,
		    ISNULL(DF.IsDisplayFamilyDetail,0) AS IsDisplayFamilyDetail,
		    ISNULL(DF.IsDisplaySiblingDetail,0) AS IsDisplaySiblingDetail,
		    ISNULL(DF.IsDisplayPassportDetail,0) AS IsDisplayPassportDetail,
		    ISNULL(DF.IsDisplayBankDetail,0) AS IsDisplayBankDetail,
		    ISNULL(DF.IsDisplayCBSEREGDetail,0) AS IsDisplayCBSEREGDetail,
		    ISNULL(DF.IsDisplayCollegeDetail,0) AS IsDisplayCollegeDetail,
		    ISNULL(DF.IsDisplayGOVREGNoDetail,0) AS IsDisplayGOVREGNoDetail,
		    ISNULL(DF.IsDisplayHealthDetail,0) AS IsDisplayHealthDetail,
		    ISNULL(DF.IsDisplayTransportDetail,0) AS IsDisplayTransportDetail,
		    ISNULL(DF.IsDisplayHostelDetail,0) AS IsDisplayHostelDetail,
		    ISNULL(DF.IsDisplayClubDetail,0) AS IsDisplayClubDetail,
		    
		    ISNULL(DF.IsDisplaySSCResultDDetail,0) AS IsDisplaySSCResultDDetail,
		    ISNULL(DF.IsDisplayHSCResultDetail,0) AS IsDisplayHSCResultDetail,
		    ISNULL(DF.IsDisplayJeeDetail,0) AS IsDisplayJeeDetail,
		    ISNULL(DF.IsDisplayDiplomaDetail,0) AS IsDisplayDiplomaDetail,
		    --Sibling Detail
		    isnull(SS.SiblingName1,'') AS SiblingName1,
	        ISNULL (SS.SiblingInstitue1,'') AS SiblingInstitue1,
	        ISNULL(SS.SiblingClass1,'')AS SiblingClass1,
	        ISNULL(SS.SiblingAge1,'')AS SiblingAge1,
	        ISNULL(SS.SiblingRelation1,'')AS SiblingRelation1,
	        isnull(SS.SiblingName2,'') AS SiblingName2,
	        ISNULL(SS.SiblingInstitue2,'')AS SiblingInstitue2,
	        ISNULL(SS.SiblingClass2,'')AS SiblingClass2,
	        ISNULL(SS.SiblingAge2,'') AS SiblingAge2,
	        ISNULL(SS.SiblingRelation2,'')AS SiblingRelation2,
	        isnull(SS.SiblingName3,'') AS SiblingName3,
	        ISNULL( SS.SiblingInstitue3,'')AS SiblingInstitue3,
	        ISNULL(SS.SiblingClass3,'')AS SiblingClass3,
	        ISNULL(SS.SiblingAge3,'')AS SiblingAge3,
	        ISNULL(SS.SiblingRelation3,'')AS SiblingRelation3,
	        ISNULL(SAD.BankAccountNumber,'')AS BankAccountNumber,
	        ISNULL(SAD.BankName,'')AS BankName,
	        ISNULL(SAD.BankBranch,'') AS BankBranch,
	        ISNULL(SAD.BankIFSCCode,'')AS BankIFSCCode,
	        ISNULL(SAD.Class9BoardRegistrationNumber,'') AS Class9BoardRegistrationNumber,
	        ISNULL(SAD.Class11BoardRegistrationNumber,'')AS Class11BoardRegistrationNumber,
	        ISNULL(SAD.PassportNumber,'')AS PassportNumber, 
	        ISNULL(SAD.PassportType,'') AS PassportType,
	       ISNULL( SAD.PassportCountryCode,'') AS PassportCountryCode,
	        CASE WHEN @rReportId=0 THEN ISNULL(SAD.PassportIssueDate,'0001/01/01')
			WHEN @rReportId=1 THEN  SAD.PassportIssueDate END AS PassportIssueDate,
			CASE WHEN @rReportId=0 THEN ISNULL(SAD.PassportExpiryDate,'0001/01/01')
			WHEN @rReportId=1 THEN  SAD.PassportExpiryDate END AS PassportExpiryDate,
	        ISNULL(SA.UIDNumber,'')AS UIDNumber,
	        ISNULL(SA.AdhaarNumber,'') AS AdhaarNumber,
	       ISNull(SA.StatusId,0) AS StatusId,
	       ISNUll(SA.IsTransfer,0)AS IsTransfer,
	       ISNULL(SA.TransferFrom,'') AS TransferFrom,
	       ISNULL(SA.CertificateName,'') AS CertificateName,
	       ISNUll(SA.IsTFWS,0)AS IsTFWS,
	       ISNUll(SA.IsCertificateHolder,0)AS IsCertificateHolder,
	       ISNULL(CD.SSCBoard,'') AS SSCBoard,
	       ISNULL(CD.SSCSchool,'') AS SSCSchool,
	       ISNULL(CD.SSCPassingYear,'') AS SSCPassingYear,
	       ISNULL(CD.SSCObtainMarks,0) AS SSCObtainMarks,
	       ISNULL(CD.SSCOutOfMarks,0) AS SSCOutOfMarks,
	       ISNULL(CD.SSCPercentage,0) AS SSCPercentage,
	       ISNULL(CD.SSCMathMarks,0) AS SSCMathMarks,
	       ISNULL(CD.SSCMathOutOfMarks,0) AS SSCMathOutOfMarks,
	       ISNULL(CD.HSCBoard,'') AS HSCBoard,
	       ISNULL(CD.HSCSchool,'') AS HSCSchool,
	       ISNULL(CD.HSCPassingYear,0) AS HSCPassingYear,
	       ISNULL(CD.HSCObtainMarks,0) AS HSCObtainMarks,
	       ISNULL(CD.HSCOutOfMarks,0) AS HSCOutOfMarks,
	       ISNULL(CD.HSCPercentage,0) AS HSCPercentage,
	       ISNULL(CD.HSCPhysicsMarks,0) AS HSCPhysicsMarks,
	       ISNULL(CD.HSCPhysicsOutOfMarks,0) AS HSCPhysicsOutOfMarks,
	       ISNULL(CD.HSCChemistryMarks,0) AS HSCChemistryMarks,
	       ISNULL(CD.HSCChemistryOutOfMarks,0) AS HSCChemistryOutOfMarks,
	       ISNULL(CD.HSCMathMarks,0) AS HSCMathMarks,
	       ISNULL(CD.HSCMathOutOfMarks,0) AS HSCMathOutOfMarks,
	       ISNULL(CD.HSCBiologyMarks,0) AS HSCBiologyMarks,
	       ISNULL(CD.HSCBiologyOutOfMarks,0) AS HSCBiologyOutOfMarks,
	       ISNULL(CD.PCMMarks,0) AS PCMMarks,
	       ISNULL(CD.PCBMarks,0) AS PCBMarks,
	       ISNULL(CD.JEERollNo,'') AS JEERollNo,
	       ISNULL(CD.JEEMeritNo,'') AS JEEMeritNo,
	       ISNULL(CD.JEEMeritMarks,0) AS JEEMeritMarks,
	       ISNULL(CD.JEEOutOfMarks,0) AS JEEOutOfMarks,
	       ISNULL(CD.DiplomaBoard,'') AS DiplomaBoard,
	       ISNULL(CD.DiplomaCollege,'') AS DiplomaCollege,
	       ISNULL(CD.DiplomaPassingYear,'') AS DiplomaPassingYear,
	       ISNULL(CD.DiplomaObtainMarks,0) AS DiplomaObtainMarks,
	       ISNULL(CD.DiplomaOutOfMarks,0) AS DiplomaOutOfMarks,
	       ISNULL(CD.DiplomaPercentage,0) AS DiplomaPercentage,
	       ISNULL(CD.ApplicationNo,'') AS ApplicationNo,
	       ISNULL(CD.AdmissionRound,0) AS AdmissionRound,
	       ISNULL(CD.MaritalStatusId,0) AS MaritalStatusId,
	       ISNULL(MS.Title,'') AS MaritalStatus,
	       ISNULL(ACD.RepeatCount,1)AS RepeatCount
	       --,
	       --[sHostel].[fHostelWardenGet](HM.Id) As WardenName
	       
	       
		    
  FROM 
           sStudent.vStudentAllDetail SA
           LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
           LEFT JOIN sStudent.tStudentHealth SH ON SA.StudentId=SH.StudentId
           LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SA.StudentId 
           LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId = SA.StudentId
           LEFT JOIN sActivity.tHouseMaster SM ON SM.ID = SO.HouseId
           LEFT JOIN sHostel.tAssignRoom AR ON AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003
           LEFT JOIN sHostel.tRoomMaster RM ON RM.Id=AR.RoomId
           LEFT JOIN sHostel.tHostelMaster HM ON HM.Id=RM.HostelId      
            
            LEFT JOIN
            (
		   SELECT 
		   employeeId, 
		   HostelId,   
		   ROW_NUMBER() OVER (PARTITION BY HostelId ORDER By HostelId ) as ROWNo 		   
		 
		   FROM sHostel.tHostelwarden 
            )  HW ON HW.HostelId=HM.Id AND RowNo = 1       
           --LEFT JOIN sHostel.tHostelWarden HW ON HW.HostelId=HM.Id
           LEFT JOIN sHrm.tEmployeeMaster EMW ON HW.EmployeeId=EMW.Id
           LEFT JOIN sHrm.tEmployeeMaster EMA ON RM.AssignedEmployeeId=EMA.Id
           LEFT JOIN sHrm.tEmployeeCommunications ECW ON EMW.Id=ECW.EmployeeId 
           LEFT JOIN sHrm.tEmployeeCommunications ECA ON  EMA.Id=ECA.EmployeeId
           LEFT JOIN sTransport.tAssignRoute AR1 ON AR1.SourceId=SA.StudentId AND AR1.SourceTypeId=2003
           LEFT JOIN sTransport.tBusRouteDestinationMaster BRDM ON BRDM.Id=AR1.PickupDestinationId
           LEFT JOIN sTransport.tBusRouteMaster BRM ON BRM.Id=BRDM.BusRouteId
           LEFT JOIN sTransport.tVehicleMaster VM ON VM.Id=BRM.VehicleId
           LEFT JOIN sTransport.tVehicleTypeMaster TV ON TV.Id = VM.VehicleTypeId
           LEFT JOIN sTransport.tBusRouteDestinationMaster BRDM1 ON BRDM1.Id=AR1.DropDestinationId
           LEFT JOIN sTransport.tBusRouteMaster BRM1 ON BRM1.Id=BRDM1.BusRouteId
           LEFT JOIN sTransport.tVehicleMaster VM1 ON VM1.Id=BRM1.VehicleId
           LEFT JOIN sTransport.tVehicleTypeMaster TV1 ON TV1.Id = VM1.VehicleTypeId
           LEFT JOIN sSetup.tDivisionMaster DM ON  DM.Id=SA.DivisionId
           LEFT JOIN sHrm.tEmployeeMaster EMT ON EMT.Id=DM.InchargeEmployeeId
           LEFT JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EMT.Id
           LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id=EJD.EmployeeDesignationId
           LEFT JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId=EMT.Id
           LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId=EMT.Id
           LEFT JOIN sStudent.tStudentSibling  SS ON SS.StudentId=SA.StudentId 
           LEFT JOIN sStudent.tStudentAdditional  SAD ON SAD.StudentId=SA.StudentId 
           LEFT JOIN sStudent.tCollegeDetail  CD ON CD.StudentId=SA.StudentId 
           LEFT JOIN sStudent.tAcademicDetail  ACD ON ACD.AcademicId=SA.AcademicId 
           LEFT JOIN sCommon.tMaritalStatusMaster  MS ON MS.Id=CD.MaritalStatusId
           LEFT JOIN sConfig.fDisplayFieldGet(@rOrgId) AS DF ON DF.OrgId=SA.OrgId
           
             
  WHERE 
			((SA.StudentId=@rStudentId)OR(@rStudentId=0))
			AND(SA.BatchId=@rBatchId)
			--AND(SA.OrgId=@rOrgId)
			
END
GO
PRINT N'Altering [sStudent].[pStudentImportGet]...';


GO

ALTER PROCEDURE [sStudent].[pStudentImportGet]
	 
	@rClassId int=0,
	@rDivisionId int=0,
	@rOrgId int,
	@rBatchId int
	
	
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 
		
	SELECT 
			SA.Id AS AcademicId,
			SA.StudentId,
			ISNULL(SA.RollNo,0) AS RollNo,
			SM.FirstName+' '+SM.LastName AS Name,
			SM.Code,
			STM.Id AS StatusId,
			STM.Title AS StatusName,
			
			CM.Id AS ClassId,
			CM.Title AS ClassName,
			DM.Id AS DivisionId,
			DM.Title AS DivisionName,
			ISNULL(SA.ExemptionTypeId,0) AS ExemptionTypeId
			
			
			
    FROM 
           sStudent.tAcademic SA
           INNER JOIN sStudent.tStudentMaster SM
           ON SM.Id=SA.StudentId
           INNER JOIN sStudent.tStatusMaster STM
           ON STM.Id=SM.StatusId
           INNER JOIN sSetup.tClassMaster CM
           ON CM.Id=SA.ClassId
           INNER JOIN sSetup.tDivisionMaster DM
           ON DM.Id=SA.DivisionId             
  WHERE 
 
		((SA.ClassId=@rClassId)OR(@rClassId=0))
		AND((SA.DivisionId=@rDivisionId)OR(@rDivisionId=0))
		AND((SA.BatchId=@rBatchId)OR(@rBatchId=0))	
		AND(SA.OrgId=@rOrgId)
		
ORDER BY SA.RollNo

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


GO
ALTER PROCEDURE [sStudent].[pStudentProfileGet]
	 
	 @rBatchId int,
	 @rStudentId bigint
	 --@rIsSearch bit
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	
	SELECT 
			SA.FirstName + ' ' + ISNULL(SA.MiddleName,'') + ' ' + 	SA.LastName AS StudentName,
			SA.Batch AS AcademicYear,
			ISNULL(SA.Code,'') AS Code,
			SA.DateOfBirth,
			SA.RollNo,
			ISNULL(SA.BirthPlace,'-') AS BirthPlace,
			SA.ClassDivision AS ClassDiv,
			SA.StudentId AS Id,
			--SA.GenderId			
			ISNULL(SM.Title,'-') AS House,
			ISNULL(SA.BloodGroup,'-') AS BloodGroup,
	   	    ISNULL(SA.StudentPhoto, CONVERT(VARBINARY(MAX), 0)) AS StudentPhoto,
			ISNULL(SA.PresentStreetone,'') + ' ' + ISNULL(SA.PresentStreetTwo,'') + ' ' + ISNULL(SA.PresentStreetThree,'') AS PresentAddress,
			ISNULL(SA.PresentCity,'-') AS City,
			ISNULL(SA.PresentState,'-') As State,
			ISNULL(SA.PresentZipCode,'-') as PinCode,
			ISNULL(SA.PresentCountry,'-') AS Country,
			ISNULL(SA.PresentContactNo,'-') as ContactNo,
			ISNULL(SF.FatherName,'-') AS FatherName,
			ISNULL(SF.FatherOccupation,'-') AS Occupation,
			ISNULL(SF.FatherQualification,'-') AS Qualification,
			SA.Gender,
			ISNULL(SF.FatherContactNo,'-') AS FatherContactNo,
			ISNULL(SF.FatherMail,'-') AS FatherMail,
			ISNULL(SF.FatherOfficeAddress,'-') AS FatherOfficeAddress,
			ISNULL(SA.ParentEmail,'-') AS ParentEmail,
			ISNULL(SA.ParentContactNo,'-') AS ParentContactNo,
			ISNULL(SA.DepartmentId,0) AS DepartmentId,
			ISNULL(SA.ClassId,0) AS ClassId,
			ISNULL(SA.DivisionId,0) AS DivisionId,
			OM.DisplayTitle AS OrgTitle
			
  FROM 
           sStudent.vStudentAllDetail SA
           --LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
           LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SA.StudentId 
           ----AND SF.RelationshipId = 1
           --LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId = SA.StudentId
           LEFT JOIN sActivity.tHouseMaster SM ON SM.ID = SA.HouseId
           --LEFT JOIN sCommon.tGenderMaster GM ON GM.ID = SO.GenderId
           INNER JOIN sSetup.tOrganizationMaster OM 
			ON OM.Id=SA.OrgId  
             
  WHERE 
			((SA.StudentId=@rStudentId)OR(@rStudentId=0))
			AND(SA.BatchId=@rBatchId)
			
 
  
		
END
GO
PRINT N'Altering [sStudent].[pXMLAcademicImportAdd]...';


GO
 

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

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

DECLARE @lToClassId int 
DECLARE @lToOrgId int
SELECT @lToClassId = ClassId,@lToOrgId = OrgId FROM sSetup.tDivisionMaster WHERE Id = @rToDivisionId
 

 
 
 IF (@lToOrgId <> @rToOrgId )
 BEGIN
 SELECT 'Org Not Matching, Contact Administrator'
		RETURN
 END
 
 
Declare @lExistCode nvarchar(max)
 
	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.Id=E.StudentId AND SM.OrgId=@rToOrgId
	INNER JOIN sStudent.tAcademic A ON A.StudentId=SM.Id AND A.BatchId=@rToBatchId)
	BEGIN
		SELECT @lExistCode  = COALESCE(@lExistCode ,'') + CONVERT(VARCHAR(15),SM.Code) + ' , ' 
		from
		(
				SELECT StudentId FROM
				OPENXML (@loDoc, '/Table/StudentImportDetail', 1)
				WITH (
						StudentId bigint)	
		)E
		INNER JOIN sStudent.tStudentMaster SM ON SM.Id=E.StudentId AND SM.OrgId=@rToOrgId
		INNER JOIN sStudent.tAcademic A ON A.StudentId=SM.Id AND A.BatchId=@rToBatchId
		SELECT @lExistCode
	 	RETURN
	END
	
	BEGIN TRY
	BEGIN TRANSACTION
	DECLARE @lCount INT
	DECLARE @lNextNumber BIGINT 
	
	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,
			IsCurrent,
			ExemptionTypeId
			)
		SELECT
		
			@lNextNumber+ ROW_NUMBER() OVER(ORDER BY StudentId),
			StudentId,
			@lToClassId,
			@rToBatchId,
			@rToDivisionId,
			0,
			@rToOrgId,
			@rCreatedUserId,
			sCommon.fGetDate(),
			1,
			ExemptionTypeId
		FROM OPENXML (@loDoc, '/Table/StudentImportDetail', 1)
		WITH ( 
				StudentId bigint,
				ExemptionTypeId int
			  ) 
			  --B INNER JOIN sStudent.tAcademic A ON B.StudentId = A.StudentId AND A.BatchId = 
		
		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 
	    SELECT 1 AS Result
		
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sTally].[pFeeLedgerMappingGet]...';


GO
ALTER PROCEDURE [sTally].[pFeeLedgerMappingGet]

	 @rOrgGroupBatchId int,
	 @rReceiptBookId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
		
		SELECT Distinct
			   FHM.TITLE AS FeeName,
			   FHM.Id AS FeeId,
			   FLM.LedgerName,
			   RBC.CompanyName 
	    FROM sFee.tFeeSetup FS
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = FS.BatchId AND BM.OrgGroupBatchId = @rOrgGroupBatchId
		INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
		INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FM.FeeHeadId
		INNER JOIN sTally.tReceiptBookCompanyMapping RBC ON RBC.ReceiptBookId = FS.ReceiptBookId AND RBC.OrgGroupBatchId = @rOrgGroupBatchId
		LEFT JOIN sTally.tFeeLedgerMapping FLM ON FLM.FeeId= FHM.Id
		Where FS.ReceiptBookId = @rReceiptBookId 
		
END
GO
PRINT N'Altering [sTally].[pReceiptPostingGet]...';


GO
ALTER PROCEDURE [sTally].[pReceiptPostingGet]

	 @rOrgGroupBatchId int,
	 @rReceiptBookId int,
	 @rReceiptDate Date,
	 @rToReceiptDate Date
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	
	DECLARE @lTallyPostingType nVarchar(100)
	DECLARE @lOrgGroupId INT
	
	SELECT @lOrgGroupId = OrgGroupId from sSetup.tOrgGroupBatchMaster Where Id=@rOrgGroupBatchId
	
	SELECT @lTallyPostingType = CASE WHEN CS.ItemValue IS NULL THEN C.ItemValue ELSE CS.ItemValue END 
		FROM sConfig.tConfigurationMaster C
        INNER JOIN sConfig.tConfigurationLevelMaster CM ON CM.Id = C.ConfigurationLevelId
        LEFT JOIN sConfig.tConfigurationSetup CS ON CS.ConfigurationId = C.Id AND CS.SOURCEID= @lOrgGroupId
        WHERE  C.ItemKey = 'Tally.PostingType'
        
        IF @lTallyPostingType = 'FeeHeadWise' 
        BEGIN
			   SELECT	ReceiptDate,
						ISNULL(FHM.Title,'') AS FeeName,
						PM.Title AS PayType,
						Sum(FRD.Amount) AS Amount,
						FHM.Id AS FeeId,
						FR.PayTypeId AS PayTypeId 
				FROM sFee.tReceipt FR 
					INNER JOIN sFee.tReceiptDetail FRD ON FR.Id = FRD.ReceiptId
					INNER JOIN sFee.tFeeSetup FS ON FS.Id = FRD.FeeSetupId
					INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
					INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FM.FeeHeadId
					INNER JOIN sFinanceCommon.tPayTypeMaster PM ON PM.Id = FR.PayTypeId
					WHERE	FR.ReceiptBookId = @rReceiptBookId 
							AND FR.IsObsolete = 0 
							AND FR.OrgGroupBatchId = @rOrgGroupBatchId
							AND FR.ReceiptDate >= @rReceiptDate AND FR.ReceiptDate <= @rToReceiptDate
				group by ReceiptDate,FHM.Title,PM.Title,FHM.Id,FR.PayTypeId
				Order By ReceiptDate Desc
			END	
			
			IF @lTallyPostingType = 'ReceiptWise' 
			BEGIN	
				SELECT	ReceiptDate,						
						ISNULL(SLM.LedgerName,'') AS FeeName,
						PM.Title AS PayType,						
						Sum(FRD.Amount) AS Amount,
						case When FR.PayTypeId = 1 then
						'Std-' + ClassName + ':' + DivisionName + ' RollNo :' + convert(nvarchar(20),RollNo) + ' ' + BatchName + '-->' +
						STUFF((SELECT ','  + convert(nvarchar(20),isnull(FRD1.Amount,'')) + '-' + isnull(FM1.Title ,'') 
						from sFee.tReceipt FR1  INNER JOIN sFee.tReceiptDetail FRD1 ON FR1.Id = FRD1.ReceiptId
						INNER JOIN sFee.tFeeSetup FS1 ON FS1.Id = FRD1.FeeSetupId 						
						INNER JOIN sFee.tFeeMaster FM1 ON FM1.Id = FS1.FeeId AND FRD.ReceiptId=FRD1.ReceiptId  FOR XML PATH('')),1,1,'') 
						when FR.PayTypeId = 2 then 
						'Std-' + ClassName + ':' + DivisionName + ' RollNo :' + convert(nvarchar(20),RollNo) + ' ' + BatchName + '-->' +
						STUFF((SELECT ','  + convert(nvarchar(20),isnull(FRD1.Amount,'')) + '-' + isnull(FM1.Title ,'') 
						from sFee.tReceipt FR1  INNER JOIN sFee.tReceiptDetail FRD1 ON FR1.Id = FRD1.ReceiptId
						INNER JOIN sFee.tFeeSetup FS1 ON FS1.Id = FRD1.FeeSetupId 						
						INNER JOIN sFee.tFeeMaster FM1 ON FM1.Id = FS1.FeeId AND FRD.ReceiptId=FRD1.ReceiptId  FOR XML PATH('')),1,1,'') + '  Cheque No. :' + ISNULL(FR.ChequeNo,'') + ' BankName :' + ISNULL(FR.BankName,'')  ENd
						AS Narration,					
						FR.PayTypeId AS PayTypeId,									
						A.StudentId AS FeeId,
						FRD.ReceiptId					 
				FROM sFee.tReceipt FR 
					INNER JOIN sFee.tReceiptDetail FRD ON FR.Id = FRD.ReceiptId
					INNER JOIN sFee.tFeeSetup FS ON FS.Id = FRD.FeeSetupId
					INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
					INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FM.FeeHeadId
					INNER JOIN sFinanceCommon.tPayTypeMaster PM ON PM.Id = FR.PayTypeId
					INNER JOIN sStudent.vStudentAcademic A ON A.AcademicId = FR.SourceId
					LEFT JOIN sTally.tStudentLedgerMapping SLM ON SLM.StudentId = A.StudentId
					WHERE							
							FR.ReceiptBookId = @rReceiptBookId 
							AND FR.IsObsolete = 0 
							AND FR.OrgGroupBatchId = @rOrgGroupBatchId
							AND FR.ReceiptDate >= @rReceiptDate	And FR.ReceiptDate <= @rToReceiptDate					
				group by 
				ReceiptDate,PM.Title,
				SLM.LedgerName,FR.PayTypeId,A.StudentId,
				FRD.ReceiptId,Isnull(FR.ChequeNo,''),ISNull(FR.BankName,''),
				'Std-' + ClassName + ':' + DivisionName + ' RollNo :' + convert(nvarchar(20),RollNo) + ' ' + BatchName				
				Order By ReceiptDate desc	
			END			
			
END
GO
PRINT N'Altering [sTally].[pReceiptTallyPostingAdd]...';


GO
ALTER PROCEDURE [sTally].[pReceiptTallyPostingAdd]	 
      @rXmlDoc nvarchar(MAX),     
      @rReceiptId Int,
      @rOrgGroupBatchId Int,
      @rVoucherNumber Int    
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

SET @rXmlDoc=REPLACE(@rXmlDoc,'&','AND')
DECLARE @lInterrorCode INT,
			@intDoc INT
		
	BEGIN TRY
	 BEGIN TRANSACTION	
		
	EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc
	
	
			
		
	
	UPDATE sTally.tReceiptPosting
	SET
		TransactionDate=A1.ReceiptDate,
		ReceiptBookId=@rReceiptId,
		StudentId=A1.FeeId,
		OrgGroupBatchId=@rOrgGroupBatchId,
		PayTypeId=A1.PayTypeId,		
		Amount = A1.Amount,
		Narration = A1.Narration
	FROM
	(
		SELECT	
			FeeId,
			PayTypeId,
			Amount,
			Narration,
			ReceiptDate			
			FROM OPENXML (@intDoc, '/Table/ReceiptTallyPosting', 1)
			WITH
			(
				FeeId bigint '@FeeId',
				PayTypeId int '@PayTypeId',
				Amount decimal(12,2) '@Amount',
				Narration nvarchar(500) '@Narration',
				ReceiptDate DateTime '@ReceiptDate'	
			))A1 INNER JOIN sTally.tReceiptPosting RP ON RP.StudentId = A1.FeeId AND RP.OrgGroupBatchId=@rOrgGroupBatchId
			AND RP.ReceiptBookId=@rReceiptId 
			AND RP.TransactionDate= A1.ReceiptDate
	
	

	INSERT INTO sTally.tReceiptPosting
		(
		TransactionDate,
		ReceiptBookId,
		FeeId,
		StudentId,
		OrgGroupBatchId,
		PayTypeId,		
		VoucherNumber,
		Amount,
		Narration
		)
	SELECT
		A.ReceiptDate,
		@rReceiptId,
		0,
		A.FeeId,
		@rOrgGroupBatchId,
		A.PayTypeId,
		@rVoucherNumber  + ROW_NUMBER() OVER(ORDER BY ReceiptBookId),
		A.Amount,
		A.Narration
		
	FROM OPENXML (@intDoc, '/Table/ReceiptTallyPosting', 1)
	WITH
	(
		FeeId bigint '@FeeId',
		PayTypeId int '@PayTypeId',
		Amount decimal(12,2) '@Amount',
		Narration nvarchar(500) '@Narration',
		ReceiptDate DateTime '@ReceiptDate'			
	)A LEFT JOIN sTally.tReceiptPosting RP ON RP.StudentId = A.FeeId AND RP.OrgGroupBatchId=@rOrgGroupBatchId
	AND RP.ReceiptBookId=@rReceiptId 
	AND RP.TransactionDate= A.ReceiptDate	
	WHERE RP.StudentId IS NULL
	
	SELECT 101 AS RESULT
	
	COMMIT TRANSACTION		
	END TRY

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


GO
ALTER PROCEDURE [sTally].[pStudentLedgerMappingGet]

	 @rOrgId int,
	 @rReceiptBookId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
		
		SELECT 
		Distinct
			   ISNULL(SM.FirstName,'') + ' ' +  ISNULL(SM.MiddleName,'') + ' ' + ISNULL(SM.LastName,'') + '#' + CONVERT(NVARCHAR(10),ISNULL(SM.OrgId,0)) + '#' + CONVERT(NVARCHAR(20),ISNULL(NUMBER,0)) AS StudentName,
			   SM.Id AS StudentId,
			   ISNULL(SLM.LedgerName,'') AS LedgerName,
			   RCM.CompanyName
			FROM sStudent.tStudentMaster SM
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SM.OrgId AND SM.OrgId = @rOrgId
			INNER JOIN sSetup.tOrgGroupBatchMaster OB ON OB.OrgGroupId = OM.OrgGRoupId
			INNER JOIN sTally.tReceiptBookCompanyMapping RCM ON RCM.OrgGroupBatchId = OB.Id AND RCM.ReceiptBookId=@rReceiptBookId
			LEFT JOIN sTally.tStudentLedgerMapping SLM ON SLM.StudentId= SM.Id AND RCM.ReceiptBookId=SLM.ReceiptBookId	
		WHERE SM.STATUSID= 1
END
GO
PRINT N'Altering [sTimetable].[pRptDivisionTimeTableGet]...';


GO
 
 

 
ALTER PROCEDURE [sTimetable].[pRptDivisionTimeTableGet]

	  --@rBuilder1 nvarchar(max)='',
	  --@rBuilder2 nvarchar(max)='', 
	  @rBatchId int,
	  @rClassId int,
	  @rDivisionId int,
	  @rEmployeeId bigint,
	  @rTimeTableSchemaId int,
	  @rReportId int=0
	
	  
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON 

BEGIN   
  IF(@rReportId=10166) -- Teacherwise
  BEGIN
  SELECT

	A.TimeTableID,
	A.DivisionName,
	
	A.EmployeeId,
	A.SubjectId,
	
	CASE WHEN A.EmployeeId=-1 THEN '###' WHEN A.EmployeeId=-2 THEN '***' ELSE A.EmployeeName END  AS EmployeeName,
	CASE WHEN A.SubjectId=-1 THEN '###' WHEN A.SubjectId=-2 THEN '***' ELSE A.Subject END  AS Subject,
	--A.Subject,
	A.DivisionId,
	ISNULL(L.Title,'') AS DayName,
	ISNULL(L.DayId,0) AS DayId,
	ISNULL(L.LectureNumber,'') AS LactureNumber,
	--ISNULL(A.DayName,'') AS DayName,
	--ISNULL(A.DayId,0) AS DayId,
	--ISNULL(A.LactureNumber,'') AS LactureNumber,
	A.DayLacture,
	A.ClassId,
	A.ClassDivisionName,
	A.DivisionOrderIndex,
	A.Code 
  FROM
(
	SELECT 
	--@rBuilder1 AS Builder1,
	--@rBuilder2 AS Builder2,	 
	TT.Id AS TimeTableID,
	ISNULL(DV.Title,'') AS DivisionName,
	ISNULL(EmployeeId,0) AS EmployeeId,
	ISNULL(SubjectId,0) AS SubjectId,

	ISNULL(Em.ShortName,'')  AS EmployeeName,  
	ISNULL(SM.Title,'') AS Subject,
	ISNULL(TT.DivisionId,0) AS DivisionId,
	ISNULL(DM.Title,'') AS DayName,
	ISNULL(TT.DayId,0) AS DayId,
	ISNULL(TT.LectureNumber,'') AS LactureNumber,
	ISNULL(DM.Title,'') +'-'+ISNULL(convert(nvarchar(4),TT.LectureNumber),'') AS DayLacture,
	ISNULL(DV.ClassId,0) AS ClassId,
	ISNULL(CM.DisplayTitle,'')+'-'+ISNULL(DV.Title,'') as ClassDivisionName,
	ISNULL(DV.OrderIndex,0) As DivisionOrderIndex,
	ISNULL(SM.Code,'') AS Code
	
	FROM 
	sTimetable.tTimeTable TT  
	LEFT JOIN sSetup.tSubjectMaster SM ON SM.Id = TT.SubjectId 
	LEFT JOIN sHrm.tEmployeeMaster Em ON Em.Id = TT.EmployeeId
	LEFT JOIN sCommon.tDayMaster DM ON DM.Id = TT.DayId
	LEFT JOIN sSetup.tDivisionMaster DV ON DV.Id = TT.DivisionId
	LEFT JOIN sSetup.tClassMaster CM ON CM.Id = DV.ClassId
	
	WHERE (ClassId = @rClassId OR @rClassId=0)
	  AND (TT.DivisionId = @rDivisionId OR @rDivisionId=0)	
	  AND (TT.EmployeeId=@rEmployeeId OR @rEmployeeId=0)
	  AND TT.TimeTableSchemaId=@rTimeTableSchemaId
	  --ORDER BY DV.OrderIndex
	  )
	  A
			RIGHT JOIN (SELECT DISTINCT DayId,LectureNumber,DM.title  FROM sTimetable.tTimeTable
			INNER JOIN sCommon.tDayMaster DM ON DM.Id = DayId
			WHERE TimeTableSchemaId=@rTimeTableSchemaId ) L
			ON A.LactureNumber = L.LectureNumber AND A.DayId = L.DayId

	END
 ELSE
 BEGIN
	SELECT

	A.TimeTableID,
	A.DivisionName,
	A.EmployeeId,
	A.SubjectId,
	CASE WHEN A.EmployeeId=-1 THEN '###' WHEN A.EmployeeId=-2 THEN '***' ELSE A.EmployeeName END As EmployeeName,
	 CASE WHEN A.SubjectId=-1 THEN '###' WHEN A.SubjectId=-2 THEN '***' ELSE A.Subject END  AS Subject,
	--A.Subject,
	A.DivisionId,
	--ISNULL(L.Title,'') AS DayName,
	--ISNULL(L.DayId,0) AS DayId,
	--ISNULL(L.LectureNumber,'') AS LactureNumber,
	ISNULL(A.DayName,'') AS DayName,
	ISNULL(A.DayId,0) AS DayId,
	ISNULL(A.LactureNumber,'') AS LactureNumber,
	A.DayLacture,
	A.ClassId,
	A.ClassDivisionName,
	A.DivisionOrderIndex,
	A.Code 
FROM
(
	SELECT 
	--@rBuilder1 AS Builder1,
	--@rBuilder2 AS Builder2,	 
	TT.Id AS TimeTableID,
	ISNULL(DV.Title,'') AS DivisionName,
	ISNULL(EmployeeId,0) AS EmployeeId,
	ISNULL(SubjectId,0) AS SubjectId,
	ISNULL(Em.ShortName,'')  AS EmployeeName,  
	ISNULL(SM.Title,'') AS Subject,
	ISNULL(TT.DivisionId,0) AS DivisionId,
	ISNULL(DM.Title,'') AS DayName,
	ISNULL(TT.DayId,0) AS DayId,
	ISNULL(TT.LectureNumber,'') AS LactureNumber,
	ISNULL(DM.Title,'') +'-'+ISNULL(convert(nvarchar(4),TT.LectureNumber),'') AS DayLacture,
	ISNULL(DV.ClassId,0) AS ClassId,
	ISNULL(CM.DisplayTitle,'')+'-'+ISNULL(DV.Title,'') as ClassDivisionName,
	ISNULL(DV.OrderIndex,0) As DivisionOrderIndex,
	ISNULL(SM.Code,'') AS Code
	
	FROM 
	sTimetable.tTimeTable TT  
	LEFT JOIN sSetup.tSubjectMaster SM ON SM.Id = TT.SubjectId 
	LEFT JOIN sHrm.tEmployeeMaster Em ON Em.Id = TT.EmployeeId
	LEFT JOIN sCommon.tDayMaster DM ON DM.Id = TT.DayId
	LEFT JOIN sSetup.tDivisionMaster DV ON DV.Id = TT.DivisionId
	LEFT JOIN sSetup.tClassMaster CM ON CM.Id = DV.ClassId
	WHERE (ClassId = @rClassId OR @rClassId=0)
	  AND (TT.DivisionId = @rDivisionId OR @rDivisionId=0)	
	  AND (TT.EmployeeId=@rEmployeeId OR @rEmployeeId=0)
	  AND TT.TimeTableSchemaId=@rTimeTableSchemaId
	 
	  )
	  A  ORDER BY A.DivisionOrderIndex
		END
END
GO
PRINT N'Altering [sTimetable].[pTeacherWorkLoadAdd]...';


GO
 
ALTER PROCEDURE [sTimetable].[pTeacherWorkLoadAdd]
 	
	@rDivisionId int,
	@rSubjectId int,
	@rEmployeeId bigint,
	@rNoOfLecture smallint,
	@rIsTeacherWorkLoad bit=0,
	@rTimeTableSchemaId int,
	@rLectureLength smallint=0,
	@rBatchId int,
	@rCreatedUserId bigint
  
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
 
BEGIN
	BEGIN TRY
BEGIN	
	IF  (@rIsTeacherWorkLoad=1)
		BEGIN
		IF EXISTS(select EmployeeId from sTimetable.tTeacherWorkLoad where  DivisionId=@rDivisionId AND SubjectId=@rSubjectId AND TimeTableSchemaId=@rTimeTableSchemaId)
		BEGIN
			Select -103 AS Result
			RETURN
		END
		ELSE
		BEGIN
			DECLARE @lDWLNoOfLecture AS smallint
			DECLARE @lTWLNoOfLecture AS smallint
			Select @lDWLNoOfLecture = NoOfLecture from sTimetable.tDivisionWorkLoad where DivisionId = @rDivisionId AND SubjectId=@rSubjectId AND TimeTableSchemaId=@rTimeTableSchemaId
			select 
				@lTWLNoOfLecture=SUM(TWL.NoOfLecture) 
			from
				sTimetable.tDivisionWorkLoad DWL
			INNER JOIN sTimetable.tTeacherWorkLoad TWL
			ON DWL.DivisionId=TWL.DivisionId AND DWL.SubjectId=TWL.SubjectId 
			WHERE TWL.DivisionId=@rDivisionId AND TWL.SubjectId=@rSubjectId 
				AND TWL.TimeTableSchemaId=@rTimeTableSchemaId
				AND DWL.TimeTableSchemaId=@rTimeTableSchemaId
			IF(@lDWLNoOfLecture<@lTWLNoOfLecture+@rNoOfLecture)
			BEGIN
				SELECT -102 AS RESULT
				RETURN
			 END
			 ELSE
			 BEGIN
					INSERT INTO sTimetable.tTeacherWorkLoad
		(
			EmployeeId,
			BatchId,
			DivisionId,
			SubjectId,
			NoOfLecture,
			CreatedUserId,
			CreatedDateTime,
			TimeTableSchemaId,
			LectureLength
			)
		Values
		(
			@rEmployeeId,
			@rBatchId,
			@rDivisionId,
			@rSubjectId,
			@rNoOfLecture,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rTimeTableSchemaId,
			@rLectureLength
		 )
        SELECT 1 AS Result
			 END
			 
	  END
	END
	IF (@rIsTeacherWorkLoad=0)
	  BEGIN
	  IF EXISTS(select EmployeeId from sTimetable.tTeacherWorkLoad where EmployeeId=@rEmployeeId AND DivisionId=@rDivisionId AND SubjectId=@rSubjectId AND TimeTableSchemaId=@rTimeTableSchemaId)
	BEGIN
		Delete from sTimetable.tTeacherWorkLoad where  EmployeeId=@rEmployeeId AND DivisionId=@rDivisionId AND SubjectId=@rSubjectId AND TimeTableSchemaId=@rTimeTableSchemaId
	RETURN
	 END
	 ELSE
	BEGIN
  
	select 
	 
	@lTWLNoOfLecture=SUM(TWL.NoOfLecture) 
	from
	sTimetable.tDivisionWorkLoad DWL
	INNER JOIN sTimetable.tTeacherWorkLoad TWL
	ON DWL.DivisionId=TWL.DivisionId AND DWL.SubjectId=TWL.SubjectId 
	WHERE TWL.DivisionId=@rDivisionId AND TWL.SubjectId=@rSubjectId 
	AND TWL.TimeTableSchemaId=@rTimeTableSchemaId
	AND DWL.TimeTableSchemaId=@rTimeTableSchemaId 
	 IF(@lDWLNoOfLecture<@lTWLNoOfLecture+@rNoOfLecture)
	BEGIN
	SELECT -102 AS RESULT
	RETURN
	  END
	  END
	  
	
	 
	 INSERT INTO sTimetable.tTeacherWorkLoad
		(
			EmployeeId,
			BatchId,
			DivisionId,
			SubjectId,
			NoOfLecture,
			CreatedUserId,
			CreatedDateTime,
			TimeTableSchemaId,
			LectureLength
			)
		Values
		(
			@rEmployeeId,
			@rBatchId,
			@rDivisionId,
			@rSubjectId,
			@rNoOfLecture,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rTimeTableSchemaId,
			@rLectureLength
		 )
        SELECT 1 AS Result
	   END 
END
	 
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sTool].[pDeleteStaticData]...';


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

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


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

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

DELETE FROM sAdmission.tInquiryModeMaster

DELETE FROM sFee.tFeeMainGroupMaster

DELETE FROM sPayroll.tPayElementDefault

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


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

DELETE FROM sCommon.tRangeGroupMaster

DELETE FROM sHostel.tLogStatusMaster

DELETE FROM sSetup.tStudentNameFormatMaster

DELETE FROM sCommon.tMainCastCategoryMaster

DELETE FROM sOp.tFunctionalityMaster
DELETE FROM sOp.tPaymentGatewayMaster

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

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

DELETE FROM sActivity.tEventMainTypeMaster
DELETE FROM sAlert.tOSType

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

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

END
GO
PRINT N'Creating [sClient].[pIshaGeneralStudentModelGet]...';


GO
CREATE  PROCEDURE [sClient].[pIshaGeneralStudentModelGet]
	 
 
	 @rClassId nvarchar(100),
	 @rDivisionId nvarchar(100),
	 
	 @rHostelId nvarchar(100),
	 @rStudentId nvarchar(100) 
	 
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 
	SELECT 
		Sm.Id AS StudentId,
		SM.FIrstName + ' ' + SM.LastName As FullName,
		ISNULL(RM.HostelId,0) AS HostelId,
		CM.title+ '/' +DM.Title AS ClassDivision,
		GM.Title AS Gender,
		A.BatchId,
		A.Divisionid 
	 
		
			 
  FROM 
      sStudent.tStudentMaster SM 	
	INNER JOIN sStudent.tStudentOther SO ON SO.studentid = SM.Id 
	INNER JOIN sCommon.tGenderMaster GM ON GM.ID = SO.GenderID 
	INNER JOIN sStudent.tAcademic A ON A.StudentId = Sm.Id
	INNER JOIN sSetup.tClassMaster CM
		ON CM.Id=A.ClassId
	INNER JOIN sSetup.tDivisionMaster DM
		ON DM.Id=A.DivisionId
	LEFT JOIN sHostel.tAssignRoom AR ON AR.SourceId = SM.Id AND AR.SourceTypeId =2003
	LEFT JOIN sHostel.tRoomMaster RM ON RM.Id = AR.RoomId
	 
	
					     
		    
  WHERE 
    (ISNULL(Cm.Id ,0) IN( SELECT cast(item as nvarchar(100)) FROM  sCommon.fnsplit(@rClassId,',')) OR @rClassId='') 
	 
	 AND  (ISNULL(DM.Id ,0) IN( SELECT cast(item as nvarchar(100)) FROM  sCommon.fnsplit(@rDivisionId,',')) OR @rDivisionId='') 
	  
     AND (ISNULL(RM.HostelId ,0) IN( SELECT cast(item as nvarchar(100)) FROM  sCommon.fnsplit(@rHostelId,',')) OR @rHostelId='') 
     
     ANd (ISNULL(SM.Id  ,0) IN( SELECT cast(item as nvarchar(100)) FROM  sCommon.fnsplit(@rStudentId,',')) OR @rStudentId='') 
     
	  
END
GO
PRINT N'Creating [sClient].[pIshaDetailStudentModelGet]...';


GO
CREATE PROCEDURE [sClient].[pIshaDetailStudentModelGet]
	  
	 @rClassId nvarchar(100)='',
	 @rDivisionId nvarchar(100)='',
	 @rHostelId nvarchar(100)='',  
	 @rStudentId nvarchar(100)=''
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 
	SELECT 
		Sm.Id AS StudentId,
		SM.FIrstName + ' ' + SM.LastName As FullName,
		HM.Title AS HostelName,
		CM.title+ '/' +DM.Title AS ClassDivision,
		 
		GM.Title AS Gender,
		SF. FatherName,
		SF.FatherMail,
		SF.FatherContactNo,
		SF.MotherName,
		SF.MotherMail,
		SF.MotherContactNo,
		SC.StudentEmail,
		SC.StudentContactNo,
		SC.ParentEmail AS ContactEmail 
		
			 
  FROM 
      sStudent.tStudentMaster SM 	
	INNER JOIN sStudent.tStudentOther SO ON SO.studentid = SM.Id 
	INNER JOIN sCommon.tGenderMaster GM ON GM.ID = SO.GenderID 
	INNER JOIN sStudent.tAcademic A ON A.StudentId = Sm.Id
	INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
	INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
	INNER JOIN sStudent.tStudentFamily SF ON Sf.StudentId = Sm.Id 
	INNER JOIN sHostel.tAssignRoom AR ON AR.SourceId = SM.Id AND AR.SourceTypeId =2003
	LEFT JOIN sHostel.tRoomMaster RM ON RM.Id = AR.RoomId
	LEFT JOIN sHostel.tHostelMaster HM ON HM.Id = RM.HostelId
	INNER JOIN sStudent.tStudentCommunication SC on SC.Studentid = Sm.Id 
					     
		    
  WHERE 
	    (ISNULL(Cm.Id ,0) IN( SELECT cast(item as nvarchar(100)) FROM  sCommon.fnsplit(@rClassId,',')) OR @rClassId='') 
	  AND   (ISNULL(DM.Id ,0) IN( SELECT cast(item as nvarchar(100)) FROM  sCommon.fnsplit(@rDivisionId,',')) OR @rDivisionId='') 
	 AND   (ISNULL(RM.hostelId,0) IN( SELECT cast(item as nvarchar(100)) FROM  sCommon.fnsplit(@rHostelId,',')) OR @rHostelId='') 
	 AND   (ISNULL(SM.Id ,0) IN( SELECT cast(item as nvarchar(100)) FROM  sCommon.fnsplit(@rStudentId,',')) OR @rStudentId='') 
END
GO
PRINT N'Creating [sClient].[pIshaHostelModelGet]...';


GO
CREATE  PROCEDURE [sClient].[pIshaHostelModelGet]
	  @rHostelId int=0
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 
	SELECT 
		 HM.Id As HostelId,
		 Hm.Title AS HostelName,
		 HM.Title  As HostelType 
  FROM 
		   sHostel.tHostelMaster HM
		   INNER JOIN  sHostel.tHostelTypeMaster HTM ON HTM.Id = HM.HostelTypeId
 Where 
	((Hm.Id =@rHostelId) OR (@rHostelId=0))
END
GO
PRINT N'Creating [sClient].[pIshaDivisionModelGet]...';


GO
CREATE PROCEDURE [sClient].[pIshaDivisionModelGet]
	 
	@rDivisionId int=0
	 
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 
	SELECT 
		Dm.Id As DivisionId,
		Dm.Title As DivisionName,
		CM.Id as ClassId,
		Cm.Title As ClassName,
		CGm.Title As Grade
  FROM 
		   sSetup.tDivisionMaster DM
		   INNER JOIn sSetup.tClassMaster Cm ON cm.Id = Dm.ClassId
		   INNER JOIN sSetup.tClassGroupMaster CGM ON CGm.Id =Cm.ClassGroupID
 Where ((Dm.Id =@rDivisionId) OR (@rDivisionId=0))
END
GO
PRINT N'Creating [sClient].[pIshaDetailEmployeeModelGet]...';


GO
CREATE PROCEDURE [sClient].[pIshaDetailEmployeeModelGet]
	 
  @rEmployeeId bigint =0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 
	SELECT 
		 Em.Id AS EmployeeID,
		 Em.FirstName + ' ' + EM.LastName AS FullName,
		 Gm.Title As Gender,
		 EC.CompanyEmail As Email, 
		 EC.MobileNumber ,
		 EPD.DateOfBirth
  FROM 
		  sHrm.tEmployeeMaster EM 
		  INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId = EM.Id
		  INNER JOIN sCommon.tGenderMaster Gm ON GM.Id = EPD.Genderid
		  INNER JOIn sHrm.tEmployeeCommunications Ec ON Ec.EmployeeID = EM.Id
	Where 
		((Em.id =@rEmployeeId) or (@rEmployeeId=0))
END
GO
PRINT N'Creating [sClient].[pIshaGeneralEmployeeModelGet]...';


GO
CREATE PROCEDURE [sClient].[pIshaGeneralEmployeeModelGet]
	  @rEmployeeId bigint=0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 
	SELECT 
		 Em.Id AS EmployeeId,
		 Em.FirstName + ' ' + EM.LastName AS FullName,
		 Gm.Title As Gender,
		 EC.CompanyEmail AS Email, 
		 EC.MobileNumber
  FROM 
		  sHrm.tEmployeeMaster EM 
		  INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId = EM.Id
		  INNER JOIN sCommon.tGenderMaster Gm ON GM.Id = EPD.Genderid
		  INNER JOIN sHrm.tEmployeeCommunications EC ON EC.EmployeeId= EM.Id
 Where 
		((Em.id =@rEmployeeId) or (@remployeeId=0))
END
GO
PRINT N'Creating [dbo].[fndt]...';


GO
-- exec fndt ''
-- drop proc fndt
CREATE proc [dbo].[fndt]
@text varchar(200)
as
BEGIN
declare @t varchar(5)=''
select @t = ''''
SELECT @t + s.name + '.' +   t.name + @t as tab,s.name + '.' +   t.name as name
FROM sys.tables t INNER JOIN sys.schemas s ON t.schema_id = s.schema_id 
WHERE t.name LIKE '%' + @text + '%' order by s.name,t.name
END
GO
PRINT N'Creating [sAcademic].[pClassv2Get]...';


GO
CREATE PROCEDURE [sAcademic].[pClassv2Get]

	 @rEmployeeId bigint,
	 @rOrgGroupId smallint,
	 @rClassworkDate Date	 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	
	SELECT 
			TSD.SubjectId ,
		    SM.Title AS SubjectName,
			ISNULL(AC.Id,0) AS ClassworkId,
			ISNULL(AC.Classwork,'') AS Classwork,
		    ISNULL(AC.Homework,'') AS Homework,
		    ISNULL(CONVERT(VARCHAR(10), AC.HomeWorkEndDate, 103),'') AS HomeWorkEndDate,
		    DM.Id AS DivisionId,
		    DM.ClassId,
		    CM.Title +'-'+DM.Title AS ClassDivisionName,
		    OM.Id As OrgId,
		    OM.DisplayTitle AS OrgTitle,
		    DM.OrderIndex
	FROM 
	
			sAcademic.tTeacherSubjectDivision TSD			
			INNER JOIN sSetup.tSubjectMaster SM ON TSD.SubjectId = SM.Id
			INNER JOIN sSetup.tDivisionMaster DM ON TSD.DivisionId = DM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=DM.OrgId
			INNER JOIN sSetup.tClassMaster CM On CM.Id = DM.ClassId
			LEFT JOIN sAcademic.tClasswork AC ON TSD.SubjectId = AC.SubjectId  
			AND  TSD.DivisionId = AC.DivisionId AND TSD.EmployeeId = AC.EmployeeId 
			AND AC.ClassWorkDate = @rClassworkDate
															
	WHERE 
		OM.OrgGroupId=@rOrgGroupId	
		AND TSD.EmployeeId= @rEmployeeId
		
		ORDER BY OM.Id,DM.OrderIndex
		
END
GO
PRINT N'Creating [sActivity].[pStudentListGet]...';


GO

CREATE PROCEDURE [sActivity].[pStudentListGet]
	 
	
	 @rOrgId smallint,
	 @rBatchId int,
	 @rStrCode nvarchar(max)='',
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rDepartmentId int=0,
	 @rHouseId int=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

	SELECT 
			
			SA.AcademicId As Id,					
			SA.RollNo AS RollNo,						
			SA.Name	AS Title,
			SA.Code AS IdNo,
			SO.HouseId,
			HM.Title As HouseName,
			SA.ClassName+'-'+SA.DivisionName AS DivDept
		
		
	FROM 
		 	sStudent.vStudentAcademic SA
		 	LEFT JOIN sStudent.vStudentOther SO ON SO.AcademicId=SA.AcademicId
		 	LEFT JOIN sActivity.tHouseMaster HM ON HM.Id = SO.HouseId
		
	WHERE 
			SA.OrgId=@rOrgId
		AND	SA.BatchId = @rBatchId
		AND (ISNULL(SA.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rStrCode,',')) OR @rStrCode='') 
		AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		AND (SO.HouseId=@rHouseId OR @rHouseId=0)
END
GO
PRINT N'Creating [sAlert].[pAppNonRegisteredUserGet]...';


GO
CREATE PROCEDURE [sAlert].[pAppNonRegisteredUserGet]
	@rOrgId int,
	@rOSTypeId tinyint=0,	
	
	@rDepartmentId int=0,
	@rClassId int=0,
	@rDivisionId int=0,
	@rCode nvarchar(20)='',
	@rUserSourceTypeId smallint	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
if(@rUserSourceTypeId=2003)
BEGIN
SELECT 
	OM.Title AS OrganizationName,
	--RU.UserSourceId AS UserSourceId,
	--RU.UserSourceTypeId AS UserSourceTypeId,
	'Student' AS UserTypeName,
	SA.Code AS Code,
	SA.ClassName + ' ' + SA.DivisionName AS Class,
	SA.Name AS Name,
    SA.DepartmentName AS Department	
	FROM		
		sStudent.vStudentLastAcademic SA 
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=SA.OrgId	
		LEFT JOIN 	sCommunication.tRegisteredUsers RU ON RU.UserSourceId = SA.StudentId And RU.UserSourceTypeId = 2003
	WHERE
	--SA.StudentId NOT IN(SELECT RU.UserSourceId FROM sCommunication.tRegisteredUsers RU)
	--AND 
	RU.UserSourceId IS NULL 
	AND((SA.OrgId = @rOrgId) OR (@rOrgId=0))
	AND ((SA.Code like @rCode) OR (ISNULL(@rCode,'') = ''))
	AND((SA.DepartmentId=@rDepartmentId) or (@rDepartmentId = 0))
		AND((SA.ClassId=@rClassId)OR(@rClassId=0))
		AND((SA.DivisionId=@rDivisionId)OR(@rDivisionId=0))
END
ELSE
BEGIN
SELECT 
	OM.Title AS OrganizationName,
	'Employee' AS UserTypeName,
	Emp.Code  AS Code,
	Emp.DepartmentName As Department,	
	Emp.FirstName +  ' ' + Emp.LastName AS Name
	
	FROM		
		 sHrm.vExtEmployeeMaster Emp  
		 INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=Emp.OrgId	 
		 LEFT JOIN 	sCommunication.tRegisteredUsers RU ON RU.UserSourceId = Emp.Id And RU.UserSourceTypeId = 95  												
	WHERE
	RU.UserSourceId IS NULL 
	--Emp.Id NOT IN(SELECT RU.UserSourceId FROM sCommunication.tRegisteredUsers RU)
	AND  ((Emp.OrgId = @rOrgId) OR (@rOrgId=0))
	  AND((Emp.DepartmentId=@rDepartmentId) or (@rDepartmentId = 0))
	  AND ((Emp.Code like @rCode) OR (ISNULL(@rCode,'') = ''))
END
END
GO
PRINT N'Creating [sAlert].[pAppNotificationGet]...';


GO
CREATE PROCEDURE [sAlert].[pAppNotificationGet]
	
	
	@rOSTypeId tinyint,
	@rEventId int,
	@rSourceTypeId smallint,
	@rFromDate date,
	@rToDate date

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	SELECT 
	NL.Id,
	NL.CreatedDateTime AS Date,
	OT.Title AS OSType,
	EM.Title AS EventName,
	ST.Title AS SourceType,
	NL.MessageTitle,
	NL.NotificationMessage AS Message
	
			
	FROM
		sAlert.tNotificationLog NL
		INNER JOIN sAlert.tOSType OT ON OT.ID =NL.OSTypeId
		INNER JOIN sAlert.tEventMaster EM ON EM.Id=NL.EventId
		INNER JOIN sCommon.tSourceTypeMaster ST ON ST.Id=NL.SourceTypeId
		
	WHERE
		((NL.OSTypeId=@rOSTypeId) OR (@rOSTypeId=0))
		AND ((NL.EventId=@rEventId) OR (@rEventId=0))
		AND ((NL.SourceTypeId=@rSourceTypeId) OR (@rSourceTypeId=0))		
		AND ((CONVERT(date,NL.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((CONVERT(date,NL.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		
		ORDER BY NL.Id DESC
END
GO
PRINT N'Creating [sAlert].[pAppRegisteredUserGet]...';


GO
CREATE PROCEDURE [sAlert].[pAppRegisteredUserGet]
	@rOrgId int,
	@rOSTypeId tinyint=0,	
	@rFromDate date,
	@rToDate date,
	@rDepartmentId int=0,
	@rClassId int=0,
	@rDivisionId int=0,
	@rCode nvarchar(20)='',
	@rUserSourceTypeId smallint	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
if(@rUserSourceTypeId=2003)
BEGIN
SELECT 
	OM.Title AS OrganizationName,
	--RU.UserSourceId AS UserSourceId,
	--RU.UserSourceTypeId AS UserSourceTypeId,
	'Student' AS UserTypeName,
	SA.Code AS Code,
	SA.ClassName + ' ' + SA.DivisionName AS Class,
	SA.Name AS Name,
	RU.CreatedDateTime AS Date,
	OT.Title AS OSType	,
SA.DepartmentName AS Department	
	FROM		
		sCommunication.tRegisteredUsers RU
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=RU.OrgId				
		INNER JOIN sAlert.tOSType OT ON OT.ID =RU.OSTypeId											
		INNER JOIN sStudent.vStudentLastAcademic SA ON SA.StudentId = RU.UserSourceId AND RU.UserSourceTypeId=2003	
	WHERE
	((RU.OrgId = @rOrgId) OR (@rOrgId=0))
		AND((RU.OSTypeId=@rOSTypeId) OR (@rOSTypeId=0))		
		AND((SA.DepartmentId=@rDepartmentId) or (@rDepartmentId = 0))
		AND((SA.ClassId=@rClassId)OR(@rClassId=0))
		AND((SA.DivisionId=@rDivisionId)OR(@rDivisionId=0))
	AND ((SA.Code like @rCode) OR (ISNULL(@rCode,'') = ''))
		AND ((CONVERT(date,RU.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((CONVERT(date,RU.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		AND((RU.UserSourceTypeId=@rUserSourceTypeId) OR (@rUserSourceTypeId=0))	
END
ELSE
BEGIN
SELECT 
	OM.Title AS OrganizationName,
	'Employee' AS UserTypeName,
	Emp.Code  AS Code,
	Emp.DepartmentName As Department,	
	Emp.FirstName +  ' ' + Emp.LastName AS Name,
	RU.CreatedDateTime AS Date,
	OT.Title AS OSType	,
	'' AS Class	
	FROM		
		sCommunication.tRegisteredUsers RU
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=RU.OrgId				
		INNER JOIN sAlert.tOSType OT ON OT.ID =RU.OSTypeId			
		
	    INNER JOIN sHrm.vExtEmployeeMaster Emp ON Emp.Id = RU.UserSourceId AND RU.UserSourceTypeId=95	    												
	WHERE
	((RU.OrgId = @rOrgId) OR (@rOrgId=0))
		AND((RU.OSTypeId=@rOSTypeId) OR (@rOSTypeId=0))	
	    AND((Emp.DepartmentId=@rDepartmentId) or (@rDepartmentId = 0))
		AND ((Emp.Code like @rCode) OR (ISNULL(@rCode,'') = ''))
		AND ((CONVERT(date,RU.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((CONVERT(date,RU.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		AND((RU.UserSourceTypeId=@rUserSourceTypeId) OR (@rUserSourceTypeId=0))	
END
END
GO
PRINT N'Creating [sAssessment].[pExamCombineSubjectAdd]...';


GO
CREATE  PROCEDURE [sAssessment].[pExamCombineSubjectAdd]
	 @rExamId int,
	 @rSubExamId int,
	 @rClassSubjectId int,
	 @rSubjectWeightage decimal(5,2)
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 		
	if exists(Select 1 from sAssessment.tExamCombineSubject where SubExamId =@rSubExamId AND ClassSubjectId =@rClassSubjectId)
	BEGIN
		Update sAssessment.tExamCombineSubject set SubjectWeightage = @rSubjectWeightage where SubExamId =@rSubExamId AND ClassSubjectId =@rClassSubjectId
	END
	ELSE
	BEGIN
	INSERT INTO sAssessment.tExamCombineSubject
	(
		ExamId,
		SubExamId,
		ClassSubjectId,
		SubjectWeightage
	)			
	Values
	(
		@rExamId,
		@rSubExamId,
		@rClassSubjectId,
		@rSubjectWeightage
	)
	Select 1 As Result
	END
	 
		
END
GO
PRINT N'Creating [sAssessment].[pExamCombineSubjectFullGet]...';


GO
 CREATE PROCEDURE [sAssessment].[pExamCombineSubjectFullGet]
@rClassId int,
@rExamId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	SELECT 
		 ES.SubjectWeightage  AS Weightage,
		EM.Id AS SubExamId,
		CS.Id AS ClassSubjectId,
		SM.Title AS SubjectName
	from
		[sAssessment].[tExamMaster] EM 
		INNER JOIN sSetup.tClassSubject CS ON EM.ClassId = CS.ClassId
		INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = CS.SubjectId
		LEFT JOIN sAssessment.tExamCombineSubject ES ON EM.Id=ES.SubExamId AND ES.ClassSubjectId = CS.Id
	WHERE CS.ClassId = @rClassId AND EM.Id = @rExamId
END
GO
PRINT N'Creating [sAssessment].[pRptSubjectRemarkGet]...';


GO
CREATE  PROCEDURE [sAssessment].[pRptSubjectRemarkGet]
 
	 @rExamId bigint,
	 
	 @rAcademicId bigint=0,
	 @rDivisionId  int=0,
	 @rClassId int=0 ,
	 @rBatchId int=0 ,
	 @rFromROllNO int=0,
	 @rToRollno int=0
	 
	 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 		


SELECT 
	convert(nvarchar(20),@rExamId) AS ExamIdText,
	Convert(nvarchar(20),@rAcademicId)As AcademicIdText,
	 EM.ClassId
	,DM.Id AS DivisionId
	,EM.Id AS ExamId
	,ED.ClassSubjectId AS ClassSubjectId
	,SA.AcademicId
	,SA.Name AS StudentName
	,SA.Code 
	,SA.RollNo
	,ISNULL(RD.Remark,'') AS SubjectRemark,
	V.SubjectName
	,ED.Id AS ExamDetailId,
	 [sAttendance].[fSubjectTeacherGet](SA.DivisionId,V.SubjectID)AS EmployeeName
from sStudent.vStudentAcademic SA 
	INNER JOIN sSetup.tClassMaster CM ON SA.ClassId=CM.Id 
	INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId=CM.Id AND SA.DivisionId=DM.Id
 
	INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id  
	
	INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id
	LEFT JOIN sAssessment.tResultDetailOther RD ON  RD.AcademiciD=SA.AcademicId  AND EM.ID=RD.ExamId   AND RD.ClassSubjectID = Ed.ClassSubjectId 
	 LEFT JOIN sSetup.vClassSubject V ON V.ClassSubjectId = Ed.ClassSubjectId  
	Where  
		(DM.Id=@rDivisionId OR @rDivisionId = 0)
	    AND (EM.ClassId = @rClassId OR @rClassId = 0)  
	   AND  (EM.Id=@rExamId OR @rExamId = 0)
	   AND ((SA.AcademicId=@rAcademicId) OR (@rAcademicId=0))
	   AND ((SA.ROllNo >=@rFromROllNO) OR(@rFromROllNo=0)) 
	   AND ((SA.RollNo<=@rToRollno) OR (@rToRollno=0))
	  AND SA.StatusId=1 AND SA.BatchId=@rBatchId
	Order By SA.RollNo
END
GO
PRINT N'Creating [sAssessment].[pSubjectRemarkAdd]...';


GO

CREATE PROCEDURE [sAssessment].[pSubjectRemarkAdd]
	 
	       
		    @rSubjectRemark nvarchar(1000)
		   ,@rExamId int
		   ,@rAcademicId bigint,
		    @rClassSubjectId int
		   
		  	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	if exists (select 1 from sAssessment.tResultDetailOther where ExamId = @rExamid and AcademicId = @racademicid and classsubjectid= @rclasssubjectid)
	begin
		update sAssessment.tResultDetailOther
		Set 
			Remark =@rSubjectRemark
		Where  ExamId = @rExamid and AcademicId = @racademicid and classsubjectid= @rclasssubjectid
		Select 11 As Result
	end
	 
ELSE
	 BEGIN
	     
	INSERT INTO sAssessment.tResultDetailOther
			   (
			    ExamId
			   ,AcademicId 
			   ,ClassSubjectId
			   ,Remark
			   )
		 VALUES
			   (
				@rExamId
			   ,@rAcademicId
			   ,@rClassSubjectId
			   ,@rSubjectRemark
			   )
		    SELECT 1 AS Result
	 END  
		 
 
		
END
GO
PRINT N'Creating [sAssessment].[pSubjectRemarkGet]...';


GO
CREATE PROCEDURE [sAssessment].[pSubjectRemarkGet]
	 @rClassId int,
	 @rDivisionId int,
	 @rExamId int,
	  
	 @rClassSubjectId int,
	 @rBatchId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 		


SELECT 
	 EM.ClassId
	,DM.Id AS DivisionId
	,EM.Id AS ExamId
	,ED.ClassSubjectId AS ClassSubjectId
	,SA.AcademicId
	,SA.Name AS StudentName
	,SA.Code 
	,SA.RollNo
	,ISNULL(RD.Remark,'') AS SubjectRemark
	 
from 
	sStudent.vStudentAcademic SA 
	INNER JOIN sSetup.tClassMaster CM ON SA.ClassId=CM.Id 
	INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId=CM.Id AND SA.DivisionId=DM.Id
	INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id  
	INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id 
 
	 LEFT JOIN sAssessment.tResultDetailOther RD ON  RD.ExamId = Em.Id AND SA.Academicid =RD.AcademicId AND ED.ClassSubjectId = RD.ClassSubjectId
Where  
		(DM.Id=@rDivisionId OR @rDivisionId = 0)
	   AND (EM.ClassId = @rClassId OR @rClassId = 0)  
	   AND (EM.Id=@rExamId OR @rExamId = 0)
	   AND ED.ClassSubjectId = @rClassSubjectId
	   AND SA.StatusId=1 AND SA.BatchId=@rBatchId
	  
Order By SA.RollNo


END
GO
PRINT N'Creating [sAttendance].[pAttenanceRegisterGetNew1]...';


GO
 -- exec [sAttendance].[pAttenanceRegisterGetNew] '','',1,1001,7,2016,100100001,100100001,100100114,0,0,1
CREATE PROCEDURE [sAttendance].[pAttenanceRegisterGetNew1]
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rAttendanceTypeId smallint,
	 @rOrgId int,
	 @rForMonth smallint,
	 @rForYear smallint,
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rBatchId int = 0,
	 @rStudentCode nvarchar(20)='',
	 @rDepartmentId int = 0,
	 @rAcademicId bigint = 0,
	 @PageIndex int=0
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	DECLARE @lFirstDate Date
	DECLARE @lResult nvarchar(max)
	DECLARE @li int 
	SET @li=1
	SET @lFirstDate = CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'/'+CONVERT(NVARCHAR(2),@rForMonth)+'/01'))	
BEGIN 
CREATE Table #AttendanceRegistertempTable
(
	 
	ClassDivisionTitle Nvarchar(50),
	Code nvarchar(50),
	RollNo int,
	AcademicId bigint,
	Name nvarchar(50),
	AttendanceTypeId int,
	ForYear int,
	ForMonth int,
	ForMonthInWord nvarchar(100),
	ClassId int,
	DivisionId int,
	ClassName nvarchar(50),
	DivisionName nvarchar(50),
	IsPresent bit,
	DayPart int,
	LeftDate date,
	ClassOrderIndex int,
	DivisionOrderIndex int,
	FooterSignature nvarchar(500),
	StatusId int,
	AttendanceDate date,
	AttendanceTagId int 
 
)
Insert INTO #AttendanceRegistertempTable
(	
	ClassDivisionTitle,
	Code ,
	RollNo,
	AcademicId,
	Name,
	AttendanceTypeId,
	ForYear,
	ForMonth,
	ForMonthInWord,
	ClassId,
	DivisionId,
	ClassName,
	DivisionName,
	IsPresent,
	DayPart,
	LeftDate,
	ClassOrderIndex,
	DivisionOrderIndex,
	FooterSignature,
	StatusId,
	AttendanceDate,
	AttendanceTagId 
  
)
Select	    
	ISNULL(SA.ClassName + '-' + SA.DivisionName,'') AS ClassDivisionTitle,
	SA.Code,
	SA.RollNo,
	SA.AcademicId,
	SA.Name,
	SR.AttendanceTypeId ,
	YEAR(SR.AttendanceDate) AS ForYear,
	MONTH(SR.AttendanceDate) AS ForMonth,
	DATENAME(month, SR.AttendanceDate) AS ForMonthInWord,
	SA.ClassId,
	SA.DivisionId,
	SA.ClassName,Sa.DivisionName,
  
	--(CASE SR.IsPresent WHEN 1 THEN 'P' 
	--	WHEN 0 THEN 'A'
	--ELSE  ' ' END )AS  IsPresent,		
	SR.IsPresent,
	 day(SR.AttendanceDate) AS DayPart,
	 
	 A.LeftDate,
	 CM.OrderIndex AS ClassOrderIndex,
	 DM.OrderIndex As DivisionOrderIndex,
	 OM.FooterSignature AS FooterSignature,
	 SA.StatusId,
	 SR.AttendanceDate As AttendanceDate,
	 NULL AS AttendanceTagId
	 
	 --,
	 --SR.IsPresent
	 
	 
    from
            sStudent.vStudentAcademic SA 
            INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.AcademicId 
            INNER JOIN sStudent.tStudentAdmission A ON SA.StudentId = A.StudentId
            INNER JOIN sSetup.tClassMaster CM ON CM.Id = SA.ClassId
            INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = CM.OrgId
            INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=SA.DivisionId
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId
            
			
            
             WHERE  
	        ((SR.AttendanceTypeId=@rAttendanceTypeId) OR (@rAttendanceTypeId= 0))
	         AND ((SA.OrgId=@rOrgId) OR (@rOrgId= 0))
	          AND ((SA.BatchId=@rBatchId) OR (@rBatchId= 0))
	          AND ((YEAR(SR.AttendanceDate)=@rForYear) OR (@rForYear= 0))
	          AND ((MONTH(SR.AttendanceDate)=@rForMonth) OR (@rForMonth= 0))
	           AND ((SA.ClassId=@rClassId) OR (@rClassId= 0))
	           AND ((SA.Code=@rStudentCode) OR (@rStudentCode=''))
	           AND ((SA.AcademicId=@rAcademicId) OR (@rAcademicId=0))	           
				AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
	           AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId= 0))

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

SELECT 
@li AS DayPart,
 [sAttendance].[fWeekHOffHolidayGet](@rForYear,@rForMonth,@li,@rBatchId,@rDivisionId,'',@rOrgId) 
SET @li = @li + 1
END

--DECLARE @TotalRecords int,@lpaging varchar(max)='',@PageSize int =100
--SELECT @TotalRecords = count(*)	 from #AttendanceRegistertempTable
--SELECT @lpaging = @lpaging + dbo.fnc_SearchPagingFormat(@PageIndex,@TotalRecords,@PageSize)

SELECT  
			@lFirstDate AS LastDate,
			LeftDate,
            @rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			PivotTable.AcademicId,
			ClassDivisionTitle,isnull(Code,'') as Code,isnull(RollNo,0) as RollNo,
			isnull(Name,'') as Name,isnull(AttendanceTypeId,0) as AttendanceTypeId,ForYear,
			ForMonth,ClassId,ClassName,DivisionId,
			DivisionName,
			 
			ForMonthInWord,
			(ISNULL(TC.TCount,0) - ISNULL(AC.ACount,0)) AS PresentCount,
			 ISNULL(TC.TCount,0) AS AttendanceCount,
				
		      ISNULL(AC.ACount,0) As  AbsentCount,
		       ISNULL(PC.PCount,0) As  PresentUpto,
		       ClassOrderIndex,
		       DivisionOrderIndex,
		       FooterSignature,				 
			0 AS TotalPresent ,
	 		isnull([1],'') AS P1,
			isnull([2],'') AS P2,
			isnull([3],'') AS P3,
			isnull([4],'') AS P4,
			isnull([5],'') AS P5,
			isnull([6],'') AS P6,
			isnull([7],'') AS P7,
			isnull([8],'') AS P8,
			isnull([9],'') AS P9,
			isnull([10],'') AS P10,
			isnull([11],'') AS P11,
			isnull([12],'') AS P12,
			isnull([13],'') AS P13,
			isnull([14],'') AS P14,
			isnull([15],'') AS P15,
			isnull([16],'') AS P16,
			isnull([17],'') AS P17,
			isnull([18],'') AS P18,
			isnull([19],'') AS P19,
			isnull([20],'') AS P20,
			isnull([21],'') AS P21,
			isnull([22],'') AS P22,
			isnull([23],'') AS P23,
			isnull([24],'') AS P24,
			isnull([25],'') AS P25,
			isnull([26],'') AS P26,
			isnull([27],'') AS P27,
			isnull([28],'') AS P28,
			isnull([29],'') AS P29,
			isnull([30],'') AS P30,
			isnull([31],'') AS P31, 
 
sCommon.fGetDaysInMonth ( @rForMonth,@rForYear) AS DaysInMonth,Ispresent,
ISNULl(AttendanceTagId,0) AS AttendanceTagId
  
--,AttendanceTagId

 
FROM
(
	Select --TID, 
		ISNULL(ClassName + '-' + DivisionName,'') AS ClassDivisionTitle,
		Code,
		RollNo,
		AcademicId,
		Name,
		AttendanceTypeId ,
		YEAR(ST.AttendanceDate) AS ForYear,
		MONTH(ST.AttendanceDate) AS ForMonth,
		DATENAME(month, ST.AttendanceDate) AS ForMonthInWord,
		ClassId,
		DivisionId,
		ClassName,
		DivisionName,
		(
			CASE 
			 WHEN IsPresent = 1 AND ST.AttendanceTagId = 1 THEN 'LA' 
				  WHEN IsPresent = 1 AND ST.AttendanceTagId = 2 THEN 'ED' 
			      WHEN IsPresent = 1  THEN 'P' 
				  WHEN IsPresent = 0 THEN 'A'
				  ELSE  DT.Value END 
		)AS  IsPresent,		
		day(ST.AttendanceDate) AS DayPart,
		LeftDate,
		ClassOrderIndex,
		DivisionOrderIndex,
		FooterSignature 
		 -- DO NOT ADD ANY FIELD HERE WITHOUT PERMISSION OF RAJENDRA
		
	 FROM 
		#AttendanceRegistertempTable ST 
		INNER JOIN #TempDaysTempTable DT ON DT.DayPart = ST.DayPart
	 WHERE
		((LeftDate >= @lFirstDate) OR ISNULL(LeftDate,'') = '')
) AS SourceTable 
	           
	        
PIVOT
(	
MIN(IsPresent)
FOR DayPart IN ([0], [1], [2], [3], [4],[5],[6],[7],[8],[9],[10],[11],[12],[13],[14],[15],[16],[17],[18],[19],[20],[21],[22],[23],[24],[25],[26],[27],[28],[29],[30],[31])
) AS PivotTable
	LEFT JOIN
	(
		Select  AcademicId AS AcademicId, COUNT(1) AS TCount,IsPresent,AttendanceTagId 
		   FROM  
				#AttendanceRegistertempTable
		    
			GROUP BY  AcademicId,IsPresent,AttendanceTagId
    ) TC ON TC.AcademicId = PivotTable.AcademicId
    
	LEFT JOIN
	(
		Select AcademicId AS AcademicId, COUNT(1) AS ACount 
		   FROM  #AttendanceRegistertempTable
		    WHERE   IsPresent = 0	 		
             --AND ( StatusId = 1)
			GROUP BY  AcademicId
    ) AC ON AC.AcademicId = PivotTable.AcademicId
	LEFT JOIN
	(
		SELECT A.Id AS AcademicId, COUNT(1) AS PCount  FROM sAttendance.tStudentRegister SR 
			INNER JOIN sStudent.tAcademic A ON SR.AcademicId = A.Id 
		   INNER JOIN sStudent.tStudentMaster SA ON A.StudentId = SA.Id
		   INNER JOIN sSetup.tClassMaster CM ON A.ClassId = CM.Id
			WHERE  
			 SR.AttendanceDate < (convert(date,CONVERT(nvarchar(10), @rForYear)+ '/' +  CONVERT(nvarchar(10), @rForMonth) + '/' + '01' ))
			AND SR.IsPresent = 1	    		
            --AND (SA.StatusId = 1)
	        AND ((SR.AttendanceTypeId=@rAttendanceTypeId) OR (@rAttendanceTypeId= 0))
	        AND ((SA.OrgId=@rOrgId) OR (@rOrgId= 0))
	        AND ((A.BatchId=@rBatchId) OR (@rBatchId= 0))	          
	        AND ((A.ClassId=@rClassId) OR (@rClassId= 0))
	        AND ((SA.Code=@rStudentCode) OR (@rStudentCode=''))
	        AND ((A.Id=@rAcademicId) OR (@rAcademicId=0))	           
			AND ((CM.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))				
	        AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId= 0))
			GROUP BY A.Id
    ) PC ON PC.AcademicId = PivotTable.AcademicId
    ORDER BY RollNo;
    
select * from #TempDaysTempTable
--select '' as paging

drop table #AttendanceRegistertempTable	  
drop table #TempDaysTempTable
END
GO
PRINT N'Creating [sAttendance].[pStudetntAttendancev2Get]...';


GO

CREATE PROCEDURE [sAttendance].[pStudetntAttendancev2Get]
	 	 
	 	  @rForMonth smallint,
	      @rForYear smallint,
	      @rAcademicId bigint,
	      @rAttendanceTypeId smallint,
	      @rBatchId int = 0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	Select 
			DAY(SR.AttendanceDate) AS DayNo,
			
			CASE  WHEN SR.IsPresent = 1 AND SR.AttendanceTagId = 1 THEN 'LA' 
				  WHEN SR.IsPresent = 1 AND SR.AttendanceTagId = 2 THEN 'ED' 
			      WHEN SR.IsPresent = 1  THEN 'P' 
				  WHEN SR.IsPresent = 0 THEN 'A'
				  ELSE  '' END AS  Presence,
			--(CASE SR.IsPresent WHEN 1 THEN 'P' 
			--	WHEN 0 THEN 'A'
			--	END )AS  Presence,
			OM.WeekOffs,
			'5,12,15,20,21,29' Holidays
			
		
	From  
			sStudent.vStudentAcademic SA
            INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.AcademicId
            INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
	
	WHERE
			SR.AttendanceTypeId=@rAttendanceTypeId
		AND SR.AcademicId=@rAcademicId
		AND YEAR(SR.AttendanceDate)=@rForYear
		AND MONTH(SR.AttendanceDate)=@rForMonth
		AND SA.BatchId=@rBatchId
		
		ORDER BY DayNo ASC
	
END
GO
PRINT N'Creating [sCommon].[pReportRemarkGroupMasterGet]...';


GO
CREATE PROCEDURE [sCommon].[pReportRemarkGroupMasterGet]
	 
	 @rOrgGroupId smallint,
	 @rReportRemarkGroupId smallint
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
		
BEGIN 
	SELECT 
			DISTINCT(OM.Id) AS OrgId,
			OM.DisplayTitle AS Organization,
			ISNULL(RGO.SchoolRemark1,'') AS SchoolRemark1,
			ISNULL(RGO.SchoolRemark2,'') AS SchoolRemark2,
			ISNULL(RGO.SchoolRemark3,'') AS SchoolRemark3,
		    ISNULL(RGO.SchoolRequiredSignature,'') AS SchoolRequiredSignature,
			CASE WHEN RGO.OrgId IS NULL OR RGO.ReportRemarkGroupId!=@rReportRemarkGroupId THEN 'False' ELSE 'True' END AS IsObsolete
			--CASE WHEN RGO.OrgId IS NULL OR RGO.ReportRemarkGroupId!=@rReportRemarkGroupId THEN 0 ELSE RGO.ReportId END AS ReportId
  FROM 
            sSetup.tOrganizationMaster OM
       LEFT JOIN sCommon.tReportRemarkGroupOrg RGO ON RGO.OrgId=OM.Id AND (RGO.ReportRemarkGroupId=@rReportRemarkGroupId)
       
  WHERE 
			(OM.OrgGroupId=@rOrgGroupId)
		ORDER BY OM.DisplayTitle
END
GO
PRINT N'Creating [sCommon].[pReportRemarkGroupOrgAdd]...';


GO
CREATE PROCEDURE [sCommon].[pReportRemarkGroupOrgAdd]
    
    @rReportRemarkGroupId smallint,
	@rXmldoc [nvarchar](max)

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
BEGIN TRY

DECLARE @lCount INT
DECLARE @lInterrorCode INT,
		@intDoc INT,
		@lOrgId smallint,
		@lReportId int,
		@lSchoolRemark1 nvarchar(500),
		@lSchoolRemark2 nvarchar(500),
		@lSchoolRemark3 nvarchar(500),
		@lSchoolRequiredSignature nvarchar(500)
		
BEGIN TRANSACTION
			
	DELETE FROM sCommon.tReportRemarkGroupOrg WHERE ReportRemarkGroupId=@rReportRemarkGroupId	
			
	EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc
		
	CREATE TABLE #tTable  
	(
		Id bigint identity,	 
		OrgId smallint,
		ReportId int,
		SchoolRemark1 nvarchar(500),
		SchoolRemark2 nvarchar(500),
		SchoolRemark3 nvarchar(500),
		SchoolRequiredSignature nvarchar(500)
	)
		
	INSERT INTO #tTable
	(
		OrgId,
		ReportId,
		SchoolRemark1,
		SchoolRemark2,
		SchoolRemark3,
		SchoolRequiredSignature
	)
	SELECT
		OrgId,
		ReportId,
		SchoolRemark1,
		SchoolRemark2,
		SchoolRemark3,
		SchoolRequiredSignature
	FROM OPENXML (@intDoc, '/Table/ReportRemarkGroup', 1)
	WITH
	( 
		OrgId smallint '@OrgId',			
		ReportId int '@ReportId',
		SchoolRemark1 nvarchar(500) '@SchoolRemark1',
		SchoolRemark2 nvarchar(500) '@SchoolRemark2',
		SchoolRemark3 nvarchar(500) '@SchoolRemark3',
		SchoolRequiredSignature nvarchar(500) '@SchoolRequiredSignature'
	)
		
	EXEC sp_xml_removedocument @intDoc
				
	SELECT @lCount =  COUNT(Id) FROM #tTable

	WHILE @lCount > 0 
	BEGIN
		SELECT		
				@lOrgId=OrgId,
				@lReportId=ReportId,
				@lSchoolRemark1=SchoolRemark1,
			    @lSchoolRemark2=SchoolRemark2,
			    @lSchoolRemark3=SchoolRemark3,
			    @lSchoolRequiredSignature=SchoolRequiredSignature
													 	 
		FROM #tTable WHERE Id = @lCount  

		INSERT INTO sCommon.tReportRemarkGroupOrg
		(
			OrgId,
			ReportId,
			ReportRemarkGroupId,
			SchoolRemark1,
			SchoolRemark2,
			SchoolRemark3,
			SchoolRequiredSignature
			
		)
		VALUES
		(
			@lOrgId,
			@lReportId,
			@rReportRemarkGroupId,
			@lSchoolRemark1,
			@lSchoolRemark2,
			@lSchoolRemark3,
			@lSchoolRequiredSignature
		)
		SET @lCount = @lCount - 1
	END			
COMMIT TRANSACTION			
	
SELECT 1
END TRY
BEGIN CATCH
ROLLBACK TRANSACTION
SELECT -1 
END CATCH
	
END
GO
PRINT N'Creating [sCommunication].[pAssignedQueryCategoryListGet]...';


GO

CREATE PROCEDURE [sCommunication].[pAssignedQueryCategoryListGet]
	 
	 @rSourceId bigint,
	 @rSourceTypeId smallint,
	 @rOrgGroupId smallint
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
		
BEGIN 
	SELECT 
			QCA.QueryCategoryId,
			QCM.Title AS QueryCategoryTitle
	FROM 
			sCommunication.tQueryCategoryAssignedTo QCA
			INNER JOIN sCommunication.tQueryCategoryMaster QCM 
				ON QCM.Id=QCA.QueryCategoryId AND (QCM.OrgGroupId = @rOrgGroupId)	
	WHERE 
			(QCA.SourceTypeId = @rSourceTypeId) 
			AND (QCA.SourceId = @rSourceId) 
END
GO
PRINT N'Creating [sCommunication].[pAssignedQueryListGet]...';


GO

CREATE PROCEDURE [sCommunication].[pAssignedQueryListGet]
	 
	 @rOrgGroupId smallint,
	 @rOrgGroupBatchId int,
	 @rSourceId bigint,
	 @rSourceTypeId smallint,
	 @rIsOpen bit
	
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
		
BEGIN 
		DECLARE @lStatusId tinyint
		
		IF @rIsOpen=1
		BEGIN
			SET @lStatusId=209
		END
		ELSE 
		BEGIN
			SET @lStatusId=210
		END
			
	SELECT 
			 Q.Id AS QueryId,
			 Q.Title AS QueryTitle,
			 Q.Remark AS QueryRemark,
			 SM.Title AS QueryStatus,
			 QCM.Title AS QueryCategoryTitle,
			 QCA.QueryCategoryId,
			 (CONVERT(VARCHAR(25),Q.CreatedDateTime, 100)) AS QueryCreatedDateTime,
		     'Student' AS SourceType,
		     vSA.Name AS SourceName,
		     vSA.ClassName +' - ' + vSA.DivisionName AS ClasDivOrDept,
		     vSA.OrganizationName AS OrgTitle
	FROM 
			sCommunication.tQueryCategoryAssignedTo QCA
			INNER JOIN sCommunication.tQuery Q 
				ON Q.QueryCategoryId = QCA.QueryCategoryId AND (Q.StatusId=@lStatusId)
			INNER JOIN sCommunication.tQueryCategoryMaster QCM 
				ON QCM.Id=QCA.QueryCategoryId AND (QCM.OrgGroupId = @rOrgGroupId)	
			INNER JOIN sCommon.tStatusMaster SM 
				ON SM.Id = Q.StatusId
			INNER JOIN sStudent.vStudentAcademic vSA ON vSA.StudentId = QCA.SourceId
			AND vSA.OrgGroupBatchId = @rOrgGroupBatchId
	WHERE 
			(QCA.SourceTypeId = @rSourceTypeId) 
			AND (QCA.SourceId = @rSourceId) 
			
	UNION ALL
	
	SELECT 
			 Q.Id AS QueryId,
			 Q.Title AS QueryTitle,
			 Q.Remark AS QueryRemark,
			 SM.Title AS QueryStatus,
			 QCM.Title AS QueryCategoryTitle,
			 QCA.QueryCategoryId,
			 (CONVERT(VARCHAR(25),Q.CreatedDateTime, 100)) AS QueryCreatedDateTime,
		     'Employee' AS SourceType,
		     vECD.EmployeeName AS SourceName,
		     vECD.DepartmentName AS ClasDivOrDept,
		     OM.Title AS OrgTitle
	FROM 
			sCommunication.tQueryCategoryAssignedTo QCA
			INNER JOIN sCommunication.tQuery Q 
				ON Q.QueryCategoryId = QCA.QueryCategoryId AND (Q.StatusId=@lStatusId)
			INNER JOIN sCommunication.tQueryCategoryMaster QCM 
				ON QCM.Id=QCA.QueryCategoryId AND (QCM.OrgGroupId = @rOrgGroupId)	
			INNER JOIN sCommon.tStatusMaster SM 
				ON SM.Id = Q.StatusId
			INNER JOIN sHrm.vEmployeeCommonDetail vECD ON vECD.EmployeeId = QCA.SourceId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = vECD.OrgID
	WHERE
			(QCA.SourceTypeId = @rSourceTypeId) 
			AND (QCA.SourceId = @rSourceId) 
END
GO
PRINT N'Creating [sCommunication].[pQueryCloseUpdate]...';


GO

CREATE PROCEDURE [sCommunication].[pQueryCloseUpdate]
	 
	@rQueryId bigint
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
		
BEGIN 
	UPDATE sCommunication.tQuery SET StatusId=210 WHERE Id=@rQueryId
	
	SELECT 1 Result
END
GO
PRINT N'Creating [sCommunication].[pQueryListv2Get]...';


GO


CREATE PROCEDURE [sCommunication].[pQueryListv2Get]
	 
	 
	 @rOrgGroupBatchId int,
	 @rCreatedUserId bigint	
	  	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			
BEGIN 
	 
	  
	SELECT 
			QM.Id AS QueryId,
			QCM.Id AS QueryCategoryId,
			ISNULL(QCM.Title,'') AS QueryCategoryMaster,
			QM.Title,
			QM.Remark,
			CONVERT(VARCHAR(25), QM.CreatedDateTime, 100) AS CreatedDateTime,
			QM.StatusId,
			ISNULL(sm.Title,'') AS StatusMaster,
			QM.IsAssigneeView,
			QM.IsUserView,
			QM.CreatedUserId AS QueryCreatedUserId
  FROM 
			sCommunication.tQuery QM
		INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QM.QueryCategoryId=QCM.Id AND QCM.IsObsolete=0
        INNER JOIN sCommon.tStatusMaster SM ON SM.Id=QM.StatusId
        INNER JOIN sSecurity.tUser U ON QM.CreatedUserId = U.Id
  WHERE 
			QM.OrgGroupBatchId=@rOrgGroupBatchId
		AND QM.CreatedUserId=@rCreatedUserId
		
		order by QM.Id desc
        
END
GO
PRINT N'Creating [sCommunication].[pViewQueryRemarkv2Get]...';


GO

CREATE PROCEDURE [sCommunication].[pViewQueryRemarkv2Get]
	 
	 @rQueryId bigint,
	 @rUserId bigint
		 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 
	
	DECLARE	@lUserSourceTypeId smallint

	SELECT  @lUserSourceTypeId = SourceTypeId FROM sSecurity.tUser WHERE Id = @rUserId

		
	IF @lUserSourceTypeId = 2003
	 BEGIN
	  UPDATE sCommunication.tQuery SET IsUserView = 1	WHERE Id = @rQueryId
	 END
	ELSE IF @lUserSourceTypeId = 95
	 BEGIN
	  UPDATE sCommunication.tQuery SET IsAssigneeView = 1	WHERE Id = @rQueryId
	 END
	 
	SELECT 
			QC.Id,
			QC.QueryId,
			QC.Remark,
			U.DisplayTitle AS UserName,
			CONVERT(VARCHAR(25), QC.CreatedDateTime, 100) AS CreatedDateTime,
			QC.CreatedUserId AS CommentCreatedUserId,
			Q.CreatedUserId AS QueryCreatedUserId
	FROM 
			sCommunication.tQueryComment QC
		INNER JOIN sCommunication.tQuery Q ON Q.Id=QC.QueryId
		INNER JOIN sCommunication.tQueryCategoryMaster QCM ON Q.QueryCategoryId=QCM.Id AND QCM.IsObsolete=0
		INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId
		
	WHERE 
			QC.QueryId = @rQueryId
			--AND Q.CreatedUserId = @rUserId 
			order by QC.Id desc
END
GO
PRINT N'Creating [sFee].[pRptDepositMinusGet]...';


GO

CREATE PROCEDURE [sFee].[pRptDepositMinusGet]
          
           @rOrgId int,
           @rBatchId int,
           @rCode nvarchar(20)
           
AS
SET NOCOUNT ON

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


GO

CREATE PROCEDURE [sFee].[pRptFeeInvoiceRegisterGet]
		
		@rOrgGroupBatchId int,
		@rOrgId int=0,
		@rBatchId int=0,
		@rAdmissionCategoryId int=0,
		@rClassId int=0,
		@rDivisionId int=0,
		@rIdNo nvarchar(20)='',
		@rFirstName nvarchar(100)='',
		@rReceiptBookId int=0,
		@rFromInvoiceNumber int=0,
		@rToInvoiceNumber int=0,
		@rFromDate date='',
		@rToDate date='',
		@rOrgGroupId int,
		@rCollectionGroupId int = 0,
		@rDepartmentId int=0
	    
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
		BEGIN
			SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
		END			 
			 
BEGIN
		CREATE Table #InvoiceDetail
		(
		FeeInvoiceId bigint,
		FeeCode nvarchar(100),
		FeeAmount decimal(12,2),
		FeeOrder int,
		OrganizationName nvarchar(200),
		SUId nvarchar(20),
		Code nvarchar(20),
		ClassDiv nvarchar(200),
		RollNo int,
		Name nvarchar(300),
		InvoiceNumber int,
		InvoiceDate Date,
		InvoiceAmount decimal(12,2),
		ReceiptBookName nvarchar(100),
		CollectionGroupName nvarchar(100),
		VariableAmount decimal(12,2),
		DiscountAmount decimal(12,2),
		AdditionalAmount decimal(12,2),
		NotApplicableAmount decimal(12,2)
		)
		
		INSERT INTO #InvoiceDetail
		SELECT
			FeeInvoiceId,
			FM.Code,
			ID.Amount,
			FM.OrderIndex,
			SA.OrganizationName,
			SA.SUId,
			SA.Code,
			SA.ClassName+' - '+ SA.DivisionName AS Class,
			RollNo,
			Name,
			FI.InvoiceNumber,
			FI.InvoiceDate,
			FI.InvoiceAmount,
			RBM.Title,
			CGM.Title,
			FA.VariableAmount,
			FA.DiscountAmount,
			FA.AdditionalAmount,
			FA.NotApplicableAmount
		FROM
		sFee.tFeeInvoiceDetail ID 
		INNER JOIN sFee.tFeeSetup FS ON ID.FeeSetupId = FS.Id  
		INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
		INNER JOIN sFee.tFeeInvoice FI ON FI.Id = ID.FeeInvoiceId AND FI.OrgGroupBatchId = @rOrgGroupBatchId
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=FI.SourceId	
			AND (SA.ClassId=@rClassId OR @rClassId=0) 
			AND (SA.DivisionId=@rDivisionId OR @rDivisionId=0)
			AND (SA.AdmissionCategoryId=@rAdmissionCategoryId OR @rAdmissionCategoryId=0)
		INNER JOIN sSetup.tClassMaster CM ON Cm.Id = SA.ClassId
		INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=FI.ReceiptBookId
		INNER JOIN sFee.tCollectionGroupMaster CGM ON CGM.Id = FI.CollectionGroupId
		LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FI.SourceTypeId= FA.SourceTypeId AND FI.SourceId= FA.SourceId
		WHERE 
		((SA.Code like @rIdNo) OR (ISNULL(@rIdNo,'')=''))	
		AND (FI.SourceTypeId=2001)
		AND ((SA.FirstName like @rFirstName) OR(ISNULL(@rFirstName,'')=''))
		AND ((FI.InvoiceNumber>=@rFromInvoiceNumber)OR(@rFromInvoiceNumber=0))
		AND ((FI.InvoiceNumber<=@rToInvoiceNumber)OR(@rToInvoiceNumber=0))
		AND ((FI.ReceiptBookId=@rReceiptBookId)OR(@rReceiptBookId=0))
		AND ((FI.CollectionGroupId=@rCollectionGroupId)OR(@rCollectionGroupId=0))
		AND ((FI.InvoiceDate>=@rFromDate)OR(ISNULL(@rFromDate,'')=''))
		AND ((FI.InvoiceDate<=@rToDate)OR(ISNULL(@rToDate,'')=''))
		AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((FI.BatchId=@rBatchId) OR (@rBatchId=0))
		AND ((CM.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		ORDER BY FI.InvoiceNumber DESC
			
	DECLARE @cols AS NVARCHAR(MAX),@query  AS NVARCHAR(MAX)

    SELECT @cols = STUFF((SELECT  DISTINCT ',' + QUOTENAME(ID.FeeCode)
                       FROM #InvoiceDetail ID FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,'')   
 
    SELECT @query = 
    'SELECT  
			P.*,
            ID.VariableAmount,
            ID.DiscountAmount,
            ID.AdditionalAmount,
            ID.NotApplicableAmount 
     FROM
    (SELECT  
        FeeInvoiceId,   
        OrganizationName,
        SUId,
        Code,
        ClassDiv,
        RollNo,
        InvoiceNumber,
        CONVERT(varchar(11),InvoiceDate,103) AS InvoiceDate,
        FeeCode, 
        FeeAmount,
        ReceiptBookName,
        CollectionGroupName,
        InvoiceAmount
    FROM #InvoiceDetail)X
    PIVOT 
    (
         SUM(FeeAmount) 
         FOR [FeeCode] IN (' +  @cols + ')
    ) P
    LEFT JOIN
	(
		SELECT
		    FeeInvoiceId,
			SUM(VariableAmount) AS VariableAmount,
			SUM(DiscountAmount) AS DiscountAmount,
			SUM(AdditionalAmount) AS AdditionalAmount,
			SUM(NotApplicableAmount) AS NotApplicableAmount
		FROM  
			#InvoiceDetail
			GROUP BY FeeInvoiceId
    ) ID ON ID.FeeInvoiceId = P.FeeInvoiceId
    '
	EXECUTE(@query)
END
GO
PRINT N'Creating [sHostel].[pAssetTypeMasterAdd]...';


GO
CREATE PROCEDURE [sHostel].[pAssetTypeMasterAdd]
	 
        @rHostelId int,
        @rId int,
        @rCode nvarchar(20),
        @rTitle nvarchar(100),
        @rIsObsolete bit,
        @rCreatedUserId bigint,
        @rOrgGroupId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	IF(@rId = 0)	
	BEGIN
		IF EXISTS(SELECT Id FROM sHostel.tAssetTypeMaster WHERE Code=@rCode AND HostelId=@rHostelId AND OrgGroupId=@rOrgGroupId)
			BEGIN
			SELECT -102 AS Result
			RETURN
		END 
	
		IF EXISTS(SELECT Id FROM sHostel.tAssetTypeMaster WHERE Title=@rTitle AND HostelId=@rHostelId AND OrgGroupId=@rOrgGroupId)
			BEGIN
			SELECT -103 AS Result
			RETURN
		END 
	END
	ELSE
	BEGIN
		IF EXISTS(SELECT Id FROM sHostel.tAssetTypeMaster WHERE Code=@rCode AND HostelId=@rHostelId AND OrgGroupId=@rOrgGroupId  AND Id<>@rId)
		BEGIN
			SELECT -102 AS Result
			RETURN
		END
		IF  EXISTS(SELECT Id FROM sHostel.tAssetTypeMaster WHERE Title=@rTitle AND HostelId=@rHostelId AND OrgGroupId=@rOrgGroupId AND Id<>@rId)
		BEGIN
			SELECT -103 AS Result
			RETURN
		END

	END
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber INT 

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sHostel.tAssetTypeMaster', 0, 1, 1,@outNextNumber = @lNextNumber OUTPUT
	
	INSERT INTO sHostel.tAssetTypeMaster
		(
			HostelId,
			Id,
			Code,
			Title,
			IsObsolete,
			CreatedUserId,
			CreatedDateTime,
			OrgGroupId
		)
	VALUES
		(
			@rHostelId,
			@lNextNumber,
			@rCode,
			@rTitle,
			@rIsObsolete,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rOrgGroupId
		)
		    SELECT 1 AS Result
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sHostel.tAssetTypeMaster
	    SET
			
			Code=@rCode,
			Title=@rTitle,
			IsObsolete=@rIsObsolete,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate()
	      
	      WHERE Id = @rId
	      AND HostelId=@rHostelId
	      AND 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 [sHostel].[pAssetTypeMasterGet]...';


GO
CREATE PROCEDURE [sHostel].[pAssetTypeMasterGet]
	 
	 @rHostelId int,
	 @rId int,
	 @rCode nvarchar(20),
	 @rTitle nvarchar(100),
	 @rOrgGroupId int	
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	
	BEGIN
		SET @rCode = sCommon.fSearchStringGet(@rCode)
		SET @rTitle = sCommon.fSearchStringGet(@rTitle)
	END
	
	SELECT 
			
			AM.Id,
			AM.Code,
			AM.Title,
			AM.IsObsolete,
			AM.HostelId
	FROM 
			sHostel.tAssetTypeMaster AM
	WHERE 
	    AM.HostelId = @rHostelId
		AND	((AM.Id = @rId) OR (@rId = 0))
		AND ((AM.Code like @rCode) OR (ISNULL(@rCode,'') = ''))
		AND ((AM.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
		AND AM.OrgGroupId=@rOrgGroupId
		
END
GO
PRINT N'Creating [sHostel].[pAssignRoomAssetAdd]...';


GO
CREATE PROCEDURE [sHostel].[pAssignRoomAssetAdd]
	 
        @rRoomAssetId int,
        @rSourceTypeId smallint,
        @rSourceId bigint,
        @rHostelId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	 
	BEGIN
	
	INSERT INTO sHostel.tAssignRoomAsset
		(
		   RoomAssetId,
		   SourceTypeId,
		   SourceId,
		   HostelId
		
		)
	VALUES
		(
			@rRoomAssetId,
		    @rSourceTypeId,
		    @rSourceId,
		    @rHostelId
		
		)
		    SELECT 1 AS Result
	END	 


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


GO
CREATE PROCEDURE [sHostel].[pAssignRoomAssetGET]
	 
        @rHostelId int,
        @rRoomId int
        
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	SELECT
	
    DISTINCT AT.Title ,
	 RM.HostelId,
	 RM.RoomId,
	 RM.AssetTypeId
	 
	From 
	sHostel.tRoomAssetMaster RM 
	INNER JOIN sHostel.tAssetTypeMaster AT ON AT.Id=RM.AssetTypeId AND AT.IsObsolete=0
	--LEFT JOIN sHostel.tAssignRoomAsset AR ON RM.Id=AR.RoomAssetId AND AR.SourceTypeId=2003
	--LEFT JOIN sStudent.vStudentLastAcademic VA ON VA.StudentId=AR.SourceId
WHERE 
RM.RoomId=@rRoomId
AND RM.HostelId=@rHostelId
--AND ((AR.SourceTypeId=@rSourceTypeId)OR (@rSourceTypeId=0))
--AND ((AR.SourceId=@rSourceId)OR (@rSourceId=0))
END
GO
PRINT N'Creating [sHostel].[pHostelDepositAddAdd]...';


GO
CREATE PROCEDURE [sHostel].[pHostelDepositAddAdd]
	 
	@rId bigint,
	@rHostelDepositHeadId int,
	@rStudentId bigint,
	@rAmount decimal(12,2),
	@rDepositDate date,
	@rPayTypeId tinyint,
	@rChequeNo nvarchar(20),
	@rBankName nvarchar(200),
	@rRemark nvarchar(200),
	@rCreatedUserId bigint,
	@rHostelId int,
	@rOrgGroupId smallint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

DECLARE @lStudentId bigint
DECLARE @lClassId int

BEGIN	
BEGIN TRY
BEGIN TRANSACTION	

 SELECT @lStudentId= StudentId From sStudent.tAcademic Where Id=@rStudentId
 SELECT @lClassId= ClassId From sStudent.tAcademic Where Id=@rStudentId

	-- AMOUNT VALIDATION
	--If EXISTS
	--(SELECT DB.BalanceAmount FROM sFee.tDepositBalance DB WHERE DB.DepositHeadId = @rDepositHeadId AND DB.ClassId=@lClassId AND BalanceAmount 
	-- < (SELECT  ISNULL(SUM(DA.Amount),0) + @rAmount AS TotalAmount FROM sFee.tDepositAdd DA 
	--	WHERE DepositHeadId = @rDepositHeadId AND StudentId=@lStudentId AND Id <> @rId)) 				
	--BEGIN
	--	SELECT -102 as Result
	--	RETURN
	--END 

 DECLARE @lNextNumber bigint 
 IF(@rId = 0)	    
 BEGIN  
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sHostel.tHostelDepositAdd', 0, 1, 1,@outNextNumber = @lNextNumber output
	INSERT INTO sHostel.tHostelDepositAdd
		(
		Id,
		HostelDepositHeadId,
		StudentId,
		Amount,
		DepositDate,
		PayTypeId,
		ChequeNo,
		BankName,
		Remark,
		CreatedUserId,
		CreatedDateTime,
		HostelId
		)
	VALUES
		(
		@lNextNumber,
		@rHostelDepositHeadId,
		@lStudentId,
		@rAmount,
		@rDepositDate,
		@rPayTypeId,
		@rChequeNo,
		@rBankName,
		@rRemark,
		@rCreatedUserId,
		sCommon.fGetDate(),
		@rHostelId
		) 
		SELECT @lNextNumber AS Result   
	END	
ELSE

    BEGIN 
    SET @lNextNumber = @rId
	    UPDATE sHostel.tHostelDepositAdd
	    SET
	    HostelDepositHeadId=@rHostelDepositHeadId,
	    StudentId=@lStudentId,
		Amount=@rAmount,
		DepositDate=@rDepositDate,
		PayTypeId=@rPayTypeId,
		ChequeNo=@rChequeNo,
		BankName=@rBankName,
		Remark=@rRemark,
		UpdatedUserId=@rCreatedUserId,
	    UpdatedDateTime=sCommon.fGetDate(),
	    HostelId=@rHostelId	    
	    WHERE Id = @rId  AND HostelId=@rHostelId
	    SELECT @lNextNumber AS Result
	 END  
	
	COMMIT TRANSACTION
		
END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
	
END
GO
PRINT N'Creating [sHostel].[pHostelDepositAddGET]...';


GO

CREATE PROCEDURE [sHostel].[pHostelDepositAddGET]
          
		   @rOrgId int,          
           @rHostelDepositHeadId int,
           @rFromAmount decimal(12,2),
           @rToAmount decimal(12,2),
           @rFromDepositDate date,
           @rToDepositDate date,
           @rHostelId int,
           @rCode nvarchar(20)
           
AS
SET NOCOUNT ON

BEGIN
SELECT  
		DHM.Title AS DepositHeadName,
		vSA.OrgId,
		DA.Id,
		DA.HostelDepositHeadId,
		DA.StudentId AS StudentId,
		vSA.AcademicId AS AcademicId,
		DA.Amount,
		DA.DepositDate,
		DA.PayTypeId,
		DA.ChequeNo,
		DA.BankName,
		DA.Remark,
		DA.CreatedDateTime,
		vSA.Code,
        vSA.Name AS StudentName,        
        vSA.ClassName+' - '+vSA.DivisionName AS ClassDivisionName,
       ISNULL(VSA.SUID,'') AS SUID
  FROM 		
		sStudent.vStudentLastAcademic vSA
		INNER JOIN sHostel.tHostelDepositAdd DA ON DA.StudentId = vSA.StudentId
		INNER JOIN sHostel.tHostelDepositHeadMaster DHM ON DHM.Id = DA.HostelDepositHeadId 
  WHERE  
		--vSA.BatchId = @rBatchId
		 (vSA.OrgId=@rOrgId OR @rOrgId=0)
		AND (DA.HostelDepositHeadId=@rHostelDepositHeadId OR @rHostelDepositHeadId=0)
		AND ((DA.Amount >= @rFromAmount) OR (@rFromAmount = 0))
		AND ((DA.Amount <= @rToAmount) OR (@rToAmount = 0))
		AND ((DA.DepositDate >= @rFromDepositDate) OR (ISNULL(@rFromDepositDate,'') = ''))
		AND ((DA.DepositDate <= @rToDepositDate) OR (ISNULL(@rToDepositDate,'') = ''))
		AND ((vSA.Code=@rCode) OR (ISNULL(@rCode,'')=''))
		AND (DA.HostelId=@rHostelId)
		Order By DA.DepositDate
END
GO
PRINT N'Creating [sHostel].[pHostelDepositAdjustmentAdd]...';


GO
CREATE PROCEDURE [sHostel].[pHostelDepositAdjustmentAdd]
	
	@rId bigint, 
	@rHostelDepositHeadId int,
	@rStudentId bigint,
	@rAmount decimal(12,2),
	@rAdjustmentDate date,
	@rRemark nvarchar(200),
	@rCreatedUserId bigint,
	@rBatchId int,
	@rOrgGroupId smallint ,
	@rHostelId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

DECLARE @lStudentId bigint

BEGIN	
BEGIN TRY
BEGIN TRANSACTION	

 SELECT @lStudentId= StudentId From sStudent.tAcademic Where Id=@rStudentId
 	
	-- DATE VALIDATION
	BEGIN
		IF EXISTS	(SELECT 1 FROM  sHostel.tHostelDepositAdd D  INNER JOIN sHostel.tHostelDepositAdjustment DA ON D.HostelDepositHeadId = DA.HostelDepositHeadId 
									AND D.StudentId=@lStudentId  AND D.DepositDate > @rAdjustmentDate)
		BEGIN
			SELECT -101 as Result
			RETURN
		END 
	END 
 
	-- AMOUNT VALIDATIEON
	--BEGIN
	--	 If EXISTS
	--		(SELECT ISNULL(SUM(D.Amount),0),DepositHeadId,StudentId FROM sFee.tDepositAdd D 
	--		WHERE D.DepositHeadId = @rDepositHeadId AND D.StudentId=@lStudentId Group by StudentId,DepositHeadId Having Sum(D.Amount) 
	--	 < (SELECT ISNULL(SUM(Amount),0)+ @rAmount AS TotalAmount FROM sFee.tDepositAdjustment DA 
	--		WHERE DA.DepositHeadId = @rDepositHeadId AND DA.StudentId=@lStudentId AND Id <> @rId )) 	
	--	BEGIN
	--		SELECT -102 as Result
	--		RETURN
	--	END 
	--END				
 
DECLARE @lNextNumber bigint 
IF(@rId = 0)
BEGIN
EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sHostel.tHostelDepositAdjustment', 0, 1, 1,@outNextNumber = @lNextNumber output 
	INSERT INTO sHostel.tHostelDepositAdjustment
		(
		Id,
		HostelDepositHeadId,
		StudentId,
		Amount,
		AdjustmentDate,
		Remark,
		CreatedUserId,
		CreatedDateTime,
		HostelId
		)
	VALUES
		(
		@lNextNumber,
		@rHostelDepositHeadId,
		@lStudentId,
		@rAmount,
		@rAdjustmentDate,
		@rRemark,
		@rCreatedUserId,
		sCommon.fGetDate()
		,@rHostelId
		) 
		SELECT @lNextNumber AS Result   
	END	
ELSE
    BEGIN
    SET @lNextNumber = @rId
	    UPDATE sHostel.tHostelDepositAdjustment
	    SET
	    HostelDepositHeadId=@rHostelDepositHeadId,
	    StudentId=@lStudentId,
		Amount=@rAmount,
		AdjustmentDate=@rAdjustmentDate,
		Remark=@rRemark,
		UpdatedUserId=@rCreatedUserId,
	    UpdatedDateTime=sCommon.fGetDate(),
	    HostelId=@rHostelId	    
	    WHERE Id = @rId  AND HostelId=@rHostelId	 
	    SELECT @lNextNumber AS Result
	 END  
	
	COMMIT TRANSACTION
		
END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
	
END
GO
PRINT N'Creating [sHostel].[pHostelDepositAdjustmentGet]...';


GO

CREATE PROCEDURE [sHostel].[pHostelDepositAdjustmentGet]
          
		   @rOrgId int,          
           @rHostelDepositHeadId int,
           @rFromAmount decimal(12,2),
           @rToAmount decimal(12,2),
           @rFromAdjustmentDate date,
           @rToAdjustmentDate date,
        --   @rBatchId int,
           @rCode nvarchar(20),
           @rHostelId int
           
AS
SET NOCOUNT ON

BEGIN
SELECT  
		DHM.Title AS DepositHeadName,
		vSA.OrgId,
		DA.Id,
		DA.HostelDepositHeadId,
		DA.StudentId AS StudentId,
		vSA.AcademicId AS AcademicId,
		DA.Amount,
		DA.AdjustmentDate,
		DA.Remark,
		DA.CreatedDateTime,
		vSA.Code,
        vSA.Name AS StudentName,        
        vSA.ClassName+' - '+vSA.DivisionName AS ClassDivisionName,
        ISNULL(vSA.SUId,'') AS SUId
  FROM 		
		sStudent.vStudentLastAcademic vSA
		INNER JOIN sHostel.tHostelDepositAdjustment DA ON DA.StudentId = vSA.StudentId
		INNER JOIN sHostel.tHostelDepositHeadMaster DHM ON DHM.Id = DA.HostelDepositHeadId
  WHERE  
		--vSA.BatchId = @rBatchId 
		(vSA.OrgId=@rOrgId OR @rOrgId=0)
		AND (DA.HostelDepositHeadId=@rHostelDepositHeadId OR @rHostelDepositHeadId=0)
		AND ((DA.Amount >= @rFromAmount) OR (@rFromAmount = 0))
		AND ((DA.Amount <= @rToAmount) OR (@rToAmount = 0))
		AND ((DA.AdjustmentDate >= @rFromAdjustmentDate) OR (ISNULL(@rFromAdjustmentDate,'') = ''))
		AND ((DA.AdjustmentDate <= @rToAdjustmentDate) OR (ISNULL(@rToAdjustmentDate,'') = ''))
		AND ((vSA.Code=@rCode) OR (ISNULL(@rCode,'')=''))
		AND (DA.HostelId=@rHostelId)
		Order By DA.AdjustmentDate
END
GO
PRINT N'Creating [sHostel].[pHostelDepositHeadMasterAdd]...';


GO

CREATE PROCEDURE [sHostel].[pHostelDepositHeadMasterAdd]
	 
	        @rId int
	       ,@rNumber int
	       ,@rCode nvarchar(20)
           ,@rTitle nvarchar(100)
           ,@rOrderIndex smallint
           ,@rIsObsolete bit
           ,@rCreatedUserId bigint           
           ,@rOrgGroupId smallint
           ,@rHostelId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	IF(@rId = 0)	
	BEGIN
		If Exists(select Id from sHostel.tHostelDepositHeadMaster where Code=@rCode AND OrgGroupId=@rOrgGroupId AND HostelId=@rHostelId)
			BEGIN
			select -101 as Result
			RETURN
		END 
		If Exists(select Id from sHostel.tHostelDepositHeadMaster where Number=@rNumber AND OrgGroupId=@rOrgGroupId  AND HostelId=@rHostelId)
			BEGIN
			select -102 as Result
			RETURN
		END
		If Exists(select Id from sHostel.tHostelDepositHeadMaster where Title=@rTitle AND OrgGroupId=@rOrgGroupId  AND HostelId=@rHostelId)
			BEGIN
			select -103 as Result
			RETURN
		END 
		If Exists(select Id from sHostel.tHostelDepositHeadMaster where OrderIndex=@rOrderIndex AND OrgGroupId=@rOrgGroupId AND HostelId=@rHostelId)
			BEGIN
			select -104 as Result
			RETURN
		END 
	END
	ELSE
	BEGIN
		If Exists(select Id from sHostel.tHostelDepositHeadMaster where Code=@rCode AND HostelId=@rHostelId AND OrgGroupId=@rOrgGroupId AND Id<>@rId)
		Begin
			select -101 as Result
			RETURN
		End 
		If Exists(select Id from sHostel.tHostelDepositHeadMaster where Number=@rNumber AND OrgGroupId=@rOrgGroupId AND HostelId=@rHostelId AND Id<>@rId)
			BEGIN
			select -102 as Result
			RETURN
		END
		If  Exists(select Id from sHostel.tHostelDepositHeadMaster where Title=@rTitle AND OrgGroupId=@rOrgGroupId AND HostelId=@rHostelId AND Id<>@rId)
		Begin
			select -103 as Result
			RETURN
		End
		If  Exists(select Id from sHostel.tHostelDepositHeadMaster where OrderIndex=@rOrderIndex AND OrgGroupId=@rOrgGroupId  AND HostelId=@rHostelId AND Id<>@rId)
		Begin
			select -104 as Result
			RETURN
		End
	END
	
 BEGIN TRANSACTION	
	 DECLARE @lNextNumber INT     
	
IF(@rId = 0)	
BEGIN
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sHostel.tHostelDepositHeadMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	INSERT INTO [sHostel].[tHostelDepositHeadMaster]
			   (
			    [Id]
			   ,[Number]  
			   ,[Code]
			   ,[Title]
			   ,[OrderIndex]
			   ,[IsObsolete]
			   ,[CreatedUserId]
			   ,[CreatedDateTime]
			   ,[OrgGroupId]
			   ,[HostelId]
			   )
		 VALUES
			   (
				@lNextNumber
			   ,@rNumber
			   ,@rCode
			   ,@rTitle
			   ,@rOrderIndex
			   ,@rIsObsolete
			   ,@rCreatedUserId
			   ,sCommon.fGetDate()
			   ,@rOrgGroupId
			   ,@rHostelId
			   )
			   SELECT 1 AS Result
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  [sHostel].[tHostelDepositHeadMaster]
	    SET
			  Number=@rNumber
	         ,Code=@rCode
	         ,Title=@rTitle
	         ,OrderIndex=@rOrderIndex
             ,IsObsolete = @rIsObsolete                          
             ,UpdatedUserId = @rCreatedUserId
             ,UpdatedDateTime = sCommon.fGetDate() 
             ,HostelId=@rHostelId         
             
	      WHERE Id = @rId AND HostelId=@rHostelId  
	 END  
	      SELECT @lNextNumber AS Result
			COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Creating [sHostel].[pHostelDepositHeadMasterGet]...';


GO

CREATE PROCEDURE [sHostel].[pHostelDepositHeadMasterGet]
          
           @rId int,
           @rCode nvarchar(20),
           @rTitle nvarchar(100),
           @rOrgGroupId smallint,
           @rIsWildCardSearch bit,
           @rHostelId int
AS
SET NOCOUNT ON

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

BEGIN
SELECT DHM.Id 
	  ,DHM.Number
      ,DHM.Code
      ,DHM.Title
      ,DHM.OrderIndex
      ,DHM.IsObsolete
     
  FROM sHostel.tHostelDepositHeadMaster DHM 
        
  WHERE 
		((DHM.Id = @rId) OR (@rId = 0))
	AND ((DHM.Code Like @rCode)OR(ISNULL(@rCode,'') = ''))
	AND ((DHM.Title Like @rTitle)OR(ISNULL(@rTitle,'') = ''))
	AND (DHM.OrgGroupId = @rOrgGroupId)
	AND (DHM.HostelId=@rHostelId)
		order by DHM.OrderIndex 
END
GO
PRINT N'Creating [sHostel].[pHostelDepositRefundAdd]...';


GO
CREATE PROCEDURE [sHostel].[pHostelDepositRefundAdd]
	 
	@rHostelDepositHeadId int,
	@rStudentId bigint,
	@rRefundAmount decimal(12,2),
	@rRefundDate date,
	@rPayTypeId tinyint,
	@rChequeNo nvarchar(20),
	@rBankName nvarchar(200),
	@rRemark nvarchar(200),
	@rCreatedUserId bigint,
	@rHostelId int
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

DECLARE @lStudentId bigint
Declare @lRefundAmount decimal(12,2)
BEGIN	
BEGIN TRY
BEGIN TRANSACTION	

 SELECT @lStudentId= StudentId From sStudent.tAcademic Where Id=@rStudentId
 
 -- AMOUNT VALIDATIEON
 IF EXISTS (SELECT 1 FROM sHostel.tHostelDepositRefund DR WHERE StudentId= @lStudentId AND HostelDepositHeadId = @rHostelDepositHeadId AND HostelId=@rHostelId)
 BEGIN
	SELECT @lRefundAmount = (SELECT ISNULL(SUM(D.Amount),0) FROM sHostel.tHostelDepositAdd D 
	INNER JOIN sHostel.tHostelDepositRefund DR1 ON DR1.HostelDepositHeadId=D.HostelDepositHeadId AND DR1.StudentId=D.StudentId AND D.StudentId = @lStudentId
	WHERE D.HostelDepositHeadId = DR1.HostelDepositHeadId AND D.StudentId=DR1.StudentId AND D.HostelId=DR1.HostelId)

	 - (SELECT ISNULL(SUM(DA.Amount),0) AS TotalAmount FROM sHostel.tHostelDepositAdjustment DA 
	 INNER JOIN sHostel.tHostelDepositRefund DR2 ON DR2.HostelDepositHeadId=DA.HostelDepositHeadId AND DR2.StudentId=DA.StudentId AND DA.StudentId = @lStudentId
	 WHERE DA.HostelDepositHeadId = DR2.HostelDepositHeadId AND DA.StudentId=DR2.StudentId AND DA.HostelId=DR2.HostelId) 
	 
	IF @lRefundAmount < @rRefundAmount
		BEGIN
			SELECT -101 AS RESULT
			RETURN
		END		 
	END	 
	
 -- DATE VALIDATION
 
	BEGIN
		IF EXISTS	(SELECT 1 FROM  sHostel.tHostelDepositAdd D  INNER JOIN sHostel.tHostelDepositRefund DR ON D.HostelDepositHeadId = DR.HostelDepositHeadId 
									AND D.StudentId=@lStudentId  AND D.HostelId=@rHostelId AND D.DepositDate > @rRefundDate)
		BEGIN
			SELECT -102 as Result
			RETURN
		END 
	END 
 
 IF NOT EXISTS (SELECT 1 FROM sHostel.tHostelDepositRefund DR INNER JOIN sStudent.tAcademic A ON A.StudentId = DR.StudentId 
			    AND A.StudentId=@lStudentId AND DR.HostelDepositHeadId=@rHostelDepositHeadId AND DR.HostelId=@rHostelId)
 
 BEGIN   
	INSERT INTO sHostel.tHostelDepositRefund
		(
		HostelDepositHeadId,
		StudentId,
		RefundAmount,
		RefundDate,
		PayTypeId,
		ChequeNo,
		BankName,
		Remark,
		CreatedUserId,
		CreatedDateTime,
		HostelId
		)
	VALUES
		(
		@rHostelDepositHeadId,
		@lStudentId,
		@rRefundAmount,
		@rRefundDate,
		@rPayTypeId,
		@rChequeNo,
		@rBankName,
		@rRemark,
		@rCreatedUserId,
		sCommon.fGetDate(),
		@rHostelId
		) 
		SELECT 1 AS Result   
	END	
	
ELSE
    BEGIN
	    UPDATE sHostel.tHostelDepositRefund
	    SET
		RefundAmount=@rRefundAmount,
		RefundDate=@rRefundDate,
		PayTypeId=@rPayTypeId,
		ChequeNo=@rChequeNo,
		BankName=@rBankName,
		Remark=@rRemark,
		UpdatedUserId=@rCreatedUserId,
	    UpdatedDateTime=sCommon.fGetDate()	    
	    WHERE HostelDepositHeadId=@rHostelDepositHeadId 
	    AND StudentId=@lStudentId
	    AND HostelId=@rHostelId
	    SELECT @rStudentId AS Result
	 END  
	
	COMMIT TRANSACTION
		
END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
	
END
GO
PRINT N'Creating [sHostel].[pHostelDepositRefundAmountGet]...';


GO
CREATE PROCEDURE [sHostel].[pHostelDepositRefundAmountGet]
	 
	@rHostelDepositHeadId int,
	@rStudentId bigint,
	@rHostelId int  
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
DECLARE @lStudentId bigint
BEGIN	
BEGIN TRY
BEGIN TRANSACTION	

 SELECT @lStudentId= StudentId From sStudent.tAcademic Where Id=@rStudentId
 
 -- AMOUNT VALIDATIEON
 IF EXISTS (SELECT 1 FROM sHostel.tHostelDepositRefund DR WHERE StudentId= @lStudentId AND HostelDepositHeadId = @rHostelDepositHeadId AND DR.HostelId=@rHostelId)
  BEGIN
		SELECT ISNULL((SELECT ISNULL(SUM(D.Amount),0) FROM sHostel.tHostelDepositAdd D 
		LEFT JOIN sHostel.tHostelDepositRefund DR1 ON DR1.HostelDepositHeadId=D.HostelDepositHeadId AND DR1.StudentId=D.StudentId
		WHERE D.HostelDepositHeadId = @rHostelDepositHeadId AND D.StudentId=@lStudentId AND D.HostelId=@rHostelId)

		 - (SELECT ISNULL(SUM(DA.Amount),0) AS TotalAmount FROM sHostel.tHostelDepositAdjustment DA 
		 LEFT JOIN sHostel.tHostelDepositRefund DR2 ON DR2.HostelDepositHeadId=DA.HostelDepositHeadId AND DR2.StudentId=DA.StudentId
		 WHERE DA.HostelDepositHeadId = @rHostelDepositHeadId AND DA.StudentId=@lStudentId AND DA.HostelId=@rHostelId)
		 - (select ISNULL(DR.RefundAmount,0) FROM sHostel.tHostelDepositRefund DR WHERE StudentId= @lStudentId AND HostelDepositHeadId = @rHostelDepositHeadId AND HostelId=@rHostelId ),0) As RefundAmount
   END	
ELSE
BEGIN
		SELECT ISNULL((SELECT ISNULL(SUM(D.Amount),0) FROM sHostel.tHostelDepositAdd D 
		LEFT JOIN sHostel.tHostelDepositRefund DR1 ON DR1.HostelDepositHeadId=D.HostelDepositHeadId AND DR1.StudentId=D.StudentId
		WHERE D.HostelDepositHeadId = @rHostelDepositHeadId AND D.StudentId=@lStudentId AND D.HostelId=@rHostelId)

		 - (SELECT ISNULL(SUM(DA.Amount),0) AS TotalAmount FROM sHostel.tHostelDepositAdjustment DA 
		 LEFT JOIN sHostel.tHostelDepositRefund DR2 ON DR2.HostelDepositHeadId=DA.HostelDepositHeadId AND DR2.StudentId=DA.StudentId
		  WHERE DA.HostelDepositHeadId = @rHostelDepositHeadId AND DA.StudentId=@lStudentId AND DA.HostelId=@rHostelId),0) As RefundAmount
     END

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


GO


CREATE PROCEDURE [sHostel].[pHostelDepositRefundDelete]
	 
		@rStudentId bigint,
		@rHostelDepositHeadId int,
		@rHostelId int  
		
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 

	BEGIN TRY
		BEGIN TRANSACTION		

	
	BEGIN
		DELETE  sHostel.tHostelDepositRefund
		FROM sHostel.tHostelDepositRefund DR
		WHERE DR.StudentId=@rStudentId AND DR.HostelDepositHeadId=@rHostelDepositHeadId
		AND DR.HostelId=@rHostelId
		SELECT 1 AS Result
	END		
COMMIT TRANSACTION	
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH			
END
GO
PRINT N'Creating [sHostel].[pHostelDepositRefundGet]...';


GO

CREATE PROCEDURE [sHostel].[pHostelDepositRefundGet]
          
		   @rOrgId int,          
           @rHostelDepositHeadId int,
           @rFromRefundAmount decimal(12,2),
           @rToRefundAmount decimal(12,2),
           @rFromRefundDate date,
           @rToRefundDate date,
           @rHostelId int,
           @rCode nvarchar(20)
           
AS
SET NOCOUNT ON

BEGIN
SELECT 
		DHM.Title AS DepositHeadName,
		vSA.OrgId,
		DR.HostelDepositHeadId,
		DR.StudentId AS StudentId,
		vSA.AcademicId AS AcademicId,
		DR.RefundDate,
		DR.PayTypeId,
		DR.ChequeNo,
		DR.BankName,
		DR.Remark,
		DR.CreatedDateTime,
		vSA.Code,
        vSA.Name AS StudentName,        
        vSA.ClassName+' - '+vSA.DivisionName AS ClassDivisionName,
        CASE  WHEN ISNULL(DR.RefundAmount,0) <> 0 THEN ISNULL(DR.RefundAmount,0) ELSE
        (SELECT ISNULL(SUM(D.Amount),0) FROM sFee.tDepositAdd D 
        INNER JOIN sFee.tDepositRefund DR1 ON DR1.DepositHeadId=D.DepositHeadId AND DR1.StudentId=D.StudentId AND D.StudentId = DR.StudentId
        WHERE D.DepositHeadId = DR1.DepositHeadId AND D.StudentId=DR1.StudentId)         
		 - (SELECT ISNULL(SUM(DA.Amount),0) AS TotalAmount FROM sFee.tDepositAdjustment DA 
		 INNER JOIN sFee.tDepositRefund DR2 ON DR2.DepositHeadId=DA.DepositHeadId AND DR2.StudentId=DA.StudentId AND DA.StudentId= DR.StudentId
		 WHERE DA.DepositHeadId = DR2.DepositHeadId AND DA.StudentId=DR2.StudentId) END AS RefundAmount,
		 ISNULL(vSA.SUId,'')AS SUId
        
        
  FROM 		
		sStudent.vStudentLastAcademic vSA
		INNER JOIN sHostel.tHostelDepositRefund DR ON DR.StudentId = vSA.StudentId
		INNER JOIN sHostel.tHostelDepositHeadMaster DHM ON DHM.Id = DR.HostelDepositHeadId
		
  WHERE  
		--vSA.BatchId = @rBatchId 
		(vSA.OrgId=@rOrgId OR @rOrgId=0)
		AND (DR.HostelDepositHeadId=@rHostelDepositHeadId OR @rHostelDepositHeadId=0)
		AND ((DR.RefundAmount >= @rFromRefundAmount) OR (@rFromRefundAmount = 0))
		AND ((DR.RefundAmount <= @rToRefundAmount) OR (@rToRefundAmount = 0))
		AND ((DR.RefundDate >= @rFromRefundDate) OR (ISNULL(@rFromRefundDate,'') = ''))
		AND ((DR.RefundDate <= @rToRefundDate) OR (ISNULL(@rToRefundDate,'') = ''))
		AND ((vSA.Code=@rCode) OR (ISNULL(@rCode,'')=''))
		AND (DR.HostelId=@rHostelId)
		GROUP BY
		DHM.Title,vSA.OrgId,DR.HostelDepositHeadId,DR.StudentId,vSA.AcademicId,DR.RefundAmount,DR.RefundDate,DR.PayTypeId,
		DR.ChequeNo,DR.BankName,DR.Remark,DR.CreatedDateTime,vSA.Code,vSA.Name,vSA.ClassName,vSA.DivisionName ,vSA.SUId 
		Order By DR.RefundDate     
END
GO
PRINT N'Creating [sHostel].[pHostelModelGet]...';


GO
CREATE  PROCEDURE [sHostel].[pHostelModelGet]
	  
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 
	SELECT 
		 HM.Id As HostelId,
		 Hm.Title AS HostelName,
		 HM.Title  As HostelType 
  FROM 
		   sHostel.tHostelMaster HM
		   INNER JOIN  sHostel.tHostelTypeMaster HTM ON HTM.Id = HM.HostelTypeId
 
END
GO
PRINT N'Creating [sHostel].[pRoomAssetMasterAdd]...';


GO
CREATE PROCEDURE [sHostel].[pRoomAssetMasterAdd]
	 
        @rHostelId int,
        @rId int,
        @rRoomId int,
        @rAssetTypeId int,
        @rAssetNumber nvarchar(100),
        @rOrgGroupId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
		
IF(@rId = 0)	
BEGIN
	If Exists(select Id from sHostel.tRoomAssetMaster where AssetNumber=@rAssetNumber AND HostelId=@rHostelId AND RoomId=@rRoomId )
	BEGIN
		select -103 as Result
		RETURN
	END 
END
--ELSE
--BEGIN
--	If  Exists(select Id from sHostel.tRoomAssetMaster where AssetNumber=@rAssetNumber AND HostelId=@rHostelId AND RoomId=@rRoomId AND Id<>@rId)
--	BEGIN
--		select -103 as Result
--		RETURN
--	END
--END
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber INT 

	--IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sHostel.tRoomAssetMaster', 0, 1, 1,@outNextNumber = @lNextNumber OUTPUT
	
	INSERT INTO sHostel.tRoomAssetMaster
		(
			HostelId,
			Id,
			RoomId,
			AssetTypeId,
			AssetNumber
		)
	VALUES
		(
			@rHostelId,
			@lNextNumber,
			@rRoomId,
			@rAssetTypeId,
			@rAssetNumber
		)
		    SELECT 1 AS Result
	END	 
	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Creating [sHostel].[pRoomAssetMasterGet]...';


GO
CREATE PROCEDURE [sHostel].[pRoomAssetMasterGet]
	 
	 @rHostelId int,
	 @rId int=0,
	 @rRoomId int
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	SELECT 
			
			RM.Id,
			RM.RoomId,
			RM.AssetTypeId,
			RM.AssetNumber,
			AM.Title AS AssetType
			
	FROM 
			sHostel.tRoomAssetMaster  RM
			INNER JOIN sHostel.tAssetTypeMaster  AM ON RM.AssetTypeId=AM.Id
	WHERE 
	    RM.HostelId = @rHostelId
	    AND	((RM.RoomId = @rRoomId) OR (@rRoomId = 0))
END
GO
PRINT N'Creating [sHostel].[pRptAddressLabelGet]...';


GO


CREATE PROCEDURE [sHostel].[pRptAddressLabelGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rHostelId int,
	 @rOrgGroupBatchId int,
	 @rOrgId int,
	 @rStudentName nvarchar(100)='',
	 @rStudentCode nvarchar(100)='',
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rIsBasedOnSUId bit = 0,
	 @rDepartmentId int=0,
	 @rSUId nvarchar(20)='',
	 @rRoomId int=0
	 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

	SELECT 
	HM.Title,
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		ISNULL(SA.StudentId,0) as SourceId,
		SA.OrgId,
		SA.DivisionId,
		SA.DivisionOrder,
		@rIsBasedOnSUId AS IsBasedOnSUId ,
		CD.PresentStreetOne AS Address1,
		CD.PresentStreetTwo AS Address2,
		CD.PresentStreetThree AS Address3,
		CD.PresentCountry AS AddressCountry,
		CD.PresentState AS AddressState,
		CD.PresentCity AS AddressCity,
		CD.PresentZipCode AS AddressZipCode,
		CD.PresentContactNo AS ContactNo,
		CD.ParentContactNo ,
		CD.StudentContactNo,
		CD.ParentEmail,
		CD.StudentEmail,
		SA.Name,
		SA.Code,
		SA.SUId
		
			
			
			
	FROM 
		sStudent.vStudentLastAcademic SA 
		LEFT JOIN sStudent.tStudentCommunication CD ON  SA.StudentId=CD.StudentId
		INNER JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 
		INNER JOIN sHostel.tRoomMaster RM ON RM.Id=AR.RoomId 
		INNER JOIN sHostel.tHostelMaster HM ON HM.Id=RM.HostelId
	 
	WHERE 
 (SA.OrgGroupBatchId = @rOrgGroupBatchId)
 AND
		((RM.HostelId=@rHostelId) OR (@rHostelId=0))
		AND ((SA.OrgId = @rOrgId) OR (@rOrgId=0))
		AND ((RM.Id=@rRoomId) OR (@rRoomId=0))
		AND ((SA.DepartmentId = @rDepartmentId ) OR (@rDepartmentId = 0))
		AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
		AND ((SA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))
		AND ((SA.Code Like @rStudentCode) OR (ISNULL(@rStudentCode,'')=''))
	    AND ((SA.SUId like @rSUId) OR (ISNULL(@rSUId,'')=''))
		AND ((SA.FirstName like @rStudentName + '%') OR (ISNULL(@rStudentName,'') = ''))
		 
END
GO
PRINT N'Creating [sHostel].[pRptHostelDepositAddGet]...';


GO

CREATE PROCEDURE [sHostel].[pRptHostelDepositAddGet]
          
		   @rOrgId int,          
           @rHostelDepositHeadId int,
           @rFromAmount decimal(12,2),
           @rToAmount decimal(12,2),
           @rFromDepositDate date,
           @rToDepositDate date,
          -- @rBatchId int,
           @rCode nvarchar(20),
           @rHostelId int
           
AS
SET NOCOUNT ON 

BEGIN
SELECT  
		DHM.Title AS DepositHeadName,
		DA.Id,
		DA.HostelDepositHeadId,
		DA.StudentId AS StudentId,
		vSA.AcademicId AS AcademicId,
		DA.Amount,
		DA.DepositDate,
		DA.PayTypeId,	
		DA.ChequeNo,
		DA.BankName,
		DA.Remark,
		DA.CreatedDateTime,
		vSA.Code,
        vSA.Name AS StudentName,        
        vSA.ClassName+' - '+vSA.DivisionName AS ClassDivisionName,
        OM.Id AS OrgId,
        OM.DisplayTitle AS OrganizationName
  FROM 		
		sStudent.vStudentLastAcademic vSA
		INNER JOIN sHostel.tHostelDepositAdd DA ON DA.StudentId = vSA.StudentId
		INNER JOIN sHostel.tHostelDepositHeadMaster DHM ON DHM.Id = DA.HostelDepositHeadId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=vSA.OrgId
  WHERE  
		--vSA.BatchId = @rBatchId 
		 (vSA.OrgId=@rOrgId OR @rOrgId=0)
		AND (DA.HostelDepositHeadId=@rHostelDepositHeadId OR @rHostelDepositHeadId=0)
		AND ((DA.Amount >= @rFromAmount) OR (@rFromAmount = 0))
		AND ((DA.Amount <= @rToAmount) OR (@rToAmount = 0))
		AND ((DA.DepositDate >= @rFromDepositDate) OR (ISNULL(@rFromDepositDate,'') = ''))
		AND ((DA.DepositDate <= @rToDepositDate) OR (ISNULL(@rToDepositDate,'') = ''))
		AND ((vSA.Code=@rCode) OR (ISNULL(@rCode,'')=''))
		AND (DA.HostelId=@rHostelId)
		Order By DA.DepositDate
END
GO
PRINT N'Creating [sHostel].[pRptHostelDepositAddReceiptGet]...';


GO

CREATE PROCEDURE [sHostel].[pRptHostelDepositAddReceiptGet]
          
		   @rId bigint,
		   @rOrgId int,          
           @rHostelDepositHeadId int,
           --@rBatchId int,
           @rOrgGroupId int,
           @rHostelId int
           
AS
SET NOCOUNT ON 
BEGIN 	
	
	DECLARE @lOrgGroupId int = 0
	DECLARE @lCurrencyCode nvarchar(20) = ''
 
	IF(@rOrgGroupId=0)
	BEGIN
		SELECT @lOrgGroupId = R.OrgGroupId  FROM sHostel.tHostelDepositHeadMaster R 
		INNER JOIN sSetup.tOrgGroupMaster OB ON R.OrgGroupId = OB.Id 
		WHERE R.Id = @rHostelDepositHeadId
		
		SELECT  @lCurrencyCode = [sFinanceCommon].[fDefaultCurrencyCodeGet](@lOrgGroupId) 
	END
	ELSE
	BEGIN
		SELECT  @lCurrencyCode = [sFinanceCommon].[fDefaultCurrencyCodeGet](@rOrgGroupId) 
	END
SELECT  
		DHM.Title AS DepositHeadName,
		DA.Id,
		DA.HostelDepositHeadId,
		DA.StudentId AS StudentId,
		vSA.AcademicId AS AcademicId,
		DA.Amount,
		DA.DepositDate,
		DA.PayTypeId,
		PTM.Title AS PayType,
		DA.ChequeNo,
		DA.BankName,
		DA.Remark,
		DA.CreatedDateTime,
		vSA.RollNo,
		vSA.Code,
        vSA.Name AS StudentName,        
        vSA.ClassName+' - '+vSA.DivisionName AS ClassDivisionName,
        OM.Id AS OrgId,
        OM.DisplayTitle AS OrganizationName,
        sFinanceCommon.fNumberToWordsWithDecimal(ISNULL(DA.Amount,0.00),1,2,OM.OrgGroupId) AS ReceiptAmountInWords,
        vSA.BatchName,
        @lCurrencyCode AS CurrencyCode
        
  FROM 		
		sStudent.vStudentLastAcademic vSA
		INNER JOIN sHostel.tHostelDepositAdd DA ON DA.StudentId = vSA.StudentId
		INNER JOIN sHostel.tHostelDepositHeadMaster DHM ON DHM.Id = DA.HostelDepositHeadId 
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=vSA.OrgId
		INNER JOIn sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=DA.PayTypeId
  WHERE  
		--vSA.BatchId = @rBatchId 
		(vSA.OrgId=@rOrgId OR @rOrgId=0)
		AND (DA.HostelDepositHeadId=@rHostelDepositHeadId OR @rHostelDepositHeadId=0)
		AND (DA.Id=@rId)
	    AND (DA.HostelId=@rHostelId)
		Order By DA.DepositDate
END
GO
PRINT N'Creating [sHostel].[pRptHostelDepositAdjustmentGet]...';


GO

CREATE PROCEDURE [sHostel].[pRptHostelDepositAdjustmentGet]
          
		   @rOrgId int,          
           @rHostelDepositHeadId int,
           @rFromAmount decimal(12,2),
           @rToAmount decimal(12,2),
          @rFromAdjustmentDate date,
           @rToAdjustmentDate date,
           --@rBatchId int,
           @rCode nvarchar(20),
           @rHostelId int
           
AS
SET NOCOUNT ON

BEGIN
SELECT  
		DHM.Title AS DepositHeadName,
		DA.Id,
		DA.HostelDepositHeadId,
		DA.StudentId AS StudentId,
		vSA.AcademicId AS AcademicId,
		DA.Amount,
		DA.AdjustmentDate,
		DA.Remark,
		DA.CreatedDateTime,
		vSA.Code,
        vSA.Name AS StudentName,        
        vSA.ClassName+' - '+vSA.DivisionName AS ClassDivisionName,
        OM.Id AS OrgId,
        OM.DisplayTitle AS OrganizationName
  FROM 		
		sStudent.vStudentLastAcademic vSA
		INNER JOIN  sHostel.tHostelDepositAdjustment DA ON DA.StudentId = vSA.StudentId
		INNER JOIN sHostel.tHostelDepositHeadMaster DHM ON DHM.Id = DA.HostelDepositHeadId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=vSA.OrgId
  WHERE  
		--vSA.BatchId = @rBatchId 
		 (vSA.OrgId=@rOrgId OR @rOrgId=0)
		AND (DA.HostelDepositHeadId=@rHostelDepositHeadId OR @rHostelDepositHeadId=0)
		AND ((DA.Amount >= @rFromAmount) OR (@rFromAmount = 0))
		AND ((DA.Amount <= @rToAmount) OR (@rToAmount = 0))
		AND ((DA.AdjustmentDate >= @rFromAdjustmentDate) OR (ISNULL(@rFromAdjustmentDate,'') = ''))
		AND ((DA.AdjustmentDate <= @rToAdjustmentDate) OR (ISNULL(@rToAdjustmentDate,'') = ''))
		AND ((vSA.Code=@rCode) OR (ISNULL(@rCode,'')=''))
		AND (DA.HostelId=@rHostelId)
		Order By DA.CreatedDateTime
END
GO
PRINT N'Creating [sHostel].[pRptHostelDepositAdjustmentReceiptGet]...';


GO

CREATE PROCEDURE [sHostel].[pRptHostelDepositAdjustmentReceiptGet]
          
		   @rId bigint,          
		   @rOrgId int,          
           @rHostelDepositHeadId int,
           --@rBatchId int,
           @rHostelId int
           
AS
SET NOCOUNT ON

BEGIN
   
 
SELECT  
		DHM.Title AS DepositHeadName,
		DA.Id,
		DA.HostelDepositHeadId,
		DA.StudentId AS StudentId,
		vSA.AcademicId AS AcademicId,
		DA.Amount,
		DA.AdjustmentDate,
		DA.Remark,
		DA.CreatedDateTime,
		vSA.RollNo,
		vSA.Code,
        vSA.Name AS StudentName,        
        vSA.ClassName+' - '+vSA.DivisionName AS ClassDivisionName,
        OM.Id AS OrgId,
        OM.DisplayTitle AS OrganizationName,
        sFinanceCommon.fNumberToWordsWithDecimal(ISNULL(DA.Amount,0.00),1,2,OM.OrgGroupId) AS ReceiptAmountInWords
  FROM 		
		sStudent.vStudentLastAcademic vSA
		INNER JOIN sHostel.tHostelDepositAdjustment DA ON DA.StudentId = vSA.StudentId
		INNER JOIN sHostel.tHostelDepositHeadMaster DHM ON DHM.Id = DA.HostelDepositHeadId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=vSA.OrgId
  WHERE  
		--vSA.BatchId = @rBatchId 
		(vSA.OrgId=@rOrgId OR @rOrgId=0)
		AND (DA.HostelDepositHeadId=@rHostelDepositHeadId OR @rHostelDepositHeadId=0)
		AND (DA.Id=@rId)
		AND (DA.HostelId=@rHostelId)
		Order By DA.CreatedDateTime
END
GO
PRINT N'Creating [sHostel].[pRptHostelDepositMinusGet]...';


GO

CREATE PROCEDURE [sHostel].[pRptHostelDepositMinusGet]
          
     @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rHostelId int,
	 @rOrgGroupBatchId int,
	 @rOrgId int,
	 @rRoomId int=0,
	 @rStudentName nvarchar(100)='',
	 @rStudentCode nvarchar(100)='',
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rIsBasedOnSUId bit = 0,
	 @rDepartmentId int=0,
	 @rSUId nvarchar(20)=''
           
AS
SET NOCOUNT ON

BEGIN
SELECT 
        @rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		'Student' AS SourceType,
		2003 AS SourceTypeId,
		ISNULL(SA.StudentId,0) as SourceId,
		SA.SUId AS SUId,
		SA.Code as SourceCode,
		SA.Name as StudentName,
		SA.ClassName+'-'+SA.DivisionName as ClassDivisionName,
		SA.RollNo,
--		DA.HostelDepositHeadId,
--		DHM.Title AS DepositHeadName,
		SA.OrgId,
		SA.OrganizationName,
		(D.TotalDeposit - A.TotalAdjustment) AS MinusAmount,
		RM.Title AS Room
		
  FROM 		
		sStudent.vStudentLastAcademic SA
		LEFT  JOIN sHostel.tAssignRoom AR ON AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003
		LEFT JOIN sHostel.tRoomMaster RM ON  RM.Id=AR.RoomId 
		LEFT JOIN
		(SELECT SUM(ISNULL(DA.Amount,0)) AS TotalDeposit,DA.StudentId,DA.HostelId FROM sHostel.tHostelDepositAdd DA WHERE DA.HostelId = @rHostelId GROUP BY DA.StudentId,DA.HostelId  )D 
		ON D.StudentId=SA.StudentId
		LEFT JOIN 
		(select SUM(ISNULL(AD.Amount,0)) AS TotalAdjustment,AD.StudentId   FROM sHostel.tHostelDepositAdjustment AD WHERE AD.HostelId = @rHostelId GROUP BY AD.StudentId) A 
		ON A.StudentId=SA.StudentId
		--INNER JOIN sHostel.tHostelDepositHeadMaster DHM ON DHM.Id = D.HostelDepositHeadId
		
  WHERE  
       
       D.TotalDeposit - A.TotalAdjustment < 0 
		AND ((SA.OrgId = @rOrgId) OR (@rOrgId=0))
		AND ((D.HostelId=@rHostelId) OR (@rHostelId=0))
		AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
		AND ((SA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))
		AND ((SA.Code Like @rStudentCode) OR (ISNULL(@rStudentCode,'')=''))
		AND ((SA.FirstName like @rStudentName + '%') OR (ISNULL(@rStudentName,'') = ''))
		AND ((SA.DepartmentId = @rDepartmentId ) OR (@rDepartmentId = 0))
		AND (SA.SUId like @rSUId OR ISNULL(@rSUId,'')='') 
		
END
GO
PRINT N'Creating [sHostel].[pRptHostelDepositRefundGet]...';


GO

CREATE PROCEDURE [sHostel].[pRptHostelDepositRefundGet]
          
		   @rOrgId int,          
           @rHostelDepositHeadId int,
           @rFromRefundAmount decimal(12,2),
           @rToRefundAmount decimal(12,2),
           @rFromRefundDate date,
           @rToRefundDate date,
           @rHostelId int,
           @rCode nvarchar(20)
           
AS
SET NOCOUNT ON

BEGIN
SELECT 
		DHM.Title AS DepositHeadName,
		DR.HostelDepositHeadId,
		DR.StudentId AS StudentId,
		vSA.AcademicId AS AcademicId,
		DR.RefundDate,
		DR.PayTypeId,
		DR.ChequeNo,
		DR.BankName,
		DR.Remark,
		DR.CreatedDateTime,
		vSA.Code,
        vSA.Name AS StudentName,        
        vSA.ClassName+' - '+vSA.DivisionName AS ClassDivisionName,
        
		CASE  WHEN ISNULL(DR.RefundAmount,0) <> 0 THEN ISNULL(DR.RefundAmount,0) ELSE
		(SELECT ISNULL(SUM(D.Amount),0) FROM sHostel.tHostelDepositAdd D 
		INNER JOIN sHostel.tHostelDepositRefund DR1 ON DR1.HostelDepositHeadId=D.HostelDepositHeadId AND DR1.StudentId=D.StudentId AND D.StudentId = DR.StudentId
		WHERE D.HostelDepositHeadId = DR1.HostelDepositHeadId AND D.StudentId=DR1.StudentId)         
		- (SELECT ISNULL(SUM(DA.Amount),0) AS TotalAmount FROM sHostel.tHostelDepositAdjustment DA 
		INNER JOIN sHostel.tHostelDepositRefund DR2 ON DR2.HostelDepositHeadId=DA.HostelDepositHeadId AND DR2.StudentId=DA.StudentId AND DA.StudentId= DR.StudentId
		WHERE DA.HostelDepositHeadId = DR2.HostelDepositHeadId AND DA.StudentId=DR2.StudentId) END AS RefundAmount,
		
		OM.Id AS OrgId,
        OM.DisplayTitle AS OrganizationName
        
        
  FROM 		
		sStudent.vStudentLastAcademic vSA
		INNER JOIN sHostel.tHostelDepositRefund DR ON DR.StudentId = vSA.StudentId
		INNER JOIN sHostel.tHostelDepositHeadMaster DHM ON DHM.Id = DR.HostelDepositHeadId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=vSA.OrgId
		
  WHERE  
		--vSA.BatchId = @rBatchId 
		 (vSA.OrgId=@rOrgId OR @rOrgId=0)
		AND (DR.HostelDepositHeadId=@rHostelDepositHeadId OR @rHostelDepositHeadId=0)
		AND ((DR.RefundAmount >= @rFromRefundAmount) OR (@rFromRefundAmount = 0))
		AND ((DR.RefundAmount <= @rToRefundAmount) OR (@rToRefundAmount = 0))
		AND ((DR.RefundDate >= @rFromRefundDate) OR (ISNULL(@rFromRefundDate,'') = ''))
		AND ((DR.RefundDate <= @rToRefundDate) OR (ISNULL(@rToRefundDate,'') = ''))
		AND ((vSA.Code=@rCode) OR (ISNULL(@rCode,'')=''))
		AND (DR.HostelId=@rHostelId)
		
		GROUP BY
		
		DHM.Title,DR.HostelDepositHeadId,DR.StudentId,vSA.AcademicId,DR.RefundAmount,DR.RefundDate,DR.PayTypeId,
		DR.ChequeNo,DR.BankName,DR.Remark,DR.CreatedDateTime,vSA.Code,vSA.Name,vSA.ClassName,vSA.DivisionName,OM.Id,OM.DisplayTitle       
		Order By DR.RefundDate
END
GO
PRINT N'Creating [sHostel].[pRptHostelStudentGatePassGet]...';


GO
CREATE PROCEDURE [sHostel].[pRptHostelStudentGatePassGet]

	 @rId int,
	 @rStudentCode nvarchar(20),
	 @rHostelId int,
	 @rOutDate datetime,
	 @rInDate datetime
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	
	SELECT 
			VA.Code,
			VA.FirstName AS StudentName,
			SG.WhithWhom,
			SG.ApprovedBy,
			SG.Reason,
		    SG.OutDate,
			SG.InDate,
			SG.Id,
			HM.Title AS HostelName,
			VA.Code,
			SG.StudentId,
			SG.OutTime,
			SG.InTime,
			VA.OrganizationName,
			VA.ClassName+' - '+VA.DivisionName AS Class,
			SI.StudentPhoto	,
			ISNULL(U.DisplayTitle,'') AS UserName	
	FROM 
			sHostel.tStudentGatePass SG
			INNER JOIN sStudent.vStudentLastAcademic VA ON VA.StudentId=SG.StudentId
			LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=VA.StudentId
			LEFT JOIN sSecurity.tUser U	ON U.Id=SG.CreatedUserId
			INNER JOIN sHostel.tHostelMaster HM ON HM.Id=SG.HostelId
		  
	WHERE 
			((SG.Id = @rId) OR (@rId = 0))
		 AND (VA.Code = @rStudentCode  OR ISNULL(@rStudentCode,'')='')
		 AND ((SG.HostelId = @rHostelId) OR (@rHostelId = 0))
		 AND (SG.OutDate>=@rOutDate OR ISNULL(@rOutDate,'')='')
		 AND (SG.OutDate<=@rInDate OR ISNULL(@rInDate,'')='')
		END
GO
PRINT N'Creating [sHostel].[pRptRoomAssetListGet]...';


GO


CREATE PROCEDURE [sHostel].[pRptRoomAssetListGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rHostelId int,
	 @rRoomId int=0
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
		
BEGIN 
	SELECT
	   --AT.Id As AssetTypeId,
        @rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
 		AT.Title AS AssetType,
        RAM.AssetTypeId AS AssetTypeId,
		RAM.AssetNumber AS AssetNumber,
        AR.RoomAssetId AS RoomAssetId,
		HM.Title AS HostelName,
		RAM.HostelId As HostelId,
		RAM.RoomId As RoomId,
		RM.Title As RoomName,
		[sHostel].[fRemainAssignRoomAssetGet](RAM.HostelId,RAM.RoomId, RAM.AssetTypeId) AS RemainAssetType
	FROM sHostel.tRoomAssetMaster RAM 
    INNER JOIN sHostel.tAssetTypeMaster AT ON AT.Id=RAM.AssetTypeId
    LEFT JOIN sHostel.tAssignRoomAsset AR ON RAM.Id=AR.RoomAssetId
    INNER JOIN sHostel.tRoomMaster RM ON Rm.Id=RAM.RoomId
    INNER JOIN sHostel.tHostelMaster HM ON HM.Id=RAM.HostelId
    
	WHERE 
	   RAM.HostelId=@rHostelId
		AND ((RAM.RoomId=@rRoomId) OR (@rRoomId=0))
		
	END
GO
PRINT N'Creating [sHostel].[pRptVisitorGatePassGet]...';


GO
CREATE PROCEDURE [sHostel].[pRptVisitorGatePassGet]


		   @rId int,
           --@rFromVisitDate datetime,
           --@rToVisitDate datetime,
           @rHostelId int
		   --@rVisitorName nvarchar(100),
		   --@rWhomToMeetSourceTypeId smallint,
		   --@rWhomToMeetSourceId bigint
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 

	
	SELECT 
			
			VG.Id,
			VG.VisitorName,
			VG.NoOfVisitor,
			VG.PurposeOfVisit,
			--ISNULL(VG.WhomToMeetName,'') AS WhomToMeetName,
			VG.InTime,
			VG.OutTime,
		    VG.VisitDate,
		    VG.VisitorPhoto, 
			HM.Title AS HostelName,
			CASE WHEN VG.WhomToMeetSourceTypeId=2003 THEN  ISNULL(SM.FirstName,'') 
			     WHEN VG.WhomToMeetSourceTypeId=95 THEN ISNULL(EM.FirstName,'')  ELSE VG.WhomToMeetName END
			       AS Name
	FROM 
			sHostel.tVisitorGatePass VG
			--Left JOIN sCommon.tSourceTypeMaster ST ON ST.Id=VG.WhomToMeetSourceTypeId
			Left JOIN sStudent.vStudentLastAcademic SM ON SM.StudentId=VG.WhomToMeetSourceId AND VG.WhomToMeetSourceTypeId=2003
			Left JOIN sHrm.tEmployeeMaster EM ON EM.Id=VG.WhomToMeetSourceId AND VG.WhomToMeetSourceTypeId=95
			Left JOIN sHostel.tHostelMaster HM ON HM.Id=VG.HostelId
	WHERE 
			((VG.Id = @rId) OR (@rId = 0))
			AND ((VG.HostelId = @rHostelId) OR (@rHostelId = 0))
		
END
GO
PRINT N'Creating [sHostel].[pStudentDetailListGet]...';


GO
CREATE PROCEDURE [sHostel].[pStudentDetailListGet]
	 
	 @rHostelId int,
	 @rSUId nvarchar(20)
	 --@rRoomId int
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	SELECT 
			O.DisplayTitle AS Organization,
			RM.Title AS Room,
			SD.Code AS StudentCode,
			SD.Name AS StudentName,
			ISNULL(RAM.AssetNumber,'') AS AssetNumber,
			ISNULL(AM.Title,'') AS AssetType,
			ISNULL(RC.Title,'') As RoomCategory,
			ARA.RoomAssetId ,
			SD.StudentId  AS SourceId,
			AR.SourceTypeId AS SourceTypeId,
			AR.RoomId,
			ISNULL(SC.PresentStreetone,'') + ' ' + ISNULL(SC.PresentStreetTwo,'') + ' ' + ISNULL(SC.PresentStreetThree,'') AS PresentAddress,
			ISNULL(SC.StudentContactNo,'') AS StudentContactNo,
			SD.ClassName + ' ' + SD.DivisionName AS Class
			
			
	FROM sStudent.vStudentLastAcademic SD   
			INNER JOIN sHostel.tAssignRoom AR ON SD.StudentId = AR.SourceId AND AR.SourceTypeId = 2003
			LEFT JOIN  sStudent.tStudentCommunication SC ON SC.StudentId=SD.StudentId
			INNER JOIN sHostel.tRoomMaster RM ON AR.RoomId = RM.Id 
			INNER JOIN sHostel.tRoomCategoryMaster RC ON RC.ID=RM.RoomCategoryId
			INNER JOIN sHostel.tHostelMaster HM ON HM.Id = RM.HostelId
			INNER JOIN sSetup.tOrganizationMaster O ON O.Id = SD.OrgId
	        LEFT JOIN sHostel.tAssignRoomAsset  ARA ON ARA.SourceId=SD.StudentId AND  ARA.SourceTypeId=2003
	        LEFT JOIN sHostel.tRoomAssetMaster RAM ON RAM.Id=ARA.RoomAssetId
            LEFT JOIN sHostel.tAssetTypeMaster  AM ON RAM.AssetTypeId=AM.Id
	WHERE 
	    HM.Id = @rHostelId
	    AND ((SD.SUID=@rSUId)OR (ISNULL(@rSUId,'')=''))
	    
END
GO
PRINT N'Creating [sHrm].[pDetailEmployeeModelGet]...';


GO
CREATE PROCEDURE [sHrm].[pDetailEmployeeModelGet]
	 
  
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 
	SELECT 
		 Em.Id,
		 Em.FirstName + ' ' + EM.LastName AS FullName,
		 Gm.Title As Gender,
		 EC.CompanyEmail As Email, 
		 EC.MobileNumber ,
		 EPD.DateOfBirth
  FROM 
		  sHrm.tEmployeeMaster EM 
		  INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId = EM.Id
		  INNER JOIN sCommon.tGenderMaster Gm ON GM.Id = EPD.Genderid
		  INNER JOIn sHrm.tEmployeeCommunications Ec ON Ec.EmployeeID = EM.Id
END
GO
PRINT N'Creating [sHrm].[pGeneralEmployeeModelGet]...';


GO
CREATE PROCEDURE [sHrm].[pGeneralEmployeeModelGet]
	  @rEmployeeId bigint=0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 
	SELECT 
		 Em.Id,
		 Em.FirstName + ' ' + EM.LastName AS FullName,
		 Gm.Title As Gender,
		 EC.CompanyEmail AS Email, 
		 EC.MobileNumber
  FROM 
		  sHrm.tEmployeeMaster EM 
		  INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId = EM.Id
		  INNER JOIN sCommon.tGenderMaster Gm ON GM.Id = EPD.Genderid
		  INNER JOIN sHrm.tEmployeeCommunications EC ON EC.EmployeeId= EM.Id
 
END
GO
PRINT N'Creating [sSetup].[pDivisionInchargeAdd]...';


GO
CREATE  PROCEDURE [sSetup].[pDivisionInchargeAdd]
	 
 
	 @rDivisionId int,
	 @rEmployeeId bigint,
	 @rBatchId int
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

	if exists(select 1 from sSetup.tDivisionInchargeEmployee where divisionid=@rdivisionid and employeeid= @rEmployeeId and batchid=@rBatchId)
	begin
		Update sSetup.tDivisionInchargeEmployee Set
			divisionid=@rdivisionid,
			employeeid= @remployeeid
		Where divisionid=@rdivisionid and employeeid= @remployeeid and batchid=@rbatchid
		select 11 as result	
	end
	Else
	begin
	
	 INSERT Into sSetup.tDivisionInchargeEmployee
	 (
		DivisionId,
		EmployeeId,
		BatchId
	 )
	 values
	 (
		@rDivisionId,
		@rEmployeeId,
		@rBatchId
	 )
	 Select 1 as result
	 end
END
GO
PRINT N'Creating [sSetup].[pDivisionInchargeGet]...';


GO
CREATE PROCEDURE [sSetup].[pDivisionInchargeGet]
	 
 
	 @rClassId int,
	  
	 @rDivisionId int,
	 @rBatchId int
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 
	SELECT 
	
			DM.Id,
			DM.Code,
			DM.Title,
			DM.DisplayTitle,
			DM.ClassId,
			CM.Title AS ClassTitle,
			DI.EmployeeId AS InchargeEmployeeId,
		    ISNULL(EM.Code,'') AS InchargeEmployeeCode,
		    ISNULL(EM.FirstName,'')+ ' ' + ISNULL(EM.MiddleName,'')+ ' ' + ISNULL(EM.LastName,'') AS InchargeEmployeeName,
		    DM.Location,
			DM.OrderIndex,
			 
			ISNULL(DM.Capacity,0) AS Capacity
      
  FROM 
            sSetup.tDivisionInchargeEmployee DI
            INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = DI.DivisionId
           INNER JOIN sSetup.tClassMaster CM ON CM.Id=DM.ClassId
		   LEFT JOIN sHrm.tEmployeeMaster EM 
				ON EM.Id = DI. EmployeeId AND EM.IsObsolete = 0
					     
		    
  WHERE 
  
      ((DI.DivisionId = @rDivisionId) OR (@rDivisionId = 0))
	AND ((DM.ClassId=@rClassId) OR (@rClassId = 0))
	 
	AND DI.BatchId= @rBatchId
	order by DM.OrderIndex asc	
END
GO
PRINT N'Creating [sSetup].[pDivisionModelGet]...';


GO
CREATE PROCEDURE [sSetup].[pDivisionModelGet]
	 
 
	 
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 
	SELECT 
		Dm.Id As DivisionId,
		Dm.Title As DivisionName,
		CM.Id as ClassId,
		Cm.Title As ClassName,
		Cm.Title As Grade
  FROM 
		   sSetup.tDivisionMaster DM
		   INNER JOIn sSetup.tClassMaster Cm ON cm.Id = Dm.ClassId
 
END
GO
PRINT N'Creating [sSetup].[pOrganizationWiseStudentDelete]...';


GO
CREATE PROCEDURE [sSetup].[pOrganizationWiseStudentDelete]
	 @rOrgId int
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN
	--BEGIN TRY
	--	BEGIN TRANSACTION SD
		
		DECLARE @lCount int
		DECLARE @lStudentId bigint
		DECLARE @lAcademicId bigint
		
		
		 
		
		Create TABLE #AcademicTable (Id int Identity, StudentId bigint,AcademicId bigint)
		INSERT INTO #AcademicTable SELECT StudentId,Id FROM sStudent.tAcademic WHERE OrgId =@rOrgId
		
		SELECT @lCount =  COUNT(Id) FROM #AcademicTable
		WHILE (@lCount > 0)
		BEGIN
			SELECT @lAcademicId = AcademicId,@lStudentId = StudentId From #AcademicTable WHERE Id = @lCount
			execute [sStudent].[pForceStudentDelete] @lAcademicId
			execute [sStudent].[pStudentDelete] @lStudentId
			SET @lCount = @lCount - 1
		END
		
	 
			
	--	COMMIT TRANSACTION	SD
	--END TRY
	
	--BEGIN CATCH 
	--	ROLLBACK TRANSACTION SD
	--END CATCH	
END
GO
PRINT N'Creating [sStudent].[pAddSiblingLink]...';


GO

CREATE PROCEDURE [sStudent].[pAddSiblingLink]	 
	    @rStudentId bigint,
	    @rLinkedStudentId bigint
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	

 BEGIN 
	IF EXISTS(SELECT LinkedStudentId FROM sStudent.tLinkSibling WHERE ((StudentId=@rStudentId) AND (LinkedStudentId = @rLinkedStudentId)))
	BEGIN
	UPDATE  sStudent.tLinkSibling
	    SET	
			StudentId=@rStudentId,
	        LinkedStudentId= @rLinkedStudentId
		   
		  
	     -- SELECT @lNextNumber AS Result
	      WHERE ((StudentId = @rStudentId) AND (LinkedStudentId = @rLinkedStudentId))
	     -- SELECT @lNextNumber AS Result
	     SELECT 2 AS Result
	END
	
	ELSE
	BEGIN
	INSERT INTO sStudent.tLinkSibling
		(
		 StudentId,
		LinkedStudentId
			
		)
	VALUES
		(
		 @rStudentId,
		 @rLinkedStudentId		 
		
		)
		    SELECT 1 AS Result

	END
	    
	 END  	

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


GO
CREATE PROCEDURE [sStudent].[pDetailStudentModelGet]
	  
	 @rClassId nvarchar(100),
	 @rDivisionId nvarchar(100),
	 @rHostelId int,  
	 @rStudentId nvarchar(100)=''
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 
	SELECT 
		Sm.Id AS StudentId,
		SM.FIrstName + ' ' + SM.LastName As FullName,
		HM.Title AS HostelName,
		CM.title+ '/' +DM.Title AS Class,
		GM.Title AS Gender,
		SF. FatherName,
		SF.FatherMail,
		SF.FatherContactNo,
		SF.MotherName,
		SF.MotherMail,
		SF.MotherContactNo,
		SC.StudentEmail,
		SC.StudentContactNo,
		SC.ParentEmail AS ContactEmail 
		
			 
  FROM 
      sStudent.tStudentMaster SM 	
	INNER JOIN sStudent.tStudentOther SO ON SO.studentid = SM.Id 
	INNER JOIN sCommon.tGenderMaster GM ON GM.ID = SO.GenderID 
	INNER JOIN sStudent.tAcademic A ON A.StudentId = Sm.Id
	INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
	INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
	INNER JOIN sStudent.tStudentFamily SF ON Sf.StudentId = Sm.Id 
	INNER JOIN sHostel.tAssignRoom AR ON AR.SourceId = SM.Id AND AR.SourceTypeId =2003
	INNER JOIN sHostel.tRoomMaster RM ON RM.Id = AR.RoomId
	INNER JOIN sHostel.tHostelMaster HM ON HM.Id = RM.HostelId
	INNER JOIN sStudent.tStudentCommunication SC on SC.Studentid = Sm.Id 
					     
		    
  WHERE 
	  ((SM.Id = [sCommon].[fnSplit](@rStudentId,',')) OR (@rStudentId=''))
	  AND ((Cm.Id =[sCommon].[fnSplit](@rClassId,',')) OR (@rClassId =''))
	 AND ((DM.Id =[sCommon].[fnSplit](@rDivisionId,',')) OR (@rDivisionId=''))
	 AND ((HM .id=@rHostelId) OR (@rHostelId =0))
END
GO
PRINT N'Creating [sStudent].[pEnrollmentStatusAdd]...';


GO

CREATE PROCEDURE [sStudent].[pEnrollmentStatusAdd]
	 		@rId bigint,
	 		@rOrgId smallint	, 
			@rAcademicId bigint,
           @rStatusDate date,
		   @rRemark nvarchar(200),
		   @rEnrollmentStatusId int,		 
		    @rCreatedUserId bigint
		    
		   
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	BEGIN TRANSACTION	
	DECLARE @lNextNumber BIGINT 
	DECLARE @lStudentStatusId INT
	DECLARE @lEnrollmentStatus nvarchar(200)
	DECLARE @lStudentId bigint
	
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sStudent.tEnrollmentStatusStudent', 0, 1, 1,@outNextNumber = @lNextNumber output
	INSERT INTO sStudent.tEnrollmentStatusStudent
			   (
			    Id,
			    AcademicId
			   ,StatusDate		
			   ,Remark 
			   ,EnrollmentStatusId
			    ,CreatedUserId
			   ,CreatedDateTime			 
			   )
		 VALUES
			   (
			   @lNextNumber,
				@rAcademicId
			   ,@rStatusDate  
			   ,@rRemark
			    ,@rEnrollmentStatusId			  
			   ,@rCreatedUserId
			   ,sCommon.fGetDate()			   
			   )
			   
			  SELECT @lStudentStatusId = StatusId,@lEnrollmentStatus = Title FROM sStudent.tEnrollmentStatusMaster WHERE Id = @rEnrollmentStatusId
			  SELECT @lStudentId = StudentId FROM sStudent.tAcademic WHERE Id = @rAcademicId
			  
			  UPDATE sStudent.tStudentMaster SET StatusId = @lStudentStatusId,UpdatedUserId =@rCreatedUserId,UpdatedDateTime = GETDATE()  WHERE Id = @lStudentId
			  if (@lStudentStatusId = 2)
			  UPDATE sStudent.tStudentAdmission SET InActiveReason = @lEnrollmentStatus + ' - ' + ISNULL(@rRemark,''),InactiveDate = @rStatusDate,UpdatedUserId =@rCreatedUserId,UpdatedDateTime = GETDATE()  WHERE studentId = @lStudentId
			  else if (@lStudentStatusId = 1)
			     UPDATE sStudent.tStudentAdmission SET InActiveReason = '',InactiveDate = null,UpdatedUserId =@rCreatedUserId,UpdatedDateTime = GETDATE()  WHERE studentId = @lStudentId
			  
			   
		    SELECT 1 AS Result
	
		
COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Creating [sStudent].[pEnrollmentStatusGet]...';


GO

CREATE PROCEDURE [sStudent].[pEnrollmentStatusGet]
	 
	 
	 @rOrgId smallint=0,
	 @rBatchId int = 0,
	 @rDepartmentId int=0,
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rAcademicId bigint=0,
	 @rStatusId int=0,
	 @rCode nvarchar(20)='',
	@rSUId nvarchar(20)='',
	@rEnrollmentStatusId int=0,
	@rFromDate date='',
	@rToDate date=''
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON		
BEGIN 	 
		
	SELECT 
			ES.CreatedDateTime,
			SA.SUId,
			SA.Code,
			SA.ClassName+'-'+SA.DivisionName AS DivDept,
			SA.RollNo,
			SA.Name,
			ES.Remark,
			EM.Title AS EnrollmentStatusName,
			SA.BatchId	,
			ES.AcademicId,
			SA.OrgId,
			SA.BatchId,
			SA.DepartmentId,
			SA.ClassId,
			SA.DivisionId,
			ES.EnrollmentStatusId
  FROM 
			sStudent.tEnrollmentStatusStudent ES
			LEFT JOIN sStudent.vStudentLastAcademic SA ON SA.AcademicId =ES.AcademicId
			LEFT JOIN  sStudent.tEnrollmentStatusMaster EM ON EM.Id=ES.EnrollmentStatusId
			--INNER JOIN sActivity.tEventAttendance EA ON  SA.AcademicId = EA.SourceId AND EA.SourceTypeId = 2001
			--INNER JOIN sActivity.tEventSchedule ES ON EA.EventScheduleId=ES.Id 
			--INNER JOIN sActivity.tEventTypeMaster EM ON EM.Id = ES.EventTypeId
  WHERE 
			((SA.ClassId=@rClassId)OR(@rClassId=0))
			AND((SA.DivisionId=@rDivisionId)OR(@rDivisionId=0))
			AND((SA.Code like @rCode) OR (ISNULL(@rCode,'') = '')) 
			AND((SA.SUId like @rSUId) OR (ISNULL(@rSUId,'') = '')) 
			AND(SA.OrgId=@rOrgId)
			AND((SA.BatchId=@rBatchId )or( @rBatchId = 0))
			AND((SA.DepartmentId=@rDepartmentId) or (@rDepartmentId = 0))
		AND((ES.EnrollmentStatusId=@rEnrollmentStatusId )or( @rEnrollmentStatusId = 0))
			AND ((ES.CreatedDateTime >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			--AND ((ES.ToDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
				AND((SA.AcademicId=@rAcademicId)OR(@rAcademicId=0)) 
			ORDER BY SA.ClassId,SA.DivisionId
END
GO
PRINT N'Creating [sStudent].[pEnrollmentStatusOrgAdd]...';


GO


CREATE PROCEDURE [sStudent].[pEnrollmentStatusOrgAdd]

	@rAssignEnrollmentStatusXml [nvarchar](max),
	@rOrgId smallint
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rAssignEnrollmentStatusXml
BEGIN 	
 
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	 
	 DELETE FROM sStudent.tEnrollmentStatusOrg
				 WHERE   OrgId=@rOrgId
	
		INSERT INTO sStudent.tEnrollmentStatusOrg
		(
			EnrollmentStatusId,
			OrgId
		)
		SELECT
		EnrollmentStatusId,
			OrgId
		FROM OPENXML (@loDoc, '/Table/AssignEnrollmentStatus', 1)
		WITH ( 
				EnrollmentStatusId int,
				OrgId Smallint
			  ) 
	--END
	SELECT 1 AS Result
	
	COMMIT TRANSACTION
	
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
END
GO
PRINT N'Creating [sStudent].[pEnrollmentStatusOrgGet]...';


GO

CREATE PROCEDURE [sStudent].[pEnrollmentStatusOrgGet]
	 
	@rEnrollmentStatusId int=0,
	@rOrgId smallint
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 
	SELECT
				EM.Title AS EnrollmentStatus,
				EM.Id AS EnrollmentStatusId,
				CASE WHEN ES.EnrollmentStatusId IS NULL THEN 'False' ELSE 'True' END AS IsObsolete,
				SM.Title AS StudentStatus
	FROM
	
			sStudent.tEnrollmentStatusMaster EM
			INNER JOIN  sStudent.tStatusMaster  SM ON SM.Id=EM.StatusId 
		    LEFT JOIN sStudent.tEnrollmentStatusOrg  ES ON ES.EnrollmentStatusId=EM.Id AND ES.OrgId=@rOrgId
		 
		
     WHERE
    EM.IsObsolete=0
	Order by EM.Id 
END
GO
PRINT N'Creating [sStudent].[pGeneralStudentModelGet]...';


GO
CREATE  PROCEDURE [sStudent].[pGeneralStudentModelGet]
	 
 
	 @rClassId nvarchar(100),
	 @rDivisionId nvarchar(100),
	 
	 @rHostelId int,
	 @rStudentId nvarchar(100) 
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 
	SELECT 
		Sm.Id AS StudentId,
		SM.FIrstName + ' ' + SM.LastName As FullName,
		RM.hostelId,
		CM.title+ '/' +DM.Title AS Class,
		GM.Title AS Gender 
			 
  FROM 
      sStudent.tStudentMaster SM 	
	INNER JOIN sStudent.tStudentOther SO ON SO.studentid = SM.Id 
	INNER JOIN sCommon.tGenderMaster GM ON GM.ID = SO.GenderID 
	INNER JOIN sStudent.tAcademic A ON A.StudentId = Sm.Id
	INNER JOIN sSetup.tClassMaster CM
		ON CM.Id=A.ClassId
	INNER JOIN sSetup.tDivisionMaster DM
		ON DM.Id=A.DivisionId
	INNER JOIN sHostel.tAssignRoom AR ON AR.SourceId = SM.Id AND AR.SourceTypeId =2003
	INNER JOIN sHostel.tRoomMaster RM ON RM.Id = AR.RoomId
					     
		    
  WHERE 
	((Cm.Id =[sCommon].[fnSplit](@rClassId,',')) OR (@rClassID=''))
	AND ((DM.Id=[sCommon].[fnSplit](@rDivisionId,',')) OR (@rDivisionID=''))
     AND RM.HostelId = @rHostelId
     ANd ((SM.Id = [sCommon].[fnSplit](@rStudentId,',')) OR (@rStudentId=''))
	 
END
GO
PRINT N'Creating [sStudent].[pRptStudentInformationFormGet]...';


GO

CREATE PROCEDURE [sStudent].[pRptStudentInformationFormGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rOrgId smallint,
	 @rBatchId int,
	 @rStrStudentId nvarchar(max),
	 @rStrCode nvarchar(max),
	 @rClassId int,
	 @rDivisionId int,
	 @rStudentId bigint,
	 @rFromRollNo int,
	 @rToRollNo int,
	 @rStatusId int,
	 @rDateOfBirth int,
	 @rDepartmentId int,
	 @rRemark nvarchar(500),
	 @rNote nvarchar(500)

	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			@rRemark AS Remark,
			@rNote AS Note,
			SA.AcademicId,
			SA.StudentId, 			
			SA.Code,						
			SA.Name,		
			SA.ClassDivision AS ClassDiv,	
			
			ISNULL(SF.FatherName,'') AS FatherName,
			ISNULL(SF.FatherContactNo,'') AS FatherContactNo,
			ISNULL(SF.MotherName,'') AS MotherName,
			ISNULL(SF.MotherContactNo,'') AS MotherContactNo,
			ISNULL(SA.Religion,'') AS Religion,
			ISNULL(SA.Gender,'') AS Gender,
			SA.DateOfBirth AS DateOfBirth,
			ISNULL(SA.BloodGroup,'') AS BloodGroup,
			ISNULL(SA.AdhaarNumber,'') AS AdhaarNumber,
			ISNULL(SC.PresentStreetone,'') + ' ' + ISNULL(SC.PresentStreetTwo,'') + ' ' + ISNULL(SC.PresentStreetThree,'') AS PresentAddress,
			
			SF.FatherIncome AS FatherIncome,
			SF.MotherIncome AS MotherIncome,
			SD.BankAccountNumber AS BankAccountNo,
			SD.BankName AS BankName,
			SD.BankAccountNumber AS BranchName,
			SD.BankIFSCCode AS BankIFSCCode,
			CM.Id AS CategoryId,
			CM.Title AS Category,
			SO.FamilyCast AS Cast,
			 CASE WHEN EXISTS (SELECT StudentId FROM sStudent.tStudentSibling AS SS WHERE SS.StudentId = SA.StudentId)
				THEN 'No' 
					ELSE 'Yes'
				 END AS OnlyOneChild
			
	FROM 
		 	 sStudent.vStudentAllDetail SA
		 	 LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=SA.StudentId
		 	 LEFT JOIN sCommon.tCastCategoryMaster CM ON CM.Id=SO.CastCategoryId
		 	  LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
		 	  LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SA.StudentId 
		 	  LEFT JOIN sStudent.tStudentAdditional SD ON SD.StudentId=SA.StudentId 
		 	
	WHERE 
			SA.OrgId=@rOrgId
		AND	SA.BatchId = @rBatchId
		AND (ISNULL(SA.StudentId,0) NOT IN( SELECT cast(item as bigint) FROM  sCommon.fnsplit(@rStrStudentId,',')) OR @rStrStudentId='') 
		AND (ISNULL(SA.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rStrCode,',')) OR @rStrCode='') 
		AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((SA.StudentId=@rStudentId) OR (@rStudentId=0))
		AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((SA.StatusId=@rStatusId)OR(@rStatusId=0))
		AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
END
GO
PRINT N'Creating [sStudent].[pRptStudentWithoutHostelTransportGet]...';


GO

CREATE PROCEDURE [sStudent].[pRptStudentWithoutHostelTransportGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rOrgId smallint,
	 @rBatchId int,
	 @rStrStudentId nvarchar(max),
	 @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,
			SA.AcademicId,
			SA.StudentId, 
			SA.ClassId,
			SA.DivisionId,
			SA.Code,
			SA.RollNo AS RollNo,			
			SA.FirstName,			
			SA.LastName,
			SA.Name,		
			SA.ClassName,
			SA.DivisionName,
			SA.StatusName,
			SA.DivisionOrder,
			SA.Number AS StudentNumber
      
	FROM  sStudent.vStudentLastAcademic SA
			WHERE 
			SA.OrgId=@rOrgId
		AND	SA.BatchId = @rBatchId
		AND (ISNULL(SA.StudentId,0) NOT IN( SELECT cast(item as bigint) FROM  sCommon.fnsplit(@rStrStudentId,',')) OR @rStrStudentId='') 
		AND (ISNULL(SA.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rStrCode,',')) OR @rStrCode='') 
		AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((SA.StudentId=@rStudentId) OR (@rStudentId=0))
		AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((SA.StatusId=@rStatusId)OR(@rStatusId=0))
		AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		
		 EXCEPT
		SELECT
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			SA.AcademicId,
			SA.StudentId, 
			SA.ClassId,
			SA.DivisionId,
			SA.Code,
			SA.RollNo AS RollNo,			
			SA.FirstName,			
			SA.LastName,
			SA.Name,		
			SA.ClassName,
			SA.DivisionName,
			SA.StatusName,
			SA.DivisionOrder,
			SA.Number AS StudentNumber
			 FROM sHostel.tAssignRoom AR  INNER JOIN sStudent.vStudentLastAcademic SA ON  SA.StudentId=AR.SourceId  WHERE  AR.SourceTypeId = 2003
			  
	   
		
			
			EXCEPT
	  SELECT
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			SA.AcademicId,
			SA.StudentId, 
			SA.ClassId,
			SA.DivisionId,
			SA.Code,
			SA.RollNo AS RollNo,			
			SA.FirstName,			
			SA.LastName,
			SA.Name,		
			SA.ClassName,
			SA.DivisionName,
			SA.StatusName,
			SA.DivisionOrder,
			SA.Number AS StudentNumber
			 FROM sTransport.tAssignRoute  TA INNER JOIN sStudent.vStudentLastAcademic SA ON  SA.StudentId=TA.SourceId  WHERE  TA.SourceTypeId = 2003
			
END
GO
PRINT N'Creating [sStudent].[pSiblingLinkListGet]...';


GO

CREATE PROCEDURE [sStudent].[pSiblingLinkListGet]	
	@rOrgId int,	
	@rStudentId bigint
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON			 
BEGIN 	 		
	SELECT 
			SA.Name,
			SA.Code,		
			SA.ClassName+'-'+SA.DivisionName AS DivDept	,
			LS.LinkedStudentId		
  FROM sStudent.tLinkSibling LS
		left JOIN	sStudent.vStudentLastAcademic SA ON SA.StudentId=LS.LinkedStudentId
			--INNER JOIN sActivity.tEventAttendance EA ON  SA.AcademicId = EA.SourceId AND EA.SourceTypeId = 2001
			--INNER JOIN sActivity.tEventSchedule ES ON EA.EventScheduleId=ES.Id 
			--INNER JOIN sActivity.tEventTypeMaster EM ON EM.Id = ES.EventTypeId
  WHERE 
			((LS.StudentId like @rStudentId) OR (ISNULL(@rStudentId,0) = 0)) 
	
			AND(SA.OrgId=@rOrgId)
			
			ORDER BY SA.Code
END
GO
PRINT N'Creating [sSystem].[pExceptionLogAdd]...';


GO

CREATE PROCEDURE [sSystem].[pExceptionLogAdd]
	    
	    @rExceptionDetail	nvarchar(MAX)='',
	 	@rOrgGroupId int,
	 	@rOrgId int,
	 	@rCreatedUserId bigint, 
	 	@rMachineName nvarchar(200) = '',
	 	@rAppDomainName nvarchar(200) = '',
	 	@rExceptionType	nvarchar(1000)='',
		@rExceptionMessage	nvarchar(MAX)='',
		@rExceptionSource	nvarchar(MAX)='',
		@rExceptionStackTrace	nvarchar(MAX),
		@rInnerExceptionType	nvarchar(1000) = '',
		@rInnerExceptionMessage	nvarchar(MAX)='',
		@rInnerExceptionSource	nvarchar(MAX)='',
		@rInnerExceptionStackTrace	nvarchar(MAX)=''
			 

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
 

	INSERT INTO [sSystem].[tExceptionLog]
		(
		ExceptionDetail,
		OrgGroupId, 		 
		CreatedUserId,
		MachineName,
	 	AppDomainName,
		CreatedDateTime,
		ExceptionType,
		ExceptionMessage,
		ExceptionSource,
		ExceptionStackTrace,
		InnerExceptionType,
		InnerExceptionMessage,
		InnerExceptionSource,
		InnerExceptionStackTrace
		)
	VALUES
		(
		@rExceptionDetail,
		@rOrgGroupId,			 		 
		@rCreatedUserId,
		@rMachineName,
		@rAppDomainName,			
		sCommon.fGetDate(),
		@rExceptionType,
		@rExceptionMessage,
		@rExceptionSource,
		@rExceptionStackTrace,
		@rInnerExceptionType,
		@rInnerExceptionMessage,
		@rInnerExceptionSource,
		@rInnerExceptionStackTrace	
		)
		  
	END
GO
PRINT N'Creating [sSystem].[pExceptionLogGet]...';


GO
CREATE PROCEDURE [sSystem].[pExceptionLogGet]

	@rOrgGroupId int,
	@rFromDate date,
	@rToDate date
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
SET @rToDate = DATEADD(day,1,@rToDate)
       SELECT 
       
         EL.Id AS ExceptionId,
         EL.ExceptionType AS ExceptionType,
         EL.ExceptionDetail AS ExceptionDetail,
         EL.CreatedDateTime AS CreateUpdateTime
			
       FROM        
       sSystem.tExceptionLog EL
    --   INNER JOIN sSecurity.tUser U ON U.Id = AL.UserId
	   --INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = AL.OrgId
	   --INNER JOIN sSecurity.tScreen S ON S.Id = AL.ScreenId
          
       WHERE       
       ((EL.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))
      
       AND (EL.CreatedDateTime >= @rFromDate)
	   AND (EL.CreatedDateTime <= @rToDate)
       ORDER BY EL.CreatedDateTime DESC
		
END
GO

 
ALTER PROCEDURE [sFee].[pAllocatedFeeGet]
	 
		@rOrgId int,
		@rBatchId int,
		@rAdmissionCategoryId int,
		@rClassId int,
		@rDivisionId int,
		@rFeeHeadId int,
		@rFeeId int,
		@rOrgGroupBatchId int,
		@rDepartmentId int=0,
		@rExemptionTypeId int=0
		
		
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 	

	SELECT 
			SA.AcademicId AS SourceId,
			SA.Name,
			SA.Code,
			SA.RollNo,
			SA.ClassId,
			SA.DivisionId,
			SA.OrgId,
			SA.ClassName+' - '+SA.DivisionName AS ClassName,
			FS.Id AS FeeSetupId,
			ISNULL(FS.IsOptional,0)AS IsOptional,
			ISNULL(FS.IsVariable,0)AS IsVariable,
			ISNULL(FS.Amount,0)AS Amount,
			ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
			ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
			ISNULL(FA.VariableAmount,0.00)AS FAAmount,
			ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
			ISNULL(FA.NotApplicableAmount,0.00)AS NotApplicableAmount,
			ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
			ISNULL(R.PaidAmount,0) AS PaidAmount,
			ISNULL(FS.Amount,0.00) + ISNULL(FA.VariableAmount,0.00) + ISNULL(FA.AdditionalAmount,0.00) - ISNULL(FA.DiscountAmount,0.00) - ISNULL(FA.NotApplicableAmount,0.00) - ISNULL(R.PaidAmount,0.00) AS PendingAmount,
			ISNULL(FA.Remark,'') AS Remark,
			FM.Title AS FeeName,
			FS.AdmissionCategoryId,
			ISNULL(EM.Title,'') AS ExemptionFeeType
			
	FROM 
			sStudent.vStudentAcademic SA
			INNER JOIN sSetup.tClassMaster CM ON CM.Id = SA.ClassId 
			INNER JOIN sFee.tFeeSetup FS ON FS.ClassId=SA.ClassId AND FS.AdmissionCategoryId = SA.AdmissionCategoryId AND FS.BatchId = SA.BatchId
			INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
			INNER JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId = SA.AcademicId
			LEFT JOIN  sFee.tExemptionTypeMaster EM ON EM.Id = SA.ExemptionTypeId
			LEFT JOIN
			(
				SELECT 
						ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
				FROM
					sFee.tReceipt R 
					INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
					INNER JOIN sFee.tFeeSetup FS ON FS.Id = RD.FeeSetupId
					INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId AND R.SourceTypeId = 2001				
					AND (SA1.ClassId=@rClassId OR @rClassId=0) AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
				WHERE			 		
					(R.IsObsolete = 0) 
					AND ((R.BatchId = @rBatchId) OR (@rBatchId=0))
				GROUP BY FeeSetupId,R.SourceId
			) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId 
	WHERE 
				SA.OrgGroupBatchId = @rOrgGroupBatchId
				AND ((SA.OrgId = @rOrgId) OR (@rOrgId=0))
				AND ((SA.BatchId = @rBatchId) OR (@rBatchId=0))
				AND ((SA.AdmissionCategoryId = @rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((SA.ClassId = @rClassId) OR (@rClassId=0))
				AND ((SA.DivisionId = @rDivisionId) OR (@rDivisionId=0))
				AND ((FM.FeeHeadId = @rFeeHeadId) OR (@rFeeHeadId=0))
				AND ((FS.FeeId = @rFeeId) OR (@rFeeId=0))
				AND ((CM.DepartmentId=@rDepartmentId) OR (@rDepartmentId =0))
				AND ((SA.ExemptionTypeId =@rExemptionTypeId) OR (@rExemptionTypeId=0))
	ORDER BY SA.DivisionOrder,SA.RollNo
END

GO


ALTER PROCEDURE [sFee].[pFeeAllocationClassGet]
	 
		@rFeeSetupId int,
		@rDivisionId int,
		@rClassId int,
		@rAdmissionCategoryId int,
		@rExemptionTypeId int=0
		
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 	

DECLARE @rBatchId int

SELECT @rBatchId = BatchId FROM sFee.tFeeSetup WHERE id = @rFeeSetupId	
	
	SELECT 
			SA.AcademicId AS SourceId,
			SA.Name,
			SA.Code,
			SA.RollNo,
			FS.Id AS FeeSetupId,
			ISNULL(FS.IsOptional,0)AS IsOptional,
			ISNULL(FS.IsVariable,0)AS IsVariable,
			ISNULL(FS.Amount,0)AS Amount,
			ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
			ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
			ISNULL(FA.VariableAmount,0.00)AS FAAmount,
			ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
			ISNULL(FA.NotApplicableAmount,0.00)AS NotApplicableAmount,
			ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
			ISNULL(R.PaidAmount,0) AS PaidAmount,
			ISNULL(FS.Amount,0.00) + ISNULL(FA.VariableAmount,0.00) + ISNULL(FA.AdditionalAmount,0.00) - ISNULL(FA.DiscountAmount,0.00) - ISNULL(FA.NotApplicableAmount,0.00) - ISNULL(R.PaidAmount,0.00) AS PendingAmount,
			ISNULL(FA.Remark,'') AS Remark,
			ISNULL(EM.Title,'') AS ExemptionFeeType
			
	  FROM 
			 sStudent.vStudentAcademic SA
			 
		INNER JOIN 
		(
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId
			FROM sFee.tFeeSetup FS1
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId
				WHERE FS1.ClassId=@rClassId AND 
				FS1.AdmissionCategoryId=@rAdmissionCategoryId AND 
				FS1.Id=@rFeeSetupId AND IsOptional=0 AND
				SA1.BatchId = @rBatchId AND
				FS1.BatchId = @rBatchId
				
				UNION ALL
				
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId
			FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO
			ON FO.FeeSetupId=FS1.Id
		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND 
		SA1.ClassId=@rClassId  AND SA1.AdmissionCategoryId=@rAdmissionCategoryId AND SA1.BatchId = @rBatchId
		
		WHERE
		 FS1.Id=@rFeeSetupId AND
		 FS1.ClassId=@rClassId AND FS1.AdmissionCategoryId=@rAdmissionCategoryId 
		 AND IsOptional=1
		 AND FS1.BatchId = @rBatchId
		 
				
		) FS ON FS.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tExemptionTypeMaster EM ON EM.Id = SA.ExemptionTypeId
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
		LEFT JOIN
		(
		    SELECT 
					ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
		    FROM
				sFee.tReceipt R 
				INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId AND R.SourceTypeId = 2001				
				AND (SA1.ClassId=@rClassId OR @rClassId=0) AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
			WHERE			 		
				 (R.IsObsolete = 0) 
				AND RD.FeeSetupId = @rFeeSetupId
				AND (R.BatchId = @rBatchId) 
					GROUP BY FeeSetupId,R.SourceId
		
		) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId 
		--AND SA.StatusId=1	
		WHERE
				(SA.ClassId=@rClassId)
			AND (SA.DivisionId=@rDivisionId)
			AND (SA.AdmissionCategoryId=@rAdmissionCategoryId)
			AND (FS.Id=@rFeeSetupId)	
			AND SA.BatchId = @rBatchId
			AND ((SA.ExemptionTypeId =@rExemptionTypeId) OR (@rExemptionTypeId=0))
ORDER BY SA.RollNo
	
END
GO
ALTER PROCEDURE [sStudent].[pRptCountCategorywiseStudentGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rOrgId smallint,
	 @rBatchId int,
	 @rClassId int,
	 @rDivisionId int,
	 @rAsOnDate date,
	 @rReportId int,
	 @rDepartmentId int,
	 @rStudentCode varchar(20),
	 @rCasteCategoryIds nvarchar(max) = '',
	 @rReligionIds nvarchar(max) = '',
	 @rGenderIds nvarchar(max) = '',
	 @rAdmissionCatgoryIds nvarchar(max) = '',
	 @rClassGroup bit=0,
	 @rDivisionGroup bit=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
  
	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			CM.DisplayTitle AS Class,
			DM.DisplayTitle AS Division,
			ISNULL(GM.Title,'') As Gender,
			A.ClassId,
			A.DivisionId,
			A.Id AS AcademicId,
			A.RollNo,
			SO.DateOfBirth,
			CM.DisplayTitle+' '+DM.DisplayTitle AS ClassDivision,
			SM.FirstName +' '+ SM.MiddleName +' '+ SM.LastName AS Name,
			SM.Code,
			CASE WHEN  @rReportId=10135 OR @rReportId=20702-- Caste Category
			THEN ISNULL(CCM.Title,'') 
		    WHEN  @rReportId=10136 OR @rReportId=20703 -- Religion
			THEN ISNULL(RM.Title,'') 
			WHEN  @rReportId=20704 -- Gender
			THEN ISNULL(GM.Title,'') 
			WHEN @rReportId=20328 OR @rReportId=20705 -- Admission Catgory 
			THEN ISNULL(SCM.Title,'')
			WHEN  @rReportId=10152 -- BloodGroupwise Summary
			THEN ISNULL(BGM.Title,'') 
			WHEN  @rReportId=20329 OR @rReportId=20706--Agegroupwise
			THEN  ([sStudent].[fStudentAgeGroupGet](SO.DateOfBirth,@rAsOnDate,@rOrgId))
			--WHEN  @rReportId=20426 OR @rReportId=20707  --Age wise
			--THEN  ([sStudent].[fStudentAgeGet](SO.DateOfBirth,@rAsOnDate,@rOrgId) + ' Y')
			WHEN    @rReportId = 20866 OR @rReportId=20426 OR @rReportId=20707
			
			THEN RIGHT('00'+ CAST([sStudent].[fStudentAgeGet](SO.DateOfBirth,@rAsOnDate,@rOrgId) AS VARCHAR(2)), 2)
			
			END AS Head,
			DM.OrderIndex AS DivisionOrder,
			@rClassGroup As ClassGroup,
			@rDivisionGroup As DivisionGroup
			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
		
	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 (ISNULL(CCM.Id,0) IN(SELECT cast(item as int) FROM  sCommon.fnsplit(@rCasteCategoryIds,','))OR @rCasteCategoryIds='')
	    AND (ISNULL(RM.Id,0) IN(SELECT cast(item as int) FROM  sCommon.fnsplit(@rReligionIds,','))OR @rReligionIds='')
	    AND (ISNULL(GM.Id,0) IN(SELECT cast(item as int) FROM  sCommon.fnsplit(@rGenderIds,','))OR @rGenderIds='')
	    AND (ISNULL(SCM.Id,0) IN(SELECT cast(item as int) FROM  sCommon.fnsplit(@rAdmissionCatgoryIds,','))OR @rAdmissionCatgoryIds='')
	    
END
GO
 
 
ALTER PROCEDURE [sFee].[pFeeVariableAdd]
	@rOrgId int,
	@rBatchId int,
	@rClassId int,
	@rDivisionId int,
	@rDepartmentId int,	
	@rExemptionTypeId int,
	@rAdmissionCategoryId int,
	@rFeeId int,
	@rVariableAmount decimal(12,2),
	 
	@rCreatedUserId bigint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN


IF NOT EXISTS(SELECT 1 FROM sFee.tFeeSetup WHERE BatchId = @rBatchId AND AdmissionCategoryId =  @rAdmissionCategoryId AND FeeId = @rFeeId AND IsVariable = 1 AND (ClassId =@rClassId OR @rClassId = 0)  )
BEGIN
SELECT -101 AS  Result -- Fee must be marked as variable in fee setup
RETURN
END


INSERT INTO sFee.tFeeAllocation
		(
			SourceTypeId,
			SourceId,
			FeeSetupId,
			VariableAmount,
			DiscountAmount,
			NotApplicableAmount,
			AdditionalAmount,
			Remark,
			CreatedUserId,
			CreatedDateTime
		)
				
		SELECT
		2001,
		A.Id,
		(SELECT Id FROM sFee.tFeeSetup FS WHERE FS.ClassId = A.ClassId AND FS.BatchId = @rBatchId AND FS.FeeId = @rFeeId AND FS.AdmissionCategoryId = @rAdmissionCategoryId AND IsVariable = 1) AS FeeSetupId,
		@rVariableAmount,
		0,
		0,
		0,
		'',
		@rCreatedUserId,
		GETDATE()
		FROM sStudent.tAcademic A
		INNER JOIN sStudent.tStudentMaster SM ON A.StudentId = SM.Id
		INNER JOIN sSetup.tClassMaster CM ON A.ClassId = CM.Id
		LEFT JOIN (SELECT SourceId FROM  sFee.tFeeAllocation FA 
		INNER JOIN sStudent.tAcademic AC ON FA.SourceId = AC.Id
		INNER JOIN sFee.tFeeSetup FS ON FA.FeeSetupId = FS.Id
		AND FS.BatchId = @rBatchId AND FS.FeeId = @rFeeId 
		AND FS.AdmissionCategoryId = @rAdmissionCategoryId
		AND FS.IsVariable = 1
		AND ((AC.ClassId=@rClassId) OR (@rClassId=0))
		AND ((AC.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((AC.ExemptionTypeId=@rExemptionTypeId) OR (@rExemptionTypeId=0))
		 WHERE AC.BatchId = @rBatchId  
		 )AL ON AL.SourceId = A.Id 
		
		
        WHERE  
			 AL.SourceId IS NULL
  			AND ((A.BatchId=@rBatchId) OR (@rBatchId=0))			 
			--AND (SA.StatusId = @rStatusId OR @rStatusId=0)			 
			AND ((CM.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
			AND ((A.ClassId=@rClassId) OR (@rClassId=0))
			AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			AND ((A.ExemptionTypeId=@rExemptionTypeId) OR (@rExemptionTypeId=0))
			AND ((SM.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))

   SELECT 1 AS Result 
	
 --  
		
END
GO
ALTER PROCEDURE [sAttendance].[pRptDailyAttendanceList]
	
		@rBuilder1 nvarchar(max)='',
		@rBuilder2 nvarchar(max)='', 
		 @rBatchId int,
		@rClassId int,
		@rDivisionId int,
		@rDepartmentId int ,
		--@rOrgMainGroupId int,
		--@rOrgSubGroupId int,
		 @rOrgId smallint,
		 @rAttendanceTypeId int,
		 @rDate date,
		 
		 @rDivisionGroup bit=0
		--@rOrgGroupBatchId int,
		--@rFromDate Date,
		--@rToDate Date 
		--@rStrOrgMainGroupId nvarchar(max),
		--@rStrOrgSubGroupId nvarchar(max),
		--@rStrOrgId nvarchar(max),
		--@rStrDepartmentId nvarchar(max),
		--@rStrClassId nvarchar(max),
		--@rIsTestMainGroup bit =0,
		--@rIsTestSubGroup bit =0,
		--@rIsTestOrg bit=0,
		--@rIsTestClass bit=0,
		--@rIsTestDepartment bit=0,
		--@rOrgGroupId int,
		--@rIsDisplayOrgGroup bit=0
		
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	SELECT 
			 
			@rDivisionGroup AS DivisionGroup,
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2, 
			CM.Id AS ClassId,
			CM.DisplayTitle AS ClassName,
			CM.OrderIndex  ,
			DM.Id AS DivisionId,
			DM.Title AS DivisionName,
			DM.OrderIndex AS DivisionOrderIndex,
			
		 --   (select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			--ON SA.StudentId = A.StudentId INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
			--WHERE BM.IsActive = 1 AND  SA.AdmissionDate= Convert(DATE,GETDATE()-1)
			--AND A.ClassId =CM.Id AND A.DivisionId = DM.Id  ) AS OpeningStrength,
			
		   (select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
			WHERE BM.IsActive = 1 AND SA.AdmissionDate = @rDate 
			AND A.ClassId =CM.Id AND A.DivisionId = DM.Id AND A.OrgId = @rOrgId  ) AS NewJoinedStudent,
			
		   (select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			 ON SA.StudentId = A.StudentId INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
			 WHERE BM.IsActive = 1 AND SA.LeftDate = @rDate 
			 AND A.ClassId =CM.Id AND A.DivisionId = DM.Id AND A.OrgId = @rOrgId ) AS LeftStudent,
			 
		   (select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId 
			INNER JOIN sStudent.tStudentMaster SM ON SA.StudentId = SM.Id
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
			WHERE BM.IsActive = 1 AND SM.StatusId = 1
			AND A.ClassId =CM.Id AND A.DivisionId = DM.Id AND A.OrgId = @rOrgId ) AS ClosingStrength,
			
			
			(SELECT COUNT(A.Id) FROM sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentAdmission SA  ON SA.StudentId = A.StudentId
			WHERE 
			 SA.AdmissionDate < @rDate
			 AND  ((SA.LeftDate >= @rDate) OR ISNULL(SA.LeftDate,'')= '')
			AND A.ClassId =CM.Id AND A.DivisionId=DM.Id  
			AND CM.DepartmentId = Dept.Id AND A.BatchId = @rBatchId AND A.DivisionId = DM.Id AND A.OrgId = @rOrgId ) AS PreviousDay,
			
			
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate=@rDate
	        AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id  AND  CM.DepartmentId =Dept.Id 
			AND SR.AttendanceTypeId =@rAttendanceTypeId AND SR.IsPresent =1 AND A.OrgId = @rOrgId ) AS Present,
			
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate=@rDate
	        AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id  AND  CM.DepartmentId =Dept.Id 
			AND SR.AttendanceTypeId =@rAttendanceTypeId AND SR.IsPresent =0 AND A.OrgId = @rOrgId ) AS AbsentStudent,
			
			0 as WithLeave,
			0 as SeekLeave,
			 0 AS TotalStudent,
			 '' AS Remark 
	FROM 
			sSetup.tDivisionMaster DM  
			 
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=DM.ClassId
			INNER JOIN sSetup.tDepartmentMaster Dept ON Dept.Id=CM.DepartmentId 
			 
			--AND DM.Id=A.DivisionId AND CM.Id=A.ClassId
			--sSetup.tClassMaster CM			
			 
			--INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=CM.DepartmentId
			--INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = DM.OrgId
		 
	WHERE 
		  DM.OrgId=@rOrgId
	 
		AND ((DM.ClassId=@rClassId) OR (@rClassId=0))
		AND ((DM.Id=@rDivisionId) OR (@rDivisionId=0))
		AND ((Dept.Id=@rDepartmentId) OR (@rDepartmentId=0))
		
		  -- ((CM.Id=@rClassId) OR (@rClassId=0))
			 --AND	((CM.DepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))
		 
			 
			ORDER BY CM.OrderIndex ASC
END
GO

ALTER PROCEDURE [sAttendance].[pRptMonthlyStrengthAttendanceSummary]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rOrgId smallint,
	 @rBatchId int,
	 @rClassId int,
	 @rDivisionId int,
	 --@rFromDate date='',
	 --@rToDate date='', 
	 @rDepartmentId int,
	 
	 @rOrgGroupBatchId int,
	 
	 @rAttendanceTypeId smallint=0,
	 @rYear int=0,
	 @rMonth int=0,
	 @rDivisionGroup bit=0
	
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

	 DECLARE @lFirstDate Date
	SET @lFirstDate = CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+ '/'+CONVERT(NVARCHAR(2),@rMonth)+'/01'))
	 
	  
	SELECT 
			@rDivisionGroup  AS DivisionGroup,
			  Dept.Id AS DepartmentId,
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			 
			(
			SELECT COUNT(A.Id) FROM sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentAdmission SA  ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
			INNER JOIN sCommon.tGenderMaster GM ON GM.Id=SO.GenderId
			
            INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId 			 
			WHERE 
			BM.OrgGroupBatchId = @rOrgGroupBatchId AND
			Year(SA.AdmissionDate) = @rYear 
			AND Month(SA.AdmissionDate) = @rMonth 
			AND A.ClassId =CM.Id AND A.DivisionId=DM.Id AND GM.Id=2 
			AND CM.DepartmentId = Dept.Id AND A.BatchId = @rBatchId 
			)AS NewGirls,
			
		 
			
						(
			SELECT COUNT(A.Id) FROM sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentAdmission SA  ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=SA.StudentId 
			INNER JOIN sCommon.tGenderMaster GM ON GM.Id=SO.GenderId			 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId 			 
			WHERE 
			BM.OrgGroupBatchId = @rOrgGroupBatchId AND
				Year(SA.AdmissionDate) = @rYear 
			AND Month(SA.AdmissionDate) = @rMonth 
			AND A.ClassId =CM.Id AND A.DivisionId=DM.Id AND GM.Id=1 
			AND CM.DepartmentId=Dept.Id	AND A.BatchId = @rBatchId 
			) AS NewBoys,
			 
	
				(
			SELECT COUNT(A.Id) FROM sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentAdmission SA  ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=SA.StudentId 
			INNER JOIN sCommon.tGenderMaster GM ON GM.Id=SO.GenderId 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId 			 
			WHERE 
			BM.OrgGroupBatchId = @rOrgGroupBatchId AND
				Year(SA.LeftDate) = @rYear 
			AND Month(SA.LeftDate) = @rMonth 
			 
			AND A.ClassId =CM.Id AND A.DivisionId=DM.Id AND GM.Id=2 
			AND CM.DepartmentId=Dept.Id AND A.BatchId = @rBatchId 
			) AS LeftGirls,
			
			 
	
				(
			SELECT COUNT(A.Id) FROM sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentAdmission SA  ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=SA.StudentId 
			INNER JOIN sCommon.tGenderMaster GM ON GM.Id=SO.GenderId 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId 			 
			WHERE 
			BM.OrgGroupBatchId = @rOrgGroupBatchId AND 
			Year(SA.LeftDate) = @rYear 
			AND Month(SA.LeftDate) = @rMonth 
			AND A.ClassId =CM.Id AND A.DivisionId=DM.Id AND GM.Id=1 
			AND CM.DepartmentId=Dept.Id AND A.BatchId = @rBatchId 
			) AS LeftBoys,		
		  
			
		 (
			select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND ((YEAR(SR.AttendanceDate)=@rYear) OR (@rYear= 0))
	        AND ((MONTH(SR.AttendanceDate)=@rMonth) OR (@rMonth= 0))
	        AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id 
			) AS TotalGirls,
 
			(
				select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND ((YEAR(SR.AttendanceDate)=@rYear) OR (@rYear= 0))
	        AND ((MONTH(SR.AttendanceDate)=@rMonth) OR (@rMonth= 0))
	        AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id  
			) AS TotalBoys,	
			
			
			Dept.Title AS DepartmentName,
			CM.Id AS ClassId,
			CM.Title AS ClassName,
			DM.Id AS DivId,
			DM.Title AS DivisionName, 
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			 
	        WHERE A.BatchId = @rBatchId  
	        AND ((YEAR(SR.AttendanceDate)=@rYear) OR (@rYear= 0))
	        AND ((MONTH(SR.AttendanceDate)=@rMonth) OR (@rMonth= 0))
	        AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id   AND CM.DepartmentId = Dept.Id AND SR.AttendanceTypeId =1 AND SR.IsPresent =1) AS TotalPresent,
			
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			 
	        WHERE A.BatchId = @rBatchId  
	        AND ((YEAR(SR.AttendanceDate)=@rYear) OR (@rYear= 0))
	        AND ((MONTH(SR.AttendanceDate)=@rMonth) OR (@rMonth= 0))
	        AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id   AND CM.DepartmentId = Dept.Id AND SR.AttendanceTypeId =1 AND SR.ISPresent =0) AS TotalAbsent,
			
			(SELECT COUNT(A.Id) FROM sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentAdmission SA  ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=SA.StudentId
			INNER JOIN sCommon.tGenderMaster GM ON GM.Id=SO.GenderId 

			WHERE 
				
			 (( SA.AdmissionDate < @lFirstDate) OR (ISNULL(SA.AdmissionDate,'')= ''))
			AND A.ClassId =CM.Id AND A.DivisionId=DM.Id  
			AND CM.DepartmentId = Dept.Id AND A.BatchId = @rBatchId AND A.DivisionId = DM.Id  AND GM.Id=1 ) AS PreviousBoys,
			
			(SELECT COUNT(A.Id) FROM sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentAdmission SA  ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=SA.StudentId
			INNER JOIN sCommon.tGenderMaster GM ON GM.Id=SO.GenderId 
			WHERE 
				 ((SA.AdmissionDate< @lFirstDate) OR (ISNULL(SA.AdmissionDate,'')= ''))
			AND A.ClassId =CM.Id AND A.DivisionId=DM.Id  
			AND CM.DepartmentId = Dept.Id AND A.BatchId = @rBatchId AND A.DivisionId = DM.Id  AND GM.Id=2 ) AS PreviousGirls,
			
			(select WorkingDays FROM sAttendance.tMonthlySetup
			 
	        WHERE  BatchId = @rBatchId  
	        AND ((ForMonth=@rMonth) OR (@rMonth= 0))
	        AND (( ForYEAR=@rYear) OR (@rYear= 0))
	        AND ClassId =CM.Id )as WorkingDays 
			 
			FROM 
			
			 
			sSetup.tDivisionMaster DM  
		 
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=DM.ClassId
			INNER JOIN sSetup.tDepartmentMaster Dept ON Dept.Id=CM.DepartmentId 
			 
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = DM.OrgId
			INNER JOIN sSetup.tBatchClass BC ON BC.ClassId = CM.Id
			INNER JOIN sSetup.tBatchMaster BM ON BC.BatchId = BM.Id
			
			
			 
			
	WHERE 
		 DM.OrgId=@rOrgId
		 
		
		AND ((DM.ClassId=@rClassId) OR (@rClassId=0))
		AND ((DM.Id=@rDivisionId) OR (@rDivisionId=0))
		AND ((Dept.Id=@rDepartmentId) OR (@rDepartmentId=0))
		AND	BM.OrgGroupBatchId = @rOrgGroupBatchId 
		
	
END
GO

ALTER PROCEDURE [sAssessment].[pMarkEntryDetailAdd]
	 
	        @rId bigint
           ,@rResultId bigint
		   ,@rExamDetailId int
		   ,@rObtain Decimal(6,2)
		   ,@rIsPresent bit
		   ,@rExamId int
		   ,@rAcademicId bigint
		   ,@rOrgId int
		  	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 
	 DECLARE @lMarkInDecimal bit
	 DECLARE @lClassId int
	 DECLARE @lDecimalPlace nvarchar(10)

Select @lMarkInDecimal=IsMarksInDecimal,@lClassId = ClassId,@lDecimalPlace=DecimalFormat from sAssessment.tExamMaster Where Id = @rExamId
	 
--Select @lMarkInDecimal=IsMarksInDecimal from sAssessment.tExamMaster Where Id = @rExamId And ClassId IN (SELECT ClassId FROM sStudent.tAcademic WHERE ID=@rAcademicId)
--Select @lClassId = ClassId From sAssessment.tExamMaster Where Id=@rExamId

IF @lMarkInDecimal = 1 AND @lDecimalPlace='0.0'
	BEGIN
		SET @rObtain = ROUND(@rObtain,1)
		
	END
ELSE if @lMarkInDecimal = 1 AND @lDecimalPlace='0.00'
	BEGIN	 
			SET @rObtain =round(@rObtain,2)
		END	
ELSE
	BEGIN
		SET @rObtain =ROUND(@rObtain,0)
		END		
	
		
If NOT EXISTS (SELECT 1 FROM sAssessment.tExamDetail Where Id= @rExamDetailId And   ClassSubjectId in 
				(Select cs.Id from sSetup.tClassSubject CS 
					Left join sAssessment.tOptionalSubject O ON o.ClassSubjectId=cs.Id 
					AND O.AcademicId=@rAcademicId
					WHERE (CS.ClassId =@lClassId AND IsOptional = 0) OR (IsOptional = 1 AND AcademicId IS NOt Null))
					)
BEGIN
	SELECT 1 as Result
END

ELSE IF NOT EXISTS(SELECT Id From sAssessment.tResultDetail Where ResultId IN (SELECT ID from sAssessment.tResult Where AcademicId=@rAcademicId AND ExamId=@rExamId) AND ExamDetailId=@rExamDetailId)	
BEGIN

	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAssessment.tResultDetail', 0, 1, 1,@outNextNumber = @lNextNumber output	
	 
	INSERT INTO [sAssessment].[tResultDetail]
			   (
			    [Id]
			   ,[ResultId] 
			   ,[ExamDetailId]
			   ,[Obtain]
			   ,[IsPresent]
			   )
		 VALUES
			   (
				@lNextNumber
			   ,@rResultId
			   ,@rExamDetailId
			   ,@rObtain
			   ,@rIsPresent
			   )
			  
		    SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION         
	END	 
ELSE
	 BEGIN
	 
	 Select @rId = Id From sAssessment.tResultDetail Where ResultId IN (SELECT ID from sAssessment.tResult Where AcademicId=@rAcademicId AND ExamId=@rExamId) AND ExamDetailId=@rExamDetailId
	
	    UPDATE  [sAssessment].[tResultDetail]
	    SET
	         -- ResultId=@rResultId
	         --,ExamDetailId=@rExamDetailId,
			 Obtain=@rObtain
			 ,IsPresent=@rIsPresent
			 ,SubjectGrade = ''
			 ,SubjectGradePoint=0
			 ,Percentile=0
	      WHERE Id = @rId 	   
	      SELECT @rId AS Result
	
		--COMMIT TRANSACTION
	 END  
		
	--END
--END	
COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END	


GO
ALTER PROCEDURE [sHrm].[pValidateImportEmployee]
    
    @rOrgGroupId int,
    @rOrgId int,
	@rXmldoc [nvarchar](max)
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
DECLARE @lCount INT
DECLARE @lInterrorCode INT,
		@intDoc INT,
        @lCode nvarchar(20),     
        @lDOB nvarchar(15),        
        @lDOJ nvarchar(15),      
        @1ReturnCode int = 1,
        @1ExistEmployeeCode nvarchar(max) = '',
        @1ValidDOB nvarchar(max) = '',
        @1ValidDOJ nvarchar(max) = '',
        @1DuplicateEmployeeCode nvarchar(max) = ''
       
EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc
 
CREATE TABLE #tTable1 
 (
		Id bigint identity,
        Code nvarchar(20),
        FirstName nvarchar(100),
        LastName nvarchar(100),
		EmployeeType nvarchar(100),
		EmployeeGroup nvarchar(100),
		EmployeeGrade nvarchar(100),
		Department nvarchar(100),
		Designation nvarchar(100),
        Gender nvarchar(10),
        DOB nvarchar(15),
		DOJ nvarchar(15),
		Religion nvarchar(100)
  )
  INSERT INTO #tTable1
	(
	    Code,
	    FirstName,
	    LastName,
	    EmployeeType,
	    EmployeeGroup,
	    EmployeeGrade,
	    Department,
	    Designation,
	    Gender,
	    DOB,
	    DOJ,
	    Religion
    ) 
   SELECT
        Code,
	    FirstName,
	    LastName,
	    EmployeeType,
	    EmployeeGroup,
	    EmployeeGrade,
	    Department,
	    Designation,
	    Gender,
	    DOB,
	    DOJ,
	    Religion   
   
   FROM OPENXML (@intDoc, '/Table/ImportEmployee', 1)
   With
   (
        Code nvarchar(50) '@Code',
        FirstName nvarchar(100) '@FirstName',
        LastName nvarchar(100) '@LastName',
        EmployeeType nvarchar(100) '@EmployeeType',
        EmployeeGroup nvarchar(100) '@EmployeeGroup',
        EmployeeGrade nvarchar(100) '@EmployeeGrade',
        Department nvarchar(100) '@Department',
        Designation nvarchar(100) '@Designation',
		Gender nvarchar(10) '@Gender',
		DOB nvarchar(15) '@DOB',
		DOJ nvarchar(15) '@DOJ',
		Religion nvarchar(100) '@Religion'
   )   
EXEC sp_xml_removedocument @intDoc
		
SELECT @lCount =  COUNT(Id) FROM #tTable1
 
WHILE @lCount > 0 
BEGIN
  
    SELECT         
         
         @lCode = Code, 
         @lDOB=DOB,
         @lDOJ=DOJ
         
    FROM #tTable1 WHERE Id = @lCount 
     
    IF Exists ((select 1 from sHrm.tEmployeeMaster where Code COLLATE DATABASE_DEFAULT = @lCode COLLATE DATABASE_DEFAULT AND OrgId = @rOrgId))         
    BEGIN
		SET @1ExistEmployeeCode = @1ExistEmployeeCode + @lCode + ','
    END
	IF(ISDATE(@lDOB) = 0 AND @lDOB!='')
	BEGIN
		SET @1ValidDOB=@1ValidDOB + @lDOB+','
	END
	IF(ISDATE(@lDOJ) = 0 AND @lDOJ!='')
	BEGIN
		SET @1ValidDOJ=@1ValidDOJ + @lDOJ+','
	END
		SET @lCount = @lCount - 1	
    END	
    
	IF EXISTS(SELECT 1 fROM #tTable1 WHERE Code IS NULL OR Code COLLATE DATABASE_DEFAULT = '' COLLATE DATABASE_DEFAULT)
	BEGIN
		SELECT 'Code Should not be empty' AS EmployeeCode
	END
	ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE LastName IS NULL OR LastName COLLATE DATABASE_DEFAULT = '' COLLATE DATABASE_DEFAULT)
	BEGIN
		SELECT 'Surname Should not be empty' AS EmployeeCode
	END
	ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE FirstName IS NULL OR FirstName COLLATE DATABASE_DEFAULT = '' COLLATE DATABASE_DEFAULT)
	BEGIN
		SELECT 'First Name Should not be empty' AS EmployeeCode
	END
	ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE Gender IS NULL OR Gender COLLATE DATABASE_DEFAULT = '' COLLATE DATABASE_DEFAULT)
	BEGIN
		SELECT 'Gender Should not be empty' AS EmployeeCode
	END
	ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE EmployeeType IS NULL OR EmployeeType COLLATE DATABASE_DEFAULT = '' COLLATE DATABASE_DEFAULT)
	BEGIN
		SELECT 'Employee Type Should not be empty' AS EmployeeCode
	END
	ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE EmployeeGroup IS NULL OR EmployeeGroup COLLATE DATABASE_DEFAULT = '' COLLATE DATABASE_DEFAULT)
	BEGIN
		SELECT 'Employee Group Should not be empty' AS EmployeeCode
	END
	--ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE EmployeeGrade IS NULL OR EmployeeGrade COLLATE DATABASE_DEFAULT = '' COLLATE DATABASE_DEFAULT)
	--BEGIN
	--	SELECT 'Employee Grade Should not be empty' AS EmployeeCode
	--END
	ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE Department COLLATE DATABASE_DEFAULT  IS NULL OR Department COLLATE DATABASE_DEFAULT = '' COLLATE DATABASE_DEFAULT)
	BEGIN
		SELECT 'Department Should not be empty' AS EmployeeCode
	END
	
	ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE EmployeeType COLLATE DATABASE_DEFAULT  NOT IN(SELECT Title FROM sHrm.tEmployeeTypeMaster WHERE OrgId=@rOrgId))
	BEGIN
		SELECT 'Enter proper value for Employee Type' AS EmployeeCode
	END	
	ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE EmployeeGroup  COLLATE DATABASE_DEFAULT NOT IN(SELECT Title FROM sHrm.tEmployeeGroupMaster))
	BEGIN
		SELECT 'Enter proper value for Employee Group' AS EmployeeCode
	END	
	ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE EmployeeGrade  COLLATE DATABASE_DEFAULT NOT IN(SELECT Title FROM sHrm.tEmployeeGradeMaster WHERE OrgId=@rOrgId))
	BEGIN
		SELECT 'Enter proper value for Employee Grade' AS EmployeeCode
	END	
	ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE Department  COLLATE DATABASE_DEFAULT NOT IN(SELECT Title FROM sSetup.tDepartmentMaster WHERE OrgId=@rOrgId))
	BEGIN
		SELECT 'Enter proper value for Department' AS EmployeeCode
	END	
	--ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE Designation  COLLATE DATABASE_DEFAULT !=''  COLLATE DATABASE_DEFAULT AND Designation  COLLATE DATABASE_DEFAULT NOT IN(SELECT Title FROM sHrm.tEmployeeDesignationMaster WHERE OrgId=@rOrgId))
	--BEGIN
	--	SELECT 'Enter proper value for Designation' AS EmployeeCode
	--END	
	ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE Religion!='' AND Religion COLLATE DATABASE_DEFAULT NOT IN(SELECT Title FROM sCommon.tReligionMaster WHERE OrgGroupId=@rOrgGroupId))
	BEGIN
		SELECT 'Enter proper value for Religion' AS EmployeeCode
	END
	ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE Gender!='' AND Gender COLLATE DATABASE_DEFAULT NOT IN(SELECT Title FROM sCommon.tGenderMaster))
	BEGIN
		SELECT 'Enter proper value for gender' AS EmployeeCode
	END
	ELSE
	BEGIN
	SELECT @1DuplicateEmployeeCode=COALESCE(@1DuplicateEmployeeCode ,'') 
	+ Code + ',' FROM #tTable1 GROUP BY Code HAVING ( COUNT(Code) > 1 )	
	IF(@1DuplicateEmployeeCode IS NOT NULL AND @1DuplicateEmployeeCode != '')
	BEGIN
		SET @1DuplicateEmployeeCode = 'Duplicate Code ' + @1DuplicateEmployeeCode
		SELECT @1DuplicateEmployeeCode AS EmployeeCode
	END
	ELSE
	IF((@1ExistEmployeeCode IS NULL OR @1ExistEmployeeCode = '') 
	AND (@1ValidDOB IS NULL OR @1ValidDOB = '') AND (@1ValidDOJ IS NULL OR @1ValidDOJ = ''))
	BEGIN
		SELECT '' AS EmployeeCode
	END
	ELSE IF (@1ExistEmployeeCode IS NOT NULL AND @1ExistEmployeeCode != '')
	BEGIN
		SET @1ExistEmployeeCode = 'Exist Code ' + @1ExistEmployeeCode
		Select @1ExistEmployeeCode AS EmployeeCode
	END
	ELSE IF (@1ValidDOB IS NOT NULL AND @1ValidDOB != '')
	BEGIN
		SET @1ValidDOB = 'Wrong DOB ' + @1ValidDOB
		Select @1ValidDOB AS EmployeeCode
	END
	ELSE IF (@1ValidDOJ IS NOT NULL AND @1ValidDOJ != '')
	BEGIN
		SET @1ValidDOJ = 'Wrong DOJ ' + @1ValidDOJ
		Select @1ValidDOJ AS EmployeeCode
	END
	END
END
	
GO


 

ALTER PROCEDURE [sAssessment].[pCCEResultDetailAdd]
	 
	     
            @rAcademicId bigint
		   ,@rClassSubjectId int
		   ,@rObtain decimal(6,2)		
		   ,@rExamOrder int
		   ,@rCCEExamId INT  -- CCEId
		   ,@rSubExamId INT  -- CCEId
		   ,@rOrgId int
		   ,@rIsPresent bit = null,
		   @rCCEGradePointMarks decimal(6,2)=0,
		   @rClassId int=0
		 
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	--BEGIN TRY
	
	-- BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 
	 DECLARE @lMaxiMark decimal(6,2)
	 SELECT  @lMaxiMark = Maximum FROM sAssessment.tExamDetail Where ExamId = @rSubExamId AND ClassSubjectId = @rClassSubjectId
	 DECLARE @lCCEResultDetailId BIGINT

SELECT @lCCEResultDetailId= ISNULL(AcademicId,0) From sAssessment.tCCEResultDetail Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
--Select @rObtain
 
IF ISNULL(@lCCEResultDetailId,0) = 0
	 BEGIN

	--EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAssessment.tCCEResultDetail', 0, 1, 1,@outNextNumber = @lNextNumber output	
	 
	INSERT INTO [sAssessment].[tCCEResultDetail]
			   (
				[AcademicId] 
			   ,[ClassSubjectId]
			   ,[GradePointFA1]
			   ,[GradePointFA2]
			   ,[GradePointSA1]
			   ,[GradePointFA3]
			   ,[GradePointFA4]
			   ,[GradePointSA2]
			   ,[UpdatedUserId]
			   ,[UpdatedDateTime]
			   )
		 VALUES
			   (
			    @rAcademicId
			   ,@rClassSubjectId
			   ,0.00
			   ,0.00
			   ,0.00
			   ,0.00
			   ,0.00
			   ,0.00
			   ,0
			   ,sCommon.fGetDate()
			   )
  
			 
     			IF(@rExamOrder=1) UPDATE [sAssessment].[tCCEResultDetail] SET [FA1]=ISNULL(@rObtain,0),IsPresentFA1=@rIsPresent,GRADEPOINTFA1 =(@rCCEGradePointMarks *ISNULL(@rObtain,0))/@lMaxiMark Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
			ELSE IF(@rExamOrder=2) UPDATE [sAssessment].[tCCEResultDetail] SET [FA2]=ISNULL(@rObtain,0),IsPresentFA2=@rIsPresent,GradePointFA2 =(@rCCEGradePointMarks * ISNULL(@rObtain,0))/@lMaxiMark Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
			ELSE IF(@rExamOrder=3) UPDATE [sAssessment].[tCCEResultDetail] SET [SA1]=ISNULL(@rObtain,0),IsPresentSA1=@rIsPresent,GradePointSA1 =(@rCCEGradePointMarks *ISNULL(@rObtain,0) )/@lMaxiMark Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
			ELSE IF(@rExamOrder=4) UPDATE [sAssessment].[tCCEResultDetail] SET [FA3]=ISNULL(@rObtain,0),IsPresentFA3=@rIsPresent,GradePointFA3 = (@rCCEGradePointMarks * ISNULL(@rObtain,0))/@lMaxiMark  Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
			ELSE IF(@rExamOrder=5) UPDATE [sAssessment].[tCCEResultDetail] SET [FA4]=ISNULL(@rObtain,0),IsPresentFA4=@rIsPresent,GradePointFA4 =(@rCCEGradePointMarks * ISNULL(@rObtain,0))/@lMaxiMark Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
			ELSE IF(@rExamOrder=6) UPDATE [sAssessment].[tCCEResultDetail] SET [SA2]=ISNULL(@rObtain,0),IsPresentSA2=@rIsPresent,GradePointSA2 =(@rCCEGradePointMarks *ISNULL(@rObtain,0) )/@lMaxiMark  Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
	
			UPDATE [sAssessment].[tCCEResultDetail] SET [FA]= ISNULL(FA1,0)+ISNULL(FA2,0)+ISNULL(FA3,0)+ISNULL(FA4,0),FAGradePoint=ROUND(GradePointFA1+GradePointFA2+GradePointFA3 +GradePointFA4,0) Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
			UPDATE [sAssessment].[tCCEResultDetail] SET [SA]=ISNULL(SA1,0)+ISNULL(SA2,0),SAGradePoint = ROUND( GradePointSA1+GradePointSA2  ,0) Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
			UPDATE [sAssessment].[tCCEResultDetail] SET [Term1]= ISNULL(FA1,0)+ISNULL(FA2,0)+ISNULL(SA1,0), Term1GradePoint = ROUND( GradePointFA1+GradePointFA2+GradePointSA1 ,0) Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
			UPDATE [sAssessment].[tCCEResultDetail] SET [Term2]=ISNULL(FA3,0)+ISNULL(FA4,0)+ISNULL(SA2,0),Term2GradePoint = ROUND( GradePointFA3+GradePointFA4+GradePointSA2 ,0) Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
			UPDATE [sAssessment].[tCCEResultDetail] SET [TOTAL]=ISNULL(FA1,0)+ISNULL(FA2,0)+ISNULL(FA3,0)+ISNULL(FA4,0)+ISNULL(SA1,0)+ISNULL(SA2,0) Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
		    SELECT @rAcademicId AS Result
	
		--COMMIT TRANSACTION         
	END	 
ELSE
	 BEGIN
	
	    --UPDATE  [sAssessment].[tCCEResultDetail]
	    --SET  
	    --     [UpdatedDateTime]=sCommon.fGetDate()
	    --  WHERE [AcademicId] =@rAcademicId
	     	 
	     
	        IF(@rExamOrder=1) UPDATE [sAssessment].[tCCEResultDetail] SET [FA1]=ISNULL(@rObtain,0),IsPresentFA1=@rIsPresent,GRADEPOINTFA1 =(@rCCEGradePointMarks *ISNULL(@rObtain,0))/@lMaxiMark Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
			ELSE IF(@rExamOrder=2) UPDATE [sAssessment].[tCCEResultDetail] SET [FA2]=ISNULL(@rObtain,0),IsPresentFA2=@rIsPresent,GradePointFA2 =(@rCCEGradePointMarks * ISNULL(@rObtain,0))/@lMaxiMark Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
			ELSE IF(@rExamOrder=3) UPDATE [sAssessment].[tCCEResultDetail] SET [SA1]=ISNULL(@rObtain,0),IsPresentSA1=@rIsPresent,GradePointSA1 =(@rCCEGradePointMarks *ISNULL(@rObtain,0) )/@lMaxiMark Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
			ELSE IF(@rExamOrder=4) UPDATE [sAssessment].[tCCEResultDetail] SET [FA3]=ISNULL(@rObtain,0),IsPresentFA3=@rIsPresent,GradePointFA3 = (@rCCEGradePointMarks * ISNULL(@rObtain,0))/@lMaxiMark  Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
			ELSE IF(@rExamOrder=5)UPDATE [sAssessment].[tCCEResultDetail] SET [FA4]=ISNULL(@rObtain,0),IsPresentFA4=@rIsPresent,GradePointFA4 =(@rCCEGradePointMarks * ISNULL(@rObtain,0))/@lMaxiMark Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
			ELSE UPDATE [sAssessment].[tCCEResultDetail] SET [SA2]=ISNULL(@rObtain,0),IsPresentSA2=@rIsPresent,GradePointSA2 =(@rCCEGradePointMarks *ISNULL(@rObtain,0) )/@lMaxiMark  Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
			
			UPDATE [sAssessment].[tCCEResultDetail] SET [FA]= ISNULL(FA1,0)+ISNULL(FA2,0)+ISNULL(FA3,0)+ISNULL(FA4,0),FAGradePoint=ROUND(GradePointFA1+GradePointFA2+GradePointFA3 +GradePointFA4,0) Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
			UPDATE [sAssessment].[tCCEResultDetail] SET [SA]=ISNULL(SA1,0)+ISNULL(SA2,0),SAGradePoint = ROUND( GradePointSA1+GradePointSA2  ,0) Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
			UPDATE [sAssessment].[tCCEResultDetail] SET [Term1]= ISNULL(FA1,0)+ISNULL(FA2,0)+ISNULL(SA1,0),Term1GradePoint = ROUND( GradePointFA1+GradePointFA2+GradePointSA1 ,0) Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
			UPDATE [sAssessment].[tCCEResultDetail] SET [Term2]=ISNULL(FA3,0)+ISNULL(FA4,0)+ISNULL(SA2,0),Term2GradePoint = ROUND( GradePointFA3+GradePointFA4+GradePointSA2 ,0) Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
			UPDATE [sAssessment].[tCCEResultDetail] SET [TOTAL]=ISNULL(FA1,0)+ISNULL(FA2,0)+ISNULL(FA3,0)+ISNULL(FA4,0)+ISNULL(SA1,0)+ISNULL(SA2,0) Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
			 
		 
			--SELECT @rAcademicId AS Result
	
	 END  
		
--Grade Evaluation
DECLARE @MinimumScore decimal(5,2)
DECLARE @GradeTitle nvarchar(10)
DECLARE @GradePoint decimal(6,2)
DECLARE @lCount int
DECLARE @lDataSetID INT  
--DECLARE @lClassId int

DECLARE @lTempMark decimal(6,2)
 

--SELECT @lDataSetID=GradeSetId FROM sAssessment.tExamDetail WHERE ExamId = @rCCEExamId AND ClassSubjectId = @rClassSubjectId
  --SELECT @lClassId = ClassId From sStudent.tAcademic Where Id =  @rAcademicId 	
  SELECT @lDataSetID=GradeSetId  FROM sAssessment.tCCEExamSetting WHERE CCEExamId = @rCCEExamId AND ClassId = @rClassId

CREATE TABLE #tempGradeSetDetail
	(
		Id INT IDENTITY (1, 1),
		MinimumScore decimal(5,2),
		GradeTitle nvarchar(10),
		GradePoint decimal(6,2) 					 
	) 
	INSERT INTO #tempGradeSetDetail
	SELECT MinimumScore,GradeCode,GradePoint		
	FROM sAssessment.tGradeSetDetail where GradesetId=@lDataSetID
	order by MinimumScore DESC

SELECT @lCount =  COUNT(Id) FROM #tempGradeSetDetail
DECLARE @lloopCount int
--set @lloopCount=1
while ( @lCount > 0 )
BEGIN
		SELECT @MinimumScore =MinimumScore,@GradeTitle=GradeTitle,@GradePoint=GradePoint
		FROM #tempGradeSetDetail WHERE Id = @lCount
		 
		IF @rExamOrder = 1 
		BEGIN				
			Update sAssessment.tCCEResultDetail  Set GradeFA1 = @GradeTitle,FA1Max=@lMaxiMark WHERE AcademicId=@rAcademicId AND ClassSubjectID=@rClassSubjectId AND (FA1 * 100)/@lMaxiMark  >= @MinimumScore 
			
		END
		IF @rExamOrder = 2 
		BEGIN							
			Update sAssessment.tCCEResultDetail  Set GradeFA2 = @GradeTitle,FA2Max=@lMaxiMark WHERE AcademicId=@rAcademicId AND ClassSubjectID=@rClassSubjectId AND (FA2 * 100)/@lMaxiMark >= @MinimumScore 
			
		END
		IF @rExamOrder = 3 
		BEGIN				
			Update sAssessment.tCCEResultDetail  Set GradeSA1 = @GradeTitle,SA1Max=@lMaxiMark WHERE AcademicId=@rAcademicId AND ClassSubjectID=@rClassSubjectId AND (SA1 * 100)/@lMaxiMark >= @MinimumScore 
			 
		END
		IF @rExamOrder = 4 
		BEGIN				
			Update sAssessment.tCCEResultDetail  Set GradeFA3 = @GradeTitle,FA3Max=@lMaxiMark WHERE AcademicId=@rAcademicId AND ClassSubjectID=@rClassSubjectId AND (FA3 * 100)/@lMaxiMark >= @MinimumScore 
			
		END
		IF @rExamOrder = 5 
		BEGIN				
			Update sAssessment.tCCEResultDetail  Set GradeFA4 = @GradeTitle,FA4Max=@lMaxiMark WHERE AcademicId=@rAcademicId AND ClassSubjectID=@rClassSubjectId AND (FA4 * 100)/@lMaxiMark >= @MinimumScore 
			 
		END
		IF @rExamOrder = 6 
		BEGIN		
			Update sAssessment.tCCEResultDetail  Set GradeSA2 = @GradeTitle,SA2Max=@lMaxiMark WHERE AcademicId=@rAcademicId AND ClassSubjectID=@rClassSubjectId AND (SA2 * 100)/@lMaxiMark >= @MinimumScore 
			 
		END
			SELECT @lTempMark = ISNULL(FA1MAX,0)+ISNULL(FA2MAX,0)+ISNULL(FA3MAX,0)+ISNULL(FA4MAX,0) FROM sAssessment.tCCEResultDetail WHERE AcademicId=@rAcademicId AND ClassSubjectID=@rClassSubjectId 
			IF @lTempMark <> 0 
			BEGIN
				Update sAssessment.tCCEResultDetail  Set FAGRADE = @GradeTitle WHERE AcademicId=@rAcademicId AND ClassSubjectID=@rClassSubjectId 
				AND (FA * 100)/@lTempMark >= @MinimumScore 
			END

SELECT @lTempMark = ISNULL(FA1MAX,0)+ISNULL(FA2MAX,0) FROM sAssessment.tCCEResultDetail WHERE AcademicId=@rAcademicId AND ClassSubjectID=@rClassSubjectId 
			IF @lTempMark <> 0 
			BEGIN
				Update sAssessment.tCCEResultDetail  Set [FATerm1] = @GradeTitle WHERE AcademicId=@rAcademicId AND ClassSubjectID=@rClassSubjectId 
				AND ((FA1+FA2) * 100)/@lTempMark >= @MinimumScore 
			END

SELECT @lTempMark = ISNULL(FA3MAX,0)+ISNULL(FA4MAX,0) FROM sAssessment.tCCEResultDetail WHERE AcademicId=@rAcademicId AND ClassSubjectID=@rClassSubjectId 
			IF @lTempMark <> 0 
			BEGIN
				Update sAssessment.tCCEResultDetail  Set [FATerm2] = @GradeTitle WHERE AcademicId=@rAcademicId AND ClassSubjectID=@rClassSubjectId 
				AND ((FA3+FA4) * 100)/@lTempMark >= @MinimumScore 
			END
			
			SELECT @lTempMark = ISNULL(SA1MAX,0)+ISNULL(SA2MAX,0) FROM sAssessment.tCCEResultDetail WHERE AcademicId=@rAcademicId AND ClassSubjectID=@rClassSubjectId 
			IF @lTempMark <> 0 
			BEGIN
				Update sAssessment.tCCEResultDetail  Set SAGRADE = @GradeTitle WHERE AcademicId=@rAcademicId AND ClassSubjectID=@rClassSubjectId 
				AND (SA * 100)/@lTempMark >= @MinimumScore 
			END
			
			SELECT @lTempMark = ISNULL(FA1MAX,0)+ISNULL(FA2MAX,0)+ISNULL(SA1MAX,0) FROM sAssessment.tCCEResultDetail WHERE AcademicId=@rAcademicId AND ClassSubjectID=@rClassSubjectId 
			IF @lTempMark <> 0 
			BEGIN
				Update sAssessment.tCCEResultDetail  Set Term1Grade = @GradeTitle WHERE AcademicId=@rAcademicId AND ClassSubjectID=@rClassSubjectId 
				AND (TERM1 * 100)/@lTempMark >= @MinimumScore 
			END
			
			SELECT @lTempMark = ISNULL(FA3MAX,0)+ISNULL(FA4MAX,0)+ISNULL(SA2MAX,0) FROM sAssessment.tCCEResultDetail WHERE AcademicId=@rAcademicId AND ClassSubjectID=@rClassSubjectId 
			IF @lTempMark <> 0 
			BEGIN	
				Update sAssessment.tCCEResultDetail  Set Term2Grade = @GradeTitle WHERE AcademicId=@rAcademicId AND ClassSubjectID=@rClassSubjectId 
				AND (TERM2 * 100)/@lTempMark >= @MinimumScore 
			END
		
			SELECT @lTempMark = ISNULL(FA1MAX,0)+ISNULL(FA2MAX,0)+ISNULL(SA1MAX,0)+ISNULL(FA1MAX,0)+ISNULL(FA2MAX,0)+ISNULL(SA1MAX,0) FROM sAssessment.tCCEResultDetail WHERE AcademicId=@rAcademicId AND ClassSubjectID=@rClassSubjectId 
			IF @lTempMark <> 0  
			BEGIN
				Update sAssessment.tCCEResultDetail  Set Grade = @GradeTitle WHERE AcademicId=@rAcademicId AND ClassSubjectID=@rClassSubjectId 
				AND (TOTAL * 100)/@lTempMark >= @MinimumScore 
			END 
		SET @lCount = @lCount - 1
 END
	--End Grade Evaluation	
--END	
--COMMIT TRANSACTION		
--	END TRY
	
--	BEGIN CATCH 
--		ROLLBACK TRANSACTION
--		SELECT -1 AS Result
--	END CATCH	
		
END

GO

ALTER PROCEDURE [sAssessment].[pCCEResultGenerate]
	
	@rClassId int,
	@rExamId int,
	@rBatchId int,
	@rOrgId int,
	@rExamOrder int,
	@rCCEExamId int,
	@rDivisionId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	DECLARE @lCount_MarkEntryStudent int
	DECLARE @lAcademicId bigint
	Declare @lCCESettingMaxMark decimal(6,2)
	
	SELECT @lCCESettingMaxMark=MaxMark  FROM sAssessment.tCCEExamSetting WHERE CCEExamId = @rExamOrder AND ClassId = @rClassId
	 
	CREATE TABLE #TempMarkEntryStudent(
	[AutoId] [int] identity,
	[AcademicId] [bigint] NOT NULL,
	[ExamId] [int] NULL,
	[OrgId] [int] NULL,
	[ClassId] [int] NULL,
	)
	 
	INSERT INTO #TempMarkEntryStudent 
	SELECT  
		SA.AcademicId,
		EM.Id AS ExamId,
		SA.OrgId,
		EM.ClassId
    FROM  
		sStudent.vStudentAcademic SA 
		INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = SA.ClassId 
		INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=SA.AcademicId
		--LEFT JOIN sAssessment.tCCEResult CR ON CR.AcademicId = SA.AcademicId
	WHERE 
		(EM.ClassId = @rClassId OR @rClassId = 0 )    
		AND (EM.Id=@rExamId OR @rExamId = 0)
		AND (EM.BatchId = @rBatchId or @rBatchId=0)
		AND SA.StatusId=1
		AND SA.BatchId=@rBatchId
		AND SA.DivisionId=@rDivisionId
    
    SET @lCount_MarkEntryStudent = 0
    SELECT @lCount_MarkEntryStudent = COUNT(AutoId) FROM #TempMarkEntryStudent
     
    --SELECT * FROM #TempMarkEntryStudent
    
	CREATE TABLE #TempCCEMarkEntry (
	[AutoId] [int] identity,
	[AcademicId] [bigint] NOT NULL ,
	[ResultDetailId] [bigint] NULL,
	[ClassSubjectId] [int] NULL,
	[Obtain] [decimal](5,2) NULL,
	[IsPresent] [bit] NULL,
	[ExamId] [int] NULL
	)
	
	WHILE (@lCount_MarkEntryStudent > 0)
	BEGIN
		
		SET @lAcademicId = 0
		SELECT @lAcademicId = AcademicId FROM #TempMarkEntryStudent WHERE AutoId = @lCount_MarkEntryStudent
	    EXEC sAssessment.pCCEResultAdd @rAcademicId=@lAcademicId,@rUpdatedUserId=0,@rOrgId=@rOrgId
			
		INSERT INTO #TempCCEMarkEntry 
		SELECT 
			SA.AcademicId,
			ISNULL(RD.ID,0) AS ResultDetailId,
			ED.ClassSubjectId AS ClassSubjectId,
			ISNULL(RD.Obtain,0) AS Obtain,
			RD.IsPresent,
			@rExamId
		FROM sAssessment.tResultDetail RD 
			INNER JOIN sAssessment.tResult R ON R.Id= RD.ResultId
			INNER JOIN 	sStudent.vStudentAcademic SA ON SA.AcademicId = R.AcademicId
			INNER JOIN sAssessment.tExamMaster EM ON  EM.Id=R.ExamId 	
			INNER JOIN sAssessment.tExamDetail ED ON  RD.ExamDetailId = ED.Id		
		WHERE
			(SA.ClassId = @rClassId)    
			AND SA.StatusId=1
			AND SA.BatchId=@rBatchId
			AND R.ExamId = @rExamId
			AND R.AcademicId = @lAcademicId
			AND SA.DivisionId =@rDivisionId
			--SELECT * FROM #TempCCEMarkEntry 
			
			DECLARE @lCount int
			SET @lCount = 0
			SELECT @lCount = COUNT(AcademicId) FROM #TempCCEMarkEntry
				WHILE (@lCount > 0)
				BEGIN
					DECLARE @lClassSubjectId int
				    DECLARE @lObtain decimal(5,2)
				    DECLARE @lIsPresent bit
				    DECLARE @rIsPresent bit
					SELECT @lClassSubjectId = ClassSubjectId, @lObtain = Obtain,@lIsPresent = IsPresent  FROM #TempCCEMarkEntry WHERE AcademicId = @lAcademicId AND ExamId = @rExamId AND AutoId = @lCount
					EXEC sAssessment.pCCEResultDetailAdd @rAcademicId=@lAcademicId,@rClassSubjectId=@lClassSubjectId,@rObtain=@lObtain,@rExamOrder=@rExamOrder,@rCCEExamId=@rCCEExamId,@rSubExamId=@rExamId,@rOrgId=@rOrgId,@rIsPresent=@lIsPresent,@rCCEGradePointMarks=@lCCESettingMaxMark,@rClassId=@rClassId
					SET @lCount = @lCount -1
				END
				TRUNCATE TABLE #TempCCEMarkEntry
				--DELETE FROM #TempCCEMarkEntry
				--DBCC CHECKIDENT (#TempCCEMarkEntry, RESEED, 1);
		SET @lCount_MarkEntryStudent = @lCount_MarkEntryStudent -1
	    EXEC sAssessment.pCCEResultDetailSubjectGradeUpdate @rExamOrder,@rCCEExamId,@rExamId,@rBatchId,@rClassId,@rDivisionId
	END
	DROP TABLE #TempMarkEntryStudent
	DROP TABLE #TempCCEMarkEntry
		SELECT 1 AS Result
END

GO

ALTER PROCEDURE [sAttendance].[pAttenanceRegisterGet]
 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rAttendanceTypeId smallint,
	 @rOrgId int,
	 @rForMonth smallint,
	 @rForYear smallint,
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rBatchId int = 0,
	 @rStudentCode nvarchar(20)='',
	 @rDepartmentId int = 0,
	 @rAcademicId bigint = 0,
	 @PageIndex int=0,
	 @rStatus int=0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
DECLARE @lFirstDate Date
	DECLARE @lResult nvarchar(max)
	DECLARE @li int 
	SET @li=1
	SET @lFirstDate = CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'/'+CONVERT(NVARCHAR(2),@rForMonth)+'/01'))	
	
	
DECLARE @lOrgId  int
--DECLARE @lSchoolRemark1  nvarchar(500)
--DECLARE @lSchoolRemark2  nvarchar(500)
--DECLARE @lSchoolRemark3  nvarchar(500)
DECLARE @lSchoolRequiredSignature  nvarchar(500)

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=1 where RGM.Id=1
 
-- select @lSchoolRequiredSignature as sig
 	
BEGIN 
	 CREATE Table #AttendanceRegistertempTable
(
	TID int identity(1,1),
	ClassDivisionTitle Nvarchar(50),
	Code nvarchar(50),
	RollNo int,
	AcademicId bigint,
	Name nvarchar(50),
	AttendanceTypeId int,
	ForYear int,
	ForMonth int,
	ForMonthInWord nvarchar(100),
	ClassId int,
	DivisionId int,
	ClassName nvarchar(50),
	DivisionName nvarchar(50),
	IsPresent bit,
	DayPart int,
	LeftDate date,
	ClassOrderIndex int,
	DivisionOrderIndex int,
	FooterSignature nvarchar(500),
	StatusId int,
	AttendanceDate date,
	AttendanceTagId int ,
	EmployeeName nvarchar(100)
)
Insert INTO #AttendanceRegistertempTable
(	
	ClassDivisionTitle,
	Code ,
	RollNo,
	AcademicId,
	Name,
	AttendanceTypeId,
	ForYear,
	ForMonth,
	ForMonthInWord,
	ClassId,
	DivisionId,
	ClassName,
	DivisionName,
	IsPresent,
	DayPart,
	LeftDate,
	ClassOrderIndex,
	DivisionOrderIndex,
	FooterSignature,
	StatusId,
	AttendanceDate,
	AttendanceTagId,
	EmployeeName
)
Select	    
	ISNULL(SA.ClassName + '-' + SA.DivisionName,'') AS ClassDivisionTitle,
	SA.Code,
	SA.RollNo,
	SA.AcademicId,
	SA.Name,
	SR.AttendanceTypeId ,
	YEAR(SR.AttendanceDate) AS ForYear,
	MONTH(SR.AttendanceDate) AS ForMonth,
	DATENAME(month, SR.AttendanceDate) AS ForMonthInWord,
	SA.ClassId,
	SA.DivisionId,
	SA.ClassName,Sa.DivisionName,
  
	--(CASE SR.IsPresent WHEN 1 THEN 'P' 
	--	WHEN 0 THEN 'A'
	--ELSE  ' ' END )AS  IsPresent,		
	SR.IsPresent,
	 day(SR.AttendanceDate) AS DayPart,
	 
	 A.LeftDate,
	 CM.OrderIndex AS ClassOrderIndex,
	 DM.OrderIndex As DivisionOrderIndex,
	@lSchoolRequiredSignature AS FooterSignature,
	 SA.StatusId,
	 SR.AttendanceDate As AttendanceDate,
	 SR.AttendanceTagId,
	 EM.FirstName+' ' + EM.LastName AS EmployeeName
	 --,
	 --SR.IsPresent
	 
	 
    from
            sStudent.vStudentAcademic SA 
            INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.AcademicId 
            INNER JOIN sStudent.tStudentAdmission A ON SA.StudentId = A.StudentId
            INNER JOIN sSetup.tClassMaster CM ON CM.Id = SA.ClassId
            INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = CM.OrgId
            INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=SA.DivisionId
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId
            
			
            
             WHERE  
	        ((SR.AttendanceTypeId=@rAttendanceTypeId) OR (@rAttendanceTypeId= 0))
	         AND ((SA.OrgId=@rOrgId) OR (@rOrgId= 0))
	          AND ((SA.BatchId=@rBatchId) OR (@rBatchId= 0))
	          AND ((YEAR(SR.AttendanceDate)=@rForYear) OR (@rForYear= 0))
	          AND ((MONTH(SR.AttendanceDate)=@rForMonth) OR (@rForMonth= 0))
	           AND ((SA.ClassId=@rClassId) OR (@rClassId= 0))
	           AND ((SA.Code=@rStudentCode) OR (@rStudentCode=''))
	           AND ((SA.AcademicId=@rAcademicId) OR (@rAcademicId=0))	           
				AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
	           AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId= 0))
	           AND ((SA.StatusId=@rStatus)OR (@rStatus=0))

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

SELECT 
@li AS DayPart,
 [sAttendance].[fWeekHOffHolidayGet](@rForYear,@rForMonth,@li,@rBatchId,@rDivisionId,'',@rOrgId) 
SET @li = @li + 1
END

 

SELECT  
			@lFirstDate AS LastDate,
			LeftDate,
            @rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			PivotTable.AcademicId,
			ClassDivisionTitle,isnull(Code,'') as Code,isnull(RollNo,0) as RollNo,
			isnull(Name,'') as Name,isnull(AttendanceTypeId,0) as AttendanceTypeId,ForYear,
			ForMonth,ClassId,ClassName,DivisionId,
			DivisionName,
			 
			ForMonthInWord,
			(ISNULL(TC.TCount,0) - ISNULL(AC.ACount,0)) AS PresentCount,
			 ISNULL(TC.TCount,0) AS AttendanceCount,
		      ISNULL(AC.ACount,0) As  AbsentCount,
		       ISNULL(PC.PCount,0) As  PresentUpto,
		       ClassOrderIndex,
		       DivisionOrderIndex,
		       FooterSignature,				 
			0 AS TotalPresent ,
	 		 isnull([1],'') AS P1,
			isnull([2],'') AS P2,
			isnull([3],'') AS P3,
			isnull([4],'') AS P4,
			isnull([5],'') AS P5,
			isnull([6],'') AS P6,
			isnull([7],'') AS P7,
			isnull([8],'') AS P8,
			isnull([9],'') AS P9,
			isnull([10],'') AS P10,
			isnull([11],'') AS P11,
			isnull([12],'') AS P12,
			isnull([13],'') AS P13,
			isnull([14],'') AS P14,
			isnull([15],'') AS P15,
			isnull([16],'') AS P16,
			isnull([17],'') AS P17,
			isnull([18],'') AS P18,
			isnull([19],'') AS P19,
			isnull([20],'') AS P20,
			isnull([21],'') AS P21,
			isnull([22],'') AS P22,
			isnull([23],'') AS P23,
			isnull([24],'') AS P24,
			isnull([25],'') AS P25,
			isnull([26],'') AS P26,
			isnull([27],'') AS P27,
			isnull([28],'') AS P28,
			isnull([29],'') AS P29,
			isnull([30],'') AS P30,
			isnull([31],'') AS P31, 
			 EmployeeName ,
 
sCommon.fGetDaysInMonth ( @rForMonth,@rForYear) AS DaysInMonth 
--,
--AttendanceTagId

 
FROM
(
	Select --TID, 
		ISNULL(ClassName + '-' + DivisionName,'') AS ClassDivisionTitle,
		Code,
		RollNo,
		AcademicId,
		Name,
		AttendanceTypeId ,
		YEAR(ST.AttendanceDate) AS ForYear,
		MONTH(ST.AttendanceDate) AS ForMonth,
		DATENAME(month, ST.AttendanceDate) AS ForMonthInWord,
		ClassId,
		DivisionId,
		ClassName,
		DivisionName,
		(
			CASE  WHEN IsPresent = 1 AND ST.AttendanceTagId = 1 THEN 'LC' 
				  WHEN IsPresent = 1 AND ST.AttendanceTagId = 2 THEN 'EL' 
			      WHEN IsPresent = 1  THEN 'P' 
				  WHEN IsPresent = 0 THEN 'A'
				  ELSE  DT.Value END 
		)AS  IsPresent,		
		day(ST.AttendanceDate) AS DayPart,
		LeftDate
		,
		ClassOrderIndex,
		DivisionOrderIndex,
		FooterSignature,EmployeeName
      -- DO NOT ADD ANY FIELD HERE WITHOUT PERMISSION OF RAJENDRA
	 FROM 
		#AttendanceRegistertempTable ST 
		INNER JOIN #TempDaysTempTable DT ON DT.DayPart = ST.DayPart
	 WHERE
		((LeftDate >= @lFirstDate) OR ISNULL(LeftDate,'') = '')
) AS SourceTable 
 
	           
	        
PIVOT
(	
MIN(IsPresent)
FOR DayPart IN ([0], [1], [2], [3], [4],[5],[6],[7],[8],[9],[10],[11],[12],[13],[14],[15],[16],[17],[18],[19],[20],[21],[22],[23],[24],[25],[26],[27],[28],[29],[30],[31])
) AS PivotTable
	LEFT JOIN
	(
		Select  AcademicId AS AcademicId, COUNT(1) AS TCount 
		   FROM  
				#AttendanceRegistertempTable
		    
			GROUP BY  AcademicId
    ) TC ON TC.AcademicId = PivotTable.AcademicId
    
	LEFT JOIN
	(
		Select AcademicId AS AcademicId, COUNT(1) AS ACount 
		   FROM  #AttendanceRegistertempTable
		    WHERE   IsPresent = 0	 		
            
			GROUP BY  AcademicId
    ) AC ON AC.AcademicId = PivotTable.AcademicId
	LEFT JOIN
	(SELECT A.Id AS AcademicId, COUNT(1) AS PCount  FROM sAttendance.tStudentRegister SR 
			INNER JOIN sStudent.tAcademic A ON SR.AcademicId = A.Id 
		   INNER JOIN sStudent.tStudentMaster SA ON A.StudentId = SA.Id
		   INNER JOIN sSetup.tClassMaster CM ON A.ClassId = CM.Id
			WHERE  
			 SR.AttendanceDate < (convert(date,CONVERT(nvarchar(10), @rForYear)+ '/' +  CONVERT(nvarchar(10), @rForMonth) + '/' + '01' ))
			AND SR.IsPresent = 1	    		
            --AND (SA.StatusId = 1)
	        AND ((SR.AttendanceTypeId=@rAttendanceTypeId) OR (@rAttendanceTypeId= 0))
	        AND ((SA.OrgId=@rOrgId) OR (@rOrgId= 0))
	        AND ((A.BatchId=@rBatchId) OR (@rBatchId= 0))	          
	        AND ((A.ClassId=@rClassId) OR (@rClassId= 0))
	        AND ((SA.Code=@rStudentCode) OR (@rStudentCode=''))
	        AND ((A.Id=@rAcademicId) OR (@rAcademicId=0))	           
			AND ((CM.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))				
	        AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId= 0))
			GROUP BY A.Id
    ) PC ON PC.AcademicId = PivotTable.AcademicId
 
 
    ORDER BY RollNo;
 

select * from #TempDaysTempTable
 

drop table #AttendanceRegistertempTable	  
drop table #TempDaysTempTable
	
	
END


GO

ALTER PROCEDURE [sAssessment].[pCCEResultDetailSubjectGradeUpdate]
	  
	
	  @rExamOrder INT
	 ,@rCCEExamId INT
	 ,@rSubExamId INT
	 ,@rBatchId INT
	 ,@rClassId INT,
	 @rDivisionId int
	
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 	
--BEGIN TRY
-- BEGIN TRANSACTION	

	
		DECLARE @MinimumScore decimal(5,2)
		DECLARE @GradeTitle nvarchar(10)
		DECLARE @GradePoint decimal(6,2)
		DECLARE @lCount int
		DECLARE @lDataSetID INT
		DECLARE @lMaxiMark Decimal(5,2)
		--SELECT @lDataSetID=GradeSetId FROM sAssessment.tExamMaster WHERE Id = @rCCEExamId 
		
		
		if @rCCEExamId=8
		BEGIN
		 SELECT @lDataSetID=GradeSetId FROM sAssessment.tCCEExamSetting WHERE CCEExamId = @rCCEExamId AND ClassId = @rClassId
		CREATE TABLE #tempGradeSetDetail
			(
				Id INT IDENTITY (1, 1),
				MinimumScore decimal(5,2),
				GradeTitle nvarchar(10),
				GradePoint decimal(6,2) 					 
			) 
			INSERT INTO #tempGradeSetDetail
			SELECT MinimumScore,GradeCode,GradePoint		
			FROM sAssessment.tGradeSetDetail where GradesetId=@lDataSetID
			order by Id Asc

		SELECT @lCount =  COUNT(Id) FROM #tempGradeSetDetail
		DECLARE @lloopCount int
		set @lloopCount=1
		SELECT @lCount =  COUNT(Id) FROM #tempGradeSetDetail
 set @lloopCount=1
 while (@lloopCount <= @lCount )
 BEGIN
	SELECT
		@MinimumScore =MinimumScore,
		@GradeTitle=GradeTitle,
		@GradePoint=GradePoint
		FROM #tempGradeSetDetail WHERE Id = @lloopCount
			
			update sAssessment.tCCEResultDetail Set GradePoint = @GradePoint Where  Grade = @GradeTitle AND AcademicId IN (Select Id From sStudent.tAcademic Where ClassId=@rClassId And BatchId=@rBatchId AND DivisionId=@rDivisionId)	
		 
		SET @lloopCount = @lloopCount + 1
		
 END
 	END   
 	--    Update sAssessment.tCCEResultDetail  Set FA = ROUND((FA1+FA2+FA3 +FA4),0) WHERE AcademicId IN (Select Id From sStudent.tAcademic Where ClassId=@rClassId And BatchId=@rBatchId)
		--Update sAssessment.tCCEResultDetail  Set SA = ROUND((SA1+SA2),0) WHERE AcademicId IN (Select Id From sStudent.tAcademic Where ClassId=@rClassId And BatchId=@rBatchId)
		--Update sAssessment.tCCEResultDetail  Set Term1 = ROUND((FA1+FA2+SA1),0) WHERE AcademicId IN (Select Id From sStudent.tAcademic Where ClassId=@rClassId And BatchId=@rBatchId)
		--Update sAssessment.tCCEResultDetail  Set Term2 = ROUND((FA3+FA4+SA2),0)  WHERE AcademicId IN (Select Id From sStudent.tAcademic Where ClassId=@rClassId And BatchId=@rBatchId)
		--Update sAssessment.tCCEResultDetail  Set TOTAL = ROUND((FA1+FA2+FA3 +FA4 + SA1 +SA2),0) WHERE AcademicId IN (Select Id From sStudent.tAcademic Where ClassId=@rClassId And BatchId=@rBatchId)
		
		--Update sAssessment.tCCEResultDetail  Set FAGradePoint = ROUND((GradePointFA1+GradePointFA2+GradePointFA3 +GradePointFA4)/4,0) WHERE AcademicId IN (Select Id From sStudent.tAcademic Where ClassId=@rClassId And BatchId=@rBatchId)
		--Update sAssessment.tCCEResultDetail  Set SAGradePoint = ROUND((GradePointSA1+GradePointSA2/2),0) WHERE AcademicId IN (Select Id From sStudent.tAcademic Where ClassId=@rClassId And BatchId=@rBatchId)
		--Update sAssessment.tCCEResultDetail  Set Term1GradePoint = ROUND((GradePointFA1+GradePointFA2+GradePointSA1)/3,0) WHERE AcademicId IN (Select Id From sStudent.tAcademic Where ClassId=@rClassId And BatchId=@rBatchId)
		--Update sAssessment.tCCEResultDetail  Set Term2GradePoint = ROUND((GradePointFA3+GradePointFA4+GradePointSA2)/3,0) WHERE AcademicId IN (Select Id From sStudent.tAcademic Where ClassId=@rClassId And BatchId=@rBatchId)
		
		--Update sAssessment.tCCEResultDetail  Set GRADEPOINT = ROUND((GradePointFA1+GradePointFA2+GradePointFA3)/3,0) WHERE Term2GradePoint = 0 AND AcademicId IN (Select Id From sStudent.tAcademic Where ClassId=@rClassId And BatchId=@rBatchId)
		--Update sAssessment.tCCEResultDetail  Set GRADEPOINT = ROUND((GradePointFA1+GradePointFA2+GradePointFA3 +GradePointFA4+GradePointSA1+GradePointSA2)/6,0) WHERE AcademicId IN (Select Id From sStudent.tAcademic Where ClassId=@rClassId And BatchId=@rBatchId)
		--AND Term2GradePoint <> 0 AND Term1GradePoint <> 0
	if(@rCCEExamId=9)
	BEGIN
		update CR set cgpa =  (CRD.GradePoint) from  sAssessment.tCCEResult CR 
		Inner Join (select Avg(GradePoint) AS GradePoint,AcademicId From sAssessment.tCCEResultDetail Group By ACademicId ) CRD 
		ON CR.AcademicId = CRD.AcademicId
		INNER JOIN sStudent.tAcademic A ON CR.AcademicId = A.Id
		AND A.ClassId=@rClassId And A.BatchId=@rBatchId AND A.DivisionId=@rDivisionId
		 --AND CR.AcademicId IN (Select Id From sStudent.tAcademic Where ClassId=@rClassId And BatchId=@rBatchId AND DivisionId=@rDivisionId)
	END
	if (@rCCEExamId=7)
	begin
	update CR set Term1CGPA =  (CRD.GradePoint) from  sAssessment.tCCEResult CR 
		Inner Join (select Avg(Term1GradePoint) AS GradePoint,AcademicId From sAssessment.tCCEResultDetail Group By ACademicId ) CRD 
		ON CR.AcademicId = CRD.AcademicId 
		INNER JOIN sStudent.tAcademic A ON CR.AcademicId = A.Id
		AND A.ClassId=@rClassId And A.BatchId=@rBatchId AND A.DivisionId=@rDivisionId
		--AND CR.AcademicId IN (Select Id From sStudent.tAcademic Where ClassId=@rClassId And BatchId=@rBatchId AND DivisionId=@rDivisionId)
	END
	if(@rCCEExamId=8)
	BEGIN
	update CR set Term2CGPA =  (CRD.GradePoint) from  sAssessment.tCCEResult CR 
		Inner Join (select Avg(Term2GradePoint) AS GradePoint,AcademicId From sAssessment.tCCEResultDetail Group By ACademicId ) CRD 
		ON CR.AcademicId = CRD.AcademicId 
		INNER JOIN sStudent.tAcademic A ON CR.AcademicId = A.Id
		AND A.ClassId=@rClassId And A.BatchId=@rBatchId AND A.DivisionId=@rDivisionId
		--AND CR.AcademicId IN (Select Id From sStudent.tAcademic Where ClassId=@rClassId And BatchId=@rBatchId AND DivisionId=@rDivisionId)
	
	END
		--SELECT 1 AS Result
	--COMMIT TRANSACTION		
	--END TRY
	
	--BEGIN CATCH 
	--	ROLLBACK TRANSACTION
	--	SELECT -1 AS Result
	--END CATCH	
END

GO

 

ALTER PROCEDURE [sAssessment].[pCCEResultDetailAdd]
	 
	     
            @rAcademicId bigint
		   ,@rClassSubjectId int
		   ,@rObtain decimal(6,2)		
		   ,@rExamOrder int
		   ,@rCCEExamId INT  -- CCEId
		   ,@rSubExamId INT  -- CCEId
		   ,@rOrgId int
		   ,@rIsPresent bit = null,
		   @rCCEGradePointMarks decimal(6,2)=0,
		   @rClassId int=0
		 
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	--BEGIN TRY
	
	-- BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 
	 DECLARE @lMaxiMark decimal(6,2)
	 SELECT  @lMaxiMark = Maximum FROM sAssessment.tExamDetail Where ExamId = @rSubExamId AND ClassSubjectId = @rClassSubjectId
	 DECLARE @lCCEResultDetailId BIGINT

SELECT @lCCEResultDetailId= ISNULL(AcademicId,0) From sAssessment.tCCEResultDetail Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
--Select @rObtain
 
IF ISNULL(@lCCEResultDetailId,0) = 0
	 BEGIN

	--EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAssessment.tCCEResultDetail', 0, 1, 1,@outNextNumber = @lNextNumber output	
	 
	INSERT INTO [sAssessment].[tCCEResultDetail]
			   (
				[AcademicId] 
			   ,[ClassSubjectId]
			   ,[GradePointFA1]
			   ,[GradePointFA2]
			   ,[GradePointSA1]
			   ,[GradePointFA3]
			   ,[GradePointFA4]
			   ,[GradePointSA2]
			   ,[UpdatedUserId]
			   ,[UpdatedDateTime]
			   )
		 VALUES
			   (
			    @rAcademicId
			   ,@rClassSubjectId
			   ,0.00
			   ,0.00
			   ,0.00
			   ,0.00
			   ,0.00
			   ,0.00
			   ,0
			   ,sCommon.fGetDate()
			   )
  
			 
     			IF(@rExamOrder=1) UPDATE [sAssessment].[tCCEResultDetail] SET [FA1]=ISNULL(@rObtain,0),IsPresentFA1=@rIsPresent,GRADEPOINTFA1 =(@rCCEGradePointMarks *ISNULL(@rObtain,0))/@lMaxiMark Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
			ELSE IF(@rExamOrder=2) UPDATE [sAssessment].[tCCEResultDetail] SET [FA2]=ISNULL(@rObtain,0),IsPresentFA2=@rIsPresent,GradePointFA2 =(@rCCEGradePointMarks * ISNULL(@rObtain,0))/@lMaxiMark Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
			ELSE IF(@rExamOrder=3) UPDATE [sAssessment].[tCCEResultDetail] SET [SA1]=ISNULL(@rObtain,0),IsPresentSA1=@rIsPresent,GradePointSA1 =(@rCCEGradePointMarks *ISNULL(@rObtain,0) )/@lMaxiMark Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
			ELSE IF(@rExamOrder=4) UPDATE [sAssessment].[tCCEResultDetail] SET [FA3]=ISNULL(@rObtain,0),IsPresentFA3=@rIsPresent,GradePointFA3 = (@rCCEGradePointMarks * ISNULL(@rObtain,0))/@lMaxiMark  Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
			ELSE IF(@rExamOrder=5) UPDATE [sAssessment].[tCCEResultDetail] SET [FA4]=ISNULL(@rObtain,0),IsPresentFA4=@rIsPresent,GradePointFA4 =(@rCCEGradePointMarks * ISNULL(@rObtain,0))/@lMaxiMark Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
			ELSE IF(@rExamOrder=6) UPDATE [sAssessment].[tCCEResultDetail] SET [SA2]=ISNULL(@rObtain,0),IsPresentSA2=@rIsPresent,GradePointSA2 =(@rCCEGradePointMarks *ISNULL(@rObtain,0) )/@lMaxiMark  Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
	
			UPDATE [sAssessment].[tCCEResultDetail] SET [FA]= ISNULL(FA1,0)+ISNULL(FA2,0)+ISNULL(FA3,0)+ISNULL(FA4,0),FAGradePoint=ROUND(GradePointFA1+GradePointFA2+GradePointFA3 +GradePointFA4,0) Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
			UPDATE [sAssessment].[tCCEResultDetail] SET [SA]=ISNULL(SA1,0)+ISNULL(SA2,0),SAGradePoint = ROUND( GradePointSA1+GradePointSA2  ,0) Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
			UPDATE [sAssessment].[tCCEResultDetail] SET [Term1]= ISNULL(FA1,0)+ISNULL(FA2,0)+ISNULL(SA1,0), Term1GradePoint = ROUND( GradePointFA1+GradePointFA2+GradePointSA1 ,0) Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
			UPDATE [sAssessment].[tCCEResultDetail] SET [Term2]=ISNULL(FA3,0)+ISNULL(FA4,0)+ISNULL(SA2,0),Term2GradePoint = ROUND( GradePointFA3+GradePointFA4+GradePointSA2 ,0) Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
			UPDATE [sAssessment].[tCCEResultDetail] SET [TOTAL]=ISNULL(FA1,0)+ISNULL(FA2,0)+ISNULL(FA3,0)+ISNULL(FA4,0)+ISNULL(SA1,0)+ISNULL(SA2,0) Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
		    SELECT @rAcademicId AS Result
	
		--COMMIT TRANSACTION         
	END	 
ELSE
	 BEGIN
	
	    --UPDATE  [sAssessment].[tCCEResultDetail]
	    --SET  
	    --     [UpdatedDateTime]=sCommon.fGetDate()
	    --  WHERE [AcademicId] =@rAcademicId
	     	 
	     
	        IF(@rExamOrder=1) UPDATE [sAssessment].[tCCEResultDetail] SET [FA1]=ISNULL(@rObtain,0),IsPresentFA1=@rIsPresent,GRADEPOINTFA1 =(@rCCEGradePointMarks *ISNULL(@rObtain,0))/@lMaxiMark Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
			ELSE IF(@rExamOrder=2) UPDATE [sAssessment].[tCCEResultDetail] SET [FA2]=ISNULL(@rObtain,0),IsPresentFA2=@rIsPresent,GradePointFA2 =(@rCCEGradePointMarks * ISNULL(@rObtain,0))/@lMaxiMark Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
			ELSE IF(@rExamOrder=3) UPDATE [sAssessment].[tCCEResultDetail] SET [SA1]=ISNULL(@rObtain,0),IsPresentSA1=@rIsPresent,GradePointSA1 =(@rCCEGradePointMarks *ISNULL(@rObtain,0) )/@lMaxiMark Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
			ELSE IF(@rExamOrder=4) UPDATE [sAssessment].[tCCEResultDetail] SET [FA3]=ISNULL(@rObtain,0),IsPresentFA3=@rIsPresent,GradePointFA3 = (@rCCEGradePointMarks * ISNULL(@rObtain,0))/@lMaxiMark  Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
			ELSE IF(@rExamOrder=5)UPDATE [sAssessment].[tCCEResultDetail] SET [FA4]=ISNULL(@rObtain,0),IsPresentFA4=@rIsPresent,GradePointFA4 =(@rCCEGradePointMarks * ISNULL(@rObtain,0))/@lMaxiMark Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
			ELSE UPDATE [sAssessment].[tCCEResultDetail] SET [SA2]=ISNULL(@rObtain,0),IsPresentSA2=@rIsPresent,GradePointSA2 =(@rCCEGradePointMarks *ISNULL(@rObtain,0) )/@lMaxiMark  Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
			
			UPDATE [sAssessment].[tCCEResultDetail] SET [FA]= ISNULL(FA1,0)+ISNULL(FA2,0)+ISNULL(FA3,0)+ISNULL(FA4,0),FAGradePoint=ROUND(GradePointFA1+GradePointFA2+GradePointFA3 +GradePointFA4,0) Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
			UPDATE [sAssessment].[tCCEResultDetail] SET [SA]=ISNULL(SA1,0)+ISNULL(SA2,0),SAGradePoint = ROUND( GradePointSA1+GradePointSA2  ,0) Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
			UPDATE [sAssessment].[tCCEResultDetail] SET [Term1]= ISNULL(FA1,0)+ISNULL(FA2,0)+ISNULL(SA1,0),Term1GradePoint = ROUND( GradePointFA1+GradePointFA2+GradePointSA1 ,0) Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
			UPDATE [sAssessment].[tCCEResultDetail] SET [Term2]=ISNULL(FA3,0)+ISNULL(FA4,0)+ISNULL(SA2,0),Term2GradePoint = ROUND( GradePointFA3+GradePointFA4+GradePointSA2 ,0) Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
			UPDATE [sAssessment].[tCCEResultDetail] SET [TOTAL]=ISNULL(FA1,0)+ISNULL(FA2,0)+ISNULL(FA3,0)+ISNULL(FA4,0)+ISNULL(SA1,0)+ISNULL(SA2,0) Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
			 
		 
			--SELECT @rAcademicId AS Result
	
	 END  
		
--Grade Evaluation
DECLARE @MinimumScore decimal(5,2)
DECLARE @GradeTitle nvarchar(10)
DECLARE @GradePoint decimal(6,2)
DECLARE @lCount int
DECLARE @lDataSetID INT  
--DECLARE @lClassId int

DECLARE @lTempMark decimal(6,2)
 

--SELECT @lDataSetID=GradeSetId FROM sAssessment.tExamDetail WHERE ExamId = @rCCEExamId AND ClassSubjectId = @rClassSubjectId
  --SELECT @lClassId = ClassId From sStudent.tAcademic Where Id =  @rAcademicId 	
  SELECT @lDataSetID=GradeSetId  FROM sAssessment.tCCEExamSetting WHERE CCEExamId = @rCCEExamId AND ClassId = @rClassId

CREATE TABLE #tempGradeSetDetail
	(
		Id INT IDENTITY (1, 1),
		MinimumScore decimal(5,2),
		GradeTitle nvarchar(10),
		GradePoint decimal(6,2) 					 
	) 
	INSERT INTO #tempGradeSetDetail
	SELECT MinimumScore,GradeCode,GradePoint		
	FROM sAssessment.tGradeSetDetail where GradesetId=@lDataSetID
	order by MinimumScore DESC

SELECT @lCount =  COUNT(Id) FROM #tempGradeSetDetail
DECLARE @lloopCount int
--set @lloopCount=1
while ( @lCount > 0 )
BEGIN
		SELECT @MinimumScore =MinimumScore,@GradeTitle=GradeTitle,@GradePoint=GradePoint
		FROM #tempGradeSetDetail WHERE Id = @lCount
		 
		IF @rExamOrder = 1 
		BEGIN				
			Update sAssessment.tCCEResultDetail  Set GradeFA1 = @GradeTitle,FA1Max=@lMaxiMark WHERE AcademicId=@rAcademicId AND ClassSubjectID=@rClassSubjectId AND (FA1 * 100)/@lMaxiMark  >= @MinimumScore 
			
		END
		IF @rExamOrder = 2 
		BEGIN							
			Update sAssessment.tCCEResultDetail  Set GradeFA2 = @GradeTitle,FA2Max=@lMaxiMark WHERE AcademicId=@rAcademicId AND ClassSubjectID=@rClassSubjectId AND (FA2 * 100)/@lMaxiMark >= @MinimumScore 
			
		END
		IF @rExamOrder = 3 
		BEGIN				
			Update sAssessment.tCCEResultDetail  Set GradeSA1 = @GradeTitle,SA1Max=@lMaxiMark WHERE AcademicId=@rAcademicId AND ClassSubjectID=@rClassSubjectId AND (SA1 * 100)/@lMaxiMark >= @MinimumScore 
			 
		END
		IF @rExamOrder = 4 
		BEGIN				
			Update sAssessment.tCCEResultDetail  Set GradeFA3 = @GradeTitle,FA3Max=@lMaxiMark WHERE AcademicId=@rAcademicId AND ClassSubjectID=@rClassSubjectId AND (FA3 * 100)/@lMaxiMark >= @MinimumScore 
			
		END
		IF @rExamOrder = 5 
		BEGIN				
			Update sAssessment.tCCEResultDetail  Set GradeFA4 = @GradeTitle,FA4Max=@lMaxiMark WHERE AcademicId=@rAcademicId AND ClassSubjectID=@rClassSubjectId AND (FA4 * 100)/@lMaxiMark >= @MinimumScore 
			 
		END
		IF @rExamOrder = 6 
		BEGIN		
			Update sAssessment.tCCEResultDetail  Set GradeSA2 = @GradeTitle,SA2Max=@lMaxiMark WHERE AcademicId=@rAcademicId AND ClassSubjectID=@rClassSubjectId AND (SA2 * 100)/@lMaxiMark >= @MinimumScore 
			 
		END
			SELECT @lTempMark = ISNULL(FA1MAX,0)+ISNULL(FA2MAX,0)+ISNULL(FA3MAX,0)+ISNULL(FA4MAX,0) FROM sAssessment.tCCEResultDetail WHERE AcademicId=@rAcademicId AND ClassSubjectID=@rClassSubjectId 
			IF @lTempMark <> 0 
			BEGIN
				Update sAssessment.tCCEResultDetail  Set FAGRADE = @GradeTitle WHERE AcademicId=@rAcademicId AND ClassSubjectID=@rClassSubjectId 
				AND (FA * 100)/@lTempMark >= @MinimumScore 
			END

SELECT @lTempMark = ISNULL(FA1MAX,0)+ISNULL(FA2MAX,0) FROM sAssessment.tCCEResultDetail WHERE AcademicId=@rAcademicId AND ClassSubjectID=@rClassSubjectId 
			IF @lTempMark <> 0 
			BEGIN
				Update sAssessment.tCCEResultDetail  Set [FATerm1] = @GradeTitle WHERE AcademicId=@rAcademicId AND ClassSubjectID=@rClassSubjectId 
				AND ((FA1+FA2) * 100)/@lTempMark >= @MinimumScore 
			END

SELECT @lTempMark = ISNULL(FA3MAX,0)+ISNULL(FA4MAX,0) FROM sAssessment.tCCEResultDetail WHERE AcademicId=@rAcademicId AND ClassSubjectID=@rClassSubjectId 
			IF @lTempMark <> 0 
			BEGIN
				Update sAssessment.tCCEResultDetail  Set [FATerm2] = @GradeTitle WHERE AcademicId=@rAcademicId AND ClassSubjectID=@rClassSubjectId 
				AND ((FA3+FA4) * 100)/@lTempMark >= @MinimumScore 
			END
			
			SELECT @lTempMark = ISNULL(SA1MAX,0)+ISNULL(SA2MAX,0) FROM sAssessment.tCCEResultDetail WHERE AcademicId=@rAcademicId AND ClassSubjectID=@rClassSubjectId 
			IF @lTempMark <> 0 
			BEGIN
				Update sAssessment.tCCEResultDetail  Set SAGRADE = @GradeTitle WHERE AcademicId=@rAcademicId AND ClassSubjectID=@rClassSubjectId 
				AND (SA * 100)/@lTempMark >= @MinimumScore 
			END
			
			SELECT @lTempMark = ISNULL(FA1MAX,0)+ISNULL(FA2MAX,0)+ISNULL(SA1MAX,0) FROM sAssessment.tCCEResultDetail WHERE AcademicId=@rAcademicId AND ClassSubjectID=@rClassSubjectId 
			IF @lTempMark <> 0 
			BEGIN
				Update sAssessment.tCCEResultDetail  Set Term1Grade = @GradeTitle WHERE AcademicId=@rAcademicId AND ClassSubjectID=@rClassSubjectId 
				AND (TERM1 * 100)/@lTempMark >= @MinimumScore 
			END
			
			SELECT @lTempMark = ISNULL(FA3MAX,0)+ISNULL(FA4MAX,0)+ISNULL(SA2MAX,0) FROM sAssessment.tCCEResultDetail WHERE AcademicId=@rAcademicId AND ClassSubjectID=@rClassSubjectId 
			IF @lTempMark <> 0 
			BEGIN	
				Update sAssessment.tCCEResultDetail  Set Term2Grade = @GradeTitle WHERE AcademicId=@rAcademicId AND ClassSubjectID=@rClassSubjectId 
				AND (TERM2 * 100)/@lTempMark >= @MinimumScore 
			END
		
			SELECT @lTempMark = ISNULL(FA1MAX,0)+ISNULL(FA2MAX,0)+ISNULL(SA1MAX,0)+ISNULL(FA1MAX,0)+ISNULL(FA2MAX,0)+ISNULL(SA1MAX,0) FROM sAssessment.tCCEResultDetail WHERE AcademicId=@rAcademicId AND ClassSubjectID=@rClassSubjectId 
			IF @lTempMark <> 0  
			BEGIN
				Update sAssessment.tCCEResultDetail  Set Grade = @GradeTitle WHERE AcademicId=@rAcademicId AND ClassSubjectID=@rClassSubjectId 
				AND (TOTAL * 100)/@lTempMark >= @MinimumScore 
			END 
		SET @lCount = @lCount - 1
 END
	--End Grade Evaluation	
--END	
--COMMIT TRANSACTION		
--	END TRY
	
--	BEGIN CATCH 
--		ROLLBACK TRANSACTION
--		SELECT -1 AS Result
--	END CATCH	
		
END

GO

ALTER PROCEDURE [sAssessment].[pCCEResultGenerate]
	
	@rClassId int,
	@rExamId int,
	@rBatchId int,
	@rOrgId int,
	@rExamOrder int,
	@rCCEExamId int,
	@rDivisionId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	DECLARE @lCount_MarkEntryStudent int
	DECLARE @lAcademicId bigint
	Declare @lCCESettingMaxMark decimal(6,2)
	
	SELECT @lCCESettingMaxMark=MaxMark  FROM sAssessment.tCCEExamSetting WHERE CCEExamId = @rExamOrder AND ClassId = @rClassId
	 
	CREATE TABLE #TempMarkEntryStudent(
	[AutoId] [int] identity,
	[AcademicId] [bigint] NOT NULL,
	[ExamId] [int] NULL,
	[OrgId] [int] NULL,
	[ClassId] [int] NULL,
	)
	 
	INSERT INTO #TempMarkEntryStudent 
	SELECT  
		SA.AcademicId,
		EM.Id AS ExamId,
		SA.OrgId,
		EM.ClassId
    FROM  
		sStudent.vStudentAcademic SA 
		INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = SA.ClassId 
		INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=SA.AcademicId
		--LEFT JOIN sAssessment.tCCEResult CR ON CR.AcademicId = SA.AcademicId
	WHERE 
		(EM.ClassId = @rClassId OR @rClassId = 0 )    
		AND (EM.Id=@rExamId OR @rExamId = 0)
		AND (EM.BatchId = @rBatchId or @rBatchId=0)
		AND SA.StatusId=1
		AND SA.BatchId=@rBatchId
		AND SA.DivisionId=@rDivisionId
    
    SET @lCount_MarkEntryStudent = 0
    SELECT @lCount_MarkEntryStudent = COUNT(AutoId) FROM #TempMarkEntryStudent
     
    --SELECT * FROM #TempMarkEntryStudent
    
	CREATE TABLE #TempCCEMarkEntry (
	[AutoId] [int] identity,
	[AcademicId] [bigint] NOT NULL ,
	[ResultDetailId] [bigint] NULL,
	[ClassSubjectId] [int] NULL,
	[Obtain] [decimal](5,2) NULL,
	[IsPresent] [bit] NULL,
	[ExamId] [int] NULL
	)
	
	WHILE (@lCount_MarkEntryStudent > 0)
	BEGIN
		
		SET @lAcademicId = 0
		SELECT @lAcademicId = AcademicId FROM #TempMarkEntryStudent WHERE AutoId = @lCount_MarkEntryStudent
	    EXEC sAssessment.pCCEResultAdd @rAcademicId=@lAcademicId,@rUpdatedUserId=0,@rOrgId=@rOrgId
			
		INSERT INTO #TempCCEMarkEntry 
		SELECT 
			SA.AcademicId,
			ISNULL(RD.ID,0) AS ResultDetailId,
			ED.ClassSubjectId AS ClassSubjectId,
			ISNULL(RD.Obtain,0) AS Obtain,
			RD.IsPresent,
			@rExamId
		FROM sAssessment.tResultDetail RD 
			INNER JOIN sAssessment.tResult R ON R.Id= RD.ResultId
			INNER JOIN 	sStudent.vStudentAcademic SA ON SA.AcademicId = R.AcademicId
			INNER JOIN sAssessment.tExamMaster EM ON  EM.Id=R.ExamId 	
			INNER JOIN sAssessment.tExamDetail ED ON  RD.ExamDetailId = ED.Id		
		WHERE
			(SA.ClassId = @rClassId)    
			AND SA.StatusId=1
			AND SA.BatchId=@rBatchId
			AND R.ExamId = @rExamId
			AND R.AcademicId = @lAcademicId
			AND SA.DivisionId =@rDivisionId
			--SELECT * FROM #TempCCEMarkEntry 
			
			DECLARE @lCount int
			SET @lCount = 0
			SELECT @lCount = COUNT(AcademicId) FROM #TempCCEMarkEntry
				WHILE (@lCount > 0)
				BEGIN
					DECLARE @lClassSubjectId int
				    DECLARE @lObtain decimal(5,2)
				    DECLARE @lIsPresent bit
				    DECLARE @rIsPresent bit
					SELECT @lClassSubjectId = ClassSubjectId, @lObtain = Obtain,@lIsPresent = IsPresent  FROM #TempCCEMarkEntry WHERE AcademicId = @lAcademicId AND ExamId = @rExamId AND AutoId = @lCount
					EXEC sAssessment.pCCEResultDetailAdd @rAcademicId=@lAcademicId,@rClassSubjectId=@lClassSubjectId,@rObtain=@lObtain,@rExamOrder=@rExamOrder,@rCCEExamId=@rCCEExamId,@rSubExamId=@rExamId,@rOrgId=@rOrgId,@rIsPresent=@lIsPresent,@rCCEGradePointMarks=@lCCESettingMaxMark,@rClassId=@rClassId
					SET @lCount = @lCount -1
				END
				TRUNCATE TABLE #TempCCEMarkEntry
				--DELETE FROM #TempCCEMarkEntry
				--DBCC CHECKIDENT (#TempCCEMarkEntry, RESEED, 1);
		SET @lCount_MarkEntryStudent = @lCount_MarkEntryStudent -1
	    EXEC sAssessment.pCCEResultDetailSubjectGradeUpdate @rExamOrder,@rCCEExamId,@rExamId,@rBatchId,@rClassId,@rDivisionId
	END
	DROP TABLE #TempMarkEntryStudent
	DROP TABLE #TempCCEMarkEntry
		SELECT 1 AS Result
END

GO

ALTER PROCEDURE [sAttendance].[pAttenanceRegisterGet]
 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rAttendanceTypeId smallint,
	 @rOrgId int,
	 @rForMonth smallint,
	 @rForYear smallint,
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rBatchId int = 0,
	 @rStudentCode nvarchar(20)='',
	 @rDepartmentId int = 0,
	 @rAcademicId bigint = 0,
	 @PageIndex int=0,
	 @rStatus int=0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
DECLARE @lFirstDate Date
	DECLARE @lResult nvarchar(max)
	DECLARE @li int 
	SET @li=1
	SET @lFirstDate = CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'/'+CONVERT(NVARCHAR(2),@rForMonth)+'/01'))	
	
	
DECLARE @lOrgId  int
--DECLARE @lSchoolRemark1  nvarchar(500)
--DECLARE @lSchoolRemark2  nvarchar(500)
--DECLARE @lSchoolRemark3  nvarchar(500)
DECLARE @lSchoolRequiredSignature  nvarchar(500)

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=1 where RGM.Id=1
 
-- select @lSchoolRequiredSignature as sig
 	
BEGIN 
	 CREATE Table #AttendanceRegistertempTable
(
	TID int identity(1,1),
	ClassDivisionTitle Nvarchar(50),
	Code nvarchar(50),
	RollNo int,
	AcademicId bigint,
	Name nvarchar(50),
	AttendanceTypeId int,
	ForYear int,
	ForMonth int,
	ForMonthInWord nvarchar(100),
	ClassId int,
	DivisionId int,
	ClassName nvarchar(50),
	DivisionName nvarchar(50),
	IsPresent bit,
	DayPart int,
	LeftDate date,
	ClassOrderIndex int,
	DivisionOrderIndex int,
	FooterSignature nvarchar(500),
	StatusId int,
	AttendanceDate date,
	AttendanceTagId int ,
	EmployeeName nvarchar(100)
)
Insert INTO #AttendanceRegistertempTable
(	
	ClassDivisionTitle,
	Code ,
	RollNo,
	AcademicId,
	Name,
	AttendanceTypeId,
	ForYear,
	ForMonth,
	ForMonthInWord,
	ClassId,
	DivisionId,
	ClassName,
	DivisionName,
	IsPresent,
	DayPart,
	LeftDate,
	ClassOrderIndex,
	DivisionOrderIndex,
	FooterSignature,
	StatusId,
	AttendanceDate,
	AttendanceTagId,
	EmployeeName
)
Select	    
	ISNULL(SA.ClassName + '-' + SA.DivisionName,'') AS ClassDivisionTitle,
	SA.Code,
	SA.RollNo,
	SA.AcademicId,
	SA.Name,
	SR.AttendanceTypeId ,
	YEAR(SR.AttendanceDate) AS ForYear,
	MONTH(SR.AttendanceDate) AS ForMonth,
	DATENAME(month, SR.AttendanceDate) AS ForMonthInWord,
	SA.ClassId,
	SA.DivisionId,
	SA.ClassName,Sa.DivisionName,
  
	--(CASE SR.IsPresent WHEN 1 THEN 'P' 
	--	WHEN 0 THEN 'A'
	--ELSE  ' ' END )AS  IsPresent,		
	SR.IsPresent,
	 day(SR.AttendanceDate) AS DayPart,
	 
	 A.LeftDate,
	 CM.OrderIndex AS ClassOrderIndex,
	 DM.OrderIndex As DivisionOrderIndex,
	@lSchoolRequiredSignature AS FooterSignature,
	 SA.StatusId,
	 SR.AttendanceDate As AttendanceDate,
	 SR.AttendanceTagId,
	 EM.FirstName+' ' + EM.LastName AS EmployeeName
	 --,
	 --SR.IsPresent
	 
	 
    from
            sStudent.vStudentAcademic SA 
            INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.AcademicId 
            INNER JOIN sStudent.tStudentAdmission A ON SA.StudentId = A.StudentId
            INNER JOIN sSetup.tClassMaster CM ON CM.Id = SA.ClassId
            INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = CM.OrgId
            INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=SA.DivisionId
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId
            
			
            
             WHERE  
	        ((SR.AttendanceTypeId=@rAttendanceTypeId) OR (@rAttendanceTypeId= 0))
	         AND ((SA.OrgId=@rOrgId) OR (@rOrgId= 0))
	          AND ((SA.BatchId=@rBatchId) OR (@rBatchId= 0))
	          AND ((YEAR(SR.AttendanceDate)=@rForYear) OR (@rForYear= 0))
	          AND ((MONTH(SR.AttendanceDate)=@rForMonth) OR (@rForMonth= 0))
	           AND ((SA.ClassId=@rClassId) OR (@rClassId= 0))
	           AND ((SA.Code=@rStudentCode) OR (@rStudentCode=''))
	           AND ((SA.AcademicId=@rAcademicId) OR (@rAcademicId=0))	           
				AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
	           AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId= 0))
	           AND ((SA.StatusId=@rStatus)OR (@rStatus=0))

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

SELECT 
@li AS DayPart,
 [sAttendance].[fWeekHOffHolidayGet](@rForYear,@rForMonth,@li,@rBatchId,@rDivisionId,'',@rOrgId) 
SET @li = @li + 1
END

 

SELECT  
			@lFirstDate AS LastDate,
			LeftDate,
            @rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			PivotTable.AcademicId,
			ClassDivisionTitle,isnull(Code,'') as Code,isnull(RollNo,0) as RollNo,
			isnull(Name,'') as Name,isnull(AttendanceTypeId,0) as AttendanceTypeId,ForYear,
			ForMonth,ClassId,ClassName,DivisionId,
			DivisionName,
			 
			ForMonthInWord,
			(ISNULL(TC.TCount,0) - ISNULL(AC.ACount,0)) AS PresentCount,
			 ISNULL(TC.TCount,0) AS AttendanceCount,
		      ISNULL(AC.ACount,0) As  AbsentCount,
		       ISNULL(PC.PCount,0) As  PresentUpto,
		       ClassOrderIndex,
		       DivisionOrderIndex,
		       FooterSignature,				 
			0 AS TotalPresent ,
	 		 isnull([1],'') AS P1,
			isnull([2],'') AS P2,
			isnull([3],'') AS P3,
			isnull([4],'') AS P4,
			isnull([5],'') AS P5,
			isnull([6],'') AS P6,
			isnull([7],'') AS P7,
			isnull([8],'') AS P8,
			isnull([9],'') AS P9,
			isnull([10],'') AS P10,
			isnull([11],'') AS P11,
			isnull([12],'') AS P12,
			isnull([13],'') AS P13,
			isnull([14],'') AS P14,
			isnull([15],'') AS P15,
			isnull([16],'') AS P16,
			isnull([17],'') AS P17,
			isnull([18],'') AS P18,
			isnull([19],'') AS P19,
			isnull([20],'') AS P20,
			isnull([21],'') AS P21,
			isnull([22],'') AS P22,
			isnull([23],'') AS P23,
			isnull([24],'') AS P24,
			isnull([25],'') AS P25,
			isnull([26],'') AS P26,
			isnull([27],'') AS P27,
			isnull([28],'') AS P28,
			isnull([29],'') AS P29,
			isnull([30],'') AS P30,
			isnull([31],'') AS P31, 
			 EmployeeName ,
 
sCommon.fGetDaysInMonth ( @rForMonth,@rForYear) AS DaysInMonth 
--,
--AttendanceTagId

 
FROM
(
	Select --TID, 
		ISNULL(ClassName + '-' + DivisionName,'') AS ClassDivisionTitle,
		Code,
		RollNo,
		AcademicId,
		Name,
		AttendanceTypeId ,
		YEAR(ST.AttendanceDate) AS ForYear,
		MONTH(ST.AttendanceDate) AS ForMonth,
		DATENAME(month, ST.AttendanceDate) AS ForMonthInWord,
		ClassId,
		DivisionId,
		ClassName,
		DivisionName,
		(
			CASE  WHEN IsPresent = 1 AND ST.AttendanceTagId = 1 THEN 'LC' 
				  WHEN IsPresent = 1 AND ST.AttendanceTagId = 2 THEN 'EL' 
			      WHEN IsPresent = 1  THEN 'P' 
				  WHEN IsPresent = 0 THEN 'A'
				  ELSE  DT.Value END 
		)AS  IsPresent,		
		day(ST.AttendanceDate) AS DayPart,
		LeftDate
		,
		ClassOrderIndex,
		DivisionOrderIndex,
		FooterSignature,EmployeeName
      -- DO NOT ADD ANY FIELD HERE WITHOUT PERMISSION OF RAJENDRA
	 FROM 
		#AttendanceRegistertempTable ST 
		INNER JOIN #TempDaysTempTable DT ON DT.DayPart = ST.DayPart
	 WHERE
		((LeftDate >= @lFirstDate) OR ISNULL(LeftDate,'') = '')
) AS SourceTable 
 
	           
	        
PIVOT
(	
MIN(IsPresent)
FOR DayPart IN ([0], [1], [2], [3], [4],[5],[6],[7],[8],[9],[10],[11],[12],[13],[14],[15],[16],[17],[18],[19],[20],[21],[22],[23],[24],[25],[26],[27],[28],[29],[30],[31])
) AS PivotTable
	LEFT JOIN
	(
		Select  AcademicId AS AcademicId, COUNT(1) AS TCount 
		   FROM  
				#AttendanceRegistertempTable
		    
			GROUP BY  AcademicId
    ) TC ON TC.AcademicId = PivotTable.AcademicId
    
	LEFT JOIN
	(
		Select AcademicId AS AcademicId, COUNT(1) AS ACount 
		   FROM  #AttendanceRegistertempTable
		    WHERE   IsPresent = 0	 		
            
			GROUP BY  AcademicId
    ) AC ON AC.AcademicId = PivotTable.AcademicId
	LEFT JOIN
	(SELECT A.Id AS AcademicId, COUNT(1) AS PCount  FROM sAttendance.tStudentRegister SR 
			INNER JOIN sStudent.tAcademic A ON SR.AcademicId = A.Id 
		   INNER JOIN sStudent.tStudentMaster SA ON A.StudentId = SA.Id
		   INNER JOIN sSetup.tClassMaster CM ON A.ClassId = CM.Id
			WHERE  
			 SR.AttendanceDate < (convert(date,CONVERT(nvarchar(10), @rForYear)+ '/' +  CONVERT(nvarchar(10), @rForMonth) + '/' + '01' ))
			AND SR.IsPresent = 1	    		
            --AND (SA.StatusId = 1)
	        AND ((SR.AttendanceTypeId=@rAttendanceTypeId) OR (@rAttendanceTypeId= 0))
	        AND ((SA.OrgId=@rOrgId) OR (@rOrgId= 0))
	        AND ((A.BatchId=@rBatchId) OR (@rBatchId= 0))	          
	        AND ((A.ClassId=@rClassId) OR (@rClassId= 0))
	        AND ((SA.Code=@rStudentCode) OR (@rStudentCode=''))
	        AND ((A.Id=@rAcademicId) OR (@rAcademicId=0))	           
			AND ((CM.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))				
	        AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId= 0))
			GROUP BY A.Id
    ) PC ON PC.AcademicId = PivotTable.AcademicId
 
 
    ORDER BY RollNo;
 

select * from #TempDaysTempTable
 

drop table #AttendanceRegistertempTable	  
drop table #TempDaysTempTable
	
	
END


GO

ALTER PROCEDURE [sAssessment].[pCCEResultDetailSubjectGradeUpdate]
	  
	
	  @rExamOrder INT
	 ,@rCCEExamId INT
	 ,@rSubExamId INT
	 ,@rBatchId INT
	 ,@rClassId INT,
	 @rDivisionId int
	
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 	
--BEGIN TRY
-- BEGIN TRANSACTION	

	
		DECLARE @MinimumScore decimal(5,2)
		DECLARE @GradeTitle nvarchar(10)
		DECLARE @GradePoint decimal(6,2)
		DECLARE @lCount int
		DECLARE @lDataSetID INT
		DECLARE @lMaxiMark Decimal(5,2)
		--SELECT @lDataSetID=GradeSetId FROM sAssessment.tExamMaster WHERE Id = @rCCEExamId 
		
		
		if @rCCEExamId=8
		BEGIN
		 SELECT @lDataSetID=GradeSetId FROM sAssessment.tCCEExamSetting WHERE CCEExamId = @rCCEExamId AND ClassId = @rClassId
		CREATE TABLE #tempGradeSetDetail
			(
				Id INT IDENTITY (1, 1),
				MinimumScore decimal(5,2),
				GradeTitle nvarchar(10),
				GradePoint decimal(6,2) 					 
			) 
			INSERT INTO #tempGradeSetDetail
			SELECT MinimumScore,GradeCode,GradePoint		
			FROM sAssessment.tGradeSetDetail where GradesetId=@lDataSetID
			order by Id Asc

		SELECT @lCount =  COUNT(Id) FROM #tempGradeSetDetail
		DECLARE @lloopCount int
		set @lloopCount=1
		SELECT @lCount =  COUNT(Id) FROM #tempGradeSetDetail
 set @lloopCount=1
 while (@lloopCount <= @lCount )
 BEGIN
	SELECT
		@MinimumScore =MinimumScore,
		@GradeTitle=GradeTitle,
		@GradePoint=GradePoint
		FROM #tempGradeSetDetail WHERE Id = @lloopCount
			
			update sAssessment.tCCEResultDetail Set GradePoint = @GradePoint Where  Grade = @GradeTitle AND AcademicId IN (Select Id From sStudent.tAcademic Where ClassId=@rClassId And BatchId=@rBatchId AND DivisionId=@rDivisionId)	
		 
		SET @lloopCount = @lloopCount + 1
		
 END
 	END   
 	--    Update sAssessment.tCCEResultDetail  Set FA = ROUND((FA1+FA2+FA3 +FA4),0) WHERE AcademicId IN (Select Id From sStudent.tAcademic Where ClassId=@rClassId And BatchId=@rBatchId)
		--Update sAssessment.tCCEResultDetail  Set SA = ROUND((SA1+SA2),0) WHERE AcademicId IN (Select Id From sStudent.tAcademic Where ClassId=@rClassId And BatchId=@rBatchId)
		--Update sAssessment.tCCEResultDetail  Set Term1 = ROUND((FA1+FA2+SA1),0) WHERE AcademicId IN (Select Id From sStudent.tAcademic Where ClassId=@rClassId And BatchId=@rBatchId)
		--Update sAssessment.tCCEResultDetail  Set Term2 = ROUND((FA3+FA4+SA2),0)  WHERE AcademicId IN (Select Id From sStudent.tAcademic Where ClassId=@rClassId And BatchId=@rBatchId)
		--Update sAssessment.tCCEResultDetail  Set TOTAL = ROUND((FA1+FA2+FA3 +FA4 + SA1 +SA2),0) WHERE AcademicId IN (Select Id From sStudent.tAcademic Where ClassId=@rClassId And BatchId=@rBatchId)
		
		--Update sAssessment.tCCEResultDetail  Set FAGradePoint = ROUND((GradePointFA1+GradePointFA2+GradePointFA3 +GradePointFA4)/4,0) WHERE AcademicId IN (Select Id From sStudent.tAcademic Where ClassId=@rClassId And BatchId=@rBatchId)
		--Update sAssessment.tCCEResultDetail  Set SAGradePoint = ROUND((GradePointSA1+GradePointSA2/2),0) WHERE AcademicId IN (Select Id From sStudent.tAcademic Where ClassId=@rClassId And BatchId=@rBatchId)
		--Update sAssessment.tCCEResultDetail  Set Term1GradePoint = ROUND((GradePointFA1+GradePointFA2+GradePointSA1)/3,0) WHERE AcademicId IN (Select Id From sStudent.tAcademic Where ClassId=@rClassId And BatchId=@rBatchId)
		--Update sAssessment.tCCEResultDetail  Set Term2GradePoint = ROUND((GradePointFA3+GradePointFA4+GradePointSA2)/3,0) WHERE AcademicId IN (Select Id From sStudent.tAcademic Where ClassId=@rClassId And BatchId=@rBatchId)
		
		--Update sAssessment.tCCEResultDetail  Set GRADEPOINT = ROUND((GradePointFA1+GradePointFA2+GradePointFA3)/3,0) WHERE Term2GradePoint = 0 AND AcademicId IN (Select Id From sStudent.tAcademic Where ClassId=@rClassId And BatchId=@rBatchId)
		--Update sAssessment.tCCEResultDetail  Set GRADEPOINT = ROUND((GradePointFA1+GradePointFA2+GradePointFA3 +GradePointFA4+GradePointSA1+GradePointSA2)/6,0) WHERE AcademicId IN (Select Id From sStudent.tAcademic Where ClassId=@rClassId And BatchId=@rBatchId)
		--AND Term2GradePoint <> 0 AND Term1GradePoint <> 0
	if(@rCCEExamId=9)
	BEGIN
		update CR set cgpa =  (CRD.GradePoint) from  sAssessment.tCCEResult CR 
		Inner Join (select Avg(GradePoint) AS GradePoint,AcademicId From sAssessment.tCCEResultDetail Group By ACademicId ) CRD 
		ON CR.AcademicId = CRD.AcademicId
		INNER JOIN sStudent.tAcademic A ON CR.AcademicId = A.Id
		AND A.ClassId=@rClassId And A.BatchId=@rBatchId AND A.DivisionId=@rDivisionId
		 --AND CR.AcademicId IN (Select Id From sStudent.tAcademic Where ClassId=@rClassId And BatchId=@rBatchId AND DivisionId=@rDivisionId)
	END
	if (@rCCEExamId=7)
	begin
	update CR set Term1CGPA =  (CRD.GradePoint) from  sAssessment.tCCEResult CR 
		Inner Join (select Avg(Term1GradePoint) AS GradePoint,AcademicId From sAssessment.tCCEResultDetail Group By ACademicId ) CRD 
		ON CR.AcademicId = CRD.AcademicId 
		INNER JOIN sStudent.tAcademic A ON CR.AcademicId = A.Id
		AND A.ClassId=@rClassId And A.BatchId=@rBatchId AND A.DivisionId=@rDivisionId
		--AND CR.AcademicId IN (Select Id From sStudent.tAcademic Where ClassId=@rClassId And BatchId=@rBatchId AND DivisionId=@rDivisionId)
	END
	if(@rCCEExamId=8)
	BEGIN
	update CR set Term2CGPA =  (CRD.GradePoint) from  sAssessment.tCCEResult CR 
		Inner Join (select Avg(Term2GradePoint) AS GradePoint,AcademicId From sAssessment.tCCEResultDetail Group By ACademicId ) CRD 
		ON CR.AcademicId = CRD.AcademicId 
		INNER JOIN sStudent.tAcademic A ON CR.AcademicId = A.Id
		AND A.ClassId=@rClassId And A.BatchId=@rBatchId AND A.DivisionId=@rDivisionId
		--AND CR.AcademicId IN (Select Id From sStudent.tAcademic Where ClassId=@rClassId And BatchId=@rBatchId AND DivisionId=@rDivisionId)
	
	END
		--SELECT 1 AS Result
	--COMMIT TRANSACTION		
	--END TRY
	
	--BEGIN CATCH 
	--	ROLLBACK TRANSACTION
	--	SELECT -1 AS Result
	--END CATCH	
END





GO


 


ALTER PROCEDURE [sStudent].[pStudentFullGet]
	 
	@rClassId int=0,
	@rDivisionId int=0,
	@rRollNo int=NULL,
	@rOrgId int,
	@rBatchId int,
	@rCode nvarchar(20),
	@rStatusId smallint=0,
	@rFirstName nvarchar(100)='',
	@rLastName nvarchar(100)='',
	@rOrgGroupId int,
	@rOrgGroupBatchId int,
	@rDepartmentId int,
	@rBatchStatusId smallint=0
	
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 
		BEGIN
			SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
			SET @rLastName = sCommon.fSearchStringGet(@rLastName)
		END
	IF(@rRollNo IS NULL)
	BEGIN
	SELECT 
			SF.AcademicId,
			SF.StudentId,
			SF.FirstName + ' ' + SF.MiddleName + ' ' + SF.LastName AS Name,
			SF.FirstName,
			SF.LastName,
			SF.Code,
			SF.BatchId,
			BM.Title AS BatchName,
			SF.ClassId,
			SF.ClassName,
			SF.DivisionId,
			SF.DivisionName,
			SF.Number,
			ISNULL(SF.RollNo,0) AS RollNo,
			SF.StatusId,
			SF.StatusName,
			SF.OrgId,
			ISNULL(OM.DisplayTitle,'') AS DisplayTitle,
			SB.EnrollmentStatusId AS  BatchStatusId,
			ISNULL(BS.Title,'') AS BatchStatus,
			SB.Remark,
			ISNULL(SB.StatusDate,'') AS  StatusDate
			 
  FROM 
           sStudent.vStudentFull SF
           LEFT JOIN sSetup.tBatchMaster BM
           ON BM.Id=SF.BatchId
           LEFT JOIN sSetup.tOrganizationMaster OM ON OM.Id=SF.OrgId
           INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id=OM.OrgGroupId AND OGM.Id=@rOrgGroupId
           LEFT JOIN sStudent.tEnrollmentStatusStudent SB ON SB.AcademicId = SF.AcademicId
           LEFT JOIN sStudent.tEnrollmentStatusMaster BS ON BS.Id = SB.EnrollmentStatusId
           --LEFT JOIN sStudent.tStudentBatchStatus SB ON SB.AcademicId = SF.AcademicId
           --LEFT JOIN sStudent.tBatchStatusMaster BS ON BS.Id = SB.BatchStatusId
  WHERE 
 
		((SF.ClassId=@rClassId)OR(@rClassId=0))
		AND((SF.DivisionId=@rDivisionId)OR(@rDivisionId=0))
		AND((SF.Code= @rCode) OR (ISNULL(@rCode,'') = '')) 
		AND((SF.FirstName like @rFirstName) OR (ISNULL(@rFirstName,'') = '')) 
		AND((SF.LastName like @rLastName) OR (ISNULL(@rLastName,'') = '')) 
		AND((SF.StatusId=@rStatusId)OR(@rStatusId=0))	
		AND((SF.BatchId=@rBatchId)OR(@rBatchId=0))	
		AND((OM.Id=@rOrgId)OR(@rOrgId=0))
		AND (OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId = 0)
		AND((SF.DepartmentId=@rDepartmentId)OR(@rDepartmentId=0))
		AND ((SB.EnrollmentStatusId =@rBatchStatusId) OR (@rBatchStatusId=0))
ORDER BY SF.ClassId,SF.DivisionId,SF.RollNo
END
ELSE
BEGIN

	SELECT 
			SF.AcademicId,
			SF.StudentId,
			SF.Name,
			SF.FirstName,
			SF.LastName,
			SF.Code,
			SF.BatchId,
			BM.Title AS BatchName,
			SF.ClassId,
			SF.ClassName,
			SF.DivisionId,
			SF.DivisionName,
			SF.Number,
			ISNULL(SF.RollNo,0) AS RollNo,
			SF.StatusId,
			SF.StatusName,
			SF.OrgId,
			ISNULL(OM.DisplayTitle,'') AS DisplayTitle,
			SB.EnrollmentStatusId AS  BatchStatusId,
			ISNULL(BS.Title,'') AS BatchStatus,
			SB.Remark,
			ISNULL(SB.StatusDate,'') AS  StatusDate 
  FROM 
           sStudent.vStudentFull SF
           LEFT JOIN sSetup.tBatchMaster BM
           ON BM.Id=SF.BatchId
           LEFT JOIN sSetup.tOrganizationMaster OM ON OM.Id=SF.OrgId
           INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id=OM.OrgGroupId AND OGM.Id=@rOrgGroupId
           LEFT JOIN sStudent.tEnrollmentStatusStudent SB ON SB.AcademicId = SF.AcademicId
           LEFT JOIN sStudent.tEnrollmentStatusMaster BS ON BS.Id = SB.EnrollmentStatusId
           --LEFT JOIN sStudent.tStudentBatchStatus SB ON SB.AcademicId = SF.AcademicId
           --LEFT JOIN sStudent.tBatchStatusMaster BS ON BS.Id = SB.BatchStatusId
  WHERE 
 
		((SF.ClassId=@rClassId)OR(@rClassId=0))
		AND((SF.DivisionId=@rDivisionId)OR(@rDivisionId=0))
		AND((SF.Code= @rCode) OR (ISNULL(@rCode,'') = '')) 
		AND((SF.FirstName like @rFirstName) OR (ISNULL(@rFirstName,'') = '')) 
		AND((SF.LastName like @rLastName) OR (ISNULL(@rLastName,'') = '')) 
		AND(SF.RollNo=@rRollNo)	
		AND((SF.StatusId=@rStatusId)OR(@rStatusId=0))	
		AND((SF.BatchId=@rBatchId)OR(@rBatchId=0))	
		AND((OM.Id=@rOrgId)OR(@rOrgId=0))
		AND (OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId = 0)
		AND((SF.DepartmentId=@rDepartmentId)OR(@rDepartmentId=0))
		AND ((SB.EnrollmentStatusId =@rBatchStatusId) OR (@rBatchStatusId=0))
ORDER BY SF.ClassId,SF.DivisionId,SF.RollNo
END
  
		
END
GO
 

ALTER PROCEDURE [sStudent].[pStudentFullWithPhotoGet]
	 
	@rClassId int=0,
	@rDivisionId int=0,
	@rRollNo int=NULL,
	@rOrgId int,
	@rBatchId int,
	@rCode nvarchar(20),
	@rStatusId smallint=0,
	@rFirstName nvarchar(100)='',
	@rLastName nvarchar(100)='',
	@rOrgGroupId int,
	@rOrgGroupBatchId int=0,
	@rDepartmentId int=0,
	@rBatchStatusId smallint=0
	
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 
		BEGIN
			SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
			SET @rLastName = sCommon.fSearchStringGet(@rLastName)
		END
	IF(@rRollNo IS NULL)
	BEGIN
	SELECT 
			SF.AcademicId,
			SF.StudentId,
			SF.Name,
			SF.FirstName,
			SF.LastName,
			SF.Code,
			SF.BatchId,
			BM.Title AS BatchName,
			SF.ClassId,
			SF.ClassName,
			SF.DivisionId,
			SF.DivisionName,
			SF.Number,
			ISNULL(SF.RollNo,0) AS RollNo,
			SF.StatusId,
			SF.StatusName,
			SF.OrgId,
			ISNULL(SF.StudentPhoto, CONVERT(VARBINARY(MAX), 0)) AS StudentPhoto,
			ISNULL(OM.DisplayTitle,'') AS DisplayTitle,  
			SB.EnrollmentStatusId AS  BatchStatusId,
			ISNULL(BS.Title,'') AS BatchStatus,
			SB.Remark,
			ISNULL(SB.StatusDate,'') AS  StatusDate
  FROM 
           sStudent.vStudentFull SF
           LEFT JOIN sSetup.tBatchMaster BM
           ON BM.Id=SF.BatchId
           LEFT JOIN sSetup.tOrganizationMaster OM ON OM.Id=SF.OrgId
           INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id=OM.OrgGroupId AND OGM.Id=@rOrgGroupId
           LEFT JOIN sStudent.tEnrollmentStatusStudent SB ON SB.AcademicId = SF.AcademicId
           LEFT JOIN sStudent.tEnrollmentStatusMaster BS ON BS.Id = SB.EnrollmentStatusId
         
           --LEFT JOIN sStudent.tStudentBatchStatus SB ON SB.AcademicId = SF.AcademicId
           --LEFT JOIN sStudent.tBatchStatusMaster BS ON BS.Id = SB.BatchStatusId
           
  WHERE 
 
		((SF.ClassId=@rClassId)OR(@rClassId=0))
		AND((SF.DivisionId=@rDivisionId)OR(@rDivisionId=0))
		AND((SF.Code= @rCode) OR (ISNULL(@rCode,'') = '')) 
		AND((SF.FirstName like @rFirstName) OR (ISNULL(@rFirstName,'') = '')) 
		AND((SF.LastName like @rLastName) OR (ISNULL(@rLastName,'') = '')) 
		AND((SF.StatusId=@rStatusId)OR(@rStatusId=0))	
		AND((SF.BatchId=@rBatchId)OR(@rBatchId=0))	
		AND((OM.Id=@rOrgId)OR(@rOrgId=0))	
		AND (OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId = 0)
		AND((SF.DepartmentId=@rDepartmentId)OR(@rDepartmentId=0))
		AND ((SB.EnrollmentStatusId =@rBatchStatusId) OR (@rBatchStatusId=0))
		--AND ((SB.BatchStatusId =@rBatchStatusId) OR (@rBatchStatusId=0))
ORDER BY SF.ClassId,SF.DivisionId,SF.RollNo
END
ELSE
BEGIN
	SELECT 
			SF.AcademicId,
			SF.StudentId,
			SF.Name,
			SF.FirstName,
			SF.LastName,
			SF.Code,
			SF.BatchId,
			BM.Title AS BatchName,
			SF.ClassId,
			SF.ClassName,
			SF.DivisionId,
			SF.DivisionName,
			SF.Number,
			ISNULL(SF.RollNo,0) AS RollNo,
			SF.StatusId,
			SF.StatusName,
			SF.OrgId,
			ISNULL(SF.StudentPhoto, CONVERT(VARBINARY(MAX), 0)) AS StudentPhoto,
			ISNULL(OM.DisplayTitle,'') AS DisplayTitle,
			SB.EnrollmentStatusId AS  BatchStatusId,
			ISNULL(BS.Title,'') AS BatchStatus,
			SB.Remark,
			ISNULL(SB.StatusDate,'') AS  StatusDate  
  FROM 
           sStudent.vStudentFull SF
           LEFT JOIN sSetup.tBatchMaster BM
           ON BM.Id=SF.BatchId
           LEFT JOIN sSetup.tOrganizationMaster OM ON OM.Id=SF.OrgId
           INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id=OM.OrgGroupId AND OGM.Id=@rOrgGroupId 
            LEFT JOIN sStudent.tEnrollmentStatusStudent SB ON SB.AcademicId = SF.AcademicId
           LEFT JOIN sStudent.tEnrollmentStatusMaster BS ON BS.Id = SB.EnrollmentStatusId
           --LEFT JOIN sStudent.tStudentBatchStatus SB ON SB.AcademicId = SF.AcademicId
           --LEFT JOIN sStudent.tBatchStatusMaster BS ON BS.Id = SB.BatchStatusId
  WHERE 
 
		((SF.ClassId=@rClassId)OR(@rClassId=0))
		AND((SF.DivisionId=@rDivisionId)OR(@rDivisionId=0))
		AND((SF.Code= @rCode) OR (ISNULL(@rCode,'') = '')) 
		AND((SF.FirstName like @rFirstName) OR (ISNULL(@rFirstName,'') = '')) 
		AND((SF.LastName like @rLastName) OR (ISNULL(@rLastName,'') = '')) 
		AND(SF.RollNo=@rRollNo)	
		AND((SF.StatusId=@rStatusId)OR(@rStatusId=0))	
		AND((SF.BatchId=@rBatchId)OR(@rBatchId=0))	
		AND((OM.Id=@rOrgId)OR(@rOrgId=0))	
		AND (OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId = 0)
		AND((SF.DepartmentId=@rDepartmentId)OR(@rDepartmentId=0))
		AND ((SB.EnrollmentStatusId =@rBatchStatusId) OR (@rBatchStatusId=0))
		--AND ((SB.BatchStatusId =@rBatchStatusId) OR (@rBatchStatusId=0))
ORDER BY SF.ClassId,SF.DivisionId,SF.RollNo

END
  
		
END

GO

 
 
 -- exec [sAttendance].[pAttenanceRegisterGet] '','',1,1001,6,2014,100100001,100100001,100100001,'',0,0
ALTER PROCEDURE [sAttendance].[pAttenanceRegisterGet]
 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rAttendanceTypeId smallint,
	 @rOrgId int,
	 @rForMonth smallint,
	 @rForYear smallint,
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rBatchId int = 0,
	 @rStudentCode nvarchar(20)='',
	 @rDepartmentId int = 0,
	 @rAcademicId bigint = 0,
	 @PageIndex int=0,
	 @rStatus int=0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
DECLARE @lFirstDate Date
	DECLARE @lResult nvarchar(max)
	DECLARE @li int 
	SET @li=1
	SET @lFirstDate = CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'/'+CONVERT(NVARCHAR(2),@rForMonth)+'/01'))	
	
	
DECLARE @lOrgId  int
--DECLARE @lSchoolRemark1  nvarchar(500)
--DECLARE @lSchoolRemark2  nvarchar(500)
--DECLARE @lSchoolRemark3  nvarchar(500)
DECLARE @lSchoolRequiredSignature  nvarchar(500)

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=1 where RGM.Id=1
 
-- select @lSchoolRequiredSignature as sig
 	
BEGIN 
	 CREATE Table #AttendanceRegistertempTable
(
	TID int identity(1,1),
	ClassDivisionTitle Nvarchar(50),
	Code nvarchar(50),
	RollNo int,
	AcademicId bigint,
	Name nvarchar(50),
	AttendanceTypeId int,
	ForYear int,
	ForMonth int,
	ForMonthInWord nvarchar(100),
	ClassId int,
	DivisionId int,
	ClassName nvarchar(50),
	DivisionName nvarchar(50),
	IsPresent bit,
	DayPart int,
	LeftDate date,
	ClassOrderIndex int,
	DivisionOrderIndex int,
	FooterSignature nvarchar(500),
	StatusId int,
	AttendanceDate date,
	AttendanceTagId int ,
	EmployeeName nvarchar(100)
)
Insert INTO #AttendanceRegistertempTable
(	
	ClassDivisionTitle,
	Code ,
	RollNo,
	AcademicId,
	Name,
	AttendanceTypeId,
	ForYear,
	ForMonth,
	ForMonthInWord,
	ClassId,
	DivisionId,
	ClassName,
	DivisionName,
	IsPresent,
	DayPart,
	LeftDate,
	ClassOrderIndex,
	DivisionOrderIndex,
	FooterSignature,
	StatusId,
	AttendanceDate,
	AttendanceTagId,
	EmployeeName
)
Select	    
	ISNULL(SA.ClassName + '-' + SA.DivisionName,'') AS ClassDivisionTitle,
	SA.Code,
	SA.RollNo,
	SA.AcademicId,
	SA.Name,
	SR.AttendanceTypeId ,
	YEAR(SR.AttendanceDate) AS ForYear,
	MONTH(SR.AttendanceDate) AS ForMonth,
	DATENAME(month, SR.AttendanceDate) AS ForMonthInWord,
	SA.ClassId,
	SA.DivisionId,
	SA.ClassName,Sa.DivisionName,
  
	--(CASE SR.IsPresent WHEN 1 THEN 'P' 
	--	WHEN 0 THEN 'A'
	--ELSE  ' ' END )AS  IsPresent,		
	SR.IsPresent,
	 day(SR.AttendanceDate) AS DayPart,
	 
	 A.LeftDate,
	 CM.OrderIndex AS ClassOrderIndex,
	 DM.OrderIndex As DivisionOrderIndex,
	@lSchoolRequiredSignature AS FooterSignature,
	 SA.StatusId,
	 SR.AttendanceDate As AttendanceDate,
	 SR.AttendanceTagId,
	 EM.FirstName+' ' + EM.LastName AS EmployeeName
	 --,
	 --SR.IsPresent
	 
	 
    from
            sStudent.vStudentAcademic SA 
            INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.AcademicId 
            INNER JOIN sStudent.tStudentAdmission A ON SA.StudentId = A.StudentId
            INNER JOIN sSetup.tClassMaster CM ON CM.Id = SA.ClassId
            INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = CM.OrgId
            INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=SA.DivisionId
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId
            
			
            
             WHERE  
	        ((SR.AttendanceTypeId=@rAttendanceTypeId) OR (@rAttendanceTypeId= 0))
	         AND ((SA.OrgId=@rOrgId) OR (@rOrgId= 0))
	          AND ((SA.BatchId=@rBatchId) OR (@rBatchId= 0))
	          AND ((YEAR(SR.AttendanceDate)=@rForYear) OR (@rForYear= 0))
	          AND ((MONTH(SR.AttendanceDate)=@rForMonth) OR (@rForMonth= 0))
	           AND ((SA.ClassId=@rClassId) OR (@rClassId= 0))
	           AND ((SA.Code=@rStudentCode) OR (@rStudentCode=''))
	           AND ((SA.AcademicId=@rAcademicId) OR (@rAcademicId=0))	           
				AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
	           AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId= 0))
	           AND ((SA.StatusId=@rStatus)OR (@rStatus=0))

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

SELECT 
@li AS DayPart,
 [sAttendance].[fWeekHOffHolidayGet](@rForYear,@rForMonth,@li,@rBatchId,@rDivisionId,'',@rOrgId) 
SET @li = @li + 1
END

 

SELECT  
			@lFirstDate AS LastDate,
			LeftDate,
            @rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			PivotTable.AcademicId,
			ClassDivisionTitle,isnull(Code,'') as Code,isnull(RollNo,0) as RollNo,
			isnull(Name,'') as Name,isnull(AttendanceTypeId,0) as AttendanceTypeId,ForYear,
			ForMonth,ClassId,ClassName,DivisionId,
			DivisionName,
			 
			ForMonthInWord,
			(ISNULL(TC.TCount,0) - ISNULL(AC.ACount,0)) AS PresentCount,
			 ISNULL(TC.TCount,0) AS AttendanceCount,
		      ISNULL(AC.ACount,0) As  AbsentCount,
		       ISNULL(PC.PCount,0) As  PresentUpto,
		       ClassOrderIndex,
		       DivisionOrderIndex,
		       FooterSignature,				 
			0 AS TotalPresent ,
			[sAttendance].[fWeekHOffHolidayGet](@rForYear ,@rForMonth ,1 ,@rBatchId ,@rDivisionId , isnull([1],''),@rOrgId )  AS P1,
			[sAttendance].[fWeekHOffHolidayGet](@rForYear ,@rForMonth ,2 ,@rBatchId ,@rDivisionId , isnull([2],''),@rOrgId )  AS P2,
			[sAttendance].[fWeekHOffHolidayGet](@rForYear ,@rForMonth ,3 ,@rBatchId ,@rDivisionId , isnull([3],''),@rOrgId )  AS P3,
			[sAttendance].[fWeekHOffHolidayGet](@rForYear ,@rForMonth ,4 ,@rBatchId ,@rDivisionId , isnull([4],''),@rOrgId )  AS P4,
			[sAttendance].[fWeekHOffHolidayGet](@rForYear ,@rForMonth ,5 ,@rBatchId ,@rDivisionId , isnull([5],''),@rOrgId )  AS P5,
			[sAttendance].[fWeekHOffHolidayGet](@rForYear ,@rForMonth ,6 ,@rBatchId ,@rDivisionId , isnull([6],''),@rOrgId ) AS P6,
			[sAttendance].[fWeekHOffHolidayGet](@rForYear ,@rForMonth ,7 ,@rBatchId ,@rDivisionId , isnull([7],''),@rOrgId ) AS P7,
			[sAttendance].[fWeekHOffHolidayGet](@rForYear ,@rForMonth ,8 ,@rBatchId ,@rDivisionId , isnull([8],''),@rOrgId ) AS P8,
			[sAttendance].[fWeekHOffHolidayGet](@rForYear ,@rForMonth ,9 ,@rBatchId ,@rDivisionId , isnull([9],''),@rOrgId ) AS P9,
			[sAttendance].[fWeekHOffHolidayGet](@rForYear ,@rForMonth ,10 ,@rBatchId ,@rDivisionId , isnull([10],''),@rOrgId ) AS P10,
			[sAttendance].[fWeekHOffHolidayGet](@rForYear ,@rForMonth ,11 ,@rBatchId ,@rDivisionId , isnull([11],''),@rOrgId ) AS P11,
			[sAttendance].[fWeekHOffHolidayGet](@rForYear ,@rForMonth ,12 ,@rBatchId ,@rDivisionId , isnull([12],''),@rOrgId ) AS P12,
			[sAttendance].[fWeekHOffHolidayGet](@rForYear ,@rForMonth ,13 ,@rBatchId ,@rDivisionId , isnull([13],''),@rOrgId ) AS P13,
			[sAttendance].[fWeekHOffHolidayGet](@rForYear ,@rForMonth ,14 ,@rBatchId ,@rDivisionId , isnull([14],''),@rOrgId ) AS P14,
			[sAttendance].[fWeekHOffHolidayGet](@rForYear ,@rForMonth ,15 ,@rBatchId ,@rDivisionId , isnull([15],''),@rOrgId ) AS P15,
			[sAttendance].[fWeekHOffHolidayGet](@rForYear ,@rForMonth ,16 ,@rBatchId ,@rDivisionId , isnull([16],''),@rOrgId ) AS P16,
			[sAttendance].[fWeekHOffHolidayGet](@rForYear ,@rForMonth ,17 ,@rBatchId ,@rDivisionId , isnull([17],''),@rOrgId ) AS P17,
			[sAttendance].[fWeekHOffHolidayGet](@rForYear ,@rForMonth ,18 ,@rBatchId ,@rDivisionId , isnull([18],''),@rOrgId ) AS P18,
			[sAttendance].[fWeekHOffHolidayGet](@rForYear ,@rForMonth ,19 ,@rBatchId ,@rDivisionId , isnull([19],''),@rOrgId ) AS P19,
			[sAttendance].[fWeekHOffHolidayGet](@rForYear ,@rForMonth ,20 ,@rBatchId ,@rDivisionId , isnull([20],''),@rOrgId ) AS P20,
			[sAttendance].[fWeekHOffHolidayGet](@rForYear ,@rForMonth ,21 ,@rBatchId ,@rDivisionId , isnull([21],''),@rOrgId ) AS P21,
			[sAttendance].[fWeekHOffHolidayGet](@rForYear ,@rForMonth ,22 ,@rBatchId ,@rDivisionId , isnull([22],''),@rOrgId ) AS P22,
			[sAttendance].[fWeekHOffHolidayGet](@rForYear ,@rForMonth ,23 ,@rBatchId ,@rDivisionId , isnull([23],''),@rOrgId ) AS P23,
			[sAttendance].[fWeekHOffHolidayGet](@rForYear ,@rForMonth ,24 ,@rBatchId ,@rDivisionId , isnull([24],''),@rOrgId ) AS P24,
			[sAttendance].[fWeekHOffHolidayGet](@rForYear ,@rForMonth ,25 ,@rBatchId ,@rDivisionId , isnull([25],''),@rOrgId ) AS P25,
			[sAttendance].[fWeekHOffHolidayGet](@rForYear ,@rForMonth ,26 ,@rBatchId ,@rDivisionId , isnull([26],''),@rOrgId ) AS P26,
			[sAttendance].[fWeekHOffHolidayGet](@rForYear ,@rForMonth ,27 ,@rBatchId ,@rDivisionId , isnull([27],''),@rOrgId ) AS P27,
			[sAttendance].[fWeekHOffHolidayGet](@rForYear ,@rForMonth ,28 ,@rBatchId ,@rDivisionId , isnull([28],''),@rOrgId ) AS P28,
			[sAttendance].[fWeekHOffHolidayGet](@rForYear ,@rForMonth ,29 ,@rBatchId ,@rDivisionId , isnull([29],''),@rOrgId ) AS P29,
			[sAttendance].[fWeekHOffHolidayGet](@rForYear ,@rForMonth ,30 ,@rBatchId ,@rDivisionId , isnull([30],''),@rOrgId ) AS P30,
			[sAttendance].[fWeekHOffHolidayGet](@rForYear ,@rForMonth ,31 ,@rBatchId ,@rDivisionId , isnull([31],''),@rOrgId ) AS P31,
			 
			
	 	--	 isnull([1],'') AS P1,
			--isnull([2],'') AS P2,
			--isnull([3],'') AS P3,
			--isnull([4],'') AS P4,
			--isnull([5],'') AS P5,
			--isnull([6],'') AS P6,
			--isnull([7],'') AS P7,
			--isnull([8],'') AS P8,
			--isnull([9],'') AS P9,
			--isnull([10],'') AS P10,
			--isnull([11],'') AS P11,
			--isnull([12],'') AS P12,
			--isnull([13],'') AS P13,
			--isnull([14],'') AS P14,
			--isnull([15],'') AS P15,
			--isnull([16],'') AS P16,
			--isnull([17],'') AS P17,
			--isnull([18],'') AS P18,
			--isnull([19],'') AS P19,
			--isnull([20],'') AS P20,
			--isnull([21],'') AS P21,
			--isnull([22],'') AS P22,
			--isnull([23],'') AS P23,
			--isnull([24],'') AS P24,
			--isnull([25],'') AS P25,
			--isnull([26],'') AS P26,
			--isnull([27],'') AS P27,
			--isnull([28],'') AS P28,
			--isnull([29],'') AS P29,
			--isnull([30],'') AS P30,
			--isnull([31],'') AS P31, 
			 EmployeeName ,
 
sCommon.fGetDaysInMonth ( @rForMonth,@rForYear) AS DaysInMonth 
--,
--AttendanceTagId

 
FROM
(
	Select --TID, 
		ISNULL(ClassName + '-' + DivisionName,'') AS ClassDivisionTitle,
		Code,
		RollNo,
		AcademicId,
		Name,
		AttendanceTypeId ,
		YEAR(ST.AttendanceDate) AS ForYear,
		MONTH(ST.AttendanceDate) AS ForMonth,
		DATENAME(month, ST.AttendanceDate) AS ForMonthInWord,
		ClassId,
		DivisionId,
		ClassName,
		DivisionName,
		(
			CASE  WHEN IsPresent = 1 AND ST.AttendanceTagId = 1 THEN 'LC' 
				  WHEN IsPresent = 1 AND ST.AttendanceTagId = 2 THEN 'EL' 
			      WHEN IsPresent = 1  THEN 'P' 
				  WHEN IsPresent = 0 THEN 'A'
				  ELSE  DT.Value END 
		)AS  IsPresent,		
		day(ST.AttendanceDate) AS DayPart,
		LeftDate
		,
		ClassOrderIndex,
		DivisionOrderIndex,
		FooterSignature,EmployeeName
      -- DO NOT ADD ANY FIELD HERE WITHOUT PERMISSION OF RAJENDRA
	 FROM 
		#AttendanceRegistertempTable ST 
		INNER JOIN #TempDaysTempTable DT ON DT.DayPart = ST.DayPart
	 WHERE
		((LeftDate >= @lFirstDate) OR ISNULL(LeftDate,'') = '')
) AS SourceTable 
 
	           
	        
PIVOT
(	
MIN(IsPresent)
FOR DayPart IN ([0], [1], [2], [3], [4],[5],[6],[7],[8],[9],[10],[11],[12],[13],[14],[15],[16],[17],[18],[19],[20],[21],[22],[23],[24],[25],[26],[27],[28],[29],[30],[31])
) AS PivotTable
	LEFT JOIN
	(
		Select  AcademicId AS AcademicId, COUNT(1) AS TCount 
		   FROM  
				#AttendanceRegistertempTable
		    
			GROUP BY  AcademicId
    ) TC ON TC.AcademicId = PivotTable.AcademicId
    
	LEFT JOIN
	(
		Select AcademicId AS AcademicId, COUNT(1) AS ACount 
		   FROM  #AttendanceRegistertempTable
		    WHERE   IsPresent = 0	 		
            
			GROUP BY  AcademicId
    ) AC ON AC.AcademicId = PivotTable.AcademicId
	LEFT JOIN
	(SELECT A.Id AS AcademicId, COUNT(1) AS PCount  FROM sAttendance.tStudentRegister SR 
			INNER JOIN sStudent.tAcademic A ON SR.AcademicId = A.Id 
		   INNER JOIN sStudent.tStudentMaster SA ON A.StudentId = SA.Id
		   INNER JOIN sSetup.tClassMaster CM ON A.ClassId = CM.Id
			WHERE  
			 SR.AttendanceDate < (convert(date,CONVERT(nvarchar(10), @rForYear)+ '/' +  CONVERT(nvarchar(10), @rForMonth) + '/' + '01' ))
			AND SR.IsPresent = 1	    		
            --AND (SA.StatusId = 1)
	        AND ((SR.AttendanceTypeId=@rAttendanceTypeId) OR (@rAttendanceTypeId= 0))
	        AND ((SA.OrgId=@rOrgId) OR (@rOrgId= 0))
	        AND ((A.BatchId=@rBatchId) OR (@rBatchId= 0))	          
	        AND ((A.ClassId=@rClassId) OR (@rClassId= 0))
	        AND ((SA.Code=@rStudentCode) OR (@rStudentCode=''))
	        AND ((A.Id=@rAcademicId) OR (@rAcademicId=0))	           
			AND ((CM.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))				
	        AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId= 0))
			GROUP BY A.Id
    ) PC ON PC.AcademicId = PivotTable.AcademicId
 
 
    ORDER BY RollNo;
 

select * from #TempDaysTempTable
 

drop table #AttendanceRegistertempTable	  
drop table #TempDaysTempTable
	
	
END

GO

 

ALTER PROCEDURE [sAssessment].[pRptResultSheetStandardMultiExamGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rSubjectId int = 0,
	 @rBatchId int=0,
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rExamId int,
	 @rCode nvarchar(20)='',
	 @rFromRollNo int=0,
	 @rToRollNo int=0,
	 @rFromRank int=0,
	 @rToRank int=0,
	 @rGrade nvarchar(20)='',
	 @rResultId bigint=0,
	 @rStatusId int=0,
	 @rAcademicId bigint=0,
	 @rFromPercentage decimal(5,2)=0,
	 @rToPercentage decimal(5,2)=0,
	 @rIsDetail 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),
@GradeSetId int , @IsIncludeSubExam bit
SELECT @GradeSetId = GradesetId,
	   @IsIncludeSubExam = ISNULL(IsIncludeSubExam,0)  FROM sAssessment.tExamMaster WHERE Id = @rExamId
SELECT @GradeString = [sAssessment].[fGradeStringGet](@GradeSetId)
 
--#TempAllExam
	CREATE TABLE #TempAllExam
	(
		AcademicIdText nvarchar(20),
		ExamIdText nvarchar(20),
		CoScholasticScopeIdText nvarchar(20),
		IsDisplayMonthlyAttendanceText nvarchar(20),
		
		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),
		IsMarksInDecimal bit,
		column_visible bit,
		--Obtain decimal(5,2),
		Percentile decimal(5,2),
		--ClassSubject nvarchar(100),
		ResultDetailId bigint,
		ResultId bigint,	
		Remark1 nvarchar(150),
		Remark2 nvarchar(150),
		Remark3 nvarchar(150),
		DisplayTitle nvarchar(150),		
		IsRankNo bit, 
		IsGrade bit,
		IsPercentile bit,
		IsPercentage bit,
		IsSubjectPercentile bit,
		IsProcessResult bit,
		IsNegativeMarks bit,
		IsIncludeCoScholastic bit,
		IsOnPrePrinted bit,
		IsDisplayPhoto bit,
		IsDisplayBirthDate bit,
		IsLockForEdit bit,
		IsDisplaySchoolName bit,			
		IsDisplayAttendance bit,
		IsDisplayHeightWeight bit,
		IsResultStatus bit,
		FooterAdjustmentText nvarchar(max),
		DetailAdjustmentText nvarchar(max),
		FooterAdjustment smallint,
		DetailAdjustment smallint,
		ResultRemark nvarchar(200),
		DateOfBirth date,
		HeightTerm1 decimal(5,2),
		WeightTerm1 decimal(5,2),
		HeightTerm2 decimal(5,2),
		WeightTerm2 decimal(5,2),
		HeightAnnual decimal(5,2),
		WeightAnnual decimal(5,2),
		PresentDaysTerm1 smallint,
		PresentDaysTerm2 smallint,
		PresentDaysAnnual smallint,
		TotalDaysTerm1 smallint,
		TotalDaysTerm2 smallint,
		TotalDaysAnnual smallint,
		TotalMarkTerm1 decimal(8,2),
		TotalObtainTerm1 decimal(8,2),
		PercentageTerm1 decimal(8,2),
		RankNumberTerm1 int,
		ResultGradeTerm1 NVarchar(50),
		PercentileTerm1 decimal(8,2),
		ResultStatusTerm1 Nvarchar(20),		   
		TotalMarkTerm2 decimal(8,2),
		TotalObtainTerm2 decimal(8,2),
		PercentageTerm2 decimal(8,2),
		RankNumberTerm2 int,
		ResultGradeTerm2 NVarchar(50),
		PercentileTerm2 decimal(8,2),
		ResultStatusTerm2 Nvarchar(20), 
		TermScopeId tinyint,		 
		StudentPhoto varbinary(max),
		GradeString nvarchar(1000),
		IsDisplayGradeString bit,		 
		IsDisplayInMarksheet bit,
		IsShowSubjectGrade bit,
		IsIncludeInTotal bit,
		ClassSubjectID int,
		SubjectId int,
		--Maximum decimal(5,2),
		SubjectOrderIndex smallint,
		SubjectGrade NVarchar(50),
		SubjectName NVarchar(150),
		SubjectCode Nvarchar(50),	
		SubjectMinimum decimal(8,2),		
		SubjectMaximum decimal(8,2),
		SubjectObtain  decimal(8,2),
		
		Exam1Name Nvarchar(150),		
		TotalMarks1 decimal(8,2),		
		TotalObtain1 decimal(8,2),
		Percentage1 decimal(8,2),
		RankNumber1 int,
		ResultGrade1 NVarchar(50),
		Percentile1 decimal(8,2),
		ResultStatus1 Nvarchar(20),
		
		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),
		
		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) ,
		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),
		DecimalFormat nvarchar(10),
		SubjectRemark nvarchar(1000),
		GraceMark decimal(5,2)
		 
		
	)	
	 --print 'temp created'    	
	INSERT INTO  #TempAllExam 
	(
	AcademicIdText,
	ExamIdText,
	CoScholasticScopeIdText,
	IsDisplayMonthlyAttendanceText,
	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,
	DecimalFormat,
	SubjectRemark,
	GraceMark
	
 
 
	 
	)
	SELECT 
		Convert(nvarchar(20),A.Id),
		Convert(nvarchar(20),@rExamId),
		Convert(nvarchar(20),EM.CoScholasticScopeId),
		Convert(nvarchar(20),ISNULL(EM.IsDisplayMonthlyAttendance,0)),
		A.Id,
		ISNULL(ESGM.Title,'') AS EXAMNAME,
		StuM.Code AS StudCode,
		StuM.FirstName+' '+StuM.MiddleName+' '+StuM.LastName AS Name,
		A.RollNo,
		R.ResultStatus,
		CM.DisplayTitle AS ClassName,
		DM.DisplayTitle AS Division,
		R.TotalMarks AS TotalMark,
		R.TotalObtain,
		R.Percentage,
		R.RankNumber,
		R.ResultGrade,


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

		ISNULL(EM.Remark1,'') AS Remark1,
		ISNULL(EM.Remark2,'') AS Remark2,
		ISNULL(EM.Remark3,'') AS Remark3,
		EM.DisplayTitle,
		EM.IsRankNo, 
		EM.IsGrade,
		EM.IsPercentile,
		EM.IsPercentage,
		EM.IsSubjectPercentile,
		EM.IsProcessResult,
		EM.IsNegativeMarks,
		EM.IsIncludeCoScholastic,
		EM.IsOnPrePrinted,
		EM.IsDisplayPhoto,
		EM.IsDisplayBirthDate,
		EM.IsLockForEdit,
		EM.IsDisplaySchoolName,			
		EM.IsDisplayAttendance,
		EM.IsDisplayHeightWeight,
		EM.IsResultStatus,
		REPLICATE(',',EM.FooterAdjustment) AS FooterAdjustmentText,
		REPLICATE(',',EM.DetailAdjustment) AS DetailAdjustmentText,
		EM.FooterAdjustment,
		EM.DetailAdjustment,
		ISNULL(R.ResultRemark,'') AS ResultRemark,
		SO.DateOfBirth,
		AD.HeightTerm1,
		AD.WeightTerm1,
		AD.HeightTerm2,
		AD.WeightTerm2,
		AD.HeightAnnual,
		AD.WeightAnnual,
		AD.PresentDaysTerm1,
		AD.PresentDaysTerm2,
		AD.PresentDaysAnnual,
		AD.TotalDaysTerm1,
		AD.TotalDaysTerm2,
		AD.TotalDaysAnnual,
		EM.TermScopeId,
		(CASE EM.IsDisplayPhoto WHEN 1 THEN
			SI.StudentPhoto
		ELSE NULL END)AS StudentPhoto,
		@GradeString 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(EM.DecimalFormat,0) AS DecimalFormat,
		ISNULL(RD.Remark,'') AS SubjectRemark,
		RD.GraceMark
		
		
		 
			
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 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										
					 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 
				    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)+'=EM.ExamMaximum
					 From						
						sAssessment.tResult R						
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON  T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
						
		execute(@query)
		
		
	set @lCount = @lCount -1
	end
	

	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
							 
					 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					 
					 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)
		
	
	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

 
ALTER PROCEDURE [sHostel].[pHostelFeeUpdate]
	 
	@rClassId int, 
	@rFeeHeadId int,
	@rCreatedUserId bigint,
	@rOrgId int,
	@rOrgGroupId int,
	@rBatchId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION





	CREATE TABLE #TempHostelFee
	(	Id int IDENTITY,	   
	    AcademicId bigint,
	    RoomId int,
	    FeeSetupId int,		 
		Amount Decimal(12,2),
		ReceiptAmount  Decimal(12,2)
    )
	 INSERT INTO #TempHostelFee
	 SELECT	  
	 A.AcademicId,
	 AR.RoomId,
	 FS.Id,	 
	 RCM.RoomCharge,
	 sFee.fStudentFeeSetupReceiptAmountGet(AcademicId,Fs.Id)
	 FROM sHostel.tAssignRoom AR
	 INNER JOIN sHostel.tRoomMaster   RM ON AR.RoomId = RM.Id 
	 INNER JOIN sHostel.tRoomCategoryMaster RCM ON RM.RoomCategoryId = RCM.Id
	 INNER JOIN sStudent.vStudentAcademic A ON AR.SourceId = A.StudentId  AND Ar.SourceTypeId = 2003
	 INNER JOIN sFee.tFeeSetup FS ON A.ClassId = FS.ClassId AND A.AdmissionCategoryId = FS.AdmissionCategoryId AND FS.BatchId = A.BatchId
	 INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id 	 
	 INNER JOIN sFee.tFeeHeadMaster FHM ON FM.FeeHeadId = FHM.Id
	 WHERE  
	   FHM.Number = 1002
	 AND FHM.OrgGroupId = @rOrgGroupId
	 AND A.BatchId = @rBatchId
	 AND FS.IsVariable = 1
	 AND FS.IsOptional = 1
	 

--IF EXISTS(SELECT SOURCEID From sFee.tFeeAllocation WHERE
--SourceTypeId = 2003 AND SourceId NOT IN (SELECT AcademicId FROM #TempHostelFee RD WHERE ReceiptAmount > 0))
--BEGIN
--DROP TABLE	#TempHostelFee
--SELECT -101 AS Result    
--RETURN
--END


MERGE sFee.tFeeOptional FO
USING #TempHostelFee RD
ON FO.FeeSetupId = RD.FeeSetupId AND FO.SourceTypeId = 2001 AND FO.SourceId = RD.AcademicId
--WHEN MATCHED AND
--  bi.Quantity + bo.Quantity = 0 THEN
--  DELETE
--WHEN MATCHED THEN
--  UPDATE
--  SET FA.VariableAmount = RD.Amount
WHEN NOT MATCHED BY TARGET THEN
INSERT (FeeSetupId,SourceTypeId,SourceId,BatchId)   
 VALUES (RD.FeeSetupId,2001, RD.AcademicId,@rBatchId )
-- WHEN NOT MATCHED  BY SOURCE   THEN
--DELETE
;
	 	 
MERGE sFee.tFeeAllocation FA
USING #TempHostelFee RD
ON FA.FeeSetupId = RD.FeeSetupId AND FA.SourceTypeId = 2001 AND FA.SourceId = RD.AcademicId
--WHEN MATCHED AND
--  bi.Quantity + bo.Quantity = 0 THEN
--  DELETE
WHEN MATCHED AND RD.ReceiptAmount <= RD.Amount  THEN
  UPDATE
  SET FA.VariableAmount = RD.Amount
WHEN NOT MATCHED BY TARGET THEN
  INSERT (SourceTypeId, SourceId, FeeSetupId,VariableAmount,DiscountAmount,AdditionalAmount,NotApplicableAmount,Remark,ReferenceTypeId,ReferenceSourceId,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime)
  VALUES (2001, RD.AcademicId,RD.FeeSetupId,RD.Amount,0,0,0,'',0,0,@rCreatedUserId,getdate(),@rCreatedUserId,getdate())
--WHEN NOT MATCHED BY SOURCE THEN
--DELETE
;
	DROP TABLE	#TempHostelFee
	
		SELECT 1 AS Result   
	COMMIT TRANSACTION
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END



GO

ALTER PROCEDURE [sCommunication].[pQueryListv2Get]
	 
	 
	 @rOrgGroupBatchId int,
	 @rCreatedUserId bigint	
	  	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			
BEGIN 
	 
	  
	SELECT 
			QM.Id AS QueryId,
			QCM.Id AS QueryCategoryId,
			ISNULL(QCM.Title,'') AS QueryCategoryMaster,
			QM.Title,
			QM.Remark,
			CONVERT(VARCHAR(25), QM.CreatedDateTime, 100) AS CreatedDateTime,
			QM.StatusId,
			ISNULL(sm.Title,'') AS StatusMaster,
			QM.IsAssigneeView,
			QM.IsUserView,
			QM.CreatedUserId AS QueryCreatedUserId
  FROM 
			sCommunication.tQuery QM
		INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QM.QueryCategoryId=QCM.Id AND QCM.IsObsolete=0
        INNER JOIN sCommon.tStatusMaster SM ON SM.Id=QM.StatusId
        INNER JOIN sSecurity.tUser U ON QM.CreatedUserId = U.Id
  WHERE 
			QM.OrgGroupBatchId=@rOrgGroupBatchId
		AND QM.CreatedUserId=@rCreatedUserId
		
		order by QM.Id desc
        
END


GO

 

ALTER PROCEDURE [sCommunication].[pViewQueryRemarkv2Get]
	 
	 @rQueryId bigint,
	 @rUserId bigint
		 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 
	
	DECLARE	@lUserSourceTypeId smallint

	SELECT  @lUserSourceTypeId = SourceTypeId FROM sSecurity.tUser WHERE Id = @rUserId

		
	IF @lUserSourceTypeId = 2003
	 BEGIN
	  UPDATE sCommunication.tQuery SET IsUserView = 1	WHERE Id = @rQueryId
	 END
	ELSE IF @lUserSourceTypeId = 95
	 BEGIN
	  UPDATE sCommunication.tQuery SET IsAssigneeView = 1	WHERE Id = @rQueryId
	 END
	 
	SELECT 
			QC.Id,
			QC.QueryId,
			QC.Remark,
			U.DisplayTitle AS UserName,
			CONVERT(VARCHAR(25), QC.CreatedDateTime, 100) AS CreatedDateTime,
			QC.CreatedUserId AS CommentCreatedUserId,
			Q.CreatedUserId AS QueryCreatedUserId
	FROM 
			sCommunication.tQueryComment QC
		INNER JOIN sCommunication.tQuery Q ON Q.Id=QC.QueryId
		INNER JOIN sCommunication.tQueryCategoryMaster QCM ON Q.QueryCategoryId=QCM.Id AND QCM.IsObsolete=0
		INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId
		
	WHERE 
			QC.QueryId = @rQueryId
			--AND Q.CreatedUserId = @rUserId 
			order by QC.Id desc
END




GO

ALTER PROCEDURE [sActivity].[pEventAttendanceGet]
	 
	 
	 @rEventScheduleId int,
	 @rDivisionId int=0,
	 @rDepartmentId int=0,
	 @rOrgId smallint,
	 @rBatchId int=0
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 		
		-- For Student Deatils
		IF(@rDivisionId != 0)
		BEGIN 
			SELECT
				vSA.AcademicId AS SourceId,
				vSA.Code,
				vSA.RollNo,
				vSA.Name,
				ISNULL(EAT.IsSelfPresent,0) AS IsSelfPresent,
				ISNULL(EAT.IsFatherPresent,0) AS IsFatherPresent,
				ISNULL(EAT.IsMotherPresent,0) AS IsMotherPresent,
				ISNULL(EAT.IsGuardianPresent,0) AS IsGuardianPresent,
				CONVERT (bit ,CASE WHEN EAT.SourceId IS NULL OR EAT.EventScheduleId!=@rEventScheduleId THEN 0 ELSE 1 END) AS IsObsolete,
				vSA.BatchId
			FROM 
				sStudent.vStudentAcademic vSA
				INNER JOIN sActivity.tEventAssign EA 
					ON EA.SourceId=vSA.DivisionId AND EA.SourceTypeId=2005 AND EA.EventScheduleId=@rEventScheduleId
				LEFT JOIN sActivity.tEventAttendance EAT 
					ON EAT.EventScheduleId = EA.EventScheduleId AND EAT.SourceId = vSA.AcademicId AND EAT.SourceTypeId = 2001
			WHERE
				vSA.OrgId=@rOrgId AND vSA.DivisionId = @rDivisionId
				AND vSA.BatchId = @rBatchId
			ORDER BY vSA.RollNo	
		END
		
		-- For Employee Deatils
		IF(@rDepartmentId != 0)
		BEGIN 
			SELECT
				vECD.EmployeeId AS SourceId,
				vECD.Code,
				vECD.EmployeeName AS Name,
				ISNULL(EAT.IsSelfPresent,0) AS IsSelfPresent,
				ISNULL(EAT.IsFatherPresent,0) AS IsFatherPresent,
				ISNULL(EAT.IsMotherPresent,0) AS IsMotherPresent,
				ISNULL(EAT.IsGuardianPresent,0) AS IsGuardianPresent,
				CONVERT (bit ,CASE WHEN EAT.SourceId IS NULL OR EAT.EventScheduleId!=@rEventScheduleId THEN 0 ELSE 1 END) AS IsObsolete
			FROM 
				sHrm.vEmployeeCommonDetail vECD
				INNER JOIN sActivity.tEventAssign EA 
					ON EA.SourceId=vECD.OrganizationDepartmentId AND EA.SourceTypeId=2004 AND EA.EventScheduleId=@rEventScheduleId
				LEFT JOIN sActivity.tEventAttendance EAT 
					ON EAT.EventScheduleId = EA.EventScheduleId AND EAT.SourceId = vECD.EmployeeId AND EAT.SourceTypeId = 95
			WHERE
				vECD.OrgId=@rOrgId AND vECD.OrganizationDepartmentId = @rDepartmentId
			ORDER BY vECD.Code	
		END
END


GO



ALTER PROCEDURE [sActivity].[pEventAttendanceListGet]
	 
	@rClassId int=0,
	@rDivisionId int=0,
	@rOrgId int,
	@rCode nvarchar(20)='',
	@rFirstName nvarchar(100)='',
	@rBatchId int = 0,
	@rDepartmentId int=0,
	@rEventTypeId int = 0,
	@rEventId int=0,
	@rFromDate date='',
	@rToDate date='',
	@rAcademicId bigint=0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON			 

BEGIN 	 
		BEGIN
			SET @rCode= sCommon.fSearchStringGet(@rCode)
			SET @rFirstName= sCommon.fSearchStringGet(@rFirstName)
		END
	SELECT 
			SA.AcademicId,
			SA.FirstName,
			SA.Name,
			SA.Code,
			SA.ClassId,
			SA.ClassName+'-'+SA.DivisionName AS DivDept,
			--SA.DivisionId,
			SA.RollNo,
			SA.OrgId,
			ISNULL (EA.IsSelfPresent,0) AS IsSelfPresent,
			ISNULL (EA.IsMotherPresent,0) AS IsMotherPresent,
			ISNULL (EA.IsFatherPresent,0) AS IsFatherPresent,
			ISNULL (EA.IsGuardianPresent,0) AS IsGuardianPresent,
			ES.FromDate,
			ES.ToDate,
			EM.Title AS EventTypeName,
			ES.Title AS EventName,
			ES.EventTypeId AS EventTypeId,
			ISNULL (EA.EventScheduleId,0) as EventScheduleId,
		
			
			ISNULL (EA.SchoolFeedback,'') AS SchoolFeedback,
			ISNULL (EA.ParentFeedback,'') AS ParentFeedback,
			ISNULL (EA.ParentAction,'') AS ParentAction,
			ISNULL (EA.SchoolAction,'') AS SchoolAction,
		ISNULL (EA.IsTrackForReview,0) AS IsTrackForReview,
		SA.DepartmentName,
		SA.BatchName
			
		
			
  FROM 
			sStudent.vStudentAcademic SA 
			INNER JOIN sActivity.tEventAttendance EA ON  SA.AcademicId = EA.SourceId AND EA.SourceTypeId = 2001
			INNER JOIN sActivity.tEventSchedule ES ON EA.EventScheduleId=ES.Id 
			INNER JOIN sActivity.tEventTypeMaster EM ON EM.Id = ES.EventTypeId
  WHERE 
			((SA.ClassId=@rClassId)OR(@rClassId=0))
			AND((SA.DivisionId=@rDivisionId)OR(@rDivisionId=0))
			AND((SA.Code like @rCode) OR (ISNULL(@rCode,'') = '')) 
			AND((SA.FirstName like @rFirstName) OR (ISNULL(@rFirstName,'') = '')) 
			AND(SA.OrgId=@rOrgId)
			AND(SA.BatchId=@rBatchId or @rBatchId = 0)
			AND(SA.DepartmentId=@rDepartmentId or @rDepartmentId = 0)
			AND ((ES.EventTypeId = @rEventTypeId) OR (@rEventTypeId = 0))
			AND ((ES.Id = @rEventId) OR (@rEventId = 0))
			AND ((ES.FromDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((ES.ToDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
				AND((SA.AcademicId=@rAcademicId)OR(@rAcademicId=0)) 
			ORDER BY SA.ClassId,SA.DivisionId
END




GO
 
 
 -- exec [sAttendance].[pAttenanceRegisterGet] '','',1,1001,6,2014,100100001,100100001,100100001,'',0,0
ALTER PROCEDURE [sAttendance].[pAttenanceRegisterGet]
 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rAttendanceTypeId smallint,
	 @rOrgId int,
	 @rForMonth smallint,
	 @rForYear smallint,
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rBatchId int = 0,
	 @rStudentCode nvarchar(20)='',
	 @rDepartmentId int = 0,
	 @rAcademicId bigint = 0,
	 @PageIndex int=0,
	 @rStatus int=0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
DECLARE @lFirstDate Date
	DECLARE @lResult nvarchar(max)
	DECLARE @li int 
	SET @li=1
	SET @lFirstDate = CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'/'+CONVERT(NVARCHAR(2),@rForMonth)+'/01'))	
	
	
DECLARE @lOrgId  int
--DECLARE @lSchoolRemark1  nvarchar(500)
--DECLARE @lSchoolRemark2  nvarchar(500)
--DECLARE @lSchoolRemark3  nvarchar(500)
DECLARE @lSchoolRequiredSignature  nvarchar(500)

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=1 where RGM.Id=1
 
-- select @lSchoolRequiredSignature as sig
 	
BEGIN 
	 CREATE Table #AttendanceRegistertempTable
(
	TID int identity(1,1),
	ClassDivisionTitle Nvarchar(50),
	Code nvarchar(50),
	RollNo int,
	AcademicId bigint,
	Name nvarchar(50),
	AttendanceTypeId int,
	ForYear int,
	ForMonth int,
	ForMonthInWord nvarchar(100),
	ClassId int,
	DivisionId int,
	ClassName nvarchar(50),
	DivisionName nvarchar(50),
	IsPresent bit,
	DayPart int,
	LeftDate date,
	ClassOrderIndex int,
	DivisionOrderIndex int,
	FooterSignature nvarchar(500),
	StatusId int,
	AttendanceDate date,
	AttendanceTagId int ,
	EmployeeName nvarchar(100)
)
Insert INTO #AttendanceRegistertempTable
(	
	ClassDivisionTitle,
	Code ,
	RollNo,
	AcademicId,
	Name,
	AttendanceTypeId,
	ForYear,
	ForMonth,
	ForMonthInWord,
	ClassId,
	DivisionId,
	ClassName,
	DivisionName,
	IsPresent,
	DayPart,
	LeftDate,
	ClassOrderIndex,
	DivisionOrderIndex,
	FooterSignature,
	StatusId,
	AttendanceDate,
	AttendanceTagId,
	EmployeeName
)
Select	    
	ISNULL(SA.ClassName + '-' + SA.DivisionName,'') AS ClassDivisionTitle,
	SA.Code,
	SA.RollNo,
	SA.AcademicId,
	SA.Name,
	SR.AttendanceTypeId ,
	YEAR(SR.AttendanceDate) AS ForYear,
	MONTH(SR.AttendanceDate) AS ForMonth,
	DATENAME(month, SR.AttendanceDate) AS ForMonthInWord,
	SA.ClassId,
	SA.DivisionId,
	SA.ClassName,Sa.DivisionName,
  
	--(CASE SR.IsPresent WHEN 1 THEN 'P' 
	--	WHEN 0 THEN 'A'
	--ELSE  ' ' END )AS  IsPresent,		
	SR.IsPresent,
	 day(SR.AttendanceDate) AS DayPart,
	 
	 A.LeftDate,
	 CM.OrderIndex AS ClassOrderIndex,
	 DM.OrderIndex As DivisionOrderIndex,
	@lSchoolRequiredSignature AS FooterSignature,
	 SA.StatusId,
	 SR.AttendanceDate As AttendanceDate,
	 SR.AttendanceTagId,
	 EM.FirstName+' ' + EM.LastName AS EmployeeName
	 --,
	 --SR.IsPresent
	 
	 
    from
            sStudent.vStudentAcademic SA 
            INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.AcademicId 
            INNER JOIN sStudent.tStudentAdmission A ON SA.StudentId = A.StudentId
            INNER JOIN sSetup.tClassMaster CM ON CM.Id = SA.ClassId
            INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = CM.OrgId
            INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=SA.DivisionId
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId
            
			
            
             WHERE  
	        ((SR.AttendanceTypeId=@rAttendanceTypeId) OR (@rAttendanceTypeId= 0))
	         AND ((SA.OrgId=@rOrgId) OR (@rOrgId= 0))
	          AND ((SA.BatchId=@rBatchId) OR (@rBatchId= 0))
	          AND ((YEAR(SR.AttendanceDate)=@rForYear) OR (@rForYear= 0))
	          AND ((MONTH(SR.AttendanceDate)=@rForMonth) OR (@rForMonth= 0))
	           AND ((SA.ClassId=@rClassId) OR (@rClassId= 0))
	           AND ((SA.Code=@rStudentCode) OR (@rStudentCode=''))
	           AND ((SA.AcademicId=@rAcademicId) OR (@rAcademicId=0))	           
				AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
	           AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId= 0))
	           AND ((SA.StatusId=@rStatus)OR (@rStatus=0))

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

SELECT 
@li AS DayPart,
 [sAttendance].[fWeekHOffHolidayGet](@rForYear,@rForMonth,@li,@rBatchId,@rDivisionId,'',@rOrgId) 
SET @li = @li + 1
END

 

SELECT  
			@lFirstDate AS LastDate,
			LeftDate,
            @rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			PivotTable.AcademicId,
			ClassDivisionTitle,isnull(Code,'') as Code,isnull(RollNo,0) as RollNo,
			isnull(Name,'') as Name,isnull(AttendanceTypeId,0) as AttendanceTypeId,ForYear,
			ForMonth,ClassId,ClassName,DivisionId,
			DivisionName,
			 
			ForMonthInWord,
			(ISNULL(TC.TCount,0) - ISNULL(AC.ACount,0)) AS PresentCount,
			 ISNULL(TC.TCount,0) AS AttendanceCount,
		      ISNULL(AC.ACount,0) As  AbsentCount,
		       ISNULL(PC.PCount,0) As  PresentUpto,
		       ClassOrderIndex,
		       DivisionOrderIndex,
		       FooterSignature,				 
			0 AS TotalPresent ,
			[sAttendance].[fWeekHOffHolidayGet](@rForYear ,@rForMonth ,1 ,@rBatchId ,@rDivisionId , isnull([1],''),@rOrgId )  AS P1,
			[sAttendance].[fWeekHOffHolidayGet](@rForYear ,@rForMonth ,2 ,@rBatchId ,@rDivisionId , isnull([2],''),@rOrgId )  AS P2,
			[sAttendance].[fWeekHOffHolidayGet](@rForYear ,@rForMonth ,3 ,@rBatchId ,@rDivisionId , isnull([3],''),@rOrgId )  AS P3,
			[sAttendance].[fWeekHOffHolidayGet](@rForYear ,@rForMonth ,4 ,@rBatchId ,@rDivisionId , isnull([4],''),@rOrgId )  AS P4,
			[sAttendance].[fWeekHOffHolidayGet](@rForYear ,@rForMonth ,5 ,@rBatchId ,@rDivisionId , isnull([5],''),@rOrgId )  AS P5,
			[sAttendance].[fWeekHOffHolidayGet](@rForYear ,@rForMonth ,6 ,@rBatchId ,@rDivisionId , isnull([6],''),@rOrgId ) AS P6,
			[sAttendance].[fWeekHOffHolidayGet](@rForYear ,@rForMonth ,7 ,@rBatchId ,@rDivisionId , isnull([7],''),@rOrgId ) AS P7,
			[sAttendance].[fWeekHOffHolidayGet](@rForYear ,@rForMonth ,8 ,@rBatchId ,@rDivisionId , isnull([8],''),@rOrgId ) AS P8,
			[sAttendance].[fWeekHOffHolidayGet](@rForYear ,@rForMonth ,9 ,@rBatchId ,@rDivisionId , isnull([9],''),@rOrgId ) AS P9,
			[sAttendance].[fWeekHOffHolidayGet](@rForYear ,@rForMonth ,10 ,@rBatchId ,@rDivisionId , isnull([10],''),@rOrgId ) AS P10,
			[sAttendance].[fWeekHOffHolidayGet](@rForYear ,@rForMonth ,11 ,@rBatchId ,@rDivisionId , isnull([11],''),@rOrgId ) AS P11,
			[sAttendance].[fWeekHOffHolidayGet](@rForYear ,@rForMonth ,12 ,@rBatchId ,@rDivisionId , isnull([12],''),@rOrgId ) AS P12,
			[sAttendance].[fWeekHOffHolidayGet](@rForYear ,@rForMonth ,13 ,@rBatchId ,@rDivisionId , isnull([13],''),@rOrgId ) AS P13,
			[sAttendance].[fWeekHOffHolidayGet](@rForYear ,@rForMonth ,14 ,@rBatchId ,@rDivisionId , isnull([14],''),@rOrgId ) AS P14,
			[sAttendance].[fWeekHOffHolidayGet](@rForYear ,@rForMonth ,15 ,@rBatchId ,@rDivisionId , isnull([15],''),@rOrgId ) AS P15,
			[sAttendance].[fWeekHOffHolidayGet](@rForYear ,@rForMonth ,16 ,@rBatchId ,@rDivisionId , isnull([16],''),@rOrgId ) AS P16,
			[sAttendance].[fWeekHOffHolidayGet](@rForYear ,@rForMonth ,17 ,@rBatchId ,@rDivisionId , isnull([17],''),@rOrgId ) AS P17,
			[sAttendance].[fWeekHOffHolidayGet](@rForYear ,@rForMonth ,18 ,@rBatchId ,@rDivisionId , isnull([18],''),@rOrgId ) AS P18,
			[sAttendance].[fWeekHOffHolidayGet](@rForYear ,@rForMonth ,19 ,@rBatchId ,@rDivisionId , isnull([19],''),@rOrgId ) AS P19,
			[sAttendance].[fWeekHOffHolidayGet](@rForYear ,@rForMonth ,20 ,@rBatchId ,@rDivisionId , isnull([20],''),@rOrgId ) AS P20,
			[sAttendance].[fWeekHOffHolidayGet](@rForYear ,@rForMonth ,21 ,@rBatchId ,@rDivisionId , isnull([21],''),@rOrgId ) AS P21,
			[sAttendance].[fWeekHOffHolidayGet](@rForYear ,@rForMonth ,22 ,@rBatchId ,@rDivisionId , isnull([22],''),@rOrgId ) AS P22,
			[sAttendance].[fWeekHOffHolidayGet](@rForYear ,@rForMonth ,23 ,@rBatchId ,@rDivisionId , isnull([23],''),@rOrgId ) AS P23,
			[sAttendance].[fWeekHOffHolidayGet](@rForYear ,@rForMonth ,24 ,@rBatchId ,@rDivisionId , isnull([24],''),@rOrgId ) AS P24,
			[sAttendance].[fWeekHOffHolidayGet](@rForYear ,@rForMonth ,25 ,@rBatchId ,@rDivisionId , isnull([25],''),@rOrgId ) AS P25,
			[sAttendance].[fWeekHOffHolidayGet](@rForYear ,@rForMonth ,26 ,@rBatchId ,@rDivisionId , isnull([26],''),@rOrgId ) AS P26,
			[sAttendance].[fWeekHOffHolidayGet](@rForYear ,@rForMonth ,27 ,@rBatchId ,@rDivisionId , isnull([27],''),@rOrgId ) AS P27,
			[sAttendance].[fWeekHOffHolidayGet](@rForYear ,@rForMonth ,28 ,@rBatchId ,@rDivisionId , isnull([28],''),@rOrgId ) AS P28,
			[sAttendance].[fWeekHOffHolidayGet](@rForYear ,@rForMonth ,29 ,@rBatchId ,@rDivisionId , isnull([29],''),@rOrgId ) AS P29,
			[sAttendance].[fWeekHOffHolidayGet](@rForYear ,@rForMonth ,30 ,@rBatchId ,@rDivisionId , isnull([30],''),@rOrgId ) AS P30,
			[sAttendance].[fWeekHOffHolidayGet](@rForYear ,@rForMonth ,31 ,@rBatchId ,@rDivisionId , isnull([31],''),@rOrgId ) AS P31,
			 
			
	 	--	 isnull([1],'') AS P1,
			--isnull([2],'') AS P2,
			--isnull([3],'') AS P3,
			--isnull([4],'') AS P4,
			--isnull([5],'') AS P5,
			--isnull([6],'') AS P6,
			--isnull([7],'') AS P7,
			--isnull([8],'') AS P8,
			--isnull([9],'') AS P9,
			--isnull([10],'') AS P10,
			--isnull([11],'') AS P11,
			--isnull([12],'') AS P12,
			--isnull([13],'') AS P13,
			--isnull([14],'') AS P14,
			--isnull([15],'') AS P15,
			--isnull([16],'') AS P16,
			--isnull([17],'') AS P17,
			--isnull([18],'') AS P18,
			--isnull([19],'') AS P19,
			--isnull([20],'') AS P20,
			--isnull([21],'') AS P21,
			--isnull([22],'') AS P22,
			--isnull([23],'') AS P23,
			--isnull([24],'') AS P24,
			--isnull([25],'') AS P25,
			--isnull([26],'') AS P26,
			--isnull([27],'') AS P27,
			--isnull([28],'') AS P28,
			--isnull([29],'') AS P29,
			--isnull([30],'') AS P30,
			--isnull([31],'') AS P31, 
			 EmployeeName ,
 
sCommon.fGetDaysInMonth ( @rForMonth,@rForYear) AS DaysInMonth 
--,
--AttendanceTagId

 
FROM
(
	Select --TID, 
		ISNULL(ClassName + '-' + DivisionName,'') AS ClassDivisionTitle,
		Code,
		RollNo,
		AcademicId,
		Name,
		AttendanceTypeId ,
		YEAR(ST.AttendanceDate) AS ForYear,
		MONTH(ST.AttendanceDate) AS ForMonth,
		DATENAME(month, ST.AttendanceDate) AS ForMonthInWord,
		ClassId,
		DivisionId,
		ClassName,
		DivisionName,
		(
			CASE  WHEN IsPresent = 1 AND ST.AttendanceTagId = 1 THEN 'LC' 
				  WHEN IsPresent = 1 AND ST.AttendanceTagId = 2 THEN 'EL' 
			      WHEN IsPresent = 1  THEN 'P' 
				  WHEN IsPresent = 0 THEN 'A'
				  ELSE  DT.Value END 
		)AS  IsPresent,		
		day(ST.AttendanceDate) AS DayPart,
		LeftDate
		,
		ClassOrderIndex,
		DivisionOrderIndex,
		FooterSignature,EmployeeName
      -- DO NOT ADD ANY FIELD HERE WITHOUT PERMISSION OF RAJENDRA
	 FROM 
		#AttendanceRegistertempTable ST 
		INNER JOIN #TempDaysTempTable DT ON DT.DayPart = ST.DayPart
	 WHERE
		((LeftDate >= @lFirstDate) OR ISNULL(LeftDate,'') = '')
) AS SourceTable 
 
	           
	        
PIVOT
(	
MIN(IsPresent)
FOR DayPart IN ([0], [1], [2], [3], [4],[5],[6],[7],[8],[9],[10],[11],[12],[13],[14],[15],[16],[17],[18],[19],[20],[21],[22],[23],[24],[25],[26],[27],[28],[29],[30],[31])
) AS PivotTable
	LEFT JOIN
	(
		Select  AcademicId AS AcademicId, COUNT(1) AS TCount 
		   FROM  
				#AttendanceRegistertempTable
		    
			GROUP BY  AcademicId
    ) TC ON TC.AcademicId = PivotTable.AcademicId
    
	LEFT JOIN
	(
		Select AcademicId AS AcademicId, COUNT(1) AS ACount 
		   FROM  #AttendanceRegistertempTable
		    WHERE   IsPresent = 0	 		
            
			GROUP BY  AcademicId
    ) AC ON AC.AcademicId = PivotTable.AcademicId
	LEFT JOIN
	(SELECT A.Id AS AcademicId, COUNT(1) AS PCount  FROM sAttendance.tStudentRegister SR 
			INNER JOIN sStudent.tAcademic A ON SR.AcademicId = A.Id 
		   INNER JOIN sStudent.tStudentMaster SA ON A.StudentId = SA.Id
		   INNER JOIN sSetup.tClassMaster CM ON A.ClassId = CM.Id
			WHERE  
			 SR.AttendanceDate < (convert(date,CONVERT(nvarchar(10), @rForYear)+ '/' +  CONVERT(nvarchar(10), @rForMonth) + '/' + '01' ))
			AND SR.IsPresent = 1	    		
            --AND (SA.StatusId = 1)
	        AND ((SR.AttendanceTypeId=@rAttendanceTypeId) OR (@rAttendanceTypeId= 0))
	        AND ((SA.OrgId=@rOrgId) OR (@rOrgId= 0))
	        AND ((A.BatchId=@rBatchId) OR (@rBatchId= 0))	          
	        AND ((A.ClassId=@rClassId) OR (@rClassId= 0))
	        AND ((SA.Code=@rStudentCode) OR (@rStudentCode=''))
	        AND ((A.Id=@rAcademicId) OR (@rAcademicId=0))	           
			AND ((CM.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))				
	        AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId= 0))
			GROUP BY A.Id
    ) PC ON PC.AcademicId = PivotTable.AcademicId
 
 
    ORDER BY RollNo;
 

select * from #TempDaysTempTable
 

drop table #AttendanceRegistertempTable	  
drop table #TempDaysTempTable
	
	
END
GO

 
ALTER PROCEDURE [sFee].[pFeeAllocationAdd]
	
	@rXmlDoc nvarchar(MAX),
	@rClassId int,
	@rDivisionId int,
	@rSourceTypeId smallint,
	@rSourceId bigint,
	@rFeeSetupId int,
	@rCreatedUserId bigint,
	@rOrgId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	DECLARE @lInterrorCode INT,
			@intDoc INT
	--BEGIN TRY
	
	 BEGIN TRANSACTION	
	 
	 EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc
	
	IF(@rFeeSetupId=0 AND @rClassId=0 AND @rSourceTypeId!=0 AND @rSourceId!=0)
	BEGIN
		DELETE FROM sFee.tFeeAllocation WHERE SourceTypeId=@rSourceTypeId AND SourceId=@rSourceId
	END
	ELSE IF(@rFeeSetupId!=0 AND @rClassId!=0 AND @rSourceTypeId=0 AND @rSourceId=0)
	BEGIN
		DELETE sFee.tFeeAllocation FROM sFee.tFeeAllocation FA
		INNER JOIN (
			SELECT
			SourceTypeId,
			SourceId,
			FeeSetupId
			 
		
	FROM OPENXML (@intDoc, '/Table/FeeAllocation', 1)
	WITH
	(
		SourceTypeId smallint '@SourceTypeId',
		SourceId bigint '@SourceId',
		FeeSetupId int '@FeeSetupId'
		 
	) )TEMP ON Temp.SourceId=FA.SourceId AND Temp.SourceTypeId=FA.SourceTypeId AND FA.FeeSetupId=@rFeeSetupId
		--)
		--INNER JOIN 
		--(
		--	SELECT
		--			2001 AS SourceTypeId,
		--			AcademicId 
		--	FROM 
		--			sStudent.vStudentAcademic WHERE ClassId=@rClassId AND DivisionId=@rDivisionId
		--) Temp ON Temp.AcademicId=FA.SourceId AND Temp.SourceTypeId=FA.SourceTypeId AND FeeSetupId=@rFeeSetupId
	END
	
	INSERT INTO sFee.tFeeAllocation
		(
			SourceTypeId,
			SourceId,
			FeeSetupId,
			VariableAmount,
			DiscountAmount,
			NotApplicableAmount,
			AdditionalAmount,
			Remark,
			CreatedUserId,
			CreatedDateTime
		)
	SELECT
			SourceTypeId,
			SourceId,
			FeeSetupId,
			VariableAmount,
			DiscountAmount,
			NotApplicableAmount,
			AdditionalAmount,
			Remark,
			@rCreatedUserId,
			sCommon.fGetDate()	
		
	FROM OPENXML (@intDoc, '/Table/FeeAllocation', 1)
	WITH
	(
		SourceTypeId smallint '@SourceTypeId',
		SourceId bigint '@SourceId',
		FeeSetupId int '@FeeSetupId',
		VariableAmount decimal(12,2) '@VariableAmount',
		DiscountAmount decimal(12,2) '@DiscountAmount',
		NotApplicableAmount decimal(12,2) '@NotApplicableAmount',
		AdditionalAmount decimal(12,2) '@AdditionalAmount',
		Remark nvarchar(200) '@Remark'
	) 
		  
   DELETE FROM  sFee.tFeeAllocation WHERE ISNULL(VariableAmount,0) = 0 AND ISNULL(DiscountAmount,0) = 0 AND ISNULL(AdditionalAmount,0) = 0 AND ISNULL(NotApplicableAmount,0) = 0 
   
   SELECT 1 AS Result 
	
 --   UPDATE sFee.tFeeAllocation
 --   SET
	--	VariableAmount=Temp.VariableAmount,
	--	DiscountAmount=Temp.DiscountAmount,
	--	NotApplicableAmount=Temp.NotApplicableAmount,
	--	AdditionalAmount=Temp.AdditionalAmount,
	--	Remark=Temp.Remark,
	--	UpdatedUserId=@rCreatedUserId,
	--	UpdatedDateTime=sCommon.fGetDate() 
	--FROM sFee.tFeeAllocation FA 
	--INNER JOIN 
	--(SELECT
	--		SourceTypeId,
	--		SourceId,
	--		FeeSetupId,
	--		VariableAmount,
	--		DiscountAmount,
	--		NotApplicableAmount,
	--		AdditionalAmount,
	--		Remark
		
	--FROM OPENXML (@intDoc, '/Table/FeeAllocation', 1)
	--WITH
	--(
	--	SourceTypeId smallint '@SourceTypeId',
	--	SourceId bigint '@SourceId',
	--	FeeSetupId int '@FeeSetupId',
	--	VariableAmount decimal(12,2) '@VariableAmount',
	--	DiscountAmount decimal(12,2) '@DiscountAmount',
	--	NotApplicableAmount decimal(12,2) '@NotApplicableAmount',
	--	AdditionalAmount decimal(12,2) '@AdditionalAmount',
	--	Remark nvarchar(200) '@Remark',
	--	IsRecordExist bit '@IsRecordExist'
	--) 
	--WHERE IsRecordExist=1) Temp ON Temp.SourceTypeId=FA.SourceTypeId 
	--	AND Temp.SourceId=FA.SourceId
	--	AND Temp.FeeSetupId=FA.FeeSetupId
 	 
	--	SELECT 11 AS Result    
		
	EXEC sp_xml_removedocument @intDoc
	COMMIT TRANSACTION
		
	--END TRY
	
	--BEGIN CATCH 
	--	ROLLBACK TRANSACTION
	--	SELECT -1 AS Result
	--END CATCH	
		
END
GO
 

ALTER PROCEDURE [sFee].[pFeeImportAdd]
	
	@rClassId int=0,
	@rFromBatchId int,
	@rToBatchId int,
	@rOrgId int,
	@rCreatedUserId bigint,
	@rAddMonthInDate int = 0,
	@rOrgGroupId int =0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
BEGIN TRY 

	IF EXISTS (SELECT 1 FROM sFee.tFeeSetup WHERE BatchId = @rToBatchId AND ((ClassId = @rClassId) OR (@rClassId=0)))
	BEGIN
		SELECT -101 AS RESULT
		RETURN
	END
	
	BEGIN TRANSACTION
	Declare @lCount int
	DECLARE @lNextNumber INT
	-- Fee Setup Temp Table
	CREATE TABLE #TempFeeMaster(
	[AutoId] int identity,
	[Id] [int] NOT NULL,
	[ClassId] [int] NULL,
	[AdmissionCategoryId] [int] NULL,
	[BatchId] [int] NOT NULL,
	[FeeId] [int] NOT NULL,
	[IsVariable] [bit] NOT NULL,
	[IsOptional] [bit] NULL,
	[Amount] [decimal](12, 2) NOT NULL,
	[StartDate] [date] NOT NULL,
	[EndDate] [date] NOT NULL,
	[ReceiptBookId] [int] NULL,
	[CreatedUserId] [bigint] NOT NULL,
	[CreatedDateTime] [datetime] NOT NULL,
	[UpdatedUserId] [bigint] NULL,
	[UpdatedDateTime] [datetime] NULL,
	[IsServiceTax] [bit] NULL,
	[CollectionGroupId] [int] NULL
	)
	-- End Create Table
	
	INSERT INTO #TempFeeMaster SELECT * FROM sFee.tFeeSetup WHERE BatchId=@rFromBatchId AND ((ClassId = @rClassId) OR (@rClassId=0))
	
	Select @lCount = COUNT(Id) From #TempFeeMaster
	
	While (@lCount > 0)
	BEGIN
		-- Collection Group Entry
		
		DECLARE @lOrgGroupBatchId int =0
		DECLARE @lCollectionGroupId int=0 
		DECLARE @lReceiptBookId int=0
		DECLARE @lCode nvarchar(20)=''
		DECLARE @lTitle nvarchar(100)=''
		
		SELECT @lReceiptBookId=ReceiptBookId,@lCollectionGroupId=CollectionGroupId FROM #TempFeeMaster WHERE AutoId = @lCount
		SELECT @lOrgGroupBatchId=OrgGroupBatchId FROM sSetup.tBatchMaster WHERE Id = @rToBatchId
		SELECT @lCode=Code,@lTitle=Title FROM sFee.tCollectionGroupMaster WHERE Id = @lCollectionGroupId
		
		
		
		
		IF NOT EXISTS (SELECT 1 FROM sFee.tCollectionGroupMaster WHERE Code=@lCode AND Title=@lTitle AND OrgGroupBatchId=@lOrgGroupBatchId AND ReceiptBookId=@lReceiptBookId)
		BEGIN
			DECLARE @lNumber int=0
			DECLARE @lOrderIndex smallint=0 
			SELECT @lOrderIndex=MAX(OrderIndex) FROM sFee.tCollectionGroupMaster WHERE OrgGroupBatchId = @lOrgGroupBatchId
			EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sFee.tCollectionGroupMaster', 0, 1, 1,@outNextNumber = @lNumber output
			INSERT INTO sFee.tCollectionGroupMaster
			SELECT 
				@lOrgGroupBatchId,@lNumber,Code,Title,DATEADD(MONTH,@rAddMonthInDate,StartDate),DATEADD(MONTH,@rAddMonthInDate,EndDate),
				Remark,IsObsolete,@lOrderIndex,ReceiptBookId,FooterRemark1,FooterRemark2,FeePeriod,IsDisplayCashDetailInFolio
			FROM sFee.tCollectionGroupMaster Where Id = @lCollectionGroupId
		END 
		
		SELECT @lCollectionGroupId=Id FROM sFee.tCollectionGroupMaster WHERE Code = @lCode AND Title=@lTitle AND OrgGroupBatchId=@lOrgGroupBatchId AND ReceiptBookId=@lReceiptBookId
		
		-- END Collection Group Entry
		
		-- Fee Setup Entry
		
		EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sFee.tFeeSetup', 0, 1, 1,@outNextNumber = @lNextNumber output
		INSERT INTO sFee.tFeeSetup 
		SELECT 
				@lNextNumber,ClassId,AdmissionCategoryId,@rToBatchId,FeeId,ISNULL(IsVariable,0),ISNULL(IsOptional,0),Amount,
				DATEADD(MONTH,@rAddMonthInDate,StartDate),DATEADD(MONTH,@rAddMonthInDate,EndDate),ReceiptBookId,@rCreatedUserId,GETDATE(),NULL,NULL,IsServiceTax,@lCollectionGroupId
		FROM #TempFeeMaster Where AutoId = @lCount
		
		-- END Fee Setup Entry
		Set @lCount = @lCount -1
	END

	Drop Table #TempFeeMaster 
	SELECT 1 AS Result
	COMMIT TRANSACTION
END TRY

BEGIN CATCH 
Drop Table #TempFeeMaster 
		ROLLBACK TRANSACTION
		
		SELECT -1 AS Result
END CATCH	
END


GO
UPDATE sPayroll.tPayElement SET IsIncludeInTotal = 1
UPDATE sPayroll.tPayElementDefault SET IsIncludeInTotal = 1
GO