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

GO
PRINT N'Altering [sAccounting].[tAccountingYearMaster]...';


GO
ALTER TABLE [sAccounting].[tAccountingYearMaster]
    ADD [IsLocked] BIT NULL;


GO
PRINT N'Altering [sAccounting].[tTransaction]...';


GO
ALTER TABLE [sAccounting].[tTransaction]
    ADD [TransactionApproveId] BIGINT NULL;


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


GO
ALTER TABLE [sAssessment].[tCCECSClass]
    ADD [BatchId] INT NULL;


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


GO
ALTER TABLE [sAssessment].[tCCECSForClass]
    ADD [BatchId] INT NULL;


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


GO
ALTER TABLE [sAssessment].[tTempAllExam]
    ADD [BatchIdText] NVARCHAR (20) NULL;


GO
PRINT N'Altering [sAttendance].[tTempAttendance]...';


GO
ALTER TABLE [sAttendance].[tTempAttendance]
    ADD [PCount1]  INT NULL,
        [PCount2]  INT NULL,
        [PCount3]  INT NULL,
        [PCount4]  INT NULL,
        [PCount5]  INT NULL,
        [PCount6]  INT NULL,
        [PCount7]  INT NULL,
        [PCount8]  INT NULL,
        [PCount9]  INT NULL,
        [PCount10] INT NULL,
        [PCount11] INT NULL,
        [PCount12] INT NULL,
        [PCount13] INT NULL,
        [PCount14] INT NULL,
        [PCount15] INT NULL,
        [PCount16] INT NULL,
        [PCount17] INT NULL,
        [PCount18] INT NULL,
        [PCount19] INT NULL,
        [PCount20] INT NULL,
        [PCount21] INT NULL,
        [PCount22] INT NULL,
        [PCount23] INT NULL,
        [PCount24] INT NULL,
        [PCount25] INT NULL,
        [PCount26] INT NULL,
        [PCount27] INT NULL,
        [PCount28] INT NULL,
        [PCount29] INT NULL,
        [PCount30] INT NULL,
        [PCount31] INT NULL,
        [ACount1]  INT NULL,
        [ACount2]  INT NULL,
        [ACount3]  INT NULL,
        [ACount4]  INT NULL,
        [ACount5]  INT NULL,
        [ACount6]  INT NULL,
        [ACount7]  INT NULL,
        [ACount8]  INT NULL,
        [ACount9]  INT NULL,
        [ACount10] INT NULL,
        [ACount11] INT NULL,
        [ACount12] INT NULL,
        [ACount13] INT NULL,
        [ACount14] INT NULL,
        [ACount15] INT NULL,
        [ACount16] INT NULL,
        [ACount17] INT NULL,
        [ACount18] INT NULL,
        [ACount19] INT NULL,
        [ACount20] INT NULL,
        [ACount21] INT NULL,
        [ACount22] INT NULL,
        [ACount23] INT NULL,
        [ACount24] INT NULL,
        [ACount25] INT NULL,
        [ACount26] INT NULL,
        [ACount27] INT NULL,
        [ACount28] INT NULL,
        [ACount29] INT NULL,
        [ACount30] INT NULL,
        [ACount31] INT NULL;


GO
PRINT N'Starting rebuilding table [sBiometric].[tEmployeeLateStatus]...';


GO
/*
The column [sBiometric].[tEmployeeLateStatus].[IsApproved] is being dropped, data loss could occur.
*/
GO
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;

SET XACT_ABORT ON;

BEGIN TRANSACTION;

CREATE TABLE [sBiometric].[tmp_ms_xx_tEmployeeLateStatus] (
    [Id]               INT             IDENTITY (1, 1) NOT NULL,
    [EmployeeId]       BIGINT          NULL,
    [LateDate]         DATETIME        NULL,
    [LateStatus]       NVARCHAR (10)   NULL,
    [StatusId]         SMALLINT        NULL,
    [EarlyLeaveRemark] NVARCHAR (200)  NULL,
    [EarlyHrs]         DECIMAL (10, 2) NULL,
    [CreatedUserId]    BIGINT          NOT NULL,
    [CreatedDateTime]  DATETIME        NOT NULL,
    [UpdatedUserId]    BIGINT          NULL,
    [UpdatedDateTime]  DATETIME        NULL
);

ALTER TABLE [sBiometric].[tmp_ms_xx_tEmployeeLateStatus]
    ADD CONSTRAINT [tmp_ms_xx_clusteredindex_PK_tEmployeeLateStatus] PRIMARY KEY CLUSTERED ([Id] ASC) WITH (ALLOW_PAGE_LOCKS = ON, ALLOW_ROW_LOCKS = ON, PAD_INDEX = OFF, IGNORE_DUP_KEY = OFF, STATISTICS_NORECOMPUTE = OFF);

IF EXISTS (SELECT TOP 1 1
           FROM   [sBiometric].[tEmployeeLateStatus])
    BEGIN
        SET IDENTITY_INSERT [sBiometric].[tmp_ms_xx_tEmployeeLateStatus] ON;
        INSERT INTO [sBiometric].[tmp_ms_xx_tEmployeeLateStatus] ([Id], [EmployeeId], [LateDate], [LateStatus], [CreatedUserId], [CreatedDateTime], [UpdatedUserId], [UpdatedDateTime])
        SELECT   [Id],
                 [EmployeeId],
                 [LateDate],
                 [LateStatus],
                 [CreatedUserId],
                 [CreatedDateTime],
                 [UpdatedUserId],
                 [UpdatedDateTime]
        FROM     [sBiometric].[tEmployeeLateStatus]
        ORDER BY [Id] ASC;
        SET IDENTITY_INSERT [sBiometric].[tmp_ms_xx_tEmployeeLateStatus] OFF;
    END

DROP TABLE [sBiometric].[tEmployeeLateStatus];

EXECUTE sp_rename N'[sBiometric].[tmp_ms_xx_tEmployeeLateStatus]', N'tEmployeeLateStatus';

EXECUTE sp_rename N'[sBiometric].[tmp_ms_xx_clusteredindex_PK_tEmployeeLateStatus]', N'PK_tEmployeeLateStatus', N'OBJECT';

COMMIT TRANSACTION;

SET TRANSACTION ISOLATION LEVEL READ COMMITTED;


GO
PRINT N'Altering [sCertificate].[tLeaving]...';


GO
ALTER TABLE [sCertificate].[tLeaving]
    ADD [TermsInInstitute] NVARCHAR (500) NULL;


GO
PRINT N'Altering [sCommunication].[tFeedbackResponse]...';


GO
ALTER TABLE [sCommunication].[tFeedbackResponse]
    ADD [FeedbackForId] BIGINT NULL,
        [IsCompleted]   BIT    NULL;


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


GO
ALTER TABLE [sFee].[tAccountPosting]
    ADD [ChequeDate] DATETIME NULL;


GO
PRINT N'Altering [sHrm].[tEmployeeJobDetail]...';


GO
ALTER TABLE [sHrm].[tEmployeeJobDetail]
    ADD [Subjects] NVARCHAR (200) NULL;


GO
PRINT N'Altering [sLibrary].[tBookMaster]...';


GO
ALTER TABLE [sLibrary].[tBookMaster]
    ADD [BookImage] VARBINARY (MAX) NULL;


GO
PRINT N'Altering [sSetup].[tOrgGroupSetting]...';


GO
ALTER TABLE [sSetup].[tOrgGroupSetting]
    ADD [StudentExtraCap] INT NULL;


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


GO
ALTER TABLE [sStudent].[tStudentAdmission]
    ADD [PreviousStandard] NVARCHAR (50) NULL;


GO
PRINT N'Creating [sAccounting].[tBudget]...';


GO
CREATE TABLE [sAccounting].[tBudget] (
    [Id]               INT             NOT NULL,
    [LedgerId]         INT             NOT NULL,
    [BudgetAmount]     DECIMAL (12, 2) NULL,
    [AccountingYearId] INT             NULL,
    [CreatedUserId]    BIGINT          NOT NULL,
    [CreatedDateTime]  DATETIME        NOT NULL,
    [UpdatedUserId]    BIGINT          NULL,
    [UpdatedDateTime]  DATETIME        NULL
);


GO
PRINT N'Creating [sAccounting].[tTransactionApprove]...';


GO
CREATE TABLE [sAccounting].[tTransactionApprove] (
    [Id]               BIGINT         NOT NULL,
    [AccountId]        INT            NULL,
    [AccountingYearId] INT            NOT NULL,
    [TransactionDate]  DATE           NULL,
    [Narration]        NVARCHAR (150) NULL,
    [VoucherNumber]    BIGINT         NULL,
    [VoucherTypeId]    TINYINT        NULL,
    [SourceTypeId]     SMALLINT       NULL,
    [SourceId]         BIGINT         NULL,
    [IsProfitAndLoss]  INT            NULL,
    [RepeatLedger]     INT            NULL,
    [CreatedUserId]    BIGINT         NOT NULL,
    [CreatedDateTime]  DATETIME       NOT NULL,
    [UpdatedUserId]    BIGINT         NULL,
    [UpdatedDateTime]  DATETIME       NULL,
    [OrgGroupId]       SMALLINT       NULL,
    [PayTypeId]        TINYINT        NULL,
    [ChequeNo]         NVARCHAR (20)  NULL,
    [BankName]         NVARCHAR (200) NULL,
    [ChequeDate]       DATE           NULL,
    [IsChequeCleared]  BIT            NULL,
    [ChequeClearDate]  DATE           NULL
);


GO
PRINT N'Creating [sAccounting].[tTransactionApproveDetail]...';


GO
CREATE TABLE [sAccounting].[tTransactionApproveDetail] (
    [Id]                BIGINT          NOT NULL,
    [TransactionId]     BIGINT          NOT NULL,
    [Number]            BIGINT          NULL,
    [TransactionTypeId] NVARCHAR (10)   NULL,
    [LedgerId]          BIGINT          NULL,
    [Amount]            DECIMAL (12, 2) NULL
);


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


GO
CREATE TABLE [sCommon].[tSubmitDocumentFunctionalityMaster] (
    [Id]    SMALLINT       NOT NULL,
    [Code]  NVARCHAR (20)  NOT NULL,
    [Title] NVARCHAR (100) NOT NULL
);


GO
PRINT N'Creating PK_tSubmitDocumentFunctionalityMaster...';


GO
ALTER TABLE [sCommon].[tSubmitDocumentFunctionalityMaster]
    ADD CONSTRAINT [PK_tSubmitDocumentFunctionalityMaster] 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].[tSubmitDocumentMaster]...';


GO
CREATE TABLE [sCommon].[tSubmitDocumentMaster] (
    [Id]                            INT            NOT NULL,
    [SubmitDocumentFunctionalityId] SMALLINT       NOT NULL,
    [DocumentName]                  NVARCHAR (100) NOT NULL,
    [OrgId]                         SMALLINT       NOT NULL
);


GO
PRINT N'Creating PK_tSubmitDocumentMaster...';


GO
ALTER TABLE [sCommon].[tSubmitDocumentMaster]
    ADD CONSTRAINT [PK_tSubmitDocumentMaster] 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 [sSetup].[tMandatoryFeild]...';


GO
CREATE TABLE [sSetup].[tMandatoryFeild] (
    [Id]                            INT            NOT NULL,
    [MandatoryFeildFunctionalityId] SMALLINT       NOT NULL,
    [FieldName]                     NVARCHAR (100) NOT NULL
);


GO
PRINT N'Creating PK_tMandatoryFeild...';


GO
ALTER TABLE [sSetup].[tMandatoryFeild]
    ADD CONSTRAINT [PK_tMandatoryFeild] 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 [sSetup].[tMandatoryFeildFunctionalityMaster]...';


GO
CREATE TABLE [sSetup].[tMandatoryFeildFunctionalityMaster] (
    [Id]    SMALLINT       NOT NULL,
    [Code]  NVARCHAR (20)  NOT NULL,
    [Title] NVARCHAR (100) NOT NULL
);


GO
PRINT N'Creating PK_tMandatoryFeildFunctionalityMaster...';


GO
ALTER TABLE [sSetup].[tMandatoryFeildFunctionalityMaster]
    ADD CONSTRAINT [PK_tMandatoryFeildFunctionalityMaster] 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 [sSetup].[tScreenMandatoryFeild]...';


GO
CREATE TABLE [sSetup].[tScreenMandatoryFeild] (
    [MandatoryFeildId] INT NOT NULL,
    [OrgGroupId]       INT NOT NULL
);


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


GO
CREATE TABLE [sStudent].[tStudentDocument] (
    [StudentId]              BIGINT         NOT NULL,
    [SubmitDocumentMasterId] INT            NOT NULL,
    [DocumentName]           NVARCHAR (150) NOT NULL
);


GO
PRINT N'Creating [sTimetable].[tAnnualSubjectWorkLoad]...';


GO
CREATE TABLE [sTimetable].[tAnnualSubjectWorkLoad] (
    [BatchId]         INT      NOT NULL,
    [DivisionId]      INT      NOT NULL,
    [SubjectId]       INT      NOT NULL,
    [NoOfLecture]     TINYINT  NOT NULL,
    [CreatedUserId]   BIGINT   NOT NULL,
    [CreatedDateTime] DATETIME NOT NULL
);


GO
PRINT N'Creating PK_tFeedBackAnswerGroupMaster...';


GO
ALTER TABLE [sCommunication].[tFeedBackAnswerGroupMaster]
    ADD CONSTRAINT [PK_tFeedBackAnswerGroupMaster] 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 FK_sStudent_tStudentDocument_StudentId...';


GO
ALTER TABLE [sStudent].[tStudentDocument] WITH NOCHECK
    ADD CONSTRAINT [FK_sStudent_tStudentDocument_StudentId] FOREIGN KEY ([StudentId]) REFERENCES [sStudent].[tStudentMaster] ([Id]) ON DELETE NO ACTION ON UPDATE NO ACTION;

GO
PRINT N'Checking existing data against newly created constraints';


GO
ALTER TABLE [sStudent].[tStudentDocument] WITH CHECK CHECK CONSTRAINT [FK_sStudent_tStudentDocument_StudentId];


GO

GO
PRINT N'Altering [sHrm].[fWeekHOffHolidayGet]...';


GO
ALTER FUNCTION [sHrm].[fWeekHOffHolidayGet](@rEmployeeId bigint, @rForYear smallint,@rForMonth smallint,@rDay smallint,@rBatchId int,@rDepartmentId int,@rOrgId smallint)
RETURNS nvarchar(20) WITH EXECUTE AS CALLER
AS 
BEGIN
DECLARE @lStatus nvarchar(200)='-' 
	BEGIN
		
		DECLARE @lDate nvarchar(20)  
		DECLARE @lWeekOff nvarchar(100)
	 
		SET @lDate = CONVERT(nvarchar(10), @rForYear)+ '/' +  CONVERT(nvarchar(10), @rForMonth) + '/' + CONVERT(nvarchar(10), @rDay)
		
		IF ISDATE (@lDate)=1
		BEGIN
			DECLARE @tbl TABLE(tid int identity(1,1),id int)
			INSERT INTO @tbl
			SELECT LTRIM(RTRIM(m.n.value('.[1]','varchar(8000)'))) AS dgid FROM
			(
				SELECT CAST('<XMLRoot><RowData>' + REPLACE(weekoffs,',','</RowData><RowData>') + '</RowData></XMLRoot>' AS XML) AS x
				FROM sSetup.tOrganizationMaster where Id = @rOrgid
			) t CROSS APPLY x.nodes('/XMLRoot/RowData')m(n)
			 
			SET @lWeekOff = [sAssessment].[fGetWeekdayNumber](@lDate)
			
			IF  EXISTS(SELECT 1 from @tbl where @lWeekOff in (id)) 
			BEGIN
				SET @lStatus = 'W'
				RETURN @lStatus	
			END	 
			
			IF(@lDate > GETDATE())
			BEGIN
				SET @lStatus = ''
				RETURN @lStatus	
			END	 
			
			IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
						INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=EA.SourceId WHERE ES.BatchId = @rBatchId AND ((SourceId=@rDepartmentId) OR (@rDepartmentId=0)) 
						AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)
			BEGIN
				SET @lStatus = 'H'	
				RETURN @lStatus		
			END
			
			SELECT @lStatus=LTM.Code + ' / ' + CASE WHEN L.LeavePeriodId = 1 THEN '1' WHEN L.LeavePeriodId = 2  THEN  '0.5' ELSE '0.25' END
			FROM sHrm.tLeave L INNER JOIN sHrm.tLeaveTypeMaster LTM ON LTM.Id = L.LeaveTypeId
			WHERE L.StatusId = 550 AND L.EmployeeId = @rEmployeeId AND @lDate BETWEEN L.FromDate AND L.ToDate
		 END
	END	
	RETURN @lStatus	
END
GO
PRINT N'Creating [sAttendance].[fAbsentCountGet]...';


GO
CREATE FUNCTION [sAttendance].[fAbsentCountGet](@rForYear smallint,@rForMonth smallint,@rDay smallint,@rBatchId int, @rOrgId smallint , @rClassId int, @rDivisionId int)
RETURNS int WITH EXECUTE AS CALLER
AS 
BEGIN
	declare @lCount int=0
	declare @ldate date=CONVERT(nvarchar(10), @rForYear)+ '/' +  CONVERT(nvarchar(10), @rForMonth) + '/' + CONVERT(nvarchar(10), @rDay)
	
	SELECT @lCount=
		(
 				Select count(A.Id) AS AcademicId FROM sAttendance.tStudentRegister SR 
					INNER JOIN sStudent.tAcademic A ON SR.AcademicId = A.Id  
					WHERE  
					  SR.AttendanceDate =@ldate
					AND SR.IsPresent = 0	  
					AND ((SR.AttendanceTypeId=1)) 
					AND (A.BatchId=@rBatchId)       
					AND A.DivisionId=Dm.Id
			        
		) 
		From sSetup.tDivisionMaster  DM 
		Where OrgId=@rOrgId 
		And ((Dm.ID=@rDivisionId) OR (@rDivisionId=0))
		AND ((Dm.ClassId=@rClassId) OR (@rClassId=0))

			 
 
	RETURN @lCount	
	
END
GO
PRINT N'Creating [sAttendance].[fPresentCountGet]...';


GO
CREATE FUNCTION [sAttendance].[fPresentCountGet](@rForYear smallint,@rForMonth smallint,@rDay smallint,@rBatchId int, @rOrgId smallint , @rClassId int  ,@rDivisionId int)
RETURNS int WITH EXECUTE AS CALLER
AS 
BEGIN
	declare @lCount int=0
	declare @ldate date=CONVERT(nvarchar(10), @rForYear)+ '/' +  CONVERT(nvarchar(10), @rForMonth) + '/' + CONVERT(nvarchar(10), @rDay)
	
	SELECT @lCount=
		(
 				Select count(A.Id) AS AcademicId FROM sAttendance.tStudentRegister SR 
					INNER JOIN sStudent.tAcademic A ON SR.AcademicId = A.Id  
					WHERE  
					  SR.AttendanceDate =@ldate
					AND SR.IsPresent = 1	  
					AND ((SR.AttendanceTypeId=1)) 
					AND (A.BatchId=@rBatchId)       
					AND A.DivisionId=Dm.Id
			        
		) 
		From sSetup.tDivisionMaster  DM 
		Where OrgId=@rOrgId 
		And ((Dm.ID=@rDivisionId) OR (@rDivisionId=0))
		AND ((Dm.ClassId=@rClassId) OR (@rClassId=0))

			 
 
	RETURN @lCount	
	
END
GO
PRINT N'Creating [sBiometric].[fEmployeeCLTypeGet]...';


GO

CREATE  FUNCTION [sBiometric].[fEmployeeCLTypeGet](@rMonth int,@rYear Int,@rEmployeeId bigint)
RETURNS [nvarchar](200) WITH EXECUTE AS CALLER
AS 
BEGIN
Declare @Days int 
 select @Days=sCommon.fGetDaysInMonth(@rMonth,@rYear)
DECLARE @lLeaveType nvarchar(100)
DECLARE @StartDate date=convert(nvarchar(10),@rYear)+'-'+convert(nvarchar(10),@rMonth)+'-'+'01'
 Declare @ToDate date 	
 
if @Days=31
BEGIN
	Set @ToDate =convert(nvarchar(10),@rYear)+'-'+convert(nvarchar(10),@rMonth)+'-'+'31'

	SELECT @lLeaveType=Stuff (( select ',' + Convert(nvarchar(20),day(L.FromDate))
	FROM 
	sHrm.tLeave L 
	INNER JOIN sHrm.tLeaveTypeMaster LTM ON LTM.Id = L.LeaveTypeId
	WHERE 
	L.StatusId = 550 
	AND L.EmployeeId = @rEmployeeId 
	AND @StartDate<=L.FromDate 
	AND @ToDate>=L.ToDate	
      FOR XML PATH('')  
     ),1,1,'')	
     
END 

if @Days=30
BEGIN
	Set @ToDate =convert(nvarchar(10),@rYear)+'-'+convert(nvarchar(10),@rMonth)+'-'+'30'

	SELECT @lLeaveType=Stuff (( select ',' + Convert(nvarchar(20),day(L.FromDate))
	FROM 
	sHrm.tLeave L 
	INNER JOIN sHrm.tLeaveTypeMaster LTM ON LTM.Id = L.LeaveTypeId
	WHERE 
	L.StatusId = 550 
	AND L.EmployeeId = @rEmployeeId 
	AND @StartDate<=L.FromDate 
	AND @ToDate>=L.ToDate	
      FOR XML PATH('')  
     ),1,1,'')	
     
END 

if @Days=29
BEGIN
	Set @ToDate =convert(nvarchar(10),@rYear)+'-'+convert(nvarchar(10),@rMonth)+'-'+'29'

	SELECT @lLeaveType=Stuff (( select ',' + Convert(nvarchar(20),day(L.FromDate))
	FROM 
	sHrm.tLeave L 
	INNER JOIN sHrm.tLeaveTypeMaster LTM ON LTM.Id = L.LeaveTypeId
	WHERE 
	L.StatusId = 550 
	AND L.EmployeeId = @rEmployeeId 
	AND @StartDate<=L.FromDate 
	AND @ToDate>=L.ToDate	
      FOR XML PATH('')  
     ),1,1,'')	
     
END 

if @Days=28
BEGIN
	Set @ToDate =convert(nvarchar(10),@rYear)+'-'+convert(nvarchar(10),@rMonth)+'-'+'28'

	SELECT @lLeaveType=Stuff (( select ',' + Convert(nvarchar(20),day(L.FromDate))
	FROM 
	sHrm.tLeave L 
	INNER JOIN sHrm.tLeaveTypeMaster LTM ON LTM.Id = L.LeaveTypeId
	WHERE 
	L.StatusId = 550 
	AND L.EmployeeId = @rEmployeeId 
	AND @StartDate<=L.FromDate 
	AND @ToDate>=L.ToDate	
      FOR XML PATH('')  
     ),1,1,'')	
     
END 
RETURN  ISNULL(@lLeaveType,'')
END
GO
PRINT N'Creating [sBiometric].[fEmployeeLeaveTypePendingGet]...';


GO
CREATE FUNCTION [sBiometric].[fEmployeeLeaveTypePendingGet](@rDate date, @rEmployeeId bigint)
RETURNS [nvarchar](200) WITH EXECUTE AS CALLER
AS 
BEGIN
DECLARE @lLeaveType nvarchar(200)=''
SELECT @lLeaveType=LTM.Code + ' / ' + CASE WHEN L.LeavePeriodId = 1 THEN '1' WHEN L.LeavePeriodId = 2  THEN  '0.5' ELSE '0.25' END
FROM 
sHrm.tLeave L 
INNER JOIN sHrm.tLeaveTypeMaster LTM ON LTM.Id = L.LeaveTypeId
WHERE 
L.StatusId = 549 
AND L.EmployeeId = @rEmployeeId 
AND @rDate BETWEEN L.FromDate AND L.ToDate
RETURN  ISNULL(@lLeaveType,'')
END
GO
PRINT N'Creating [sBiometric].[fTimeConversion]...';


GO
CREATE FUNCTION [sBiometric].[fTimeConversion](@rValue nvarchar(10),@rFlag bit)
RETURNS [nvarchar](10) WITH EXECUTE AS CALLER
AS 
BEGIN
	DECLARE @Result nvarchar(10)
	IF @rFlag = 0 -- Time to Decimal
		BEGIN
			SET @Result = cast(datepart(hour, @rValue) + datepart(minute, @rValue) / 60.00 as decimal(10, 2))
		END
	ELSE -- Decimal To Time
		BEGIN
			SET @Result = RIGHT('00' + CONVERT(varchar(2),FLOOR(@rValue)),2) + ':' + RIGHT('00' + CONVERT(varchar(2),FLOOR(((@rValue-FLOOR(@rValue))*60))),2)
		END
	RETURN  ISNULL(@Result,'')
END
GO
PRINT N'Creating [sSetup].[fStudentCapGet]...';


GO
 
CREATE FUNCTION [sSetup].[fStudentCapGet]( @rOrgGroupBatchId int)
RETURNS [nvarchar](50) WITH EXECUTE AS CALLER
AS 
BEGIN
	 Declare  @lStatus nvarchar(10)
	Select @lStatus=COUNT(*)
	from sStudent.tAcademic A 
	INNER JOIN sSetup.tBatchMaster BM ON BM.Id=A.BatchId 
	Where BM.OrgGroupBatchId=@rOrgGroupBatchId
	RETURN @lStatus
END
GO
PRINT N'Creating [sStudent].[fMandatoryFieldGet]...';


GO


CREATE FUNCTION [sStudent].[fMandatoryFieldGet](@rOrgGroupId int,@rStrMandatoryFeildId Nvarchar(Max))
RETURNS  @List TABLE (
		
		 IsDisplayFatherName bit,
		 IsDisplayReligion bit,
		 IsDisplayBloodGroup bit,
		 IsDisplayBirthPlace bit,
		 IsDisplayBirthTaluka bit,
		 IsDisplayBirthDistrict bit,
		 IsDisplayBirthState bit,
		 IsDisplayBirthCountry bit,
		 IsDisplayFamilyCaste bit,
		 IsDisplayFamilySubCaste bit,
		 IsDisplayCasteCategory bit,
		 IsDisplayHouse bit,
		 IsDisplayMotherTongue bit,
		 IsDisplayNationality bit,
		 IsDisplayReferenceRemark   bit,
		IsDisplayParentContactNo   bit,
		IsDisplayParentEmail   bit,
		IsDisplayStudentContactNo   bit,
		IsDisplayStudentEmail   bit,
		IsDisplayLocalAddress1   bit,
		IsDisplayLocalAddress2   bit,
		IsDisplayLocalAddress3   bit,
		IsDisplayLocalAddressCity   bit,
		IsDisplayLocalAddressState   bit,
		IsDisplayLocalAddressCountry   bit,
		IsDisplayLocalAddressPINCode   bit,
		IsDisplayLocalAddressContactNo   bit,
		OrgGroupId smallint 
)  WITH EXECUTE AS CALLER
AS 
BEGIN

	INSERT INTO @List 
	SELECT 
		   (CASE WHEN charindex('1001',@rStrMandatoryFeildId) = 0 THEN  0 ELSE 1 END) AS IsDisplayFatherName,
		   (CASE WHEN charindex('1002',@rStrMandatoryFeildId) = 0 THEN 0 ELSE 1 END)AS IsDisplayReligion,
		   (CASE WHEN charindex('1003',@rStrMandatoryFeildId) = 0 THEN 0  ELSE 1 END)AS IsDisplayBloodGroup,
		   (CASE WHEN charindex('1004',@rStrMandatoryFeildId) = 0 THEN 0  ELSE 1 END)AS IsDisplayBirthPlace,
		   (CASE WHEN charindex('1005',@rStrMandatoryFeildId) = 0 THEN 0  ELSE 1 END)AS IsDisplayBirthTaluka,
		   (CASE WHEN charindex('1006',@rStrMandatoryFeildId) = 0 THEN 0  ELSE 1 END)AS IsDisplayBirthDistrict,
		   (CASE WHEN charindex('1007',@rStrMandatoryFeildId) = 0 THEN 0 ELSE  1 END)AS IsDisplayBirthState,
		   (CASE WHEN charindex('1008',@rStrMandatoryFeildId) = 0 THEN 0  ELSE 1 END)AS IsDisplayBirthCountry,
		   (CASE WHEN charindex('1009',@rStrMandatoryFeildId) = 0 THEN 0 ELSE  1 END)AS IsDisplayFamilyCaste,
		   (CASE WHEN charindex('1010',@rStrMandatoryFeildId) = 0 THEN 0  ELSE 1 END)AS IsDisplayFamilySubCaste,
		   (CASE WHEN charindex('1011',@rStrMandatoryFeildId) = 0 THEN 0  ELSE 1 END)AS IsDisplayCasteCategory,
		   (CASE WHEN charindex('1012',@rStrMandatoryFeildId) = 0  THEN 0  ELSE 1 END)AS IsDisplayHouse,
		   (CASE WHEN charindex('1013',@rStrMandatoryFeildId) = 0  THEN 0  ELSE 1 END)AS IsDisplayMotherTongue,
		   (CASE WHEN charindex('1014',@rStrMandatoryFeildId) = 0  THEN 0  ELSE 1 END)AS IsDisplayNationality,
			(CASE  WHEN charindex('1015',@rStrMandatoryFeildId) = 0   THEN  0 ELSE 1 END ) AS  IsDisplayReferenceRemark,
			(CASE  WHEN charindex('1017',@rStrMandatoryFeildId) = 0  THEN  0 ELSE 1 END ) AS  IsDisplayParentContactNo,
			(CASE  WHEN charindex('1018',@rStrMandatoryFeildId)  = 0   THEN  0 ELSE 1 END ) AS  IsDisplayParentEmail,
			(CASE  WHEN charindex('1019',@rStrMandatoryFeildId)= 0  THEN  0 ELSE 1 END ) AS  IsDisplayStudentContactNo,
			(CASE  WHEN charindex('1020',@rStrMandatoryFeildId)= 0  THEN  0 ELSE 1 END ) AS  IsDisplayStudentEmail,
			(CASE  WHEN charindex('1021',@rStrMandatoryFeildId)= 0   THEN  0 ELSE 1 END ) AS  IsDisplayLocalAddress1,
			(CASE  WHEN charindex('1022',@rStrMandatoryFeildId)= 0  THEN  0 ELSE 1 END ) AS  IsDisplayLocalAddress2,
			(CASE  WHEN charindex('1023',@rStrMandatoryFeildId)= 0  THEN  0 ELSE 1 END ) AS  IsDisplayLocalAddress3,
			(CASE  WHEN charindex('1024',@rStrMandatoryFeildId)= 0   THEN  0 ELSE 1 END ) AS  IsDisplayLocalAddressCity,
			(CASE  WHEN charindex('1025',@rStrMandatoryFeildId)= 0  THEN  0 ELSE 1 END ) AS  IsDisplayLocalAddressState,
			(CASE  WHEN charindex('1026',@rStrMandatoryFeildId)= 0   THEN  0 ELSE 1 END ) AS  IsDisplayLocalAddressCountry,
			(CASE  WHEN charindex('1027',@rStrMandatoryFeildId)= 0   THEN  0 ELSE 1 END ) AS  IsDisplayLocalAddressPINCode,
			(CASE  WHEN charindex('1028',@rStrMandatoryFeildId)= 0   THEN  0 ELSE 1 END ) AS  IsDisplayLocalAddressContactNo,
		    @rOrgGroupId AS OrgGroupId
		  
	 
    RETURN  
    
END
GO
PRINT N'Altering [sAssessment].[vCCECSGROUPMASTER]...';


GO

ALTER VIEW [sAssessment].[vCCECSGROUPMASTER]  
  
AS  
  
SELECT CG.Id,
	   CG.Title,
	   CG.OrderIndex,
	   CG.GradeSetId,
	   CG.OrgId,
	   CC.ClassId ,
	   CC.BatchId
FROM sAssessment.tCCECSGroupMaster CG 
INNER JOIN sAssessment.tCCECSClass CC ON CG.Id=CC.CCECSGroupId
GO
PRINT N'Altering [sStudent].[vStudentAllDetail]...';


GO




















/******************************************************************************  
 Purpose          : To get Doctor details  
 Created date     : 18 Jan 2012  
 Author           : Rajendra Patel 
 Copyright©       : Copyright © Sapphire Software Solutions
 Last Change Desc : Moved EmployeeMaster from sCommon to sHrm.
*******************************************************************************/  
ALTER VIEW [sStudent].[vStudentAllDetail]  
  
AS  
  
SELECT 
	  A.Id AS AcademicId,	  
	  A.ClassId,
	  A.DivisionId,
	  A.RollNo,
	  A.OrgId,
	  A.BatchId,
	  SM.Id AS StudentId,
	  SM.Code,
	  SM.Number,
	  SM.FirstName,
	  SM.MiddleName,
	  SM.LastName,
	  [sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Name,
	  CM.DisplayTitle+' / '+DM.DisplayTitle AS ClassDivision,
	  SM.StatusId,
	  CM.DisplayTitle AS ClassName,
	  DM.DisplayTitle AS DivisionName,
	  STM.Title AS StatusName,
	  SA.LCProgress,
	  SA.LCConduct,
	  SA.LeftDate,
	  SA.PreviousSchool,
	  SA.LeftReason,
	  SA.InactiveDate,
	  SA.AdmissionDate,
	  AdmissionStandard=(SELECT Title FROM SSetup.tClassMaster WHERE Id=SA.AdmissionStandardId),
	  LeftStandard=(SELECT Title FROM SSetup.tClassMaster WHERE Id=SA.LeftStandardId),
	  SA.LCNumber,
	  SA.LCDate,
	  RM.Title AS Religion,
	  SO.FamilyCast,
	  SO.FamilySubCast,
	  SO.BirthPlace,
	  SO.BirthTaluka,
	  SO.BirthDistrict,
	  ISNULL(SO.DateOfBirth,'0001/01/01') AS DateOfBirth,
	  SO.BirthDateInWord,
	  (SI.StudentPhoto) AS StudentPhoto,
	  (SI.FatherPhoto) AS FatherPhoto,
	  (SI.MotherPhoto) AS MotherPhoto,
	  (SI.RelativePhoto) AS RelativePhoto,
	  BGM.Title AS BloodGroup,
	  ISNULL(SC.PermanentStreetOne,'')+' '+ISNULL(SC.PresentStreetTwo,'')+' '+ISNULL(SC.PresentStreetThree,'')+' '+ISNULL(SC.PresentCity,'')+' '+ISNULL(SC.PresentState,'')+' '+ISNULL(SC.PresentZipCode,'') AS PresentAddress,
	  ISNULL(GM.Title,'') AS Gender,
	  ISNULL(SC.StudentContactNo,'') AS ContactNo,
	  BM.Title AS Batch,
	  ISNULL(ACM.Title,'') AS AdmissionCategory,
	  SO.HouseId,
	  ISNULL(SC.PresentStreetone,'') AS PresentStreetone,
	  ISNULL(SC.PresentStreetTwo,'') AS PresentStreetTwo,
	  ISNULL(SC.PresentStreetThree,'') AS PresentStreetThree,
	  ISNULL(SC.PresentCity,'-') AS PresentCity,
	  ISNULL(SC.PresentState,'-') As PresentState,
	  ISNULL(SC.PresentZipCode,'-') as PresentZipCode,
	  ISNULL(SC.PresentCountry,'-') AS PresentCountry,
	  ISNULL(SC.PresentContactNo,'-') as PresentContactNo,
	  ISNULL(SC.ParentEmail,'-') AS ParentEmail,
	  ISNULL(SC.ParentContactNo,'-') AS ParentContactNo,
	  ISNULL(SC.StudentContactNo,'-') AS StudentContactNo,
	  DM.OrderIndex AS DivisionOrder,
	  SM.RegistrationNumber,
	  BM.IsActive AS IsActiveBatch,
	  CM.DepartmentId,
	  BM.OrgGroupBatchId ,
	  ISNULL(SO.UIDNumber,'' ) AS UIDNumber,
	  ISNULL(SO.AdhaarNumber,'') AS AdhaarNumber,
	  ISNULL(SM.SUId,'') AS SUId,
	  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(SC.EmergencyStreetOne,'') AS EmergencyStreetOne,
	  ISNULL(SC.EmergencyStreetTwo,'') AS EmergencyStreetTwo,
	  ISNULL(SC.EmergencyStreetThree,'') AS EmergencyStreetThree,
	  ISNULL(SC.EmergencyCountry,'') AS EmergencyCountry,
	  ISNULL(SC.EmergencyState,'') As EmergencyState,
	  ISNULL(SC.EmergencyCity,'') AS EmergencyCity,
	  ISNULL(SC.EmergencyZipCode,'') as EmergencyZipCode,
	  ISNULL(SC.EmergencyContactNo,'') AS EmergencyContactNo,
	  ISNULL(CM.StreamId,0) AS StreamId,
	  Isnull(SO.CastCategoryId,0) AS CastCategoryId,
	  Isnull(SO.NationalityId,0) AS NationalityId,
	  ISNULL(SO.MotherTongue,'') As MotherTongue,
	  Isnull(SO.BirthState,'') AS BirthState,
	  ISNULL(SO.BirthCountry,'') As BirthCountry,
	  ISNULL(SC.PermanentStreetOne,'') AS  PermanentStreetOne ,
	  ISNULL(SC.PermanentStreetTwo,'')  AS  PermanentStreetTwo,
	  ISNULL(SC.PermanentStreetThree,'') AS PermanentStreetThree,
	  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,
	  ISNULL(Sc.StudentEmail,'') AS StudentEmail,
	  ISNULL(SC.PresentDistanceFromSchool,0) AS PresentDistanceFromSchool,
	  ISNULL(NM.Title,'') AS Nationality,
	  ISNULL(SA.PreviousStandard,'')AS PreviousStandard 
	  
	 
  FROM 
  
	sStudent.tAcademic A
	INNER JOIN sStudent.tStudentMaster SM
		ON A.StudentId=SM.Id	
	INNER JOIN sSetup.tClassMaster CM
		ON CM.Id=A.ClassId
	INNER JOIN sSetup.tDivisionMaster DM
		ON DM.Id=A.DivisionId
	INNER JOIN sStudent.tStatusMaster STM
		ON STM.Id=SM.StatusId
	LEFT JOIN sStudent.tStudentCommunication SC 
		ON SC.StudentId=A.StudentId
	LEFT JOIN sStudent.tStudentOther SO
		ON SO.StudentId=A.StudentId
	LEFT JOIN sStudent.tStudentAdmission SA
		ON SA.StudentId=A.StudentId
	LEFT JOIN sCommon.tReligionMaster RM
		ON RM.Id=SO.ReligionId
	LEFT JOIN sStudent.tStudentImages SI
		ON SI.StudentId=A.StudentId
	LEFT JOIN 	sCommon.tBloodGroupMaster BGM
		ON BGM.Id=SO.BloodGroupId
	INNER JOIN sSetup.tBatchMaster BM
		ON BM.Id=A.BatchId
	LEFT JOIN sCommon.tGenderMaster GM 
		ON GM.Id=SO.GenderId
	LEFT JOIN sStudent.tAdmissionCategoryMaster ACM 
		ON ACM.Id=SM.AdmissionCategoryId
	INNER JOIN sSetup.tOrganizationMaster OM
	    ON SM.OrgId = OM.Id
	LEFT JOIN sCommon.tNationalityMaster NM ON Nm.Id=SO.NationalityId
GO
PRINT N'Altering [sStudent].[vStudentColumnName]...';


GO




















/******************************************************************************  
 Purpose          : To get Batch Wise  Class
 Created date     : 21 Nov 2013
 Author           : Kundan Patel 
 Copyright©       : Copyright © Sapphire Software Solutions
 ******************************************************************************/  
ALTER VIEW [sStudent].[vStudentColumnName]  
  
AS  
  
SELECT 	
	  --SA.AcademicId,	  
	  --SA.ClassId,
	  --SA.DivisionId,
	  SA.RollNo,
	  --SA.OrgId,
	  --SA.BatchId,
	  BM.Title AS Batch,
	  --SA.StudentId,
	  SA.SUId,
	  SA.Code AS [ID No],
	  SA.Number,
	  SA.FirstName,
	  SA.MiddleName,
	  SA.LastName,
	  SA.Name,
	  --SA.DepartmentId,
	  --SA.StatusId,
	  SA.ClassName,
	  SA.DivisionName,
	  SA.StatusName,
	  SO.UIDNumber,
	  SO.AdhaarNumber,
      SO.DateOfBirth,
      SO.BirthdateInWord,
      --SO.TransportModeId,
      TM.Title AS TransportMode,
      --SO.GenderId,
      GM.Title AS Gender,
      --SO.BloodGroupId,
      BGM.Title AS BloodGroup,
      SO.BirthPlace,
      SO.BirthTaluka,
      SO.BirthDistrict,
      SO.FamilyCast As FamilyCaste,
      --SO.FamilySubCast,
      --SO.CastCategoryId,
      
      CCM.Title AS CasteCategory,
      --SO.ReligionId,
      RM.Title AS Religion,
      --SO.HouseId,
      HM.Title AS House,
      --SO.MotherTongueId,
      MTM.Title AS MotherTongue,
      --SO.NationalityId,
      NM.Title AS Nationality,
      SO.Hobby,
      SH.IdentificationMark1,
      SH.IdentificationMark2,
      SH.IsPysicalDeformity AS IsPhysicalDeformity,
      SH.PysicalDeformityRemark AS PhysicalDeformityRemark,
      SH.IsMajorIllness,
      SH.MajorIllnessRemark,
      SH.FamilyDoctorName,
      SH.FamilyDoctorContactNo,
	  SC.PresentStreetOne,
      SC.PresentStreetTwo,
      SC.PresentStreetThree,
      SC.PresentCountry,
      SC.PresentState,
      SC.PresentCity,
      SC.PresentZipCode,
      SC.PresentContactNo,
      SC.PermanentStreetOne,
      SC.PermanentStreetTwo,
      SC.PermanentStreetThree,
      SC.PermanentCountry,
      SC.PermanentState,
      SC.PermanentCity,
      SC.PermanentZipCode,
      SC.PermanentContactNo,
      SC.EmergencyStreetOne,
      SC.EmergencyStreetTwo,
      SC.EmergencyStreetThree,
      SC.EmergencyCountry,
      SC.EmergencyState,
      SC.EmergencyCity,
      SC.EmergencyZipCode,
      SC.EmergencyContactNo,
      SC.ParentContactNo,
      SC.ParentEmail,
      SC.StudentContactNo,
      SC.StudentEmail,
	  --AR.PickupDestinationId AS BusRouteDestinationId,
	  BDM.Title AS BusRouteDestination,
	  SF.FatherName,
	  SF.FatherDateOfBirth,	 
	  SF.FatherQualification,
	  SF.FatherOccupation,
	  SF.FatherContactNo,
	  SF.FatherMail,
	  SF.FatherOfficeAddress,
	  SF.FatherIncome,
	  SF.MotherName,
	  SF.MotherDateOfBirth,
	  SF.MotherQualification,
	  SF.MotherOccupation,
      SF.MotherContactNo,
      SF.MotherMail,
      SF.MotherOfficeAddress,
      SF.MotherIncome,      
	  AC.Title AS AdmissionCategory,
	  SAD.PreviousSchool,
	  SAD.AdmissionDate,
	  SAD.AdmissionFormNumber,
	  SAD.AdmissionNumber,
	  SAD.IsTransfer,
	  SAD.TransferFrom,
	  SAD.PassingYear,
	  SAD.IsTFWS,
	  SAD.IsCertificateHolder,
	  SAD.CertificateName,
	  AQM.Title AS AdmissionQuota,
	  SAD.LeftDate,
	  SA.BlackListReason,
	  SA.DivisionOrder,
	  SA.ClassOrderIndex,
	  AD.BankAccountNumber,
	  AD.BankName,
	  AD.BankBranch,
	  AD.BankIFSCCode,
	  BSM.Title AS StudentBatchStatus,
	  AD.Class9BoardRegistrationNumber,
	  AD.Class11BoardRegistrationNumber,
	  AD.PassportNumber,
	  AD.PassportType,
	  AD.PassportCountryCode,
	  AD.PassportIssueDate,
	  AD.PassportExpiryDate,
	  SS.SiblingName1,
	  SS.SiblingInstitue1,
	  SS.SiblingClass1,
	  SS.SiblingAge1,
	  SS.SiblingRelation1,
	  SS.SiblingName2,
	  SS.SiblingInstitue2,
	  SS.SiblingClass2,
	  SS.SiblingAge2,
	  SS.SiblingRelation2,
	  SS.SiblingName3,
	  SS.SiblingInstitue3,
	  SS.SiblingClass3,
	  SS.SiblingAge3,
	  SS.SiblingRelation3,
	  CD.SSCBoard,
	  CD.SSCSchool,
	  CD.SSCPassingYear,
	  CD.SSCObtainMarks,
	  CD.SSCOutOfMarks,
	  CD.SSCPercentage,
	  CD.SSCMathMarks,
	  CD.SSCMathOutOfMarks,
	  CD.HSCBoard,
	  CD.HSCSchool,
	  CD.HSCPassingYear,
	  CD.HSCObtainMarks,
	  CD.HSCOutOfMarks,
	  CD.HSCPercentage,
	  
	  CD.HSCBiologyMarks,
	  CD.HSCBiologyOutOfMarks,
	 
	  CD.HSCChemistryMarks,
	  CD.HSCChemistryOutOfMarks,
	  CD.HSCMathMarks,
	  CD.HSCMathOutOfMarks,
	  cd.HSCPhysicsMarks,
	  CD.HSCPhysicsOutOfMarks,
	  CD.PCMMarks,
	  CD.PCBMarks,
	  CD.JEERollNo,
	  CD.JEEMeritNo,
	  CD.JEEMeritMarks,
	  CD.JEEOutOfMarks,
	  CD.DiplomaBoard,
	  CD.DiplomaCollege,
	  CD.DiplomaPassingYear,
	  CD.DiplomaObtainMarks,
	  CD.DiplomaOutOfMarks,
	  CD.DiplomaPercentage,
	  CD.ApplicationNo,
	  CD.AdmissionRound,
	  CD.MaritalStatusId,
	  ISNULL(HHM.Title,'') AS HostelName,
	  ISNULL(HRM.Title,'') AS Room,
	  ISNULL(HBM.Title,'') AS BuildingName,
	  ISNULL(HAR.BedNumber,'') AS BedNumber,
	  ISNULL(SGM.Title,'') AS StudentGroup,
	  ISNULL(SGMO.Title,'') AS StudentOtherGroup,
	  SO.BirthState,
	  SO.BirthCountry,
	  ISNULL(BDM.PickupTime,'') AS PickupTime,
	  ISNULL(BDM.DropTime,'') AS DropTime,
	  ISNULL(BRM.Title,'') AS BusRoute,
	  ISNULL(SAD.PreviousStandard,'') AS PreviousStandard,
	  ISNULL(So.ReferenceRemark,'') AS ReferenceRemark
	  
	  
  FROM sStudent.vStudentAcademic SA
	INNER JOIN sStudent.tStudentAdmission SAD ON SAD.StudentId=SA.StudentId
	INNER JOIN sCommon.tAdmissionQuotaMaster AQM ON AQM.Id = SAD.AdmissionQuotaId
	INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA.BatchId
	INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=SA.StudentId
	INNER JOIN sStudent.tStudentCommunication SC ON SC.StudentId=SA.StudentId
	INNER JOIN sTransport.tAssignRoute AR ON AR.SourceId=SA.StudentId
	INNER JOIN sCommon.tTransportModeMaster TM ON TM.Id=SO.TransportModeId
	INNER JOIN sCommon.tGenderMaster GM ON GM.Id=SO.GenderId
	INNER JOIN sCommon.tBloodGroupMaster BGM ON BGM.Id=SO.BloodGroupId
	INNER JOIN sCommon.tCastCategoryMaster CCM ON CCM.Id=SO.CastCategoryId
	INNER JOIN sCommon.tReligionMaster RM ON RM.Id=SO.ReligionId
	INNER JOIN sActivity.tHouseMaster HM ON HM.Id=SO.HouseId
	INNER JOIN sCommon.tMotherTongueMaster MTM ON MTM.Id=SO.MotherTongueId
	INNER JOIN sCommon.tNationalityMaster NM ON NM.Id=SO.NationalityId
	INNER JOIN sTransport.tBusRouteDestinationMaster BDM ON BDM.Id=AR.PickupDestinationId
	INNER JOIN sStudent.tStudentFamily SF ON SF.StudentId=SA.StudentId
	INNER JOIN sStudent.tStudentHealth SH ON SH.StudentId=SA.StudentId
	INNER JOIN sStudent.tAdmissionCategoryMaster AC ON AC.Id=SA.AdmissionCategoryId
	INNER JOIN sStudent.tStudentadditional AD ON AD.StudentId= SA.StudentId
	INNER JOIN sStudent.tStudentBatchStatus SBS ON SBS.AcademicId = SA.AcademicId
	INNER JOIN sStudent.tBatchStatusMaster BSM ON BSM.Id = SBS.BatchStatusId
	INNER JOIN sStudent.tStudentSibling SS ON SS.StudentId= SA.StudentId
	INNER JOIN sStudent.tCollegeDetail CD ON CD.StudentId = SA.StudentId
	INNER JOIN sHostel.tAssignRoom HAR ON HAR.SourceId = SA.StudentId
	INNER JOIN sHostel.tRoomMaster HRM ON HRM.Id = HAR.RoomId
	INNER JOIN sHostel.tBuildingMaster HBM ON HBM.HostelId = HRM.HostelId
	INNER JOIN sHostel.tHostelMaster HHM ON HHM.Id = HRM.HostelId
	INNER JOIN sStudent.tStudentGroupMaster SGM ON SGM.Id = SA.StudentGroupId
	INNER JOIN sStudent.tStudentOtherGroupMaster SGMO ON SGMO.Id = SA.StudentOtherGroupId
    INNER JOIN sTransport.tBusRouteMaster BRM ON BRM.Id=BDM.BusRouteId
GO
PRINT N'Altering [sStudent].[vStudentCustomSearch]...';


GO



 
ALTER VIEW [sStudent].[vStudentCustomSearch]  
  
AS  
  
SELECT 	
	  SA.AcademicId,	  
	  SA.ClassId,
	  SA.DivisionId,
	  SA.RollNo,
	  SA.OrgId,
	  SA.BatchId,
	  BM.Title AS Batch,
	  SA.StudentId,
	  SA.SUId,
	  SA.Code,
	  SA.Number,
	  SA.FirstName,
	  SA.MiddleName,
	  SA.LastName,
	  SA.Name,
	  --SA.DepartmentId,
	  SA.StatusId,
	  SA.ClassName,
	  SA.DivisionName,
	  SA.StatusName,
	  SO.UIDNumber,
	  SO.AdhaarNumber,
      CONVERT(VARCHAR(10), SO.DateOfBirth, 111) AS DateOfBirth,
      SO.BirthdateInWord,
      SO.TransportModeId,
      TM.Title AS TransportMode,
      SO.GenderId,
      GM.Title AS Gender,
      SO.BloodGroupId,
      BGM.Title AS BloodGroup,
      SO.BirthPlace,
      SO.BirthTaluka,
      SO.BirthDistrict,
      SO.FamilyCast AS FamilyCaste,
      SO.FamilySubCast,
      
      
      SO.CastCategoryId,
      CCM.Title AS CasteCategory,
      SO.ReligionId,
      RM.Title AS Religion,
      SO.HouseId,
      HM.Title AS House,
      SO.MotherTongueId,
     SO.MotherTongue AS MotherTongue,
      SO.NationalityId,
      NM.Title AS Nationality,
      SO.Hobby,
      SH.IdentificationMark1,
      SH.IdentificationMark2,
      SH.IsPysicalDeformity,
      SH.PysicalDeformityRemark,
      SH.IsMajorIllness,
      SH.MajorIllnessRemark,
      SH.FamilyDoctorName,
      SH.FamilyDoctorContactNo,
	  SC.PresentStreetOne,
      SC.PresentStreetTwo,
      SC.PresentStreetThree,
      SC.PresentCountry,
      SC.PresentState,
      SC.PresentCity,
      SC.PresentZipCode,
      SC.PresentContactNo,
      SC.PermanentStreetOne,
      SC.PermanentStreetTwo,
      SC.PermanentStreetThree,
      SC.PermanentCountry,
      SC.PermanentState,
      SC.PermanentCity,
      SC.PermanentZipCode,
      SC.PermanentContactNo,
      SC.EmergencyStreetOne,
      SC.EmergencyStreetTwo,
      SC.EmergencyStreetThree,
      SC.EmergencyCountry,
      SC.EmergencyState,
      SC.EmergencyCity,
      SC.EmergencyZipCode,
      SC.EmergencyContactNo,
      SC.ParentContactNo,
      SC.ParentEmail,
      SC.StudentContactNo,
      SC.StudentEmail,
	  RT.BusRouteDestinationId AS BusRouteDestinationId,
	  RT.BusRouteDestination AS BusRouteDestination,
	  SF.FatherName,
	  CONVERT(VARCHAR(10), SF.FatherDateOfBirth, 111)AS FatherDateOfBirth,
	  SF.FatherQualification,
	  SF.FatherOccupation,
	  SF.FatherContactNo,
	  SF.FatherMail,
	  SF.FatherOfficeAddress,
	  SF.FatherIncome,
	  SF.MotherName,
	 CONVERT(VARCHAR(10),  SF.MotherDateOfBirth,111) AS MotherDateOfBirth,
	  SF.MotherQualification,
	  SF.MotherOccupation,
      SF.MotherContactNo,
      SF.MotherMail,
      SF.MotherOfficeAddress,
      SF.MotherIncome,      
	  ISNULL(SA.AdmissionCategoryId,0) AS AdmissionCategoryId,
	  AC.Title AS AdmissionCategory,
	  SAD.PreviousSchool,
	  CONVERT(VARCHAR(10), SAD.AdmissionDate, 111) AS AdmissionDate,
	  SAD.AdmissionFormNumber,
	  SAD.AdmissionNumber,
	  SAD.IsTransfer,
	  SAD.TransferFrom,
	  SAD.PassingYear,
	  SAD.IsTFWS,
	  SAD.IsCertificateHolder,
	  SAD.CertificateName,
	  AQM.Title AS AdmissionQuota,
	  CONVERT(VARCHAR(10),SAD.LeftDate, 111) AS LeftDate,
	  SA.IsBlackList,
	  SA.BlackListReason,
	  SA.DivisionOrder,
	  SA.ClassOrderIndex,
	  AD.RepeatCount,
	  ADI.BankAccountNumber,
	  ADi.BankBranch,
	  ADI.BankIFSCCode,
	  ADI.BankName,
	  ESM.Title AS StudentBatchStatus,
	  EnrollmentStatusId AS StudentStatusId,
	  ADI.Class9BoardRegistrationNumber,
	  ADI.Class11BoardRegistrationNumber,
	  ADI.PassportNumber,
	  ADI.PassportType,
	  ADI.PassportCountryCode,
	CONVERT(VARCHAR(10),ADI.PassportIssueDate,111) AS PassportIssueDate,
	  ADI.PassportExpiryDate,
	  '' SiblingName1,
	  '' SiblingInstitue1,
	  '' SiblingClass1,
	  '' SiblingAge1,
	  '' SiblingRelation1,
	  '' SiblingName2,
	  '' SiblingInstitue2,
	  '' SiblingClass2,
	  '' SiblingAge2,
	  '' SiblingRelation2,
	  '' SiblingName3,
	  '' SiblingInstitue3,
	  '' SiblingClass3,
	  '' SiblingAge3,
	  '' SiblingRelation3,
	  ISNULL(HHM.Title,'') AS HostelName,
	  ISNULL(HRM.Title,'') AS Room,
	  ISNULL(HBM.Title,'') AS BuildingName,
	  ISNULL(HAR.BedNumber,'') AS BedNumber,
	  
	  ISNULL(SM.StudentGroupId,0) AS StudentGroupId,
	  ISNULL(SM.StudentOtherGroupId,0) AS StudentOtherGroupId,
	  
	  SGM.Title AS StudentGroup,
	  SOGM.Title AS StudentOtherGroup,
	  SO.BirthState,
	  So.BirthCountry,
	  ISNULL(RT.BusRouteId,0) AS BusRouteId,
	  ISNULL(RT.PickupTime,'') AS PickupTime,
	  ISNULL(RT.Droptime,'') AS Droptime,
	  ISNULL(RT.BusRoute,'' )AS BusRoute,
	   CD.SSCBoard,
	   CD.SSCSchool,
	  CD.SSCPassingYear,
	  CD.SSCObtainMarks,
	  CD.SSCOutOfMarks,
	  CD.SSCPercentage,
	  CD.SSCMathMarks,
	  CD.SSCMathOutOfMarks,
	  CD.HSCBoard,
	  CD.HSCSchool,
	  CD.HSCPassingYear,
	  CD.HSCObtainMarks,
	  CD.HSCOutOfMarks,
	  CD.HSCPercentage,
	  
	  CD.HSCBiologyMarks,
	  CD.HSCBiologyOutOfMarks,
	 
	  CD.HSCChemistryMarks,
	  CD.HSCChemistryOutOfMarks,
	  CD.HSCMathMarks,
	  CD.HSCMathOutOfMarks,
	  cd.HSCPhysicsMarks,
	  CD.HSCPhysicsOutOfMarks,
	  CD.PCMMarks,
	  CD.PCBMarks,
	  CD.JEERollNo,
	  CD.JEEMeritNo,
	  CD.JEEMeritMarks,
	  CD.JEEOutOfMarks,
	  CD.DiplomaBoard,
	  CD.DiplomaCollege,
	  CD.DiplomaPassingYear,
	  CD.DiplomaObtainMarks,
	  CD.DiplomaOutOfMarks,
	  CD.DiplomaPercentage,
	  CD.ApplicationNo,
	  CD.AdmissionRound,
	  CD.MaritalStatusId,
	  EX.Id As ExemptionTypeId,
	  SAD.PreviousStandard,
	  SO.ReferenceRemark
	 
	  	  	   
  FROM sStudent.vStudentAcademic SA
    INNER JOIN sStudent.tStudentMaster SM ON SM.Id = SA.StudentId
	LEFT JOIN sStudent.tStudentAdmission SAD ON SAD.StudentId=SA.StudentId
	LEFT JOIN sCommon.tAdmissionQuotaMaster AQM ON AQM.Id = SAD.AdmissionQuotaId
	LEFT JOIN sSetup.tBatchMaster BM ON BM.Id=SA.BatchId
	LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=SA.StudentId
	LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=SA.StudentId
	--LEFT JOIN sTransport.tAssignRoute AR ON AR.SourceId=SA.StudentId
	LEFT JOIN sCommon.tTransportModeMaster TM ON TM.Id=SO.TransportModeId
	LEFT JOIN sCommon.tGenderMaster GM ON GM.Id=SO.GenderId
	LEFT JOIN sCommon.tBloodGroupMaster BGM ON BGM.Id=SO.BloodGroupId
	LEFT JOIN sCommon.tCastCategoryMaster CCM ON CCM.Id=SO.CastCategoryId
	LEFT JOIN sCommon.tReligionMaster RM ON RM.Id=SO.ReligionId
	LEFT JOIN sActivity.tHouseMaster HM ON HM.Id=SO.HouseId
	LEFT JOIN sCommon.tMotherTongueMaster MTM ON MTM.Id=SO.MotherTongueId
	LEFT JOIN sCommon.tCountryMaster NM ON NM.Id=SO.NationalityId
	--LEFT JOIN sTransport.tBusRouteDestinationMaster BDM ON BDM.Id=AR.PickupDestinationId
	LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId=SA.StudentId
	LEFT JOIN sStudent.tStudentHealth SH ON SH.StudentId=SA.StudentId
	LEFT JOIN sStudent.tAdmissionCategoryMaster AC ON AC.Id=SA.AdmissionCategoryId
	LEFT JOIN sStudent.tAcademicDetail AD ON AD.AcademicId = SA.AcademicId
	LEFT JOIN sStudent.tStudentadditional ADI ON ADI.StudentId = SA.StudentId
	LEFT JOIN sStudent.tEnrollmentStatusMaster ESM ON ESM.Id = SM.EnrollmentStatusId
	--LEFT JOIN sStudent.tStudentSibling SS ON SS.StudentId = SA.StudentId
	LEFT JOIN sHostel.tAssignRoom HAR ON HAR.SourceId = SM.Id AND HAR.OrgGroupBatchId = SA.OrgGroupBatchId
	LEFT JOIN sHostel.tRoomMaster HRM ON HRM.Id = HAR.RoomId
	LEFT JOIN sHostel.tBuildingMaster HBM ON HRM.BuildingId = HBM.Id 
	LEFT JOIN sHostel.tHostelMaster HHM ON HHM.Id = HRM.HostelId
	
	LEFT JOIN sStudent.tStudentGroupMaster SGM ON SGM.Id=SM.StudentGroupId
	LEFT JOIN sStudent.tStudentOtherGroupMaster SOGM ON SOGM.Id=SM.StudentOtherGroupId
	--LEFT JOIN sTransport.tBusRouteMaster BRM ON BRM.Id=BDM.BusRouteId
	LEFT JOIN sStudent.tCollegeDetail CD ON CD.StudentId = SA.StudentId
	LEFT JOIN sFee.tExemptionTypeMaster EX ON Ex.Id=SA.ExemptionTypeId
   LEFT JOIN
	(SELECT AR.SourceId,AR.PickupDestinationId AS BusRouteDestinationId,BDM.Title AS BusRouteDestination, ISNULL(BRM.Id,0) AS BusRouteId,
	  ISNULL(BDM.PickupTime,'') AS PickupTime,
	  ISNULL(BDM.Droptime,'') AS Droptime,
	  ISNULL(BRM.Title,'' )AS BusRoute,BRM.OrgGroupBatchId FROM sTransport.tAssignRoute AR 
    INNER JOIN sTransport.tBusRouteDestinationMaster BDM ON BDM.Id=AR.PickupDestinationId
    INNER JOIN sTransport.tBusRouteMaster BRM ON BRM.Id=BDM.BusRouteId AND  AR.SourceTypeId=2003  )  RT 
   
    ON RT.SourceId = SA.StudentId     AND RT.OrgGroupBatchId =SA.OrgGroupBatchId
GO

GO
PRINT N'Altering [sAccounting].[pAccountingYearMasterAdd]...';


GO




ALTER PROCEDURE [sAccounting].[pAccountingYearMasterAdd]
	 
	@rId int,
	@rCode nvarchar(20),
	@rTitle nvarchar(100),
	@rFromDate date,
	@rToDate date,
	@rCreatedUserId bigint,
	@rUpdatedUserId bigint,
	@rOrgGroupId int,
	@rAccountId int ,
	@rIsLocked bit 
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
		IF Exists(select Id from sAccounting.tAccountingYearMaster where (Title=@rTitle AND AccountId = @rAccountId) OR (Code = @rCode AND AccountId = @rAccountId))
			BEGIN
			select -103 as Result
			RETURN
		END 
	
	BEGIN TRANSACTION
	
	DECLARE @lCount INT
	DECLARE @lNextNumber INT     
	DECLARE @1CurruntAccountingYearId INT
	DECLARE @1MaxLedgerGroupId INT	
	DECLARE @1MaxLedgerId int 
	DECLARE @1Count int
	DECLARE @1LedgerGroupId int
	DECLARE @1LedgerGroupName nvarchar(200)
	DECLARE @1LedgerId int

	SELECT @lCount = ISNULL( COUNT(Id),0) FROM sAccounting.tAccountingYearMaster WHERE AccountId = @rAccountId
	
		CREATE TABLE #TempLedgerGroupMaster
	(
		Id bigint identity,	 
	    LedgerGroupName nvarchar(100),
	    LedgerId int,
	    LedgerGroupId int
	)
	
IF @lCount >= 1 --- If any year created get old ledger and Ledger group accordingly
BEGIN

		Select @1CurruntAccountingYearId = MAX(Id) from sAccounting.tAccountingYearMaster Where OrgGroupId = @rOrgGroupId AND AccountId = @rAccountId
		SET @1CurruntAccountingYearId = ISNULL(@1CurruntAccountingYearId,1) 

	
 IF(@rId = 0)	
BEGIN

	   --SELECT @1MaxLedgerGroupId =  sCommon.fGetIntIdForOrg(101,@rOrgGroupId)
	   --SELECT @1MaxLedgerId = sCommon.fGetIntIdForOrg(101,@rOrgGroupId) 
	   
 
	
	
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sAccounting.tAccountingYearMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	--EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sAccounting.tAccountingYearMaster',@lNextNumber = @lNextNumber output
 
	INSERT INTO sAccounting.tAccountingYearMaster
		(
			Id,
			Code,
			Title,
			FromDate,
			ToDate,
			CreatedUserId,
			CreatedDateTime,
			AccountId,
			OrgGroupId,
			IsLocked
		)
	VALUES
		(
			@lNextNumber,
			@rCode,
			@rTitle,
			@rFromDate,
			@rToDate,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rAccountId,
			@rOrgGroupId,
			@rIsLocked
		) 
		
		

	  
	--END 
		
		INSERT INTO sAccounting.tLedgerGroupMaster
		SELECT  CASE WHEN  @1CurruntAccountingYearId = 1 then sCommon.fGetIntIdForOrg(Id,@rOrgGroupId)
		ELSE Id END ,Code,Title,IsObsolete,LedgerMainGroupId,@lNextNumber,
		@rCreatedUserId,sCommon.fGetDate(),@rCreatedUserId,sCommon.fGetDate(),@rAccountId,@rOrgGroupId		
		from sAccounting.tLedgerGroupMaster  where AccountingYearId = @1CurruntAccountingYearId
		--SELECT @1MaxLedgerGroupId = MAX(Id)  from sAccounting.tLedgerGroupMaster Where AccountingYearId = @lNextNumber
	
	
				  
		INSERT INTO #TempLedgerGroupMaster
		SELECT LGM.Title,l.Id,LedgerGroupId AS LedgerGroup FROM sAccounting.tLedgerMaster l 
		INNER JOIN sAccounting.tLedgerGroupMaster LGM 
		ON LGM.Id = l.LedgerGroupId  AND lgm.AccountingYearId = @1CurruntAccountingYearId
		WHERE l.AccountingYearId = @1CurruntAccountingYearId order by l.Id DESC
				 
		SELECT @1Count = COUNT(*) FROM #TempLedgerGroupMaster
		
		WHILE(@1Count > 0)
		 BEGIN		   		   
		   SELECT @1LedgerGroupName = LedgerGroupName,@1LedgerId = LedgerId  FROM #TempLedgerGroupMaster WHere Id = @1Count
		   SELECT @1LedgerGroupId = Id FROM sAccounting.tLedgerGroupMaster WHERE Title = @1LedgerGroupName AND AccountingYearId = @lNextNumber
		   	
		   INSERT INTO sAccounting.tLedgerMaster
		   SELECT CASE WHEN  @1CurruntAccountingYearId = 1 then sCommon.fGetIntIdForOrg(Id,@rOrgGroupId) ELSE Id END 
		   --@1MaxLedgerId + ROW_NUMBER() over(Order by Id asc)
		   ,Code,Title,IsObsolete,
		   @1LedgerGroupId,
		   0.00,LedgerTypeId,
		   @lNextNumber,@rCreatedUserId,sCommon.fGetDate(),@rCreatedUserId,sCommon.fGetDate(),@rOrgGroupId 
		   FROM sAccounting.tLedgerMaster 
		   WHERE AccountingYearId = @1CurruntAccountingYearId	 AND Id = @1LedgerId		   
		   SET @1Count = @1Count - 1;		    
		 END
		 		 
		SELECT 1 AS RESULT            
		
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE sAccounting.tAccountingYearMaster
	    SET
			  Code=@rCode,
			  Title=@rTitle,
			  FromDate=@rFromDate,
			  AccountId = @rAccountId,
			  ToDate=@rToDate,
			  UpdatedUserId=@rUpdatedUserId,
			  UpdatedDateTime= sCommon.fGetDate() ,
			  IsLocked=@rIsLocked
	      
	      WHERE Id = @rId 	   
	 END  
		  SELECT @lNextNumber AS Result
		  
END
ELSE --- If any year not created get old ledger and Ledger group from default
BEGIN



 
	
 IF(@rId = 0)	
BEGIN
 
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sAccounting.tAccountingYearMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	--EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sAccounting.tAccountingYearMaster',@lNextNumber = @lNextNumber output
 
	INSERT INTO sAccounting.tAccountingYearMaster
		(
			Id,
			Code,
			Title,
			FromDate,
			ToDate,
			CreatedUserId,
			CreatedDateTime,
			AccountId,
			OrgGroupId,
			IsLocked
		)
	VALUES
		(
			@lNextNumber,
			@rCode,
			@rTitle,
			@rFromDate,
			@rToDate,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rAccountId,
			@rOrgGroupId,
			@rIsLocked
		) 
		
		
 
		
		INSERT INTO sAccounting.tLedgerGroupMaster
		SELECT  sCommon.fGetIntIdForOrg(Id,@rOrgGroupId),Code,
		Title,IsObsolete,LedgerMainGroupId,@lNextNumber,
		@rCreatedUserId,sCommon.fGetDate(),@rCreatedUserId,sCommon.fGetDate(),@rAccountId,@rOrgGroupId		
		from sAccounting.tLedgerGroupMaster  where OrgGroupId = 1 AND AccountId = 1 AND AccountingYearId = 1
	 
		
	INSERT INTO sAccounting.tLedgerMaster
	SELECT  sCommon.fGetIntIdForOrg(Id,@rOrgGroupId)
		   
		   ,Code,Title,IsObsolete,
		   sCommon.fGetIntIdForOrg(Id,@rOrgGroupId),
		   0.00,LedgerTypeId,
		   @lNextNumber,@rCreatedUserId,sCommon.fGetDate(),@rCreatedUserId,sCommon.fGetDate(),@rOrgGroupId 
		   FROM sAccounting.tLedgerMaster 
		   WHERE AccountingYearId = 1  AND OrgGroupId = 1	  
	
				  
 
		 		 
		SELECT 1 AS RESULT            
		
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE sAccounting.tAccountingYearMaster
	    SET
			  Code=@rCode,
			  Title=@rTitle,
			  FromDate=@rFromDate,
			  AccountId = @rAccountId,
			  ToDate=@rToDate,
			  UpdatedUserId=@rUpdatedUserId,
			  UpdatedDateTime= sCommon.fGetDate() ,
			  IsLocked =@rIsLocked
	      
	      WHERE Id = @rId 	   
	 END  
		  SELECT @lNextNumber AS Result




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


GO

ALTER PROCEDURE [sAccounting].[pAccountingYearMasterGet]
	 
	 @rId int = 0,
	 --@rAffiliationId int,
	 @rTitle nvarchar(100),
	 @rCode nvarchar(20),
	 @rAccountId int,
	 @rOrgGroupId int	 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	  BEGIN 
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
			SET @rCode = sCommon.fSearchStringGet(@rCode)
	  END	 
	SELECT 
	AYM.Id,
	AYM.Code,
	AYM.Title,
	AYM.FromDate,
	AYM.ToDate,
	ISNULL(AYM.AccountId,0) AS AccountId,
	Am.Title AS Account,
	ISNULL(IsLocked,0)  AS  IsLocked 
	     
  FROM 
       sAccounting.tAccountingYearMaster AYM
       INNER JOIN sAccounting.tAccountMaster AM ON AM.Id = AYM.AccountId
        --INNER JOIN sSetup.tAffiliationMaster AM
        --ON DSM.AffiliationId= AM.Id 
  WHERE  
             ((AYM.Id = @rId) OR (@rId = 0))
        AND  ((AYM.Title like @rTitle) OR (ISNULL(@rTitle,'') = '')) 
        AND  ((AYM.Code like @rCode) OR (ISNULL(@rCode,'') = '')) 
		AND  (AYM.AccountId=@rAccountId OR @rAccountId = 0)
		AND AYM.OrgGroupId = @rOrgGroupId
		
END
GO
PRINT N'Altering [sAccounting].[pBankReconsilationGet]...';


GO
ALTER PROCEDURE [sAccounting].[pBankReconsilationGet]
	
	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='', 
	@rStartDate Date,
	@rEndDate Date,
	@rOrgGroupId int = 0,
	@rAccountingYearId [int],
	@rLedgerId [int],
	@rLedgerMainGroupId [int],
	@rLedgerGroupId [int],
	@rAccountId int=0,
	@rChequeClearDate date
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

--SELECT '' AS OrgTitle,
--	   '' AS SmallAddress1,
--       '' As SmallAddress2,
--	   '' As Builder1,
--	   '' As Builder2,
--	   '' As Id,
--	   '' As LedgerId,
--	   '' As LedgerName,
--	   '' As OpBalance,
--	   '' As CrBalance,
--	   '' As DrBalance,
--	   '' As ClBalance,
--       '' As LedgerGroupId




Declare @LedgerId int 
Declare @LOpeningBalance Decimal (12,2)
Declare @OpeningBalance Decimal (12,2)
Declare @lClOsingBalance Decimal (12,2)
Declare @CreditBalance Decimal (12,2)
Declare @DebitBalance Decimal (12,2)
Declare @lCount int
Declare @lLedgerTypeId int
Declare @LedgerName Nvarchar(150)
Declare @LedgerGroupId int
Declare @ReportOrgTitle Nvarchar(200)
Declare @SmallAddress1  Nvarchar(200)
Declare	@SmallAddress2 Nvarchar(200)
	

  
  SELECT @ReportOrgTitle=ReportOrgTitle ,@SmallAddress1=SmallAddress1, @SmallAddress2= SmallAddress2  
  From sAccounting.tAccountMaster AM Where AM.Id= @rAccountId  
  
  
    DECLARE @1OpeningBalance DECIMAL(22,2)
    DECLARE @1ClosingBalance DECIMAl(22,2)
     
	CREATE TABLE #tempUpdateClosingBalance
	(	
	    Id INT IDENTITY (1, 1),
		LedgerId int,
		Temp_Op_Balance decimal(12,2),
		Closing_Balance decimal(12,2),
		Transaction_Balance decimal(12,2)	    
	) 
	
	INSERT INTO #tempUpdateClosingBalance (LedgerId,Temp_Op_Balance,Closing_Balance,Transaction_Balance)
	EXEC [sAccounting].[pUpdateClosingBalance] @rStartDate,@rEndDate,@rOrgGroupId,@rAccountingYearId,@rLedgerId,''
		
	SELECT @1OpeningBalance = Temp_Op_Balance,@1ClosingBalance = Closing_Balance
	FROM #tempUpdateClosingBalance WHERE LedgerId = @rLedgerId

  
 	SELECT @1OpeningBalance AS OPeningBalance,
 	T.TransactionDate,
 	T.Id,T.Chequeno,
 	ISNULL(T.ChequeDate,'1900-01-01') as ChequeDate,
 	L.Title, 
	ISNULL(CASE WHEN TD.TransactionTypeId = 1 THEN -1 * SUM(TD.AMOUNT) END,0) AS CREDIT,
	ISNULL(CASE WHEN TD.TransactionTypeId = 2 THEN SUM(TD.AMOUNT) END,0) AS DEBIT,
	ISNULL(IsChequeCleared,0) AS IsChequeCleared,
	ISNULL(T.ChequeClearDate,getdate()) AS ChequeClearDate
	from sAccounting.tTransactionDetail TD 
	INNER JOIN sAccounting.tLedgerMAster L ON L.Id = TD.LedgerId 
	INNER JOIN sAccounting.tTransaction T ON T.Id = TD.TransactionId AND T.AccountingYearId = L.AccountingYearId
	Where TD.TransactionId IN
	(Select TD1.TransactionId FRom sAccounting.tTransactionDetail TD1 Where TD1.LedgerId = @rLedgerId)
	and TD.LedgerId <> @rLedgerId  AND T.AccountingYearId =@rAccountingYearId
	AND T.TransactionDate >= @rStartDate AND T.TransactionDate <= @rEndDate
	AND (T.ChequeClearDate = @rChequeClearDate OR ISNULL(@rChequeClearDate,'') = '')
	Group by T.TransactionDate,T.Id,T.Chequeno,T.ChequeDate,TD.TransactionTypeId,L.Title,IsChequeCleared,ChequeClearDate	
	
	drop table #tempUpdateClosingBalance
END
GO
PRINT N'Altering [sAccounting].[pTransactionAdd]...';


GO

ALTER PROCEDURE [sAccounting].[pTransactionAdd]
	 
	        @rId bigint
	       ,@rOrgGroupId int
           ,@rAccountingYearId int
           ,@rTransactionDate date
           ,@rNarration nvarchar(150)           
           ,@rVoucherNumber bigint
           ,@rVoucherTypeId tinyint
           ,@rIsProfitAndLoss int
           ,@rRepeatLedger int
           ,@rCreatedUserId bigint
           ,@rChequeNo nvarchar(10)
           ,@rBankName nvarchar(100)
           ,@rChequeDate datetime
           ,@rTransactionApproveId bigint=null
           
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	BEGIN TRANSACTION	
	DECLARE @lNextNumber BIGINT
	DECLARE @1AccountId int 
	
	IF (@rId = 0)  AND  EXISTS (Select 1 FROM sAccounting.tTransaction where AccountingYearId = @rAccountingYearId AND VoucherNumber = @rVoucherNumber AND VoucherTypeId = @rVoucherTypeId AND OrgGroupId = @rOrgGroupId)
	  BEGIN
	        SELECT -111 AS Result
	  END
  
    ELSE IF(@rId = 0)	
	BEGIN
		
    Select @1AccountId = AccountId from sAccounting.tAccountingYearMaster where Id = @rAccountingYearId 
    EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sAccounting.tTransaction', 0, 1, 1,@outNextNumber = @lNextNumber output
	--EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sAccounting.tTransaction',@lNextNumber = @lNextNumber output
	
	INSERT INTO [sAccounting].[tTransaction]
			   (
			    [Id]
			   ,OrgGroupId
			   ,[AccountingYearId]
			   ,[TransactionDate]
			   ,[Narration]
			   ,[VoucherNumber]
			   ,[VoucherTypeId]
			   ,[IsProfitAndLoss]
			   ,[RepeatLedger]
			   ,[CreatedUserId]
			   ,[CreatedDateTime]
			   ,AccountId
			   ,[ChequeNo]
			   ,[BankName]
			   ,[ChequeDate]
			   ,TransactionApproveId
			   )
		 VALUES
			   (
				@lNextNumber
			   ,@rOrgGroupId
			   ,@rAccountingYearId
			   ,@rTransactionDate
			   ,@rNarration
			   ,@rVoucherNumber
			   ,@rVoucherTypeId
			   ,@rIsProfitAndLoss
			   ,@rRepeatLedger
			   ,@rCreatedUserId
			   ,sCommon.fGetDate()
			   ,@1AccountId
			   ,@rChequeNo
			   ,@rBankName
			   ,@rChequeDate
			   ,@rTransactionApproveId
			   )
		    SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION         
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  [sAccounting].[tTransaction]
	    SET
			 
	          AccountingYearId=@rAccountingYearId
	         ,TransactionDate = @rTransactionDate 
             ,Narration = @rNarration
             ,VoucherNumber=@rVoucherNumber
             ,VoucherTypeId=@rVoucherTypeId
             ,IsProfitAndLoss=@rIsProfitAndLoss
             ,RepeatLedger=@rRepeatLedger
             ,UpdatedUserId=@rCreatedUserId
             ,UpdatedDateTime= sCommon.fGetDate() 
             ,ChequeNo = @rChequeNo
             ,ChequeDate = @rChequeDate
             ,BankName = @rBankName         
             
	      WHERE Id = @rId 	   
	      SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION
	 END  	

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


GO

ALTER PROCEDURE [sActivity].[pAssignHouseGet]
          
           @rClassId int,
           @rDivisionId int,
           @rHouseGroupId int=0,
           @rHouseId int,
           @rOrgId int,
           @rBatchId int,
           @rStatusId int=0
          
AS
SET NOCOUNT ON

BEGIN
SELECT  
		SO.StudentId,
		SO.Code,
		SO.Name,
		SO.ClassName+'-'+SO.DivisionName AS ClassName,
		ISNULL(SO.HouseId,0) HouseId,
		SO.RollNo,
		So.DivisionId
		
  FROM sStudent.vStudentOther SO
  LEFT JOIN sActivity.tHouseMaster HM ON HM.Id = SO.HouseId
	
  WHERE 
		(SO.ClassId=@rClassId OR @rClassId=0)
	AND (SO.DivisionId=@rDivisionId OR @rDivisionId=0)
	AND (HM.HouseGroupId=@rHouseGroupId OR @rHouseGroupId=0)
	AND (SO.HouseId=@rHouseId OR @rHouseId=0)
    AND (SO.StatusId=@rStatusId OR @rStatusId=0)
	AND (SO.OrgId = @rOrgId) 
	AND (SO.BatchId=@rBatchId)
	ORDER BY SO.ClassId,SO.DivisionId,SO.RollNo
END
GO
PRINT N'Altering [sActivity].[pXMLEventHoliday]...';


GO


ALTER PROCEDURE [sActivity].[pXMLEventHoliday]
	(
		@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
	
	DECLARE @lNextNumber BIGINT    
	DECLARE @lOrgId smallint
	DECLARE @lCount int
	DECLARE @lDivisionId int
	DECLARE @lEventSchduleCount int
	DECLARE @lEventSchduleId int
	
	
	-----------------------  UPDATE EventSchedule
	UPDATE sActivity.tEventSchedule
	SET	
		FromDate = A.FromDate,
		ToDate = A.ToDate,
		Title = A.Title,
		UpdatedUserId = 9999000000003,
		UpdatedDateTime = sCommon.fGetDate() 
	FROM 
	(
	SELECT
		Id,
		FromDate,
		ToDate,
		Title,
		BatchId
	FROM OPENXML (@intDoc, '/Table/Holiday', 1)
	WITH
	(
		Id int '@Id',
		FromDate datetime '@FromDate',
		ToDate datetime '@ToDate',
		Title nvarchar(100) '@Title',
		BatchId int '@BatchId'	
	))A
	 WHERE sCommon.fGetIntIdForOrg(A.Id,@rOrgId) = sActivity.tEventSchedule.Id 
	AND sCommon.fGetIntIdForOrg(A.BatchId,@rOrgId) = sActivity.tEventSchedule.BatchId 
	

	-----------------------  INSERT EventSchedule holiday
	INSERT INTO sActivity.tEventSchedule
	(
		Id,
		BatchId,
		FromDate,
		ToDate,
		Title,
		IsCommonForAll,
		IsEnrollment,
		IsHoliday,
		CreatedUserId,
		CreatedDateTime
	)
	SELECT		
		sCommon.fGetIntIdForOrg(A.Id,@rOrgId),
		A.BatchId,
		A.FromDate,
		A.ToDate,
		A.Title,
		1,
		1,
		1,
		9999000000003,
		sCommon.fGetDate()
		
	FROM OPENXML (@intDoc, '/Table/Holiday', 1)
	WITH
	(
		Id int '@Id',
		FromDate datetime '@FromDate',
		ToDate datetime '@ToDate',
		Title nvarchar(100) '@Title',
		BatchId int '@BatchId'	
	) A LEFT JOIN sActivity.tEventSchedule ES ON 
	sCommon.fGetIntIdForOrg(A.Id,@rOrgId) = ES.Id AND A.BatchId = ES.BatchId
	WHERE ES.Id IS NULL 
	
	DECLARE @lEvetntTypeId int

	SELECT @lEvetntTypeId= Id FRom sActivity.tEventTypeMaster ET Where EventMainTypeId = 1 AND OrgGroupId IN
	(select OrgGroupId from sSetup.tOrganizationMaster Where Id = @rOrgId)
	
	
	Update ES SET ES.EventTypeId = @lEvetntTypeId From sActivity.tEventSchedule ES inner join 
	(SELECT sCommon.fGetIntIdForOrg(A.Id,@rOrgId) AS Id	,BatchId	
	FROM OPENXML (@intDoc, '/Table/Holiday', 1)
	WITH
	(
		Id int '@Id',
		BatchId int '@BatchId'	
	)A) A1  ON 
	A1.Id = ES.Id AND A1.BatchId = ES.BatchId
	
	
	CREATE Table #EventSchedule (Id Int Identity,EventScheduleId int)
	
	Insert Into #EventSchedule SELECT sCommon.fGetIntIdForOrg(A.Id,@rOrgId)		
	FROM OPENXML (@intDoc, '/Table/Holiday', 1)
	WITH
	(
		Id int '@Id',
		BatchId int '@BatchId'	
	) A INNER JOIN sActivity.tEventSchedule ES ON 
	sCommon.fGetIntIdForOrg(A.Id,@rOrgId) = ES.Id AND A.BatchId = ES.BatchId
	
	
	SELECT @lEventSchduleCount = Max(Id) FROM #EventSchedule
	
	CREATE Table #Division (Id Int Identity,DivId int)
	Insert into #Division Select Id From sSetup.tDivisionMaster Where OrgId = @rOrgId
	Select @lCount = Max(id) From #Division	
	While @lEventSchduleCount > 0
	BEGIN
		SELECT @lEventSchduleId = EventScheduleId From #EventSchedule Where Id = @lEventSchduleCount		
		While @lCount > 0 
		BEGIN
			SELECT @lDivisionId = DivId From #Division Where Id = @lCount			
			IF NOT EXISTS (SELECT 1 FROM sActivity.tEventAssign WHERE SourceTypeId = 2005 AND EventScheduleId = @lEventSchduleId AND SourceId = @lDivisionId )
			BEGIN
				Exec [sActivity].[pEventAssignAdd] 0,@lEventSchduleId,2005,@lDivisionId,0,@rOrgId	
			END
			SET @lCount = @lCount - 1
		END
		SET @lEventSchduleCount = @lEventSchduleCount  -1
	END	      
           
	
	Drop Table #Division
	EXEC sp_xml_removedocument @intDoc
	COMMIT TRANSACTION
	SELECT 1
	END TRY
	BEGIN CATCH
	SELECT -1
	END CATCH

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


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

BEGIN 
		--IF @rIsSearch = 1
		BEGIN
		SET @rFirstName = ISNULL(@rFirstName,'')
		SET @rLastName = ISNULL(@rLastName,'')
			SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
			SET @rLastName = sCommon.fSearchStringGet(@rLastName)
		END
	
	SELECT 
			 AF.Id
			,AF.FormNo
			,AF.FirstName
			,AF.MiddleName
			,AF.LastName
			,AF.FirstName+' '+AF.LastName as Name
			,AF.ForClassId
			,AF.BatchId
			,CM.Title AS ClassName
			,AF.ForBatch
			,ISNULL(AF.DateOfBirth,'') AS DateOfBirth
			,AF.DateOfBirthInWord
			,AF.StatusId
			,SM.Title as StatusName
			,ISNULL(ASM.Title,'') AS FormStatus
			,AF.StreetOne
			,AF.StreetTwo
			,AF.StreetThree
			,AF.Country
			,AF.State
			,AF.City
			,AF.ZipCode
			,AF.ContactNo
			,AF.ContactEmail
			,AF.Remark
			,AF.PreviousSchool
			,AF.MeritMarks
			,AF.MeritGrade
			,AF.GenderId
			,ISNULL(GM.Title,'') AS Gender
			,ISNULL(AF.ReligionId,0) AS ReligionId
			,AF.FamilyCast
			,AF.FamilySubCast
			,ISNULL(AF.CastCategoryId,0) AS CastCategoryId
			,AF.CreatedDateTime AS AdmissionFormDate
			,ISNULL(AF.StudentId,0) AS StudentId
			,AF.StudentPhoto,
			ISNULL(AFFD.FatherName,'') AS FatherName,
			Isnull(AFFD.FatherDateOfBirth,'') AS FatherDateOfBirth,
			Isnull(AFFD.FatherOccupation,'') AS FatherOccupation,
			Isnull(AFFD.FatherQualification,'') AS FatherQualification,
			Isnull(AFFD.FatherContactNo,'') AS FatherContactNo,
			Isnull(AFFD.FatherMail,'') AS FatherMail,
			Isnull(AFFD.FatherOfficeAddress,'') As FatherOfficeAddress,
			Isnull(AFFD.FatherIncome,'') as FatherIncome,
			Isnull(AFFD.MotherName,'') AS MotherName,
			iSNULL(AFFD.MotherDateOfBirth,'')AS MotherDateOfBirth,
			isnull(AFFD.MotherOccupation,'') AS MotherOccupation,
			isnull(AFFD.MotherQualification,'') AS MotherQualification,
			isnull(AFFD.MotherContactNo,'') as MotherContactNo,
			isnull(AFFD.MotherMail,'') As MotherMail,
			isnull(AFFD.MotherOfficeAddress,'') as MotherOfficeAddress,
			isnull(AFFD.MotherIncome,'') as MotherIncome,
		 
			isnull(AFFD.RelationshipName,'') as RelationshipName,
			isnull(AFFD.RelativeName,'')  AS GuardianName ,
			isnull(AFFD.RelativeDateOfBirth ,'')AS GuardianDateOfBirth,
			isnull(AFFD.RelativeOccupation,'') AS GuardianOccupation,
			isnull(AFFD.RelativeQualification,'') AS GuardianQualification,
			isnull(AFFD.RelativeContactNo,'') AS GuardianContactNo,
			isnull(AFFD.RelativeMail,'')  AS GuardianMail,
			isnull(AFFD.RelativeOfficeAddress,'') AS GuardianOfficeAddress,
			isnull(AFFD.RelativeIncome,'') AS GuardianIncome  ,
			isnull(AF.IsHostelRequired,0) AS IsHostelRequired  ,
			isnull(AF.IsTransportRequired,0) AS IsTransportRequired,
			isnull(AF.BirthPlace,'') AS BirthPlace,
			isnull(AF.BirthTaluka,'') AS BirthTaluka,
			isnull(AF.BirthDistrict,'') AS BirthDistrict,
			isnull(AF.BloodGroupId,0) AS BloodGroupId,
			isnull(AF.AdhaarNumber,'') AS AdhaarNumber,
			isnull(AF.IsPysicalDeformity,0) AS IsPysicalDeformity,
			isnull(AF.PysicalDeformityRemark,'') AS PysicalDeformityRemark,
			isnull(AF.IsMajorIllness,0) AS IsMajorIllness,
			isnull(AF.MajorIllnessRemark,'') AS MajorIllnessRemark,
			isnull(AF.IsAllergy,0) AS IsAllergy,
			isnull(AF.AllergyRemark,'') AS AllergyRemark,
			isnull(AF.BirthState,'') AS BirthState,
			isnull(AF.BirthCountry,'') AS BirthCountry,
			isnull(SA.PreviousStandard,'') As PreviousStandard
	         
			--isnull(ASB.SiblingName,'') AS SiblingName,
			--isnull(ASB.SiblingRelation,'')AS SiblingRelation,
			
			--isnull(ASB.SiblingStandard,'') AS SiblingStandard,
			--isnull(ASB.SiblingSchool,'')AS SiblingSchool
			 
			 
  FROM 
            sAdmission.tAdmissionForm AF
			INNER JOIN sCommon.tStatusMaster SM ON SM.Id=AF.StatusId
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=AF.ForClassId
			LEFT JOIN sCommon.tGenderMaster GM ON GM.Id=AF.GenderId
			LEFT JOIN sAdmission.tAdmissionFormSelected AFS ON AF.Id = AFS.AdmissionFormId
			LEFT JOIN sAdmission.tAdmissionStatusMaster ASM ON ASM.Id = AFS.AdmissionStatusId
			LEFT JOIN sAdmission.tAdmissionFormFamilyDetail AFFD ON AFFD.AdmissionFormId = AF.Id
			 --LEFT JOIN sAdmission.tAdmissionFormSibling ASB ON ASB.AdmissionFormId = AF.Id
			LEFT JOIN sStudent.tStudentAdmission SA ON SA.StudentID=AF.StudentID
  WHERE 
  
      ((AF.Id = @rAdmissionFormId) OR (@rAdmissionFormId = 0))
		AND ((AF.FormNo=@rFormNo) OR (@rFormNo=0))
		AND ((AF.FirstName like @rFirstName) OR (@rFirstName=''))
		AND ((AF.LastName like @rLastName) OR (@rLastName=''))
		AND ((AF.CreatedDateTime>= @rFromDate) OR (@rFromDate=''))
		AND ((AF.CreatedDateTime < @rToDate) OR (@rToDate=''))
		AND ((AF.StatusId=@rStatusId) OR (@rStatusId=0))
		AND ((AF.ForClassId=@rForClassId) OR (@rForClassId=0)) 
		AND ((AF.BatchId=@rBatchId) OR (@rBatchId=0)) 
		--AND ((AF.MeritMarks=@rMeritMarks) OR (@rMeritMarks=0))
		
		AND ((AF.StatusId=@rStatusId) OR (@rStatusId = ''))
		AND ((CM.DepartmentId=@rDepartmentId) OR (@rDepartmentId = 0))
		AND AF.OrgId=@rOrgId
        AND ((ISnull(AF.IsHostelRequired,0)=@rIsHostelFilter ) OR   (ISNULL(@rIsHostelFilter,2)=2) )
	   AND ((ISNUll(AF.IsTransportRequired,0)=@rIsTransportFilter) OR (isnull(@rIsTransportFilter,0) = 2))
	  
 order by AF.FormNo
END
GO
PRINT N'Altering [sAdmission].[pAdmissionHSCDetailAdd]...';


GO
ALTER PROCEDURE [sAdmission].[pAdmissionHSCDetailAdd]
	    @rId bigint,
		@rHSCSchoolName	nvarchar(200),
		@rIsHSCSchoolLocal	bit,
		@rHSCStreamId	int,
		@rHSCSeatNo	nvarchar(20),
		@rHSCJoinDate	date,
		@rHSCLeaveDate	date,
		@rHSCNoOfTrials	tinyint,
		@rHSCPassingMonth	tinyint,
		@rHSCPassingYear	tinyint,
		@rHSCTotalMarks	smallint,
		@rHSCObtainMarks	smallint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
 BEGIN TRANSACTION	
	
	IF NOT EXISTS (Select AdmissionFormId from sAdmission.tAdmissionHSCDetail where AdmissionFormId = @rId)
	BEGIN
	INSERT INTO sAdmission.tAdmissionHSCDetail
		(
		AdmissionFormId,
		HSCSchoolName,
		IsHSCSchoolLocal,
		HSCStreamId,
		HSCSeatNo,
		HSCJoinDate,
		HSCLeaveDate,
		HSCNoOfTrials,
		HSCPassingMonth,
		HSCPassingYear,
		HSCTotalMarks,
		HSCObtainMarks

		)
	VALUES
		(
	    @rId,
		@rHSCSchoolName,
		@rIsHSCSchoolLocal,
		@rHSCStreamId,
		@rHSCSeatNo,
		@rHSCJoinDate,
		@rHSCLeaveDate,
		@rHSCNoOfTrials,
		@rHSCPassingMonth,
		@rHSCPassingYear,
		@rHSCTotalMarks,
		@rHSCObtainMarks
		)
		             
	END	 
	 ELSE
	 BEGIN

	    UPDATE  sAdmission.tAdmissionHSCDetail
	    SET
		HSCSchoolName=@rHSCSchoolName,
		IsHSCSchoolLocal=@rIsHSCSchoolLocal,
		HSCStreamId=@rIsHSCSchoolLocal,
		HSCSeatNo=@rHSCSeatNo,
		HSCJoinDate=@rHSCJoinDate,
		HSCLeaveDate=@rHSCLeaveDate,
		HSCNoOfTrials=@rHSCNoOfTrials,
		HSCPassingMonth=@rHSCPassingMonth,
		HSCPassingYear=@rHSCPassingYear,
		HSCTotalMarks=@rHSCTotalMarks,
		HSCObtainMarks =@rHSCObtainMarks
	      WHERE AdmissionFormId = @rId 	
	 END  
		SELECT @rId AS Result
	
		COMMIT TRANSACTION
		
	
	
		
END
GO
PRINT N'Altering [sAdmission].[pAdmissionInquiryGet]...';


GO
ALTER PROCEDURE [sAdmission].[pAdmissionInquiryGet]
	
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='',
	 @rId bigint = 0,
	 
	 @rForClassId int = 0,
	 @rClassId int = 0,
	 @rBatchId int = 0,
	 @rStatusId int =0,
	-- @rStatusId smallint,
	 @rInquiryStatusMasterId int = 0,
	 @rOrgId int,
	 @rFirstName nvarchar(100) = '',
	 @rLastName nvarchar(100) = '',
	 @rFromDate datetime='',
	 @rToDate datetime='',
	 @rForBatchId int = 0,
	 @rDepartmentId int,
	 @rFromMeritMarks decimal(10,2) = 0,
	 @rToMeritMarks decimal(10,2)=0,
	 @rInquiryModeId smallint=0,
	 @rInquiryReferenceId int=0,
	 @rNumber bigint=0,
	 @rOrgGroupBatchId int = 0,
	 @rFollowUpdate datetime='',
	 @rIsTransportRequired int=0,
	 @rIsHostelRequired int=0	
	 
	 
	 --@rIsSearch bit = 1
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 
	 SET @rToDate = DATEADD(d,1,@rToDate)
	 --IF @rIsSearch = 1
		BEGIN
			SET @rFirstName= sCommon.fSearchStringGet(@rFirstName)
			SET @rLastName= sCommon.fSearchStringGet(@rLastName)
		END
	
	SELECT 
	
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			 AI.Id
			,AI.ForBatchId
			,AI.ForClassId
			,AI.StatusId
			,ISNULL(SM.Id,0) AS InquiryStatusMasterId
			,ISNULL(AI.GenderId,0) AS GenderId
			,ISNULL(AI.InquiryModeId,0) AS InquiryModeId
			,ISNULL(AI.InquiryReferenceId,0) AS InquiryReferenceId		
		    ,ISNULL(AI.AdmissionCategoryId,0) AS AdmissionCategoryId
		    ,AI.OrgId
		    ,ISNULL(AI.Number,0) AS InquiryNumber
		    ,ISNULL(AI.InquiryDate,'') AS AdmissionInquiryDate 		    
		    ,OM.DisplayTitle AS OrgName
		    ,BM.Title AS ForBatch
			,ISNULL(CM.Title,'') AS ClassName	
			,AI.FirstName
			,AI.MiddleName
			,AI.LastName
			,AI.LastName +' ' +AI.FirstName+' '+AI.MiddleName as Name				
			,AI.DateOfBirth
			,ISNULL(GM.Title,'') As Gender			
			,AI.ContactNo
			,AI.ContactEmail			
			,AI.StreetOne
			,AI.StreetTwo
			,AI.StreetThree
			,AI.Country
			,AI.State
			,AI.City
			,AI.ZipCode
			,ISNULL(AI.Remark,'') AS Remark						
		    ,ISNULL(AI.PreviousSchool,'') as PreviousSchool			
			,ISNULL(AI.MeritMarks,0) AS MeritMarks
			,ISNULL(AI.MeritGrade,'') AS MeritGrade
			,ISNULL(AI.MeritMarksBreakup,'') AS MeritMarksBreakup
			,SM.Title as StatusName			
			,ISNULL(AI.FollowupDate,'') As FollowupDate
			,ISNULL(AI.FollowupRemark,'') As FollowupRemark			
			,ISNULL(IRM.Title ,'') AS InquiryReference	
			,ISNULL(SCM.Title,'') AS AdmissionCategory		
			,ISNULL(AI.HandledBy,'') AS HandledBy
			,AI.CreatedDateTime
			,ISNULL(AI.StudentId,0) AS StudentId,
			ISNULL(AI.CastCategoryId,0) AS CastCategoryId,
			ISNULL(AI.IsTransportRequired,0) AS IsTransportRequired,
			ISNULL(AI.IsHostelRequired,0) AS IsHostelRequired,
			ISNULL(SM.HighlightColor,'') AS HighlightColor,
			ISNULL(SA.PreviousStandard,'') As PreviousStandard
  FROM 
            sAdmission.tAdmissionInquiry AI
           --INNER JOIN sCommon.tStatusMaster SM ON SM.Id=AI.StatusId AND StatusTypeId=104
            INNER JOIN sAdmission.tInquiryStatusMaster SM ON SM.Id=AI.InquiryStatusId 
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=AI.ForClassId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=AI.OrgId
			INNER JOIN sSetup.tBatchMaster BM ON AI.ForBatchId = BM.Id
			LEFT JOIN sAdmission.tInquiryReferenceMaster IRM ON IRM.Id=AI.InquiryReferenceId
			LEFT JOIN sStudent.tAdmissionCategoryMaster SCM ON SCM.Id=AI.AdmissionCategoryId
			LEFT JOIN sCommon.tGenderMaster GM ON GM.Id=AI.GenderId
			LEFT JOIN sStudent.tStudentAdmission SA oN SA.StudentId=AI.StudentID
  WHERE  
      ((AI.Id = @rId) OR (@rId = 0))
      AND ((AI.FirstName like @rFirstName) OR (@rFirstName=''))
      AND ((AI.LastName like @rLastName) OR (@rLastName=''))
      AND ((AI.InquiryDate>= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
      AND ((AI.InquiryDate < @rToDate) OR (ISNULL(@rToDate,'')=''))
	  AND ((AI.ForClassId=@rForClassId) OR (@rForClassId=0)) 
	  --AND ((AI.StatusId=@rStatusId) OR (@rStatusId=0))
	  AND ((SM.Id=@rInquiryStatusMasterId) OR (@rInquiryStatusMasterId=0))
	  AND (AI.OrgId=@rOrgId OR @rOrgId=0)
	  AND ((AI.ForBatchId=@rForBatchId) OR (@rForBatchId=0))
	  AND ((CM.DepartmentId=@rDepartmentId) or (@rDepartmentId = 0))
	  AND ((AI.MeritMarks >= @rFromMeritMarks) OR (@rFromMeritMarks=0))
	  AND ((AI.MeritMarks <= @rToMeritMarks) OR (@rToMeritMarks=0))
	  AND ((AI.InquiryModeId=@rInquiryModeId) OR (@rInquiryModeId=0))
	  AND ((AI.InquiryReferenceId=@rInquiryReferenceId) OR (@rInquiryReferenceId=0))
	  AND ((AI.Number=@rNumber) OR (@rNumber=0))
	  AND (BM.OrgGroupBatchid=@rOrgGroupBatchId)
	  AND ((AI.FollowUpdate=@rFollowupdate) OR (ISNULL(@rFollowUpdate,'')=''))
	  AND (AI.IsTransportRequired = CASE @rIsTransportRequired
                              WHEN 0 THEN AI.IsTransportRequired
                              WHEN 2 THEN 0
                              WHEN 1 THEN 1
                         END)
	  
	  AND (AI.IsHostelRequired = CASE @rIsHostelRequired
                              WHEN 0 THEN AI.IsHostelRequired
                              WHEN 2 THEN 0
                              WHEN 1 THEN 1
                         END)
	  --AND ((AI.IsTransportRequired=@rIsTransportRequired) OR (@rIsTransportRequired=0))	   
	    --AND ((AI.IsHostelRequired =@rIsHostelRequired) OR (@rIsHostelRequired=0))
	  Order by AI.Number DESC 
END
GO
PRINT N'Altering [sAssessment].[pActivityDefaultAdd]...';


GO
 
 
ALTER PROCEDURE [sAssessment].[pActivityDefaultAdd]
	 @rStrXml [nvarchar](max),
	 @rOrgId int	
AS
BEGIN
 
	SET NOCOUNT ON;
	SET @rStrXml=REPLACE(@rStrXml,'&','AND')
	DECLARE @loDoc INT
	EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml
BEGIN 
	 BEGIN	
		if exists(select 1 
		FROM sAssessment.tCCESubjectSubActivityExamScore AI
		INNER JOIN OPENXML (@loDoc, '/Table/SubjectActivityScoreBulk', 1)
			WITH ( 				
						AcademicId bigint,
						SubjectSubActivityId int,
						ExamId int,
						Term1Grade nvarchar(20),
						GradeTitle nvarchar(50)
									
				  ) A 	ON AI.AcademicId = A.AcademicId AND AI.ExamId=A.ExamId
		AND A.SubjectSubActivityId = AI.SubjectSubActivityId 
		)
		BEGIN
		SELECT 1 AS Result
			return
			 
		END
		Else
		
		INSERT INTO  sAssessment.tCCESubjectSubActivityExamScore
			(ExamId,AcademicId,SubjectSubActivityId,Grade,GradeIndicator)
			
			SELECT	
			A.ExamId,A.AcademicId,A.SubjectSubActivityId,Term1Grade,GradeTitle
         			
			FROM OPENXML (@loDoc, '/Table/SubjectActivityScoreBulk', 1)
			WITH ( 				
					ExamId int,
					AcademicId bigint,					
					Term1Grade nvarchar(20),
					GradeTitle nvarchar(50),
					SubjectSubActivityId int
				  ) A  LEFT JOIN sAssessment.tCCESubjectSubActivityExamScore AI ON AI.AcademicId = A.AcademicId AND AI.ExamId=A.ExamId  AND A.SubjectSubActivityId = AI.SubjectSubActivityId 
			       WHERE (AI.AcademicId IS NULL AND AI.ExamId IS NULL AND AI.SubjectSubActivityId IS NULL)
			  
 			SELECT 1 AS Result
	END		
	 
END
END
GO
PRINT N'Altering [sAssessment].[pCSClassActivityAdd]...';


GO


ALTER PROCEDURE [sAssessment].[pCSClassActivityAdd]
	 
     --       @rAcademicId bigint
     --      ,@rExamId int
     --      ,@rIndicator nvarchar(200)
		   --,@rGrade nvarchar(10)
		   --,@rDescriptiveIndicator nvarchar(max)
		   
		   @rCCECSId int,
		   @rClassId int,
		   @rTotalMark decimal(12,2)=0,
		   @rConvertToMark decimal(12,2)=0,
		    @rIsDeleted int,
		    @rIsOptional int=0,
		    @rBatchID int
		   --,@rIndicatodIds nvarchar(50)
		   --,@rIsIndicatodIds bit
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
 
	 
	  
IF   EXISTS(SELECT 1 FROM sAssessment.tCCECSForClass WHERE CCECSId=@rCCECSId AND ClassId=@rClassId and @rIsDeleted=0 AND  BatchId=@rBatchID)
BEGIN
	Delete from sAssessment.tCCECSForClass where CCECSId =@rCCECSId ANd ClassId =@rClassID AND BatchId=@rBatchID
	 SELECT 1 AS Result
END
ELSE 
BEGIN
	IF exists(Select 1 from sAssessment.tCCECSForClass where CCECSId=@rCCECSId AND ClassId=@rClassId  AND @rIsDeleted=1 ANd BatchId=@rBatchID)
	BEGIN
		Update sAssessment.tCCECSForClass 
		Set
			CCECSId =@rCCECSId,
			ClassId=@rClassId,
			TotalMark=@rTotalMark,
			ConvertToMark=@rConvertToMark,
			IsOptional =@rIsOptional
			Where CCECSId=@rCCECSId AND ClassId=@rClassId 
			AND BatchID=@rBatchID
			Select 1 as Result
	END
	ELSE
	BEGIn
		IF @rIsDeleted=1
		BEGIN
			INSERT INTO sAssessment.tCCECSForClass
			   (
			    [CCECSId]
			   ,ClassId
			   ,TotalMark
			   ,ConvertToMark,
			   IsOptional
			   ,BatchId
			   )
		 VALUES
			   (
				@rCCECSId
			   ,@rClassId	
			   , @rTotalMark
			   , @rConvertToMark,
			   @rIsOptional,
			   @rBatchID
			   )
			   Select 1 as Result
		END	
		 
		
	END
END


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


GO


ALTER PROCEDURE [sAssessment].[pCSClassAdd]
	 
	        @rId int
           ,@rCCECSGroupId int
           ,@rClassId int
		   ,@rUpdatedUserId bigint
		   ,@rOrgId bigint
		   ,@rIsDeleted bit
		   ,@rOrderIndex smallint
		   ,@rBatchId int
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 
IF(@rId = 0 AND @rIsDeleted = 1 )	
BEGIN
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAssessment.tCCECSClass', 0, 1, 1,@outNextNumber = @lNextNumber output
	INSERT INTO [sAssessment].[tCCECSClass]
			   (
			    [Id]
			   ,[CCECSGroupId]
			   ,[ClassId]
			   ,[OrderIndex]
			   ,[UpdatedUserId]
			   ,[UpdatedDateTime]
			   ,BatchId
			   )
		 VALUES
			   (
				@lNextNumber
			   ,@rCCECSGroupId
			   ,@rClassId
			   ,@rOrderIndex
			   ,@rUpdatedUserId			   
			   ,sCommon.fGetDate()
			   ,@rBatchId
			   )
		    SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION         
	END	 
ELSE
 BEGIN
   IF @rIsDeleted = 1
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  [sAssessment].[tCCECSClass]
	    SET
			 
	          [CCECSGroupId]=@rCCECSGroupId
	         ,ClassId=@rClassId
	         ,OrderIndex = @rOrderIndex
			 ,UpdatedUserId =@rUpdatedUserId
			 ,UpdatedDateTime=sCommon.fGetDate()
	      WHERE Id = @rId And BatchId=@rBatchId 	   
	      SELECT @lNextNumber AS Result
	  END    
   ELSE IF EXISTS (SELECT 1 FROM sAssessment.tCCECSExamScore CS
				   INNER JOIN sStudent.tAcademic A ON CS.AcademicId = A.Id 
				   INNER JOIN sAssessment.tCCECSMaster CM ON CM.Id = CS.CCECSId				  
				   INNER JOIN sAssessment.tCCECSGroupMaster CGM ON CGM.Id = CM.CCECAGroupId 
				   INNER JOIn sAssessment.tCCECSClass CL ON Cl.ClassId=A.ClassId AND CL.CCECSGroupId=@rCCECSGroupId AND CL.BatchId =@rBatchId   
				   WHERE A.ClassId = @rClassId AND CGM.Id = @rCCECSGroupId  ANd A.BatchId=@rBatchId)
				   
	  BEGIN
		SELECT -101 AS RESULT
	  END	  	
   ELSE
	BEGIN
		DELETE FROM sAssessment.tCCECSClass WHERE Id = @rId ANd BatchId=@rBatchId
		SELECT 1 AS RESULT
	END	
		--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].[pCSClassGet]...';


GO
ALTER PROCEDURE [sAssessment].[pCSClassGet]
	  @rClassId int,
	  @rOrgId int,
	  @rbatchid int
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 		
SELECT 
			ISNULL(FS.Id,0) AS Id,
			ISNULL(FGM.ID,0) AS CCEFSGroupId,
			ISNULL(FS.ClassId,0) AS ClassId,			
			FGM.Title AS CCECSGroupName,
			ISNULL(FS.OrderIndex ,0) AS OrderIndex,
			CASE WHEN ISNULL(FS.ClassId,0)=0 THEN 'false' ELSE 'true' END AS Selected
FROM 
			
			sAssessment.tCCECSGroupMaster FGM 
			LEFT JOIN sAssessment.tCCECSCLASS FS ON FGM.Id=FS.CCECSGroupId	
			AND (FS.ClassId=@rClassId OR @rClassId=0) ANd FS.BatchId=@rbatchid
	WHERE FGM.OrgId =   @rOrgId
				
			  
END
--SELECT * FROM sAssessment.tCCECSClass
--SELECT * FROM sAssessment.tCCECSGroupMaster 
GO
PRINT N'Altering [sAssessment].[pCSClassGroupActivityGet]...';


GO
ALTER PROCEDURE [sAssessment].[pCSClassGroupActivityGet]
 
	  @rOrgId int,
	 
	  @rClassId int,
	  @rBatchID int
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 	
 
			SELECT 		
				ISNULL(CGM.Title,'') AS CSGroup,
				ISNULL(CM.Title,'') AS CS,				
			 
				CGM.GradeSetId,
				CM.Id as CMID,
				Isnull(CCFC.TotalMark,0) AS TotalMark,
				Isnull(CCFC.ConvertToMark,0) AS ConvertToMark,
				CASE WHEN ISNULL(CCFC.CCECSId,0)=0 THEN  'False' ELSE 'True' END AS Checked,
				CASE WHEN ISNULL(CCFC.IsOptional,0)=0 then 'false' ELSE 'True' END AS IsOptional
						
			FROM   
				sAssessment.tCCECSGroupMaster CGM  
				INNER JOIN sAssessment.tCCECSClass CL ON CL.CCECSGroupId = CGM.Id
				 LEFT join sAssessment.tCCECSMaster  CM ON CM.CCECAGroupId = CGM.Id AND CM.OrgId=@rOrgId
				LEFT JOIN sAssessment.tCCECSForClass CCFC ON CCFC.CCECSId = CM.Id AND CCFC.ClassId=@rClassId AND CCFC.BatchID=@rBatchID
				
				WHERE 
					   CM.OrgId = @rOrgId
					 AND  CL.ClassId = @rClassId
					AND CL.BatchId=@rBatchID
			ORDER BY CGM.OrderIndex
			 
 
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.BatchId=@rBatchId
					INNER JOIN sAssessment.tCCECSForClass CL ON CL.CCECSID= CM.Id AND CL.ClassID= @rClassId  
					AND CC.ClassId = @rClassId AND CGM.OrgId = @rOrgId  AND CL.BatchId=@rBatchID
					AND CGM.Id=@rCCECSGroupId 
					
					Order by CM.OrderIndex
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')
      
	SET @query = 'Select AcademicId,RollNo,Code As Number,Name,  ' + @cols + '
	FROM
	(
		SELECT SA.AcademicId,SA.RollNo,SA.Code,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) +' AND CA.BatchID='+Convert(nvarchar,@rBatchID)+'
	
	INNER JOIN sAssessment.tCCECSMaster AM ON CA.CCECSGroupId=AM.CCECAGroupId
	 INNER JOIN sAssessment.tCCECSForClass CL ON CL.CCECSID= AM.Id AND CL.ClassID='+ CONVERT(nvarchar,@rClassId) +' AND CL.BatchId='+convert(nvarchar,@rBatchId)+'
	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 ((AM.Id = '+ 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].[pCSEXamIndicatorGet]...';


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

BEGIN 	
--BEGIN TRY
	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
					INNER JOIN sAssessment.tCCECSClass CC ON CC.CCECSGroupId=CGM.Id AND CC.BatchID=@rBatchId
					INNER JOIN sAssessment.tCCECSForClass CL ON CL.CCECSID= CM.Id AND CL.ClassID= @rClassId
					AND CC.ClassId = @rClassId AND CGM.OrgId = @rOrgId AND CGM.Id=@rCCECSGroupId AND CL.BatchID=@rBatchId
					AND ((CM.Id=@rCCECSId) OR (@rCCECSId=0))
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')
       
	SET @query = 'Select AcademicId,RollNo,Code As Number,Name, ' + @cols + '
	FROM
	(
		SELECT SA.AcademicId,SA.RollNo,SA.Code,SA.Name,AM.Title,	 ISNULL(AIS.IndicatorIds,'''') AS Term1Indicator
	FROM sStudent.vStudentAcademic SA
	INNER JOIN sAssessment.tCCECSClass CA ON CA.ClassId = SA.ClassId AND SA.StatusId = 1 AND CA.BatchID='+convert(nvarchar,@rBatchID)+'
	INNER JOIN sAssessment.tCCECSMaster AM ON CA.CCECSGroupId=AM.CCECAGroupId
	 INNER JOIN sAssessment.tCCECSForClass CL ON CL.CCECSID= AM.Id AND CL.ClassID='+ CONVERT(nvarchar,@rClassId)+' ANd CL.BatchId='+convert(nvarchar,@rBatchID)+'
	LEFT JOIN sAssessment.tCCECSExamScore AIS ON AIS.AcademicId =SA.AcademicId AND AIS.CCECSId= AM.Id AND AIS.ExamId= ' + Convert(nvarchar,@rExamId) + ' AND (AIS.CCECSId = ' + convert(nvarchar,@rCCECSId) + ' OR ' + convert(nvarchar,@rCCECSId) + ' = 0 ) 
	WHERE SA.ClassId=' + CONVERT(nvarchar,@rClassId) + ' 
	And SA.DivisionId = ' + CONVERT(nvarchar,@rDivisionID) + '	
	And SA.BatchId = ' + CONVERT(nvarchar,@rBatchId) + '	
	And AM.CCECAGroupId= ' + CONVERT(nvarchar,@rCCECSGroupId) + '
	 
	) MAIN
	PIVOT
	(
		max(Term1Indicator)
	FOR Title IN (' + @cols + ')
	)pvt Order by RollNo,Number,Academicid'
	print @query
EXECUTE(@query)
--END TRY
--BEGIN CATCH
--	SELECT -1 AS RESULT
--END CATCH
END
GO
PRINT N'Altering [sAssessment].[pCSExamScoreGet]...';


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

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


GO
ALTER PROCEDURE [sAssessment].[pCSExamScoreSetupGet]
	  @rClassId bigint,
	  @rDivisionID Bigint,
	  @rExamId int,
	  @rOrgId int,
	  @rCCECSGroupId int,
	  @rBatchId int,
	  @rCCECSId int=0,
	  @rFilter 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
					INNER JOIN sAssessment.tCCECSClass CC ON CC.CCECSGroupId=CGM.Id AND CC.BatchId=@rBatchID
					INNER JOIN sAssessment.tCCECSForClass CL ON CL.CCECSID= CM.Id AND CL.ClassID= @rClassId
					AND CC.ClassId = @rClassId AND CGM.OrgId = @rOrgId 
					AND CGM.Id=@rCCECSGroupId AND CL.BatchId=@rBatchID
					AND ((CM.Id=@rCCECSId) OR (@rCCECSId=0))
					Order by CM.OrderIndex
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')
       
     IF @rFilter = 1
     BEGIN  
	SET @query = 'Select AcademicId,RollNo,Code As Number,Name , ' + @cols + '
	FROM
	(
		SELECT SA.RollNo,SA.Code,SA.Name,AM.Title, ISNULL(AIS.ObtianMark,0) AS TotalMark,SA.AcademicId
	FROM sStudent.vStudentAcademic SA
	INNER JOIN sAssessment.tCCECSClass CA ON CA.ClassId = SA.ClassId AND SA.StatusId = 1 AND CA.BatchID='+Convert(nvarchar,@rBatchId)+'
	INNER JOIN sAssessment.tCCECSMaster AM ON CA.CCECSGroupId=AM.CCECAGroupId
	 INNER JOIN sAssessment.tCCECSForClass CL ON CL.CCECSID= AM.Id AND CL.ClassID='+ CONVERT(nvarchar,@rClassId)+' AND CL.BatchId='+convert(nvarchar,@rBatchId)+'
	LEFT JOIN sAssessment.tCCECSExamScore AIS ON AIS.AcademicId =SA.AcademicId AND AIS.CCECSId= AM.Id AND AIS.ExamId= ' + Convert(nvarchar,@rExamId) + ' AND (AIS.CCECSId = ' + convert(nvarchar,@rCCECSId) + ' OR ' + convert(nvarchar,@rCCECSId) + ' = 0 ) 
	WHERE SA.ClassId=' + CONVERT(nvarchar,@rClassId) + ' 
	And SA.DivisionId = ' + CONVERT(nvarchar,@rDivisionID) + '	
	And SA.BatchId = ' + CONVERT(nvarchar,@rBatchId) + ' 
	And AM.CCECAGroupId= ' + CONVERT(nvarchar,@rCCECSGroupId) + '
 
	) MAIN
	PIVOT
	(
		max(TotalMark)
	FOR Title IN (' + @cols + ')
	)pvt Order by RollNo,Number,Academicid'
	END
	IF @rFilter=2
	BEGIN
	SET @query = 'Select AcademicId,RollNo,Number,Name, ' + @cols + '
	FROM
	(
		SELECT  SA.RollNo,SA.Code AS Number,SA.Name,AM.Title, ISNULL(AIS.ConvertedMark,0) AS ConvertToMarks,SA.AcademicId
			FROM sStudent.vStudentAcademic SA
	INNER JOIN sAssessment.tCCECSClass CA ON CA.ClassId = SA.ClassId AND SA.StatusId = 1 AND CA.BatchID='+Convert(nvarchar,@rBatchId)+'
	INNER JOIN sAssessment.tCCECSMaster AM ON CA.CCECSGroupId=AM.CCECAGroupId
	 INNER JOIN sAssessment.tCCECSForClass CL ON CL.CCECSID= AM.Id AND CL.ClassID='+ CONVERT(nvarchar,@rClassId) +'
	LEFT JOIN sAssessment.tCCECSExamScore AIS ON AIS.AcademicId =SA.AcademicId AND AIS.CCECSId= AM.Id AND AIS.ExamId= ' + Convert(nvarchar,@rExamId) + ' AND (AIS.CCECSId = ' + convert(nvarchar,@rCCECSId) + ' OR ' + convert(nvarchar,@rCCECSId) + ' = 0 ) 
	WHERE SA.ClassId=' + CONVERT(nvarchar,@rClassId) + ' 
	And SA.DivisionId = ' + CONVERT(nvarchar,@rDivisionID) + '	
	And SA.BatchId = ' + CONVERT(nvarchar,@rBatchId) + ' 
	And AM.CCECAGroupId= ' + CONVERT(nvarchar,@rCCECSGroupId) + '
	 
	) MAIN
	PIVOT
	(
		max(ConvertToMarks)
	FOR Title IN (' + @cols + ')
	)pvt Order by RollNo,Number,Academicid'
	END
  --print @query
EXECUTE(@query)

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


GO
ALTER PROCEDURE [sAssessment].[pCSOptionalActivityGet]
                  
          @rDivisionId  int,
          @rClassId  int,
          @rBatchId int 
      
AS
SET NOCOUNT ON

BEGIN

SELECT 
SS.AcademicId,
SS.CCECSId,
SS.StudentName, 
SS.Code,
SS.RollNo,
CM.Title AS CS,
CASE WHEN isnull(OCES.CCECSId,0) <> 0 THEN 'true' ELSE 'false' END AS Selected
FROM
(SELECT
SA.AcademicId,
CS.CCECSId as CCECSId,
SA.Name as StudentName,
SA.Code,
SA.RollNo 
 
FROM
 (select * FROM sStudent.vStudentAcademic where DivisionId=@rDivisionId AND StatusId=1 AND BatchId=@rBatchId )SA  
 CROSS JOIN    (select * FROM sAssessment.tCCECSForClass B   WHERE  B.IsOptional=1 AND   B.ClassId = @rClassId and BatchId=@rBatchID 
) AS CS 
 ) AS SS
 INNER JOIN sAssessment.tCCECSMaster CM ON SS.CCECSId = Cm.Id 
 LEFT JOIN sAssessment.tOptionalCCECS OCES ON OCES.AcademicId = SS.AcademicId AND OCES.CCECSId = SS.CCECSId

ORDER BY SS.RollNo,CM.OrderIndex
	   
END
GO
PRINT N'Altering [sAssessment].[pExamMasterGet]...';


GO
ALTER PROCEDURE [sAssessment].[pExamMasterGet]
	 @rTitle nvarchar(100),
	 @rExamGroupId int,
	 @rClassId int,
	 @rOrgId int ,
	 @rBatchId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 		
					 
	--SET @rTitle = sCommon.fSearchStringGet(@rTitle)
	SELECT 
	EM.Id,
	EM.ClassID,
	EGM.Title as ExamGroup,
	ESGM.Title as ExamName,
	CM.DisplayTitle as ClassName,
	ISNULL(IsProcessResult,0) AS IsProcessResult,
	IsNull(IsMarksInDecimal,0) AS IsMarksInDecimal,
	ISNULL(ISNegativeMarks,0) AS ISNegativeMarks ,
	ISNULL(IsIncludeCoScholastic,0) AS IsIncludeCoScholastic,
	ISNULL(IsIncludeSubExam,0) AS IsIncludeSubExam  
  FROM	
			[sAssessment].[tExamMaster] EM			
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=EM.ClassId
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.ID = EM.ExamSubGroupId
			INNER JOIN sAssessment.tExamGroupMaster EGM ON EGM.Id=ESGM.ExamGroupId
			 
			 
WHERE		(CM.OrgId = @rOrgId  OR @rOrgId=0) AND (EM.BatchId=@rBatchId)
			AND (EGM.Id=@rExamGroupId OR @rExamGroupId=0)
			AND (CM.Id=@rClassId or @rClassId=0)  
		--	AND ((EM.Name Like  @rTitle )OR(ISNULL(@rTitle,'') = ''))
		    AND ESGM.IsObsolete=0
			ORDER BY EGM.Title ,ESGM.Title

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


GO
ALTER PROCEDURE [sAssessment].[pImportSubjectActivityIndicator]
    @rOrgId smallint ,
	@rXmldoc [nvarchar](max),
	@rUserId bigint

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
BEGIN TRY
	
DECLARE @lCount INT
DECLARE @lInterrorCode INT,@intDoc INT,@lActivity nvarchar(200),@lSubActivity nvarchar(200),@lNumber int,@lGradeSetdetailid int,@lOrderIndex int,	
@lGrade nvarchar(100),@lSubActivityId int,@lIndicator nvarchar(100),@lClass nvarchar(100),@lSubject nvarchar(100),@lGradeSetId int
	 
EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc
	CREATE TABLE #tTable  
	(
		Id bigint identity,
		Class nvarchar(100),
		Subject nvarchar(100),
		Activity nvarchar(200), 
		SubActivity nvarchar(200), 
		Number int, 
		Indicator nvarchar(100),
		Grade nvarchar(100), 
		OrderIndex int
	)
	INSERT INTO #tTable
	(  
		Class,Subject,Activity,SubActivity, Number,Indicator,Grade, OrderIndex
	)
	SELECT
		Class,Subject,Activity,SubActivity, Number,Indicator,Grade, OrderIndex
	FROM OPENXML (@intDoc, '/Table/ImportSubjectActivityIndicator', 1)
	WITH
	(   
	    Class nvarchar(100) '@Class',	
	    Subject nvarchar(100) '@Subject',	
		Activity nvarchar(200) '@Activity',			
		SubActivity nvarchar(200) '@SubActivity',			
		Number int '@Number',			
		Indicator nvarchar(100) '@Indicator',
		Grade nvarchar(100) '@Grade',
		OrderIndex int '@OrderIndex'
	)
EXEC sp_xml_removedocument @intDoc
SELECT @lCount =  COUNT(Id) FROM #tTable
WHILE @lCount > 0 
BEGIN	
		SET @lActivity = ''
		SET @lSubActivity = ''
		SET @lClass = ''
		SET @lSubject = ''
		SET @lNumber = 0
		SET @lIndicator = ''
		SET @lOrderIndex = 0
		SET @lGrade=''
		SET @lSubActivityId =0
		SET @lGradeSetdetailid=0 
	
  SELECT		
		@lActivity = Activity,@lSubActivity = SubActivity,@lNumber = Number,@lOrderIndex = OrderIndex,
		@lIndicator=Indicator,@lGrade=Grade,@lClass=Class,@lSubject=Subject
FROM #tTable WHERE Id = @lCount  
--BEGIN TRANSACTION
	SELECT  @lSubActivityId=SA.Id,@lGradeSetId= AM.GradeSetId from sAssessment.tCCESubjectSubActivityMaster SA INNER JOIN  sAssessment.tCCESubjectActivityMaster AM ON SA.SubjectActivityId=AM.Id
    INNER JOIN sSetup.tClassSubject  CS On AM.ClassSubjectId=Cs.Id INNER JOIN sSetup.tClassMaster CM ON CM.Id=Cs.ClassId INNER JOIN  sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId
    WHERE  SA.OrgId=@rOrgId AND SA.Title=@lSubActivity AND AM.Title=@lActivity AND SM.Title=@lSubject AND CM.Title=@lClass AND CS.OrgId=@rOrgId
    SELECT @lGradeSetdetailid=Id FROM sAssessment.tGradeSetDetail WHERE GradeCode=@lGrade  and GradeSetId=@lGradeSetId

    IF NOT EXISTS(select 1 from sAssessment.tCCESubjectSubActivityIndicatorMaster  where Title=@lIndicator AND OrgId=@rOrgId AND CCESubjectSubActivityId = @lSubActivityId )
     BEGIN	
     EXEC [sAssessment].[pCSSubjectActivityIndicatorAdd] 0,@lSubActivityId,@lIndicator,@lGradeSetdetailid,@rOrgId,@lOrderIndex,@rUserId,@lNumber,@rUserId
  	END
		 SET @lCount = @lCount - 1
	--COMMIT TRANSACTION			
END
	SELECT 1
	END TRY
	BEGIN CATCH
	SELECT ERROR_MESSAGE(), ERROR_LINE()
	END CATCH
	
END
GO
PRINT N'Altering [sAssessment].[pMarkEntryGet]...';


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

BEGIN 		

if(@rIsWithPhoto=1)
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,
	ISNULL(ED.ExamTopic,'') as ExamTopic
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
ELse
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,
	CONVERT(VARBINARY(MAX), 0) AS  StudentPhoto,
	ISNULL(ED.ExamTopic,'') as ExamTopic
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

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


GO
 
ALTER PROCEDURE [sAssessment].[pRptExamAdmitcard]
	  
	  @rBatchId int,
	  @rClassId int,
	  @rDivisionId int,
	 -- @rExamId int=0,
	  @rExamSubGroupId int=0,
	  @rCode nvarchar(20),
	  @rFromRollNo int,
	  @rToRollNo int,
	  @rDepartmentId int,
	  @rSubjectId int=0
	  
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON 
BEGIN 	
	SELECT 		
	       	ESGM.Title AS ExamName,
	       	ISNULL(ED.DisplayOrder,0) as DisplayOrder,
	        ISNULL(ED.ExamDate,GETDATE()) as ExamDate,
	        ISNULL(ED.ExamTime,'') as ExamTime,
	        V.SubjectName AS SubjectName,
	        CM.DisplayTitle+' / '+DM.DisplayTitle AS ClassDivision,
	         CM.DisplayTitle AS ClassName,
	         CM.Id As ClassId,
	         DM.Id AS DiVisionId,
	        V.ClassSubjectId AS ClassSubjectId,
	        SA.Name,
	        SA.RollNo,
	        SA.Code,
	        SF.FatherName,
	        So.DateOfBirth,
	        GM.Title AS Gender,
	        EM.Remark1,
	        EM.Remark2,
	        EM.Remark3,
	        SA.AcademicId,
	        SI.StudentPhoto,
	        SF.MotherName,
	        SR. ExamCenter,
	        SR.ExamSeatNo,
	        V.SubjectCode AS SubjectCode,
	         
		(CASE EM.IsDisplayImageHeader WHEN 1 THEN
			OI.CertificateHeaderA4 
			ELSE NULL END)AS  MarksheetHeaderA4 ,
			ISNULL(EM.IsDisplayImageHeader,0) AS IsImageHeader,
			EM.IsOnPrePrinted ,
	        --EM.Id As ExamId,
			EM.IsDisplayPhoto
			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  ANd Em.BatchId=SA.BatchId 
			INNER JOIN sAssessment.tExamSubGroupMaster	ESGM ON ESGM.Id = EM.ExamSubGroupId
			INNER JOIN sAssessment.tExamGroupMaster EGM ON EGM.Id=ESGM.ExamGroupId
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			LEFT JOIN sSetup.vClassSubject V ON V.ClassSubjectId = Ed.ClassSubjectId  
			LEFT JOIN sAssessment.tOptionalSubject OS on OS.AcademicId=SA.AcademicId and OS.ClassSubjectId=V.ClassSubjectId
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId=SA.StudentId  
			LEFT JOIN sStudent.tStudentOther SO ON So.StudentId=SA.StudentId  
			LEFT JOIN sCommon.tGenderMaster GM ON GM.Id=So.GenderId   
			LEFT JOIN  sStudent.tStudentImages SI ON SI.StudentId=SA.StudentId 
			LEFT JOIN sAssessment.tStudentRemark SR ON SR.ExamId=EM.Id AND SR.AcademicId=SA.AcademicId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=SA.OrgId
			LEFT JOIN sSetup.tOrgImages OI ON OI.Orgid = OM.Id
	WHERE 
			SA.BatchId = @rBatchId 
		 AND (SA.ClassId=@rClassId OR @rClassId=0) 
		 AND (SA.DivisionId=@rDivisionId OR @rDivisionId=0)
		 AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		 AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		 AND ((ESGM.Id = @rExamSubGroupId) OR (@rExamSubGroupId = 0))	
	     AND ((SA.Code=@rCode) OR (@rCode=''))
	     AND (SA.DepartmentId=@rDepartmentId OR @rDepartmentId=0) 
	     AND (V.SubjectId=@rSubjectId OR @rSubjectId=0) 
	    AND ((V.IsOptional = 1 AND  isnull(OS.AcademicId,0) <> 0) OR (V.IsOptional = 0))
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,
	CONVERT (nvarchar(20),@rBatchId) AS BatchIdText,
			Convert(nvarchar(20),ISNULL(EM.IsDisplayMonthlyAttendance,0))AS IsDisplayMonthlyAttendanceText,
			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,
			EM.DecimalFormat
			
			 
		 
			
      
	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))
		ANd SM.StatusId=1
END
GO
PRINT N'Altering [sAssessment].[pRptResultSheetCoScholasticSubSingleGet]...';


GO




ALTER PROCEDURE [sAssessment].[pRptResultSheetCoScholasticSubSingleGet]
	 
	 
	 --@rExamId int,
	 --@rAcademicId bigint
	 @rAcademicId bigint,
	 @rExamId bigint ,
	 @rCoScholasticScopeId int=0,
	 @rBatchId int
 
	 
	  
		
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

DECLARE @lIsCoScholasticGrade	bit,@lIsCoScholasticGradeIndicator bit, @lIsCoScholasticGradeDesIndicator bit  
 
 
SELECT @lIsCoScholasticGrade = IsCoScholasticGrade,
@lIsCoScholasticGradeIndicator=IsCoScholasticGradeIndicator,
@lIsCoScholasticGradeDesIndicator=IsCoScholasticGradeDesIndicator  
 
 
FROM sAssessment.tExamMaster WHERE Id = @rExamId --and coscholasticscopeid=@rCoScholasticScopeId
	SELECT		
			 
			Convert(nvarchar(10),@rExamId) AS ExamIdText,
			Convert(nvarchar(20),@rAcademicId) AS   AcademicIdText,	
			 Convert(nvarchar(20),@rCoScholasticScopeId) AS   CoScholasticScopeIdText,	
			Convert(nvarchar(20),@rBatchId) AS   BatchIdText,	
		 
			cceCSS.AcademicId,
			cceCSS.ExamId,
			cceCSS.Grade,
			cceCSS.GradeIndicator, 
			cceCSS.DescriptiveIndicator,
			cceCSM.Title AS CoSubject,
			cceCSGM.Title AS CoSubjectGroup,
			cceCSM.OrderIndex AS CoSujbectOrderIndex,
			cceCSGM.OrderIndex AS CoSubjectGroupOrderIndex,
			@lIsCoScholasticGrade AS IsCoScholasticGrade,
			@lIsCoScholasticGradeIndicator AS IsCoScholasticGradeIndicator,
			@lIsCoScholasticGradeDesIndicator AS IsCoScholasticGradeDesIndicator,
			cceCSGM.CCECSGroupTypeId,
			cceCSGM.Code,
			cceCST.Id AS GroupTypeId,
			cceCST.Title AS GroupType,
			EM.CoScholasticTitle,
			cceCSS.ConvertedMark,
			cceCSS.ObtianMark
			
	FROM 
			sAssessment.tCCECSExamScore cceCSS		
			 INNER JOIN sAssessment.tExamMaster EM ON EM.Id = cceCSS.ExamId
			INNER JOIN sAssessment.tCCECSMaster cceCSM ON cceCSM.Id=cceCSS.CCECSId
			INNER JOIN sAssessment.tCCECSGroupMaster cceCSGM ON cceCSGM.Id=cceCSM.CCECAGroupId
			INNER  JOIN sAssessment.tCCECSGroupTypeMaster cceCST ON cceCST.Id = cceCSGM.CCECSGroupTypeId
			 
			INNER JOIN sStudent.tAcademic A ON A.Id = cceCSS.AcademicId 
			INNER JOIN sAssessment.tCCECSClass CCC ON CCC.ClassId = A.ClassId AND CCC.CCECSGroupId = cceCSGM.Id 
	WHERE 
		     cceCSS.ExamId=@rExamId
		     AND cceCSS.AcademicId=@rAcademicId	
		     AND CCC.BatchID=@rBatchId
		     
		    
		      
END
GO
PRINT N'Altering [sAssessment].[pRptResultSheetStandardGet]...';


GO
 
 

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

BEGIN 

DECLARE @GradeString nvarchar(1000),  @GradeStringRemark nvarchar(500),
@GradeSetId int,@lGradeStringText nvarchar(1000)
 
SELECT @GradeSetId = GradesetId FROM sAssessment.tExamMaster WHERE Id = @rExamId
 SELECT @GradeString = [sAssessment].[fGradeStringGet](@GradeSetId)
 Select @lGradeStringText = GradeStringText from sAssessment.tGradeSetMaster where Id=@Gradesetid
   
Select @GradeStringRemark = GradeStringText from sAssessment.tGradeSetMaster Where Id =@GradeSetId
 
	SELECT 
			Convert(nvarchar(20),A.Id) AS AcademicIdText,
			Convert(nvarchar(20),@rExamId) AS ExamIdText,
			Convert(nvarchar(20),EM.CoScholasticScopeId) AS CoScholasticScopeIdText,
			Convert(nvarchar(20),ISNULL(EM.IsDisplayMonthlyAttendance,0)) AS IsDisplayMonthlyAttendanceText,
				Convert(nvarchar(20),@rBatchId) AS BatchIdText,
			ESGM.Title AS Exam,
			StuM.Code,
			[sStudent].[fStudentNameGet](stum.FirstName , StuM.MiddleName, StuM.LastName,OM.StudentNameFormatId ) AS Name,
			A.RollNo,
			R.AcademicId,			
			R.ResultStatus,
			CM.DisplayTitle AS Class,
			DM.DisplayTitle AS Division,
			R.TotalMarks,
			R.TotalObtain,
			R.Percentage,
			R.RankNumber,
			R.ResultGrade,
			R.Percentile,			
			RD.Id AS ResultDetailId,		
			ED.IsDisplayInMarksheet,
			ED.IsShowSubjectGrade,
			ED.IsIncludeInTotal,
			RD.Obtain AS SubjectObtain,
			ED.Minimum AS SubjectMinimum,
			ED.Maximum AS SubjectMaximum,
			RD.SubjectGrade,
			SM.Code AS SubjectCode,
			SM.Title AS SubjectName,
			(CASE ISNULL(ED.DisplayOrder,0)
			WHEN 0 THEN CS.OrderIndex
			ELSE ED.DisplayOrder END) AS SubjectOrderIndex,
			R.Id AS ResultId,
			CS.Id AS SubjectId,			 	
			EM.IsMarksInDecimal,
			--SM.OrderIndex AS SubjectCode,
			
			--CS.OrderIndex AS SubjectOrderIndex,
			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.IsMarksInDecimal,
			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,
			SR.StudentHeight,
			SR.StudentWeight,		
			SR.PresentDays,			
			SR.TotalDays,
			SR.ResultRemark1,
			SR.ResultRemark2,						 
			EM.TermScopeId,
			(CASE EM.IsDisplayPhoto WHEN 1 THEN
				SI.StudentPhoto
			ELSE NULL END) AS StudentPhoto,
			RD.IsPresent,
			CASE @GradeStringRemark WHEN '' THEN @GradeString  ELSE @GradeStringRemark END AS GradeString,
			EM.IsDisplayGradeString,
			(CASE EM.IsDisplayHighestDivisionMark
			WHEN 1 THEN [sAssessment].[fGetHighestDivisionMark](A.DivisionId ,RD.ExamDetailId)
			ELSE 0 END) AS HighestDivisionMark,
			(CASE EM.IsDisplayHighestDivisionGrade
			WHEN 1 THEN [sAssessment].[fGetHighestDivisionGrade] (A.DivisionId ,RD.ExamDetailId)
			ELSE '' END) AS HighestDivisionGrade,			
			OM.SmallAddress1,
			EM.IsDisplayParentName,
			SF.FatherName,
			SF.MotherName,
			ISNULL(ED.IsShowSubjectMark,1) AS IsShowSubjectMark,
			
			EM.IsDisplayTeacherSign,
			Em.IsDisplayPrincipalSign,
			(CASE 	EM.IsDisplayTeacherSign WHEN 1 THEN
				EI.EmployeeSign
			ELSE NULL END)AS EmployeeSign,
			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,
			ISNULL(Emp.FirstName,'') +' ' + ISNULL(EMp.LastName,'') AS ClassTeacherName,
			BM.Title AS BatchName,
			Em.DecimalFormat,
			SR.Resultremark3,
			RD.GraceMark,
			ISNULL(SM.SubjectGroupId,0) AS SubjectGroupId,
		ISNULL(SG.Title,'')AS SubjectGroupTitle,
		ISNULL(SG.Code,'') AS SubjectGroupCode,
		@lGradeStringText AS GradeStringText,
		ISNULL(HM.Title,'') AS House,
		ISNULL(EM.TeacherSignCaption,'') As TeacherSignCaption,
		ISNULL(EM.PrincipalSignCaption,'') As PrincipalSignCaption,
		ISNULL(EM.ParentSignCaption,'') As ParentSignCaption,
		ISNULL(SR.ImprovementArea,'') As ImprovementArea,
		ISNULL(SR.ProgressArea,'') AS ProgressArea,
		ISNULL(SR.GeneralRemark,'') As GeneralRemark,
		ISNULL(SR.MyActivity,'') AS MyActivity,
		ISNULL(SR.ClassTeacherRemark,'') As ClassTeacherRemark,
		ISNULL(Sr.HouseRemark,'') As HouseRemark,
		ISNULL(BGM.Title,'') AS BloodGroup
			--[sAssessment].[fGetHighestDivisionMark](A.DivisionId ,RD.ExamDetailId) AS HighestDivisionMark,
			--[sAssessment].[fGetHighestDivisionGrade] (A.DivisionId ,RD.ExamDetailId) AS HighestDivisionGrade
			
			
			
	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
			LEFT JOIN sStudent.tAcademicDetail AD ON AD.AcademicId=A.Id
			INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
			LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
			LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=StuM.Id
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
			LEFT JOIN sHrm.tEmployeeMaster Emp ON Emp.Id=DM.InchargeEmployeeId
			LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = Dm.InchargeEmployeeId
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.EXAMSUBGROUPID
			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
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.batchId
			LEFT JOIN sActivity.tHouseMaster HM ON HM.Id=SO.HouseId
			LEFT JOIN 	sCommon.tBloodGroupMaster BGM ON BGM.Id=So.BloodGroupId
	WHERE 
			
		((EM.BatchId = @rBatchId) OR  (@rBatchId = 0))
		AND ((A.ClassId=@rClassId) OR (@rClassId=0)) 
		AND ((SM.Id=@rSubjectId) OR (@rSubjectId=0))
		AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((R.RankNumber >= @rFromRank) OR (@rFromRank=0))
		AND ((R.RankNumber <= @rToRank) OR (@rToRank=0))
		AND ((R.ResultGrade = @rGrade) OR (@rGrade=''))
		AND (R.ExamId = @rExamId)
		AND ((StuM.Code=@rCode) OR (@rCode=''))
		AND ((R.Id = @rResultId) OR (@rResultId = 0))
		AND ((StuM.StatusId=@rStatusId)OR(@rStatusId=0))
		order by A.RollNo,CS.OrderIndex 
		--AND A.id = 1005000000007
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)
DECLARE @GradeStringRemark nvarchar(500),
@GradeSetId int , @IsIncludeSubExam bit,@GradeStringHtml nvarchar(500)
SELECT @GradeSetId = GradesetId,
	   @IsIncludeSubExam = ISNULL(IsIncludeSubExam,0)  FROM sAssessment.tExamMaster WHERE Id = @rExamId
SELECT @GradeString = [sAssessment].[fGradeStringGet](@GradeSetId)

Select @GradeStringHtml = GradeStringHtml from sAssessment.tGradeSetMaster where Id =@GradeSetId
Select @GradeStringRemark = GradeStringText from sAssessment.tGradeSetMaster Where Id =@GradeSetId
--#TempAllExam
	CREATE TABLE #TempAllExam
	(
		AcademicIdText nvarchar(20),
		ExamIdText nvarchar(20),
		CoScholasticScopeIdText nvarchar(20),
		IsDisplayMonthlyAttendanceText nvarchar(20),
		
		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),
		Exam12Code nvarchar(20),
		
		IsDisplayParentName bit,
		FatherName nvarchar(100),
		MotherName nvarchar(100),
		IsShowSubjectMark bit, 
		IsOptionalSubject bit,
		CoScholasticScopeId tinyint,
		IsDisplayPrincipalSign bit,
		IsDisplayTeacherSign bit,
		EmployeeSign varbinary(max),
		Batch nvarchar(100),
		ExamNameTerm1 NVarchar(100),
		ExamNameTerm2 NVarchar(100) ,
		ClassTeacherName Nvarchar(100),
		FirstName nvarchar(50),
		LastName nvarchar(50),
		IsDisplayMonthlyAttendance bit,
		MarksheetHeaderA4 varbinary(max),
		IsImageHeader bit,
		MyGoal nvarchar(200),
		AreaOfInterest nvarchar(200),
		Responsibility nvarchar(200),
		MyInterestHobby nvarchar(200),
		MyStrength nvarchar(200),
		Achievements nvarchar(200),
		DentalHygiene nvarchar(200),
		VisionLeft nvarchar(50),
		VisionRight nvarchar(50), 
		IsDetail bit,
		SubjectGroupId int,
		SubjectGroupTitle nvarchar(50),
		SubjectGroupCode nvarchar(50),
		DecimalFormat nvarchar(10),
		SubjectRemark nvarchar(1000),
		GraceMark decimal(5,2),
		GradeStringHtml nvarchar(500),
		ResultRemark3 nvarchar(200),
		IsDisplayTotalMark bit,
		SubjectObtainTerm1 decimal(8,2),	
		SubjectObtainTerm2 decimal(8,2),
		SubjectMaxTerm1 decimal(8,2),
		SubjectMaxTerm2 decimal(8,2),
		ContactNo nvarchar(20),
		PresentAddress nvarchar(max),
		TeacherSignCaption nvarchar(100),
		PrincipalSignCaption nvarchar(100),
		 ParentSignCaption nvarchar(100),
		 ImprovementArea nvarchar(200),
		 ProgressArea nvarchar(200),
		 GeneralRemark nvarchar(200),
		 MyActivity nvarchar(200),
		 ClassTeacherRemark nvarchar(1000),
		 
		HouseRemark nvarchar(1000),
		BloodGroup Nvarchar(100),
		TotalDays1 smallint,
		PresentDays1 smallint,
		TotalDays2 smallint,
		PresentDays2 Smallint,
		TotalDays3 smallint,
		PresentDays3 smallint,
		TotalDays4 smallint,
		PresentDays4 smallint,
		TotalDays5 smallint,
		PresentDays5 smallint,
		TotalDays6 smallint,
		PresentDays6 smallint,
		TotalDays7 smallint,
		PresentDays7 smallint, 
		TotalDays8 smallint,
		PresentDays8 smallint,
		TotalDays9 smallint,
		PresentDays9 smallint,
		TotalDays10 smallint,
		PresentDays10 smallint,
		TotalDays11 smallint,
		PresentDays11 smallint,
		TotalDays12 smallint,
		PresentDays12 smallint,
		BatchIdText nvarchar(20)			
	)	
	 --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,
	SubjectGroupCode,
	DecimalFormat,
	SubjectRemark,
	GraceMark,
	GradeStringHtml,
	ResultRemark3,
	IsDisplayTotalMark,
	ContactNo,
	PresentAddress,
	TeacherSignCaption,
	PrincipalSignCaption,
	ParentSignCaption,
	ImprovementArea,
	ProgressArea,
	GeneralRemark,
	MyActivity,
	ClassTeacherRemark,
	
	HouseRemark,
	BloodGroup,
	BatchIdText
 
 
	 
	)
	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,
		[sStudent].[fStudentNameGet](stum.FirstName , StuM.MiddleName, StuM.LastName,OM.StudentNameFormatId ) AS Name,
		A.RollNo,
		ISNULL(R.ResultStatus,'') AS ResultStatus,
		CM.DisplayTitle AS ClassName,
		DM.DisplayTitle AS Division,
		R.TotalMarks AS TotalMark,
		R.TotalObtain,
		ISNULL(R.Percentage,0) As Percentage,
		R.RankNumber,
		ISNULL(R.ResultGrade,'') AS ResultGrade,


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

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

	IF (@IsIncludeSubExam = 0)
	BEGIN	
	INSERT INTO #tempcombineExam (ExamID) 
	SELECT SUBEXAMID FROM sAssessment.tExamCombine WHERE ExamId  = @rExamId Order By ExamOrder ASC
 	END
 	ELSE
 	BEGIN
 	-- if we want to display result for both the term with all exam select this option
 	INSERT INTO #tempcombineExam (ExamID) 
	SELECT C.SUBEXAMID FROM sAssessment.tExamCombine C
	INNER JOIN (SELECT SUBEXAMID,ExamOrder FROM sAssessment.tExamCombine WHERE ExamId  = @rExamId) E
	ON C.ExamId = E.SubExamId
	ORDER BY E.ExamOrder,C.ExamOrder
	END
	--ON 
	
	-- Order By ExamOrder ASC
	--WHERE ExamId in (SELECT SUBEXAMID FROM sAssessment.tExamCombine WHERE ExamId  = @rExamId Order By ExamOrder ASC)
	
	DECLARE @lCount int,@query  AS NVARCHAR(MAX),@lSubExamId int,@lCount1 int
  
	Select @lCount = MAX(Id) from #tempcombineExam
	--SET @lCount1 = @lCount+1
	DECLARE @ExamTitle nvarchar(150)
	while (@lCount > 0)
	begin
		select @lSubExamId = ExamID from #tempcombineExam Where Id = @lCount
		--select @ExamTitle = Title from sAssessment.tExamMaster Where Id = @lSubExamId	
		set @query ='update T SET
					 MaximumMark' + convert(nvarchar(15),@lCount)+ '=ED.Maximum,
					 Obtain' + convert(nvarchar(15),@lCount)+'=RD.Obtain,
					 IsPresent' + convert(nvarchar(15),@lCount)+'=RD.IsPresent,	
					 				
					 SubjectGrade' + convert(nvarchar(15),@lCount)+ '=RD.SubjectGrade,
					  TotalDays'+convert(nvarchar(15),@lCount)+'=SR.TotalDays,
					 PresentDays'+convert(nvarchar(15),@lCount)+'=SR.PresentDays										
					 From
						sAssessment.tResultDetail RD
						INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId	
						LEFT JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND T.AcademicId = SR.AcademicId 									
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
						
	
	 execute(@query)
	
						
			set @query ='update T set 
				    TotalMarks' + convert(nvarchar(15),@lCount)+ '=R.TotalMarks,
					TotalObtain' + convert(nvarchar(15),@lCount)+ '=R.TotalObtain,
					Percentage' + convert(nvarchar(15),@lCount)+ '=R.Percentage,
					RankNumber' + convert(nvarchar(15),@lCount)+'=R.RankNumber,
					ResultGrade' + convert(nvarchar(15),@lCount)+'=R.ResultGrade,
					Percentile' + convert(nvarchar(15),@lCount)+'=R.Percentile,
					ResultStatus' + convert(nvarchar(15),@lCount)+'=R.ResultStatus,
					Exam' + convert(nvarchar(15),@lCount)+ 'Name=ESGM.Title,
					Exam' + convert(nvarchar(15),@lCount)+ 'Code=ESGM.Code,
					ExamMaximum' + convert(nvarchar(15),@lCount)+'=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,
					SubjectObtainTerm1 = RD.Obtain,
					 SubjectMaxTerm1 = ED.Maximum
							 
					 From
						 sAssessment.tResultDetail RD
						INNER JOIN  sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
		
				execute(@query)
				
		set @query ='update T set					 
					 
					TotalMarkTerm1 = R.TotalMarks,
					TotalObtainTerm1=R.TotalObtain,
					PercentageTerm1=R.Percentage,
					RankNumberTerm1=R.RankNumber,
					ResultGradeTerm1=R.ResultGrade,
					PercentileTerm1 = R.Percentile,
					ResultStatusTerm1 = R.ResultStatus,
					ExamNameTerm1 = ESGM.Code					 
					 From
						sAssessment.tResult  R 				
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id = R.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON  T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
						
		 	
						
		execute(@query)
		
					select @lSubExamId = SubExamId from sAssessment.tExamCombine  Where ExamId  = @rExamId AND ExamOrder = 2
		--select @ExamTitle = Title from sAssessment.tExamMaster Where Id = @lSubExamId	
		set @query ='update T set					 
					SubjectGradeTerm2=RD.SubjectGrade,
					SubjectObtainTerm2 = RD.Obtain,
					SubjectMaxTerm2= ED.Maximum				 
					 From
						sAssessment.tResultDetail RD
						INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
		execute(@query)
		
		
				set @query ='update T set
 
					TotalMarkTerm2 = R.TotalMarks,
					TotalObtainTerm2=R.TotalObtain,
					PercentageTerm2=R.Percentage,
					RankNumberTerm2=R.RankNumber,
					ResultGradeTerm2=R.ResultGrade,
					PercentileTerm2 = R.Percentile,
					ResultStatusTerm2 = R.ResultStatus,
					ExamNameTerm2 = ESGM.Code			
					 From						 
					   sAssessment.tResult R  				 
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON  T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
		execute(@query)
		
	
	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 [sAttendance].[pAttenanceRegisterGet]...';


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

--Select * from sAttendance.tTempAttendance

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),
	DateOfBirth date,
	Religion nvarchar(50),
	MotherName nvarchar(50),
	FamilyCast 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,
	DateOfBirth,
	Religion,
	MotherName,
	FamilyCast
)
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,
	 SO.DateOfBirth,
	 RE.Title As Religion,
	 Sf.MotherName,
	 SO.FamilyCast
	 --,
	 --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
            INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=SA.StudentId
			LEFT JOIN  sStudent.tStudentFamily SF ON Sf.StudentId=Sa.StudentID
            LEFT JOIN sCommon.tReligionMaster RE On RE.Id=SO.ReligionId
            
             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(ABU.AUCount,0) AS AbsentUpto,
			ISNULL(TC.TCount,0) AS AttendanceCount,
		    ISNULL(AC.ACount,0) As  AbsentCount,
		    ISNULL(PC.PCount,0) As  PresentUpto,	    
		    
		    ClassOrderIndex,
		    DivisionOrderIndex,
		    FooterSignature,
			(ISNULL(TotalPresent,0) + ISNULL(TC.TCount,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,
              DateOfBirth,Religion,MotherName,FamilyCast
--,
--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,
		DateOfBirth,Religion,MotherName,FamilyCast
      -- 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
		LEFT JOIN
	(SELECT A.Id AS AcademicId, COUNT(1) AS AUCount  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 = 0	    		
            --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
    ) ABU ON ABU.AcademicId = PivotTable.AcademicId
	LEFT JOIN
	(SELECT A.Id AS AcademicId, COUNT(1) AS TotalPresent  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.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
    ) AA ON AA.AcademicId = PivotTable.AcademicId
 
    ORDER BY RollNo;
 

select * from #TempDaysTempTable
 				
drop table #AttendanceRegistertempTable	  
drop table #TempDaysTempTable
	
	
END
GO
PRINT N'Altering [sAttendance].[pMonthlyAttenanceRegisterGet]...';


GO
 
 -- exec [sAttendance].[pAttenanceRegisterGetNew] '','',1,1001,7,2016,100100001,100100001,100100114,0,0,1
ALTER PROCEDURE [sAttendance].[pMonthlyAttenanceRegisterGet]
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rAttendanceTypeId smallint=0,
	 @rOrgId int,
	 @rForMonth smallint,
	 @rForYear smallint,
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rBatchId int = 0  
	 WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	DECLARE @lFirstDate Date,@lLastDate date
	
	DECLARE @lResult nvarchar(max)
	DECLARE @li int 
	SET @li=1
	SET @lFirstDate = CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'/'+CONVERT(NVARCHAR(2),@rForMonth)+'/01'))	
	SET @lLastDate = sCommon.fGetLastDateofMonth(@lFirstDate)
	
	--DECLARE @lAdmissionDate date 
	-- select @lAdmissionDate=Stud.AdmissionDate from    sStudent.tStudentAdmission Stud  inner join sStudent.vStudentAcademic A ON A.StudentId = Stud.StudentId
	--						Where AdmissionStandardId=@rClassId AND Stud.BatchId =@rBatchId  
BEGIN 
CREATE Table #AttendanceRegistertempTable
(
	 
	ClassDivisionTitle Nvarchar(50),
	Code nvarchar(50),
	RollNo int,
	AcademicId bigint,
	Name nvarchar(100),
	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 ,
	AdmissionDate date
 
)
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,
	AdmissionDate
  
)
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,
	 A.AdmissionDate
	 
	 --,
	 --SR.IsPresent
	 
	 
    from
            sStudent.vStudentAcademic SA 
            LEFT JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.AcademicId AND (YEAR(SR.AttendanceDate)=@rForYear) AND (MONTH(SR.AttendanceDate)=@rForMonth) AND (SR.AttendanceTypeId=@rAttendanceTypeId)
            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  
	        
			  SA.OrgId=@rOrgId  
	          AND  (SA.BatchId=@rBatchId) AND  (SA.ClassId=@rClassId) 
	          AND  (SA.DivisionId=@rDivisionId)
	          AND  A.AdmissionDate <=  @lLastDate
	          AND ((A.LeftDate >= @lFirstDate) OR ISNULL(A.LeftDate,'') = '')

				
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,isnull(ForYear,'') AS ForYear,
			isnull(ForMonth,'') AS 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.fAttendanceAdmissionDateGet(AdmissionDate,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-01')),LeftDate,[1]) AS P1,
	 	 
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-02')),LeftDate,[2]) AS P2,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-03')),LeftDate,[3]) AS P3,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-04')),LeftDate,[4]) AS P4,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-05')),LeftDate,[5]) AS P5,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-06')),LeftDate,[6]) AS P6,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-07')),LeftDate,[7]) AS P7,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-08')),LeftDate,[8]) AS P8,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-09')),LeftDate,[9]) AS P9,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-10')),LeftDate,[10]) AS P10,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-11')),LeftDate,[11]) AS P11,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-12')),LeftDate,[12]) AS P12,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-13')),LeftDate,[13]) AS P13,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-14')),LeftDate,[14]) AS P14,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-15')),LeftDate,[15]) AS P15,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-16')),LeftDate,[16]) AS P16,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-17')),LeftDate,[17]) AS P17,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-18')),LeftDate,[18]) AS P18,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-19')),LeftDate,[19]) AS P19,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-20')),LeftDate,[20]) AS P20,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-21')),LeftDate,[21]) AS P21,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-22')),LeftDate,[22]) AS P22,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-23')),LeftDate,[23]) AS P23,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-24')),LeftDate,[24]) AS P24,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-25')),LeftDate,[25]) AS P25,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-26')),LeftDate,[26]) AS P26,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-27')),LeftDate,[27]) AS P27,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-28')),LeftDate,[28]) AS P28,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate, (CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-29') ,LeftDate,[29]) AS P29,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate, (CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-30') ,LeftDate,[30]) AS P30,
		    
		    sAttendance.fAttendanceAdmissionDateGet(AdmissionDate, (CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-31') ,LeftDate,[31])  AS P31,
		 
sCommon.fGetDaysInMonth ( @rForMonth,@rForYear) AS DaysInMonth
,0 Ispresent,
0 AS AttendanceTagId,
AdmissionDate  
FROM
(
	Select  
		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,
		AdmissionDate

		 
		
	 FROM 
		#AttendanceRegistertempTable ST 
		LEFT 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 sStudent.tAcademic A 
			LEFT JOIN  sAttendance.tStudentRegister SR 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 (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
PRINT N'Altering [sBiometric].[pBiometricReportData]...';


GO
ALTER PROCEDURE [sBiometric].[pBiometricReportData]
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='',
	 @rOrgId int,
	 @rDeptId int,
	 @rForYear int=0,
	 @rForMonth int=0,
	 @rIsFirstIn bit=0,
	 @rIsLastOut bit=0,
	 @rIsOT bit=0,
	 @rIsLateBy	bit=0,
	 @rIsEarlyBy bit=0,
	 @rIsDuration  bit=0
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	
	DECLARE @lATTN_DATE NVARCHAR(20)
	Declare @Days int 
	select @Days=sCommon.fGetDaysInMonth(@rForMonth,@rForYear)
	
	SET @lATTN_DATE = CONVERT(NVARCHAR(10),@rForYear) + '-' + Right('000000' + CONVERT(NVARCHAR, @rForMonth), 2) + '-01'
	
	SELECT 
	
	datediff(day, dateadd(day, 1-day(@lATTN_DATE), @lATTN_DATE),
              dateadd(month, 1, dateadd(day, 1-day(@lATTN_DATE), @lATTN_DATE))) AS DayCount,
 
	 @rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2, 
		
		'01 ' + substring(DATENAME( dw, convert( date, ( '01' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2) as DN1,
		'02 ' + substring(DATENAME( dw, convert( date, ( '02' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2) as DN2,
		'03 ' + substring(DATENAME( dw, convert( date, ( '03' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2) as DN3,
		'04 ' + substring(DATENAME( dw, convert( date, ( '04' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2) as DN4,
		'05 ' + substring(DATENAME( dw, convert( date, ( '05' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2) as DN5,
		'06 ' + substring(DATENAME( dw, convert( date, ( '06' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2) as DN6,
		'07 ' + substring(DATENAME( dw, convert( date, ( '07' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2) as DN7,
		'08 ' + substring(DATENAME( dw, convert( date, ( '08' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2) as DN8,
		'09 ' + substring(DATENAME( dw, convert( date, ( '09' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2) as DN9,
		'10 ' + substring(DATENAME( dw, convert( date, ( '10' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2) as DN10,
		'11 ' + substring(DATENAME( dw, convert( date, ( '11' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2) as DN11,
		'12 ' + substring(DATENAME( dw, convert( date, ( '12' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2) as DN12,
		'13 ' + substring(DATENAME( dw, convert( date, ( '13' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2) as DN13,
		'14 ' + substring(DATENAME( dw, convert( date, ( '14' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2) as DN14,
		'15 ' + substring(DATENAME( dw, convert( date, ( '15' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2) as DN15,
		'16 ' + substring(DATENAME( dw, convert( date, ( '16' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2) as DN16,
		'17 ' + substring(DATENAME( dw, convert( date, ( '17' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2) as DN17,
		'18 ' + substring(DATENAME( dw, convert( date, ( '18' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2) as DN18,
		'19 ' + substring(DATENAME( dw, convert( date, ( '19' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2) as DN19,
		'20 ' + substring(DATENAME( dw, convert( date, ( '20' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2) as DN20,
		'21 ' + substring(DATENAME( dw, convert( date, ( '21' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2) as DN21,
		'22 ' + substring(DATENAME( dw, convert( date, ( '22' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2) as DN22,
		'23 ' + substring(DATENAME( dw, convert( date, ( '23' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2) as DN23,
		'24 ' + substring(DATENAME( dw, convert( date, ( '24' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2) as DN24,
		'25 ' + substring(DATENAME( dw, convert( date, ( '25' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2) as DN25,
		'26 ' + substring(DATENAME( dw, convert( date, ( '26' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2) as DN26,
		'27 ' + substring(DATENAME( dw, convert( date, ( '27' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2) as DN27,
		'28 ' + substring(DATENAME( dw, convert( date, ( '28' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2) as DN28,		
		case when @Days >= 29 then '29 ' + substring(DATENAME( dw, convert( date, ( '29' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2) end as DN29,
		case when @Days >= 30 then '30 ' + substring(DATENAME( dw, convert( date, ( '30' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2) end as DN30,
		case when @Days = 31 then '31 ' + substring(DATENAME( dw, convert( date, ( '31' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2) end as DN31,
		
		
	--T.*,
	E.Code,	
	E.ShortName,
	DM.Displaytitle DeptName,
	DM.Code AS DeptCode,
	E.OrgID,
	DM.Id AS DepartmentId,
	EDM.Title AS Designation,
	EDM.Code AS DesignationCode,
	 @rIsFirstIn AS IsFirstIn,
	 @rIsLastOut AS IsLastOut,
	 @rIsOT AS IsOT,
	 @rIsLateBy	AS IsLateBy,
	 @rIsEarlyBy AS IsEarlyBy,
	 @rIsDuration  AS IsDuration,
	 E.FirstName +' ' + E.MiddleName +' '+ E.LastName AS Name,
	 sBiometric.fEmployeeLeaveTypeGet(Attn_Dt,T.EmployeeId) AS LeaveStatus,
	 Isnull(sBiometric.fEmployeeCLTypeGet(@rForMonth,@rForYear,T.EmployeeId),'') AS CLeaveStatus,
	 case when len(sBiometric.fEmployeeLeaveTypeGet(convert(nvarchar(4),@rForYear) + '-' + convert(nvarchar(2),@rForMonth) + '-' + '1',T.EmployeeId)) > 0 then sBiometric.fEmployeeLeaveTypeGet(convert(nvarchar(4),@rForYear) + '-' + convert(nvarchar(2),@rForMonth) + '-' + '1',T.EmployeeId) else T.D01 end AS D01,
	 case when len(sBiometric.fEmployeeLeaveTypeGet(convert(nvarchar(4),@rForYear) + '-' + convert(nvarchar(2),@rForMonth) + '-' + '2',T.EmployeeId)) > 0 then sBiometric.fEmployeeLeaveTypeGet(convert(nvarchar(4),@rForYear) + '-' + convert(nvarchar(2),@rForMonth) + '-' + '2',T.EmployeeId) else T.D02 end AS D02,
	 case when len(sBiometric.fEmployeeLeaveTypeGet(convert(nvarchar(4),@rForYear) + '-' + convert(nvarchar(2),@rForMonth) + '-' + '3',T.EmployeeId)) > 0 then sBiometric.fEmployeeLeaveTypeGet(convert(nvarchar(4),@rForYear) + '-' + convert(nvarchar(2),@rForMonth) + '-' + '3',T.EmployeeId) else T.D03 end AS D03,
	 case when len(sBiometric.fEmployeeLeaveTypeGet(convert(nvarchar(4),@rForYear) + '-' + convert(nvarchar(2),@rForMonth) + '-' + '4',T.EmployeeId)) > 0 then sBiometric.fEmployeeLeaveTypeGet(convert(nvarchar(4),@rForYear) + '-' + convert(nvarchar(2),@rForMonth) + '-' + '4',T.EmployeeId) else T.D04 end AS D04,
	 case when len(sBiometric.fEmployeeLeaveTypeGet(convert(nvarchar(4),@rForYear) + '-' + convert(nvarchar(2),@rForMonth) + '-' + '5',T.EmployeeId)) > 0 then sBiometric.fEmployeeLeaveTypeGet(convert(nvarchar(4),@rForYear) + '-' + convert(nvarchar(2),@rForMonth) + '-' + '5',T.EmployeeId) else T.D05 end AS D05,
	 case when len(sBiometric.fEmployeeLeaveTypeGet(convert(nvarchar(4),@rForYear) + '-' + convert(nvarchar(2),@rForMonth) + '-' + '6',T.EmployeeId)) > 0 then sBiometric.fEmployeeLeaveTypeGet(convert(nvarchar(4),@rForYear) + '-' + convert(nvarchar(2),@rForMonth) + '-' + '6',T.EmployeeId) else T.D06 end AS D06,
	 case when len(sBiometric.fEmployeeLeaveTypeGet(convert(nvarchar(4),@rForYear) + '-' + convert(nvarchar(2),@rForMonth) + '-' + '7',T.EmployeeId))> 0 then sBiometric.fEmployeeLeaveTypeGet(convert(nvarchar(4),@rForYear) + '-' + convert(nvarchar(2),@rForMonth) + '-' + '7',T.EmployeeId) else T.D07 end AS D07,
	 case when len(sBiometric.fEmployeeLeaveTypeGet(convert(nvarchar(4),@rForYear) + '-' + convert(nvarchar(2),@rForMonth) + '-' + '8',T.EmployeeId)) > 0 then sBiometric.fEmployeeLeaveTypeGet(convert(nvarchar(4),@rForYear) + '-' + convert(nvarchar(2),@rForMonth) + '-' + '8',T.EmployeeId) else T.D08 end AS D08,
	 case when len(sBiometric.fEmployeeLeaveTypeGet(convert(nvarchar(4),@rForYear) + '-' + convert(nvarchar(2),@rForMonth) + '-' + '9',T.EmployeeId)) > 0 then sBiometric.fEmployeeLeaveTypeGet(convert(nvarchar(4),@rForYear) + '-' + convert(nvarchar(2),@rForMonth) + '-' + '9',T.EmployeeId) else T.D09 end AS D09,
	 case when len(sBiometric.fEmployeeLeaveTypeGet(convert(nvarchar(4),@rForYear) + '-' + convert(nvarchar(2),@rForMonth) + '-' + '10',T.EmployeeId)) > 0 then sBiometric.fEmployeeLeaveTypeGet(convert(nvarchar(4),@rForYear) + '-' + convert(nvarchar(2),@rForMonth) + '-' + '10',T.EmployeeId) else T.D10 end AS D10,
	 case when len(sBiometric.fEmployeeLeaveTypeGet(convert(nvarchar(4),@rForYear) + '-' + convert(nvarchar(2),@rForMonth) + '-' + '11',T.EmployeeId)) > 0 then sBiometric.fEmployeeLeaveTypeGet(convert(nvarchar(4),@rForYear) + '-' + convert(nvarchar(2),@rForMonth) + '-' + '11',T.EmployeeId) else T.D11 end AS D11,
	 case when len(sBiometric.fEmployeeLeaveTypeGet(convert(nvarchar(4),@rForYear) + '-' + convert(nvarchar(2),@rForMonth) + '-' + '12',T.EmployeeId)) > 0 then sBiometric.fEmployeeLeaveTypeGet(convert(nvarchar(4),@rForYear) + '-' + convert(nvarchar(2),@rForMonth) + '-' + '12',T.EmployeeId) else T.D12 end AS D12,
	 case when len(sBiometric.fEmployeeLeaveTypeGet(convert(nvarchar(4),@rForYear) + '-' + convert(nvarchar(2),@rForMonth) + '-' + '13',T.EmployeeId)) > 0 then sBiometric.fEmployeeLeaveTypeGet(convert(nvarchar(4),@rForYear) + '-' + convert(nvarchar(2),@rForMonth) + '-' + '13',T.EmployeeId) else T.D13 end AS D13,
	 case when len(sBiometric.fEmployeeLeaveTypeGet(convert(nvarchar(4),@rForYear) + '-' + convert(nvarchar(2),@rForMonth) + '-' + '14',T.EmployeeId)) > 0 then sBiometric.fEmployeeLeaveTypeGet(convert(nvarchar(4),@rForYear) + '-' + convert(nvarchar(2),@rForMonth) + '-' + '14',T.EmployeeId) else T.D14 end AS D14,
	 case when len(sBiometric.fEmployeeLeaveTypeGet(convert(nvarchar(4),@rForYear) + '-' + convert(nvarchar(2),@rForMonth) + '-' + '15',T.EmployeeId)) > 0 then sBiometric.fEmployeeLeaveTypeGet(convert(nvarchar(4),@rForYear) + '-' + convert(nvarchar(2),@rForMonth) + '-' + '15',T.EmployeeId) else T.D15 end AS D15,
	 case when len(sBiometric.fEmployeeLeaveTypeGet(convert(nvarchar(4),@rForYear) + '-' + convert(nvarchar(2),@rForMonth) + '-' + '16',T.EmployeeId)) > 0 then sBiometric.fEmployeeLeaveTypeGet(convert(nvarchar(4),@rForYear) + '-' + convert(nvarchar(2),@rForMonth) + '-' + '16',T.EmployeeId) else T.D16 end AS D16,
	 case when len(sBiometric.fEmployeeLeaveTypeGet(convert(nvarchar(4),@rForYear) + '-' + convert(nvarchar(2),@rForMonth) + '-' + '17',T.EmployeeId)) > 0 then sBiometric.fEmployeeLeaveTypeGet(convert(nvarchar(4),@rForYear) + '-' + convert(nvarchar(2),@rForMonth) + '-' + '17',T.EmployeeId) else T.D17 end AS D17,
	 case when len(sBiometric.fEmployeeLeaveTypeGet(convert(nvarchar(4),@rForYear) + '-' + convert(nvarchar(2),@rForMonth) + '-' + '18',T.EmployeeId)) > 0 then sBiometric.fEmployeeLeaveTypeGet(convert(nvarchar(4),@rForYear) + '-' + convert(nvarchar(2),@rForMonth) + '-' + '18',T.EmployeeId) else T.D18 end AS D18,
	 case when len(sBiometric.fEmployeeLeaveTypeGet(convert(nvarchar(4),@rForYear) + '-' + convert(nvarchar(2),@rForMonth) + '-' + '19',T.EmployeeId)) > 0 then sBiometric.fEmployeeLeaveTypeGet(convert(nvarchar(4),@rForYear) + '-' + convert(nvarchar(2),@rForMonth) + '-' + '19',T.EmployeeId) else T.D19 end AS D19,
	 case when len(sBiometric.fEmployeeLeaveTypeGet(convert(nvarchar(4),@rForYear) + '-' + convert(nvarchar(2),@rForMonth) + '-' + '20',T.EmployeeId)) > 0 then sBiometric.fEmployeeLeaveTypeGet(convert(nvarchar(4),@rForYear) + '-' + convert(nvarchar(2),@rForMonth) + '-' + '20',T.EmployeeId) else T.D20 end AS D20,
	 case when len(sBiometric.fEmployeeLeaveTypeGet(convert(nvarchar(4),@rForYear) + '-' + convert(nvarchar(2),@rForMonth) + '-' + '21',T.EmployeeId)) > 0 then sBiometric.fEmployeeLeaveTypeGet(convert(nvarchar(4),@rForYear) + '-' + convert(nvarchar(2),@rForMonth) + '-' + '21',T.EmployeeId) else T.D21 end AS D21,
	 case when len(sBiometric.fEmployeeLeaveTypeGet(convert(nvarchar(4),@rForYear) + '-' + convert(nvarchar(2),@rForMonth) + '-' + '22',T.EmployeeId)) > 0 then sBiometric.fEmployeeLeaveTypeGet(convert(nvarchar(4),@rForYear) + '-' + convert(nvarchar(2),@rForMonth) + '-' + '22',T.EmployeeId) else T.D22 end AS D22,
	 case when len(sBiometric.fEmployeeLeaveTypeGet(convert(nvarchar(4),@rForYear) + '-' + convert(nvarchar(2),@rForMonth) + '-' + '23',T.EmployeeId)) > 0 then sBiometric.fEmployeeLeaveTypeGet(convert(nvarchar(4),@rForYear) + '-' + convert(nvarchar(2),@rForMonth) + '-' + '23',T.EmployeeId) else T.D23 end AS D23,
	 case when len(sBiometric.fEmployeeLeaveTypeGet(convert(nvarchar(4),@rForYear) + '-' + convert(nvarchar(2),@rForMonth) + '-' + '24',T.EmployeeId)) > 0 then sBiometric.fEmployeeLeaveTypeGet(convert(nvarchar(4),@rForYear) + '-' + convert(nvarchar(2),@rForMonth) + '-' + '24',T.EmployeeId) else T.D24 end AS D24,
	 case when len(sBiometric.fEmployeeLeaveTypeGet(convert(nvarchar(4),@rForYear) + '-' + convert(nvarchar(2),@rForMonth) + '-' + '25',T.EmployeeId)) > 0 then sBiometric.fEmployeeLeaveTypeGet(convert(nvarchar(4),@rForYear) + '-' + convert(nvarchar(2),@rForMonth) + '-' + '25',T.EmployeeId) else T.D25 end AS D25,
	 case when len(sBiometric.fEmployeeLeaveTypeGet(convert(nvarchar(4),@rForYear) + '-' + convert(nvarchar(2),@rForMonth) + '-' + '26',T.EmployeeId)) > 0 then sBiometric.fEmployeeLeaveTypeGet(convert(nvarchar(4),@rForYear) + '-' + convert(nvarchar(2),@rForMonth) + '-' + '26',T.EmployeeId) else T.D26 end AS D26,
	 case when len(sBiometric.fEmployeeLeaveTypeGet(convert(nvarchar(4),@rForYear) + '-' + convert(nvarchar(2),@rForMonth) + '-' + '27',T.EmployeeId)) > 0 then sBiometric.fEmployeeLeaveTypeGet(convert(nvarchar(4),@rForYear) + '-' + convert(nvarchar(2),@rForMonth) + '-' + '27',T.EmployeeId) else T.D27 end AS D27,
	 case when len(sBiometric.fEmployeeLeaveTypeGet(convert(nvarchar(4),@rForYear) + '-' + convert(nvarchar(2),@rForMonth) + '-' + '28',T.EmployeeId)) > 0 then sBiometric.fEmployeeLeaveTypeGet(convert(nvarchar(4),@rForYear) + '-' + convert(nvarchar(2),@rForMonth) + '-' + '28',T.EmployeeId) else T.D28 end AS D28,
	 case when @Days >= 29 AND len(sBiometric.fEmployeeLeaveTypeGet(convert(nvarchar(4),@rForYear) + '-' + convert(nvarchar(2),@rForMonth) + '-' + '29',T.EmployeeId)) > 0 then sBiometric.fEmployeeLeaveTypeGet(convert(nvarchar(4),@rForYear) + '-' + convert(nvarchar(2),@rForMonth) + '-' + '29',T.EmployeeId) else T.D29 end AS D29,
	 case when @Days >= 30 AND len(sBiometric.fEmployeeLeaveTypeGet(convert(nvarchar(4),@rForYear) + '-' + convert(nvarchar(2),@rForMonth) + '-' + '30',T.EmployeeId)) > 0 then sBiometric.fEmployeeLeaveTypeGet(convert(nvarchar(4),@rForYear) + '-' + convert(nvarchar(2),@rForMonth) + '-' + '30',T.EmployeeId) else T.D30 end AS D30,
	 case when @Days = 31 AND len(sBiometric.fEmployeeLeaveTypeGet(convert(nvarchar(4),@rForYear) + '-' + convert(nvarchar(2),@rForMonth) + '-' + '31',T.EmployeeId)) > 0 then sBiometric.fEmployeeLeaveTypeGet(convert(nvarchar(4),@rForYear) + '-' + convert(nvarchar(2),@rForMonth) + '-' + '31',T.EmployeeId) else T.D31 end AS D31,
	 EmpCode, Attn_Dt, D01_IN, D02_IN, D03_IN, D04_IN, D05_IN, D06_IN, D07_IN, D08_IN, D09_IN, D10_IN, D11_IN, D12_IN, D13_IN, D14_IN, D15_IN, D16_IN, 
     D17_IN, D18_IN, D19_IN, D20_IN, D21_IN, D22_IN, D23_IN, D24_IN, D25_IN, D26_IN, D27_IN, D28_IN, D29_IN, D30_IN, D31_IN, D01_OUT, D02_OUT, D03_OUT, 
     D04_OUT, D05_OUT, D06_OUT, D07_OUT, D08_OUT, D09_OUT, D10_OUT, D11_OUT, D12_OUT, D13_OUT, D14_OUT, D15_OUT, D16_OUT, D17_OUT, D18_OUT, 
     D19_OUT, D20_OUT, D21_OUT, D22_OUT, D23_OUT, D24_OUT, D25_OUT, D26_OUT, D27_OUT, D28_OUT, D29_OUT, D30_OUT, D31_OUT, D01_O, D02_O, D03_O, 
     D04_O, D05_O, D06_O, D07_O, D08_O, D09_O, D10_O, D11_O, D12_O, D13_O, D14_O, D15_O, D16_O, D17_O, D18_O, D19_O, D20_O, D21_O, D22_O, D23_O, 
     D24_O, D25_O, D26_O, D27_O, D28_O, D29_O, D30_O, D31_O, D01_L, D02_L, D03_L, D04_L, D05_L, D06_L, D07_L, D08_L, D09_L, D10_L, D11_L, D12_L, D13_L, 
     D14_L, D15_L, D16_L, D17_L, D18_L, D19_L, D20_L, D21_L, D22_L, D23_L, D24_L, D25_L, D26_L, D27_L, D28_L, D29_L, D30_L, D31_L, D01_T, D02_T, D03_T, 
     D04_T, D05_T, D06_T, D07_T, D08_T, D09_T, D10_T, D11_T, D12_T, D13_T, D14_T, D15_T, D16_T, D17_T, D18_T, D19_T, D20_T, D21_T, D22_T, D23_T, D24_T, 
      D25_T, D26_T, D27_T, D28_T, D29_T, D30_T, D31_T, D01_E, D02_E, D03_E, D04_E, D05_E, D06_E, D07_E, D08_E, D09_E, D10_E, D11_E, D12_E, D13_E, D14_E, 
      D15_E, D16_E, D17_E, D18_E, D19_E, D20_E, D21_E, D22_E, D23_E, D24_E, D25_E, D26_E, D27_E, D28_E, D29_E, D30_E, D31_E, D01_S, D02_S, D03_S, D04_S, 
      D05_S, D06_S, D07_S, D08_S, D09_S, D10_S, D11_S, D12_S, D13_S, D14_S, D15_S, D16_S, D17_S, D18_S, D19_S, D20_S, D21_S, D22_S, D23_S, D24_S, D25_S, 
      D26_S, D27_S, D28_S, D29_S, D30_S, D31_S, Tot_Attn, Tot_Abs, Tot_WeekOFF, Tot_Holiday, TotalHour, Tot_HD, Tot_Early, Tot_Late, Tot_OT, Tot_OD, Tot_Leave, 
      Count_Late, Count_Early, Count_OT, Tot_CL, Tot_SL, Tot_EL, Tot_SP, Tot_C, Tot_PL, Tot_ML, T.EmployeeId
	from 
		sBiometric.tMonthTrans T
		LEFT JOIN sHRM.tEmployeeMaster E on E.Id = T.EmployeeId
		LEFT JOIN sHRM.tEmployeeJobDetail ED ON ED.EmployeeId = E.Id
		LEFT JOIN sSetup.tDepartmentMaster DM ON DM.Id = ED.OrganizationDepartmentId
		LEFT JOIN sHRM.tEmployeeDesignationMaster EDM ON EDM.Id = ED.EmployeeDesignationId
	WHERE 
		(E.OrgId=@rOrgId) AND
		(DM.Id = @rDeptId OR @rDeptId = 0)		 
		AND
		(T.Attn_dt = @lATTN_DATE) AND E.StatusID = 7
    Order by E.Code,T.Attn_dt
END
GO
PRINT N'Altering [sBiometric].[pLateTimeSheetListGet]...';


GO
 
ALTER PROCEDURE [sBiometric].[pLateTimeSheetListGet]
	 @rEmployeeId bigint=0,
	 @rFromDate Date,
	 @rToDate Date,
	 @rStatus nvarchar(10) = '0',
	  @rOrgGroupId int =0

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

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

	CREATE TABLE #TempMonthTrans
	(
	Id int Identity,
	EmployeeId bigint,	
	Attn_Date DateTime,
	PresentStatus nvarchar(5),
	FirstIn nvarchar(20),
	LastOut nvarchar(20),
	OverTime nvarchar(20),
	LateBy nvarchar(20),
	Duration nvarchar(20),	
	EarlyBy nvarchar(20)
	)
	
	INSERT INTO #TempMonthTrans
	
	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 01) as datetime),D01,D01_IN,D01_OUT,D01_O,D01_L,D01_T,D01_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 02) as datetime),D02,D02_IN,D02_OUT,D02_O,D02_L,D02_T,D02_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 03) as datetime),D03,D03_IN,D03_OUT,D03_O,D03_L,D03_T,D03_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 04) as datetime),D04,D04_IN,D04_OUT,D04_O,D04_L,D04_T,D04_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 05) as datetime),D05,D05_IN,D05_OUT,D05_O,D05_L,D05_T,D05_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 06) as datetime),D06,D06_IN,D06_OUT,D06_O,D06_L,D06_T,D06_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 07) as datetime),D07,D07_IN,D07_OUT,D07_O,D07_L,D07_T,D07_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 08) as datetime),D08,D08_IN,D08_OUT,D08_O,D08_L,D08_T,D08_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 09) as datetime),D09,D09_IN,D09_OUT,D09_O,D09_L,D09_T,D09_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 10) as datetime),D10,D10_IN,D10_OUT,D10_O,D10_L,D10_T,D10_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 11) as datetime),D11,D11_IN,D11_OUT,D11_O,D11_L,D11_T,D11_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 12) as datetime),D12,D12_IN,D12_OUT,D12_O,D12_L,D12_T,D12_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 13) as datetime),D13,D13_IN,D13_OUT,D13_O,D13_L,D13_T,D13_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 14) as datetime),D14,D14_IN,D14_OUT,D14_O,D14_L,D14_T,D14_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 15) as datetime),D15,D15_IN,D15_OUT,D15_O,D15_L,D15_T,D15_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 16) as datetime),D16,D16_IN,D16_OUT,D16_O,D16_L,D16_T,D16_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 17) as datetime),D17,D17_IN,D17_OUT,D17_O,D17_L,D17_T,D17_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 18) as datetime),D18,D18_IN,D18_OUT,D18_O,D18_L,D18_T,D18_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 19) as datetime),D19,D19_IN,D19_OUT,D19_O,D19_L,D19_T,D19_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 20) as datetime),D20,D20_IN,D20_OUT,D20_O,D20_L,D20_T,D20_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 21) as datetime),D21,D21_IN,D21_OUT,D21_O,D21_L,D21_T,D21_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 22) as datetime),D22,D22_IN,D22_OUT,D22_O,D22_L,D22_T,D22_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 23) as datetime),D23,D23_IN,D23_OUT,D23_O,D23_L,D23_T,D23_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 24) as datetime),D24,D24_IN,D24_OUT,D24_O,D24_L,D24_T,D24_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 25) as datetime),D25,D25_IN,D25_OUT,D25_O,D25_L,D25_T,D25_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 26) as datetime),D26,D26_IN,D26_OUT,D26_O,D26_L,D26_T,D26_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 27) as datetime),D27,D27_IN,D27_OUT,D27_O,D27_L,D27_T,D27_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 28) as datetime),D28,D28_IN,D28_OUT,D28_O,D28_L,D28_T,D28_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	IF  Month(@rFromDate) <> 2 or (((YEAR(@rFromDate) % 4 = 0 AND YEAR(@rFromDate) % 100 <> 0) OR YEAR(@rFromDate) % 400 = 0 And Month(@rFromDate)  =2)) 
	BEGIN
		INSERT INTO #TempMonthTrans
	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 29) as datetime),D29,D29_IN,D29_OUT,D29_O,D29_L,D29_T,D29_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
	END
	
	IF Month(@rFromDate) <> 2
	BEGIN
	INSERT INTO #TempMonthTrans
	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 30) as datetime),D30,D30_IN,D30_OUT,D30_O,D30_L,D30_T,D30_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
	END
	
	IF Month(@rFromDate) NOT IN (2,4,6,9,11)
	BEGIN
	INSERT INTO #TempMonthTrans
	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 31) as datetime),D31,D31_IN,D31_OUT,D31_O,D31_L,D31_T,D31_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
	END
	
	SELECT 
	TM.*,
	MT.Tot_Attn + Tot_WeekOff + Tot_Holiday  AS TotalPresent,
	Tot_Abs AS TotalAbsent,
	Tot_WeekOff AS TotalWeekOff,
	Tot_Holiday AS Totalholiday,
	Tot_Leave AS TotalLeave,
	EM.FirstName + ' ' + EM.LastName AS Name,
	EM.Code,
	ISNULL(ELS.Id,0) AS EmployeeLateStatusId,
	ISNULL(ELS.EarlyLeaveRemark,'') AS EarlyLeaveRemark,
	ISNULL(SM.Id,0) AS StatusId,
	ISNULL(SM.Title,'') AS Status,
	'EL' AS PresentStatus1
	FROM #TempMonthTrans TM 
	INNER JOIN sBiometric.tMonthTrans MT ON MT.EmployeeId=TM.EmployeeId
	INNER JOIN sHRM.tEmployeeMaster EM ON EM.Id=TM.EmployeeId
	LEFT JOIN sBiometric.tEmployeeLateStatus ELS ON ELS.EmployeeId = TM.EmployeeId AND CONVERT(date,TM.Attn_Date) = CONVERT(date,ELS.LateDate)
	LEFT JOIN sCommon.tStatusMaster SM ON SM.Id = ELS.StatusId
	WHERE 
	TM.ATTN_DATE >= @rFromDate AND TM.ATTN_DATE <=@rToDate 	
	AND (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND MT.Attn_dt=cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime)
	--AND (PresentStatus = @rStatus OR @rStatus='0') AND PresentStatus IN ('LH','HD')
	AND Convert(decimal(10,2),Replace(TM.Duration,':','.')) >= convert(decimal(10,2),SUBSTRING(@lItemValue,1,CHARINDEX ( ';',@lItemValue)-1))
	AND Convert(decimal(10,2),Replace(TM.Duration,':','.')) <= Convert(decimal(10,2),SUBSTRING(@lItemValue,CHARINDEX (';',@lItemValue)+1,4))
	Order By TM.EmployeeId,TM.Attn_Date
END
GO
PRINT N'Altering [sBiometric].[pMonthlyPresenceSummaryGet]...';


GO
ALTER PROCEDURE [sBiometric].[pMonthlyPresenceSummaryGet]	 
	 @rCode nvarchar(20)='',
	 @rForYear int,
	 @rForMonth int,
	 @rOrgId int

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 

	DECLARE @rFromDate date
	DECLARE @rToDate date
	
	SET @rFromDate = CONVERT(date,CONVERT(nvarchar(10), @rForYear) + '-' + CONVERT(nvarchar(10), @rForMonth) + '-' + '01')
	SET @rToDate = DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, @rFromDate) + 1, 0))
	
	CREATE TABLE #TempMonthTrans
	(
	Id int Identity,
	EmployeeId bigint,	
	PresentStatus nvarchar(5),
	LateBy decimal(10,2)
	)
	
	INSERT INTO #TempMonthTrans
	
	SELECT EmployeeId,D01,Replace(D01_L,':','.') FROM sBiometric.tMonthTrans WHERE 1=1 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL
	SELECT EmployeeId,D02,Replace(D02_L,':','.') FROM sBiometric.tMonthTrans WHERE 1=1 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL
	SELECT EmployeeId,D03,Replace(D03_L,':','.') FROM sBiometric.tMonthTrans WHERE 1=1 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL
	SELECT EmployeeId,D04,Replace(D04_L,':','.') FROM sBiometric.tMonthTrans WHERE 1=1 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL
	SELECT EmployeeId,D05,Replace(D05_L,':','.') FROM sBiometric.tMonthTrans WHERE 1=1 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL
	SELECT EmployeeId,D06,Replace(D06_L,':','.') FROM sBiometric.tMonthTrans WHERE 1=1 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL
	SELECT EmployeeId,D07,Replace(D07_L,':','.') FROM sBiometric.tMonthTrans WHERE 1=1 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL
	SELECT EmployeeId,D08,Replace(D08_L,':','.') FROM sBiometric.tMonthTrans WHERE 1=1 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL
	SELECT EmployeeId,D09,Replace(D09_L,':','.') FROM sBiometric.tMonthTrans WHERE 1=1 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL
	SELECT EmployeeId,D10,Replace(D10_L,':','.') FROM sBiometric.tMonthTrans WHERE 1=1 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL
	SELECT EmployeeId,D11,Replace(D11_L,':','.') FROM sBiometric.tMonthTrans WHERE 1=1 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL
	SELECT EmployeeId,D12,Replace(D12_L,':','.') FROM sBiometric.tMonthTrans WHERE 1=1 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL
	SELECT EmployeeId,D13,Replace(D13_L,':','.') FROM sBiometric.tMonthTrans WHERE 1=1 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL
	SELECT EmployeeId,D14,Replace(D14_L,':','.') FROM sBiometric.tMonthTrans WHERE 1=1 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL
	SELECT EmployeeId,D15,Replace(D15_L,':','.') FROM sBiometric.tMonthTrans WHERE 1=1 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL
	SELECT EmployeeId,D16,Replace(D16_L,':','.') FROM sBiometric.tMonthTrans WHERE 1=1 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL
	SELECT EmployeeId,D17,Replace(D17_L,':','.') FROM sBiometric.tMonthTrans WHERE 1=1 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL
	SELECT EmployeeId,D18,Replace(D18_L,':','.') FROM sBiometric.tMonthTrans WHERE 1=1 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL
	SELECT EmployeeId,D19,Replace(D19_L,':','.') FROM sBiometric.tMonthTrans WHERE 1=1 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL
	SELECT EmployeeId,D20,Replace(D20_L,':','.') FROM sBiometric.tMonthTrans WHERE 1=1 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL
	SELECT EmployeeId,D21,Replace(D21_L,':','.') FROM sBiometric.tMonthTrans WHERE 1=1 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL
	SELECT EmployeeId,D22,Replace(D22_L,':','.') FROM sBiometric.tMonthTrans WHERE 1=1 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL
	SELECT EmployeeId,D23,Replace(D23_L,':','.') FROM sBiometric.tMonthTrans WHERE 1=1 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL
	SELECT EmployeeId,D24,Replace(D24_L,':','.') FROM sBiometric.tMonthTrans WHERE 1=1 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL
	SELECT EmployeeId,D25,Replace(D25_L,':','.') FROM sBiometric.tMonthTrans WHERE 1=1 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL
	SELECT EmployeeId,D26,Replace(D26_L,':','.') FROM sBiometric.tMonthTrans WHERE 1=1 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL
	SELECT EmployeeId,D27,Replace(D27_L,':','.') FROM sBiometric.tMonthTrans WHERE 1=1 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL
	SELECT EmployeeId,D28,Replace(D28_L,':','.') FROM sBiometric.tMonthTrans WHERE 1=1 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	IF  Month(@rFromDate) <> 2 or (((YEAR(@rFromDate) % 4 = 0 AND YEAR(@rFromDate) % 100 <> 0) OR YEAR(@rFromDate) % 400 = 0 And Month(@rFromDate)  =2)) 
	BEGIN
		INSERT INTO #TempMonthTrans
		SELECT EmployeeId,D29,Replace(D29_L,':','.') FROM sBiometric.tMonthTrans WHERE 1=1 
		AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
	END
	
	IF Month(@rFromDate) <> 2
	BEGIN
	INSERT INTO #TempMonthTrans
	SELECT EmployeeId,D30,Replace(D30_L,':','.') FROM sBiometric.tMonthTrans WHERE 1=1 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
	END
	
	IF Month(@rFromDate) NOT IN (2,4,6,9,11)
	BEGIN
	INSERT INTO #TempMonthTrans
	SELECT EmployeeId,D31,Replace(D31_L,':','.') FROM sBiometric.tMonthTrans WHERE 1=1 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
	END
	
	DECLARE @lAttendanceDate AS nvarchar(20)
	SET @lAttendanceDate = CONVERT(nvarchar(10), @rForYear) + '-' + CONVERT(nvarchar(10), @rForMonth) + '-' + '01'

	DECLARE @lOrgGroupId int=0
	SELECT @lOrgGroupId = OrgGroupId FROM sSetup.tOrganizationMaster WHERE Id = @rOrgId
		
	DECLARE @lItemValue nvarchar(20) = ''
	SELECT @lItemValue = CASE WHEN CS.Id IS NOT NULL THEN ISNULL(CS.ItemValue,'') ELSE ISNULL(CM.ItemValue,'') END
	FROM sConfig.tConfigurationMaster CM
	LEFT JOIN sConfig.tConfigurationSetup CS ON CM.Id = CS.ConfigurationId
	AND SourceTypeId = 2010 AND SourceId = @lOrgGroupId WHERE CM.Id = 204

	SELECT
		ROW_NUMBER() OVER (ORDER BY EM.Code ASC) AS SrNo,
		EM.Code,
		EM.FirstName + ' ' + EM.Lastname AS Name,
		Tot_Abs AS Absent,
		ISNULL(TotalLate,0) AS ELTotal,
		ISNULL(LateStatus,0) AS ELApprove,

	    Count_Late - ISNULL(LateValid.LateValid,0) AS Late,

		ISNULL((SELECT COUNT(value) FROM sBiometric.tMonthTrans
		UNPIVOT
		(value FOR col IN (d01_t, d02_t, d03_t, d04_t, d05_t, d06_t, d07_t, d08_t, d09_t, d10_t, d11_t, d12_t, d13_t, d14_t, d15_t, d16_t, d17_t, d18_t, d19_t, d20_t, d21_t, d22_t, d23_t, d24_t, d25_t, d26_t, d27_t, d28_t, d29_t, d30_t, d31_t)) PT
		WHERE CONVERT(FLOAT,REPLACE(value,':','.')) >= CONVERT(FLOAT,REPLACE(@lItemValue,':','.')) AND attn_dt = MT.attn_dt AND EM.Id = PT.EmployeeId GROUP BY empcode),0) AS DinnerAllowance,

		ISNULL((SELECT COUNT(value) FROM sBiometric.tMonthTrans
		UNPIVOT
		(value FOR col IN (d01, d02, d03, d04, d05, d06, d07, d08, d09, d10, d11, d12, d13, d14, d15, d16, d17, d18, d19, d20, d21, d22, d23, d24, d25, d26, d27, d28, d29, d30, d31)) PT
		WHERE value LIKE 'PW' AND attn_dt = MT.attn_dt AND EM.Id = PT.EmployeeId GROUP BY empcode),0) AS CompOff,
		
		[sBiometric].[fTimeConversion](
		CONVERT(FLOAT,REPLACE(Tot_Early,':','.')) +
		ISNULL((SELECT SUM(CONVERT(DECIMAL(10,2),[sBiometric].[fTimeConversion](CONVERT(nvarchar(10),value),0))) FROM sBiometric.tMonthTrans
		UNPIVOT
		(value FOR col IN (d01_l, d02_l, d03_l, d04_l, d05_l, d06_l, d07_l, d08_l, d09_l, d10_l, d11_l, d12_l, d13_l, d14_l, d15_l, d16_l, d17_l, d18_l, d19_l, d20_l, d21_l, d22_l, d23_l, d24_l, d25_l, d26_l, d27_l, d28_l, d29_l, d30_l, d31_l)) PT
		WHERE CONVERT(FLOAT,REPLACE(value,':','.')) >= CONVERT(FLOAT,REPLACE('00:30',':','.')) AND attn_dt = MT.attn_dt AND EM.Id = PT.EmployeeId GROUP BY empcode),0) - ISNULL(A.EarlyHrs,0),1) AS EarlyLeave,
		
		Tot_OT AS Tot_OT,		

		CAse When (CONVERT(decimal(10,2),REPLACE(Tot_OT,':','.')) - CONVERT(decimal(10,2),REPLACE(([sBiometric].[fTimeConversion](
		CONVERT(FLOAT,REPLACE(Tot_Early,':','.')) +
		ISNULL((SELECT SUM(CONVERT(DECIMAL(10,2),[sBiometric].[fTimeConversion](CONVERT(nvarchar(10),value),0))) FROM sBiometric.tMonthTrans
		UNPIVOT
		(value FOR col IN (d01_l, d02_l, d03_l, d04_l, d05_l, d06_l, d07_l, d08_l, d09_l, d10_l, d11_l, d12_l, d13_l, d14_l, d15_l, d16_l, d17_l, d18_l, d19_l, d20_l, d21_l, d22_l, d23_l, d24_l, d25_l, d26_l, d27_l, d28_l, d29_l, d30_l, d31_l)) PT
		WHERE CONVERT(FLOAT,REPLACE(value,':','.')) >= CONVERT(FLOAT,REPLACE('00:30',':','.')) AND attn_dt = MT.attn_dt AND EM.Id = PT.EmployeeId GROUP BY empcode),0) - ISNULL(A.EarlyHrs,0),1)),':','.'))) > 0 Then 
		
		[sBiometric].[fTimeConversion](
		
		Convert(nvarchar(20),Convert(decimal(10,2),Replace(Tot_OT,':','.')) - Convert(decimal(10,2),Replace(([sBiometric].[fTimeConversion](
		--Convert(nvarchar(20),Convert(nvarchar(10),[sBiometric].[fTimeConversion](Tot_OT,0)) - Convert(decimal(10,2),Replace(([sBiometric].[fTimeConversion](
		
		CONVERT(FLOAT,REPLACE(Tot_Early,':','.')) +
		ISNULL((SELECT SUM(CONVERT(DECIMAL(10,2),[sBiometric].[fTimeConversion](CONVERT(nvarchar(10),value),0))) FROM sBiometric.tMonthTrans
		UNPIVOT
		(value FOR col IN (d01_l, d02_l, d03_l, d04_l, d05_l, d06_l, d07_l, d08_l, d09_l, d10_l, d11_l, d12_l, d13_l, d14_l, d15_l, d16_l, d17_l, d18_l, d19_l, d20_l, d21_l, d22_l, d23_l, d24_l, d25_l, d26_l, d27_l, d28_l, d29_l, d30_l, d31_l)) PT
		WHERE CONVERT(FLOAT,REPLACE(value,':','.')) >= CONVERT(FLOAT,REPLACE('00:30',':','.')) AND attn_dt = MT.attn_dt AND EM.Id = PT.EmployeeId GROUP BY empcode),0) - ISNULL(A.EarlyHrs,0),1)),':','.')))
		,1)
		else
		'-' + [sBiometric].[fTimeConversion](Convert(decimal(10,2),Replace(([sBiometric].[fTimeConversion](
		CONVERT(FLOAT,REPLACE(Tot_Early,':','.')) +
		ISNULL((SELECT SUM(CONVERT(DECIMAL(10,2),[sBiometric].[fTimeConversion](CONVERT(nvarchar(10),value),0))) FROM sBiometric.tMonthTrans
		UNPIVOT
		(value FOR col IN (d01_l, d02_l, d03_l, d04_l, d05_l, d06_l, d07_l, d08_l, d09_l, d10_l, d11_l, d12_l, d13_l, d14_l, d15_l, d16_l, d17_l, d18_l, d19_l, d20_l, d21_l, d22_l, d23_l, d24_l, d25_l, d26_l, d27_l, d28_l, d29_l, d30_l, d31_l)) PT
		WHERE CONVERT(FLOAT,REPLACE(value,':','.')) >= CONVERT(FLOAT,REPLACE('00:30',':','.')) AND attn_dt = MT.attn_dt AND EM.Id = PT.EmployeeId GROUP BY empcode),0) - ISNULL(A.EarlyHrs,0),1)),':','.')) - Convert(decimal(10,2),Replace(Tot_OT,':','.')),1)
		end		AS Tot_OT_EL,

		Tot_Abs - (SELECT ISNULL(SUM(NoOfLeave),0) FROM sHrm.tLeave WHERE EmployeeId = EM.Id AND StatusId=550 AND FromDATE BETWEEN CONVERT(DATE,@lAttendanceDate) AND DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, @lAttendanceDate) + 1, 0))) 
		- (ISNULL(LateStatus,0) * 0.5)
		AS LWP
		
	FROM 
		sBiometric.tMonthTrans MT
		INNER JOIN sHrm.tEmployeeMaster EM ON MT.EMployeeId = EM.Id AND MT.attn_dt = @lAttendanceDate
		LEFT JOIN 
		(	Select TT.EmployeeID, Count(ISNULL(TT.EmployeeId,0)) AS LateValid From
			sBiometric.tMonthTrans MT
			leFT jOIN #TempMonthTrans TT on MT.EmployeeId = TT.EmployeeId  AND TT.PresentStatus ='HD' AND TT.LateBy > '4.0'
			where MT.attn_dt = @lAttendanceDate 
			GRoup By TT.EmployeeId
		)LateValid ON LateValid.EmployeeId = MT.EmployeeId
		LEFT JOIN
		(
		SELECT SUM(ISNULL(ELS.EarlyHrs,0)) AS EarlyHrs,ELS.EmployeeId FROM sBiometric.tEmployeeLateStatus ELS 
		WHERE ELS.StatusId = 550 AND  CONVERT(DATE,ELS.LateDate)>= CONVERT(DATE,@lAttendanceDate)
		AND CONVERT(DATE,ELS.LateDate) <= CONVERT(DATE,DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, @lAttendanceDate) + 1, 0)))
		GROUP BY ELS.EmployeeId
		) A ON A.EMployeeId = MT.EMployeeId 
		LEFT JOIN
		(
		SELECT ELS1.EmployeeId,COUNT(ELS1.LateStatus) AS LateStatus FROM sBiometric.tEmployeeLateStatus ELS1 
		WHERE ELS1.StatusId = 550 AND LateStatus = 'EL' AND CONVERT(DATE,ELS1.LateDate)>= CONVERT(DATE,@lAttendanceDate)
		AND CONVERT(DATE,ELS1.LateDate) <=CONVERT(DATE,DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, @lAttendanceDate) + 1, 0)))
		GROUP BY ELS1.EmployeeId
		) A1 ON A1.EMployeeId = MT.EMployeeId 
		LEFT JOIN
		(
		SELECT ELS1.EmployeeId,COUNT(ELS1.LateStatus) AS TotalLate FROM sBiometric.tEmployeeLateStatus ELS1 
		WHERE LateStatus = 'EL' AND CONVERT(DATE,ELS1.LateDate)>= CONVERT(DATE,@lAttendanceDate)
		AND CONVERT(DATE,ELS1.LateDate) <=CONVERT(DATE,DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, @lAttendanceDate) + 1, 0)))
		GROUP BY ELS1.EmployeeId
		) A2 ON A2.EMployeeId = MT.EMployeeId 
	
	WHERE (EM.Code = @rCode OR ISNULL(@rCode,'') = '')
	ORDER BY EM.Code

	TRUNCATE TABLE #TempMonthTrans
END
GO
PRINT N'Altering [sBiometric].[pTimeSheetListGet]...';


GO
ALTER PROCEDURE [sBiometric].[pTimeSheetListGet]
	 @rEmployeeId bigint=0,
	 @rFromDate Date,
	 @rToDate Date,
	 @rStatus nvarchar(10) = '0'

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 

	CREATE TABLE #TempMonthTrans
	(
	Id int Identity,
	EmployeeId bigint,	
	Attn_Date DateTime,
	PresentStatus nvarchar(5),
	FirstIn nvarchar(20),
	LastOut nvarchar(20),
	OverTime nvarchar(20),
	LateBy nvarchar(20),
	Duration nvarchar(20),	
	EarlyBy nvarchar(20)
	)
	
	INSERT INTO #TempMonthTrans
	
	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 01) as datetime),D01,D01_IN,D01_OUT,D01_O,D01_L,D01_T,D01_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 02) as datetime),D02,D02_IN,D02_OUT,D02_O,D02_L,D02_T,D02_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 03) as datetime),D03,D03_IN,D03_OUT,D03_O,D03_L,D03_T,D03_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 04) as datetime),D04,D04_IN,D04_OUT,D04_O,D04_L,D04_T,D04_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 05) as datetime),D05,D05_IN,D05_OUT,D05_O,D05_L,D05_T,D05_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 06) as datetime),D06,D06_IN,D06_OUT,D06_O,D06_L,D06_T,D06_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 07) as datetime),D07,D07_IN,D07_OUT,D07_O,D07_L,D07_T,D07_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 08) as datetime),D08,D08_IN,D08_OUT,D08_O,D08_L,D08_T,D08_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 09) as datetime),D09,D09_IN,D09_OUT,D09_O,D09_L,D09_T,D09_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 10) as datetime),D10,D10_IN,D10_OUT,D10_O,D10_L,D10_T,D10_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 11) as datetime),D11,D11_IN,D11_OUT,D11_O,D11_L,D11_T,D11_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 12) as datetime),D12,D12_IN,D12_OUT,D12_O,D12_L,D12_T,D12_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 13) as datetime),D13,D13_IN,D13_OUT,D13_O,D13_L,D13_T,D13_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 14) as datetime),D14,D14_IN,D14_OUT,D14_O,D14_L,D14_T,D14_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 15) as datetime),D15,D15_IN,D15_OUT,D15_O,D15_L,D15_T,D15_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 16) as datetime),D16,D16_IN,D16_OUT,D16_O,D16_L,D16_T,D16_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 17) as datetime),D17,D17_IN,D17_OUT,D17_O,D17_L,D17_T,D17_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 18) as datetime),D18,D18_IN,D18_OUT,D18_O,D18_L,D18_T,D18_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 19) as datetime),D19,D19_IN,D19_OUT,D19_O,D19_L,D19_T,D19_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 20) as datetime),D20,D20_IN,D20_OUT,D20_O,D20_L,D20_T,D20_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 21) as datetime),D21,D21_IN,D21_OUT,D21_O,D21_L,D21_T,D21_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 22) as datetime),D22,D22_IN,D22_OUT,D22_O,D22_L,D22_T,D22_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 23) as datetime),D23,D23_IN,D23_OUT,D23_O,D23_L,D23_T,D23_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 24) as datetime),D24,D24_IN,D24_OUT,D24_O,D24_L,D24_T,D24_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 25) as datetime),D25,D25_IN,D25_OUT,D25_O,D25_L,D25_T,D25_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 26) as datetime),D26,D26_IN,D26_OUT,D26_O,D26_L,D26_T,D26_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 27) as datetime),D27,D27_IN,D27_OUT,D27_O,D27_L,D27_T,D27_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 28) as datetime),D28,D28_IN,D28_OUT,D28_O,D28_L,D28_T,D28_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	IF  Month(@rFromDate) <> 2 or (((YEAR(@rFromDate) % 4 = 0 AND YEAR(@rFromDate) % 100 <> 0) OR YEAR(@rFromDate) % 400 = 0 And Month(@rFromDate)  =2)) 
	BEGIN
		INSERT INTO #TempMonthTrans
	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 29) as datetime),D29,D29_IN,D29_OUT,D29_O,D29_L,D29_T,D29_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
	END
	
	IF Month(@rFromDate) <> 2
	BEGIN
	INSERT INTO #TempMonthTrans
	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 30) as datetime),D30,D30_IN,D30_OUT,D30_O,D30_L,D30_T,D30_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
	END
	
	IF Month(@rFromDate) NOT IN (2,4,6,9,11)
	BEGIN
	INSERT INTO #TempMonthTrans
	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 31) as datetime),D31,D31_IN,D31_OUT,D31_O,D31_L,D31_T,D31_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
	END
	
	SELECT TM.*,MT.Tot_Attn + Tot_WeekOff + Tot_Holiday  AS TotalPresent,Tot_Abs AS TotalAbsent,Tot_WeekOff AS TotalWeekOff,
	Tot_Holiday AS Totalholiday,Tot_Leave AS TotalLeave,EM.FirstName + ' ' + EM.LastName As ShortName,EM.Code as EmpCode , [sBiometric].[fEmployeeLeaveTypeGet] (TM.ATTN_DATE,TM.EmployeeId) AS LeaveStatus , 
	[sBiometric].[fEmployeeLeaveTypePendingGet](TM.ATTN_DATE,TM.EmployeeId) AS LeavePendingStatus, 
	[sBiometric].[fEmployeeTravelGet](TM.ATTN_DATE,TM.EmployeeId) AS EmployeeTravel,
	ISNULL(ELS.Id,0) AS EmployeeLateStatusId,
	ISNULL(SM.Id,0) AS StatusId,
	ISNULL(SM.Title,'') AS Status
	FROM #TempMonthTrans TM 
	INNER JOIN sBiometric.tMonthTrans MT ON MT.EmployeeId=TM.EmployeeId
	INNER JOIN sHRM.tEmployeeMaster EM ON EM.Id=TM.EmployeeId
	LEFT JOIN sBiometric.tEmployeeLateStatus ELS ON ELS.EmployeeId = TM.EmployeeId AND CONVERT(date,TM.Attn_Date) = CONVERT(date,ELS.LateDate)
	LEFT JOIN sCommon.tStatusMaster SM ON SM.Id = ELS.StatusId
	WHERE 
	TM.ATTN_DATE >= @rFromDate AND TM.ATTN_DATE <=@rToDate 	
	AND (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND MT.Attn_dt=cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime)
	AND (PresentStatus = @rStatus OR @rStatus='0')
	Order By TM.EmployeeId,TM.Attn_Date
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)='',
     @rOrgGroupBatchId int
	 
	 
	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,
			   [sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) 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,
			SF.MotherName,
			C.PermanentStreetOne,
			C.PermanentStreetTwo,
			C.PermanentStreetThree,
			C.PermanentCountry,
			C.PermanentState,
			C.PermanentCity,
			C.PermanentZipCode,
			C.PermanentContactNo,
			C.PresentStreetOne,
			C.PresentStreetTwo,
			C.PresentStreetThree,
			C.PresentCountry,
			C.PresentState,
			C.PresentCity,
			C.PresentContactNo,
			C.PresentZipCode,
			SM.SUId,
			SO.AdhaarNumber,
			CM.DisplayTitle AS ClassName,
			ISNULL(CTM.Nationality,'') AS Nationality,
			OM.PrincipalSignature,
			ISnull(AR.SourceId,0) AS StudentidForhostel
			
			
	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
			LEFT JOIN sStudent.tStudentCommunication C ON C.StudentId = A.StudentId
			LEFT JOIN sCommon.tCountryMaster CTM ON CTM.Id=SO.NationalityId
			LEFT JOIN SHostel.tAssignRoom Ar On Ar.SourceId=A.StudentId AND Ar.OrgGroupBatchId=@rOrgGroupBatchId 
			
			
			--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,
			SM.FirstName+' '+SM.MiddleName+' '+SM.LastName AS Name,
			ISNULL(SF.FatherName,'') As FatherName,
			ISNULL(SF.MotherName,'') As MotherName,
			ISNULL(CTM.Nationality,'') AS Nationality,
			--0 As CastCategoryId,
			--ISNULL(SO.CastCategoryId,0) As CastCategoryId,
			ISNULL(RM.Title,'') AS Religion,
			ISNULL(so.BirthPlace,'') AS BirthPlace,
			ISNULL(SO.BirthTaluka,'') AS BirthTaluka,
			ISNULL(SO.BirthDistrict,'') AS BirthDistrict,
			SO.DateOfBirth,
			ISNULL(SO.BirthDateInWord,'') AS BirthDateInWord,
			SA.PreviousSchool,
			SA.AdmissionDate,
			L.LCNumber,
			L.LeftDate,
			L.LCReason,
			L.LCProgress,
			L.LCConduct,
			L.LCRemark,
			L.LCDate,
			SO.GenderId,
			ISNULL(SO.FamilySubCast,'') AS SubCaste,
			ISNULL(SO.FamilyCast,'') AS Caste,
			ISNULL(OM.CityName,'') AS City,
			ISNULL(OM.StateName,'') AS CityState,
			CM.DisplayTitle AS AdmissionStandard,
			CMS.DisplayTitle AS CurrentStandard,
			CMS.Title AS CurrentStandardTitle,
			--'' AS CurrentStandardInWords,
			SM.StatusId,
			L.LastExamName AS Result,
			L.LastExamResult AS FailOrPass,
			L.SubjectStudied AS SubjectNAme,
			--ISNULL(SubM.Title,'') AS SubjectNAme,
			'' AS PromotedorNot,
			L.PromoteToClass  AS PromotedToClass,
			L.FeeDetail AS LastFeesPaid,
			L.FeeConcessionDetail AS AnyConcession,
			L.NCCScoutDetail  AS NCCScoutDetail,
			L.ExtraCurricularActivities AS GamesPlayed,
			OM.OrgLogo,
			OM.Title AS OrgTitle,
			OM.StreetOne+' '+OM.StreetTwo+' '+OM.StreetThree AS OrgAddress,
			OM.PhoneNo,
			vSA.RollNo,
			DM.OrderIndex AS DivisionOrder,
			OM.SmallAddress1,
			OM.SmallAddress2,
			OM.RegistrationDetail,
			@lIsOnPrePrinted AS IsOnPrePrinted,
			@lIsDisplayReligion AS IsDisplayReligion,
			AD.PresentDaysAnnual AS PresentDaysSum,
			AD.TotalDaysAnnual AS TotalDaysSum,
			vSA.ClassName AS ClassName,
			vSA.DivisionName AS DivisionName,
			@lIsDisplayImageHeader AS IsDisplayImageHeader,
			OI.CertificateHeaderA4  ,
			isnull(MainCastCategoryId,0) AS CastCategoryId,
			ISNULL(L.ToCollege,'') AS ToCollege ,
			ISNULL(L.ToCollegeAddress,'')AS ToCollegeAddress,
			ISNULL(OM.University,'')AS University,
			@lSchoolRemark1 AS SchoolRemark1 ,
			@lSchoolRemark2 AS SchoolRemark2 ,
			@lSchoolRemark3 AS SchoolRemark3 ,
			@lSchoolRequiredSignature AS SchoolRequiredSignature,
			ISNULL(CSG.Inword,'')AS CurrentStandardInWords,
			SO.MotherTongue,
			SO.AdhaarNumber,
			vSA.SUId,
			CASE WHEN isnull(BM.FromDate,'')>Isnull(SA.AdmissionDate,'') THEN BM.FromDate ELSE SA.AdmissionDate END AS BatchDate,
			SO.BirthState,
			SO.BirthCountry,
			SD.BankAccountNumber,
			SO.UIDNumber,
			SD.BankName,
			SD.BankIFSCCode,
			SA.PreviousStandard 
		--sFinanceCommon.fNumberToWords(ISNULL(CM.ClassGroupId,0),'',OM.OrgGroupId) AS CurrentStandardInWords
		--CASE WHEN @rIsTransferCerti=1
		--THEN ISNULL(MR.PresentCount,0)
		--WHEN @rIsTransferCerti=0
		--THEN SUM(ISNULL(MR.PresentCount,0))
		--END AS Presentdays,
		--CASE WHEN @rIsTransferCerti=1
		--THEN ISNULL(MR.TotalCount,0)
		--WHEN @rIsTransferCerti=0
		--THEN SUM(ISNULL(MR.TotalCount,0))
		--END AS TotalCount
	FROM 
			sCertificate.tLeaving L
			INNER JOIN sStudent.vStudentAcademic vSA ON vSA.AcademicId=L.AcademicId
			--INNER JOIN sStudent.tAcademic A ON L.AcademicId=A.Id
			LEFT JOIN sStudent.tStudentAdmission SA ON SA.StudentId=vSA.StudentId
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=vSA.StudentId			
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=vSA.OrgId 
			LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=vSA.StudentId 
			LEFT JOIN sCommon.tReligionMaster RM ON SO.ReligionId=RM.Id
			--LEFT JOIN  sAttendance.tMonthlyRegister MR ON MR.AcademicId=A.Id 
			LEFT JOIN sSetup.tClassMaster CM ON CM.Id=SA.AdmissionStandardId
			INNER JOIN sSetup.tDivisionMaster DM ON vSA.DivisionId = DM.Id  
			INNER JOIN sSetup.tClassMaster CMS ON CMS.Id= DM.ClassId 
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId=vSA.StudentId
			LEFT JOIN sCommon.tCountryMaster CTM ON CTM.Id=SO.NationalityId
			LEFT JOIN sStudent.tAcademicDetail AD ON AD.AcademicId=vSA.AcademicId
			--LEFT JOIN sSetup.tClassSubject CS ON CS.ClassId=A.ClassId
			--LEFT JOIN sSetup.tSubjectMaster SubM ON SM.Id=CS.SubjectId
			LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = OM.Id
			LEFT JOIN sCommon.tCastCategoryMaster CSM ON CSM.Id=SO.CastCategoryId
			LEFT JOIN sSetup.tClassGroupMaster CSG ON CSG.Id=CMS.ClassGroupId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id=vSA.BatchId 
			--AND BM.OrgGroupBatchId=vSA.OrgGroupBatchId
			LEFT JOIN sStudent.tStudentAdditional SD ON SD.StudentId=vSA.StudentId

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


GO

ALTER 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,
		ISNULL(HM.Id,0) AS HostelId,
		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,
		ISNULL(A.RollNo,0) AS RollNo,
		ISNULL(DM.Id,0) AS DivisionId,
		ISNULL(A.BatchId,0) AS BatchId,
		SM.FIrstName,
		SM.LastName,
		SO.DateOfBirth,
		S.Title AS Status,
		ISNULL(SA.LeftDate,'') AS LeftDate
  FROM
      sStudent.tStudentMaster SM 	
    INNER JOIN sStudent.tStudentAdmission SA ON SM.Id = SA.StudentId  
	LEFT JOIN sStudent.tStudentOther SO ON SO.studentid = SM.Id 
	LEFT 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 sStudent.tStudentFamily SF ON Sf.StudentId = Sm.Id 
	LEFT 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
	LEFT JOIN sStudent.tStudentCommunication SC on SC.Studentid = Sm.Id 
	LEFT JOIN sStudent.tStatusMaster S ON S.Id = SM.StatusId 
	INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId AND IsActive = 1
  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='') 
	 ORDER BY DM.OrderIndex
END
GO
PRINT N'Altering [sCommon].[pOrganizationSetupRemove]...';


GO


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

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


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

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

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

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

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

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

DELETE FROM sTimetable.tAssignOrg WHERE OrgId = @rOrgId

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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


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

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

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


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

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

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


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

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

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

DELETE FROM sErp.tCustomerMaster WHERE OrgGroupId = @rOrgGroupId

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

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

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


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


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

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


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

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

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

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



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

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


GO
ALTER PROCEDURE [sCommon].[pPrefixSetupGet]
	@rOrgId [smallint] = 0,
	@rId [int] = 0,
	@rPrefix [nvarchar](10) = '',
	@rPrefixFunctionalityId [int] = 0,
	@rIsIncludeObsoleted [bit] = 1,
	@rStoreLocationId int  = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

SET @rPrefix = sCommon.fSearchStringGet(@rPrefix)

	 SELECT ISNULL(PS.Id,0) AS Id, 
			ISNULL(PF.Id,0) AS PrefixFunctionalityId, 
			ISNULL(PS.Prefix,'') AS Prefix, 
			--(CONVERT(NVARCHAR(12), PS.EffectiveDate, 101)) AS EffectiveDate, 
			ISNULL(PS.EffectiveDate,sCommon.fGetDate()) AS EffectiveDate,
			ISNULL(PS.IsObsolete,0) AS IsObsolete, 
			ISNULL(PF.Title,'') AS Title, 
			ISNULL(PS.NumberLength,0) AS SpecifiedPrefixLength, 
			ISNULL(PF.NumberMaxLength,0) AS MaxPrefixLength, 
			ISNULL(PS.Prefix +  CONVERT(NVARCHAR(10), ISNULL(PS.CurrentNumber, 0)),'') AS CurrentPrefix
	   FROM sCommon.tPrefixFunctionality PF		
	   LEFT JOIN sCommon.tPrefixSetup   PS	  
	   ON PS.PrefixFunctionalityId = PF.Id AND (PS.StoreLocationId = @rStoreLocationId OR PS.StoreLocationId=0) AND PS.OrgId = @rOrgId AND PF.IsObsolete=0
	   
	   WHERE  PF.IsObsolete = 0 AND	   
	         ISNULL(PS.IsObsolete,0) = (CASE WHEN @rIsIncludeObsoleted = 1 THEN PS.IsObsolete ELSE 0 END)
			 AND ((PS.Id = @rId) OR (@rId = 0)) 
	         AND ((PS.Prefix LIKE @rPrefix) OR (@rPrefix = '')) 
	         AND ((PS.PrefixFunctionalityId = @rPrefixFunctionalityId) OR (@rPrefixFunctionalityId = 0)) 
	         AND (ISNULL(PS.EffectiveDate,sCommon.fGetDate()) <= (CASE WHEN @rPrefixFunctionalityId > 0 THEN (sCommon.fGetDate()) ELSE (ISNULL(PS.EffectiveDate,sCommon.fGetDate())) END)) 
	         AND PF.Id not in (27,1005,1004,1006,26,52,53,1007)
	          --AND PS.OrgId = @rOrgId
	         --AND (PS.StoreLocationid = @rStoreLocationId )OR (@rStoreLocationId = 0)
	         order by PF.Title
	         
	         
END
GO
PRINT N'Altering [sCommunication].[pBehaviourEntryAdd]...';


GO

ALTER PROCEDURE [sCommunication].[pBehaviourEntryAdd]
	 
	@rId bigint,
	@rBehaviourDate date,
	@rAcademicId  bigint,
	@rBehaviourTypeId int,
	@rTitle nvarchar(100),
	@rRemark nvarchar(200),
	@rCreatedUserId bigint,
	@rCreatedDateTime datetime,
	@rOrgGroupId smallint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
		--IF(@rId = 0)	
--	IF Exists(Select @rCode from	sLibrary.tBookMaster where Code=@rCode)
--BEGIN
--Select -103 AS Result
--RETURN
--END	
BEGIN TRANSACTION

IF(@rId = 0)

    BEGIN
DECLARE @lNextNumber BIGINT     
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sCommunication.tBehaviour', 0, 1, 1,@outNextNumber = @lNextNumber output

	INSERT INTO sCommunication.tBehaviour
		(
			Id,
			BehaviourDate,
			AcademicId,
			BehaviourTypeId,
			Title,
			Remark,
			CreatedUserId,
			CreatedDateTime
		)
	VALUES
		(
			@lNextNumber,
			@rBehaviourDate,
			@rAcademicId,
			@rBehaviourTypeId,
			@rTitle,
			ISNULL(@rRemark,''),
			@rCreatedUserId,
			sCommon.fGetDate()
		)
		   Select @lNextNumber AS Result
	END
	ELSE
	
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sCommunication.tBehaviour
	    SET
			BehaviourDate=@rBehaviourDate,
			AcademicId=@rAcademicId,
			BehaviourTypeId=@rBehaviourTypeId,
			Title=@rTitle,
			Remark=ISNULL(@rRemark,'')
	--		BehaviourIndicatorId=@rBehaviourIndicatorId,
	--		OrgId=@rOrgId,
	--		IsObsolete=@rIsObsolete,
	--		UpdatedUserId=@rUpdatedUserId,
	--		UpdatedDateTime= sCommon.fGetDate()
			
	      
	      WHERE Id = @rId 
     SELECT @lNextNumber AS Result
	
END	
	
	COMMIT TRANSACTION
END TRY

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


GO
ALTER PROCEDURE [sCommunication].[pFeedbackAdd]
	 
	 	@rOrgGroupBatchId  int,
        @rId bigint=0,
        @rTitle nvarchar(200), 
		@rCreatedUserId bigint ,
		@rIsPublish bit,
		@rIsClose bit,
		@rFeedbackTemplateId bigint ,
		@rOrgGroupId int
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	 
	 DECLARE @lNextNumber BIGINT 

	 
	
	IF(@rId = 0)	
	BEGIN
		if exists(Select 1 from sCommunication.tFeedback where Title=@rTitle AND FeedbackTemplateId=@rFeedbackTemplateId)
	BEGIn
		Select -101 As Result
		Return
	END  
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sCommunication.tFeedback', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sCommunication.tFeedback
		(
			Id,
			Title,
			FeedbackTemplateId ,
			IsPublish,
			IsClose,			
			OrgGroupBatchId,
			CreatedUserId,
			CreatedDateTime 
			 
		)
	VALUES
		(
			@lNextNumber,
			@rTitle, 
			@rFeedbackTemplateId,
			@rIsPublish,
			@rIsClose,
			@rOrgGroupBatchId,
			@rCreatedUserId,
			sCommon.fGetDate() 
		)
		    SELECT @lNextNumber AS Result
	END	 

ELSE
	 BEGIN
	 --SET @lNextNumber = @rId
	    UPDATE  sCommunication.tFeedback
	    SET
			 
		 
			IsPublish=@rIsPublish,
			IsClose=@rIsClose,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate() 
	      
	      WHERE Id = @rId
	      SELECT @rId AS Result
	 END  	

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


GO
ALTER PROCEDURE [sCommunication].[pFeedbackAnswerTemplateQuestionGet]
	  
        @rFeedbackTemplateId bigint=0,
        @rId bigint=0
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	Select 
		Id,
		QuestionNumber,
		Question ,
		FeedbackTemplateId,
		ISNULL(FeedbackAnswerTypeId,0) AS FeedbackAnswerTypeId ,
		CreatedUserId,
		CreatedDateTime
		
	from sCommunication.tFeedbackTemplateQuestion
	Where  ((FeedbackTemplateId=@rFeedbackTemplateId) OR (@rFeedbackTemplateId=0))
	AND ((Id=@rId) OR (@rId=0))
	 
END
GO
PRINT N'Altering [sCommunication].[pFeedbackAnswerTypeMasterAdd]...';


GO
ALTER PROCEDURE [sCommunication].[pFeedbackAnswerTypeMasterAdd]
	 
	 	@rOrgGroupId smallint,
        @rId bigint=0,
        @rCode nvarchar(200),
        @rTitle nvarchar(200),
        @rIsObsolete bit,
		@rCreatedUserId bigint,
		@rFeedBackAnswerGroupMasterId int
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	 DECLARE @lNextNumber BIGINT 

 
	
	
	IF(@rId = 0)	
	BEGIN
		
			if exists(Select 1 from sCommunication.tFeedbackAnswerTypeMaster where Code=@rCode AND ORggroupId=@rOrgGroupId)
	BEGIn
		Select -101 As Result
		Return
	END
	
	If exists(Select 1 from sCommunication.tFeedbackAnswerTypeMaster where Title =@rTitle AND ORggroupId=@rOrgGroupId)
	BEGIN
		Select -102 As Result
		Return
	END
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sCommunication.tFeedbackAnswerTypeMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sCommunication.tFeedbackAnswerTypeMaster
		(
			Id,
			Code,
			Title,
			IsObsolete,
			OrgGroupId,
			CreatedUserId,
			CreatedDateTime,
			FeedBackAnswerGroupMasterId
		)
	VALUES
		(
			@lNextNumber,
			@rCode,
			@rTitle,
			@rIsObsolete,
			@rOrgGroupId,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rFeedBackAnswerGroupMasterId
		)
		    SELECT @lNextNumber AS Result
	END	 

ELSE
	 BEGIN
	 --SET @lNextNumber = @rId
	    UPDATE  sCommunication.tFeedbackAnswerTypeMaster
	    SET
			Code=@rCode,
			Title=@rTitle,
			OrgGroupId=@rOrgGroupId,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate() ,
			 FeedBackAnswerGroupMasterId=@rFeedBackAnswerGroupMasterId
	      
	      WHERE Id = @rId
	      SELECT @rId AS Result
	 END  	

	
	END TRY
	
	BEGIN CATCH 
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sCommunication].[pFeedbackAssignAdd]...';


GO
ALTER PROCEDURE [sCommunication].[pFeedbackAssignAdd]
	 
	 	 
        --@rId bigint=0,
        --@rAssignSourceTypeId smallint, 
		--@rAssignSourceId bigint ,
		@rFeedbackId bigint,
		@rDetail nvarchar(max)='',
		@rBatchId int,
		@rOrgId smallint,
		@rAssignToSourceTypeId smallint
		--@rForName nvarchar(200) ,
		--@rIsDelete bit
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
 DECLARE @loDoc INT
SET @rDetail=REPLACE(@rDetail,'&','AND')
EXEC sp_xml_preparedocument @loDoc OUTPUT  ,@rDetail
Declare @lCount int
BEGIN
	
		CREATE Table #temp
		(
			Id int Identity(1,1),
			AssignToSourceTypeId smallint,
			AssignToSourceId bigint,
			FeedbackId bigint
		)
		Insert Into #temp
		Select AssignToSourceTypeId,AssignToSourceId ,FeedbackId
					From Openxml(@loDoc,'Table/Feedback',1)
					With
					(
						AssignToSourceTypeId smallint,
						AssignToSourceId bigint ,
						FeedbackId bigint
					)
		Select @lCount=count(*) from #temp
	 
	 
	 
	 Delete FB from  sCommunication.tFeedbackAssign FB
	 INNER JOIN #temp T ON T.AssignToSourceId =FB.AssignToSourceId 
	 WHere  T.FeedbackId=@rFeedbackId
	 
	 
	 INSERT INTO sCommunication.tFeedbackAssign
	 (
		 
		AssignToSourceTypeId,
		AssignToSourceId,
		FeedbackId,
		ForName
	 )
	  Select AssignToSourceTypeId,AssignToSourceId,@rFeedbackId,''
	From Openxml(@loDoc,'Table/Feedback',1)
		With
		(
			AssignToSourceTypeId smallint,
			AssignToSourceId bigint ,
			FeedbackId bigint
		)
	 
	  
	 --Values
	 --(
		 
		--@rAssignSourceTypeId,
		--@rAssignSourceId,
		--@rFeedbackId,
		--@rForName
	 --)
	  
	 --END
	-- ELse 
	-- BEGIN
	-- SET @lNextNumber = @rId
	-- IF(@rIsDelete = 0)
	-- BEGIN
	--	 UPDATE sCommunication.tFeedbackAssign
	--	 SET
	--		AssignToSourceTypeId=@rAssignSourceTypeId,
	--		AssignToSourceId=@rAssignSourceId,
	--		FeedbackId=@rFeedbackId,
	--		ForName=@rForName
	--		WHERE Id=@rId
	--	 END 
	--	  ELSE 
	--	DELETE FROM sCommunication.tFeedbackAssign  WHERE Id =  @rId	
	--END
		Select 1 As Result
END
GO
PRINT N'Altering [sCommunication].[pFeedbackAssignGet]...';


GO
ALTER PROCEDURE [sCommunication].[pFeedbackAssignGet]
	  
        @rFeedbackId bigint=0,
        @rId bigint=0,
        @rAssignToSourceTypeId smallint
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	if(@rAssignToSourceTypeId=2003)
	BEGIN
	SELECT
		 
		 FA.Id,
		 SM.ID AS SourceId,
		 FeedbackId,
		 AssignToSourceTypeId,
		 ForName,
		 
		 Isnull(A.DivisionId,0) AS DivisionId,
		 Firstname+' '+MiddleName+' ' +LastName AS Name,  AssignToSourceId ,
		 SM.Code
		 FROM  sCommunication.tFeedbackAssign FA
		 INNER JOIN sStudent.tAcademic A  ON FA.AssignToSourceId=A.ID 
		 INNER  JOIN sStudent.tStudentMaster SM ON SM.ID=A.StudentID
		 
		 WHERE  ((FeedbackId=@rFeedbackId) OR (@rFeedbackId=0))  AND AssignToSourceTypeId=2003
	END
	
	else if(@rAssignToSourceTypeId=95)
	BEGIN
		SELECT
		 
		 FA.Id,
		 Em.ID AS SourceId,
		 FeedbackId,
		 AssignToSourceTypeId,
		 ForName,
		 Code,
		 --Isnull(A.DivisionId,0) AS DivisionId,
		 Firstname+' '+MiddleName+' ' +LastName AS Name,  AssignToSourceId 
		 FROM  sCommunication.tFeedbackAssign FA
		 INNER JOIN sHrm.tEmployeeMaster Em ON FA.AssignToSourceId=Em.ID 
		 
		 WHERE  ((FeedbackId=@rFeedbackId) OR (@rFeedbackId=0))  AND AssignToSourceTypeId=95
	END
	--Select 
	--	 (CASE AssignToSourceTypeId WHen  95
	--	 THEN
	--		(Select 
	--		 FirstName +' ' + MiddleName+' ' + LastName
	--		From sHrm.tEmployeeMaster Where  Id=FB.AssignToSourceId And FB.AssignToSourceTypeId=95)
	--	 WHEN  2003
	--	 THEN
	--		(Select
	--		 FirstName +' ' + MiddleName+' ' + LastName
	--		From sStudent.tStudentMaster Where Id=FB.AssignToSourceId ANd FB.AssignToSourceTypeId=2003)
	--	 Else
	--		ForName
	--	 END) AS Name,
	--	FB.Id,
	--	AssignToSourceTypeId,
	--	AssignToSourceId,
	--	FeedbackId,
	--	ForName 
	  
		
	--from sCommunication.tFeedbackAssign FB
	 
	--Where  ((FeedbackId=@rFeedbackId) OR (@rFeedbackId=0))
	--AND ((FB.Id=@rId) OR (@rId=0))
	 
END
GO
PRINT N'Altering [sCommunication].[pFeedbackForGet]...';


GO
ALTER PROCEDURE [sCommunication].[pFeedbackForGet]
	  
        @rFeedbackId bigint=0,
        @rId bigint=0
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	Select 
		 (CASE ForSourceTypeId WHen  95
		 THEN
			(Select 
			 FirstName +' ' + MiddleName+' ' + LastName
			From sHrm.tEmployeeMaster Where  Id=FB.ForSourceId And FB.ForSourceTypeId=95)
		 WHEN  2003
		 THEN
			(Select
			 FirstName +' ' + MiddleName+' ' + LastName
			From sStudent.tAcademic A
			INNER JOIN  sStudent.tStudentMaster SM ON SM.Id=A.StudentID
			Where A.Id=FB.ForSourceId ANd FB.ForSourceTypeId=2003)
		 Else
			ForName
		 END) AS Name,
		 (CASE ForSourceTypeId WHen  95
		 THEN
			(Select 
			 Code
			From sHrm.tEmployeeMaster Where  Id=FB.ForSourceId And FB.ForSourceTypeId=95)
		 WHEN  2003
		 THEN
			(Select
			 Code
			From sStudent.tAcademic A
			INNER JOIN  sStudent.tStudentMaster SM ON SM.Id=A.StudentID
			Where A.Id=FB.ForSourceId ANd FB.ForSourceTypeId=2003)
		 Else
			ForName
		 END) AS StudentIdNo,
		FB.Id,
		ForSourceTypeId,
		ForSourceId,
		FeedbackId,
		ForName
		
	from sCommunication.tFeedbackFor FB
	 
	 
	Where  ((FeedbackId=@rFeedbackId) OR (@rFeedbackId=0))
	AND ((FB.Id=@rId) OR (@rId=0))
	 
END
GO
PRINT N'Altering [sCommunication].[pFeedbackQuestionResponseAdd]...';


GO
ALTER PROCEDURE [sCommunication].[pFeedbackQuestionResponseAdd]
	  
        @rFeedbackResponseId bigint=0,
        @rFeedbackTemplateQuestionId bigint,
        @rFeedbackAnswerTypeDetailId bigint,
        @rFeedbackAnswerDescription nvarchar(200)=''
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	 if not exists(Select 1 from sCommunication.tFeedbackQuestionResponse where FeedbackResponseId=@rFeedbackResponseId
	 AND FeedbackTemplateQuestionId=@rFeedbackTemplateQuestionId)
	 BEGIN
		Insert Into sCommunication.tFeedbackQuestionResponse
		 (
			FeedbackResponseId,
			FeedbackTemplateQuestionId,
			FeedbackAnswerTypeDetailId,
			FeedbackAnswerDescription 
			 
		 )
		 Values
		 (
			@rFeedbackResponseId,
			@rFeedbackTemplateQuestionId,
			@rFeedbackAnswerTypeDetailId,
			@rFeedbackAnswerDescription 
			 
		 )
		 Select 1 As Result
	 END
	 Else
	 BEGIN
		Update sCommunication.tFeedbackQuestionResponse
		Set
			FeedbackAnswerTypeDetailId =@rFeedbackAnswerTypeDetailId,
			FeedbackAnswerDescription=@rFeedbackAnswerDescription,
			FeedbackTemplateQuestionId= @rFeedbackTemplateQuestionId
			
		Where
			FeedbackResponseId=@rFeedbackResponseId AND FeedbackTemplateQuestionId=@rFeedbackTemplateQuestionId
		Select 11 As Result
	 END 
	 
END
GO
PRINT N'Altering [sCommunication].[pFeedbackResponseAdd]...';


GO
ALTER PROCEDURE [sCommunication].[pFeedbackResponseAdd]
	  
        @rFeedbackId bigint=0,
        @rSourceTypeId smallint,
        @rSourceId bigint,
        @rCreatedUserId bigint,
        @rOrgGroupId bigint
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	 IF Not Exists(Select 1 from sCommunication.tFeedbackResponse where FeedbackId=@rFeedbackId ANd SourceId=@rSourceId and SourceTypeId=@rSourceTypeId)
	 BEGIN
	  Declare @lNextNumber bigint
	  EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sCommunication.tFeedbackResponse', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	 Insert Into sCommunication.tFeedbackResponse
	 (
		Id,
		FeedbackId,
		SourceTypeId,
		SourceId,
		CreatedUserId,
		CreatedDateTime
	 )
	 Values
	 (
		@lNextNumber,
		@rFeedbackId,
		@rSourceTypeId,
		@rSourceId,
		@rCreatedUserId,
		sCommon.fGetDate() 
	 )
	Select @lNextNumber As Result
	 END
	ELse
	BEGIN
		Select Id from sCommunication.tFeedbackResponse
		Where FeedbackId=@rFeedbackId And SourceTypeId=@rSourceTypeId AND SourceId=@rSourceId
			
	END

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


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

BEGIN 
	 SELECT	
		FQ.Id As TempateQuestionId,
					FQ.QuestionNumber,
					FQ.Question ,
					FQ.FeedbackAnswerTypeID,			 
					ISNULL(FQR. FeedbackAnswerTypeDetailId,0) AS FeedbackAnswerTypeDetailId,
					FR.SourceId ,
					ISNULL(FQR.FeedbackAnswerDescription,'') AS FeedbackAnswerDescription
		from sCommunication.tFeedback FB 
		INNER JOIN	sCommunication.tFeedbackTemplateQuestion FQ ON FQ.FeedbackTemplateId = FB.FeedbackTemplateId
		LEFT JOIN sCommunication.tFeedbackResponse FR ON FR.FeedbackId = FB.Id AND  SourceId = @rUserSourceId 		
				  AND SourceTypeId=@rUserSourceTypeId 
		Left Join sCommunication.tFeedbackQuestionResponse FQR ON  FQR.FeedBackResponseId = FR.Id 
		AND FQR.FeedbackTemplateQuestionID = FQ.Id
		--AND FQR.FeedBackResponseId = 1001000000001
		--LEFT JOIN sCommunication.tFeedbackAnswerTypeDetail FA ON FA.ID=FQR.FeedbackAnswerTypeDetailId
		WHERE FB.Id = @rFeedbackId ANd OrgGroupBatchId=@rOrgGroupBatchId
		 END
GO
PRINT N'Altering [sCommunication].[pFeedbackTemplateAdd]...';


GO
ALTER PROCEDURE [sCommunication].[pFeedbackTemplateAdd]
	 
	 	@rOrgGroupId smallint,
        @rId bigint=0,
        @rCode nvarchar(200),
        @rTitle nvarchar(200), 
		@rCreatedUserId bigint 
		 
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	 DECLARE @lNextNumber BIGINT 

	 
	
	IF(@rId = 0)	
	BEGIN
		if exists(Select 1 from sCommunication.tFeedbackTemplate where Code=@rCode AND OrgGroupId=@rOrgGroupId)
	BEGIn
		Select -101 As Result
		Return
	END
	
	If exists(Select 1 from sCommunication.tFeedbackTemplate where Title =@rTitle AND OrgGroupId=@rOrgGroupId)
	BEGIN
		Select -102 As Result
		Return
	END
	
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sCommunication.tFeedbackTemplate', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sCommunication.tFeedbackTemplate
		(
			Id,
			Code,
			Title, 
			OrgGroupId,
			CreatedUserId,
			CreatedDateTime 
			 
		)
	VALUES
		(
			@lNextNumber,
			@rCode,
			@rTitle, 
			@rOrgGroupId,
			@rCreatedUserId,
			sCommon.fGetDate() 
		)
		    SELECT @lNextNumber AS Result
	END	 

ELSE
	 BEGIN
	 --SET @lNextNumber = @rId
	    UPDATE  sCommunication.tFeedbackTemplate
	    SET
			Code=@rCode,
			Title=@rTitle, 
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate() 
	      
	      WHERE Id = @rId
	      SELECT @rId AS Result
	 END  	

	
	END TRY
	
	BEGIN CATCH 
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sCommunication].[pFeedbackTypeMasterDelete]...';


GO
ALTER PROCEDURE [sCommunication].[pFeedbackTypeMasterDelete]

	 @rId bigint,
	 @rOrgGroupId int
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	BEGIN TRY
		--IF NOT EXISTS (SELECT Id FROM sCommunication.tCircular WHERE CircularTypeId = @rId)	
		--BEGIN	
			Delete from sCommunication.tFeedbackAnswerTypeMaster where Id=@rId AND OrgGroupId=@rOrgGroupId
			  
			Delete from sCommunication.tFeedbackAnswerTypeDetail where FeedbackAnswerTypeId=@rId
			Select 1 AS RESULT
		--END
		--ELSE
		--	BEGIN
		--		SELECT -101 AS RESULT
		--	END
			
		
	END TRY
	
	BEGIN CATCH 
		SELECT -1 AS RESULT
	END CATCH	
END
GO
PRINT N'Altering [sErp].[pStudentStrengthDetailGet]...';


GO


ALTER PROCEDURE [sErp].[pStudentStrengthDetailGet]
	 	 
		@rDatabaseName nvarchar(max)='',
		@rOrgGroupId smallint=0
		 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 

Declare @strStudentCount VarChar (MAX)
Declare @strFeeReceiptDate VarChar (MAX)
Declare @strExamStatusDate VarChar (MAX)
Declare @strBonafiesCertificateDate VarChar (MAX)
Declare @strLCCertificateDate VarChar (MAX)
Declare @strAttendanceDate VarChar (MAX)
Declare @strEmployeeDate VarChar (MAX)
Declare @strAlertDate VarChar (MAX)
DECLARE @strMobileUserCount varchar(MAX)
--SET @strSQL = 'SELECT * FROM ' + @rDatabaseName+ '.sSetup.tOrgGroupSetting WHERE OrgGroupId = '+ convert (nvarchar,@rOrgGroupId)

		SET @strStudentCount =  'SELECT NoOfStudent FROM '+ @rDatabaseName+'.sSetup.tOrgGroupSetting WHERE '+ 
		+' OrgGroupId ='+ convert (nvarchar,@rOrgGroupId)+' SELECT COUNT(SM.AcademicId) FROM '+ @rDatabaseName+'.sStudent.vStudentAcademic SM '+ 
		+'INNER JOIN '+@rDatabaseName+'.sSetup.tOrganizationMaster OM ON OM.Id = SM.OrgId '+
		+'INNER JOIN '+@rDatabaseName+'.sSetup.tBatchMaster BM ON BM.Id=SM.BatchId  '+
		+'WHERE OM.OrgGroupId = '+convert (nvarchar,@rOrgGroupId)+ ' AND BM.IsActive = 1 SELECT COUNT(SM.AcademicId) FROM '+@rDatabaseName+'.sStudent.vStudentAcademic SM '+ 
		+'INNER JOIN '+@rDatabaseName+'.sSetup.tOrganizationMaster OM ON OM.Id = SM.OrgId '+
		+'INNER JOIN '+@rDatabaseName+'.sSetup.tBatchMaster BM ON BM.Id=SM.BatchId '+
		+' WHERE OM.OrgGroupId = '+convert (nvarchar,@rOrgGroupId)+' AND BM.IsActive = 1'		
		


		SET @strFeeReceiptDate = 'SELECT DATEDIFF(DAY,MAX(FR.CreatedDateTime),GETDATE())AS FeeDays,MAX(FR.CreatedDateTime)AS LastFeeDate FROM '+@rDatabaseName+'.sFee.tReceipt FR 
		INNER JOIN '+@rDatabaseName+'.sSetup.tOrgGroupBatchMaster OBM ON OBM.Id=FR.OrgGroupBatchId WHERE OBM.OrgGroupId = '++convert (nvarchar,@rOrgGroupId)
	
			SET @strExamStatusDate= 'SELECT DATEDIFF(DAY,MAX(ES.UpdatedDateTime),GETDATE())AS ExamDays,MAX(ES.UpdatedDateTime)AS LastExamDate FROM '+@rDatabaseName+'.sAssessment.tResult ES'+
		--+' INNER JOIN '+@rDatabaseName+'.sSetup.tDivisionMaster DM ON DM.Id=ES.DivisionId'+
		--+' INNER JOIN '+@rDatabaseName+'.sSetup.tOrganizationMaster OM ON OM.Id=DM.OrgId WHERE OM.OrgGroupId='+convert (nvarchar,@rOrgGroupId)
		+' INNER JOIN '+@rDatabaseName+'.sStudent.vStudentAcademic vSA ON vSA.AcademicId =ES.AcademicId '+
		+' INNER JOIN '+@rDatabaseName+'.sSetup.tOrganizationMaster OM ON OM.Id=vSA.OrgId WHERE OM.OrgGroupId='+convert (nvarchar,@rOrgGroupId)


		SET @strAttendanceDate ='SELECT  DATEDIFF(DAY,MAX(SR.AttendanceDate),GETDATE())AS AttendancDays,MAX(SR.AttendanceDate)AS LastAttendanceDate FROM '+@rDatabaseName+'.sAttendance.tStudentRegister SR '+ 
		+'INNER JOIN '+@rDatabaseName+'.sStudent.vStudentAcademic vSA ON vSA.AcademicId =  SR.AcademicId '+
		+'INNER JOIN '+@rDatabaseName+'.sSetup.tOrganizationMaster OM ON OM.Id=vSA.OrgId WHERE OM.OrgGroupId='+convert (nvarchar,@rOrgGroupId)


		SET @strEmployeeDate ='SELECT DATEDIFF(DAY,MAX(EM.CreatedDateTime),GETDATE())AS EmployeeDays,MAX(EM.CreatedDateTime)AS LastEmployeeDate FROM '+@rDatabaseName+'.sHrm.tEmployeeMaster EM'+
		+' INNER JOIN '+@rDatabaseName+'.sSetup.tOrganizationMaster OM ON OM.Id=EM.OrgId WHERE OM.OrgGroupId='+convert (nvarchar,@rOrgGroupId)

		SET @strAlertDate= 'SELECT DATEDIFF(DAY,MAX(AL.CreatedDateTime),GETDATE())AS AlertDays,MAX(AL.CreatedDateTime)AS LastAlertDate FROM '+@rDatabaseName+'.sAlert.tAlertLog AL'+
		+' INNER JOIN '+@rDatabaseName+'.sSetup.tOrganizationMaster OM ON OM.Id=AL.OrgId WHERE OM.OrgGroupId='+convert (nvarchar,@rOrgGroupId)

		SET @strBonafiesCertificateDate = 'SELECT DATEDIFF(DAY,MAX(B.CreatedDateTime),GETDATE())AS BonafiedDays,MAX(B.CreatedDateTime)AS BonafiedDate FROM '+@rDatabaseName+'.sCertificate.tBonafide  B'+
		+' INNER JOIN '+@rDatabaseName+'.sSetup.tOrganizationMaster OM ON OM.Id=B.OrgId WHERE OM.OrgGroupId='+convert (nvarchar,@rOrgGroupId)


		SET @strLCCertificateDate = 'SELECT DATEDIFF(DAY,MAX(L.CreatedDateTime),GETDATE())AS LCDays,MAX(L.CreatedDateTime)AS LCDate FROM '+@rDatabaseName+'.sCertificate.tLeaving  L'+
		+' INNER JOIN '+@rDatabaseName+'.sSetup.tOrganizationMaster OM ON OM.Id=L.OrgId WHERE OM.OrgGroupId='+convert (nvarchar,@rOrgGroupId)

        SET @strMobileUserCount = 'SELECT  COUNT(UserId) AS Registerdcount FROM '+@rDatabaseName+'.sCommunication.tRegisteredUsers  RU'+
		+' INNER JOIN '+@rDatabaseName+'.sSetup.tOrganizationMaster OM ON OM.Id=RU.OrgId WHERE DeviceToken IS NOT NULL  AND UserSourceTypeId=2003 AND OM.OrgGroupId='+convert (nvarchar,@rOrgGroupId) 


		exec (@strStudentCount)
		exec (@strFeeReceiptDate)
		exec (@strExamStatusDate)
		exec (@strBonafiesCertificateDate)
		exec (@strLCCertificateDate)
		exec (@strAttendanceDate)
		exec (@strEmployeeDate)
		exec (@strAlertDate)
	    exec (@strMobileUserCount)
END
GO
PRINT N'Altering [sFee].[pChargePostingGet]...';


GO

ALTER PROCEDURE [sFee].[pChargePostingGet]
				
		   --@rClassId int,
           @rReceiptBookId int,
		   @rBatchId int,
		   @rOrgGroupId int,
		   @rReceiptDate date,
		   @rReceiptDateTo date,
		   @rChequePosting nvarchar(50)
           
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 
	IF @rChequePosting = 'Single'
	BEGIN
			SELECT  
					R.ReceiptDate,
					AMast.Title AS AccountName,
					AYM.Title AS AccountingYearName,
					AM.CreditLedgerId,
					CLM.Title AS CreditLedgerName,
					AM.DebitLedgerId,
					DLM.Title AS DebitLedgerName,
					SUM(RD.Amount) AS ReceiptAmount,
					'' AS ChequeNo,'' AS ChequeDate,'' AS BankName,0 AS PayTypeId,
					ISNULL(AYM.ISLocked,0) AS ISLocked				
			FROM 
					sFee.tChargeAccountMapping AM
					INNER JOIN sFee.tChargeReceiptDetail RD ON RD.ChargeId = AM.ChargeId  
					INNER JOIN sFee.tChargeReceipt R ON R.Id = RD.ChargeReceiptId 
						AND R.PayTypeId = AM.PayTypeId
						AND R.ReceiptDate >= @rReceiptDate 
						AND R.ReceiptDate <= @rReceiptDateTo AND R.IsObsolete = 0
					--INNER JOIN sFee.tFeeSetup FS ON FS.Id=AM.ChargeId 
					----AND (FS.ClassId=@rClassId) 
					--	AND (FS.ReceiptBookId=@rReceiptBookId) 
					--	AND (R.OrgGroupBatchId=@rBatchId)
					INNER JOIN sFee.tChargeMaster FM ON FM.Id=AM.ChargeId 
					INNER JOIN sAccounting.tAccountingYearMaster AYM ON AYM.Id=AM.AccountingYearId
					INNER JOIN sAccounting.tAccountMaster AMast ON AMast.Id=AYM.AccountId
					INNER JOIN sAccounting.tLedgerMaster CLM ON (CLM.Id=AM.CreditLedgerId)  AND CLM.AccountingYearId = AM.AccountingYearId
					INNER JOIN sAccounting.tLedgerMaster DLM ON (DLM.Id=AM.DebitLedgerId) AND DLM.AccountingYearId = AM.AccountingYearId
				WHERE 
					AMast.OrgGroupId=@rOrgGroupId			
					GROUP BY R.ReceiptDate,AM.CreditLedgerId,	AM.DebitLedgerId,AMast.Title,AYM.Title,CLM.Title,DLM.Title,AYM.IsLocked
	 END
	 ELSE
		BEGIN		
		SELECT  
			R.ReceiptDate,
			AMast.Title AS AccountName,
			AYM.Title AS AccountingYearName,
			AM.CreditLedgerId,
			CLM.Title AS CreditLedgerName,
			AM.DebitLedgerId,
			DLM.Title AS DebitLedgerName,
			SUM(RD.Amount) AS ReceiptAmount,
			'' AS ChequeNo,'' AS ChequeDate,'' AS BankName,0 AS PayTypeId,
			ISNULL(AYM.ISLocked,0) AS ISLocked				
		FROM 
			sFee.tChargeAccountMapping AM
			INNER JOIN sFee.tChargeReceiptDetail RD ON RD.ChargeId = AM.ChargeId  
			INNER JOIN sFee.tChargeReceipt R ON R.Id = RD.ChargeReceiptId 
				AND R.PayTypeId = AM.PayTypeId
				AND R.ReceiptDate >= @rReceiptDate 
				AND R.ReceiptDate <= @rReceiptDateTo AND R.IsObsolete = 0
			--INNER JOIN sFee.tFeeSetup FS ON FS.Id=AM.ChargeId 
			--AND (FS.ClassId=@rClassId) 
			--	AND (FS.ReceiptBookId=@rReceiptBookId) 
				--AND (R.OrgGroupBatchId=@rBatchId)
            INNER JOIN sAccounting.tAccountingYearMaster AYM ON AYM.Id=AM.AccountingYearId
            INNER JOIN sAccounting.tAccountMaster AMast ON AMast.Id=AYM.AccountId
            INNER JOIN sAccounting.tLedgerMaster CLM ON (CLM.Id=AM.CreditLedgerId)  AND CLM.AccountingYearId = AM.AccountingYearId
            INNER JOIN sAccounting.tLedgerMaster DLM ON (DLM.Id=AM.DebitLedgerId) AND DLM.AccountingYearId = AM.AccountingYearId
		WHERE 
			AMast.OrgGroupId=@rOrgGroupId AND R.PayTypeId = 1
			GROUP BY R.ReceiptDate,AM.CreditLedgerId,	AM.DebitLedgerId,AMast.Title,AYM.Title,CLM.Title,DLM.Title,AYM.IsLocked
			
		UNION ALL
		
		SELECT  
			R.ReceiptDate,
			AMast.Title AS AccountName,
			AYM.Title AS AccountingYearName,
			AM.CreditLedgerId,
			CLM.Title AS CreditLedgerName,
			AM.DebitLedgerId,
			DLM.Title AS DebitLedgerName,
			RD.Amount AS ReceiptAmount,
			R.ChequeNo,R.ChequeDate,R.BankName,R.PayTypeId AS PayTypeId,
			ISNULL(AYM.ISLocked,0) AS ISLocked	
						
		FROM 
			sFee.tChargeAccountMapping AM
			INNER JOIN sFee.tChargeReceiptDetail RD ON RD.ChargeId = AM.ChargeId  
			INNER JOIN sFee.tChargeReceipt R ON R.Id = RD.ChargeId 
				AND R.PayTypeId = AM.PayTypeId
				AND R.ReceiptDate >= @rReceiptDate  
				AND R.ReceiptDate <= @rReceiptDateTo AND R.IsObsolete = 0
			--INNER JOIN sFee.tFeeSetup FS ON FS.Id=AM.FeeSetupId 
			--	AND (FS.ReceiptBookId=@rReceiptBookId) 
			--	AND (R.OrgGroupBatchId=@rBatchId)
            INNER JOIN sAccounting.tAccountingYearMaster AYM ON AYM.Id=AM.AccountingYearId
            INNER JOIN sAccounting.tAccountMaster AMast ON AMast.Id=AYM.AccountId
            INNER JOIN sAccounting.tLedgerMaster CLM ON (CLM.Id=AM.CreditLedgerId)  AND CLM.AccountingYearId = AM.AccountingYearId
            INNER JOIN sAccounting.tLedgerMaster DLM ON (DLM.Id=AM.DebitLedgerId) AND DLM.AccountingYearId = AM.AccountingYearId
		WHERE  R.PayTypeId = 2 AND	 AMast.OrgGroupId=@rOrgGroupId			
		END
END
GO
PRINT N'Altering [sFee].[pChargeReceiptListGet]...';


GO

ALTER PROCEDURE [sFee].[pChargeReceiptListGet]
	 
	 --@rReceiptNumber int,
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rSourceTypeId smallint,
	 @rSourceCode nvarchar(20),
	 @rGuestName nvarchar(200),
	 @rFromDate date,
	 @rToDate date,
	 @rFromNo int,
	 @rToNo int,
	 @rReceiptBookId int,
	 @rChargeCategoryId int,
	 @rOrgId int,
	 @rBatchId int,
	 @rOrgGroupBatchId int,
	 @rDepartmentId int = 0,
	 @rStudentCode nvarchar(20) = '',
	 @rOrgGroupId int=0,
	 @rStatusId int=0
	 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

		--select 
		
		--		'' AS Builder1,
		--		'' AS Builder2,
		--		'' AS Id,
		--		'' AS SourceType,
		--		'' AS SourceTypeId
		--		,'' AS GuestName
		--		,'' AS ReceiptNumber
		--		,'' AS ReceiptDate
		--		,'' AS Amount
		--		,'' AS ChargeCategory
		--		,'' AS ReceiptBook
		--		,'' AS ChargeCategoryId
		--		,'' As ReceiptBookId
		--		,'' AS OrgId
		--		,'' AS School
		--		,'' AS OrgGroupId
		--		,'' AS ChargeId








	 ----IF(@rIsSearch=1)
		----BEGIN
			SET @rSourceCode = sCommon.fSearchStringGet(@rSourceCode)
			SET @rGuestName = sCommon.fSearchStringGet(@rGuestName)
		--Declare @rSourceTypeId smallint
		--select @rSourceTypeId=SourceTypeId from sFee.tChargeReceipt where ReceiptNumber=@rReceiptNumber and OrgId=@rOrgId
		--END
IF @rSourceTypeId=95
BEGIN
		SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			--CRD.Id as DetailId,
			CR.Id,
			'Employee' as SourceType,
			CR.SourceTypeId,
			--EM.Code as SourceCode,
			EM.FirstName+' '+EM.LastName as GuestName,
			--CR.Remark,
			CR.ReceiptNumber,
			CR.ReceiptDate,
			--CR.PayTypeId,
			--CR.ChequeNo,
			--CR.BankName,
			--CR.IsObsolete,
			--CRD.Id as DetailId,
			--CRD.ChargeId,
			--CRD.Remark as DetailRemark,
			sum(CRD.Amount) as Amount,
			--Amount=(select sum(Amount) from sFee.tChargeReceiptDetail group by ChargeReceiptId),
			--CM.Code,
			--CM.Title,
			CCM.Title as ChargeCategory,
			CM.ChargeCategoryId,
			CR.OrgId,
			CR.BatchId,
			RBM.Title AS ReceiptBook,
			CR.ChargeReceiptBookId,
			OM.DisplayTitle AS OrganizationName
			--OM.DisplayTitle AS School,
			--OM.OrgGroupId,
			--CM.Id AS ChargeId
  FROM 
           sFee.tChargeReceipt CR
       INNER JOIN sFee.tChargeReceiptDetail CRD ON CRD.ChargeReceiptId=CR.Id
       INNER JOIN sHRM.tEmployeeMaster EM ON EM.Id=CR.SourceId AND (CR.SourceTypeId = @rSourceTypeId) 
       --AND EM.StatusId=7
       INNER JOIN sFee.tChargeMaster CM ON CM.Id=CRD.ChargeId
       INNER JOIN sFee.tChargeCategoryMaster CCM ON CCM.Id=CM.ChargeCategoryId
       INNER JOIN sFee.tChargeReceiptBookMaster RBM ON RBM.Id=CR.ChargeReceiptBookId
       INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=CR.OrgId
       --INNER JOIN sSetup.tOrgGroupBatchMaster OBM ON OBM.Id=CR.OrgGroupBatchId
       --INNER JOIN sSetup.tOrganizationMaster OM ON OM.OrgGroupId=OBM.OrgGroupId
     
  WHERE 
			--(CR.ReceiptNumber=@rReceiptNumber OR ISNULL(@rReceiptNumber,'')='')
			--AND 
				((EM.FirstName+' '+EM.LastName Like @rGuestName) OR (ISNULL(@rGuestName,'') = ''))
			AND ((EM.Code Like @rSourceCode) OR (ISNULL(@rSourceCode,'') = ''))
			AND ((CR.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((CR.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND ((CR.ReceiptNumber>=@rFromNo) OR (ISNULL(@rFromNo,'')=''))
			AND ((CR.ReceiptNumber<=@rToNo) OR (ISNULL(@rToNo,'')=''))
			AND ((CR.ChargeReceiptBookId = @rReceiptBookId) OR (ISNULL(@rReceiptBookId,0) = 0))
			AND ((CM.ChargeCategoryId = @rChargeCategoryId) OR (ISNULL(@rChargeCategoryId,0) = 0))
			AND (CR.IsObsolete=0)
			AND ((CR.OrgId=@rOrgId) OR (@rOrgId=0))
			And ((CR.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
			AND ((CR.BatchId=@rBatchId) OR (@rBatchId=0))
			AND (CRD.IsObsolete=0) 
			AND (OM.OrgGroupId = @rOrgGroupId or @rOrgGroupId=0)
			AND ((EM.StatusId=@rStatusId) OR (@rStatusId=0))
			group by CR.Id,EM.FirstName,EM.LastName,CR.ReceiptNumber,CR.ReceiptDate,CCM.Title,CR.OrgId,CR.BatchId,RBM.Title,CR.ChargeReceiptBookId,CM.ChargeCategoryId,CR.SourceTypeId,OM.DisplayTitle
END
ELSE IF @rSourceTypeId=2001
BEGIN
		SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			CR.Id,
			'Student' as SourceType,
			CR.SourceTypeId,
			--EM.Code as SourceCode,
			SA.FirstName+' '+SA.LastName as GuestName,
			--CR.Remark,
			CR.ReceiptNumber,
			CR.ReceiptDate,
			--CR.PayTypeId,
			--CR.ChequeNo,
			--CR.BankName,
			--CR.IsObsolete,
			--CRD.Id as DetailId,
			--CRD.ChargeId,
			--CRD.Remark as DetailRemark,
			sum(CRD.Amount) as Amount,
			--CM.Code,
			--CM.Title,
			CCM.Title as ChargeCategory,
			CM.ChargeCategoryId,
			CR.OrgId,
			CR.BatchId,
			RBM.Title AS ReceiptBook,
			CR.ChargeReceiptBookId,
			OM.DisplayTitle AS OrganizationName
			
			--OM.DisplayTitle AS School,
			--OM.OrgGroupId,
			--CM.Id AS ChargeId
  FROM 
           sFee.tChargeReceipt CR
       INNER JOIN sFee.tChargeReceiptDetail CRD ON CRD.ChargeReceiptId=CR.Id
       INNER JOIN sFee.tChargeMaster CM ON CM.Id=CRD.ChargeId
       INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=CR.SourceId AND CR.SourceTypeId=2001 
       --AND SA.StatusId=1
       INNER JOIN sFee.tChargeCategoryMaster CCM ON CCM.Id=CM.ChargeCategoryId
       INNER JOIN sFee.tChargeReceiptBookMaster RBM ON RBM.Id=CR.ChargeReceiptBookId
       INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=CR.OrgId
       --INNER JOIN sSetup.tOrgGroupBatchMaster OBM ON OBM.Id=CR.OrgGroupBatchId
       --INNER JOIN sSetup.tOrganizationMaster OM ON OM.OrgGroupId=OBM.OrgGroupId
       
  WHERE 
			--(CR.ReceiptNumber=@rReceiptNumber OR ISNULL(@rReceiptNumber,'')='')
			--AND 
				((SA.FirstName+' '+SA.LastName Like @rGuestName) OR (ISNULL(@rGuestName,'') = ''))
			AND ((SA.Code Like @rSourceCode) OR (ISNULL(@rSourceCode,'') = ''))
			AND ((CR.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((CR.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND ((CR.ChargeReceiptBookId = @rReceiptBookId) OR (ISNULL(@rReceiptBookId,0) = 0))
			AND ((CM.ChargeCategoryId = @rChargeCategoryId) OR (ISNULL(@rChargeCategoryId,0) = 0))
			AND (CR.IsObsolete=0)
			AND ((CR.OrgId=@rOrgId) OR (@rOrgId=0))
			AND ((CR.BatchId=@rBatchId) OR (@rBatchId=0))
			AND (CRD.IsObsolete=0)
			AND ((SA.Code=@rStudentCode) OR (@rStudentCode=''))
			AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0)) 
			AND (OM.OrgGroupId = @rOrgGroupId or @rOrgGroupId=0)
			AND ((SA.StatusId=@rStatusId) OR (@rStatusId=0))
			And ((CR.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
			group by CR.Id,SA.FirstName,SA.LastName,CR.ReceiptNumber,CR.ReceiptDate,CCM.Title,CR.OrgId,CR.BatchId,RBM.Title,CM.ChargeCategoryId,CR.ChargeReceiptBookId,CR.SourceTypeId,OM.DisplayTitle
END
ELSE IF @rSourceTypeId=3
BEGIN
		SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
			CR.Id,
			'Other' as SourceType,
			CR.SourceTypeId,
			--EM.Code as SourceCode,
			CR.GuestName as GuestName,
			--CR.Remark,
			CR.ReceiptNumber,
			CR.ReceiptDate,
			--CR.PayTypeId,
			--CR.ChequeNo,
			--CR.BankName,
			--CR.IsObsolete,
			--CRD.Id as DetailId,
			--CRD.ChargeId,
			--CRD.Remark as DetailRemark,
			sum(CRD.Amount) as Amount,
			--CM.Code,
			--CM.Title,
			CCM.Title as ChargeCategory,
			CM.ChargeCategoryId,
			CR.OrgId,
			CR.BatchId,
			RBM.Title AS ReceiptBook,
			CR.ChargeReceiptBookId,
			OM.DisplayTitle AS OrganizationName
			--OM.DisplayTitle AS School,
			--OM.OrgGroupId,
			--CM.Id AS ChargeId
			--CRD.IsObsolete
  FROM 
           sFee.tChargeReceipt CR
       INNER JOIN sFee.tChargeReceiptDetail CRD ON CRD.ChargeReceiptId=CR.Id
       INNER JOIN sFee.tChargeMaster CM ON CM.Id=CRD.ChargeId
       INNER JOIN sFee.tChargeCategoryMaster CCM ON CCM.Id=CM.ChargeCategoryId
       INNER JOIN sFee.tChargeReceiptBookMaster RBM ON RBM.Id=CR.ChargeReceiptBookId
       INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=CR.OrgId
       --INNER JOIN sSetup.tOrgGroupBatchMaster OBM ON OBM.Id=CR.OrgGroupBatchId
       --INNER JOIN sSetup.tOrganizationMaster OM ON OM.OrgGroupId=OBM.OrgGroupId
       
  WHERE 
			--(CR.ReceiptNumber=@rReceiptNumber OR ISNULL(@rReceiptNumber,'')='')
			--AND 
				(ISNULL(CR.SourceTypeId,0)=0)
			AND	((CR.GuestName Like @rGuestName) OR (ISNULL(@rGuestName,'') = ''))
			--AND (ISNULL(@rSourceCode,'') = '')
			AND ((CR.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((CR.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND ((CR.ChargeReceiptBookId = @rReceiptBookId) OR (ISNULL(@rReceiptBookId,0) = 0))
			AND ((CM.ChargeCategoryId = @rChargeCategoryId) OR (ISNULL(@rChargeCategoryId,0) = 0))
			AND (CR.IsObsolete=0)
			AND ((CR.OrgId=@rOrgId) OR (@rOrgId=0))
			AND ((CR.BatchId=@rBatchId) OR (@rBatchId=0))
			AND (CRD.IsObsolete=0) 
			AND (OM.OrgGroupId = @rOrgGroupId or @rOrgGroupId=0)
			And ((CR.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
			group by CR.Id,CR.GuestName,CR.ReceiptNumber,CR.ReceiptDate,CCM.Title,CR.OrgId,CR.BatchId,RBM.Title,CR.ChargeReceiptBookId,CM.ChargeCategoryId,CR.SourceTypeId,OM.DisplayTitle
END	
ELSE
BEGIN
		SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			--CRD.Id as DetailId,
			CR.Id,
			'Employee' as SourceType,
			CR.SourceTypeId,
			--EM.Code as SourceCode,
			EM.FirstName+' '+EM.LastName as GuestName,
			--CR.Remark,
			CR.ReceiptNumber,
			CR.ReceiptDate,
			--CR.PayTypeId,
			--CR.ChequeNo,
			--CR.BankName,
			--CR.IsObsolete,
			--CRD.Id as DetailId,
			--CRD.ChargeId,
			--CRD.Remark as DetailRemark,
			sum(CRD.Amount) as Amount,
			--Amount=(select sum(Amount) from sFee.tChargeReceiptDetail group by ChargeReceiptId),
			--CM.Code,
			--CM.Title,
			CCM.Title as ChargeCategory,
			CM.ChargeCategoryId,
			CR.OrgId,
			CR.BatchId,
			RBM.Title AS ReceiptBook,
			CR.ChargeReceiptBookId,
			OM.DisplayTitle AS OrganizationName
			--OM.DisplayTitle AS School,
			--OM.OrgGroupId,
			--CM.Id AS ChargeId
			--CRD.IsObsolete
  FROM 
           sFee.tChargeReceipt CR
       INNER JOIN sFee.tChargeReceiptDetail CRD ON CRD.ChargeReceiptId=CR.Id
       INNER JOIN sHRM.tEmployeeMaster EM ON EM.Id=CR.SourceId AND (CR.SourceTypeId = 95) 
       --AND EM.StatusId=7
       INNER JOIN sFee.tChargeMaster CM ON CM.Id=CRD.ChargeId
       INNER JOIN sFee.tChargeCategoryMaster CCM ON CCM.Id=CM.ChargeCategoryId
       INNER JOIN sFee.tChargeReceiptBookMaster RBM ON RBM.Id=CR.ChargeReceiptBookId
       INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=CR.OrgId
       --INNER JOIN sSetup.tOrgGroupBatchMaster OBM ON OBM.Id=CR.OrgGroupBatchId
       --INNER JOIN sSetup.tOrganizationMaster OM ON OM.OrgGroupId=OBM.OrgGroupId
       
  WHERE 
			--(CR.ReceiptNumber=@rReceiptNumber OR ISNULL(@rReceiptNumber,'')='')
			--AND 
				((EM.FirstName+' '+EM.LastName Like @rGuestName) OR (ISNULL(@rGuestName,'') = ''))
			AND ((EM.Code Like @rSourceCode) OR (ISNULL(@rSourceCode,'') = ''))
			AND ((CR.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((CR.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND ((CR.ChargeReceiptBookId = @rReceiptBookId) OR (ISNULL(@rReceiptBookId,0) = 0))
			AND ((CM.ChargeCategoryId = @rChargeCategoryId) OR (ISNULL(@rChargeCategoryId,0) = 0))
			AND (CR.IsObsolete=0)
			AND ((CR.OrgId=@rOrgId) OR (@rOrgId=0))
			AND ((CR.BatchId=@rBatchId) OR (@rBatchId=0))
			AND (CRD.IsObsolete=0)
			AND (OM.OrgGroupId = @rOrgGroupId or @rOrgGroupId=0)
			And ((CR.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
			group by CR.Id,EM.FirstName,EM.LastName,CR.ReceiptNumber,CR.ReceiptDate,CCM.Title,CR.OrgId,CR.BatchId,RBM.Title,CM.ChargeCategoryId,CR.ChargeReceiptBookId,CR.SourceTypeId,OM.DisplayTitle
			
			UNION ALL
			
			SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			CR.Id,
			'Student' as SourceType,
			CR.SourceTypeId,
			--EM.Code as SourceCode,
			SA.FirstName+' '+SA.LastName as GuestName,
			--CR.Remark,
			CR.ReceiptNumber,
			CR.ReceiptDate,
			--CR.PayTypeId,
			--CR.ChequeNo,
			--CR.BankName,
			--CR.IsObsolete,
			--CRD.Id as DetailId,
			--CRD.ChargeId,
			--CRD.Remark as DetailRemark,
			sum(CRD.Amount) as Amount,
			--CM.Code,
			--CM.Title,
			CCM.Title as ChargeCategory,
			CM.ChargeCategoryId,
			CR.OrgId,
			CR.BatchId,
			RBM.Title AS ReceiptBook,
			CR.ChargeReceiptBookId,
			OM.DisplayTitle AS OrganizationName
			--OM.DisplayTitle AS School,
			--OM.OrgGroupId,
			--CM.Id AS ChargeId
			--CRD.IsObsolete
  FROM 
           sFee.tChargeReceipt CR
       INNER JOIN sFee.tChargeReceiptDetail CRD ON CRD.ChargeReceiptId=CR.Id
       INNER JOIN sFee.tChargeMaster CM ON CM.Id=CRD.ChargeId
       INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=CR.SourceId AND CR.SourceTypeId=2001 
       --AND SA.StatusId=1
       INNER JOIN sFee.tChargeCategoryMaster CCM ON CCM.Id=CM.ChargeCategoryId
       INNER JOIN sFee.tChargeReceiptBookMaster RBM ON RBM.Id=CR.ChargeReceiptBookId
       INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=CR.OrgId
       --INNER JOIN sSetup.tOrgGroupBatchMaster OBM ON OBM.Id=CR.OrgGroupBatchId
       --INNER JOIN sSetup.tOrganizationMaster OM ON OM.OrgGroupId=OBM.OrgGroupId
       
  WHERE 
			--(CR.ReceiptNumber=@rReceiptNumber OR ISNULL(@rReceiptNumber,'')='')
			--AND 
				((SA.FirstName+' '+SA.LastName Like @rGuestName) OR (ISNULL(@rGuestName,'') = ''))
			AND ((SA.Code Like @rSourceCode) OR (ISNULL(@rSourceCode,'') = ''))
			AND ((CR.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((CR.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND ((CR.ChargeReceiptBookId = @rReceiptBookId) OR (ISNULL(@rReceiptBookId,0) = 0))
			AND ((CM.ChargeCategoryId = @rChargeCategoryId) OR (ISNULL(@rChargeCategoryId,0) = 0))
			AND (CR.IsObsolete=0)
			AND ((CR.OrgId=@rOrgId) OR (@rOrgId=0))
			AND ((CR.BatchId=@rBatchId) OR (@rBatchId=0))
			AND (CRD.IsObsolete=0)
			AND ((SA.Code=@rStudentCode) OR (@rStudentCode=''))
			AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))  
			AND (OM.OrgGroupId = @rOrgGroupId or @rOrgGroupId=0)
			And ((CR.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
			group by CR.Id,SA.FirstName,SA.LastName,CR.ReceiptNumber,CR.ReceiptDate,CCM.Title,CR.OrgId,CR.BatchId,RBM.Title,CR.ChargeReceiptBookId,CM.ChargeCategoryId,CR.SourceTypeId,OM.DisplayTitle
			
			UNION ALL
			
			SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			CR.Id,
			'Other' as SourceType,
			CR.SourceTypeId,
			--EM.Code as SourceCode,
			CR.GuestName as GuestName,
			--CR.Remark,
			CR.ReceiptNumber,
			CR.ReceiptDate,
			--CR.PayTypeId,
			--CR.ChequeNo,
			--CR.BankName,
			--CR.IsObsolete,
			--CRD.Id as DetailId,
			--CRD.ChargeId,
			--CRD.Remark as DetailRemark,
			sum(CRD.Amount) as Amount,
			--CM.Code,
			--CM.Title,
			CCM.Title as ChargeCategory,
			CM.ChargeCategoryId,
			CR.OrgId,
			CR.BatchId,
			RBM.Title AS ReceiptBook,
			CR.ChargeReceiptBookId,
			OM.DisplayTitle AS OrganizationName
			--OM.DisplayTitle AS School,
			--OM.OrgGroupId,
			--CM.Id AS ChargeId
			--CRD.IsObsolete
  FROM 
           sFee.tChargeReceipt CR
       INNER JOIN sFee.tChargeReceiptDetail CRD ON CRD.ChargeReceiptId=CR.Id
       INNER JOIN sFee.tChargeMaster CM ON CM.Id=CRD.ChargeId
       INNER JOIN sFee.tChargeCategoryMaster CCM ON CCM.Id=CM.ChargeCategoryId
       INNER JOIN sFee.tChargeReceiptBookMaster RBM ON RBM.Id=CR.ChargeReceiptBookId
       INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=CR.OrgId
       --INNER JOIN sSetup.tOrgGroupBatchMaster OBM ON OBM.Id=CR.OrgGroupBatchId
       --INNER JOIN sSetup.tOrganizationMaster OM ON OM.OrgGroupId=OBM.OrgGroupId
       
  WHERE 
			--(CR.ReceiptNumber=@rReceiptNumber OR ISNULL(@rReceiptNumber,'')='')
			--AND 
			(ISNULL(CR.SourceTypeId,0)=3)
			AND	((CR.GuestName Like @rGuestName) OR (ISNULL(@rGuestName,'') = ''))
			--AND (ISNULL(@rSourceCode,'') = '')
			AND ((CR.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((CR.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND ((CR.ChargeReceiptBookId = @rReceiptBookId) OR (ISNULL(@rReceiptBookId,0) = 0))
			AND ((CM.ChargeCategoryId = @rChargeCategoryId) OR (ISNULL(@rChargeCategoryId,0) = 0))
			AND (CR.IsObsolete=0)
			AND ((CR.OrgId=@rOrgId) OR (@rOrgId=0))
			AND ((CR.BatchId=@rBatchId) OR (@rBatchId=0))
			AND (CRD.IsObsolete=0) 
			AND (OM.OrgGroupId = @rOrgGroupId or @rOrgGroupId=0)
			And ((CR.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
			group by CR.Id,CR.GuestName,CR.ReceiptNumber,CR.ReceiptDate,CCM.Title,CR.OrgId,CR.BatchId,RBM.Title,CR.ChargeReceiptBookId,CM.ChargeCategoryId,CR.SourceTypeId,OM.DisplayTitle
END
END
GO
PRINT N'Altering [sFee].[pDeleteFee]...';


GO
ALTER PROCEDURE [sFee].[pDeleteFee]
	 
		@rReceiptBookId int=0,	 
		@rClassId int=0,
		@rDivisionId int=0,	 
		@rBatchId int=0,	 
		@rOrgId int=0,
		@rOrgGroupBatchId int=0,
		@rStatusId int=0, 
	    @rCode nvarchar(20)='',
	    @rSourceId bigint,
	    @rDeleteType nvarchar(20)='',
	    @rSourceTypeId smallint=0,
	    @rFromReceiptNo int,
	    @rToReceiptNo int
	    
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 	

IF (@rDeleteType = 'Receipt')
BEGIN
DELETE sFee.tReceiptDetail 
		FROM sFee.tReceiptDetail RD
		INNER JOIN sFee.tReceipt R  
		ON R.Id=RD.ReceiptId
		INNER JOIN sStudent.vStudentAcademic vSA 
		ON vSA.AcademicId=R.SourceId
	WHERE 
		R.ReceiptBookId=@rReceiptBookId
		AND ((R.ReceiptNumber >= @rFromReceiptNo) OR (@rFromReceiptNo=0))
		AND ((R.ReceiptNumber <= @rToReceiptNo) OR (@rToReceiptNo=0))
		AND ((R.SourceId=@rSourceId) OR (@rSourceId=0))
		AND ((R.SourceTypeId=@rSourceTypeId) OR (@rSourceTypeId=0))
		AND ((vSA.ClassId=@rClassId) OR (@rClassId=0))
		AND ((vSA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND vSA.BatchId=@rBatchId
		AND ((vSA.OrgId=@rOrgId) OR (@rOrgId=0))

DELETE sFee.tReceipt 
		FROM sFee.tReceipt R
		INNER JOIN sStudent.vStudentAcademic vSA 
		ON vSA.AcademicId=R.SourceId
	WHERE 
		R.ReceiptBookId=@rReceiptBookId
		AND ((R.ReceiptNumber >= @rFromReceiptNo) OR (@rFromReceiptNo=0))
		AND ((R.ReceiptNumber <= @rToReceiptNo) OR (@rToReceiptNo=0))
		AND ((R.SourceId=@rSourceId) OR (@rSourceId=0))
		AND ((R.SourceTypeId=@rSourceTypeId) OR (@rSourceTypeId=0))
		AND ((vSA.ClassId=@rClassId) OR (@rClassId=0))
		AND ((vSA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND vSA.BatchId=@rBatchId
		AND ((vSA.OrgId=@rOrgId) OR (@rOrgId=0))
SELECT 1 AS Result
END

IF(@rDeleteType = 'FeeAllocation')
BEGIN

	IF EXISTS
	(
	SELECT 1 FROM 
	    sFee.tFeeAllocation FA
		INNER JOIN sFee.tFeeSetup FS 
		ON FS.Id=FA.FeeSetupId
		INNER JOIN sStudent.vStudentAcademic vSA 
		ON vSA.AcademicId=FA.SourceId
		INNER JOIN sFee.tReceipt R 
		ON FA.SourceId = R.SourceId AND FA.SourceTypeId = R.SourceTypeId
	WHERE 
		(R.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0)
		AND ((R.SourceId=@rSourceId) OR (@rSourceId=0))
		AND ((R.SourceTypeId=@rSourceTypeId) OR (@rSourceTypeId=0))
		AND ((vSA.ClassId=@rClassId) OR (@rClassId=0))
		AND ((vSA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND vSA.BatchId=@rBatchId
		AND ((vSA.OrgId=@rOrgId) OR (@rOrgId=0))
    )
    BEGIN
		SELECT -101 AS Result
		RETURN
	END 

    DELETE sFee.tFeeAllocation
		FROM sFee.tFeeAllocation FA
		INNER JOIN sFee.tFeeSetup FS 
		ON FS.Id=FA.FeeSetupId
		INNER JOIN sStudent.vStudentAcademic vSA 
		ON vSA.AcademicId=FA.SourceId
	WHERE 
		(FS.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0)
		AND ((FA.SourceId=@rSourceId) OR (@rSourceId=0))
		AND ((FA.SourceTypeId=@rSourceTypeId) OR (@rSourceTypeId=0))
		AND ((vSA.ClassId=@rClassId) OR (@rClassId=0))
		AND ((vSA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND vSA.BatchId=@rBatchId
		AND ((vSA.OrgId=@rOrgId) OR (@rOrgId=0))
SELECT 2 AS Result
END	
		
IF(@rDeleteType = 'FeeOptional')
BEGIN
	
	IF EXISTS
	( 
    SELECT 1 FROM
        sFee.tFeeOptional FO
		INNER JOIN sFee.tFeeSetup FS 
		ON FS.Id=FO.FeeSetupId
		INNER JOIN sStudent.vStudentAcademic vSA 
		ON vSA.AcademicId=FO.SourceId
		INNER JOIN sFee.tReceipt R 
		ON FO.SourceId = R.SourceId AND FO.SourceTypeId = R.SourceTypeId
	WHERE 
		(R.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0)
		AND ((R.SourceId=@rSourceId) OR (@rSourceId=0))
		AND ((R.SourceTypeId=@rSourceTypeId) OR (@rSourceTypeId=0))
		AND ((vSA.ClassId=@rClassId) OR (@rClassId=0))
		AND ((vSA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND vSA.BatchId=@rBatchId
		AND ((vSA.OrgId=@rOrgId) OR (@rOrgId=0))
    )
    BEGIN
		SELECT -102 AS Result
		RETURN
	END 

    DELETE sFee.tFeeOptional
		FROM sFee.tFeeOptional FO
		INNER JOIN sFee.tFeeSetup FS 
		ON FS.Id=FO.FeeSetupId
		INNER JOIN sStudent.vStudentAcademic vSA 
		ON vSA.AcademicId=FO.SourceId
	WHERE 
		(FS.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0)
		AND ((FO.SourceId=@rSourceId) OR (@rSourceId=0))
		AND ((FO.SourceTypeId=@rSourceTypeId) OR (@rSourceTypeId=0))
		AND ((vSA.ClassId=@rClassId) OR (@rClassId=0))
		AND ((vSA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND vSA.BatchId=@rBatchId
		AND ((vSA.OrgId=@rOrgId) OR (@rOrgId=0))		
SELECT 3 AS Result
END
END
GO
PRINT N'Altering [sFee].[pDepositPostingGet]...';


GO

ALTER PROCEDURE [sFee].[pDepositPostingGet]
				
		   --@rClassId int,
           --@rReceiptBookId int,
           @rDepositHead int,
		   --@rBatchId int,
		   @rOrgGroupId int,
		   --@rReceiptDate date,
		   --@rReceiptDateTo date,
		   @rDepositePosting nvarchar(50)
           
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 
	IF @rDepositePosting = 'Single'
	BEGIN
			SELECT  
					 
					AMast.Title AS AccountName,
					AYM.Title AS AccountingYearName,
					AM.CreditLedgerId AS CreditLedgerId,
					CLM.Title AS CreditLedgerName,
					AM.CreditLedgerId As DebitLedgerId,
					DLM.Title AS DebitLedgerName ,
					 
					--'' AS ChequeNo,'' AS ChequeDate,'' AS BankName,
					AM.PayTypeId AS PayTypeId,
					ISNULL(AYM.ISLocked,0) AS ISLocked			 
			FROM 
					sFee.tDepositeAccountMapping AM
					--INNER JOIN sFee.tChargeReceiptDetail RD ON RD.ChargeId = AM.ChargeId  
					--INNER JOIN sFee.tChargeReceipt R ON R.Id = RD.ChargeReceiptId 
					--	AND R.PayTypeId = AM.PayTypeId
					--	AND R.ReceiptDate >= @rReceiptDate 
					--	AND R.ReceiptDate <= @rReceiptDateTo AND R.IsObsolete = 0
					 
					INNER JOIN  sFee.tDepositHeadMaster HM ON HM.Id=AM.DepositeHeadId AND AM.DepositeHeadId=@rDepositHead		
					INNER JOIN sAccounting.tAccountingYearMaster AYM ON AYM.Id=AM.AccountingYearId
					INNER JOIN sAccounting.tAccountMaster AMast ON AMast.Id=AYM.AccountId
					INNER JOIN sAccounting.tLedgerMaster CLM ON (CLM.Id=AM.CreditLedgerId)  AND CLM.AccountingYearId = AM.AccountingYearId
					INNER JOIN sAccounting.tLedgerMaster DLM ON (DLM.Id=AM.DebitLedgerId) AND DLM.AccountingYearId = AM.AccountingYearId
				WHERE 
					AMast.OrgGroupId=@rOrgGroupId	 
					GROUP BY  AM.CreditLedgerId,	AM.DebitLedgerId,AMast.Title,AYM.Title,CLM.Title,DLM.Title,PayTypeId,AYM.ISLocked
	 END
	 ELSE
		BEGIN		
		SELECT  
			 
			AMast.Title AS AccountName,
			AYM.Title AS AccountingYearName,
			AM.CreditLedgerId,
			CLM.Title AS CreditLedgerName,
			AM.DebitLedgerId,
			DLM.Title AS DebitLedgerName ,
			--SUM(RD.Amount) AS ReceiptAmount,
			--'' AS ChequeNo,'' AS ChequeDate,'' AS BankName,
			AM.PayTypeId AS PayTypeId,	
			ISNULL(AYM.ISLocked,0) AS ISLocked		
		FROM 
			sFee.tDepositeAccountMapping AM
			--INNER JOIN sFee.tChargeReceiptDetail RD ON RD.ChargeId = AM.DepositeHeadId  
			--INNER JOIN sFee.tChargeReceipt R ON R.Id = RD.ChargeReceiptId 
			--	AND R.PayTypeId = AM.PayTypeId
			--	AND R.ReceiptDate >= @rReceiptDate 
			--	AND R.ReceiptDate <= @rReceiptDateTo AND R.IsObsolete = 0
			
			--INNER JOIN sFee.tFeeSetup FS ON FS.Id=AM.ChargeId 
			--AND (FS.ClassId=@rClassId) 
			--	AND (FS.ReceiptBookId=@rReceiptBookId) 
				--AND (R.OrgGroupBatchId=@rBatchId)
			INNER JOIN  sFee.tDepositHeadMaster HM ON HM.Id=AM.DepositeHeadId   AND AM.DepositeHeadId=@rDepositHead		
            INNER JOIN sAccounting.tAccountingYearMaster AYM ON AYM.Id=AM.AccountingYearId
            INNER JOIN sAccounting.tAccountMaster AMast ON AMast.Id=AYM.AccountId
            INNER JOIN sAccounting.tLedgerMaster CLM ON (CLM.Id=AM.CreditLedgerId)  AND CLM.AccountingYearId = AM.AccountingYearId
            INNER JOIN sAccounting.tLedgerMaster DLM ON (DLM.Id=AM.DebitLedgerId) AND DLM.AccountingYearId = AM.AccountingYearId
		WHERE 
			AMast.OrgGroupId=@rOrgGroupId   
			GROUP BY AM.CreditLedgerId,	AM.DebitLedgerId,AMast.Title,AYM.Title,CLM.Title,DLM.Title ,PayTypeId,AYM.ISLocked
			
		UNION ALL
		
		SELECT  
			 
			AMast.Title AS AccountName,
			AYM.Title AS AccountingYearName,
			AM.CreditLedgerId,
			CLM.Title AS CreditLedgerName,
			AM.DebitLedgerId,
			DLM.Title AS DebitLedgerName ,
			 
			--R.ChequeNo,R.ChequeDate,R.BankName,
			AM.PayTypeId AS PayTypeId,
			ISNULL(AYM.ISLocked,0) AS ISLocked	
			
						
		FROM 
			sFee.tDepositeAccountMapping AM
			--INNER JOIN sFee.tChargeReceiptDetail RD ON RD.ChargeId = AM.ChargeId  
			--INNER JOIN sFee.tChargeReceipt R ON R.Id = RD.ChargeId 
			--	AND R.PayTypeId = AM.PayTypeId
			--	AND R.ReceiptDate >= @rReceiptDate  
			--	AND R.ReceiptDate <= @rReceiptDateTo AND R.IsObsolete = 0
			 INNER JOIN  sFee.tDepositHeadMaster HM ON HM.Id=AM.DepositeHeadId AND AM.DepositeHeadId=@rDepositHead		
            INNER JOIN sAccounting.tAccountingYearMaster AYM ON AYM.Id=AM.AccountingYearId
            INNER JOIN sAccounting.tAccountMaster AMast ON AMast.Id=AYM.AccountId
            INNER JOIN sAccounting.tLedgerMaster CLM ON (CLM.Id=AM.CreditLedgerId)  AND CLM.AccountingYearId = AM.AccountingYearId
            INNER JOIN sAccounting.tLedgerMaster DLM ON (DLM.Id=AM.DebitLedgerId) AND DLM.AccountingYearId = AM.AccountingYearId
		WHERE    AMast.OrgGroupId=@rOrgGroupId 
		END
END
GO
PRINT N'Altering [sFee].[pFeePostingAdd]...';


GO
ALTER PROCEDURE [sFee].[pFeePostingAdd]
	 
	        @rAccount nvarchar(100),
	        @rAccountingYear nvarchar(100),
	        @rOrgGroupId int,
            @rTransactionDate date,
            @rNarration nvarchar(150),  
            @rVoucherTypeId tinyint,
            @rIsProfitAndLoss int,
            @rRepeatLedger int,
            @rCreatedUserId bigint,
            @rCreditLedgerId int,
            @rDebitLedgerId int,
            @rReceiptBookId int,
            @rChequeNo nvarchar(10),
			@rBankName nvarchar(50),
			@rChequeDate datetime,
			@rChequeClearDate datetime=NULL,
			@rPayTypeId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	BEGIN TRANSACTION
		
		
	DECLARE @lNextNumber BIGINT
	DECLARE @lNextNumberPosting INT
	DECLARE @1AccountId int 
	DECLARE @1AccountYearId int 
	DECLARE @lVoucherNumber bigint
	
    SELECT @1AccountId = AYM.AccountId, @1AccountYearId = AYM.Id FROM sAccounting.tAccountingYearMaster AYM 
    INNER JOIN sAccounting.tAccountMaster AM ON AM.Id = AYM.AccountId 
    WHERE AM.Title= sSetup.fPortalXMLTagsReplaceReverse(@rAccount) AND AYM.Title = @rAccountingYear
    
    SELECT @lVoucherNumber = ISNULL(Max(T.VoucherNumber),0) + 1 FROM sAccounting.tTransaction T
	WHERE VoucherTypeId=@rVoucherTypeId AND AccountingYearId = @1AccountYearId
    
    IF NOT EXISTS (SELECT 1 FROM sFee.taccountposting WHERE AccountYearId=@1AccountYearId AND AccountId=@1AccountId 
    AND TransactionDate=@rTransactionDate AND VoucherTypeId=@rVoucherTypeId AND CreditLedger=@rCreditLedgerId 
    AND DebitLedger = @rDebitLedgerId AND ReceiptBookId=@rReceiptBookId And ChequeNo=@rChequeNo AND BankName=@rBankName AND ChequeDate=@rChequeDate)
    BEGIN
		SELECT @lNextNumberPosting = ISNULL(MAX(Id),0) + 1 FROM sFee.tAccountPosting
		INSERT INTO [sFee].[tAccountPosting]
		(
			Id,
			AccountId,
			AccountYearId,
			TransactionDate,
			VoucherTypeId,
			CreditLedger,
			DebitLedger,
			ReceiptBookId,
			ChequeNo,
			BankName,
			ChequeDate
		)
		VALUES
		(
			@lNextNumberPosting,
			@1AccountId,
			@1AccountYearId,
			@rTransactionDate,
			@rVoucherTypeId,
			@rCreditLedgerId,
			@rDebitLedgerId,
			@rReceiptBookId,
			@rChequeNo,
			@rBankName,
			@rChequeDate
		)
    END
	
	SELECT @lNextNumberPosting = Id FROM sFee.taccountposting WHERE AccountYearId=@1AccountYearId AND AccountId=@1AccountId 
    AND TransactionDate=@rTransactionDate AND VoucherTypeId=@rVoucherTypeId AND CreditLedger=@rCreditLedgerId
    AND DebitLedger = @rDebitLedgerId AND ReceiptBookId=@rReceiptBookId
  
	IF EXISTS (SELECT 1 FROM [sAccounting].[tTransaction] WHERE SOURCEID=@lNextNumberPosting)
	BEGIN
		SELECT 101 AS Result
		COMMIT TRANSACTION				
		RETURN 
	END
    
    EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sAccounting.tTransaction', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO [sAccounting].[tTransaction]
			   (
			    [Id],
			    [OrgGroupId],
			    [AccountingYearId],
			    [TransactionDate],
			    [Narration],
			    [VoucherNumber],
			    [VoucherTypeId],
			    [IsProfitAndLoss],
			    [RepeatLedger],
			    [CreatedUserId],
			    [CreatedDateTime],
			    [AccountId],
			    [SourceTypeId],
			    [SourceId],
			    [ChequeNo],
			    [BankName],
			    [ChequeDate],
			    [ChequeClearDate],
			    [PayTypeId]
			   )
		 VALUES
			   (
				@lNextNumber,
			    @rOrgGroupId,
			    @1AccountYearId,
			    @rTransactionDate,
			    @rNarration,
			    @lVoucherNumber,
			    @rVoucherTypeId,
			    @rIsProfitAndLoss,
			    @rRepeatLedger,
			    @rCreatedUserId,
			    sCommon.fGetDate(),
			    @1AccountId,
			    1,
			    @lNextNumberPosting,
			    @rChequeNo,
			    @rBankName,
			    @rChequeDate,
			    @rChequeClearDate,
			    @rPayTypeId
			   )
		    SELECT @lNextNumber AS Result
	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sFee].[pFeePostingGet]...';


GO

ALTER PROCEDURE [sFee].[pFeePostingGet]
				
		   --@rClassId int,
           @rReceiptBookId int,
		   @rBatchId int,
		   @rOrgGroupId int,
		   @rReceiptDate date,
		   @rReceiptDateTo date,
		   @rChequePosting nvarchar(50)
           
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 
	IF @rChequePosting = 'Single'
	BEGIN
			SELECT  
					R.ReceiptDate,
					AMast.Title AS AccountName,
					AYM.Title AS AccountingYearName,
					AM.CreditLedgerId,
					CLM.Title AS CreditLedgerName,
					AM.DebitLedgerId,
					DLM.Title AS DebitLedgerName,
					SUM(RD.Amount) AS ReceiptAmount,
					'' AS ChequeNo,'' AS ChequeDate,'' AS BankName,'' AS ChequeClearDate,0 AS PayTypeId	, 
					ISNULL(AYM.ISLocked,0) AS ISLocked					
			FROM 
					sFee.tAccountMapping AM
					INNER JOIN sFee.tReceiptDetail RD ON RD.FeeSetupId = AM.FeeSetupId  
					INNER JOIN sFee.tReceipt R ON R.Id = RD.ReceiptId 
						AND R.PayTypeId = AM.PayTypeId
						AND R.ReceiptDate >= @rReceiptDate 
						AND R.ReceiptDate <= @rReceiptDateTo AND R.IsObsolete = 0
					INNER JOIN sFee.tFeeSetup FS ON FS.Id=AM.FeeSetupId 
					--AND (FS.ClassId=@rClassId) 
						AND (FS.ReceiptBookId=@rReceiptBookId) 
						AND (R.OrgGroupBatchId=@rBatchId)
					INNER JOIN sAccounting.tAccountingYearMaster AYM ON AYM.Id=AM.AccountingYearId
					INNER JOIN sAccounting.tAccountMaster AMast ON AMast.Id=AYM.AccountId
					INNER JOIN sAccounting.tLedgerMaster CLM ON (CLM.Id=AM.CreditLedgerId)  AND CLM.AccountingYearId = AM.AccountingYearId
					INNER JOIN sAccounting.tLedgerMaster DLM ON (DLM.Id=AM.DebitLedgerId) AND DLM.AccountingYearId = AM.AccountingYearId
				WHERE 
					AMast.OrgGroupId=@rOrgGroupId			
					GROUP BY R.ReceiptDate,AM.CreditLedgerId,	AM.DebitLedgerId,AMast.Title,AYM.Title,CLM.Title,DLM.Title,AYM.IsLocked
	 END
	 ELSE
		BEGIN		
		SELECT  
			R.ReceiptDate,
			AMast.Title AS AccountName,
			AYM.Title AS AccountingYearName,
			AM.CreditLedgerId,
			CLM.Title AS CreditLedgerName,
			AM.DebitLedgerId,
			DLM.Title AS DebitLedgerName,
			SUM(RD.Amount) AS ReceiptAmount,
			'' AS ChequeNo,'' AS ChequeDate,'' AS BankName,'' AS ChequeClearDate,0 AS PayTypeId	,
			ISNULL(AYM.ISLocked,0) AS ISLocked					
		FROM 
			sFee.tAccountMapping AM
			INNER JOIN sFee.tReceiptDetail RD ON RD.FeeSetupId = AM.FeeSetupId  
			INNER JOIN sFee.tReceipt R ON R.Id = RD.ReceiptId 
				AND R.PayTypeId = AM.PayTypeId
				AND R.ReceiptDate >= @rReceiptDate 
				AND R.ReceiptDate <= @rReceiptDateTo AND R.IsObsolete = 0
			INNER JOIN sFee.tFeeSetup FS ON FS.Id=AM.FeeSetupId 
			--AND (FS.ClassId=@rClassId) 
				AND (FS.ReceiptBookId=@rReceiptBookId) 
				AND (R.OrgGroupBatchId=@rBatchId)
            INNER JOIN sAccounting.tAccountingYearMaster AYM ON AYM.Id=AM.AccountingYearId
            INNER JOIN sAccounting.tAccountMaster AMast ON AMast.Id=AYM.AccountId
            INNER JOIN sAccounting.tLedgerMaster CLM ON (CLM.Id=AM.CreditLedgerId)  AND CLM.AccountingYearId = AM.AccountingYearId
            INNER JOIN sAccounting.tLedgerMaster DLM ON (DLM.Id=AM.DebitLedgerId) AND DLM.AccountingYearId = AM.AccountingYearId
		WHERE 
			AMast.OrgGroupId=@rOrgGroupId AND R.PayTypeId = 1
			GROUP BY R.ReceiptDate,AM.CreditLedgerId,	AM.DebitLedgerId,AMast.Title,AYM.Title,CLM.Title,DLM.Title,AYM.IsLocked
			
		UNION ALL
		
		SELECT  
			R.ReceiptDate,
			AMast.Title AS AccountName,
			AYM.Title AS AccountingYearName,
			AM.CreditLedgerId,
			CLM.Title AS CreditLedgerName,
			AM.DebitLedgerId,
			DLM.Title AS DebitLedgerName,
			Sum(RD.Amount) AS ReceiptAmount,
			R.ChequeNo,R.ChequeDate,R.BankName,R.ChequeClearDate,2 AS PayTypeId,
			ISNULL(AYM.ISLocked,0) AS ISLocked			
						
		FROM 
			sFee.tAccountMapping AM
			INNER JOIN sFee.tReceiptDetail RD ON RD.FeeSetupId = AM.FeeSetupId  
			INNER JOIN sFee.tReceipt R ON R.Id = RD.ReceiptId 
				AND R.PayTypeId = AM.PayTypeId
				AND R.ReceiptDate >= @rReceiptDate 
				AND R.ReceiptDate <= @rReceiptDateTo AND R.IsObsolete = 0
			INNER JOIN sFee.tFeeSetup FS ON FS.Id=AM.FeeSetupId 
				AND (FS.ReceiptBookId=@rReceiptBookId) 
				AND (R.OrgGroupBatchId=@rBatchId)
            INNER JOIN sAccounting.tAccountingYearMaster AYM ON AYM.Id=AM.AccountingYearId
            INNER JOIN sAccounting.tAccountMaster AMast ON AMast.Id=AYM.AccountId
            INNER JOIN sAccounting.tLedgerMaster CLM ON (CLM.Id=AM.CreditLedgerId)  AND CLM.AccountingYearId = AM.AccountingYearId
            INNER JOIN sAccounting.tLedgerMaster DLM ON (DLM.Id=AM.DebitLedgerId) AND DLM.AccountingYearId = AM.AccountingYearId
		WHERE  R.PayTypeId <> 1 AND	 AMast.OrgGroupId=@rOrgGroupId			
		Group By R.ReceiptDate,AMast.Title,AYM.Title,AM.CreditLedgerId,
			CLM.Title,AM.DebitLedgerId,DLM.Title,
			R.ChequeNo,R.ChequeDate,R.BankName,R.ChequeClearDate,AYM.IsLocked
		END
END
GO
PRINT N'Altering [sFee].[pRptFeePendingAllBatchGet]...';


GO
 
ALTER PROCEDURE [sFee].[pRptFeePendingAllBatchGet]
		@rReportId int=0,
		@rReceiptBookId int=0,
		@rAdmissionCategoryId int=0,
		@rClassId int=0,
		@rDivisionId int=0,
		@rUptoDate date='',
		@rBatchId int='',
		@rUserId bigint=0,
		@rBuilder1 nvarchar(max)='',	
		@rBuilder2 nvarchar(max)='',
		@rIsDetail bit=0,
		@rOrgId int=0,
		@rOrgGroupBatchId int=0,
		@rStatusId int=0,
		@rCommonBatch nvarchar(100)='',
		@rDepartmentId int=0,
		@rFromRollNo int=0,
	    @rToRollNo int=0,
	    @rCode nvarchar(20)='',
	    @rIsFilter bit=0,
		@rIsHeader bit=0,		
		@rCreatedUserName nvarchar(20) = '',
		@rFeeHeadId nvarchar(max) = '',
		@rIsDisplayOrgGroup bit=0,
		@rFeeId nvarchar(max) = '',
		@rFilterId  int=0
	    
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 	
	
	DECLARE @p as TempPendingFee
	
	INSERT INTO  @p 
	 
	SELECT 
		--@rBuilder1 AS Builder1,
		--@rBuilder2 AS Builder2,
		--@rIsDetail AS IsDetail,
		--@rIsFilter As IsFilter,
		--@rIsHeader As IsHeader,
		SA.AcademicId,
		SA.RollNo,
		SA.Name,
		SA.Code,
		SA.ClassId,
		SA.DivisionId,
		SA.ClassName,
		SA.DivisionName,
		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.ReceiptBookId,
		FS.FeeName,
		FS.FeeCode,
		SA.OrgId,
		O.Title AS OrgName,
		O.OrderIndex AS OrgOrderIndex,
		ISNULL(RBM.Title,'') AS ReceiptBookTitle,
		ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
		SA.BatchId,
		BM.Title AS BatchName
			
  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,
				FM.Code AS FeeCode
			FROM sFee.tFeeSetup FS1
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
				AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId				
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			WHERE 
			    ((SA1.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				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 ((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='')
				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				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.Code AS FeeCode
			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))
		WHERE
		        ((SA1.OrgGroupBatchId = @rOrgGroupBatchId)  OR (@rOrgGroupBatchId=0))
				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='')
				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
		) 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=@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 ((SA1.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				GROUP BY FeeSetupId,R.SourceId
				
				
		
		) 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
		 INNER JOIN sSetup.tBatchMaster BM 
			ON BM.Id=SA.BatchId	
      LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0) AND (SA.OrgGroupBatchId = AR.OrgGroupBatchId)) 
        LEFT JOIN
	(SELECT AT.SourceId ,B.OrgGroupBatchId FROM sTransport.tAssignRoute AT 
    INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
    INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
    ON RT.SourceId = SA.StudentId 
    AND ((SA.OrgGroupBatchId = RT.OrgGroupBatchId))
    AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
	WHERE	
			((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
			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)			
		   AND (
				 (@rFilterId = 0) -- All
				 OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel
				 OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport
				 OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))
			    )
			Order by SA.RollNo
 
			SELECT
			@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
			OrgId,			 
			ReceiptBookId,
			AcademicId,
			DivisionId,
			ClassDivision,
			RollNo, 
			Name,
			Code,
			ReceiptBookTitle,
			OrgName,
			SUM(PendingAmount) AS PendingAmount, 
			[sFee].[fPendingFeeNamesGet](AcademicId,ReceiptBookId,	@p) AS PendingFeeName,
			ReceiptOrderIndex,
			BatchId,
			BatchName
			
			FROM @p 
			
			GROUP By 
			OrgId,AcademicId,ReceiptBookId,DivisionId,BatchId,
			ClassDivision,RollNo, Name,Code,ReceiptBookTitle,OrgName,ReceiptOrderIndex,BatchName
			ORDER BY AcademicId
END
GO
PRINT N'Altering [sFee].[pRptFeeReceiptListGet]...';


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

	SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		@rIsDetail AS IsDetail,
		@rIsCancel AS IsCancel,
		@rIsFilter As IsFilter,
		@rIsHeader As IsHeader,
		@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
		R.Id AS ReceiptId,
		R.ReceiptNumber,
		SA.ClassId,
		--SA.ClassName,
		SA.DivisionId,
		--SA.DivisionName,
		SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
		SA.RollNo,
		SA.Code,
		SA.Name,
		ISNULL(PTM.Title,'') AS PayType,
		ISNULL(R.ChequeNo,'') AS ChequeNo,
		ISNULL(R.BankName,'') AS BankName,
		R.ReceiptAmount,
		R.ReceiptDate,
		R.CreatedUserId,
		ISNULL(U.LoginTitle,'') AS UserName,
		ISNULL(RBM.Title,'') AS ReceiptBookTitle,
		ISNULL(RBM.BankName,'') AS ReceiptBookBank,
		ISNULL(RBM.BankAccountNumber,'') AS BankAccountNumber,
		ISNULL(R.ReceiptBookId,'0') As ReceiptBookId,
		ISNULL((CASE @rReportId WHEN 20461 THEN [sFee].[fReceiptFeeDetailGet](R.Id)
		 ELSE '' END),'') AS FeeDetail,
		 R.Remark,
		 R.DiscountAmount,
		 ISNULL(RBM.OrderIndex,0) AS ReceiptBookOrderIndex,
		 SA.OrgId,
		 SA.OrganizationName
		 
			
  FROM 
			sFee.tReceipt R
		--INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
		--INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
		--INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
	 
		INNER JOIN sStudent.vStudentAcademic SA
			ON SA.AcademicId=R.SourceId AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))
		INNER JOIN sFinanceCommon.tPayTypeMaster PTM
			ON PTM.Id=R.PayTypeId
		LEFT JOIN sSecurity.tUser U
			ON U.Id=R.CreatedUserId
		INNER JOIN sFee.tReceiptBookMaster RBM 
			ON RBM.Id=R.ReceiptBookId
	LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0) AND (SA.OrgGroupBatchId = AR.OrgGroupBatchId)) 
    LEFT JOIN
	(SELECT AT.SourceId,B.OrgGroupBatchId FROM sTransport.tAssignRoute AT 
    INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
    INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
    ON RT.SourceId = SA.StudentId 
    AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  
    AND (SA.OrgGroupBatchId = RT.OrgGroupBatchId)
WHERE 
	R.SourceTypeId = 2001
	AND	((SA.AdmissionCategoryId = @rAdmissionCategoryId) OR (@rAdmissionCategoryId = 0))
	AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
	AND ((SA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))
	AND ((R.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId = 0))
	AND ((R.ReceiptNumber >= @rFromReceiptNo) OR (@rFromReceiptNo = 0))
	AND ((R.ReceiptNumber <= @rToReceiptNo) OR (@rToReceiptNo = 0))
	AND ((R.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
	AND ((R.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
	AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))
	AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
	AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
	AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
	AND (R.IsObsolete = @rIsCancel) 
	AND (SA.StatusId=@rStatusId OR @rStatusId=0)
	AND (R.PayTypeId = @rPaytypeId OR @rPaytypeId=0)
	AND ((SA.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
	AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
	AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
	AND ((SA.Code=@rCode) OR (@rCode=''))
	AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
	AND ((ISNULL(U.DisplayTitle,'') like @rCreatedUserName) OR (ISNULL(@rCreatedUserName,'')=''))
	AND ((@rIsDiscount =1 AND R.DiscountAmount!=0) OR (@rIsDiscount=0))
	--AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
	 AND (
	 (@rFilterId = 0) -- All
     OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel
     OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport
     OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))
   )
	ORDER BY R.ReceiptNumber
--	UNION ALL
	
--	SELECT 
--		R.Id AS ReceiptId,
--		0 AS ClassId,
--		--SA.ClassName,
--		0 AS DivisionId,
--		--SA.DivisionName,
--		EM.DepartmentId,
--		EM.DepartmentName AS ClassDept,
--		0 AS RollNo,
--		EM.Code,
--		EM.EmployeeName,
--		PTM.Title AS PayType,
--		R.ReceiptAmount
			
--  FROM 
--			sFee.tReceipt R
--		INNER JOIN sCommon.tSourceTypeMaster STM
--			ON STM.Id=R.SourceTypeId AND R.SourceTypeId = 95
--		INNER JOIN sHrm.vExtEmployeeMaster EM
--			ON EM.EmployeeId=R.SourceId
--		INNER JOIN sFinanceCommon.tPayTypeMaster PTM
--			ON PTM.Id=R.PayTypeId
			
--WHERE 
--		((EM.DepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))
--	AND ((R.ReceiptNumber >= @rFromReceiptNo) OR (@rFromReceiptNo = 0))
--	AND ((R.ReceiptNumber <= @rToReceiptNo) OR (@rToReceiptNo = 0))
--	AND ((R.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
--	AND ((R.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
--	AND (R.BatchId = @rBatchId)
END
GO
PRINT N'Altering [sFee].[pRptTransportFeePendingWithFeeNameGet]...';


GO


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


--CREATE TABLE #TempStudent
--	(
--	AcademicId bigint,
--	ClassId int,
--	BatchId int,
--	a
--	)
--	SELECT AcademicId

 
	--CREATE TYPE  TempPendingFee AS TABLE
	--(
	--AcademicId bigint
	--,
	--RollNo int,
	--Name nvarchar(200),
	--Code nvarchar(20),
	--ClassId int,
	--DivisionId int,
	--ClassName nvarchar(100),
	--DivisionName nvarchar(100),
	--ClassDivision nvarchar(100),
	--FeeSetupId int,
	--IsVariable int,
	--Amount Decimal(12,2),
	--StartDate date,
	--EndDate date,
	--FAAmount Decimal(12,2),
	--DiscountAmount Decimal(12,2),
	--AdditionalAmount Decimal(12,2),
	--PaidAmount Decimal(12,2),
	--PendingAmount Decimal(12,2),
	--Remark nvarchar(200),
	--ReceiptBookId int,
	--FeeName nvarchar(100),
	--FeeCode nvarchar(100),
	--OrgId int,
	--OrgName nvarchar(200),
	--OrgOrderIndex int,
	--ReceiptBookTitle nvarchar(200),
	--ReceiptOrderIndex int 
	--)
	 
	DECLARE @p as TempPendingFee
	
	INSERT INTO  @p 
	 
	SELECT 
		--@rBuilder1 AS Builder1,
		--@rBuilder2 AS Builder2,
		--@rIsDetail AS IsDetail,
		--@rIsFilter As IsFilter,
		--@rIsHeader As IsHeader,
		SA.AcademicId
		,
		SA.RollNo,
		SA.Name,
		SA.Code,
		SA.ClassId,
		SA.DivisionId,
		SA.ClassName,
		SA.DivisionName,
		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.ReceiptBookId,
		FS.FeeName,
		FS.FeeCode,
		SA.OrgId,
		O.Title AS OrgName,
		O.OrderIndex AS OrgOrderIndex,
		ISNULL(RBM.Title,'') AS ReceiptBookTitle,
		ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
		0 AS BatchId,
		'' AS BatchName 
		
			
  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,
				FM.Code AS FeeCode,
				SA1.StudentId AS StudentId
				
			FROM sFee.tFeeSetup FS1
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
				AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			INNER JOIN sFee.tFeeHeadMaster FH ON FH.Id = FM.FeeHeadId AND FH.Number = 1001
			--INNER JOIN sTransport.tAssignRoute AR oN SA1.AcademicId = AR.SourceId AND AR.SourceTypeId = 2003
			INNER JOIN sTransport.tAssignRoute AR oN SA1.StudentId = AR.SourceId AND AR.SourceTypeId = 2003
			INNER JOIN sTransport.tBusRouteDestinationMaster BRDM ON BRDM.Id = AR.PickupDestinationId
			INNER JOIN sTransport.tBusRouteMaster BRM ON BRDM.BusRouteId = BRM.Id
			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=0)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((BRDM.BusRouteId=@rRouteId) OR (@rRouteId=0))
				AND ((BRDM.Id=@rDestinationId) OR (@rDestinationId=0))
				AND ((BRM.TransportId=@rTransportId) OR (@rTransportId=0))
				AND (BRM.OrgGroupBatchId = @rOrgGroupBatchId)
				
				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.Code AS FeeCode,
				SA1.StudentId AS StudentId
			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 sFee.tFeeHeadMaster FH ON FH.Id = FM.FeeHeadId AND FH.Number = 1001
		--INNER JOIN sTransport.tAssignRoute AR oN SA1.AcademicId = AR.SourceId AND AR.SourceTypeId = 2003
		INNER JOIN sTransport.tAssignRoute AR oN SA1.StudentId = AR.SourceId AND AR.SourceTypeId = 2003
		INNER JOIN sTransport.tBusRouteDestinationMaster BRDM ON BRDM.Id = AR.PickupDestinationId
		INNER JOIN sTransport.tBusRouteMaster BRM ON BRDM.BusRouteId = BRM.Id
		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 ((BRDM.BusRouteId=@rRouteId) OR (@rRouteId=0))
				AND ((BRDM.Id=@rDestinationId) OR (@rDestinationId=0))
				AND ((BRM.TransportId=@rTransportId) OR (@rTransportId=0))
				AND (BRM.OrgGroupBatchId = @rOrgGroupBatchId)
				
		) 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 FS.Id = RD.FeeSetupId 
				INNER JOIN sfEe.tFeeMaster FM ON FM.Id = FS.FeeId 
				INNER JOIN sFee.tFeeHeadMaster FH ON FM.FeeHeadId = FH.Id AND FH.Number = 1001
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId				
				AND (SA1.ClassId=@rClassId OR @rClassId=0) AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))
				AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
				--INNER JOIN sTransport.tAssignRoute AR oN SA1.AcademicId = AR.SourceId AND AR.SourceTypeId = 2003
				INNER JOIN sTransport.tAssignRoute AR oN SA1.StudentId = AR.SourceId AND AR.SourceTypeId = 2003
				INNER JOIN sTransport.tBusRouteDestinationMaster BRDM ON BRDM.Id = AR.PickupDestinationId
				INNER JOIN sTransport.tBusRouteMaster BRM ON BRDM.BusRouteId = BRM.Id
				
			WHERE		
				(R.SourceTypeId = 2001)
				AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND (R.IsObsolete = 0) 
				AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId)  )
				AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((BRDM.BusRouteId=@rRouteId) OR (@rRouteId=0))
				AND ((BRDM.Id=@rDestinationId) OR (@rDestinationId=0))
				AND ((BRM.TransportId=@rTransportId) OR (@rTransportId=0))
				AND (BRM.OrgGroupBatchId = @rOrgGroupBatchId)
				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
		INNER JOIN sTransport.tAssignRoute AR 
			ON  SA.StudentId = AR.SourceId AND AR.SourceTypeId = 2003	
		INNER JOIN sTransport.tBusRouteDestinationMaster BRDM 
			ON BRDM.Id = AR.PickupDestinationId
	 INNER JOIN sTransport.tBusRouteMaster BRM ON BRDM.BusRouteId = BRM.Id
		
	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)			
			AND ((BRDM.BusRouteId=@rRouteId) OR (@rRouteId=0))
			AND ((BRDM.Id=@rDestinationId) OR (@rDestinationId=0))
			AND (BRM.OrgGroupBatchId = @rOrgGroupBatchId)
			Order by SA.RollNo

			SELECT
			P.OrgId,			 
			P.ReceiptBookId,
			P.AcademicId,
			P.DivisionId,
			P.ClassDivision,P.RollNo, P.Name,P.Code,ReceiptBookTitle,OrgName,
			SUM(P.PendingAmount) AS PendingAmount, 
			[sFee].[fPendingFeeNamesGet](P.AcademicId,ReceiptBookId,	@p) AS PendingFeeName,
			P.ReceiptOrderIndex,
			BR.Id AS BusRouteId,
			BR.Title AS BusRoute,
			BD.Title AS BusDestination
			
			FROM @p P INNER JOIN sStudent.vStudentAcademic VA ON p.AcademicId=VA.AcademicId
			INNER JOIN sTransport.tAssignRoute AR oN VA.StudentId = AR.SourceId AND SourceTypeId = 2003
			INNER JOIN sTransport.tBusRouteDestinationMaster BD ON BD.Id = AR.PickupDestinationId 
			INNER JOIN sTransport.tBusRouteMaster BR ON BR.Id = BD.BusRouteId 
			AND BR.OrgGroupBatchId = @rOrgGroupBatchId
			GROUP By P.ReceiptBookId,P.OrgId,P.AcademicId,P.DivisionId,
			P.ClassDivision,P.RollNo, P.Name,P.Code,
			P.ReceiptBookTitle,P.OrgName,P.ReceiptOrderIndex,BR.Title,BD.Title,BR.Id	
			ORDER BY P.AcademicId
 
END
GO
PRINT N'Altering [sHostel].[PHostelDepositListGet]...';


GO

ALTER PROCEDURE [sHostel].[PHostelDepositListGet]
	 
	      @rHostelId int,
	      @rRoomId int,
          @rOrgGroupBatchId int,
          @rStudentCode   nvarchar(max)='',
          @rSUId nvarchar(max)='',
          @rHostelDepositHeadId int
     
          
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	SELECT
	    DHM.Title AS DepositHeadName,
		DA.Id AS DepositId,
	    DA.Studentid AS Studentid,
		DA.Amount,
		DA.DepositDate,
		vSA.Code,
        vSA.Name AS StudentName,        
        vSA.ClassName+' - '+vSA.DivisionName AS ClassDivisionName,
       ISNULL(VSA.SUID,'') AS SUID,
       RM.Title AS Room,
       	DA.HostelDepositHeadId
  FROM 		
		sHostel.tAssignRoom AR 
		INNER JOIN sStudent.vStudentAcademic vSA ON vSA.StudentId = AR.SourceId AND AR.SourceTypeId = 2003
		INNER JOIN sHostel.tHostelDepositAdd DA ON DA.StudentId = vSA.StudentId
		INNER JOIN sHostel.tHostelDepositHeadMaster DHM ON DHM.Id = DA.HostelDepositHeadId 
		INNER JOIN sHostel.tRoomMaster RM ON AR.RoomId = RM.Id
	
		WHERE	
			 (DA.HostelId=@rHostelId)
			AND DA.OrgGroupBatchId=@rOrgGroupBatchId
		    AND AR.OrgGroupBatchId=@rOrgGroupBatchId
			AND vSA.OrgGroupBatchId=@rOrgGroupBatchId
			AND ((DA.HostelDepositHeadId = @rHostelDepositHeadId) OR (ISNULL(@rHostelDepositHeadId,0) = 0))
			AND ((RM.Id = @rRoomId) OR (ISNULL(@rRoomId,0) = 0))
			AND (ISNULL(vSA.SUID,'') IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rSUId,',')) OR @rSUId='') 
	        AND (ISNULL(vSA.Code,'') IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rStudentCode,',')) OR @rStudentCode='') 
	    
			Order By VSA.SUID,VSA.Code
END
GO
PRINT N'Altering [sHrm].[pEmployeeLateStatusAdd]...';


GO
ALTER PROCEDURE [sHrm].[pEmployeeLateStatusAdd]
           
        @rEmployeeId bigint,
        @rLateDate date,  
        @rLateStatus nvarchar(10)='',
        @rStatusId smallint=0,
        @rEarlyLeaveRemark nvarchar(200)='',
        @rCreatedUserId bigint,
        @rIsUpdate bit = 0,
        @rEarlyHrs decimal(10,2)=0
AS
SET NOCOUNT ON
BEGIN

	BEGIN TRY
	BEGIN TRANSACTION
	IF(@rIsUpdate = 0)	
	BEGIN
		  INSERT INTO sBiometric.tEmployeeLateStatus
          (
		   EmployeeId,
		   LateDate,
		   LateStatus,
		   StatusId,
		   EarlyLeaveRemark,
		   CreatedUserId,
		   CreatedDateTime,
		   UpdatedUserId,
		   UpdatedDateTime
          )
          VALUES
           (
            @rEmployeeId,
            @rLateDate,
            @rLateStatus,
            @rStatusId,
            @rEarlyLeaveRemark,
            @rCreatedUserId,
            sCommon.fGetDate(),
            @rCreatedUserId,
            sCommon.fGetDate()
           )
	
	SELECT 1 AS Result	   
	
	END
	ELSE
	BEGIN
		UPDATE  sBiometric.tEmployeeLateStatus
	    SET
			StatusId = @rStatusId,
			EarlyHrs = @rEarlyHrs,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate()
	     WHERE EmployeeId = @rEmployeeId AND LateDate = @rLateDate
		 
		 SELECT 1 AS Result	   
	END   
	COMMIT TRANSACTION
	END TRY	
	BEGIN CATCH
		ROLLBACK TRANSACTION
		SELECT -1 AS RESULT
	END CATCH
END
GO
PRINT N'Altering [sHrm].[pRptExperienceCertificateGet]...';


GO
ALTER PROCEDURE [sHrm].[pRptExperienceCertificateGet]
	
	 
	 --@rReportId int=0,
	-- @rStrEmployeeId nvarchar(max),
	 --@rEmployeeTypeId [int]= 0,
	@rEmployeeId [bigint]= 0,
	 --@rEmployeeGroupId smallint=0,
	-- @rEmployeeStatusId smallint=0,
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rOrgId smallint,
	 @rCode nvarchar(20)='',
	 --@rBatchId int,
	 @rFromNo nvarchar(20)='',
	 @rToNo nvarchar(20)='',
	 @rNumber nvarchar(20)='',
	 @rFromDate date='',
     @rToDate date='',
     @rName nvarchar(20)=''
									
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

BEGIN
DECLARE @lIsOnPrePrinted bit = 0

DECLARE @lConfigValue nvarchar(50)
DECLARE @lIsDisplayImageHeader bit=0

SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 182 AND SourceTypeId = 1016 AND SourceId = @rOrgId
	
	IF (@lConfigValue IS NULL) OR (@lConfigValue = 'Default')
	BEGIN
	SET @lIsOnPrePrinted = 0
	SET @lIsDisplayImageHeader = 0
	END
	ELSE IF (@lConfigValue = 'Blank')
	BEGIN
	SET @lIsOnPrePrinted = 1
	SET @lIsDisplayImageHeader = 0
	END
	ELSE IF (@lConfigValue = 'Image')
	BEGIN
	SET @lIsOnPrePrinted = 0
	SET @lIsDisplayImageHeader = 1
	END
	--SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 158 AND SourceTypeId = 1016 AND SourceId = @rOrgId
	
	--IF (@lConfigValue IS NULL) OR (@lConfigValue = 'False')
	--SET @lIsDisplayImageHeader = 0
	--ELSE
	--SET @lIsDisplayImageHeader = 1	
	
	
	SELECT
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
	        EM.Id AS EmployeeId,
	        EM.Code,
	        EM.EmployeeName,
	       	EM.FirstName,
			EM.MiddleName,
			EM.LastName,	
			EM.ShortName,
			EM.OrgID,
			EM.GenderId,
			EM.DateOfJoining,
			EM.StatusId,
			EM.UserId,
			EM.DepartmentId,
			EM.DateOfleaving,
			EM.EmployeeTypeId,
			EM.DesignationId,
			EM.Designation,
			--EM.EmployeeGroup,
			--EM.EmployeeGroupId,
			EM.EmployeePhoto,
			EC.PresentStreetOne,
			EC.PresentStreetTwo,
			EC.PresentStreetThree,
			EC.PresentCity,
			EC.PresentState,
			EC.PresentCountry,
			EC.PresentZipCode,
			@lIsOnPrePrinted AS IsOnPrePrinted,
			@lIsDisplayImageHeader AS IsDisplayImageHeader,
			OI.CertificateHeaderA4 ,
			CE.Remark,
			CE.CertificateReason,
			CE.CertificateDate,
			CE.Number,
			convert(varchar(4),DATEDIFF(MONTH, EM.DateOfJoining, EM.DateOfleaving)/12) +' years '+
			convert(varchar(2),DATEDIFF(MONTH, EM.DateOfJoining, EM.DateOfleaving) % 12)+ ' months' As ExpMonth
			 
			
	FROM 
	        sHrm.tCertificateExperience CE
            INNER JOIN [sHrm].[vExtEmployeeMaster] EM  ON EM.EmployeeId=CE.EmployeeId  
			LEFT JOIN sHrm.tEmployeeCommunications EC ON EM.EmployeeId=EC.EmployeeId
			LEFT JOIN sCommon.tGenderMaster GM ON GM.Id = EM.GenderId
		    INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=EM.OrgId
			LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = OM.Id
	WHERE
			((EM.Code LIKE @rCode)OR (@rCode = '' ))
	   --AND (ISNULL(EM.EmployeeId,0) NOT IN( SELECT cast(item as bigint) FROM  sCommon.fnsplit(@rStrEmployeeId,',')) OR @rStrEmployeeId='') 
	   AND ((EM.EmployeeId = @rEmployeeId) OR (@rEmployeeId = 0))
	   AND ((EM.EmployeeName like @rName) OR (ISNULL(@rName,'') = ''))
	   AND ((CE.Number=@rNumber) OR (@rNumber=''))
	   AND ((CE.Number >= @rFromNo) OR (@rFromNo=0))
	   AND ((CE.Number <= @rToNo) OR (@rToNo=0))
	   AND ((CE.CertificateDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	   AND ((CE.CertificateDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))	   
	   --AND ((DATEDIFF(yy,EM.DateOfBirth,GETDATE()) <= @rAgeTo) OR (ISNULL(@rAgeTo,0)=0))
	   --AND ((DATEDIFF(yy,EM.DateOfBirth,GETDATE()) >= @rAgeFrom)OR (ISNULL(@rAgeFrom,0)=0))
	   AND  EM.OrgId = @rOrgId
END
GO
PRINT N'Altering [sIp].[pStockItemMasterModify]...';


GO
ALTER PROCEDURE [sIp].[pStockItemMasterModify]
	 
	@rId [int],
	@rCode [nvarchar](10),
	@rTitle [nvarchar](100),
	@rUpdatedUserId [bigint],	 
	@rStockItemCategoryId [int],	 
	@rIsBatchWiseTracking [bit], 
	@rIssueStockUomId [int],
	@rItemSubGroupId [int],
	@rMaximumInventory [decimal](12, 2),	 
	@rReOrderPoint [decimal](12, 2),
	@rSafetyStock [decimal](12, 2),
	@rStandardPrice [decimal](22, 6), 
 	@rTaxGroupId [int],  
	@rVendorId [int],	
	@rIsObsolete [bit], 
	@rIsBlockedForIssue bit, 
	@rDrugRemark nvarchar(500),
	@rStoreLocationId int,	
	@rOrgGroupId int,
	@rOrgId INT,
	@rBinId int=0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
 DECLARE @lCount INT 
DECLARE @StoreLocationId INT 
	--SELECT @rId
	 UPDATE sIp.tStockItemMaster
		SET 
			Code = @rCode,
			Title = @rTitle,
			UpdatedUserId = @rUpdatedUserId,
			UpdatedDateTime = sCommon.fGetDate(),			 
			StockItemCategoryId = @rStockItemCategoryId,		 
			IsBatchWiseTracking = @rIsBatchWiseTracking,			 
			IssueStockUomId = @rIssueStockUomId,
			ItemSubGroupId = @rItemSubGroupId,
			TaxGroupId = (CASE WHEN @rTaxGroupId <= 0 THEN NULL ELSE @rTaxGroupId END),			 
			VendorId = (CASE WHEN @rVendorId <= 0 THEN NULL ELSE @rVendorId END),
			IsObsolete = @rIsObsolete,
			IsBlockedForIssue = @rIsBlockedForIssue,
			StoreLocationId = @rStoreLocationId,			 
			Remark = @rDrugRemark,
			BinId=@rBinId
		 
			
	  WHERE Id = @rId
	  
	EXEC [sIp].[pItemStandardPriceLogAdd] @rId, @rStandardPrice, @rUpdatedUserId,@rOrgGroupId
	
 	EXECUTE [sIp].[pStockItemPlanningModify]  @rId,@rMaximumInventory,@rReorderPoint,@rSafetyStock,@rStandardPrice,null,null,@rStoreLocationId
		
	--EXECUTE sProcurement.pStockBatchAdd  @rOrgId,@rStoreLocationId,@rId,null,null,0,@rUpdatedUserId 
		
SELECT @rId AS RESULT
END

/****** Object:  StoredProcedure [sCwb].[pDoctorActivityTypeMasterGet]    Script Date: 07/09/2013 16:20:51 ******/
SET ANSI_NULLS ON
GO
PRINT N'Altering [sLibrary].[pAssignBooksBulkReturnGet]...';


GO

ALTER PROCEDURE [sLibrary].[pAssignBooksBulkReturnGet]
	 
	 @rLibraryId int,
	 @rClassId int,
	 @rOrgId smallint,
	 @rBatchId int,
	 @rDivisionId int

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 

	SELECT 
	Distinct VA.StudentId,
	VA.Name,
	VA.Code,
	VA.RollNo,
	VA.StudentId
	 
  FROM 
  sStudent.vStudentLastAcademic  VA
  INNER JOIN sLibrary.tBookLog BL ON VA.StudentId=BL.ReaderSourceId AND  BL.IsCurrentStatus=1 AND  BL.ReaderSourceTypeId=2003
  	AND BL.IsCurrentStatus=1
		AND ((BL.StatusId=522) OR (BL.StatusId=523))
 
  WHERE   
 VA.ClassId=@rClassId
 AND VA.BatchId=@rBatchId
 AND VA.OrgId=@rOrgId
 AND ((VA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
 AND BL.LibraryId=@rLibraryId
 order by VA.RollNo
    
END
GO
PRINT N'Altering [sLibrary].[pBookMasterAdd]...';


GO

ALTER PROCEDURE [sLibrary].[pBookMasterAdd]
	 
	
	@rId bigint,
	@rCode nvarchar(25),
	@rTitle nvarchar(100),
	@rPublisher nvarchar(200),
	@rSupplier nvarchar(200),
	@rAuthor nvarchar(200),
	@rSubject nvarchar(200),
	@rLanguage nvarchar(200),
	@rLocation nvarchar(200),
	@rEdition nvarchar(50),
	@rISBNNumber nvarchar(100),
	@rPrice decimal(12,2),
	@rCurrency nvarchar(100),
	@rBookTag nvarchar(200),
	@rBookCustomTag nvarchar(200),
	@rBookAgeGroupId int,
	@rResourceTypeId int,
	@rOrgGroupId int,
	@rBatchId int,
	@rLibraryId int,
	@rCreatedUserId bigint,
	@rUpdatedUserId bigint,
	@rBookDepartment nvarchar(150),
	@rClassNumber nvarchar(50),
	@rBookVolume smallint,
	@rNoOfCopies smallint,
	@rClassificationNo nvarchar(50),
	@rAccessionNo nvarchar(50),
	@rNoOfPages int,
	@rPurchaseDate date,
	@rBookRemark  nvarchar(300),
	@rBillNumber nvarchar(100),
	@rYearOfPublication nvarchar(50),
	@rBookEntryDate date,
	@rBookImage varbinary(max)=null
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	 

				
BEGIN TRANSACTION

IF(@rId = 0)



    BEGIN
    
    	IF Exists(Select @rCode from sLibrary.tBookMaster where Code=@rCode AND LibraryId = @rLibraryId )
		BEGIN
			Select -103 AS Result
			RETURN
		END
    
    
DECLARE @lNextNumber BIGINT   
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sLibrary.tBookMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	
	INSERT INTO sLibrary.tBookMaster
		(
			Id,
			Code,
			Title,
			Publisher,
			Supplier,
			Author,
			BookSubject,
			BookLanguage,
			Location,
			Edition,
			ISBNNumber,
			Price,
			Currency,
			BookTag,
			BookCustomTag,
			BookAgeGroupId,
			ResourceTypeId,
			CreatedUserId,
			CreatedDateTime,
			LibraryId,
			BookDepartment,
			ClassNumber,
			BookVolume,
			NoOfCopies,
			ClassificationNo ,
			AccessionNo,
			NoOfPages,
			PurchaseDate,
			BookRemark,
			BillNumber,
			YearOfPublication,
			BookEntryDate,
			BookImage
			
			
			
		)
	VALUES
		(
			@lNextNumber,
			@rCode,
			@rTitle,
		    @rPublisher,
		    @rSupplier,
			@rAuthor,
			@rSubject,
			@rLanguage,
			@rLocation,
			@rEdition,
			@rISBNNumber,
			@rPrice,
			@rCurrency,
			@rBookTag,
			@rBookCustomTag,
			@rBookAgeGroupId,
			@rResourceTypeId,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rLibraryId,
			@rBookDepartment,
			@rClassNumber,
			@rBookVolume,
			@rNoOfCopies,
			@rClassificationNo ,
			@rAccessionNo,
			@rNoOfPages,
			@rPurchaseDate,
			@rBookRemark,
			@rBillNumber,
			@rYearOfPublication,
			@rBookEntryDate,
			@rBookImage
		)
		
	  EXECUTE sLibrary.pBookLogAdd NULL,NULL,2009,@lNextNumber,null,null,521,NULL,1,@rOrgGroupId,@rBatchId,@rCreatedUserId,@rLibraryId
		   
		   Select @lNextNumber AS Result
	END
	
		
	ELSE
	
	 BEGIN
	 
	 	IF Exists(Select @rCode from sLibrary.tBookMaster where Code=@rCode AND LibraryId = @rLibraryId  AND Id!=@rId)
		BEGIN
			Select -103 AS Result
			RETURN
		END
	 
	 SET @lNextNumber = @rId
	    UPDATE  sLibrary.tBookMaster
	    SET
			Code=@rCode,
			Title=@rTitle,
			Publisher=@rPublisher,
			Supplier=@rSupplier,
			Author=@rAuthor,
			BookSubject=@rSubject,
			BookLanguage=@rLanguage,
			Location=@rLocation,
			Edition=@rEdition,
			ISBNNumber=@rISBNNumber,
			Price=@rPrice,
			Currency=@rCurrency,
			BookTag=@rBookTag,
			BookCustomTag=@rBookCustomTag,
			BookAgeGroupId=@rBookAgeGroupId,
			ResourceTypeId=@rResourceTypeId,						
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate(),
			BookDepartment=@rBookDepartment,
			ClassNumber=@rClassNumber,
			BookVolume=@rBookVolume,
			NoOfCopies=@rNoOfCopies,
			ClassificationNo=@rClassificationNo ,
			AccessionNo=@rAccessionNo,
			NoOfPages=@rNoOfPages,
			PurchaseDate=@rPurchaseDate,
			BookRemark=@rBookRemark,
			BillNumber=@rBillNumber,
			YearOfPublication=@rYearOfPublication,
			BookEntryDate=@rBookEntryDate,
			BookImage=@rBookImage
			
	      
	      WHERE Id = @rId 
	      --AND Code=@rCode
	      SELECT @lNextNumber AS Result
	
END	
		
	COMMIT TRANSACTION
END TRY
	
	
	BEGIN CATCH
	    ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH  
END
GO
PRINT N'Altering [sLibrary].[pBookMasterGet]...';


GO

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


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

	 
	SELECT @quer='SELECT BM.Code,
	BM.Title,
	ISNULL(BM.Publisher,'''')AS Publisher,
	ISNULL(BM.Supplier,'''')AS Supplier,
	ISNULL(BM.Author,'''')AS Author,
	ISNULL(BM.BookSubject,'''') AS BookSubject,
	ISNULL(BM.BookLanguage,'''') AS BookLanguage,
	ISNULL(BM.Location,'''') AS Location,
	ISNULL(BM.Edition,'''')AS Edition,
	ISNULL(BM.ISBNNumber,'''') AS ISBNNumber,
	ISNULL(BM.Price,0) AS Price,
	ISNULL(BM.Currency,'''') AS Currency,
	ISNULL(BM.BookTag,'''')AS BookTag,
	ISNULL(BM.BookCustomTag,'''') AS BookCustomTag,
	ISNULL(BM.BookDepartment,'''') AS BookDepartment,
	ISNULL(BM.ClassNumber,'''') AS ClassNumber,
	ISNULL(BM.BookVolume,1) AS BookVolume,
	ISNULL(BM.NoOfCopies,1) AS NoOfCopies,
	SM.Title AS StatusName,
	BM.Id,
	ISNULL(AGM.Id,0)AS BookAgeGroupId,
	ISNULL(RTM.Id,0) AS ResourceTypeId,
	BM.CreatedUserId,
	BM.CreatedDateTime,
	ISNULL(BM.UpdatedUserId,0) AS UpdatedUserId,
	ISNULL(BM.UpdatedDateTime,'''') AS UpdatedDateTime,
	BM.LibraryId,
	SM.Id AS StatusId,
	BM.ClassificationNo,
	BM.AccessionNo,
	ISNUll(BM.NoOfPages,0) AS NoOfPages,
	 ISNULL(BM.PurchaseDate,''0001/01/01'') AS PurchaseDate,
    ISNUll(BM.BookRemark,'''') AS BookRemark,
    ISNULL(BM.BillNumber,'''') AS BillNumber,
    BM.YearOfPublication,
    ISNULL(BM.BookEntryDate,''0001/01/01'') AS BookEntryDate,
    CASE WHEN ' + convert(varchar,@rShowWithPhotoId) + '= 1 Then ISNULL(BM.BookImage, CONVERT(VARBINARY(MAX), 0)) ELSE BM.BookImage END AS BookPicture
 
	FROM 
        sLibrary.tBookMaster BM
         LEFT JOIN sLibrary.tBookAgeGroupMaster AGM
         ON BM.BookAgeGroupId=AGM.Id
         INNER JOIN sLibrary.tResourceTypeMaster RTM
         ON BM.ResourceTypeId=RTM.Id
         INNER JOIN sLibrary.tBookLog BL
         ON BL.ResourceSourceId=BM.Id AND IsCurrentStatus=1
         INNER JOIN sCommon.tStatusMaster SM
         ON SM.Id=BL.StatusId 
         
         WHERE ((BM.Id = ' + convert(varchar,@lId) + ') OR (' + convert(varchar,@lId) + ' = 0))
	AND ((BM.Code = ''' + @lCode + ''') OR (''' + @lCode + ''' = ''''))
	AND ((BM.Title like ''' + @lTitle + ''') OR (''' + @lTitle + ''' = '''')) 
	AND ((BM.Publisher like ''' + @lPublisher + ''') OR (''' + @lPublisher + ''' = '''')) 
	AND ((BM.Supplier like ''' + @lSupplier + ''') OR (''' + @lSupplier + ''' = '''')) 
	AND ((BM.Author like ''' + @lAuthor + ''') OR (''' + @lAuthor + ''' = '''')) 
	AND ((BM.BookSubject like ''' + @lSubject + ''') OR (''' + @lSubject + ''' = ''''))  
	AND ((BM.BookLanguage like ''' + @lLanguage + ''') OR (''' + @lLanguage + ''' = ''''))  
	AND ((BM.Location like ''' + @lLocation + ''') OR (''' + @lLocation + ''' = ''''))  
	AND ((BM.Edition like ''' + @lEdition + ''') OR (''' + @lEdition + ''' = ''''))  
	AND ((BM.ISBNNumber like ''' + @lISBNNumber + ''') OR (''' + @lISBNNumber + ''' = ''''))  
	AND ((BM.BookTag like ''' + @lBookTag + ''') OR ( ''' + @lBookTag + ''' = ''''))
	AND ((BM.BookCustomTag like ''' + @lBookCustomTag + ''') OR (''' + @lBookCustomTag + ''' = ''''))
	AND ((BM.BookAgeGroupId = ' + convert(varchar,@lBookAgeGroupId) + ') OR(' + convert(varchar,@lBookAgeGroupId) + ' = 0))
	AND ((BM.ResourceTypeId = ' + convert(varchar,@lResourceTypeId) + ') OR (' + convert(varchar,@lResourceTypeId) + ' = 0))
	AND ((BM.Price = ' + convert(varchar,@lPrice) + ') OR (' + convert(varchar,@lPrice) + ' = 0))
	AND ((BM.Currency like ''' + @lCurrency + ''') OR (''' + @lCurrency  + ''' = ''''))
	AND ((BL.StatusId = ' + convert(varchar,@lStatusId) + ') OR (' + convert(varchar,@lStatusId) + '=0))
	AND ((BM.BookDepartment like ''' + @lBookDepartment + ''') OR (''' + @lBookDepartment + ''' = ''''))
	AND BM.LibraryId = ' + convert(varchar,@lLibraryId)
	
	exec (@quer)
	

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


GO
ALTER PROCEDURE [sPayroll].[pRptPayElementwiseSummaryDetail]
	
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rPayElementId int,
	 @rEmployeeId bigint,
	 @rEmployeeCode nvarchar(200),
	 @rEmployeeName nvarchar(200),
	 @rDepartmentId int,
	 @rForMonth int,
	 @rForYear int,
	 @rPayrollId int,
	 @rPayrollGroupId int,
	 @rPayrollYearId int,	
	 @rPayElementTypeId int=0,
	 @rMonths nvarchar(50)=''
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN  
	
	DECLARE @lBasicPayElementId int
	DECLARE @lProfessionalTaxPayElementId int
	
	SELECT @lBasicPayElementId = Id FROM sPayroll.tPayElement WHERE PayrollId = @rPayrollId AND PayElementDefaultId = 1
	SELECT @lProfessionalTaxPayElementId = Id FROM sPayroll.tPayElement WHERE PayrollId = @rPayrollId AND PayElementDefaultId = 57
	
	SET @rEmployeeCode = sCommon.fSearchStringGet(@rEmployeeCode)
    SET @rEmployeeName = sCommon.fSearchStringGet(@rEmployeeName)

	SELECT 
	
	@rBuilder1 AS Builder1,
	@rBuilder2 AS Builder2,	
	PE.Amount,
	P.Id AS PayElementId, 
	P.Title AS PayElementName,
	P.Code AS PayElementCode,
	EM.EmployeeId,
	tEM.FirstName +' '+tEM.MiddleName+' '+ tEM.LastName AS EmployeeName,
	EM.Code,
	EM.EmployeeDesignation,
	PP.SalaryMonth,
	PP.SalaryYear,
	MM.Title AS MonthName,
	PY.Title AS PayrollYearName,
	P.SortOrder,
	P.PayElementTypeId,
	@rPayElementTypeId AS IsPayElementTypeIdZero,
	@rPayElementId AS IsPayElementIdZero, 
	PPE.TotalEarning,		
	PPE.TotalDeduction,
	PPE.NetAmount,
	(CASE WHEN PayElementId = @lBasicPayElementId then PPE.TotalEarning else 0 END) AS TotalEarningTotal,
	(CASE WHEN (PayElementId = @lBasicPayElementId And @rPayElementTypeId <> 2) 
	 THEN PPE.TotalDeduction WHEN PayElementId = @lProfessionalTaxPayElementId And @rPayElementTypeId = 2 
	 THEN PPE.TotalDeduction ELSE 0 END) AS TotalDeductionTotal,	 
	(CASE WHEN PayElementId = @lBasicPayElementId then PPE.NetAmount else 0 END) AS NetAmountTotal,
	PGM.Id AS PayrollGroupId,
	PGM.Title AS PayrollGroupName,
	PPE.GrossBasic ,
	P.PayElementDefaultId

	FROM sPayroll.tPayProcessEmployee PPE
		INNER JOIN sPayroll.tPayProcess PP ON PPE.PayProcessId=PP.ID
		INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
		INNER JOIN sPayroll.tPayElement P ON P.ID=PE.PayElementId
		INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId=PPE.EmployeeId
		INNER JOIN sHrm.tEmployeeMaster tEM ON tEM.Id=PPE.EmployeeId
		LEFT JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.EmployeeId=PPE.EmployeeId	
		INNER JOIN sCommon.tMonthMaster MM ON MM.Id=PP.SalaryMonth
		INNER JOIN sPayroll.tPayrollYearMaster PY ON PP.PayrollYearId = PY.Id 
		INNER JOIN sPayroll.tPayrollGroupMaster PGM ON PGM.Id = PPE.PayrollGroupId
WHERE 
      (PPE.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
      AND ((P.ID=@rPayElementId) OR (@rPayElementId=0))
      AND ((EM.Code Like  @rEmployeeCode) OR (@rEmployeeCode = ''))
	  AND ((EM.EmployeeName Like @rEmployeeName ) OR (@rEmployeeName = ''))
	  AND (EM.DepartmentId = @rDepartmentId OR @rDepartmentId = 0)
	  AND (PP.SalaryMonth = @rForMonth OR @rForMonth = 0)
	  AND (PP.SalaryYear = @rForYear OR @rForYear = 0)
	  AND ((PY.PayrollId=@rPayrollId) OR (@rPayrollId=0))
	  AND (PPE.PayrollGroupId = @rPayrollGroupId OR @rPayrollGroupId = 0) 
	  AND (PP.PayrollYearId = @rPayrollYearId OR @rPayrollYearId = 0) 
	  AND (P.PayElementTypeId = @rPayElementTypeId OR @rPayElementTypeId = 0) 
	  AND (PP.SalaryMonth IN(SELECT cast(item as int) FROM  sCommon.fnsplit(@rMonths,',')) OR @rMonths='')
END
GO
PRINT N'Altering [sProcurement].[pStockResetAdd_New]...';


GO
 

ALTER PROCEDURE [sProcurement].[pStockResetAdd_New]
(
@rOrgGroupId [smallint],
@rNumber Nvarchar(max) = '',
@rResetByName Nvarchar(max) = '',
@rToStoreLocationId	Int,
@rRemark Nvarchar(max),
@rCreatedUserId	BigInt,
@rDetail Nvarchar(Max),
@rLocationId int,
@rOrgId int

)
AS
SET NOCOUNT ON
BEGIN
  BEGIN TRY	    
	DECLARE @loXML XML
	SET @loXML = CAST(@rDetail AS XML)

	EXECUTE sCommon.pPrefixSetupNextNumberGet @rOrgId = @rOrgId, @rPrefixFunctionalityId = 1007,
	@rStoreLocationId = @rToStoreLocationId, @rNextNumber  = @rNumber OUTPUT
	
	SET @rNumber = ISNULL(@rNumber, '-300')
	IF @rNumber = '-300'
	BEGIN
		SELECT -300 AS Result, '' AS Number, 0 AS Id 
		RETURN
	END


	DECLARE @tStockResetDetailBatch TABLE
	(
		Id Int IDENTITY(1, 1),	 
		StockItemId bigint,
		StockItemName nvarchar(max),
		ItemBatch Nvarchar(max) NULL,
		ItemExpiryDate Date NULL,	
		ResetQuantity Decimal(12,2),
		RequestedQuantity Decimal(12,2),
		ResetValue Decimal(12,2)
	)	
    INSERT INTO @tStockResetDetailBatch
    SELECT
            T.c.value('@StockItemId','bigint') AS StockItemId,
            T.c.value('@StockItemName','nvarchar(max)') AS StockItemname,
            T.c.value('@ItemBatch','Nvarchar(max)') AS ItemBatch,
            T.c.value('@ItemExpiryDate','Date')   AS ItemExpiryDate,
            T.c.value('@ResetQuantity','Decimal(12,2)') AS ResetQuantity,
            T.c.value('@RequestedQuantity','Decimal(12,2)') AS RequestedQuantity,
            T.c.value('@ResetValue','Decimal(12,2)') AS ResetValue 
    FROM 
            @loXML.nodes('/Table/StockReset')T(c)


  BEGIN TRANSACTION
   
	DECLARE @lNextNumberStockReset bigint,@lNextNumberStockResetBatch bigint
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sProcurement.tStockReset', 0, 1, 1,@outNextNumber = @lNextNumberStockReset output

	INSERT INTO sProcurement.tStockReset
	(
		Id,Number,ResetByName,ToStoreLocationId,Remark,CreatedUserId,CreatedDateTime,OrgGroupId
	)
	VALUES
	(
		@lNextNumberStockReset,@rNumber,
		@rResetByName,@rToStoreLocationId,@rRemark,@rCreatedUserId,sCommon.fGetDate(),
		@rOrgGroupId
	)
            
	declare @lCount int,@lIsBatchWise bit,@lbatchId int,@lNextNumberStockBatch int,@lExpiryDate date
	Declare @lItemId int,@lBatch nvarchar(300),@lResetQty decimal(12,2),@lResetValue decimal(12,2),@lIdCount int
	DECLARE @lStockItemname nvarchar(max)
	select @lCount=COUNT(*) from @tStockResetDetailBatch 
		 
	while @lcount > 0
	BEGIN
					 
		Select @lItemId =StockItemId,@lBatch = ItemBatch,@lResetQty=ResetQuantity,@lResetValue=ResetValue,@lIdCount=Id,@lExpiryDate =ItemExpiryDate 
		,@lStockItemname=StockItemname
		from  @tStockResetDetailBatch WHERE Id = @lcount
		Select @lIsBatchWise=IsBatchWiseTracking from sIp.tStockItemMaster    Where Id = @lItemId   
		 
		SET @lbatchId = 0
		 
			if (@lIsBatchWise=1)
			BEGIN		
							
				Select @lbatchId= Id from sProcurement.tStockBatch    
				Where  Number =@lBatch   AND  StoreLocationId = @rToStoreLocationId AND StockItemId = @lItemId --AND @lIdCount=@lcount
				 
			END
			else 
			BEGIN
				
				Select @lbatchId= Id from sProcurement.tStockBatch    
				Where iSNULl( Number,'') =''  AND  StoreLocationId = @rToStoreLocationId AND StockItemId = @lItemId--AND  @lIdCount=@lcount
			 
			END

			if(ISNULL(@lbatchId,0)=0)
			BEGIN
				  
				EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sProcurement.tStockBatch', 0, 1, 1,@outNextNumber = @lNextNumberStockBatch output
				 INSERT INTO sProcurement.tStockBatch (Id,StoreLocationId,StockItemId,Number,ExpiryDate,AvailableQuantity,CreatedUserId,CreatedDateTime,OrgGroupId,ItemRate)
				Select @lNextNumberStockBatch,@rToStoreLocationId,@lItemId,@lBatch,@lExpiryDate ,@lResetQty,@rCreatedUserId,getdate(),@rOrgGroupId,@lResetValue
				--from @tStockResetDetailBatch where Id=@lcount
				
				 SET @lbatchId = @lNextNumberStockBatch
				 
				 
			END 
			 	 
			 if(@lbatchId>0)
			BEGIN
					 
				 EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sProcurement.tStockResetBatch', 0, 1, 1,@outNextNumber = @lNextNumberStockResetBatch output
				
						INsert into sProcurement.tStockResetBatch(Id,StockResetId,Quantity,StockBatchId,OrgGroupId,UnitCost)
						Select @lNextNumberStockResetBatch,@lNextNumberStockReset,ResetQuantity,@lbatchId,@rOrgGroupId,ResetValue
						from @tStockResetDetailBatch where Id=@lcount
			 
						Exec sIp.pWeightedAverageCostLogAdd_New @rOrgGroupId =@rOrgGroupId,@rSourceTypeId=2028,@rSourceId=@lNextNumberStockResetBatch,
								@rItemSourceTypeId = 34,@rItemSourceId=@lItemId,@rQuantity=@lResetQty ,@rValue=@lResetValue,@rIsReceipt=1,
								@rCreatedUserId = @rCreatedUserId,@rStoreLocationId = @rToStoreLocationId
								,@rLocationId=@rLocationId,@rItemBatchId = @lbatchId,@rItemName = @lStockItemname,@rOrgId=@rOrgId		
								
						 
			 END
			set @lcount =@lcount-1
		END
		
		SELECT 1 AS RESULT , @rNumber as Number,@lNextNumberStockReset as Id
		 COMMIT TRANSACTION
        END TRY
         
        BEGIN CATCH
        IF @@TRANCOUNT > 0  
		ROLLBACK TRANSACTION
		 
		SELECT -1 AS RESULT , @rNumber as Number,@lNextNumberStockReset as Id
	    END CATCH	
END
GO
PRINT N'Altering [sSecurity].[pDashletGet]...';


GO


ALTER PROCEDURE [sSecurity].[pDashletGet]
	@rOrgGroupId int=0,
	@rDate date='',
	@rDashletId int=0,
	@rOrgGroupBatchId int=0,
	@rUserId bigint=0,
	@rUserSourceId bigint=0,
	@rUserSourceTypeId int=0,
	@rOrgId Int=0,
	@rSourceTypeId smallint=0,
	@rSourceId bigint=0,
	@rBatchId int=0,
	@rExamId int=0
	
									
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
BEGIN
if(@rDashletId='1')
       BEGIN
        exec sCommunication.pCircularListGet @rUserSourceId=@rUserSourceId,@rOrgGroupBatchId=@rOrgGroupBatchId,@rUserSourceTypeId=@rUserSourceTypeId,@rUserId=@rUserId,@rStartDate=@rDate
        END
 if(@rDashletId='2')
        BEGIN
        SELECT  N.Id,N.Title FROM sCommunication.tNews N WHERE N.OrgGroupBatchId=@rOrgGroupBatchId AND Convert(date,N.CreatedDateTime)=convert(date,getdate())
        END
 if(@rDashletId='3')
          BEGIN
        exec sActivity.pMyEventGet @rSourceTypeId=@rSourceTypeId,@rSourceId=@rSourceId,@rOrgId=@rOrgId,@rBatchId=@rBatchId,@rFromDate=@rDate,@rToDate=@rDate
          END
if(@rDashletId='4')
        BEGIN
        exec sCommunication.pAssignTaskGet @rId=0,@rOrgId=@rOrgId,@rCreatedUserId=@rUserId,@rIsAssignTaskToMe=1,@rStatus=0,@rIsSearch=1
        END
 if(@rDashletId='5')
        BEGIN
        exec sCommunication.pAssignTaskGet @rId=0,@rOrgId=@rOrgId,@rCreatedUserId=@rUserId,@rIsAssignTaskToMe=0,@rStatus=0,@rIsSearch=1
        END
 if(@rDashletId='6')
        BEGIN
       
        SELECT 	EM.FirstName + ' ' + EM.MiddleName + ' ' + EM.LastName AS Name,	EM.DepartmentName  FROM [sHrm].[vExtEmployeeMaster] EM	
        WHERE  	EM.OrgId = @rOrgId  
         AND (MONTH(EM.DateOfBirth) = CAST(MONTH(GETDATE()) AS varchar(2))) AND EM.DateOfBirth!='' AND EM.StatusId=7
	    AND (DAY(EM.DateOfBirth) = CAST(DAY(GETDATE()) AS varchar(2)))   
		
        END
 if(@rDashletId='7')
        BEGIN
        SELECT SC.FirstName + ' ' + SC.MiddleName + ' ' + SC.LastName AS Name, SC.ClassName+' '+SC.DivisionName AS ClassName FROM sStudent.vStudentAllDetail SC WHERE SC.OrgId=@rOrgId AND SC.BatchId=@rBatchId
         AND (MONTH(SC.DateOfBirth) = CAST(MONTH(GETDATE()) AS varchar(2))) AND SC.DateOfBirth!='' AND SC.StatusId=1
	    AND (DAY(SC.DateOfBirth) = CAST(DAY(GETDATE()) AS varchar(2)))   
        END
         if(@rDashletId='10')
        BEGIN
       exec sAttendance.pDashletAttendanceStatusGet @rAcademicId=@rSourceId
        END
   
   if(@rDashletId='11')
        BEGIN
       SELECT EM.EmployeeName,L.FromDate,L.ToDate FROM  sHrm.tLeave L 
        INNER JOIN sSetup.tBatchMaster BM ON BM.Id = L.BatchId	
        INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = L.EmployeeId
        INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = L.EmployeeId
         WHERE  
			   BM.OrgGroupBatchId = @rOrgGroupBatchId
			   AND L.OrgId = @rOrgId
			   AND (EJD.EmployeeManagerId = @rUserSourceId OR @rUserSourceId = 0)
			   AND ((L.FromDate >= @rDate) OR (ISNULL(@rDate,'') = ''))
			   AND EM.EmployeeStatusId=7
             
       -- exec [sHrm].[pLeaveListingGet] @rOrgId=@rOrgId,@rEmployeeId=@rUserSourceId,@rLeaveTypeId=0,@rOrgGroupBatchId=@rOrgGroupBatchId,@rFromDate=@rDate,@rTodate=''
        END
   if(@rDashletId='12')
        BEGIN
     exec sCommunication.pPollGet @rOrgGroupBatchId=@rOrgGroupBatchId,@rSourceTypeId=@rUserSourceTypeId,@rCreatedUserId=@rUserId,@rCreatedDateTime=@rDate
        END
  if(@rDashletId='14')
       BEGIN
        exec sCommunication.pMyBookGet @rReaderSourceTypeId=@rUserSourceTypeId,@rReaderSourceId=@rUserSourceId,@rBatchId=@rBatchId

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

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


GO
ALTER PROCEDURE [sSecurity].[pOrganizationGroupSettingAdd]
	 
        @rOrgGroupId smallint,
        @rNoOfStudent int,
        @rPaymentDueDate date,
        @rIsPaymentReminder bit,
        @rPaymentReminderRemark nvarchar(300) ,
        @rExtraStudent int=0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	 
	 If Exists(select 1 from sSetup.tOrgGroupSetting where OrgGroupId=@rOrgGroupId)
			BEGIN
			 UPDATE  sSetup.tOrgGroupSetting
				SET
					 
					NoOfStudent=@rNoOfStudent,
					PaymentDueDate=@rPaymentDueDate,
					IsPaymentReminder=@rIsPaymentReminder,
					PaymentReminderRemark=@rPaymentReminderRemark,
					StudentExtraCap = @rExtraStudent
				  WHERE OrgGroupId = @rOrgGroupId
	      SELECT 11 AS Result
	 END  	
			 
	ELSE 
	BEGIN	 
	INSERT INTO sSetup.tOrgGroupSetting
		(
			OrgGroupId,
			NoOfStudent,
			PaymentDueDate,
			IsPaymentReminder,
			PaymentReminderRemark,
			StudentExtraCap
		)
	VALUES
		(
			@rOrgGroupId,
			@rNoOfStudent,
			@rPaymentDueDate,
			@rIsPaymentReminder,
			@rPaymentReminderRemark ,
			@rExtraStudent
		)
		    SELECT 1 AS Result
	END	 
 
		
END
GO
PRINT N'Altering [sSetup].[pBatchMasterGet]...';


GO
ALTER PROCEDURE [sSetup].[pBatchMasterGet]
	 @rId int = 0,
	 @rCode nvarchar(20),
	 @rTitle nvarchar(100),
	 @rOrgId int,
	 @rIsSearch bit=0,
	 @rOrgGroupBatchId int=0,
	 @rOrgGroupId int = 0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 IF(@rIsSearch=1)
		BEGIN
			SET @rCode = sCommon.fSearchStringGet(@rCode)
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		END
	
	SELECT 
	
			BM.Id,
			BM.Code,
			BM.Title,
			BM.OrgId,
			BM.IsHistory,
			BM.IsObsolete,
			ISNULL(BM.IsActive,0) AS IsActive,
			BM.OrderIndex,
			BM.FromDate,
			BM.ToDate,
			BM.CreatedUserId,
			BM.CreatedDateTime,
			BM.UpdatedUserId,
			BM.UpdatedDateTime,
			ISNULL(BM.OrgGroupBatchId,0) AS OrgGroupBatchId,
			ISNULL(BM.IsInContext,0) AS IsInContext,
			OGBM.Title AS OrgGroupBatchTitle,
			OM.DisplayTitle AS OrganizationName,
			OGBM.Id AS OrgGroupBatchId,
			OGBM.OrgGroupId,
			ISNULL(BM.batchGroupId,0) AS BatchGroupId
			
			
  FROM 
            sSetup.tBatchMaster BM
            INNER JOIN sSetup.tOrgGroupBatchMaster OGBM
				ON OGBM.Id = BM.OrgGroupBatchId
			INNER JOIN sSetup.tOrganizationMaster OM
				ON OM.Id = BM.OrgId
			LEFT join sSetup.tBatchGroupMaster BGM ON BGM.Id=BM.batchGroupId  
  WHERE 
  
    ((BM.Id = @rId) OR (@rId = 0))
    AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  
	AND ((BM.Code like @rCode) OR (ISNULL(@rCode,'') = '')) 
	AND ((BM.Title like @rTitle) OR (ISNULL(@rTitle,'') = '')) 
	AND ((BM.OrgId = @rOrgId) OR (@rOrgId = 0))  
	AND ((OM.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId = 0))  
	--AND BM.IsActive=1
	--AND(BM.OrgId=@rOrgId)

ORDER BY OM.Id, BM.OrderIndex ASC
END
GO
PRINT N'Altering [sSetup].[pOrgGroupMasterAdd]...';


GO
ALTER PROCEDURE [sSetup].[pOrgGroupMasterAdd]
	 
	@rId int,
	@rCode nvarchar(20),
	@rTitle nvarchar(100),
	@rCRMLicenceNo int,
	@rPunchLine nvarchar(200),
	@rOrgGroupBatchName nvarchar(20),
	@rFromDate date,
	@rToDate date,
	@rIsWindowSupport bit=0,
	  @rIsSync bit = 0
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	 
	IF(@rId=0)
		BEGIN
		IF EXISTS(SELECT 1 FROM sSetup.tOrgGroupMaster WHERE Code=@rCode)
		BEGIN
			SELECT -100 AS Result
			RETURN
		END
	END
	
	BEGIN TRANSACTION	
		IF(@rId=0)
		BEGIN
		
			DECLARE @lOrgGroupId smallint
			DECLARE @lOrgGroupBatchId int
			SET @lOrgGroupId=@rCode
			DECLARE @lCreatedUserId Int
			SET @lCreatedUserId = 1
			DECLARE @lCreatedDateTime DATETIME
			SET @lCreatedDateTime =  GETDATE()
			
	
			
			INSERT INTO sSetup.tOrgGroupMaster
			(
				Id,
				Code,
				Title,
				PunchLine,
				CRMLicenceNo,
				IsWindowSupport
			)
			VALUES
			(
				@rCode,
				@rCode,
				@rTitle,
				@rPunchLine,
				@rCRMLicenceNo,
				@rIsWindowSupport
			)
			
	 IF ( @rIsSync = 0)
 BEGIN
			
			SELECT @lOrgGroupBatchId=ISNULL(MIN(Id),(Convert(nvarchar(10),Convert(nvarchar(10),@lOrgGroupId))+'00000')+1) 
			FROM sSetup.tOrgGroupBatchMaster WHERE OrgGroupId=@lOrgGroupId
			
					 INSERT INTO [sSetup].[tOrgGroupBatchMaster]
					   ([Id]
					   ,[Code]
					   ,[Title]
					   ,[OrgGroupId]
					   ,[IsHistory]
					   ,[IsActive]
					   ,[IsObsolete]
					   ,[OrderIndex]
					   ,[FromDate]
					   ,[ToDate]
					   ,[CreatedUserId]
					   ,[CreatedDateTime]
					   ,[UpdatedUserId]
					   ,[UpdatedDateTime])
			     
				  SELECT @lOrgGroupBatchId
					   ,@rOrgGroupBatchName
					   ,@rOrgGroupBatchName
					   ,@lOrgGroupId
					   ,0
					   ,1
					   ,0
					   ,1
					   ,@rFromDate
					   ,@rToDate
					  ,@lCreatedUserId
					  ,@lCreatedDateTime
					  ,@lCreatedUserId
					  ,@lCreatedDateTime
 END
			
			 INSERT INTO [sSecurity].[tRole]
				   ([Id]
				   ,[Title]
				   ,[Remark]
				   ,[IsObsolete]
				   ,[CreatedUserId]
				   ,[CreatedDateTime]
				   ,[UpdatedUserId]
				   ,[UpdatedDateTime]
				   ,[IsSystem]
				   ,[OrgGroupId])
			SELECT
				   sCommon.fGetIntIdForOrg(Id,@lOrgGroupId)
				  ,[Title]
				  ,[Remark]
				  ,[IsObsolete]
				  ,@lCreatedUserId
				  ,@lCreatedDateTime
				  ,@lCreatedUserId
				  ,@lCreatedDateTime
				  ,[IsSystem]
				  ,@lOrgGroupId
			  FROM [sSecurity].[tRole] WHere OrgGroupId=1          

			INSERT INTO [sFinanceCommon].[tStockUomMaster]
					   ([Id]
					   ,[Code]
					   ,[Title]
					   ,[IsObsolete]
					   ,[CreatedUserId]
					   ,[CreatedDateTime]
					   ,[UpdatedUserId]
					   ,[UpdatedDateTime]
					   ,[OrgGroupId])
				 SELECT
						 sCommon.fGetIntIdForOrg(6,@lOrgGroupId)
						,'Nos'
						,'Nos'
						,0
						,@lCreatedUserId
						,@lCreatedDateTime
						,@lCreatedUserId
						,@lCreatedDateTime
						,@lOrgGroupId
				 --FROM [sFinanceCommon].[tStockUomMaster] WHERE OrgGroupId=1
	
	
	
				INSERT INTO [sStudent].[tAdmissionCategoryMaster]
					   ([Id]
					   ,[Code]
					   ,[Title]
					   ,[IsObsolete]
					   ,[CreatedUserId]
					   ,[CreatedDateTime]
					   ,[UpdatedUserId]
					   ,[UpdatedDateTime]
					   ,[OrgGroupId])
				 SELECT
						 sCommon.fGetIntIdForOrg(1,@lOrgGroupId)
						,'General'
						,'General'
						,0
						,@lCreatedUserId
						,@lCreatedDateTime
						,@lCreatedUserId
						,@lCreatedDateTime
						,@lOrgGroupId
				 --FROM [sStudent].[tAdmissionCategoryMaster]
				 -- WHERE OrgGroupId=1

				
				
				INSERT INTO [sCommon].[tTableRowId]
					   ([OrgId]
					   ,[TableTitle]
					   ,[CurrentNumber]
					   ,[Seed]
					   ,[Increment])
				SELECT
					   @lOrgGroupId
					  ,[TableTitle]
					  
					  ,CASE 
				  WHEN IdDataType = 'int' THEN sCommon.fGetIntIdForOrg(ISNULL(CurrentNumber,0),@lOrgGroupId) 
				  WHEN IdDataType = 'bigint' THEN sCommon.fGetbigIntIdForOrg(ISNULL(CurrentNumber,0),@lOrgGroupId )
					END 
					
					  ,CASE 
				  WHEN IdDataType = 'int' THEN sCommon.fGetIntIdForOrg(ISNULL(CurrentNumber,0),@lOrgGroupId) 
				  WHEN IdDataType = 'bigint' THEN sCommon.fGetbigIntIdForOrg(ISNULL(CurrentNumber,0),@lOrgGroupId )
					END  
					   ,1
				  FROM [sCommon].[tTableRowIdMaster] where 
				  (tableType = 'Non Static' or tableType = '100Static' )
				  AND iddatatype <> '' AND IdScope = 'OrgGroup'

				
			--		INSERT INTO [sCommon].[tTableRowId]
			--           ([OrgId]
			--           ,[TableTitle]
			--           ,[CurrentNumber]
			--           ,[Seed]
			--           ,[Increment])
			--SELECT
			--		   0
			--		  ,[TableTitle]		  
			--		  ,CurrentNumber		
			--		  ,CurrentNumber
			--		  ,1
			--	  FROM [sCommon].[tTableRowIdMaster] where 
			--	  (tableType =   '100StaticCommon') 
			--	  AND IdScope = 'OrgGroup' 
			
			
			
				INSERT INTO sCommunication.tCircularTypeMaster
					   ([Id]
					   ,[Code]
					   ,[Title]
					   ,[IsObsolete]
					   ,[CreatedUserId]
					   ,[CreatedDateTime]
					   ,[UpdatedUserId]
					   ,[UpdatedDateTime]
					   ,[OrgGroupId]
					   ,HighlightColor)
				 SELECT
						 sCommon.fGetIntIdForOrg(1,@lOrgGroupId)
						,'Circular'
						,'Circular'
						,0
						,@lCreatedUserId
						,@lCreatedDateTime
						,@lCreatedUserId
						,@lCreatedDateTime
						,@lOrgGroupId
						,'#0000CC'
						
				INSERT INTO sCommunication.tCircularTypeMaster
					   ([Id]
					   ,[Code]
					   ,[Title]
					   ,[IsObsolete]
					   ,[CreatedUserId]
					   ,[CreatedDateTime]
					   ,[UpdatedUserId]
					   ,[UpdatedDateTime]
					   ,[OrgGroupId]
					   ,HighlightColor)
				 SELECT
						 sCommon.fGetIntIdForOrg(2,@lOrgGroupId)
						,'Alert'
						,'Alert'
						,0
						,@lCreatedUserId
						,@lCreatedDateTime
						,@lCreatedUserId
						,@lCreatedDateTime
						,@lOrgGroupId
						,'#006600'



			INSERT INTO sCommon.tReligionMaster
					   ([Id]
					   ,[Code]
					   ,[Title]
					   ,[IsObsolete]
					   ,[CreatedUserId]
					   ,[CreatedDateTime]
					   ,[UpdatedUserId]
					   ,[UpdatedDateTime]
					   ,[OrgGroupId]
					    )
				 SELECT						
						sCommon.fGetIntIdForOrg(ID,@lOrgGroupId)
					   ,[Code]
					   ,[Title]
					   ,[IsObsolete]
					   ,[CreatedUserId]
					   ,[CreatedDateTime]
					   ,[UpdatedUserId]
					   ,[UpdatedDateTime]
					   ,@lOrgGroupId
					   FROM sCommon.tReligionMaster WHERE OrgGroupId = 1
						

	
					   
					   
 			
				INSERT INTO sAdmission.tInquiryStatusMaster
					   ([Id]
					   ,[Code]
					   ,[Title]
					   ,[IsObsolete]
					   ,[CreatedUserId]
					   ,[CreatedDateTime]
					   ,[UpdatedUserId]
					   ,[UpdatedDateTime]
					   ,[OrgGroupId]
					   ,StatusId)
				 SELECT
						 sCommon.fGetIntIdForOrg(Id,@lOrgGroupId)
						,Title
						,Title
						,0
						,1
						,getdate()
						,NULL
						,NULL
						,@lOrgGroupId
						,Id						
						FROM sCommon.tStatusMaster
						where statustypeId = 104
						
				 Insert Into sCommunication.tFeedbackAnswerTypeMaster
				(
						Id,
						Code,
						Title,
						IsObsolete,
						OrgGroupId,
						CreatedUserId,
						CreatedDateTime,
						UpdatedUserId,
						UpdatedDateTime,
						FeedBackAnswerGroupMasterId
				)
				Values
				(
						sCommon.fGetIntIdForOrg(1,@lOrgGroupId),
						'Numeric',
						'Numeric',
						0,
						@lOrgGroupId,
						@lCreatedUserId,
						@lCreatedDateTime,
						NULL,
						NULL,
						2
				)
						
				Insert Into sCommunication.tFeedbackAnswerTypeMaster
				(
						Id,
						Code,
						Title,
						IsObsolete,
						OrgGroupId,
						CreatedUserId,
						CreatedDateTime,
						UpdatedUserId,
						UpdatedDateTime,
						FeedBackAnswerGroupMasterId
				)
				Values
				(
						sCommon.fGetIntIdForOrg(2,@lOrgGroupId),
						'Free Text',
						'Free Text',
						0,
						@lOrgGroupId,
						@lCreatedUserId,
						@lCreatedDateTime,
						NULL,
						NULL,
						3
				)
						
	DECLARE @lMaxId int
	SET @lMaxId = sCommon.fGetIntIdForOrg(213,@lOrgGroupId)					
	EXECUTE sCommon.pTableRowIdModify @lOrgGroupId, @rTableTitle = 'sAdmission.tInquiryStatusMaster', @rCurrentNumber = @lMaxId
						
 
					   
		END
		ELSE
		BEGIN
			UPDATE sSetup.tOrgGroupMaster
			SET
				Title=@rTitle,
				PunchLine=@rPunchLine,
				CRMLicenceNo=@rCRMLicenceNo,
				IsWindowSupport=@rIsWindowSupport
				
			  WHERE Id = @rId 
	    END
	      
	  
	  
	  
	  IF NOT EXISTS(SELECT 1 FROM sCommon.tCastCategoryMaster WHERE OrgGroupId = @rCode)
BEGIN				
				INSERT INTO sCommon.tCastCategoryMaster
					   ([Id]
					   ,[Number]
					   ,[Code]
					   ,[Title]
					   ,[IsObsolete]
					   ,[CreatedUserId]
					   ,[CreatedDateTime]
					   ,[UpdatedUserId]
					   ,[UpdatedDateTime]
					   ,[OrgGroupId]
					   , MainCastCategoryId 
					   ,OrderIndex)
				 SELECT
						 sCommon.fGetIntIdForOrg(Id,@rCode)
						,Id	
						,Code
						,Title
						,0
						,1
						,getdate()
						,1
						,getdate()
						,@rCode
						,Id
						,Id						
						FROM sCommon.tMainCastCategoryMaster
						 
						
	DECLARE @lMaxCatId int
	SET @lMaxCatId = sCommon.fGetIntIdForOrg(100,@rCode)					
	EXECUTE sCommon.pTableRowIdModify @rCode, @rTableTitle = 'sCommon.tCastCategoryMaster', @rCurrentNumber = @lMaxCatId


			
			
END
	   

IF NOT EXISTS(SELECT 1 FROM sSetup.tBatchGroupMaster WHERE OrgGroupId = @rCode)
BEGIN				
				INSERT INTO sSetup.tBatchGroupMaster
					   ([Id]
					   ,[Number]
					   ,[Code]
					   ,[Title]					  
					   ,[CreatedUserId]
					   ,[CreatedDateTime]
					   ,[UpdatedUserId]
					   ,[UpdatedDateTime]
					   ,[OrgGroupId]					   
					   ,OrderIndex)
				 SELECT
						 sCommon.fGetIntIdForOrg(1,@rCode)
						,1	
						,'Common'
						,'Common'					
						,1
						,getdate()
						,1
						,getdate()
						,@rCode						 
						,1						
						 
						 
END						
	 


			
			

	      
	      SELECT @rCode AS Result	
		COMMIT TRANSACTION
		
		--  exec  [sCommon].[pOrganizationSetupAdd] @rId
		
	 
		
END
GO
PRINT N'Altering [sSetup].[pPortalExemptionTypeDetailAdd]...';


GO

 
 
ALTER PROCEDURE [sSetup].[pPortalExemptionTypeDetailAdd]
	
	@rStrXml nvarchar(MAX) 
	
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
	 EXEC sp_msforeachtable "ALTER TABLE ? NOCHECK CONSTRAINT all"
	 DELETE  FROM sFee.tExemptionTypeDetail 
	 
	 INSERT INTO sFee.tExemptionTypeDetail
		(
			ExemptionTypeId,
			FeeId,
			ExemptionPercentage
		 
			 
			)
		SELECT		
			 ExemptionTypeId,
			 FeeId,
			 ExemptionPercentage
			  
		FROM OPENXML (@loDoc, '/Table/ExemptionTypeDetail', 1)
		WITH ( 
				ExemptionTypeId int,
				FeeId int,
				 ExemptionPercentage decimal(8,2) 
			  )  
		--EXEC sp_msforeachtable "ALTER TABLE ? WITH CHECK CHECK CONSTRAINT all"
        SELECT 1 AS Result
	 END	
	
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sSetup].[pPortalFeeOptionalAdd]...';


GO
 
ALTER PROCEDURE [sSetup].[pPortalFeeOptionalAdd]
	
	@rStrXml nvarchar(MAX) ,
    @rDivisionId int,
	@rBatchId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET @rStrXml=REPLACE(@rStrXml,'&','AND')
DECLARE @loDoc INT,@lCount int 
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml
BEGIN
	 BEGIN TRY
	 BEGIN TRANSACTION 
	 BEGIN
	 
	 Delete from sFee.tFeeOptional Where BatchId=@rBatchId
	  INSERT INTO sFee.tFeeOptional
		(
			FeeSetupId,
			SourceTypeId,
			SourceId ,
			BatchId 
			)
		SELECT		
			A.FeeSetupId,
			A.SourceTypeId,
			A.SourceId ,
			A.BatchId 
		
		FROM OPENXML (@loDoc, '/Table/FeeOptional', 1)
		WITH ( 
				
			   FeeSetupId  int,
			SourceTypeId  int,
			SourceId bigint,
			BatchId int 
			  ) A
	INNER JOIN sStudent.tAcademic AB ON AB.Id=A.SourceId
	WHere AB.DivisionId=@rDivisionId
		
	 
        SELECT 1 AS Result
	  END	
	
	
		COMMIT TRANSACTION
		END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END
GO
PRINT N'Altering [sSetup].[pPortalReceiptAdd]...';


GO
 
ALTER PROCEDURE [sSetup].[pPortalReceiptAdd]
	
	@rStrXml nvarchar(MAX) ,
	@rDivisionID int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET @rStrXml=REPLACE(@rStrXml,'&','AND')
DECLARE @loDoc INT,@lCount int 
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml
BEGIN
	 BEGIN TRY
	 BEGIN TRANSACTION 
	 BEGIN 
		 
		
			
	 
			Update  sFee.tReceipt
			Set SourceTypeId=A.SourceTypeId,
			SourceId=A.SourceId,
			ReceiptNumber=A.ReceiptNumber,
			ReceiptDate=A.ReceiptDate,
			ReceiptAmount=A.ReceiptAmount,
			PayTypeId=A.PayTypeId,
			ChequeNo=A.ChequeNo,
			BankName=sSetup.fPortalXMLTagsReplaceReverse(A.BankName),
			ReceiptBookId=A.ReceiptBookId,
			Remark=sSetup.fPortalXMLTagsReplaceReverse(A.Remark),
			IsObsolete=A.IsObsolete ,
			BatchId=A.BatchId,
			OrgGroupBatchId=A.OrgGroupBatchId,
			CreatedUserId=A.CreatedUserId,
			CreatedDateTime=A.CreatedDateTime,
			TotalReceiptAmount=A.TotalReceiptAmount,
			DiscountAmount=A.DiscountAmount,
			IsChequeCleared=A.IsChequeCleared,
			ChequeClearDate=A.ChequeClearDate,
			ChequeDate=A.ChequeDate,
			FeeInvoiceId=A.FeeInvoiceId,
			CollectionGroupId=A.CollectionGroupId
			From  (
				SELECT		
					Id,
					SourceTypeId,
					SourceId ,
					ReceiptNumber,
					ReceiptDate,
					ReceiptAmount,
					PayTypeId,
					ChequeNo,
					BankName,
					ReceiptBookId,
					Remark,
					IsObsolete ,
					BatchId,
					OrgGroupBatchId,
					CreatedUserId,
					CreatedDateTime,
					TotalReceiptAmount,
					DiscountAmount,
					IsChequeCleared,
					ChequeClearDate,
					ChequeDate,
					FeeInvoiceId,
					CollectionGroupId
				 
				FROM OPENXML (@loDoc, '/Table/Receipt', 1)
				WITH ( 
						
					Id bigint,
					SourceTypeId smallint,
					SourceId bigint,
					ReceiptNumber int,
					ReceiptDate date,
					ReceiptAmount decimal(12, 2),
					PayTypeId tinyint,
					ChequeNo nvarchar(20),
					BankName nvarchar(200),
					ReceiptBookId int,
					Remark nvarchar(200),
					IsObsolete  bit,
					BatchId int,
					OrgGroupBatchId int,
					CreatedUserId bigint,
					CreatedDateTime datetime,
					TotalReceiptAmount decimal(12, 2),
					DiscountAmount decimal(12, 2),
					IsChequeCleared bit,
					ChequeClearDate date,
					ChequeDate date, 
					FeeInvoiceId bigint,
					CollectionGroupId int
					)  
			)A
			INNER JOIN sStudent.tAcademic FS On FS.Id=A.SourceId
			Where sFee.tReceipt.Id=A.Id AND FS.DivisionId=@rDivisionID
			 
		 
			INsert INTO sFee.tReceipt
			(
			Id,
					SourceTypeId,
					SourceId ,
					ReceiptNumber,
					ReceiptDate,
					ReceiptAmount,
					PayTypeId,
					ChequeNo,
					BankName,
					ReceiptBookId,
					Remark,
					IsObsolete ,
					BatchId,
					OrgGroupBatchId,
					CreatedUserId,
					CreatedDateTime,
					TotalReceiptAmount,
					DiscountAmount,
					IsChequeCleared,
					ChequeClearDate,
					ChequeDate,
					FeeInvoiceId,
					CollectionGroupId
			)
			SELECT		
					A.Id,
					A.SourceTypeId,
					A.SourceId ,
					A.ReceiptNumber,
					A.ReceiptDate,
					A.ReceiptAmount,
					A.PayTypeId,
					A.ChequeNo,
					sSetup.fPortalXMLTagsReplaceReverse(A.BankName),
					A.ReceiptBookId,
					sSetup.fPortalXMLTagsReplaceReverse(A.Remark),
					A.IsObsolete ,
					A.BatchId,
					A.OrgGroupBatchId,
					A.CreatedUserId,
					A.CreatedDateTime,
					A.TotalReceiptAmount,
					A.DiscountAmount,
					A.IsChequeCleared,
					A.ChequeClearDate,
					A.ChequeDate,
					A.FeeInvoiceId,
					A.CollectionGroupId
				 
				FROM OPENXML (@loDoc, '/Table/Receipt', 1)
				WITH ( 
						
					   Id bigint,
					SourceTypeId smallint,
					SourceId bigint,
					ReceiptNumber int,
					ReceiptDate date,
					ReceiptAmount decimal(12, 2),
					PayTypeId tinyint,
					ChequeNo nvarchar(20),
					BankName nvarchar(200),
					ReceiptBookId int,
					Remark nvarchar(200),
					IsObsolete  bit,
					BatchId int,
					OrgGroupBatchId int,
					CreatedUserId bigint,
					CreatedDateTime datetime,
					TotalReceiptAmount decimal(12, 2),
					DiscountAmount decimal(12, 2),
					IsChequeCleared bit,
					ChequeClearDate date,
					ChequeDate date, 
					FeeInvoiceId bigint,
					CollectionGroupId int
					)A
		INNER JOIN sStudent.tAcademic FS On fs.Id=A.SourceId
		LEFT JOIN sFee.tReceipt R ON R.Id=A.Id 
		Where FS.DivisionId=@rDivisionId   AND R.Id  IS NULL
		 
		 		
	  END	
	
	 SELECT 1 AS Result
		COMMIT TRANSACTION
		END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END
GO
PRINT N'Altering [sSetup].[pPortalReceiptDetailAdd]...';


GO
 
 
 
ALTER PROCEDURE [sSetup].[pPortalReceiptDetailAdd]
	
	@rStrXml nvarchar(MAX),
	@rDivisionId int
   
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET @rStrXml=REPLACE(@rStrXml,'&','AND')
DECLARE @loDoc INT,@lCount int 
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml
BEGIN
	  
	 
	 Update  sFee.tReceiptDetail
	 Set 
			ReceiptId=A.ReceiptId,
			FeeSetupId=A.FeeSetupId,
			Amount=A.Amount
	From
	(
	  SELECT		
			ReceiptId,
			FeeSetupId,
			Amount 
		
		FROM OPENXML (@loDoc, '/Table/ReceiptDetail', 1)
		WITH ( 
				
			   ReceiptId bigint,
				FeeSetupId int,
				Amount decimal(12, 2) 
			  ) 
	  )A 
	  INNER JOIN sFee.tReceipt RT ON RT.Id=A.ReceiptId
	  INNER JOIN sStudent.tAcademic AB ON RT.SourceId=AB.Id
	  
	   Where sFee.tReceiptDetail.ReceiptId=A.ReceiptId AND   sFee.tReceiptDetail.FeeSetupId=A.FeeSetupId AND AB.DivisionId=@rDivisionId
	     
	  INSERT INTO sFee.tReceiptDetail
		(
			ReceiptId,
			FeeSetupId,
			Amount 
			)
		SELECT		
			A.ReceiptId,
			A.FeeSetupId,
			A.Amount 
		
		FROM OPENXML (@loDoc, '/Table/ReceiptDetail', 1)
		WITH ( 
				
			   ReceiptId bigint,
				FeeSetupId int,
				Amount decimal(12, 2) 
			  )A
	INNER JOIN sFee.tReceipt RT ON RT.Id=A.ReceiptId
	INNER JOIN sStudent.tAcademic  AB On RT.SourceId=AB.Id
	LEFT JOIN sFee.tReceiptDetail R ON R.ReceiptId =A.ReceiptId AND R.FeeSetupId=A.FeeSetupId
	
	Where AB.DivisionId=@rDivisionID AND R.ReceiptId IS NULL
		 
        SELECT 1 AS Result
	   
END
GO
PRINT N'Altering [sSetup].[pPortalStudentMasterUpdate]...';


GO

ALTER PROCEDURE [sSetup].[pPortalStudentMasterUpdate]
	 
	
	@rStrXml [nvarchar](max),
	@rDivisionId int, 
	@rOrgGroupBatchId int,
	@rOrgGroupId 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	
	if Not Exists(SELECT A.Id FROM OPENXML (@loDoc, '/Table/StudentMaster', 1)
		WITH (Id bigint)A
		INNER JOIN   sStudent.tStudentMaster SM ON SM.Id =A.Id )
	BEGIN
		Declare @lStudCap int,@lOrgStudentCap int
		Select @lStudCap=ISNULL(NoOfStudent,0)+ISNULL(StudentExtraCap,0) from
		sSetup.tOrgGroupSetting Where OrgGroupId= @rOrgGroupId

		Select @lOrgStudentCap=[sSetup].[fStudentCapGet](@rOrgGroupBatchId)
		IF(@lOrgStudentCap >= @lStudCap )
		BEGIN
			Select -111 AS RESULT 
			Return
		END
	END
	UPDATE sStudent.tStudentMaster
		SET
			Code = A.Code,
			Number = A.Number,
			FirstName = sSetup.fPortalXMLTagsReplaceReverse(A.FirstName),
			MiddleName = sSetup.fPortalXMLTagsReplaceReverse(A.MiddleName),
			LastName = sSetup.fPortalXMLTagsReplaceReverse(A.LastName),
			OrgId = A.OrgId,
			StatusId = A.StatusId,
			RecordStatusId = A.RecordStatusId,
			UpdatedUserId = A.UpdatedUserId,
			CreatedDateTime = A.CreatedDateTime,
			UpdatedDateTime = A.UpdatedDateTime,
			ReferenceSourceId = A.ReferenceSourceId,
			AdmissionCategoryId = A.AdmissionCategoryId,
			RegistrationNumber = A.RegistrationNumber,
			IsBlackList = A.IsBlackList,
			BlackListReason = sSetup.fPortalXMLTagsReplaceReverse(A.BlackListReason),
			SUId = A.SUId
		 FROM
		 (
		SELECT		
			Id,
			Code,
			Number,
			FirstName,
			MiddleName,
			LastName,
			OrgId,
			StatusId,
			RecordStatusId,
			UpdatedUserId,
			CreatedDateTime,		
			UpdatedDateTime,
			ReferenceSourceId,
			AdmissionCategoryId,
			RegistrationNumber,
			IsBlackList,
			BlackListReason,
			SUId
						
		FROM OPENXML (@loDoc, '/Table/StudentMaster', 1)
		WITH ( 
				Id bigint,
				Code nvarchar(20),
				Number bigint,					
				FirstName nvarchar(100),
				MiddleName nvarchar(100),
				LastName nvarchar(100),
				OrgId smallint,
				StatusId smallint,
				RecordStatusId smallint,
				UpdatedUserId bigint,
				CreatedDateTime DateTime,
				UpdatedDateTime DateTime,
				ReferenceSourceId bigint,
				AdmissionCategoryId int,
				RegistrationNumber nvarchar(20),
				IsBlackList bit,
				BlackListReason nvarchar(100),
				SUId nvarchar(20)
			  )) A
			  WHERE sStudent.tStudentMaster.Id = A.Id
		
		
		
		 INSERT INTO sStudent.tStudentMaster
		(
			Id,
			Code,
			Number,
			FirstName,
			MiddleName,
			LastName,
			OrgId,
			StatusId,
			RecordStatusId,
			CreatedUserId,
			UpdatedUserId,
			CreatedDateTime,
			UpdatedDateTime,
			ReferenceSourceId,
			AdmissionCategoryId,
			RegistrationNumber,
			IsBlackList,
			BlackListReason,
			SUId
			)
		SELECT		
			A.Id,
			A.Code,
			A.Number,
			sSetup.fPortalXMLTagsReplaceReverse(A.FirstName),
			sSetup.fPortalXMLTagsReplaceReverse(A.MiddleName),
			sSetup.fPortalXMLTagsReplaceReverse(A.LastName),
			A.OrgId,
			A.StatusId,
			A.RecordStatusId,
			A.CreatedUserId,
			A.UpdatedUserId,		
			A.CreatedDateTime,
			A.UpdatedDateTime,
			A.ReferenceSourceId,
			A.AdmissionCategoryId,
			A.RegistrationNumber,
			A.IsBlackList,
			sSetup.fPortalXMLTagsReplaceReverse(A.BlackListReason),
			A.SUId
						
		FROM OPENXML (@loDoc, '/Table/StudentMaster', 1)
		WITH ( 
				Id bigint,
				Code nvarchar(20),
				Number bigint,					
				FirstName nvarchar(100),
				MiddleName nvarchar(100),
				LastName nvarchar(100),
				OrgId smallint,
				StatusId smallint,
				RecordStatusId smallint,
				CreatedUserId bigint,
				UpdatedUserId bigint,
				CreatedDateTime DateTime,
				UpdatedDateTime DateTime,
				ReferenceSourceId bigint,
				AdmissionCategoryId int,
				RegistrationNumber nvarchar(20),
				IsBlackList bit,
				BlackListReason nvarchar(100),
				SUId nvarchar(20)
			  ) A LEFT JOIN sStudent.tStudentMaster S
			  ON A.Id = S.Id WHERE S.Id IS NULL
		
		 EXEC sp_xml_removedocument @loDoc
        SELECT 1 AS Result
	 END	
	
	END TRY
	
	BEGIN CATCH 
		
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sStudent].[pImportStudent]...';


GO


ALTER PROCEDURE [sStudent].[pImportStudent]
    
    @rOrgGroupId smallint,
    @rOrgId smallint,
	@rXmldoc [nvarchar](max),
	@rUserId bigint,
	@rBatchId int,
	@rOrgGroupBatchId int
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
BEGIN TRY

DECLARE @lCount INT
DECLARE @lInterrorCode INT,
			@intDoc INT,
			@lCode nvarchar(20),
			@lNumber bigint,
			@lRegistrationNumber nvarchar(20),
			@lFirstName nvarchar(100),
			@lMiddleName nvarchar(100),
			@lLastName nvarchar(100),
			@lClassId int,
			@lClass nvarchar(100),
			@lDivisionId int,
			@lDivision nvarchar(100),
			@lRollNo int,
			@lAdmissionStandardId int,
			@lAdmissionStandard nvarchar(100),
			@lAdmissionDate date,
			@lPreviousSchool nvarchar(200),
			@lDOB date,
			@lGenderId int = 0,
			@lGender nvarchar(10),
			@lBloodGroupId int = 0,
			@lBloodGroup nvarchar(10),
			@lAdmissionCategoryId int,
			--@lAdmissionCategory nvarchar(100),
			@lReligionId int,
			@lReligion nvarchar(100),
			@lFamilyCast nvarchar(100),
			@lFamilySubCast nvarchar(100),
			@lCastCategoryId int = 0,
			@lCastCategory nvarchar(100),
			@lParentContactNo nvarchar(20),
			@lParentEmail nvarchar(50),
			@lStudentContactNo nvarchar(20),
			@lStudentEmail nvarchar(50),
			@lPresentStreetOne nvarchar(150),
			@lPresentStreetTwo nvarchar(150),
			@lPresentStreetThree nvarchar(150),
			@lPresentCity nvarchar(50),
			@lPresentZipCode nvarchar(20),
			@lPresentState nvarchar(50),
			@lPresentCountry nvarchar(50),
			@lPresentContactNo nvarchar(20),
			--@lEmergencyStreetOne nvarchar(50),
			--@lEmergencyStreetTwo nvarchar(50),
			--@lEmergencyStreetThree nvarchar(50),
			--@lEmergencyCountry nvarchar(50),
			--@lEmergencyState nvarchar(50),
			--@lEmergencyCity nvarchar(50),
			--@lEmergencyZipCode nvarchar(20),
			@lEmergencyContactNo nvarchar(20),
			@lBirthPlace nvarchar(150),
			@lBirthTaluka nvarchar(150),
			@lBirthDistrict nvarchar(150),
			@lBirthDateInWord nvarchar(150),
			@lHouseId int,
			@lHouse nvarchar(100),
			--@lMotherTongueId int,
			@lMotherTongue nvarchar(100),
			@lAdhaarNumber nvarchar(20),
			@lUIDNumber nvarchar(50),
			@lQuotaId int,
			@lQuota nvarchar(100),
			-- New Add
			@lSUId nvarchar(20),
			@lLeftStandardId int,
			@lLeftStandard nvarchar(100),
			@lLeftDate date,
			@lLCNumber nvarchar(20),
			@lLCDate date,
			@lLCReason nvarchar(200) ,
			@lLCProgress nvarchar(200) ,
            @lLCConduct nvarchar(200) ,
            @lLCRemark nvarchar(200),
            @lStatusId smallint,
            @lBirthState nvarchar(100),
            @lBirthCountry nvarchar(100)


			
			
DECLARE @EmployeeId bigint			
--DECLARE @OutClassId int
--DECLARE @OutDivisionId int
DECLARE @OutStudentId bigint 
--DECLARE @OutAdmissionStandardId int
--DECLARE @OutReligionId int
--DECLARE @OutAdmissionCategoryId int		
SET @lAdmissionCategoryId=sCommon.fGetIntIdForOrg(1,@rOrgGroupId)	
 
						
EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc
	
	CREATE TABLE #tTable  
	(
		Id bigint identity,	 
		Code nvarchar(20),
		Number bigint,
		RegistrationNumber nvarchar(20),
		FirstName nvarchar(100),
		MiddleName nvarchar(100),
		LastName nvarchar(100),
		ClassId int null,
		Class nvarchar(100),
		DivisionId int null,
		Division nvarchar(100),
		RollNo int,
		AdmissionStandardId int,
		AdmissionStandard nvarchar(100),
		AdmissionDate date,
		PreviousSchool nvarchar(200),
		DOB date,
		GenderId int null,
		Gender nvarchar(10),
		BloodGroupId int null,
		BloodGroup nvarchar(10),
		ReligionId int,
		Religion nvarchar(100),
		--AdmissionCategoryId int,
		--AdmissionCategory nvarchar(100),
		FamilyCast nvarchar(100),
		FamilySubCast nvarchar(100),
		CastCategoryId int,
		CastCategory nvarchar(100),
		ParentContactNo nvarchar(20),
		ParentEmail nvarchar(50),
		StudentContactNo nvarchar(20),
		StudentEmail nvarchar(50),
		PresentStreetOne nvarchar(150),
		PresentStreetTwo nvarchar(150),
		PresentStreetThree nvarchar(150),
		PresentCity nvarchar(50),
		PresentZipCode nvarchar(20),
		PresentState nvarchar(50),
		PresentCountry nvarchar(50),
		PresentContactNo nvarchar(20),
		--EmergencyStreetOne nvarchar(50),
		--EmergencyStreetTwo nvarchar(50),
		--EmergencyStreetThree nvarchar(50),
		--EmergencyCountry nvarchar(50),
		--EmergencyState nvarchar(50),
		--EmergencyCity nvarchar(50),
		--EmergencyZipCode nvarchar(20),
		EmergencyContactNo nvarchar(20),
		BirthPlace nvarchar(150),
		BirthTaluka nvarchar(150),
		BirthDistrict nvarchar(150),
		BirthDateInWord nvarchar(150),
		CreatedUserId bigint,
		HouseId int,
		House nvarchar(100),
		MotherTongueId int,
		MotherTongue nvarchar(100),
		AdhaarNumber nvarchar(20),
		UIDNumber nvarchar(20),
		QuotaId int,
		Quota nvarchar(100),
		SUId nvarchar(20),
		LeftStandardId int,
		LeftStandard nvarchar(100),
		LeftDate date,
		LCNumber nvarchar(20),
		LCDate date,
		LCReason nvarchar(200) ,
		LCProgress nvarchar(200) ,
        LCConduct nvarchar(200) ,
        LCRemark nvarchar(200),
        StatusId smallint,
        BirthState nvarchar(100),
        BirthCountry Nvarchar(100)
	)
		
	INSERT INTO #tTable
	(
		Code,
		Number,
		RegistrationNumber,
		FirstName,
		MiddleName,
		LastName,
		ClassId,
		Class,
		DivisionId,
		Division,
		RollNo,
		AdmissionStandardId,
		AdmissionStandard,
		AdmissionDate,
		PreviousSchool,
		DOB,
		GenderId,
		Gender,
		BloodGroupId,
		BloodGroup,
		ReligionId,
		Religion,
		--AdmissionCategoryId,
		--AdmissionCategory,
		FamilyCast,
		FamilySubCast,
		CastCategoryId,
		CastCategory,
		ParentContactNo,
		ParentEmail,
		StudentContactNo,
		StudentEmail,
		PresentStreetOne,
		PresentStreetTwo,
		PresentStreetThree,
		PresentCity,
		PresentZipCode,
		PresentState,
		PresentCountry,
		PresentContactNo,
		--EmergencyStreetOne,
		--EmergencyStreetTwo,
		--EmergencyStreetThree,
		--EmergencyCountry,
		--EmergencyState,
		--EmergencyCity,
		--EmergencyZipCode,
		EmergencyContactNo,
		BirthPlace,
		BirthTaluka,
		BirthDistrict,
		BirthDateInWord,
		CreatedUserId,
		HouseId,
		House,
		MotherTongueId,
		MotherTongue,
		AdhaarNumber,
		UIDNumber,
		QuotaId,
		Quota,
		SUId,
		LeftStandardId,
		LeftStandard,
		LeftDate,
		LCNumber,
		LCDate,
		LCReason,
		LCProgress,
        LCConduct,
        LCRemark,
        StatusId,
        BirthState,
        BirthCountry
	)
	SELECT
	 
		Code,
		Number,
		RegistrationNumber,
		FirstName,
		MiddleName,
		LastName,
		0,
		Class,
		0,
		Division,
		RollNo,
		0,
		AdmissionStandard,
		AdmissionDate,
		PreviousSchool,
		DOB,
		0,
		Gender,
		0,
		BloodGroup,
		0,
		Religion,
		--0,
		--AdmissionCategory,
		FamilyCast,
		FamilySubCast,
		0,
		CastCategory,
		ParentContactNo,
		ParentEmail,
		StudentContactNo,
		StudentEmail,
		PresentStreetOne,
		PresentStreetTwo,
		PresentStreetThree,
		PresentCity,
		PresentZipCode,
		PresentState,
		PresentCountry,
		PresentContactNo,
		--EmergencyStreetOne,
		--EmergencyStreetTwo,
		--EmergencyStreetThree,
		--EmergencyCountry,
		--EmergencyState,
		--EmergencyCity,
		--EmergencyZipCode,
		EmergencyContactNo,
		BirthPlace,
		BirthTaluka,
		BirthDistrict,
		BirthDateInWord,
		CreatedUserId,
		0,
		House,
		0,
		MotherTongue,
		AdhaarNumber,
		UIDNumber,
		0,
		Quota,
		SUId,
		0,
		LeftStandard,
		LeftDate,
		LCNumber,
		LCDate,
		LCReason,
		LCProgress,
        LCConduct,
        LCRemark,
        StatusId,
        BirthState,
        BIrthCountry
			
	FROM OPENXML (@intDoc, '/Table/ImportStudent', 1)
	WITH
	( 
		Code nvarchar(20) '@Code',
		Number bigint '@Number',
		RegistrationNumber nvarchar(20) '@RegistrationNumber',
		FirstName nvarchar(100) '@FirstName',
		MiddleName nvarchar(100) '@MiddleName',
		LastName nvarchar(100) '@LastName',
		Class nvarchar(100) '@Class',
		Division nvarchar(100) '@Division',
		RollNo int '@RollNo',
		AdmissionStandard nvarchar(100) '@AdmissionStandard',
		AdmissionDate date '@AdmissionDate',
		PreviousSchool nvarchar(200) '@PreviousSchool',
		DOB date '@DOB',
		Gender nvarchar(10) '@Gender',
		BloodGroup nvarchar(10) '@BloodGroup', 			
		Religion nvarchar(100) '@Religion',
		--AdmissionCategory nvarchar(100) '@AdmissionCategory',
		FamilyCast nvarchar(100) '@FamilyCast',
		FamilySubCast nvarchar(100) '@FamilySubCast',
		CastCategory nvarchar(100) '@CastCategory',
		ParentContactNo nvarchar(20) '@ParentContactNo',
		ParentEmail nvarchar(50) '@ParentEmail',
		StudentContactNo nvarchar(20) '@StudentContactNo',
		StudentEmail nvarchar(50) '@StudentEmail',
		PresentStreetOne nvarchar(150) '@PresentStreetOne',
		PresentStreetTwo nvarchar(150) '@PresentStreetTwo',
		PresentStreetThree nvarchar(150) '@PresentStreetThree',
		PresentCity nvarchar(50) '@PresentCity',
		PresentZipCode nvarchar(20) '@PresentZipCode',
		PresentState nvarchar(50) '@PresentState',
		PresentCountry nvarchar(50) '@PresentCountry',
		PresentContactNo nvarchar(20) '@PresentContactNo',
		--EmergencyStreetOne nvarchar(50) '@EmergencyStreetOne',
		--EmergencyStreetTwo nvarchar(50) '@EmergencyStreetTwo',
		--EmergencyStreetThree nvarchar(50) '@EmergencyStreetThree',
		--EmergencyCountry nvarchar(50) '@EmergencyCountry',
		--EmergencyState nvarchar(50) '@EmergencyState',
		--EmergencyCity nvarchar(50) '@EmergencyCity',
		--EmergencyZipCode nvarchar(20) '@EmergencyZipCode',
		EmergencyContactNo nvarchar(20) '@EmergencyContactNo',
		 
		BirthPlace nvarchar(150) '@BirthPlace',
		BirthTaluka nvarchar(150) '@BirthTaluka',
		BirthDistrict nvarchar(150) '@BirthDistrict',		
		BirthDateInWord nvarchar(150) '@BirthDateInWord',
		CreatedUserId bigint '@CreatedUserId',
		House nvarchar(100) '@House',
		MotherTongue nvarchar(100) '@MotherTongue',
		AdhaarNumber nvarchar(20) '@AdhaarNumber',
		UIDNumber nvarchar(20) '@UIDNumber',
		Quota nvarchar(20) '@Quota',
		SUId nvarchar(20) '@SUId',
		LeftStandard nvarchar(100) '@LeftStandard',
		LeftDate date '@LeftDate',
		LCNumber nvarchar(20) '@LCNumber',
		LCDate date '@LCDate',
		LCReason nvarchar(200) '@LCReason',
		LCProgress nvarchar(200) '@LCProgress',
        LCConduct nvarchar(200) '@LCConduct',
        LCRemark nvarchar(200) '@LCRemark',
        StatusId smallint '@StatusId',
        BirthState nvarchar(100) '@BirthState',
        BirthCountry nvarchar(100) '@BirthCountry'
	)
	
	--print 'check'
 
EXEC sp_xml_removedocument @intDoc
			
SELECT @lCount =  COUNT(Id) FROM #tTable

WHILE @lCount > 0 

BEGIN
		SET @lCode = ''
		SET @lNumber = null
		SET @lRegistrationNumber = null
		SET @lFirstName = ''
		SET @lMiddleName = ''
		SET @lLastName = ''
		SET @lClassId = null
		SET @lClass = ''
		SET @lDivisionId = null
		SET @lDivision = ''
		SET @lRollNo = null
		SET @lAdmissionStandardId = null
		SET @lAdmissionStandard = ''
		SET @lAdmissionDate  = ''
		SET @lPreviousSchool = ''
		SET @lDOB = ''
		SET @lGenderId = null
		SET @lGender = ''
		SET @lBloodGroupId = null
		SET @lBloodGroup = ''
		SET @lReligionId  = null
		SET @lReligion = ''
		--SET @lAdmissionCategoryId  = null
		--SET @lAdmissionCategory = ''
		SET @lFamilyCast = ''
		SET @lFamilySubCast = ''
		SET @lCastCategoryId  = null
		SET @lCastCategory = ''
		SET @lParentContactNo = ''
		SET @lParentEmail = ''
		SET @lStudentContactNo = ''
		SET @lStudentEmail = ''
		SET @lPresentStreetOne = ''
		SET @lPresentStreetTwo = ''
		SET @lPresentStreetThree = ''
		SET @lPresentCity = ''
		SET @lPresentZipCode = ''
		SET @lPresentState = ''
		SET @lPresentCountry = ''
		SET @lPresentContactNo = ''
		--SET @lEmergencyStreetOne = ''
		--SET @lEmergencyStreetTwo = ''
		--SET @lEmergencyStreetThree = ''
		--SET @lEmergencyCountry = ''
		--SET @lEmergencyState = ''
		--SET @lEmergencyCity = ''
		--SET @lEmergencyZipCode = ''
		SET @lEmergencyContactNo = ''
		SET @lBirthPlace = ''
		SET @lBirthTaluka = ''
		SET @lBirthDistrict = ''
		SET @lBirthDateInWord = ''
		--SET @OutClassId = null
		--SET @OutDivisionId = null
		SET @OutStudentId = null
		--SET @OutAdmissionStandardId = null
		--SET @OutReligionId = null,
		SET @lHouseId=NULL
		SET	@lHouse=''
		--SET @lMotherTongueId=NULL
		SET	@lMotherTongue=''
		SET	@lAdhaarNumber=''
		SET @lUIDNumber=''
		SET @lQuotaId = NULL
		SET	@lQuota =''
		SET	@lSUId =''
		SET	@lLeftStandardId=NULL
		SET	@lLeftStandard = ''
		SET	@lLeftDate = ''
		SET	@lLCNumber = ''
		SET	@lLCDate = ''
		SET	@lLCReason = ''
		SET	@lLCProgress = ''
        SET	@lLCConduct = ''
        SET	@lLCRemark = ''
        SET @lStatusId = NULL 
        Set @lBirthState ='' 
        Set @lBirthCountry =''
		
SELECT		
		@lCode = Code,
		@lNumber=Number,
		@lRegistrationNumber = RegistrationNumber,
		@lFirstName = FirstName,
		@lMiddleName = MiddleName,
		@lLastName = LastName,
		@lClass = Class,
		@lDivision = Division,
		@lRollNo = RollNo,
		@lAdmissionStandard = AdmissionStandard,
		@lAdmissionDate  = CASE WHEN AdmissionDate = '' THEN  NULL ELSE AdmissionDate END,
		@lPreviousSchool = PreviousSchool,
		@lReligion = Religion,
		--@lAdmissionCategory = AdmissionCategory,
		@lFamilyCast = FamilyCast,
		@lFamilySubCast = FamilySubCast,
		@lCastCategory = CastCategory,
		@lDOB = CASE WHEN DOB = '' THEN  NULL ELSE DOB END,
		@lGender = Gender,
		@lBloodGroup = BloodGroup,
		@lParentContactNo = ParentContactNo,
		@lParentEmail = ParentEmail,
		@lStudentContactNo = StudentContactNo,
		@lStudentEmail = StudentEmail,
		@lPresentStreetOne = PresentStreetOne,
		@lPresentStreetTwo = PresentStreetTwo,
		@lPresentStreetThree = PresentStreetThree,
		@lPresentCountry = PresentCountry,
		@lPresentState = PresentState,
		@lPresentCity = PresentCity,
		@lPresentZipCode = PresentZipCode,
		@lPresentContactNo = PresentContactNo,
		--@lEmergencyStreetOne = EmergencyStreetOne,
		--@lEmergencyStreetTwo = EmergencyStreetTwo,
		--@lEmergencyStreetThree = EmergencyStreetThree,
		--@lEmergencyCountry = EmergencyCountry,
		--@lEmergencyState = EmergencyState,
		--@lEmergencyCity = EmergencyCity,
		--@lEmergencyZipCode = EmergencyZipCode,
		@lEmergencyContactNo = EmergencyContactNo,		 
		@lBirthPlace = BirthPlace,
		@lBirthTaluka = BirthTaluka,
		@lBirthDistrict = BirthDistrict,
		@lBirthDateInWord = BirthDateInWord,
		@lHouse = House,
		@lMotherTongue = MotherTongue,
		@lAdhaarNumber = AdhaarNumber,
		@lUIDNumber = UIDNumber,
		@lSUId = SUId,
		@lLeftStandard = LeftStandard,
		@lLeftDate = CASE WHEN LeftDate = '' THEN  NULL ELSE LeftDate END,
		@lLCNumber = LCNumber,
		@lLCDate = CASE WHEN LCDate = '' THEN  NULL ELSE LCDate END,
		@lLCReason = LCReason,
		@lLCProgress = LCProgress,
        @lLCConduct = LCConduct,
        @lLCRemark = LCRemark,
        @lStatusId = StatusId,
        @lBirthState = BirthState,
        @lBirthCountry = BirthCountry
											 	 
FROM #tTable WHERE Id = @lCount  

	SELECT	@lGenderId = ID FROM sCommon.tGenderMaster WHERE Title = @lGender
	SELECT	@lLeftStandardId  = ID FROM sSetup.tClassMaster WHERE Title = @lLeftStandard AND OrgId = @rOrgId
	SELECT	@lClassId  = ID FROM sSetup.tClassMaster WHERE Title = @lClass AND OrgId = @rOrgId
	SELECT	@lDivisionId  = ID FROM sSetup.tDivisionMaster WHERE Title = @lDivision AND ClassId=@lClassId AND OrgId = @rOrgId
	SELECT	@lBloodGroupId  = ID FROM sCommon.tBloodGroupMaster WHERE Title = @lBloodGroup
	SELECT	@lAdmissionStandardId  = ID FROM sSetup.tClassMaster WHERE Title = @lAdmissionStandard AND OrgId = @rOrgId
	SELECT	@lReligionId  = ID FROM sCommon.tReligionMaster WHERE Title = @lReligion AND OrgGroupId = @rOrgGroupId
	--SELECT	@lAdmissionCategoryId  = ID FROM tAdmissionCategoryMaster WHERE Title = @lAdmissionCategory AND OrgGroupId = @rOrgGroupId
	SELECT	@lCastCategoryId  = ID FROM sCommon.tCastCategoryMaster WHERE Title = @lCastCategory AND OrgGroupId = @rOrgGroupId	
	SELECT	@lHouseId  = ID FROM sActivity.tHouseMaster WHERE Title = @lHouse AND OrgId = @rOrgId
	SELECT	@lQuotaId  = ID FROM sCommon.tQuotaMaster WHERE Title = @lQuota AND OrgGroupId = @rOrgGroupId	
	--SELECT	@lMotherTongueId  = ID FROM sCommon.tMotherTongueMaster WHERE Title = @lMotherTongue
	
	IF(@lGenderId IS NULL)
		SET @lGenderId = 0
	IF(@lBloodGroupId IS NULL)
		SET	@lBloodGroupId = 0
	IF(@lCastCategoryId IS NULL)
		SET	@lCastCategoryId = 0
	IF(@lHouseId IS NULL)
		SET	@lHouseId = 0
	IF(@lQuotaId IS NULL)
		SET	@lQuotaId = 0	
	--IF(@lMotherTongueId IS NULL)
	--	SET	@lMotherTongueId = 0		
		
--IF 	@lClassId IS NULL  AND @lClass != ''
--BEGIN
--	EXEC [sSetup].[pClassMasterAdd] 0,@lClass,@lClass,@lClass,@lClass,1,0,0,0,@rUserId,@rUserId,@rOrgId,@OutClassId OUTPUT
-- END
--ELSE
--BEGIN
--SET @OutClassId = @lClassId
--END

--IF 	@lAdmissionStandardId IS NULL  AND @lAdmissionStandard != ''
--BEGIN
--	EXEC [sSetup].[pClassMasterAdd] 0,@lAdmissionStandard,@lAdmissionStandard,@lAdmissionStandard,@lAdmissionStandard,1,0,0,0,@rUserId,@rUserId,@rOrgId,0,@OutAdmissionStandardId OUTPUT
-- END
--ELSE
--BEGIN
--SET @OutAdmissionStandardId = @lAdmissionStandardId
--END

--IF 	@lDivisionId IS NULL  AND @lDivision != ''
--BEGIN
--	SET @EmployeeId = sCommon.fGetBigIntIdForOrg(1,@rOrgId)
--	EXEC [sSetup].[pDivisionMasterAdd] 0,@lDivision,@lDivision,@lDivision,@lClassId,@EmployeeId,NULL,0,@rUserId,@rUserId,0,@rOrgId,@OutDivisionId OUTPUT
-- END
--ELSE
--BEGIN
--SET @OutDivisionId = @lDivisionId
--END

--IF 	@lReligionId IS NULL  AND @lReligion != ''
--BEGIN
--	EXEC [sCommon].[pReligionMasterAdd] 0,@lReligion,@lReligion,0,@rUserId,@rOrgId,@OutReligionId OUTPUT
-- END
--ELSE
--BEGIN
--SET @OutReligionId = @lReligionId
--END

--IF 	@lAdmissionCategoryId IS NULL  AND @lAdmissionCategory != ''
--BEGIN
--	EXEC [sStudent].[pAdmissionCategoryMasterAdd] 0,@lAdmissionCategory,@lAdmissionCategory,0,@rUserId,@rOrgId,@OutAdmissionCategoryId OUTPUT
-- END
--ELSE
--BEGIN
--SET @OutAdmissionCategoryId = @lAdmissionCategoryId
--END
 
BEGIN TRANSACTION

Declare @lStudCap int,@lOrgStudentCap int
Select @lStudCap=ISNULL(NoOfStudent,0)+ISNULL(StudentExtraCap,0) from
sSetup.tOrgGroupSetting Where OrgGroupId= @rOrgGroupId

Select @lOrgStudentCap=[sSetup].[fStudentCapGet](@rOrgGroupBatchId)
 
IF(@lOrgStudentCap >= @lStudCap )
BEGIN
	Select -111 AS RESULT 
	COMMIT TRANSACTION			
	Return
END


IF(@lStatusId=1)
	EXEC sStudent.pStudentMasterAdd 0,@lCode,@lRegistrationNumber,@lNumber,@lFirstName,@lMiddleName,@lLastName,@rOrgId,@lAdmissionCategoryId,1,502,@rUserId,@rUserId,@OutStudentId,@rOrgGroupBatchId OUTPUT,@lSUId
ELSE
	EXEC sStudent.pStudentMasterAdd 0,@lCode,@lRegistrationNumber,@lNumber,@lFirstName,@lMiddleName,@lLastName,@rOrgId,@lAdmissionCategoryId,3,502,@rUserId,@rUserId,@OutStudentId,@rOrgGroupBatchId OUTPUT,@lSUId

EXEC sStudent.pAcademicAdd 0,@OutStudentId,@lClassId,@lDivisionId,@lRollNo,@rOrgId,@rBatchId,@rUserId,@rUserId

EXEC sStudent.pStudentCommunicationAdd @OutStudentId,@lPresentStreetOne,@lPresentStreetTwo,@lPresentStreetThree,
			@lPresentCountry,@lPresentState,@lPresentCity,@lPresentZipCode,@lPresentContactNo,NULL,NULL,NULL,NULL,NULL,
			NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,@lEmergencyContactNo,@lParentContactNo,@lParentEmail,
			@lStudentContactNo,@lStudentEmail,@rUserId,@rUserId

EXEC sStudent.pStudentOtherAdd @OutStudentId,@lUIDNumber,@lDOB,@lGenderId,@lReligionId,@lBloodGroupId,@lBirthPlace,@lBirthTaluka,@lBirthDistrict,@lBirthDateInWord,
			@lFamilyCast,@lFamilySubCast,@lCastCategoryId,NULL,@lHouseId,NULL,NULL,'',@rUserId,@rUserId,'',@lAdhaarNumber,@lMotherTongue,@lQuotaId

IF(@lStatusId=1)		
	EXEC [sStudent].[pStudentAdmissionAdd] @OutStudentId,@lPreviousSchool,NULL,NULL,NULL,NULL,
			@lAdmissionStandardId,@lAdmissionDate,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,
			NULL,NULL,NULL,NULL,NULL,@rBatchId,@rUserId,@rUserId,1
ELSE
	EXEC [sStudent].[pStudentAdmissionAdd] @OutStudentId,@lPreviousSchool,NULL,NULL,NULL,NULL,
			@lAdmissionStandardId,@lAdmissionDate,NULL,@lLeftStandardId,@lLeftDate,NULL,NULL,NULL,@lLCReason,@lLCProgress,@lLCConduct,NULL,
			@lLCNumber,@lLCDate,@lLCRemark,NULL,NULL,@rBatchId,@rUserId,@rUserId,0
			

		SET @lCount = @lCount - 1	
		COMMIT TRANSACTION			
END


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


GO
ALTER PROCEDURE [sStudent].[pImportStudentOldDetail]
 
	@rXmldoc [nvarchar](max) ,
	@rOrgGroupId int = 0,
	@rOrgGroupBatchId int  = 0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
DECLARE @lCount INT
DECLARE @lStudentId bigINT,
		@intDoc INT,    
        @lSSCBoard nvarchar(150),
        @lSSCSchool nvarchar(100),
        @lSSCPassingYear nvarchar(100),
        @lSSCObtainMarks decimal(10,2),
        @lSSCOutOfMarks decimal(10,2),
        @lSSCPercentage decimal(10,2),
        @lSSCMathMarks decimal(10,2),
        @lSSCMathOutOfMarks decimal(10,2),
        @lHSCBoard nvarchar(100),
        @lHSCSchool nvarchar(100),
        @lHSCPassingYear nvarchar(10),
        @lHSCObtainMarks decimal(10,2),
        @lHSCOutOfMarks decimal(10,2),
        @lHSCPercentage decimal(10,2),
        @lHSCPhysicsMarks decimal(10,2),
        @lHSCPhysicsOutOfMarks decimal(10,2),
        @lHSCChemistryMarks decimal(10,2),
        @lHSCChemistryOutOfMarks decimal(10,2),
        @lHSCMathMarks decimal(10,2),
        @lHSCMathOutOfMarks decimal(10,2),
        @lHSCBiologyMarks decimal(10,2),
        @lHSCBiologyOutOfMarks decimal(10,2),
        @lPCMMarks decimal(10,2),
        @lPCBMarks decimal(10,2),
        @lJEERollNo nvarchar(20),
        @lJEEMeritNo nvarchar(20),
        @lJEEMeritMarks decimal(10,2),
        @lJEEOutOfMarks decimal(10,2),
        @lDiplomaBoard nvarchar(200),
        @lDiplomaCollege nvarchar(200),
        @lDiplomaPassingYear nvarchar(10),
        @lDiplomaObtainMarks decimal(10,2),
        @lDiplomaOutOfMarks decimal(10,2),
        @lDiplomaPercentage decimal(10,2),
         @lInterrorCode INT
 Declare @lStudCap int,@lOrgStudentCap int       
EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc
   
  
  CREATE TABLE #tTable1 
 (
		Id Bigint Identity,
		StudentId bigint  ,
        SSCBoard nvarchar(200),
        SSCSchool nvarchar(200),
        SSCPassingYear nvarchar(10),
        SSCObtainMarks decimal(10,2),
        SSCOutOfMarks decimal(10,2),
        SSCPercentage decimal(10,2),
        SSCMathMarks decimal(10,2),
        SSCMathOutOfMarks decimal(10,2),
        HSCBoard nvarchar(200),
        HSCSchool  nvarchar(200),
        HSCPassingYear nvarchar(20),
		HSCObtainMarks decimal(10,2),
		 HSCOutOfMarks decimal(10,2),
		 HSCPercentage decimal(10,2),
		 HSCPhysicsMarks decimal(10,2),
		 HSCPhysicsOutOfMarks decimal(10,2),
		 HSCChemistryMarks decimal(10,2),
		 HSCChemistryOutOfMarks decimal(10,2),
		 HSCMathMarks decimal(10,2),
		 HSCMathOutOfMarks decimal(10,2),
		 HSCBiologyMarks decimal(10,2),
		 HSCBiologyOutOfMarks decimal(10,2),
		 PCMMarks decimal(10,2),
		 PCBMarks  decimal(10,2),
		 JEERollNo nvarchar(20),
		 JEEMeritNo nvarchar(20),
		 JEEMeritMarks decimal(10,2),
		 JEEOutOfMarks decimal(10,2),
		 DiplomaBoard nvarchar(200),
		 DiplomaCollege nvarchar(200),
		 DiplomaPassingYear nvarchar(10),
		 DiplomaObtainMarks decimal(10,2),
		 DiplomaOutOfMarks decimal(10,2),
		 DiplomaPercentage decimal(10,2)
		 
		 
  )  
  INSERT INTO #tTable1
	(
	    StudentId,
	    SSCBoard,
	    SSCSchool,
	    SSCPassingYear,
	    SSCObtainMarks,
	    SSCOutOfMarks,
	    SSCPercentage,
	    SSCMathMarks,
	    SSCMathOutOfMarks,
	    HSCBoard,
	    HSCSchool,
	   HSCPassingYear ,
	   HSCObtainMarks,
	   HSCOutOfMarks,
	   HSCPercentage,
	   HSCPhysicsMarks,
	   HSCPhysicsOutOfMarks,
	   HSCChemistryMarks,
	   HSCChemistryOutOfMarks,
	   HSCMathMarks,
	   HSCMathOutOfMarks,
	   HSCBiologyMarks,
	   HSCBiologyOutOfMarks,
	   PCMMarks,
	   PCBMarks,
	   JEERollNo,
	   JEEMeritNo,
	   JEEMeritMarks,
	   JEEOutOfMarks,
	   DiplomaBoard,
	   DiplomaCollege,
	   DiplomaPassingYear,
	   DiplomaObtainMarks,
	   DiplomaOutOfMarks,
	   DiplomaPercentage
     )      
   SELECT
     StudentId,
	    SSCBoard,
	    SSCSchool,
	    SSCPassingYear,
	    SSCObtainMarks,
	    SSCOutOfMarks,
	    SSCPercentage,
	    SSCMathMarks,
	    SSCMathOutOfMarks,
	    HSCBoard,
	    HSCSchool,
	   HSCPassingYear ,
	   HSCObtainMarks,
	   HSCOutOfMarks,
	   HSCPercentage,
	   HSCPhysicsMarks,
	   HSCPhysicsOutOfMarks,
	   HSCChemistryMarks,
	   HSCChemistryOutOfMarks,
	   HSCMathMarks,
	   HSCMathOutOfMarks,
	   HSCBiologyMarks,
	   HSCBiologyOutOfMarks,
	   PCMMarks,
	   PCBMarks,
	   JEERollNo,
	   JEEMeritNo,
	   JEEMeritMarks,
	   JEEOutOfMarks,
	   DiplomaBoard,
	   DiplomaCollege,
	   DiplomaPassingYear,
	   DiplomaObtainMarks,
	   DiplomaOutOfMarks,
	   DiplomaPercentage
   
   FROM OPENXML (@intDoc, '/Table/ImportStudentOldDetail', 1)
   With
   (   
        StudentId BIGINT '@StudentId',
        SSCBoard nvarchar(200) '@SSCBoard',
        SSCSchool nvarchar(100) '@SSCSchool',
        SSCPassingYear nvarchar(100) '@SSCPassingYear',
        SSCObtainMarks DECIMAL(10,2) '@SSCObtainMarks',
        SSCOutOfMarks DECIMAL(10,2)  '@SSCOutOfMarks' ,
		 SSCPercentage DECIMAL(10,2)  '@SSCPercentage' ,  
		 SSCMathMarks DECIMAL(10,2) '@SSCMathMarks',    
		 SSCMathOutOfMarks DECIMAL(10,2) '@SSCMathOutOfMarks' ,   
	     HSCBoard nvarchar(200) '@HSCBoard' ,   
		 HSCSchool nvarchar(200) '@HSCSchool' ,   
		 HSCPassingYear nvarchar(10 ) '@HSCPassingYear' ,
	     HSCObtainMarks DECIMAL(10,2) '@HSCObtainMarks'  ,  
		 HSCOutOfMarks DECIMAL(10,2) '@HSCOutOfMarks'  ,  
		 HSCPercentage DECIMAL(10,2) '@HSCPercentage'   , 
		 HSCPhysicsMarks DECIMAL(10,2) '@HSCPhysicsMarks'    ,
		 HSCPhysicsOutOfMarks DECIMAL(10,2)  '@HSCPhysicsOutOfMarks'    ,
		 HSCChemistryMarks DECIMAL(10,2)   '@HSCChemistryMarks',    
		 HSCChemistryOutOfMarks DECIMAL(10,2) '@HSCChemistryOutOfMarks' ,   
		 HSCMathMarks DECIMAL(10,2)  '@HSCMathMarks'    ,
		 HSCMathOutOfMarks DECIMAL(10,2)   '@HSCMathOutOfMarks'  ,  
		 HSCBiologyMarks DECIMAL(10,2)    '@HSCBiologyMarks'  ,  
		 HSCBiologyOutOfMarks DECIMAL(10,2)     '@HSCBiologyOutOfMarks'    ,
		 PCMMarks DECIMAL(10,2)      '@PCMMarks' ,   
		 PCBMarks DECIMAL(10,2) '@PCBMarks'    ,
		 JEERollNo nvarchar(20)  '@JEERollNo'  ,  
		 JEEMeritNo nvarchar(20) '@JEEMeritNo'   , 
		 JEEMeritMarks DECIMAL(10,2) '@JEEMeritMarks'  ,  
		 JEEOutOfMarks DECIMAL(10,2) '@JEEOutOfMarks' ,   
		 DiplomaBoard nvarchar(200) '@DiplomaBoard',    
		 DiplomaCollege nvarchar(200)  '@DiplomaCollege'  ,  
		 DiplomaPassingYear nvarchar(10)   '@DiplomaPassingYear'   , 
		 DiplomaObtainMarks DECIMAL(10,2) '@DiplomaObtainMarks'  ,  
		 DiplomaOutOfMarks DECIMAL(10,2)  '@DiplomaOutOfMarks' ,   
		 DiplomaPercentage DECIMAL(10,2)   '@DiplomaPercentage' 
		  
   )     
   
EXEC sp_xml_removedocument @intDoc
			
SELECT @lCount =  COUNT(StudentId) FROM #tTable1
 
WHILE @lCount > 0 
  BEGIN

       SELECT         
          
            @lStudentId = StudentId,
            @lSSCBoard = SSCBoard,
            @lSSCSchool = SSCSchool,
            @lSSCPassingYear= SSCPassingYear,
            @lSSCObtainMarks = SSCObtainMarks,
            @lSSCOutOfMarks = SSCOutOfMarks,
            @lSSCPercentage = SSCPercentage,
            @lSSCMathMarks= SSCMathMarks,
            @lSSCMathOutOfMarks = SSCMathOutOfMarks,
            @lHSCBoard= HSCBoard,
            @lHSCSchool = HSCSchool,
            @lHSCPassingYear = HSCPassingYear,
            @lHSCObtainMarks= HSCObtainMarks,
            @lHSCOutOfMarks= HSCOutOfMarks,
            @lHSCPercentage = HSCPercentage,
            @lHSCPhysicsMarks= HSCPhysicsMarks,
            @lHSCPhysicsOutOfMarks = HSCPhysicsOutOfMarks,
            @lHSCChemistryMarks = HSCChemistryMarks,
            @lHSCChemistryOutOfMarks = HSCChemistryOutOfMarks,
            @lHSCMathMarks= HSCMathMarks,
            @lHSCMathOutOfMarks= HSCMathOutOfMarks,
            @lHSCBiologyMarks = HSCBiologyMarks,
            @lHSCBiologyOutOfMarks= HSCBiologyOutOfMarks,
            @lPCMMarks= PCMMarks,
            @lPCBMarks = PCBMarks,
               @lJEERollNo =JEERollNo,
            @lJEEMeritNo= JEEMeritNo,
            @lJEEMeritMarks = JEEMeritMarks,
            @lJEEOutOfMarks = JEEOutOfMarks,
            @lDiplomaBoard= DiplomaBoard,
            @lDiplomaCollege= DiplomaCollege,
            @lDiplomaPassingYear = DiplomaPassingYear,
            @lDiplomaObtainMarks= DiplomaObtainMarks,
            @lDiplomaOutOfMarks= DiplomaOutOfMarks,
            @lDiplomaPercentage = DiplomaPercentage 
             
     FROM #tTable1 WHERE Id = @lCount    

 
		IF   EXISTS(SELECT 1 FROM sStudent.tCollegeDetail where StudentId = @lStudentId)           
          BEGIN
              
  		 	    --SELECT @1SubGroupId = Id From sIp.tItemSubGroupMaster where Title = @1SubGroup
  		 	    --SELECT @1StockItemCategoryId = Id From sIp.tStockItemCategoryMaster where  Title = @1StockItemCategory
  		 	    --SELECT @1IssuUOMId =  Id From sFinanceCommon.tStockUomMaster where Title = @1IssueUOM
  		 	    
  		 	    --Select @1IssuUOMId AS IssuUOMId,@1StockItemCategoryId AS StockItemCategoryId,@1SubGroupId AS SubGroupId
  		 	   
  		 	   --SET @1Result = -101 
  		 	   
  		 	   --IF(@1SubGroupId > 0 AND @1StockItemCategoryId>0 AND @1IssuUOMId>0)
  		 	   --  BEGIN  
  		 	         Update sStudent.tCollegeDetail
  		 	         Set
  		 				SSCBoard=@lSSCBoard,
  		 				SSCSchool=@lSSCSchool,
  		 				SSCPassingYear=@lSSCPassingYear,
  		 				SSCObtainMarks=@lSSCObtainMarks,
  		 				SSCOutOfMarks=@lSSCOutOfMarks,
  		 				SSCPercentage=@lSSCPercentage,
  		 				SSCMathMarks=@lSSCMathMarks,
  		 				SSCMathOutOfMarks=@lSSCMathOutOfMarks,
  		 				HSCBoard=@lHSCBoard,
  		 				HSCSchool=@lHSCSchool,
  		 				HSCPassingYear=@lHSCPassingYear,
  		 				HSCObtainMarks=@lHSCObtainMarks,
  		 				HSCOutOfMarks=@lHSCOutOfMarks,
  		 				HSCPercentage=@lHSCPercentage,
  		 				HSCPhysicsMarks=@lHSCPhysicsMarks,
  		 				HSCPhysicsOutOfMarks=@lHSCPhysicsOutOfMarks,
  		 				HSCChemistryMarks=@lHSCChemistryMarks,
  		 	           HSCChemistryOutOfMarks =@lHSCChemistryOutOfMarks,
  		 	           HSCMathMarks=@lHSCMathMarks,
  		 	           HSCMathOutOfMarks=@lHSCMathOutOfMarks,
  		 	           HSCBiologyMarks=@lHSCBiologyMarks,
  		 	           HSCBiologyOutOfMarks=@lHSCBiologyOutOfMarks,
  		 	           PCMMarks=@lPCMMarks,
  		 	           PCBMarks=@lPCBMarks,
  		 	           JEERollNo=@lJEERollNo,
  		 	           JEEMeritNo=@lJEEMeritNo,
  		 	           JEEMeritMarks=@lJEEMeritMarks,
  		 	           JEEOutOfMarks=@lJEEOutOfMarks,
  		 	           DiplomaBoard=@lDiplomaBoard,
  		 	           DiplomaCollege=@lDiplomaCollege,
  		 	           DiplomaPassingYear = @lDiplomaPassingYear,
  		 	           DiplomaObtainMarks =@lDiplomaObtainMarks,
  		 	           DiplomaOutOfMarks =@lDiplomaOutOfMarks,
  		 	           DiplomaPercentage=@lDiplomaPercentage
  		 	           wHERE  StudentId = @lStudentId
  		 	            Select 1 AS Result
   		        END  		 	  
   		     ELse
   		     BEGIN
   		     
   				Select @lStudCap=ISNULL(NoOfStudent,0)+ISNULL(StudentExtraCap,0) from
				sSetup.tOrgGroupSetting Where OrgGroupId= @rOrgGroupId
				
				Select @lOrgStudentCap=[sSetup].[fStudentCapGet](@rOrgGroupBatchId)
				IF(@lOrgStudentCap >= @lStudCap )
				BEGIN
					Select -111 AS RESULT 
					Return
				END
				
   				insert into    sStudent.tCollegeDetail
   				(
   					StudentId ,
					SSCBoard,
					SSCSchool,
					SSCPassingYear,
					SSCObtainMarks,
					SSCOutOfMarks,
					SSCPercentage,
					SSCMathMarks,
					SSCMathOutOfMarks,
					HSCBoard,
					HSCSchool,
					HSCPassingYear,
					HSCObtainMarks,
					HSCOutOfMarks,
					HSCPercentage,
					HSCPhysicsMarks,
					HSCPhysicsOutOfMarks,
					HSCChemistryMarks,
					HSCChemistryOutOfMarks,
					HSCMathMarks,
					HSCMathOutOfMarks,
					HSCBiologyMarks,
					HSCBiologyOutOfMarks,
					PCMMarks,
					PCBMarks,
					JEERollNo,
					JEEMeritNo,
					JEEMeritMarks,
					JEEOutOfMarks,
					DiplomaBoard,
					DiplomaCollege,
					DiplomaPassingYear,
					DiplomaObtainMarks,
					DiplomaOutOfMarks,
					DiplomaPercentage  
   				)
   				Values
   				(
   					@lStudentId ,
					@lSSCBoard,
					@lSSCSchool,
					@lSSCPassingYear,
					@lSSCObtainMarks,
					@lSSCOutOfMarks,
					@lSSCPercentage,
					@lSSCMathMarks,
					@lSSCMathOutOfMarks,
					@lHSCBoard,
					@lHSCSchool,
					@lHSCPassingYear,
					@lHSCObtainMarks,
					@lHSCOutOfMarks,
					@lHSCPercentage,
					@lHSCPhysicsMarks,
					@lHSCPhysicsOutOfMarks,
					@lHSCChemistryMarks,
					@lHSCChemistryOutOfMarks,
					@lHSCMathMarks,
					@lHSCMathOutOfMarks,
					@lHSCBiologyMarks,
					@lHSCBiologyOutOfMarks,
					@lPCMMarks,
					@lPCBMarks,
					@lJEERollNo,
					@lJEEMeritNo,
					@lJEEMeritMarks,
					@lJEEOutOfMarks,
					@lDiplomaBoard,
					@lDiplomaCollege,
					@lDiplomaPassingYear,
					@lDiplomaObtainMarks,
					@lDiplomaOutOfMarks,
					@lDiplomaPercentage 

   				)
   				 Select 101 AS Result
	END
	 SET @lCount = @lCount - 1
   END			 
    
END
GO
PRINT N'Altering [sStudent].[pStudentAdmissionAdd]...';


GO
ALTER PROCEDURE [sStudent].[pStudentAdmissionAdd]
	 
		   @rStudentId bigint,
		   @rPreviousSchool nvarchar(200),
           @rPreviousSchoolTypeId int,
           @rPreviousStudentId bigint,
           @rAdmissionFormId bigint,
           @rAdmissionFormNumber nvarchar(20),
           @rAdmissionStandardId int,
           @rAdmissionDate date,
           @rAdmissionYear nvarchar(10),
           @rLeftStandardId int,
           @rLeftDate date,
           @rLeftYear nvarchar(10),
           @rInactiveDate date,
           @rInActiveReason nvarchar(200),
           @rLeftReason nvarchar(200),
           @rLCProgress nvarchar(200),
           @rLCConduct nvarchar(200),
           @rLCBook nvarchar(20),
           @rLCNumber nvarchar(20),
           @rLCDate date,
           @rLCRemark nvarchar(200),
           @rLCCopy tinyint,
           @rLcId bigint,
           @rBatchId int,
           @rCreatedUserId bigint,
           @rUpdatedUserId bigint,
           @rIsGeneral bit,
           
           @rAdmissionNumber nvarchar(50)='',
           @rIsTransfer bit = 0,
           @rTransferFrom nvarchar(150)='',
           @rPassingYear nvarchar(20)='',
           @rIsTFWS bit = 0,
           @rIsCertificateHolder bit = 0,
           @rCertificateName nvarchar(100) = '',
           @rAdmissionQuotaId int =0,
           @rPreviousStandard nvarchar(50)=''

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	
       IF(@rIsGeneral=1)	
BEGIN 
IF NOT EXISTS(SELECT * FROM sStudent.tStudentAdmission WHERE StudentId = @rStudentId)
BEGIN

	INSERT INTO sStudent.tStudentAdmission
		(
			   StudentId,
			   PreviousSchool,
			   AdmissionStandardId,
			   AdmissionDate,
			   LeftStandardId,
			   LeftDate,
			   InactiveDate,
			   BatchId,
			   CreatedUserId,
			   CreatedDateTime,
			   PreviousStandard
			   
		)
	VALUES
		(
			   @rStudentId,
			   @rPreviousSchool,
			   @rAdmissionStandardId,
			   @rAdmissionDate,
			   @rLeftStandardId,
			   @rLeftDate,
			   @rInactiveDate,
			   @rBatchId,
			   @rCreatedUserId,
			   sCommon.fGetDate(),
			   @rPreviousStandard
		)
		SELECT 1 AS Result             
	END	 
	 ELSE
	 BEGIN
		UPDATE sStudent.tStudentAdmission
	    SET
			  
			  AdmissionStandardId = @rAdmissionStandardId, 
			  AdmissionDate = @rAdmissionDate, 
			  LeftStandardId = @rLeftStandardId,
			  LeftDate = @rLeftDate, 
			  InactiveDate = @rInactiveDate, 
			  UpdatedUserId = @rUpdatedUserId, 
			  UpdatedDateTime =sCommon.fGetDate()
	
	      WHERE StudentId = @rStudentId 	   
	 END  
		SELECT 11 AS Result
		END
ELSE
BEGIN
		IF(@rIsGeneral=0)
	IF NOT EXISTS(SELECT * FROM sStudent.tStudentAdmission WHERE StudentId = @rStudentId)
BEGIN

	INSERT INTO sStudent.tStudentAdmission
		(
			   StudentId,
			   PreviousSchool,
			   PreviousSchoolTypeId,
			   PreviousStudentId,
			   AdmissionFormId,
			   AdmissionFormNumber,
			   AdmissionStandardId,
			   AdmissionDate,
			   AdmissionYear,
			   LeftStandardId,
			   LeftDate,
			   LeftYear,
			   InactiveDate,
			   InActiveReason,
			   LeftReason,
			   LCProgress,
			   LCConduct,
			   LCBook,
			   LCNumber,
			   LCDate,
			   LCRemark,
			   LCCopy,
			   LcId,
			   BatchId,
			   CreatedUserId,
			   CreatedDateTime,
			   
			   AdmissionNumber,
			   IsTransfer,
			   TransferFrom,
			   PassingYear,
			   IsTFWS,
			   IsCertificateHolder,
			   CertificateName,
			   AdmissionQuotaId,
			   PreviousStandard
		)
	VALUES
		(
			   @rStudentId,
			   @rPreviousSchool,
			   @rPreviousSchoolTypeId,
			   @rPreviousStudentId,
			   @rAdmissionFormId,
			   @rAdmissionFormNumber,
			   @rAdmissionStandardId,
			   @rAdmissionDate,
			   @rAdmissionYear,
			   @rLeftStandardId,
			   @rLeftDate,
			   @rLeftYear,
			   @rInactiveDate,
			   @rInActiveReason,
			   @rLeftReason,
			   @rLCProgress,
			   @rLCConduct,
			   @rLCBook,
			   @rLCNumber,
			   @rLCDate,
			   @rLCRemark,
			   @rLCCopy,
			   @rLcId,
			   @rBatchId,
			   @rCreatedUserId,
			   sCommon.fGetDate(),
			   
			   @rAdmissionNumber,
			   @rIsTransfer,
			   @rTransferFrom,
			   @rPassingYear,
			   @rIsTFWS,
			   @rIsCertificateHolder,
			   @rCertificateName,
			   @rAdmissionQuotaId,
			   @rPreviousStandard
		)
		SELECT 1 AS Result             
	END	 
	 ELSE
	 BEGIN
		UPDATE sStudent.tStudentAdmission
	    SET
			  PreviousSchool = @rPreviousSchool,
			  PreviousSchoolTypeId = @rPreviousSchoolTypeId, 
			  PreviousStudentId = @rPreviousStudentId, 
			  AdmissionFormId = @rAdmissionFormId,
			  AdmissionFormNumber = @rAdmissionFormNumber, 
			  AdmissionStandardId = @rAdmissionStandardId, 
			  AdmissionDate = @rAdmissionDate, 
			  AdmissionYear = @rAdmissionYear,
			  LeftStandardId = @rLeftStandardId,
			  LeftDate = @rLeftDate, 
			  LeftYear = @rLeftYear,
			  InactiveDate = @rInactiveDate, 
			  InActiveReason = @rInActiveReason,
			  LeftReason = @rLeftReason, 
			  LCProgress = @rLCProgress,
			  LCConduct = @rLCConduct, 
			  LCBook = @rLCBook, 
			  LCNumber = @rLCNumber,
			  LCDate = @rLCDate, 
			  LCRemark = @rLCRemark, 
			  LCCopy = @rLCCopy, 
			  LcId = @rLcId, 
			  UpdatedUserId = @rUpdatedUserId, 
			  UpdatedDateTime =sCommon.fGetDate(),
			  
			  AdmissionNumber=@rAdmissionNumber,
			  IsTransfer=@rIsTransfer,
		  	  TransferFrom=@rTransferFrom,
			  PassingYear=@rPassingYear,
			  IsTFWS=@rIsTFWS,
			  IsCertificateHolder=@rIsCertificateHolder,
			  CertificateName=@rCertificateName,
			  AdmissionQuotaId=@rAdmissionQuotaId,
			  PreviousStandard=@rPreviousStandard
	      
	      WHERE StudentId = @rStudentId 	 
	      
	 END  
	 
		SELECT 11 AS Result
		
		END
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sStudent].[pStudentAdmissionGet]...';


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

BEGIN 
	SELECT 
			  SA.StudentId,
			  SA.PreviousSchool,
			  ISNULL(SA.PreviousSchoolTypeId,0) AS PreviousSchoolTypeId,
			  ISNULL(SA.PreviousStudentId,0) AS PreviousStudentId,
			  ISNULL(SA.AdmissionFormId,0) AS AdmissionFormId,
			  SA.AdmissionFormNumber,
			  ISNULL(SA.AdmissionStandardId,0) AS AdmissionStandardId,
			  ISNULL(SA.AdmissionDate,'0001/01/01') AS AdmissionDate,
			  SA.AdmissionYear,
			  ISNULL(SA.LeftStandardId,0) AS LeftStandardId,
			  ISNULL(SA.LeftDate,'0001/01/01') AS LeftDate,
			  SA.LeftYear,
			  ISNULL(SA.InactiveDate,'0001/01/01') AS InactiveDate,
			  SA.InActiveReason,
			  SA.LeftReason,
			  SA.LCProgress,
			  SA.LCConduct,
			  SA.LCBook,
			  SA.LCNumber,
			  ISNULL(SA.LCDate,'0001/01/01') AS LCDate,
			  SA.LCRemark,
			  ISNULL(SA.LCCopy,0) AS LCCopy,
			  ISNULL(SA.LcId,0) AS LcId,
			  
			  ISNULL(SA.AdmissionNumber,'') AS AdmissionNumber,
			  ISNULL(SA.IsTransfer,0) AS IsTransfer,
			  ISNULL(SA.TransferFrom,'') AS TransferFrom,
			  ISNULL(SA.PassingYear,'') AS PassingYear,
			  ISNULL(SA.IsTFWS,0) AS IsTFWS,
			  ISNULL(SA.IsCertificateHolder,0) AS IsCertificateHolder,
			  ISNULL(SA.CertificateName,'') AS CertificateName,
			  ISNULL(SA.AdmissionQuotaId,0) AS AdmissionQuotaId,
			  ISNULL(SA.PreviousStandard,'') AS PreviousStandard

  FROM 
         sStudent.tStudentAdmission SA
  WHERE 
		SA.StudentId = @rStudentId
END
GO
PRINT N'Altering [sStudent].[pStudentCustomSearchGet]...';


GO
 
ALTER PROCEDURE [sStudent].[pStudentCustomSearchGet]
(
	@rOrgId smallint,
	@rOrderBy nvarchar(max) = 'RollNo',
	@rCode [nvarchar](20) = '',
	@rFirstName [nvarchar](50) = '',	
	@rLastName [nvarchar](50) = '',
	@rCountry [nvarchar](50) = '',
	@rState [nvarchar](50) = '',
	@rCity nvarchar(max) = '',
	@rArea nvarchar(max) = '',
	--@rClassId nvarchar(max) = '',
	@rDivisionId nvarchar(max) = '',
	@rStatusId nvarchar(max) = '',
	@rTransportModeId nvarchar(max) = '',
	@rBusRouteDestinationId nvarchar(max) = '',
	@rBloodGroupId nvarchar(max) = '',
	@rGenderId nvarchar(max) = '',
	@rReligionId nvarchar(max) = '',
	@rCastCategoryId nvarchar(max) = '',
	@rHouseId nvarchar(max) = '',
	@rMotherTongueId nvarchar(max) = '',
	@rNationalityId nvarchar(max) = '',
	@rHobby nvarchar(50) = '',
	@rFatherQualification nvarchar(max) = '',
	@rMotherQualification nvarchar(max) = '',
	@rFatherOccupation nvarchar(max) = '',
	@rMotherOccupation nvarchar(max) = '',
	@rPreviousSchool nvarchar(max) = '',
	@rAdmissionCategoryId nvarchar(max) = '',
	@rDOBFromDate Date = '0001-01-01',
	@rDOBToDate Date = '9990-12-31',
	@rDOAFromDate Date = '0001-01-01',
	@rDOAToDate Date = '9990-12-31',
	@rDOLFromDate Date = '0001-01-01',
	@rDOLToDate Date = '9990-12-31',
	@rIsPysicalDeformity bit,
	@rIsMajorIllness bit,
	@BatchId int,
	@rIsBlackList bit,
	@rFromCode nvarchar(20), 
	@rToCode nvarchar(20),
	@rDropDownStatusId int,
	@rDropDownClassId int,
	@rDropDownDivisionId int,
	@rCustomTagId nvarchar(max) = '',
	@rCustomGroupId nvarchar(max) = '',
	@rClubId nvarchar(max) = '',
	@rRepeatCount Smallint=0,
	@rStudentStatus Smallint=0,
	@rHostelId nvarchar(max) = '',
	@rFatherName nvarchar(50)='',
	@rMotherName nvarchar(50)='',
	@rStudentGroupId nvarchar(max) = '',
	@rStudentOtherGroupId nvarchar(max) = '',
	@rOrgGroupBatchId int,
	@rBusRouteId nvarchar(max) = '',
	@rFeeExemption  nvarchar(max) = ''
 )
AS
SET NOCOUNT ON

BEGIN
		DECLARE @Sql nvarchar(MAX)
		
		IF(@rDOBFromDate IS NULL)
			SET @rDOBFromDate='0001-01-01'
		IF(@rDOBToDate IS NULL)
			SET @rDOBToDate='9990-12-31'
		IF(@rDOAFromDate IS NULL)
			SET @rDOAFromDate='0001-01-01'
		IF(@rDOAToDate IS NULL)
			SET @rDOAToDate='9990-12-31'
		IF(@rDOLFromDate IS NULL)
			SET @rDOLFromDate='0001-01-01'
		IF(@rDOLToDate IS NULL)
			SET @rDOLToDate='9990-12-31'
		
		 
		SET @rDOBToDate = DATEADD(d,1,@rDOBToDate)		 
		SET @rDOAToDate = DATEADD(d,1,@rDOAToDate)		 
		SET @rDOLToDate = DATEADD(d,1,@rDOLToDate)	
		
		
	
		SET @rCode = sCommon.fSearchStringGet(@rCode)
		SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
		SET @rLastName = sCommon.fSearchStringGet(@rLastName)
		SET @rCountry = sCommon.fSearchStringGet(@rCountry)
		SET @rState = sCommon.fSearchStringGet(@rState)
		 
		-- For Custom Tag
		IF (@rCustomTagId <> '')
		BEGIN
			SELECT 
			DISTINCT SM.Id AS StudentId1
			INTO sStudent.tTempStudent2
			FROM sStudent.tStudentMaster SM
			INNER JOIN sStudent.tStudentCustomTag SCT ON SCT.StudentId=SM.Id
			INNER JOIN sStudent.tAcademic A ON A.StudentId = SM.Id
			WHERE SM.OrgId = @rOrgId  AND A.BatchId = @BatchId 
			AND (ISNULL(SCT.CustomTagId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rCustomTagId,','))OR @rCustomTagId='')
		END
		
		ELSE
		BEGIN
			SELECT 
			DISTINCT NULL AS StudentId1
			INTO sStudent.tTempStudent2
		END
			 
		-- For Custom Group
		IF (@rCustomGroupId <> '')
		BEGIN
			SELECT 
			DISTINCT SM.Id AS StudentId2
			INTO sStudent.tTempStudent3
			FROM sStudent.tStudentMaster SM
			INNER JOIN sStudent.tAcademic A ON A.StudentId = SM.Id
			INNER JOIN sCommunication.tCustomGroupMember CGM ON CGM.SourceId = A.Id AND CGM.SourceTypeId=2001
			WHERE SM.OrgId = @rOrgId  AND A.BatchId = @BatchId 
			AND (ISNULL(CGM.CustomGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rCustomGroupId,','))OR @rCustomGroupId='')
		END
		ELSE
		BEGIN
			SELECT 
			DISTINCT NULL AS StudentId2
			INTO sStudent.tTempStudent3
		END
		
		-- For Club Group
		IF (@rClubId <> '')
		BEGIN
			SELECT 
			DISTINCT SM.Id AS StudentId3
			INTO sStudent.tTempStudent4
			FROM sStudent.tStudentMaster SM
			INNER JOIN sStudent.tAcademic A ON A.StudentId = SM.Id
			INNER JOIN sActivity.tAssignClub AC ON AC.AcademicId = A.Id
			WHERE SM.OrgId = @rOrgId  AND A.BatchId = @BatchId 
			AND (ISNULL(AC.ClubId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClubId,','))OR @rClubId='')
		END
		ELSE
		BEGIN
			SELECT 
			DISTINCT NULL AS StudentId3
			INTO sStudent.tTempStudent4
		END
		
		-- For Hostel
		IF (@rHostelId <> '')
		BEGIN
			SELECT 
			DISTINCT SM.Id AS StudentId4
			INTO sStudent.tTempStudent8
			FROM sStudent.tStudentMaster SM
			INNER JOIN sStudent.tAcademic A ON A.StudentId = SM.Id
			INNER JOIN sHostel.tAssignRoom AR ON AR.SourceId = A.StudentId
			AND ((AR.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
			INNER JOIN sHostel.tRoomMaster RM ON RM.Id = AR.RoomId
			WHERE SM.OrgId = @rOrgId --AND A.BatchId = @BatchId 
			AND (ISNULL(RM.HostelId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rHostelId,','))OR @rHostelId='')
		END
		ELSE
		BEGIN
			SELECT 
			DISTINCT NULL AS StudentId4
			INTO sStudent.tTempStudent8
		END
		--Transport
		IF (@rBusRouteId <> '')
		BEGIN
			SELECT 
			DISTINCT SM.Id AS StudentId5
			INTO sStudent.tTempStudent9
			FROM sStudent.tStudentMaster SM
			INNER JOIN sStudent.tAcademic A ON A.StudentId = SM.Id
			INNER JOIN sTransport.tAssignRoute AT ON AT.SourceId = A.StudentId
			INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id = AT.PickupDestinationId
			INNER JOIN sTransport.tBusRouteMaster BRM ON BRM.Id = BM.BusRouteId
			AND ((BRM.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
			WHERE SM.OrgId = @rOrgId 
			AND (ISNULL(BRM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rBusRouteId,','))OR @rBusRouteId='')
		END
		ELSE
		BEGIN
			SELECT 
			DISTINCT NULL AS StudentId5
			INTO sStudent.tTempStudent9
		END
	
		IF (@rFeeExemption <> '')
		BEGIN
			SELECT 
			DISTINCT SM.Id AS StudentId6
			INTO sStudent.tTempStudent10
			FROM sStudent.tStudentMaster SM
			INNER JOIN sStudent.tAcademic A ON A.StudentId = SM.Id
			INNER JOIN sFee.tExemptionTypeMaster AT ON AT.Id = A.ExemptionTypeId
			 
			WHERE SM.OrgId = @rOrgId 
			AND (ISNULL(AT.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeExemption,','))OR @rFeeExemption='')
		END
		ELSE
		BEGIN
			SELECT 
			DISTINCT NULL AS StudentId6
			INTO sStudent.tTempStudent10
		END
		
		SELECT 
				*,
				SCS.ClassName+'-'+SCS.DivisionName AS ClassName1
		INTO sStudent.tTempStudent1
		FROM sStudent.vStudentCustomSearch SCS
		INNER JOIN sStudent.tTempStudent2 T2 ON SCS.StudentId = T2.StudentId1 OR @rCustomTagId = ''
		INNER JOIN sStudent.tTempStudent3 T3 ON SCS.StudentId = T3.StudentId2 OR @rCustomGroupId = ''
		INNER JOIN sStudent.tTempStudent4 T4 ON SCS.StudentId = T4.StudentId3 OR @rClubId = ''
		INNER JOIN sStudent.tTempStudent8 T8 ON SCS.StudentId = T8.StudentId4 OR @rHostelId = ''
		INNER JOIN sStudent.tTempStudent9 T9 ON SCS.StudentId = T9.StudentId5 OR @rBusRouteId = ''
		INNER JOIN sStudent.tTempStudent10 T10 ON SCS.StudentId = T10.StudentId6 OR @rFeeExemption = ''
		WHERE 
			SCS.OrgId = @rOrgId AND SCS.BatchId = @BatchId 
			AND ((SCS.Code Like @rCode + '%') OR (@rCode = ''))
			AND ((SCS.FirstName Like @rFirstName  + '%') OR (@rFirstName = ''))	 			 
			AND ((SCS.LastName Like @rLastName + '%')OR(@rLastName = ''))
			AND ((ISNULL(SCS.PermanentCountry,'') Like @rCountry + '%')OR(@rCountry = ''))
			AND ((ISNULL(SCS.PermanentState,'') Like @rState + '%')OR(@rState = ''))		 
			AND (( SCS.DateOfBirth  >= @rDOBFromDate) OR (ISNULL(SCS.DateOfBirth,'') = ''))
			AND (( SCS.DateOfBirth  < @rDOBToDate) OR (ISNULL(SCS.DateOfBirth,'') = ''))
			AND (( SCS.AdmissionDate >= @rDOAFromDate) OR (ISNULL(SCS.AdmissionDate,'') = ''))
			AND (( SCS.AdmissionDate < @rDOAToDate) OR (ISNULL(SCS.AdmissionDate,'') = ''))		 
			AND (( SCS.LeftDate  >= @rDOLFromDate) OR (ISNULL(SCS.LeftDate,'') = ''))
			AND (( SCS.LeftDate   < @rDOLToDate) OR (ISNULL(SCS.LeftDate,'') = ''))
			AND ((SCS.Hobby Like '%' + @rHobby + '%') OR (@rHobby = ''))
			AND ((SCS.RepeatCount=@rRepeatCount)OR (@rRepeatCount=0))
			
             AND (ISNULL(SCS.PermanentCity,0) IN( SELECT item FROM  sCommon.fnsplit(@rCity,','))OR @rCity='')
		    
		    
		    AND (ISNULL(SCS.PermanentStreetThree,0) IN( SELECT item FROM  sCommon.fnsplit(@rArea,','))OR @rArea='')
		    
		    AND (SCS.DivisionId In( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionId,','))OR @rDivisionId='')
		         	          
			AND (SCS.StatusId In( SELECT cast(item as int) FROM  sCommon.fnsplit(@rStatusId,','))OR @rStatusId='')	
	        
	        AND (SCS.TransportModeId In( SELECT cast(item as int) FROM  sCommon.fnsplit(@rTransportModeId,','))OR @rTransportModeId='')
	        
	        AND (ISNULL(SCS.BloodGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rBloodGroupId,','))OR @rBloodGroupId='') 
		    
		    AND (ISNULL(SCS.GenderId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rGenderId,','))OR @rGenderId='')
		            
		    AND (ISNULL(SCS.ReligionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rReligionId,','))OR @rReligionId='')
		           
		    AND (ISNULL(SCS.CastCategoryId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rCastCategoryId,','))OR @rCastCategoryId='')
		           
		    AND (ISNULL(SCS.HouseId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rHouseId,','))OR @rHouseId='')
		                   
		    AND (ISNULL(SCS.MotherTongueId,0) IN ( SELECT cast(item as int) FROM  sCommon.fnsplit(@rMotherTongueId,','))OR @rMotherTongueId='')
		           
		    AND (ISNULL(SCS.NationalityId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rNationalityId,','))OR @rNationalityId='')
		     
		    AND (ISNULL(SCS.BusRouteDestinationId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rBusRouteDestinationId,','))OR @rBusRouteDestinationId='')		
		    
		    AND (ISNULL(SCS.FatherQualification,'') IN( SELECT item FROM  sCommon.fnsplit(@rFatherQualification,','))OR @rFatherQualification='')
		    
		    AND (ISNULL(SCS.FatherOccupation,'') IN( SELECT item FROM  sCommon.fnsplit(@rFatherOccupation,','))OR @rFatherOccupation='')
		    
		    AND (ISNULL(SCS.MotherQualification,'') IN( SELECT item FROM  sCommon.fnsplit(@rMotherQualification,','))OR @rMotherQualification='')
		    
		    AND (ISNULL(SCS.MotherOccupation,'') IN( SELECT item FROM  sCommon.fnsplit(@rMotherOccupation,','))OR @rMotherOccupation='')
		    
		    AND (ISNULL(SCS.AdmissionCategoryId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rAdmissionCategoryId,','))OR @rAdmissionCategoryId='')
		    
		    AND (ISNULL(SCS.PreviousSchool,'') IN( SELECT item FROM  sCommon.fnsplit(@rPreviousSchool,','))OR @rPreviousSchool='')
		    
		     -- AND (ISNULL(SCS.RepeatCount,1) IN( SELECT item FROM  sCommon.fnsplit(@rRepeatCount,','))OR @rRepeatCount=1)
		  
		    AND (ISNULL(SCS.StudentStatusId,'') IN( SELECT item FROM  sCommon.fnsplit(@rStudentStatus,','))OR @rStudentStatus='')
		  
		  AND (ISNULL(SCS.StudentGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rStudentGroupId,','))OR @rStudentGroupId='')
			  
			AND (ISNULL(SCS.StudentOtherGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rStudentOtherGroupId,','))OR @rStudentOtherGroupId='')
		  
		    AND ((SCS.IsPysicalDeformity=@rIsPysicalDeformity) OR (@rIsPysicalDeformity=0))
		    AND ((SCS.IsMajorIllness=@rIsMajorIllness) OR (@rIsMajorIllness=0)) 
		    AND ((SCS.IsBlackList=@rIsBlackList) OR (@rIsBlackList=0))
		    AND ((SCS.Code >= @rFromCode) OR (@rFromCode=''))
			AND ((SCS.Code <= @rToCode) OR (@rToCode=''))
			AND ((SCS.StatusId = @rDropDownStatusId) OR (@rDropDownStatusId=0))
			AND ((SCS.ClassId = @rDropDownClassId) OR (@rDropDownClassId=0))
			AND ((SCS.DivisionId = @rDropDownDivisionId) OR (@rDropDownDivisionId=0))
			AND ((SCS.MiddleName Like @rFatherName  + '%') OR (@rFatherName = ''))	 
			AND ((SCS.MotherName Like @rMotherName  + '%') OR (@rMotherName = ''))	 
			AND (ISNULL(SCS.BusRouteId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rBusRouteId,','))OR @rBusRouteId='')	
			AND (ISNULL(SCS.ExemptionTypeId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeExemption,','))OR @rFeeExemption='')			
	SET @rOrderBy=Replace(@rOrderBy,'ID No','Code')
		SET @sql=
		'SELECT 
				StudentId,
				Code AS Code,
				Name,
				ClassName1 AS ClassName,
				StatusName,
				ParentContactNo
		FROM sStudent.tTempStudent1 ORDER BY '+@rOrderBy

		exec(@Sql)
		 
		DROP Table sStudent.tTempStudent1
		DROP Table sStudent.tTempStudent2
		DROP Table sStudent.tTempStudent3
		DROP Table sStudent.tTempStudent4
		DROP Table sStudent.tTempStudent8
		DROP Table sStudent.tTempStudent9
		DROP Table sStudent.tTempStudent10
END
GO
PRINT N'Altering [sStudent].[pStudentDataModify]...';


GO

ALTER PROCEDURE [sStudent].[pStudentDataModify]	 
	@rCategoryId int,
	@rXML nvarchar(max),
	@rSubCategoryField nvarchar(100),
	@rOrgId int = 0
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
DECLARE @lInterrorCode INT
Declare @Sql nvarchar(max) 
DECLARE @loDoc INT

--BEGIN TRY
--BEGIN TRANSACTION

        --CategoryId
        --Communication = 1,
        --Other = 2,
        --Admission = 3,
        --Family = 4,
        --Health = 5,
        --AcademicDetail = 6,
        --General = 7
        --CustomDetail = 8
        --Sibling = 9

EXEC sp_xml_preparedocument @loDoc OUTPUT,@rXML
BEGIN
	
	IF(@rSubCategoryField = 'Gender' OR @rSubCategoryField = 'Religion' OR @rSubCategoryField = 'BloodGroup' 
			 OR @rSubCategoryField = 'TransportMode' OR @rSubCategoryField = 'House'
			OR @rSubCategoryField = 'Quota' 
			OR @rSubCategoryField = 'Nationality' OR @rSubCategoryField = 'AdmissionStandard' OR  @rSubCategoryField = 'AdmissionCategory' OR @rSubCategoryField = 'AdmissionQuota')
	BEGIN
		SET @rSubCategoryField = @rSubCategoryField + 'Id'
	END
	
	IF(	@rSubCategoryField = 'CasteCategory' )
	BEGIN
		SET @rSubCategoryField = Replace(@rSubCategoryField,'Caste','Cast') + 'Id'
	END
	
	IF(	@rSubCategoryField = 'FamilyCaste' )
	BEGIN
		SET @rSubCategoryField = Replace(@rSubCategoryField,'Caste','Cast')  
	END
	
	IF(	@rSubCategoryField = 'StudentGroup' )
	BEGIN
		SET @rSubCategoryField = Replace(@rSubCategoryField,'StudentGroup','StudentGroupId')  
	END
	IF(	@rSubCategoryField = 'StudentOtherGroup' )
	BEGIN
		SET @rSubCategoryField = Replace(@rSubCategoryField,'StudentOtherGroup','StudentOtherGroupId')  
	END
	
	IF OBJECT_ID('ListofData') IS NOT NULL	
	BEGIN 
		DROP TABLE ListofData
	END	
	
	CREATE TABLE ListofData(Id bigint,StudentId bigint,SubCategory nvarchar(150),UpdatedUserId bigint,IsExist bit);
	
	IF(@rCategoryId= 1)  
		BEGIN
		insert into ListofData
		select 0,E.StudentId,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),E.UpdatedUserId,0
		from
		(
				SELECT StudentId,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Students/Students', 2)
				WITH (
						StudentId BIGINT, 
						SubCategory nvarchar(150),
						UpdatedUserId bigint)	
						)E 	
		UPDATE ListofData SET IsExist=1 WHERE StudentId NOT IN(SELECT StudentId FROM sStudent.tStudentCommunication) 
		
		set @sql='INSERT INTO sStudent.tStudentCommunication 
					(StudentId,'+@rSubCategoryField+',CreatedUserId,CreatedDateTime)
					SELECT
						LD.StudentId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
					FROM
						ListofData LD WHERE LD.IsExist=1'
					
		print @sql		
		Exec sp_executesql @sql
		set @sql='UPDATE sStudent.tStudentCommunication set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sStudent.tStudentCommunication SC 
					INNER JOIN ListofData LD ON SC.StudentId=LD.StudentId AND IsExist=0'
		
		Exec sp_executesql @sql
	
		
		Drop Table ListofData
			 SELECT 1 AS StatusCode
	    END
	Else IF(@rCategoryId= 2)
		BEGIN
		insert into ListofData
		select 0,E.StudentId,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),E.UpdatedUserId,0
		from
		(
				SELECT StudentId,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Students/Students', 2)
				WITH (
						StudentId BIGINT, 
						SubCategory nvarchar(100),
						UpdatedUserId bigint)	
						)E 	
		UPDATE ListofData SET IsExist=1 WHERE StudentId NOT IN(SELECT StudentId FROM sStudent.tStudentOther) 
		
		IF(@rSubCategoryField = 'DateOfBirth')
		BEGIN			
			set @sql='INSERT INTO sStudent.tStudentOther 
					(StudentId,'+@rSubCategoryField+',CreatedUserId,CreatedDateTime)
					SELECT
						LD.StudentId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
					FROM
						ListofData LD WHERE LD.IsExist=1'
			Exec sp_executesql @sql				
			 				
			set @sql='UPDATE sStudent.tStudentOther set '+@rSubCategoryField+' = LD.SubCategory,
						UpdatedUserId=LD.UpdatedUserId,
						UpdatedDateTime=sCommon.fGetDate()  
						from sStudent.tStudentOther SO 
						INNER JOIN ListofData LD ON SO.StudentId=LD.StudentId'			
			Exec sp_executesql @sql
			set @sql='UPDATE sStudent.tStudentOther SET '+@rSubCategoryField+' = null WHERE DateOfBirth=''1900-01-01'''
			Exec sp_executesql @sql
		END
		ELSE
		BEGIN
			set @sql='INSERT INTO sStudent.tStudentOther 
						(StudentId,'+@rSubCategoryField+',CreatedUserId,CreatedDateTime)
						SELECT
							LD.StudentId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
						FROM
							ListofData LD WHERE LD.IsExist=1'
			Exec sp_executesql @sql				
			 				
			set @sql='UPDATE sStudent.tStudentOther set '+@rSubCategoryField+' = LD.SubCategory,
						UpdatedUserId=LD.UpdatedUserId,
						UpdatedDateTime=sCommon.fGetDate()  
						from sStudent.tStudentOther SO 
						INNER JOIN ListofData LD ON SO.StudentId=LD.StudentId'
			
			Exec sp_executesql @sql
		END
		Drop Table ListofData
			 SELECT 1 AS StatusCode
	    END	
	    
	    
	    
	Else IF(@rCategoryId= 3)
		BEGIN
		insert into ListofData
		select 0,E.StudentId,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),E.UpdatedUserId,0
		from
		(
				SELECT StudentId,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Students/Students', 2)
				WITH (
						StudentId BIGINT, 
						SubCategory nvarchar(100),
						UpdatedUserId bigint)	
						)E 	

		set @sql='UPDATE sStudent.tStudentAdmission set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sStudent.tStudentAdmission SA 
					INNER JOIN ListofData LD ON SA.StudentId=LD.StudentId'
		
		Exec sp_executesql @sql
		
		IF(@rSubCategoryField = 'AdmissionDate' )
		BEGIN
		SET @sql='UPDATE sStudent.tStudentAdmission SET '+@rSubCategoryField+' = null WHERE AdmissionDate=''1900-01-01'''
			Exec sp_executesql @sql
		END
 
		
		Drop Table ListofData
			 SELECT 1 AS StatusCode
	    END	
  Else IF(@rCategoryId= 4)
	BEGIN
		insert into ListofData
		select 0,E.StudentId,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),E.UpdatedUserId,0
		from
		(
				SELECT StudentId,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Students/Students', 2)
				WITH (
						StudentId BIGINT, 
						SubCategory nvarchar(100),
						UpdatedUserId bigint)	
						)E 	
		UPDATE ListofData SET IsExist=1 WHERE StudentId NOT IN(SELECT StudentId FROM sStudent.tStudentFamily) 
		
		set @sql='INSERT INTO sStudent.tStudentFamily 
					(StudentId,'+@rSubCategoryField+',CreatedUserId,CreatedDateTime)
					SELECT
						LD.StudentId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
					FROM
						ListofData LD WHERE LD.IsExist=1'				
		Exec sp_executesql @sql
		set @sql='UPDATE sStudent.tStudentFamily set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sStudent.tStudentFamily SA 
					INNER JOIN ListofData LD ON SA.StudentId=LD.StudentId AND IsExist=0'
		
		Exec sp_executesql @sql
		
		IF(@rSubCategoryField = 'FatherDateOfBirth' )
		BEGIN
		SET @sql='UPDATE sStudent.tStudentFamily SET '+@rSubCategoryField+' = null WHERE FatherDateOfBirth=''1900-01-01'''
			Exec sp_executesql @sql
		END
		
		IF(@rSubCategoryField = 'MotherDateOfBirth' )
		BEGIN
		SET @sql='UPDATE sStudent.tStudentFamily SET '+@rSubCategoryField+' = null WHERE MotherDateOfBirth=''1900-01-01'''
			Exec sp_executesql @sql
		END

		IF(@rSubCategoryField = 'RelativeDateOfBirth' )
		BEGIN
		SET @sql='UPDATE sStudent.tStudentFamily SET '+@rSubCategoryField+' = null WHERE RelativeDateOfBirth=''1900-01-01'''
			Exec sp_executesql @sql
		END		
				
		
		
		Drop Table ListofData
			 SELECT 1 AS StatusCode
	    END
	    
    Else IF(@rCategoryId= 5)
	     BEGIN
		insert into ListofData
		select 0,E.StudentId,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),E.UpdatedUserId,0
		from
		(
				SELECT StudentId,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Students/Students', 2)
				WITH (
						StudentId BIGINT, 
						SubCategory nvarchar(100),
						UpdatedUserId bigint)	
						)E 	
		UPDATE ListofData SET IsExist=1 WHERE StudentId NOT IN(SELECT StudentId FROM sStudent.tStudentHealth) 
		
		set @sql='INSERT INTO sStudent.tStudentHealth 
					(StudentId,'+@rSubCategoryField+',UpdatedUserId,UpdatedDateTime)
					SELECT
						LD.StudentId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
					FROM
						ListofData LD WHERE LD.IsExist=1'				
		Exec sp_executesql @sql
		set @sql='UPDATE sStudent.tStudentHealth set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sStudent.tStudentHealth SA 
					INNER JOIN ListofData LD ON SA.StudentId=LD.StudentId AND IsExist=0'
		
		Exec sp_executesql @sql
		Drop Table ListofData
			 SELECT 1 AS StatusCode
	    END		 
	 
	 Else IF(@rCategoryId= 6)
	    BEGIN
		insert into ListofData
		select E.Id,0,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),E.UpdatedUserId,0
		from
		(
				SELECT Id,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Students/Students', 2)
				WITH (
						Id BIGINT, 
						SubCategory nvarchar(100),
						UpdatedUserId bigint)	
						)E 	
		UPDATE ListofData SET IsExist=1 WHERE Id NOT IN(SELECT AcademicId FROM sStudent.tAcademicDetail) 
		
		set @sql='INSERT INTO sStudent.tAcademicDetail 
					(AcademicId,'+@rSubCategoryField+')
					SELECT
						LD.Id,Ld.SubCategory
					FROM
						ListofData LD WHERE LD.IsExist=1'				
		Exec sp_executesql @sql
		
		set @sql='UPDATE sStudent.tAcademicDetail set '+@rSubCategoryField+' = LD.SubCategory
					from sStudent.tAcademicDetail AD 
					INNER JOIN ListofData LD ON AD.AcademicId=LD.Id AND IsExist=0'
		
		Exec sp_executesql @sql
		
		IF(@rSubCategoryField = 'BatchAdmissionDate' )
		BEGIN
		SET @sql='UPDATE sStudent.tAcademicDetail SET '+@rSubCategoryField+' = NULL WHERE BatchAdmissionDate=''1900-01-01'''
			Exec sp_executesql @sql
		END
		
		Drop Table ListofData
			 SELECT 1 AS StatusCode
	    END	
	    
	Else IF(@rCategoryId= 7)
	     BEGIN
		insert into ListofData
		select 0,E.StudentId,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),E.UpdatedUserId,0
		from
		(
				SELECT StudentId,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Students/Students', 2)
				WITH (
						StudentId BIGINT, 
						SubCategory nvarchar(100),
						UpdatedUserId bigint)	
						)E 	
		UPDATE ListofData SET IsExist=1 WHERE StudentId NOT IN(SELECT Id FROM sStudent.tStudentMaster) 
		
		--set @sql='INSERT INTO sStudent.tStudentMaster 
		--			(StudentId,'+@rSubCategoryField+',UpdatedUserId,UpdatedDateTime)
		--			SELECT
		--				LD.StudentId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
		--			FROM
		--				ListofData LD WHERE LD.IsExist=1'				
		--Exec sp_executesql @sql
		
		set @sql='UPDATE sStudent.tStudentMaster set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sStudent.tStudentMaster SA 
					INNER JOIN ListofData LD ON SA.Id=LD.StudentId AND IsExist=0'
		
		Exec sp_executesql @sql
		Drop Table ListofData
			 SELECT 1 AS StatusCode
	    END			 
	 
	 
	 Else IF(@rCategoryId= 8)
	     BEGIN
	     
		insert into ListofData
		select 0,E.StudentId,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),0,0
		from
		(
				SELECT StudentId,SubCategory FROM
				OPENXML (@loDoc, '/Students/Students', 2)
				WITH (
						StudentId BIGINT, 
						SubCategory nvarchar(100)
						 )	
						)E 	
		UPDATE ListofData SET IsExist=1 WHERE StudentId NOT IN(SELECT StudentId FROM sStudent.tStudentadditional) 
		
		set @sql='INSERT INTO sStudent.tStudentAdditional
					(StudentId,'+@rSubCategoryField+')
					SELECT
						LD.StudentId,Ld.SubCategory
					FROM
						ListofData LD WHERE LD.IsExist=1'				
		Exec sp_executesql @sql
		
		set @sql='UPDATE sStudent.tStudentAdditional set '+@rSubCategoryField+' = LD.SubCategory 
					 
					from sStudent.tStudentAdditional SA 
					INNER JOIN ListofData LD ON SA.StudentId=LD.StudentId AND IsExist=0'
					
		Exec sp_executesql @sql
					
		IF(@rSubCategoryField = 'PassportIssueDate' )
		BEGIN
		SET @sql='UPDATE sStudent.tStudentAdditional SET '+@rSubCategoryField+' = null WHERE PassportIssueDate=''1900-01-01'''
			Exec sp_executesql @sql
		END
		
		IF(@rSubCategoryField = 'PassportExpiryDate' )
		BEGIN
		SET @sql='UPDATE sStudent.tStudentAdditional SET '+@rSubCategoryField+' = null WHERE PassportExpiryDate=''1900-01-01'''
			Exec sp_executesql @sql
		END						
		
		Drop Table ListofData
			 SELECT 1 AS StatusCode
	    END	
	    
	    
	     
	 Else IF(@rCategoryId= 9)
	    BEGIN
		insert into ListofData
		select 0,E.StudentId,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),0,0
		from
		(
				SELECT StudentId,SubCategory FROM
				OPENXML (@loDoc, '/Students/Students', 2)
				WITH (
						StudentId BIGINT, 
						SubCategory nvarchar(200)
						 )	
						)E 	
		UPDATE ListofData SET IsExist=1 WHERE StudentId NOT IN(SELECT StudentId FROM sStudent.tStudentadditional) 
		
		set @sql='INSERT INTO sStudent.tStudentSibling
					(StudentId,'+@rSubCategoryField+')
					SELECT
						LD.StudentId,Ld.SubCategory
					FROM
						ListofData LD WHERE LD.IsExist=1'				
		Exec sp_executesql @sql
		
		set @sql='UPDATE sStudent.tStudentSibling set '+@rSubCategoryField+' = LD.SubCategory 
					 
					from sStudent.tStudentSibling SS 
					INNER JOIN ListofData LD ON SS.StudentId=LD.StudentId AND IsExist=0'
					
		Exec sp_executesql @sql
		
		
		
		Drop Table ListofData
			 SELECT 1 AS StatusCode
	    END	
END 
	--   COMMIT TRANSACTION
		
	--END TRY
	
	--BEGIN CATCH 
	--	ROLLBACK TRANSACTION
	--	SELECT -1 AS Result
	--END CATCH
GO
PRINT N'Altering [sStudent].[pStudentDataUpdateGet]...';


GO
 
ALTER PROCEDURE [sStudent].[pStudentDataUpdateGet]
	 
	 @rCategoryId int,
	 @rSubCategory nvarchar(100),
	 @rOrgId int,
	 @rClassId int,
	 @rDivisionId int,
	 @rBatchId int,
	 @rIsBlank bit,
	 @rStatusId int,
	 @rOrderBy int
	 
AS
SET NOCOUNT ON

BEGIN
		DECLARE @lDataTypeId nvarchar(1)
		SELECT @lDataTypeId=DataTypeId FROM sCommon.tUpdateFieldMaster WHERE Field=@rSubCategory
		 
		IF(@rSubCategory = 'Gender' OR @rSubCategory = 'Religion' OR @rSubCategory = 'BloodGroup' 
			OR @rSubCategory = 'TransportMode' OR @rSubCategory = 'House'
			OR @rSubCategory = 'Quota' OR @rSubCategory = 'Nationality' OR @rSubCategory = 'AdmissionStandard' OR  @rSubCategory = 'AdmissionCategory'
			OR @rSubCategory = 'AdmissionQuota')
		BEGIN
			 
			SET @rSubCategory =@rSubCategory + 'Id'
			  
		END
		IF(@rSubCategory = 'CasteCategory' )
		BEGIN
			SET @rSubCategory = Replace(@rSubCategory,'Caste','Cast') + 'Id'
		END
		
			IF(@rSubCategory = 'FamilyCaste' )
		BEGIN
			SET @rSubCategory = Replace(@rSubCategory,'Caste','Cast') 
		END
		IF(@rSubCategory = 'StudentGroup' OR @rSubCategory='StudentOtherGroup')
		BEGIN
			SET @rSubCategory = Replace(@rSubCategory ,'StudentGroup','StudentGroupId')
			SET @rSubCategory = Replace(@rSubCategory ,'StudentOtherGroup','StudentOtherGroupId')
		END
		
		 Declare @Sql nvarchar(max)
		 
		 SET @Sql =  CASE @rCategoryId					  
					 WHEN 1 THEN -- Communication
						'Select SA.StudentId,SA.AcademicId,SA.Code,SA.Name,SA.ClassName+'' - ''+SA.DivisionName AS ClassDivision,SA.RollNo,SA.Number,
						CASE WHEN '+@lDataTypeId+'=1 THEN
						ISNULL(SC.'+@rSubCategory+','''') 
						WHEN '+@lDataTypeId+'=2 THEN
						ISNULL(SC.'+@rSubCategory+',''0'')
						WHEN '+@lDataTypeId+'=3 THEN
						ISNULL(SC.'+@rSubCategory+',''False'') 
						WHEN '+@lDataTypeId+'=4 THEN
						ISNULL(SC.'+@rSubCategory+',''0001/01/01'') 
						WHEN '+@lDataTypeId+'=5 THEN
						ISNULL(SC.'+@rSubCategory+',''0'') 
						END AS SubCategory
							FROM 
							sStudent.vStudentAcademic SA
							LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=SA.StudentId
							Where SA.OrgId='+CAST(@rOrgId AS nvarchar(15))
							+'AND (SA.ClassId='+CAST(@rClassId AS nvarchar(15))+ 'OR '+CAST(@rClassId AS nvarchar(15))+'=0)
							AND (SA.DivisionId='+CAST(@rDivisionId AS nvarchar(15))+ 'OR '+CAST(@rDivisionId AS nvarchar(15))+'=0)
							AND (SA.StatusId='+ CAST(@rStatusId AS nvarchar(15)) +' OR '+CAST(@rStatusId AS nvarchar(15))+'=0)
							AND (SA.BatchId='+CAST(@rBatchId AS nvarchar(15))+')
							AND 
							('+CAST(@rIsBlank AS nvarchar(1))+'=0 
								OR ('+@lDataTypeId+'=1 AND ISNULL(SC.'+@rSubCategory+','''')='''')
								OR ('+@lDataTypeId+'=2 AND ISNULL(SC.'+@rSubCategory+',''0'')=''0'')
								OR ('+@lDataTypeId+'=3 AND ISNULL(SC.'+@rSubCategory+',''False'')=''False'')
								OR ('+@lDataTypeId+'=4 AND ISNULL(SC.'+@rSubCategory+',''0001/01/01'')=''0001/01/01'') 
							)
							 '
							
					 WHEN 2 THEN -- Other
						'Select SA.StudentId,SA.AcademicId,SA.Code,SA.Name,SA.ClassName+'' - ''+SA.DivisionName AS ClassDivision,SA.RollNo,SA.Number,
						CASE WHEN '+@lDataTypeId+'=1 THEN
						ISNULL(SO.'+@rSubCategory+','''')
						WHEN '+@lDataTypeId+'=2 THEN
						ISNULL(SO.'+@rSubCategory+',''0'')
						WHEN '+@lDataTypeId+'=3 THEN
						ISNULL(SO.'+@rSubCategory+',''False'')
						WHEN '+@lDataTypeId+'=4 THEN
						SO.'+@rSubCategory+'
						WHEN '+@lDataTypeId+'=5 THEN
						ISNULL(SO.'+@rSubCategory+',''0'')
						END AS SubCategory
							FROM 
							sStudent.vStudentAcademic SA
							LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=SA.StudentId
							Where SA.OrgId='+CAST(@rOrgId AS nvarchar(15))
							+'AND (SA.ClassId='+CAST(@rClassId AS nvarchar(15))+ 'OR '+CAST(@rClassId AS nvarchar(15))+'=0)
							AND (SA.DivisionId='+CAST(@rDivisionId AS nvarchar(15))+ 'OR '+CAST(@rDivisionId AS nvarchar(15))+'=0)
							AND (SA.StatusId='+ CAST(@rStatusId AS nvarchar(15)) +' OR '+CAST(@rStatusId AS nvarchar(15))+'=0)
							AND (SA.BatchId='+CAST(@rBatchId AS nvarchar(15))+')
							AND 
							('+CAST(@rIsBlank AS nvarchar(1))+'=0 
								OR ('+@lDataTypeId+'=1 AND ISNULL(SO.'+@rSubCategory+','''')='''')
								OR ('+@lDataTypeId+'=2 AND ISNULL(SO.'+@rSubCategory+',''0'')=''0'')
								OR ('+@lDataTypeId+'=3 AND ISNULL(SO.'+@rSubCategory+',''False'')=''False'')
								OR ('+@lDataTypeId+'=4 AND ISNULL(SO.'+@rSubCategory+',''0001/01/01'')=''0001/01/01'') 
							)'
							
					WHEN 3 THEN -- Admission
						'Select SA.StudentId,SA.AcademicId,SA.Code,SA.Name,SA.ClassName+'' - ''+SA.DivisionName AS ClassDivision,SA.RollNo,SA.Number,
						CASE WHEN '+@lDataTypeId+'=1 THEN
						ISNULL(SAD.'+@rSubCategory+','''')
						WHEN '+@lDataTypeId+'=2 THEN
						ISNULL(SAD.'+@rSubCategory+',''0'')
						WHEN '+@lDataTypeId+'=3 THEN
						ISNULL(SAD.'+@rSubCategory+',''False'')
						WHEN '+@lDataTypeId+'=4 THEN
						ISNULL(SAD.'+@rSubCategory+',''0001/01/01'')
						WHEN '+@lDataTypeId+'=5 THEN
						ISNULL(SAD.'+@rSubCategory+',''0'')
						END AS SubCategory 
							FROM 
							sStudent.vStudentAcademic SA
							INNER JOIN sStudent.tStudentAdmission SAD ON SAD.StudentId=SA.StudentId
							Where SA.OrgId='+CAST(@rOrgId AS nvarchar(15))
							+'AND (SA.ClassId='+CAST(@rClassId AS nvarchar(15))+ 'OR '+CAST(@rClassId AS nvarchar(15))+'=0)
							AND (SA.DivisionId='+CAST(@rDivisionId AS nvarchar(15))+ 'OR '+CAST(@rDivisionId AS nvarchar(15))+'=0)
							AND (SA.StatusId='+ CAST(@rStatusId AS nvarchar(15)) +' OR '+CAST(@rStatusId AS nvarchar(15))+'=0)
							AND (SA.BatchId='+CAST(@rBatchId AS nvarchar(15))+')
							AND 
							('+CAST(@rIsBlank AS nvarchar(1))+'=0 
								OR ('+@lDataTypeId+'=1 AND ISNULL(SAD.'+@rSubCategory+','''')='''')
								OR ('+@lDataTypeId+'=2 AND ISNULL(SAD.'+@rSubCategory+',''0'')=''0'')
								OR ('+@lDataTypeId+'=3 AND ISNULL(SAD.'+@rSubCategory+',''False'')=''False'')
								OR ('+@lDataTypeId+'=4 AND ISNULL(SAD.'+@rSubCategory+',''0001/01/01'')=''0001/01/01'') 
							)'
					 
					WHEN 4 THEN --Family
					   'Select SA.StudentId,SA.AcademicId,SA.Code,SA.Name,SA.ClassName+'' - ''+SA.DivisionName AS ClassDivision,SA.RollNo,SA.Number,
						CASE WHEN '+@lDataTypeId+'=1 THEN
						ISNULL(SAF.'+@rSubCategory+','''')
						WHEN '+@lDataTypeId+'=2 THEN
						ISNULL(SAF.'+@rSubCategory+',''0'')
						WHEN '+@lDataTypeId+'=3 THEN
						ISNULL(SAF.'+@rSubCategory+',''False'')
						WHEN '+@lDataTypeId+'=4 THEN
						ISNULL(SAF.'+@rSubCategory+',''0001/01/01'')
						WHEN '+@lDataTypeId+'=5 THEN
						ISNULL(SAF.'+@rSubCategory+',''0'')
						END AS SubCategory
							FROM 
							sStudent.vStudentAcademic SA
							LEFT JOIN sStudent.tStudentFamily SAF ON SAF.StudentId=SA.StudentId
							Where SA.OrgId='+CAST(@rOrgId AS nvarchar(15))
							+'AND (SA.ClassId='+CAST(@rClassId AS nvarchar(15))+ 'OR '+CAST(@rClassId AS nvarchar(15))+'=0)
							AND (SA.DivisionId='+CAST(@rDivisionId AS nvarchar(15))+ 'OR '+CAST(@rDivisionId AS nvarchar(15))+'=0)
							AND (SA.StatusId='+ CAST(@rStatusId AS nvarchar(15)) +' OR '+CAST(@rStatusId AS nvarchar(15))+'=0)
							AND (SA.BatchId='+CAST(@rBatchId AS nvarchar(15))+')
							AND 
							('+CAST(@rIsBlank AS nvarchar(1))+'=0 
								OR ('+@lDataTypeId+'=1 AND ISNULL(SAF.'+@rSubCategory+','''')='''')
								OR ('+@lDataTypeId+'=2 AND ISNULL(SAF.'+@rSubCategory+',''0'')=''0'')
								OR ('+@lDataTypeId+'=3 AND ISNULL(SAF.'+@rSubCategory+',''False'')=''False'')
								OR ('+@lDataTypeId+'=4 AND ISNULL(SAF.'+@rSubCategory+',''0001/01/01'')=''0001/01/01'') 
							)'
				   
					WHEN 5 THEN --Health
					   'Select SA.StudentId,SA.AcademicId,SA.Code,SA.Name,SA.ClassName+'' - ''+SA.DivisionName AS ClassDivision,SA.RollNo,SA.Number,
						CASE WHEN '+@lDataTypeId+'=1 THEN
						ISNULL(SAH.'+@rSubCategory+','''')
						WHEN '+@lDataTypeId+'=2 THEN
						ISNULL(SAH.'+@rSubCategory+',''0'')
						WHEN '+@lDataTypeId+'=3 THEN
						ISNULL(SAH.'+@rSubCategory+',''False'')
						WHEN '+@lDataTypeId+'=4 THEN
						ISNULL(SAH.'+@rSubCategory+',''0001/01/01'')
						WHEN '+@lDataTypeId+'=5 THEN
						ISNULL(SAH.'+@rSubCategory+',''0'')
						END AS SubCategory
							FROM 
							sStudent.vStudentAcademic SA
							LEFT JOIN sStudent.tStudentHealth SAH ON SAH.StudentId=SA.StudentId
							Where SA.OrgId='+CAST(@rOrgId AS nvarchar(15))
							+'AND (SA.ClassId='+CAST(@rClassId AS nvarchar(15))+ 'OR '+CAST(@rClassId AS nvarchar(15))+'=0)
							AND (SA.DivisionId='+CAST(@rDivisionId AS nvarchar(15))+ 'OR '+CAST(@rDivisionId AS nvarchar(15))+'=0)
							AND (SA.StatusId='+ CAST(@rStatusId AS nvarchar(15)) +' OR '+CAST(@rStatusId AS nvarchar(15))+'=0)
							AND (SA.BatchId='+CAST(@rBatchId AS nvarchar(15))+')
							AND 
							('+CAST(@rIsBlank AS nvarchar(1))+'=0 
								OR ('+@lDataTypeId+'=1 AND ISNULL(SAH.'+@rSubCategory+','''')='''')
								OR ('+@lDataTypeId+'=2 AND ISNULL(SAH.'+@rSubCategory+',''0'')=''0'')
								OR ('+@lDataTypeId+'=3 AND ISNULL(SAH.'+@rSubCategory+',''False'')=''False'')
								OR ('+@lDataTypeId+'=4 AND ISNULL(SAH.'+@rSubCategory+',''0001/01/01'')=''0001/01/01'') 
							)'
					WHEN 6 THEN --Academic Detail
					   'Select SA.StudentId,SA.AcademicId,SA.Code,SA.Name,SA.ClassName+'' - ''+SA.DivisionName AS ClassDivision,SA.RollNo,SA.Number,
						CASE WHEN '+@lDataTypeId+'=1 THEN
						ISNULL(AD.'+@rSubCategory+','''')
						WHEN '+@lDataTypeId+'=2 THEN
						ISNULL(AD.'+@rSubCategory+',''0'')						
						WHEN '+@lDataTypeId+'=3 THEN
						ISNULL(AD.'+@rSubCategory+',''False'')
						WHEN '+@lDataTypeId+'=4 THEN
						ISNULL(AD.'+@rSubCategory+',''0001/01/01'')	
						WHEN '+@lDataTypeId+'=5 AND ''' + @rSubCategory + '''=''RepeatCount'' THEN
						ISNULL(AD.'+@rSubCategory+',''1'')
						WHEN '+@lDataTypeId+'=5 AND ''' + @rSubCategory + '''<>''RepeatCount'' THEN
						ISNULL(AD.'+@rSubCategory+',''0'')
						END AS SubCategory
							FROM 
							sStudent.vStudentAcademic SA
							LEFT JOIN sStudent.tAcademicDetail AD ON AD.AcademicId=SA.AcademicId
							Where SA.OrgId='+CAST(@rOrgId AS nvarchar(15))
							+'AND (SA.ClassId='+CAST(@rClassId AS nvarchar(15))+ 'OR '+CAST(@rClassId AS nvarchar(15))+'=0)
							AND (SA.DivisionId='+CAST(@rDivisionId AS nvarchar(15))+ 'OR '+CAST(@rDivisionId AS nvarchar(15))+'=0)
							AND (SA.BatchId='+CAST(@rBatchId AS nvarchar(15))+')
							AND (SA.StatusId='+ CAST(@rStatusId AS nvarchar(15)) +' OR '+CAST(@rStatusId AS nvarchar(15))+'=0)
							AND 
							('+CAST(@rIsBlank AS nvarchar(1))+'=0 
								OR ('+@lDataTypeId+'=1 AND ISNULL(AD.'+@rSubCategory+','''')='''')
								OR ('+@lDataTypeId+'=2 AND ISNULL(AD.'+@rSubCategory+',''0'')=''0'')
								OR ('+@lDataTypeId+'=3 AND ISNULL(AD.'+@rSubCategory+',''False'')=''False'')
								OR ('+@lDataTypeId+'=4 AND ISNULL(AD.'+@rSubCategory+',''0001/01/01'')=''0001/01/01'') 
							)'
					WHEN 7 THEN --General
					   'Select SA.StudentId,SA.AcademicId,SA.Code,SA.Name,SA.ClassName+'' - ''+SA.DivisionName AS ClassDivision,SA.RollNo,SA.Number,
						CASE WHEN '+@lDataTypeId+'=1 THEN
						ISNULL(SAH.'+@rSubCategory+','''')
						WHEN '+@lDataTypeId+'=2 THEN
						ISNULL(SAH.'+@rSubCategory+',''0'')
						WHEN '+@lDataTypeId+'=3 THEN
						ISNULL(SAH.'+@rSubCategory+',''False'')
						WHEN '+@lDataTypeId+'=4 THEN
						ISNULL(SAH.'+@rSubCategory+',''0001/01/01'')
						WHEN '+@lDataTypeId+'=5 THEN
						ISNULL(SAH.'+@rSubCategory+',''0'')
						END AS SubCategory
							FROM 
							sStudent.vStudentAcademic SA
							LEFT JOIN sStudent.tStudentMaster SAH ON SAH.Id=SA.StudentId
							Where SA.OrgId='+CAST(@rOrgId AS nvarchar(15))
							+'AND (SA.ClassId='+CAST(@rClassId AS nvarchar(15))+ 'OR '+CAST(@rClassId AS nvarchar(15))+'=0)
							AND (SA.DivisionId='+CAST(@rDivisionId AS nvarchar(15))+ 'OR '+CAST(@rDivisionId AS nvarchar(15))+'=0)
							AND (SA.StatusId='+ CAST(@rStatusId AS nvarchar(15)) +' OR '+CAST(@rStatusId AS nvarchar(15))+'=0)
							AND (SA.BatchId='+CAST(@rBatchId AS nvarchar(15))+')
							AND 
							('+CAST(@rIsBlank AS nvarchar(1))+'=0 
								OR ('+@lDataTypeId+'=1 AND ISNULL(SAH.'+@rSubCategory+','''')='''')
								OR ('+@lDataTypeId+'=2 AND ISNULL(SAH.'+@rSubCategory+',''0'')=''0'')
								OR ('+@lDataTypeId+'=3 AND ISNULL(SAH.'+@rSubCategory+',''False'')=''False'')
								OR ('+@lDataTypeId+'=4 AND ISNULL(SAH.'+@rSubCategory+',''0001/01/01'')=''0001/01/01'') 
							)'
					WHEN 8 THEN --Additonal Information
					   'Select SA.StudentId,SA.AcademicId,SA.Code,SA.Name,SA.ClassName+'' - ''+SA.DivisionName AS ClassDivision,SA.RollNo,SA.Number,
						CASE WHEN '+@lDataTypeId+'=1 THEN
						ISNULL(SAH.'+@rSubCategory+','''')
						WHEN '+@lDataTypeId+'=2 THEN
						ISNULL(SAH.'+@rSubCategory+',''0'')
						WHEN '+@lDataTypeId+'=3 THEN
						ISNULL(SAH.'+@rSubCategory+',''False'')
						WHEN '+@lDataTypeId+'=4 THEN
						ISNULL(SAH.'+@rSubCategory+',''0001/01/01'')
						WHEN '+@lDataTypeId+'=5 THEN
						ISNULL(SAH.'+@rSubCategory+',''0'')
						END AS SubCategory
							FROM 
							sStudent.vStudentAcademic SA
							LEFT JOIN sStudent.tStudentAdditional SAH ON SAH.StudentId=SA.StudentId
							Where SA.OrgId='+CAST(@rOrgId AS nvarchar(15))
							+'AND (SA.ClassId='+CAST(@rClassId AS nvarchar(15))+ 'OR '+CAST(@rClassId AS nvarchar(15))+'=0)
							AND (SA.DivisionId='+CAST(@rDivisionId AS nvarchar(15))+ 'OR '+CAST(@rDivisionId AS nvarchar(15))+'=0)
							AND (SA.StatusId='+ CAST(@rStatusId AS nvarchar(15)) +' OR '+CAST(@rStatusId AS nvarchar(15))+'=0)
							AND (SA.BatchId='+CAST(@rBatchId AS nvarchar(15))+')
							AND 
							('+CAST(@rIsBlank AS nvarchar(1))+'=0 
								OR ('+@lDataTypeId+'=1 AND ISNULL(SAH.'+@rSubCategory+','''')='''')
								OR ('+@lDataTypeId+'=2 AND ISNULL(SAH.'+@rSubCategory+',''0'')=''0'')
								OR ('+@lDataTypeId+'=3 AND ISNULL(SAH.'+@rSubCategory+',''False'')=''False'')
								OR ('+@lDataTypeId+'=4 AND ISNULL(SAH.'+@rSubCategory+',''0001/01/01'')=''0001/01/01'') 
							)'	
					
					WHEN 9 THEN --Student Sibling
					   'Select SA.StudentId,SA.AcademicId,SA.Code,SA.Name,SA.ClassName+'' - ''+SA.DivisionName AS ClassDivision,SA.RollNo,SA.Number,
						CASE WHEN '+@lDataTypeId+'=1 THEN
						ISNULL(SS.'+@rSubCategory+','''')
						WHEN '+@lDataTypeId+'=2 THEN
						ISNULL(SS.'+@rSubCategory+',''0'')
						WHEN '+@lDataTypeId+'=3 THEN
						ISNULL(SS.'+@rSubCategory+',''False'')
						WHEN '+@lDataTypeId+'=4 THEN
						ISNULL(SS.'+@rSubCategory+',''0001/01/01'')
						WHEN '+@lDataTypeId+'=5 THEN
						ISNULL(SS.'+@rSubCategory+',''0'')
						END AS SubCategory
							FROM 
							sStudent.vStudentAcademic SA
							LEFT JOIN sStudent.tStudentSibling SS ON SS.StudentId=SA.StudentId
							Where SA.OrgId='+CAST(@rOrgId AS nvarchar(15))
							+'AND (SA.ClassId='+CAST(@rClassId AS nvarchar(15))+ 'OR '+CAST(@rClassId AS nvarchar(15))+'=0)
							AND (SA.DivisionId='+CAST(@rDivisionId AS nvarchar(15))+ 'OR '+CAST(@rDivisionId AS nvarchar(15))+'=0)
							AND (SA.StatusId='+ CAST(@rStatusId AS nvarchar(15)) +' OR '+CAST(@rStatusId AS nvarchar(15))+'=0)
							AND (SA.BatchId='+CAST(@rBatchId AS nvarchar(15))+')
							AND 
							('+CAST(@rIsBlank AS nvarchar(1))+'=0 
								OR ('+@lDataTypeId+'=1 AND ISNULL(SS.'+@rSubCategory+','''')='''')
								OR ('+@lDataTypeId+'=2 AND ISNULL(SS.'+@rSubCategory+',''0'')=''0'')
								OR ('+@lDataTypeId+'=3 AND ISNULL(SS.'+@rSubCategory+',''False'')=''False'')
								OR ('+@lDataTypeId+'=4 AND ISNULL(SS.'+@rSubCategory+',''0001/01/01'')=''0001/01/01'') 
							)'	
					END				
					
		print @Sql    
		
	   
	   EXECUTE  sp_executesql @Sql
	
END
GO
PRINT N'Altering [sStudent].[pStudentDetailUpdate]...';


GO
 
ALTER PROCEDURE [sStudent].[pStudentDetailUpdate]
	 
	@rStudentId Bigint=0,
	@rCategory int,
	@rSubCategory nvarchar(20),
	@rStrXml nvarchar(max)=''
AS
SET NOCOUNT ON
SET @rStrXml=REPLACE(@rStrXml,'&','AND')
DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml
BEGIN
		 if @rCategory=1
		 BEGIN
			IF @rSubCategory='Present Address'
			BEGIN
				Update sStudent.tStudentCommunication
				Set
					PresentStreetOne=A.PresentStreetOne,
					PresentStreetTwo=A.PresentStreetTwo,
					PresentStreetThree=A.PresentStreetThree,
					PresentCountry=A.PresentCountry,
					PresentState=A.PresentState,
					PresentCity=A.PresentCity,
					PresentZipCode=A.PresentZipCode,
					PresentContactNo=A.PresentContactNo
				From
				(
					Select StudentId,PresentStreetOne,PresentStreetTwo,PresentStreetThree,PresentCountry,
					       PresentState,PresentCity,PresentZipCode,PresentContactNo
					from openxml (@loDoc,'/Table/Student',1)
					with
					(
						StudentId bigint,
						PresentStreetOne nvarchar(100),
						PresentStreetTwo nvarchar(100),
						PresentStreetThree nvarchar(100),
						PresentCountry nvarchar(50),
						PresentState nvarchar(50),
						PresentCity nvarchar(50),
						PresentZipCode nvarchar(50),
						PresentContactNo nvarchar(50)
					)	   
				)A Where sStudent.tStudentCommunication.StudentId=A.StudentId
			END
			IF @rSubCategory='Permanent Address'
			BEGIN
				Update sStudent.tStudentCommunication
				Set
					PermanentStreetOne=A.PresentStreetOne,
					PermanentStreetTwo=A.PresentStreetTwo,
					PermanentStreetThree=A.PresentStreetThree,
					PermanentCountry=A.PresentCountry,
					PermanentState=A.PresentState,
					PermanentCity=A.PresentCity,
					PermanentZipCode=A.PresentZipCode,
					PermanentContactNo=A.PresentContactNo
				from
				(
					Select StudentId,PresentStreetOne,PresentStreetTwo,PresentStreetThree,PresentCountry,
						    PresentState,PresentCity,PresentZipCode,PresentContactNo
					From openXml(@loDoc,'/Table/Student',1)
					With
					(
						StudentId bigint,
						PresentStreetOne nvarchar(150),
						PresentStreetTwo nvarchar(150),
						PresentStreetThree nvarchar(150),
						PresentCountry nvarchar(50),
						PresentState nvarchar(50),
						PresentCity nvarchar(50),
						PresentZipCode nvarchar(20),
						PresentContactNo nvarchar(20)
					)	
				)A Where sStudent.tStudentCommunication.StudentId=A.StudentId
			END
			IF @rSubCategory='Emergency Address'
			BEGIN
				Update sStudent.tStudentCommunication
				Set
					EmergencyStreetOne=A.PresentStreetOne,
					EmergencyStreetTwo=A.PresentStreetTwo,
					EmergencyStreetThree=A.PresentStreetThree,
					EmergencyCountry=A.PresentCountry,
					EmergencyState=A.PresentState,
					EmergencyCity=A.PresentCity,
					EmergencyZipCode=A.PresentZipCode,
					EmergencyContactNo=A.PresentContactNo
				From
				(
					Select StudentId,PresentStreetOne,PresentStreetTwo,PresentStreetThree,PresentCountry,
						    PresentState,PresentCity,PresentZipCode,PresentContactNo
					From Openxml(@loDoc,'Table/Student',1)
					With
					(
						StudentId Bigint,
						PresentStreetOne nvarchar(150),
						PresentStreetTwo nvarchar(150),
						PresentStreetThree nvarchar(150),
						PresentCountry nvarchar(20),
						PresentState nvarchar(20),
						PresentCity nvarchar(20),
						PresentZipCode nvarchar(20),
						PresentContactNo nvarchar(20) 
					)
				) A Where sStudent.tStudentCommunication.StudentId=A.StudentId
			END
		END
		If @rCategory=2
		BEGIN
			If @rSubCategory='Father'
			BEGIN
				Update sStudent.tStudentFamily
				Set
					FatherName=A.Name,
					FatherDateOfBirth=A.DateOfBirth,
					FatherOccupation=A.Occupation,
					FatherQualification=A.Qualification,
					FatherContactNo=A.ContactNo,
					FatherMail=A.Mail,
					FatherOfficeAddress=A.OfficeAddress,
					FatherIncome=A.Income
				From
				(
					Select StudentId,Name,DateOfBirth,Occupation,
							Qualification,ContactNo,Mail,OfficeAddress,Income
					from openxml(@loDoc,'Table/Student',1)
					with
					(
						StudentId bigint,
						Name nvarchar(100),
						DateOfBirth date,
						Occupation nvarchar(50),
						Qualification nvarchar(50),
						ContactNo nvarchar(50),
						Mail nvarchar(50),
						OfficeAddress nvarchar(50),
						Income int
					)
				)A Where sStudent.tStudentFamily.StudentId=A.StudentId
			END
			IF @rSubCategory='Mother'
			BEGIN
				update sStudent.tStudentFamily 
				Set
					MotherName=A.Name,
					MotherDateOfBirth=A.DateOfBirth,
					MotherOccupation=A.Occupation,
					MotherQualification=A.Qualification,
					MotherContactNo=A.ContactNo,
					MotherMail=A.Mail,
					MotherOfficeAddress=A.OfficeAddress,
					MotherIncome=A.Income
				from
				(
					Select StudentId,Name,DateOfBirth,Occupation,
							Qualification,ContactNo,Mail,OfficeAddress,Income
					
					from openxml(@loDoc,'Table/Student',1)
					With
					(
						StudentId bigint,
						Name nvarchar(100),
						DateOfBirth date,
						Occupation nvarchar(50),
						Qualification nvarchar(50),
						ContactNo nvarchar(20),
						Mail nvarchar(50),
						OfficeAddress nvarchar(50),
						Income int
					)
				)A Where sStudent.tStudentFamily.StudentId=A.StudentId
			END
			IF @rSubCategory ='Relative'
			BEGIN
				Update sStudent.tStudentFamily 
				Set 
					RelationshipName =A.RelationshipName,
					RelativeName=A.Name,
					RelativeDateOfBirth=A.DateOfBirth,
					RelativeOccupation=A.Occupation,
					RelativeQualification=A.Qualification,
					RelativeContactNo=A.ContactNo,
					RelativeMail=A.Mail,
					RelativeOfficeAddress=A.OfficeAddress,
					RelativeIncome=A.Income
				From
				(
					Select StudentId,RelationshipName,Name,DateOfBirth,Occupation,
							Qualification,ContactNo,Mail,OfficeAddress,Income
					From Openxml(@loDoc,'Table/Student',1)
						With
						(
							StudentId bigint,
							RelationshipName nvarchar(100),
							Name nvarchar(100),
							DateOfBirth date,
							Occupation nvarchar(50),
							Qualification nvarchar(50),
							ContactNo nvarchar(20),
							Mail nvarchar(50),
							OfficeAddress nvarchar(50),
							Income int
						)
				)A Where sStudent.tStudentFamily.StudentId=A.StudentId
			END
		END
		If @rCategory=3
		BEGIN
			DECLARE @Str varchar(500)=''
			IF @rSubCategory ='Academic'
			BEGIN
				Create Table #table1
				(
					FirstName nvarchar(100),
					MiddleName nvarchar(100),
					LastName nvarchar(100),
					StudentId bigint,
					AdmissionStandardId int,
					AdmissionDate date,
					GenderId int,
					DateOfBirth date
				)
				Insert into #table1
				Select FirstName,MiddleName,LastName,StudentId, AdmissionStandardId,AdmissionDate,GenderId,DateOfBirth
					From Openxml(@loDoc,'Table/Student',1)
						With
						( 
							FirstName nvarchar(100),
							MiddleName nvarchar(100),
							LastName nvarchar(100),
							StudentId bigint,
							AdmissionStandardId int,
							AdmissionDate date,
							GenderId int,
							DateOfBirth Date
						) 
			 IF Exists (SELECT 1 FROM #table1 WHERE AdmissionDate <= DateOfBirth)
			BEGIN
					--Set @Str=''
					--SELECT @Str=COALESCE(@Str,'')+CAST(FirstName As nvarchar(50))+ ',' FROM #table1 WHERE AdmissionDate >= DateOfBirth
					select -109,@Str AS Result
			RETURN		
			END 
			-- --Select * from #table1
				Update  Stu
				Set
					FirstName =T.FirstName,
					MiddleName=T.MiddleName,
					LastName=T.LastName 
					
				From sStudent.tStudentMaster Stu
				INNER JOIN #table1 T ON T.StudentId =Stu.Id
				Where Stu.Id =T.StudentId
					
				Update A
				Set 
						AdmissionDate=T.AdmissionDate,
						AdmissionStandardId =T.AdmissionStandardId
				from sStudent.tStudentAdmission A 
				INNER JOIN #table1 T ON T.StudentId =A.StudentId
				
				 
				
				Update SO 
				Set
					GenderId =T1.GenderId,
					
					DateOfBirth=T1.DateOfBirth
				From sStudent.tStudentOther SO 
				INNER JOIN #table1 T1 ON T1.StudentId=So.StudentId
				
				
				
				
				--Update sStudent.tStudentMaster
				--Set
				--	FirstName =SM.FirstName,
				--	MiddleName=SM.MiddleName,
				--	LastName=SM.LastName
					
				--From
				--(
				--	Select StudentId,FirstName,MiddleName,LastName
				--	From Openxml(@loDoc,'Table/Student',1)
				--		With
				--		(
				--			StudentId bigint,
				--			FirstName nvarchar(100),
				--			MiddleName nvarchar(100),
				--			LastName nvarchar(100)
				--		) 
				--)SM 
				--Where sStudent.tStudentMaster.Id=SM.StudentId
				
				 
				--Update sStudent.tAcademic
				--Set
				--	ClassID=AC.CLassId,
				--	DivisionId=AC.DivisionID
				--From
				--(
				--	Select StudentID,ClassID,DivisionId
				--	from OpenXml(@loDoc,'Table/Student',1)
				--	With
				--	(
				--		StudentID bigint,
				--		ClassID int,
				--		DivisionID int
				--	)
				--)AC Where sStudent.tAcademic.StudentId=AC.StudentID
				 
				--Update sStudent.tStudentAdmission
				--Set
				--	AdmissionStandardId =A.AdmissionStandardId,
				--	AdmissionDate =A.AdmissionDate
				--From
				--(
				--	Select StudentID,AdmissionStandardId,AdmissionDate
				--	from Openxml(@loDoc,'Table/Student',1)
				--	With
				--	(
				--		StudentID Bigint,
				--		AdmissionStandardId int,
				--		AdmissionDate date
				--	)
				--)A Where sStudent.tStudentAdmission.StudentId=A.StudentID
			 END
			 
			 
			 
			 
			IF @rSubCategory ='Main Group'
			BEGIN
				 Update sStudent.tStudentMaster Set StudentGroupId=A.StudentGroupId
				 
				 From
				(
					Select StudentId,StudentGroupId
					From Openxml(@loDoc,'Table/Student',1)
						With
						(
							StudentId bigint,
							StudentGroupId int
						)
				)A Where sStudent.tStudentMaster.Id=A.StudentId
			 END
			 
			 IF @rSubCategory ='Other Group'
			BEGIN
				 Update sStudent.tStudentMaster Set StudentOtherGroupId=A.StudentGroupId
				 
				 From
				(
					Select StudentId,StudentGroupId
					From Openxml(@loDoc,'Table/Student',1)
						With
						(
							StudentId bigint,
							StudentGroupId int
						)
				)A Where sStudent.tStudentMaster.Id=A.StudentId
			 END
		END
		 	Select 1 As Result
END
GO
PRINT N'Altering [sStudent].[pStudentDetailUpdateGet]...';


GO
ALTER PROCEDURE [sStudent].[pStudentDetailUpdateGet]
	 
	 @rCategoryId int,
	 @rSubCategory nvarchar(100),
	 @rOrgId int,
	 @rClassId int,
	 @rDivisionId int,
	 @rBatchId int,
	 --@rIsBlank bit,
	 @rStatusId int,
	 @rOrderBy int
	 
AS
SET NOCOUNT ON

BEGIN
	 	DECLARE @lDataTypeId nvarchar(1)
		SELECT @lDataTypeId=DataTypeId FROM sCommon.tUpdateFieldMaster WHERE Field=@rSubCategory
		 
		 
		 IF @rCategoryId=1 
		 BEGIN-- Communication
			IF @rSubCategory ='Present Address'
			BEGIN
				Select  SA.StudentId,SA.AcademicId,SA.Name,SA.ClassName+' - '+SA.DivisionName AS ClassDivision,SA.RollNo,SA.Code,
						PresentStreetOne,
						PresentStreetTwo,
						PresentStreetThree,
						PresentCountry,
						PresentState,
						PresentCity,
						PresentZipCode,
						PresentContactNo
				FROM 
				sStudent.vStudentAcademic SA
				LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=SA.StudentId
				Where SA.OrgId=@rOrgId
				AND ((SA.ClassId=@rClassId) OR (@rClassId =0))
				AND ((SA.DivisionId=@rDivisionId) OR  (@rDivisionId=0))
				AND ((SA.StatusId= @rStatusId ) OR  (@rStatusId  =0))
				AND ((SA.BatchId= @rBatchId )) 
			END
			IF @rSubCategory ='Permanent Address'
			BEGIN
				Select  SA.StudentId,SA.AcademicId,SA.Name,SA.ClassName+' - '+SA.DivisionName AS ClassDivision,SA.RollNo,SA.Code,
						PermanentStreetOne As PresentStreetOne,
						PermanentStreetTwo AS PresentStreetTwo,
						PermanentStreetThree AS PresentStreetThree,
						PermanentCountry AS PresentCountry,
						PermanentState AS PresentState,
						PermanentCity As PresentCity,
						PermanentZipCode As PresentZipCode,
						PermanentContactNo AS PresentContactNo
				FROM 
				sStudent.vStudentAcademic SA
				LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=SA.StudentId
				Where SA.OrgId=@rOrgId
				AND ((SA.ClassId=@rClassId) OR (@rClassId =0))
				AND ((SA.DivisionId=@rDivisionId) OR  (@rDivisionId=0))
				AND ((SA.StatusId= @rStatusId ) OR  (@rStatusId  =0))
				AND ((SA.BatchId= @rBatchId )) 
			END
			IF @rSubCategory ='Emergency Address'
			BEGIN
				Select  SA.StudentId,SA.AcademicId,SA.Name,SA.ClassName+' - '+SA.DivisionName AS ClassDivision,SA.RollNo,SA.Code,
						EmergencyStreetOne AS PresentStreetOne,
						EmergencyStreetTwo As PresentStreetTwo, 
						EmergencyStreetThree As PresentStreetThree,
						EmergencyCountry As PresentCountry,
						EmergencyState As PresentState,
						EmergencyCity AS PresentCity,
						EmergencyZipCode As PresentZipCode,
						EmergencyContactNo  AS PresentContactNo
				FROM 
				sStudent.vStudentAcademic SA
				LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=SA.StudentId
				Where SA.OrgId=@rOrgId
				AND ((SA.ClassId=@rClassId) OR (@rClassId =0))
				AND ((SA.DivisionId=@rDivisionId) OR  (@rDivisionId=0))
				AND ((SA.StatusId= @rStatusId ) OR  (@rStatusId  =0))
				AND ((SA.BatchId= @rBatchId )) 
			END
		END
		IF @rCategoryId= 4 
		BEGIN --Family
			IF @rSubCategory ='Father'
				BEGIN
					Select  SA.StudentId,SA.AcademicId,SA.Name,SA.ClassName+' - '+SA.DivisionName AS ClassDivision,SA.RollNo,SA.Code,
							FatherName,FatherDateOfBirth,FatherOccupation,FatherQualification,FatherContactNo,FatherMail,
							FatherOfficeAddress,FatherIncome
					FROM 
					sStudent.vStudentAcademic SA
					LEFT JOIN sStudent.tStudentFamily SC ON SC.StudentId=SA.StudentId
					Where SA.OrgId=@rOrgId
				AND ((SA.ClassId=@rClassId) OR (@rClassId =0))
				AND ((SA.DivisionId=@rDivisionId) OR  (@rDivisionId=0))
				AND ((SA.StatusId= @rStatusId ) OR  (@rStatusId  =0))
				AND ((SA.BatchId= @rBatchId )) 
			END
			IF @rSubCategory ='Mother'
				BEGIN
					Select  SA.StudentId,SA.AcademicId,SA.Name,SA.ClassName+' - '+SA.DivisionName AS ClassDivision,SA.RollNo,SA.Code,
							MotherName,MotherDateOfBirth,MotherOccupation,MotherQualification,MotherContactNo,MotherMail,
							MotherOfficeAddress,MotherIncome
					FROM 
					sStudent.vStudentAcademic SA
					LEFT JOIN sStudent.tStudentFamily SC ON SC.StudentId=SA.StudentId
					Where SA.OrgId=@rOrgId
					AND ((SA.ClassId=@rClassId) OR (@rClassId =0))
				AND ((SA.DivisionId=@rDivisionId) OR  (@rDivisionId=0))
				AND ((SA.StatusId= @rStatusId ) OR  (@rStatusId  =0))
				AND ((SA.BatchId= @rBatchId )) 
			END
			IF @rSubCategory ='Relative'
				BEGIN
					Select  SA.StudentId,SA.AcademicId,SA.Name,SA.ClassName+' - '+SA.DivisionName AS ClassDivision,SA.RollNo,SA.Code,
							RelativeName,RelativeDateOfBirth,RelativeOccupation,RelativeQualification,RelativeContactNo,RelativeMail,
							RelativeOfficeAddress,RelativeIncome,RelationshipName
					FROM 
					sStudent.vStudentAcademic SA
					LEFT JOIN sStudent.tStudentFamily SC ON SC.StudentId=SA.StudentId
					Where SA.OrgId=@rOrgId
					AND ((SA.ClassId=@rClassId) OR (@rClassId =0))
				AND ((SA.DivisionId=@rDivisionId) OR  (@rDivisionId=0))
				AND ((SA.StatusId= @rStatusId ) OR  (@rStatusId  =0))
				AND ((SA.BatchId= @rBatchId )) 
			END
			
		END			
		IF @rCategoryId= 10 
		BEGIN
			IF @rSubCategory ='Academic'
			BEGIN
				if @rOrderBY=1
				 BEGIN
					 Select 
						SA.StudentId,SA.Code,SA.FirstName,SA.MiddleName,SA.LastName,SA.ClassName,SA.ClassId,SA.DivisionID,
						SA.DivisionName,convert(date,SO.DateOfBirth) As DateOfBirth,AD.AdmissionDate,AD.AdmissionStandardId,SA.Name,Sa.RollNo,SO.GenderId
					From  
						 sStudent.vStudentAcademic SA
						INNER JOIN sStudent.tStudentOther SO 
									ON SO.StudentId=SA.StudentId
						LEFT JOIN sStudent.tStudentAdmission AD
									ON AD.StudentID = SA.StudentId  
					Where SA.OrgId=@rOrgId
						AND ((SA.ClassId=@rClassId) OR (@rClassId =0))
					AND ((SA.DivisionId=@rDivisionId) OR  (@rDivisionId=0))
					AND ((SA.StatusId= @rStatusId ) OR  (@rStatusId  =0))
					AND ((SA.BatchId= @rBatchId )) 
					Order by RollNo
				END
				else
				BEGIN
				Select 
						SA.StudentId,SA.Code,SA.FirstName,SA.MiddleName,SA.LastName,SA.ClassName,SA.ClassId,SA.DivisionID,
						SA.DivisionName,convert(date,SO.DateOfBirth) DateOfBirth,AD.AdmissionDate,AD.AdmissionStandardId,SA.Name,Sa.RollNo,SO.GenderId
					From  
						 sStudent.vStudentAcademic SA
						INNER JOIN sStudent.tStudentOther SO 
									ON SO.StudentId=SA.StudentId
						LEFT JOIN sStudent.tStudentAdmission AD
									ON AD.StudentID = SA.StudentId  
					Where SA.OrgId=@rOrgId
						AND ((SA.ClassId=@rClassId) OR (@rClassId =0))
					AND ((SA.DivisionId=@rDivisionId) OR  (@rDivisionId=0))
					AND ((SA.StatusId= @rStatusId ) OR  (@rStatusId  =0))
					AND ((SA.BatchId= @rBatchId )) 
					Order by Code
				END
			END
			
			IF @rSubCategory ='Main Group'
			BEGIN
				if @rOrderBY=1
				 BEGIN
					 Select 
						SA.StudentId,SA.Code,SA.FirstName,SA.MiddleName,SA.LastName,SA.ClassName,SA.ClassId,SA.DivisionID,
						SA.DivisionName,AD.Id,ISNULl(AD.Code,'') AS groupCode,ISNULl(AD.Title,'') AS Title,SA.Name,Sa.RollNo 
					From  
						 sStudent.vStudentAcademic SA
						
						LEFT JOIN sStudent.tStudentGroupMaster AD
									ON AD.Id = SA.StudentGroupId  
					Where SA.OrgId=@rOrgId
						AND ((SA.ClassId=@rClassId) OR (@rClassId =0))
					AND ((SA.DivisionId=@rDivisionId) OR  (@rDivisionId=0))
					AND ((SA.StatusId= @rStatusId ) OR  (@rStatusId  =0))
					AND ((SA.BatchId= @rBatchId )) 
					Order by RollNo
				END
				else
				BEGIN
				Select 
						SA.StudentId,SA.Code,SA.FirstName,SA.MiddleName,SA.LastName,SA.ClassName,SA.ClassId,SA.DivisionID,
						SA.DivisionName,AD.Id,ISNULl(AD.Code,'') AS groupCode,ISNULl(AD.Title,'') As Title,SA.Name,Sa.RollNo 
					From  
						 sStudent.vStudentAcademic SA
						
						LEFT JOIN sStudent.tStudentGroupMaster AD
									ON AD.Id = SA.StudentGroupId  
					Where SA.OrgId=@rOrgId
						AND ((SA.ClassId=@rClassId) OR (@rClassId =0))
					AND ((SA.DivisionId=@rDivisionId) OR  (@rDivisionId=0))
					AND ((SA.StatusId= @rStatusId ) OR  (@rStatusId  =0))
					AND ((SA.BatchId= @rBatchId )) 
					Order by SA.Code
				END
			END
			
			IF @rSubCategory ='Other Group'
			BEGIN
				if @rOrderBY=1
				 BEGIN
					 Select 
						SA.StudentId,SA.Code,SA.FirstName,SA.MiddleName,SA.LastName,SA.ClassName,SA.ClassId,SA.DivisionID,
						SA.DivisionName,AD.Id,ISNULl(AD.Code,'') As groupCode,ISNULl(AD.Title,'') AS Title,SA.Name,Sa.RollNo 
					From  
						 sStudent.vStudentAcademic SA
						
						LEFT JOIN sStudent.tStudentOtherGroupMaster AD
									ON AD.Id = SA.StudentOtherGroupId  
					Where SA.OrgId=@rOrgId
						AND ((SA.ClassId=@rClassId) OR (@rClassId =0))
					AND ((SA.DivisionId=@rDivisionId) OR  (@rDivisionId=0))
					AND ((SA.StatusId= @rStatusId ) OR  (@rStatusId  =0))
					AND ((SA.BatchId= @rBatchId )) 
					Order by RollNo
				END
				else
				BEGIN
				Select 
						SA.StudentId,SA.Code,SA.FirstName,SA.MiddleName,SA.LastName,SA.ClassName,SA.ClassId,SA.DivisionID,
						SA.DivisionName,Ad.Id,ISNULl(AD.Code,'') As groupCode,ISNULl(AD.Title,'') As Title,SA.Name,Sa.RollNo 
					From  
						 sStudent.vStudentAcademic SA
						
						LEFT JOIN sStudent.tStudentOtherGroupMaster AD
									ON AD.Id = SA.StudentOtherGroupId  
					Where SA.OrgId=@rOrgId
						AND ((SA.ClassId=@rClassId) OR (@rClassId =0))
					AND ((SA.DivisionId=@rDivisionId) OR  (@rDivisionId=0))
					AND ((SA.StatusId= @rStatusId ) OR  (@rStatusId  =0))
					AND ((SA.BatchId= @rBatchId )) 
					Order by SA.Code
				END
			END
		END
	 
		   
END
GO
PRINT N'Altering [sStudent].[pStudentFullGet]...';


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,
	@rSUId nvarchar(20)=''
	
	
	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,
			ISNULL(SF.EnrollmentStatusId,0) AS  BatchStatusId,
			ISNULL(BS.Title,'') AS BatchStatus,
			'' AS Remark,
			'01/01/1900' AS  StatusDate
			--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 = SF.EnrollmentStatusId
           --LEFT JOIN sStudent.tStudentBatchStatus SB ON SB.AcademicId = SF.AcademicId
           --LEFT JOIN sStudent.tBatchStatusMaster BS ON BS.Id = SB.BatchStatusId
           INNER JOIN  sStudent.tStudentMaster  SM ON SM.Id=SF.StudentId 
  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 (BM.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId = 0)
		AND((SF.DepartmentId=@rDepartmentId)OR(@rDepartmentId=0))
		AND ((SF.EnrollmentStatusId =@rBatchStatusId) OR (@rBatchStatusId=0))
		AND((SM.SUId= @rSUId) OR (ISNULL(@rSUId,'') = '')) 
	
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,
			ISNULL(SF.EnrollmentStatusId,0) AS  BatchStatusId,
			ISNULL(BS.Title,'') AS BatchStatus,
			'' Remark,
			'01/01/1900'  AS  StatusDate 
			--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 = SF.EnrollmentStatusId
           --LEFT JOIN sStudent.tStudentBatchStatus SB ON SB.AcademicId = SF.AcademicId
           --LEFT JOIN sStudent.tBatchStatusMaster BS ON BS.Id = SB.BatchStatusId
           INNER JOIN  sStudent.tStudentMaster  SM ON SM.Id=SF.StudentId 
  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 ((SF.EnrollmentStatusId =@rBatchStatusId) OR (@rBatchStatusId=0))
		AND((SM.SUId= @rSUId) OR (ISNULL(@rSUId,'') = '')) 
		
ORDER BY SF.ClassId,SF.DivisionId,SF.RollNo
END
  
		
END
GO
PRINT N'Altering [sStudent].[pStudentFullProfileGet]...';


GO

ALTER PROCEDURE [sStudent].[pStudentFullProfileGet]
	 
	 @rBatchId int,
	 @rStudentId bigint,
	 @rReportId int=0,
	 @rOrgId int,
	 @rStrCode nvarchar(max)='',
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rFromRollNo int=0,
	 @rToRollNo int=0,
	 @rStatusId int=0,
	 @rDateOfBirth int=0,
	 @rDepartmentId int=0,
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='',
	 @rOrgGroupBatchId 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(SA.PresentStreetone,'') + ' ' + ISNULL(SA.PresentStreetTwo,'') + ' ' + ISNULL(SA.PresentStreetThree,'') AS PresentAddress,
			ISNULL(SA.PresentCity,'') AS PresentCity,
			ISNULL(SA.PresentState,'') AS PresentState,
			ISNULL(SA.PresentCountry,'') AS PresentCountry,
			ISNULL(SA.PresentZipCode,'') AS PresentZipCode,
			ISNULL(SA.PresentContactNo,'') AS PresentContactNo,
			
			ISNULL(SA.EmergencyStreetOne,'') + ' ' + ISNULL(SA.EmergencyStreetTwo,'') + ' ' + ISNULL(SA.EmergencyStreetThree,'') AS EmergencyAddress,
			ISNULL(SA.EmergencyCity,'') AS EmergencyCity,
			ISNULL(SA.EmergencyState,'') AS EmergencyState,
			ISNULL(SA.EmergencyCountry,'') AS EmergencyCountry,
			ISNULL(SA.EmergencyZipCode,'') AS EmergencyZipCode,
			ISNULL(SA.EmergencyContactNo,'') AS EmergencyContactNo,
			
			ISNULL(SA.PermanentStreetOne,'') + ' ' + ISNULL(SA.PermanentStreetTwo,'') + ' ' + ISNULL(SA.PermanentStreetThree,'') AS PermanentAddress,
			ISNULL(SA.PermanentCity,'') AS PermanentCity,
			ISNULL(SA.PermanentState,'') AS PermanentState,
			ISNULL(SA.PermanentCountry,'') AS PermanentCountry,
			ISNULL(SA.PermanentZipCode,'') AS PermanentZipCode,
			ISNULL(SA.PermanentContactNo,'') AS PermanentContactNo,
			--Parent Information
			ISNULL(SF.FatherName,'') AS FatherName,
			ISNULL(SF.FatherOccupation,'') AS FatherOccupation,
			ISNULL(SF.FatherQualification,'') AS FatherQualification,
			ISNULL(SF.FatherContactNo,'') AS FatherContactNo,
			ISNULL(SF.FatherMail,'') AS FatherMail,
			ISNULL(SF.FatherOfficeAddress,'') AS FatherOfficeAddress,
			
			ISNULL(SF.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(SA.ParentEmail,'') AS ParentEmail,
			ISNULL(SA.ParentContactNo,'') As ParentContactNo,
			ISNULL(SA.StudentEmail,'') AS StudentEmail,
			ISNULL(SA.StudentContactNo,'') AS StudentContactNo,
					
	   	    --ISNULL(SA.StudentPhoto, CONVERT(VARBINARY(MAX), 0))AS StudentPhoto,
	   	   -- ISNULL(SA.FatherPhoto, CONVERT(VARBINARY(MAX), 0)) AS FatherPhoto,
	   	   -- ISNULL(SA.MotherPhoto, CONVERT(VARBINARY(MAX), 0)) AS MotherPhoto,
	   	    --ISNULL(SA.RelativePhoto, CONVERT(VARBINARY(MAX), 0)) AS RelativePhoto,
	   	   CASE WHEN @rReportId=0
			THEN ISNULL(SA.StudentPhoto, CONVERT(VARBINARY(MAX), 0))
			WHEN @rReportId=1
			THEN ISNULL(SA.StudentPhoto, CONVERT(VARBINARY(MAX), ''))
			END AS StudentPhoto,
			
			CASE WHEN @rReportId=0
			THEN ISNULL(SA.MotherPhoto, CONVERT(VARBINARY(MAX), 0))
			WHEN @rReportId=1
			THEN ISNULL(SA.MotherPhoto, CONVERT(VARBINARY(MAX), ''))
			END AS MotherPhoto,
			
			CASE WHEN @rReportId=0
			THEN ISNULL(SA.FatherPhoto, CONVERT(VARBINARY(MAX), 0))
			WHEN @rReportId=1
			THEN ISNULL(SA.FatherPhoto, CONVERT(VARBINARY(MAX), ''))
			END AS FatherPhoto,
			
			CASE WHEN @rReportId=0
			THEN ISNULL(SA.RelativePhoto, CONVERT(VARBINARY(MAX), 0))
			WHEN @rReportId=1
			THEN ISNULL(SA.RelativePhoto, CONVERT(VARBINARY(MAX), ''))
			END AS RelativePhoto,
		   -- Transport Details
		    A.VehicleName AS VehicleName,
		    A.VehicleRegistrationNumber AS VehicleRegistrationNumber,
		    A.TypeOfVehicle AS TypeOfVehicle,
		    ISNULL(A.BusRoute,'') AS BusRoute,
		    A.DriverName,
		    A.DriverMobileNo,
		    A.ConductorName,
		    A.ConductorMobileNo,
		    ISNULL(A.BusRouteDestination,'') AS BusRouteDestination,
		    
		    A.DropVehicleName AS DropVehicleName,
		    A.DropVehicleRegistrationNumber AS DropVehicleRegistrationNumber,
		    A.DropTypeOfVehicle AS DropTypeOfVehicle,
		    ISNULL(A.DropRoute,'') AS DropRoute,
		    A.DropRouteDriverName AS DropRouteDriverName,
		    A.DropRouteDriverMobileNo AS DropRouteDriverMobileNo,
		    A.DropRouteConductorName AS DropRouteConductorName,
		    A.DropRouteConductorMobileNo AS DropRouteConductorMobileNo,
		    ISNULL(A.DropDestination,'') AS DropDestination,
		    
		    --ClassTeacher Details
		    ISNULL(EMT.Id,0) AS TeacherId,
		    EMT.FirstName+' '+EMT.MiddleName+' '+EMT.LastName AS TeacherFullName,
		    EDM.Title AS TeacherDesignation,
		    EPD.Qualification AS TeacherQualification,
		    ISNULL(EI.EmployeePhoto, CONVERT(VARBINARY(MAX), 0)) AS TeacherPhoto,
		    ISNULL(DF.IsDisplayFamilyDetail,0) AS IsDisplayFamilyDetail,
		    ISNULL(DF.IsDisplaySiblingDetail,0) AS IsDisplaySiblingDetail,
		    ISNULL(DF.IsDisplayPassportDetail,0) AS IsDisplayPassportDetail,
		    ISNULL(DF.IsDisplayBankDetail,0) AS IsDisplayBankDetail,
		    ISNULL(DF.IsDisplayCBSEREGDetail,0) AS IsDisplayCBSEREGDetail,
		    ISNULL(DF.IsDisplayCollegeDetail,0) AS IsDisplayCollegeDetail,
		    ISNULL(DF.IsDisplayGOVREGNoDetail,0) AS IsDisplayGOVREGNoDetail,
		    ISNULL(DF.IsDisplayHealthDetail,0) AS IsDisplayHealthDetail,
		    ISNULL(DF.IsDisplayTransportDetail,0) AS IsDisplayTransportDetail,
		    ISNULL(DF.IsDisplayHostelDetail,0) AS IsDisplayHostelDetail,
		    ISNULL(DF.IsDisplayClubDetail,0) AS IsDisplayClubDetail,
		    
		    ISNULL(DF.IsDisplaySSCResultDDetail,0) AS IsDisplaySSCResultDDetail,
		    ISNULL(DF.IsDisplayHSCResultDetail,0) AS IsDisplayHSCResultDetail,
		    ISNULL(DF.IsDisplayJeeDetail,0) AS IsDisplayJeeDetail,
		    ISNULL(DF.IsDisplayDiplomaDetail,0) AS IsDisplayDiplomaDetail,
		    --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,
	       ISNULL(SA.MotherTongue,'') As MotherTongue,
	       ISNULL(SA.FamilyCast,'') AS FamilyCast,
	      ISNULL(CM.Nationality,'') AS Nationality,
	       ISNULL(CT.Title,'') AS CasteCategory,
	       ISnull(SA.ClassName,'') AS ClassName ,
	       ISnull( SA.DivisionName,'') AS DivisionName,
	      ISNULL( SF.IsFatherExStudent,0) AS IsFatherExStudent,
	       ISnull(SF.FatherPassOutYear,'') AS FatherPassOutYear,
	       Isnull(SF.IsMotherExStudent,0) AS IsMotherExStudent,
	       Isnull(SF.MotherPassOutYear,'') AS MotherPassOutYear,
	       ISNULL(SF.IsRelativeExStudent,0) AS IsRelativeExStudent,
	       ISNULL(SF.RelativePassOutYear,'') AS RelativePassOutYear,
	       ISNULL(Sa.PresentDistanceFromSchool,0) AS PresentDistanceFromSchool,
	        SA.StudentId,
	        SA.ClassId,
	        SA.DivisionId,
	        SA.BirthState,
	        SA.BirthCountry,
	         ISNULL(SA.PreviousStandard,'')AS PreviousStandard 
	        
	       --[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 = SA.HouseId
           LEFT JOIN sHostel.tAssignRoom AR ON AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003  AND ((AR.OrgGroupBatchId=@rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
           LEFT JOIN sHostel.tRoomMaster RM ON RM.Id=AR.RoomId
           LEFT JOIN 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 
           ( SElect AR1.SourceId,
           VM.Title AS VehicleName,
		    VM.RegistrationNumber AS VehicleRegistrationNumber,
		    TV.Title AS TypeOfVehicle,
		    ISNULL(BRM.Title,'') AS BusRoute,
		    BRM.DriverName,
		    BRM.DriverMobileNo,
		    BRM.ConductorName,
		    BRM.ConductorMobileNo,
		    ISNULL(BRDM.Title,'') AS BusRouteDestination,
		    VM.Title AS DropVehicleName,
		    VM.RegistrationNumber AS DropVehicleRegistrationNumber,
		    TV1.Title AS DropTypeOfVehicle,
		    ISNULL(BRM1.Title,'') AS DropRoute,
		    BRM1.DriverName AS DropRouteDriverName,
		    BRM1.DriverMobileNo AS DropRouteDriverMobileNo,
		    BRM1.ConductorName AS DropRouteConductorName,
		    BRM1.ConductorMobileNo AS DropRouteConductorMobileNo,
		    ISNULL(BRDM1.Title,'') AS DropDestination
		      FROM
             sTransport.tAssignRoute AR1   
           INNER JOIN sTransport.tBusRouteDestinationMaster BRDM ON BRDM.Id=AR1.PickupDestinationId AND AR1.SourceTypeId=2003
           INNER JOIN sTransport.tBusRouteMaster BRM ON BRM.Id=BRDM.BusRouteId AND ((BRM.OrgGroupBatchId=@rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
           LEFT JOIN sTransport.tVehicleMaster VM ON VM.Id=BRM.VehicleId
           LEFT JOIN sTransport.tVehicleTypeMaster TV ON TV.Id = VM.VehicleTypeId
           LEFT JOIN sTransport.tBusRouteDestinationMaster BRDM1 ON BRDM1.Id=AR1.DropDestinationId
           LEFT JOIN sTransport.tBusRouteMaster BRM1 ON BRM1.Id=BRDM1.BusRouteId AND ((BRM1.OrgGroupBatchId=@rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
           LEFT JOIN sTransport.tVehicleMaster VM1 ON VM1.Id=BRM1.VehicleId
           LEFT JOIN sTransport.tVehicleTypeMaster TV1 ON TV1.Id = VM1.VehicleTypeId) A ON A.SourceId=SA.StudentId
           LEFT JOIN sSetup.tDivisionMaster DM ON  DM.Id=SA.DivisionId
           LEFT JOIN sHrm.tEmployeeMaster EMT ON EMT.Id=DM.InchargeEmployeeId
           LEFT JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EMT.Id
           LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id=EJD.EmployeeDesignationId
           LEFT JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId=EMT.Id
           LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId=EMT.Id
           LEFT JOIN sStudent.tStudentSibling  SS ON SS.StudentId=SA.StudentId 
           LEFT JOIN sStudent.tStudentAdditional  SAD ON SAD.StudentId=SA.StudentId 
           LEFT JOIN sStudent.tCollegeDetail  CD ON CD.StudentId=SA.StudentId 
           LEFT JOIN sStudent.tAcademicDetail  ACD ON ACD.AcademicId=SA.AcademicId 
           LEFT JOIN sCommon.tMaritalStatusMaster  MS ON MS.Id=CD.MaritalStatusId
           LEFT JOIN sConfig.fDisplayFieldGet(@rOrgId) AS DF ON DF.OrgId=SA.OrgId
           LEFT JOIN sCommon.tCastCategoryMaster CT ON CT.Id = SA.CastCategoryId
           LEFT JOIN sCommon.tCountryMaster CM ON CM.Id=SA.NationalityId
  WHERE 
			((SA.StudentId=@rStudentId)OR(@rStudentId=0))
			AND((SA.BatchId=@rBatchId) OR(@rBatchId=0))
			AND (ISNULL(SA.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rStrCode,',')) OR @rStrCode='') 
			AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
			AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			AND ((SA.StudentId=@rStudentId) OR (@rStudentId=0))
			AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
			AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
			AND ((SA.StatusId=@rStatusId)OR(@rStatusId=0))
			AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
			AND((SA.OrgGroupBatchId=@rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
			--AND(SA.OrgId=@rOrgId)
			
END
GO
PRINT N'Altering [sStudent].[pStudentGenerateReport]...';


GO
 
ALTER PROCEDURE [sStudent].[pStudentGenerateReport]
	@rId bigint,
	@rTitle nvarchar(50),
	@rColumnName nvarchar(max) = '',
	@rOrderBy nvarchar(max) = 'RollNo',
	@rOrgId smallint,
	@rCode [nvarchar](20) = '',
	@rFirstName [nvarchar](50) = '',	
	@rLastName [nvarchar](50) = '',
	@rCountry [nvarchar](50) = '',
	@rState [nvarchar](50) = '',
	@rCity nvarchar(max) = '',
	@rArea nvarchar(max) = '',
	@rDivisionId nvarchar(max) = '',
	@rStatusId nvarchar(max) = '',
	@rTransportModeId nvarchar(max) = '',
	@rBusRouteDestinationId nvarchar(max) = '',
	@rBloodGroupId nvarchar(max) = '',
	@rGenderId nvarchar(max) = '',
	@rReligionId nvarchar(max) = '',
	@rCastCategoryId nvarchar(max) = '',
	@rHouseId nvarchar(max) = '',
	@rMotherTongueId nvarchar(max) = '',
	@rNationalityId nvarchar(max) = '',
	@rHobby nvarchar(50) = '',
	@rFatherQualification nvarchar(max) = '',
	@rMotherQualification nvarchar(max) = '',
	@rFatherOccupation nvarchar(max) = '',
	@rMotherOccupation nvarchar(max) = '',
	@rPreviousSchool nvarchar(max) = '',
	@rAdmissionCategoryId nvarchar(max) = '',
	@rDOBFromDate Date = '0001-01-01',
	@rDOBToDate Date = '9999-12-31',
	@rDOAFromDate Date = '0001-01-01',
	@rDOAToDate Date = '9999-12-31',
	@rDOLFromDate Date = '0001-01-01',
	@rDOLToDate Date = '9999-12-31',
	@rIsPysicalDeformity bit,
	@rIsMajorIllness bit,
	@rIsCommon bit,
	@rCreatedUserId bigint,
	@BatchId int,
	@rIsBlackList bit,
	@rFromCode nvarchar(20), 
	@rToCode nvarchar(20),
	@rDropDownStatusId int,
	@rDropDownClassId int,
	@rDropDownDivisionId int,
	@rCustomTagId nvarchar(max) = '',
	@rCustomGroupId nvarchar(max) = '',
	@rClubId nvarchar(max) = '',
	@rRepeatCount smallint=0,
	@rStudentStatusId smallint=0,
	@rHostelId nvarchar(max) = '',
	@rStudentGroupId nvarchar(max) = '',
	@rStudentOtherGroupId nvarchar(max) = '',
	@rOrgGroupBatchId int,
	@rBusRouteId nvarchar(max) = '',
	@rFeeExemption nvarchar(max)=''
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	
	IF(@rDOBFromDate IS NULL)
		SET @rDOBFromDate='0001-01-01'
	IF(@rDOBToDate IS NULL)
		SET @rDOBToDate='9999-12-31'
	IF(@rDOAFromDate IS NULL)
		SET @rDOAFromDate='0001-01-01'
	IF(@rDOAToDate IS NULL)
		SET @rDOAToDate='9999-12-31'
	IF(@rDOLFromDate IS NULL)
		SET @rDOLFromDate='0001-01-01'
	IF(@rDOLToDate IS NULL)
		SET @rDOLToDate='9999-12-31'
	IF(@rTitle != '' AND @rId = 0)
	BEGIN
	DECLARE @lNextNumber BIGINT     
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sStudent.tStudentCustomSearch', 0, 1, 1,@outNextNumber = @lNextNumber output

	INSERT INTO sStudent.tStudentCustomSearch
		(
			Id,
			Title,
			ColumnName,
			OrderBy,
			OrgId,
			Code,
			FirstName,	
			LastName,
			Country,
			State,
			City,
			Area,
			DivisionId,
			StatusId,
			TransportModeId,
			BusRouteDestinationId,
			BloodGroupId,
			GenderId,
			ReligionId,
			CastCategoryId,
			HouseId,
			MotherTongueId,
			NationalityId,
			Hobby,
			FatherQualification,
			MotherQualification,
			FatherOccupation,
			MotherOccupation,
			PreviousSchool,
			AdmissionCategoryId,
			DOBFromDate,
			DOBToDate,
			DOAFromDate,
			DOAToDate,
			DOLFromDate,
			DOLToDate,
			IsPysicalDeformity,
			IsMajorIllness,
			IsCommon,
			CreatedUserId,
			CreatedDateTime,
			IsBlackList,
			FromCode,
			ToCode,
			CustomTag,
			CustomGroup,
	        Club,
	        RepeatCount,
	        StudentStatusId,
	        Hostel,
	        StudentGroup,
	        StudentOtherGroup,
	       FeeExemption
		)
	VALUES
		(
			@lNextNumber,
			@rTitle,
			@rColumnName,
			@rOrderBy,
			@rOrgId,
			@rCode,
			@rFirstName,	
			@rLastName,
			@rCountry,
			@rState,
			@rCity,
			@rArea,
			@rDivisionId,
			@rStatusId,
			@rTransportModeId,
			@rBusRouteDestinationId,
			@rBloodGroupId,
			@rGenderId,
			@rReligionId,
			@rCastCategoryId,
			@rHouseId,
			@rMotherTongueId,
			@rNationalityId,
			@rHobby,
			@rFatherQualification,
			@rMotherQualification,
			@rFatherOccupation,
			@rMotherOccupation,
			@rPreviousSchool,
			@rAdmissionCategoryId,
			@rDOBFromDate,
			@rDOBToDate,
			@rDOAFromDate,
			@rDOAToDate,
			@rDOLFromDate,
			@rDOLToDate,
			@rIsPysicalDeformity,
			@rIsMajorIllness,
			@rIsCommon,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rIsBlackList,
			@rFromCode,
			@rToCode,
			@rCustomTagId,
			@rCustomGroupId,
	        @rClubId,
			@rRepeatCount,
			@rStudentStatusId,
			@rHostelId,
			@rStudentGroupId,
	        @rStudentOtherGroupId,
			@rFeeExemption
			
		)
		--SELECT @lNextNumber AS Result
	END
	IF(@rId > 0)
	BEGIN
		Select
				@rColumnName=ColumnName,
				@rOrderBy=OrderBy,
				@rOrgId=OrgId,
				@rCode=Code,
				@rFirstName=FirstName,	
				@rLastName=LastName,
				@rCountry=Country,
				@rState=State,
				@rCity=City,
				@rArea=Area,
				@rDivisionId=DivisionId,
				@rStatusId=StatusId,
				@rTransportModeId=TransportModeId,
				@rBusRouteDestinationId=BusRouteDestinationId,
				@rBloodGroupId=BloodGroupId,
				@rGenderId=GenderId,
				@rReligionId=ReligionId,
				@rCastCategoryId=CastCategoryId,
				@rHouseId=HouseId,
				@rMotherTongueId=MotherTongueId,
				@rNationalityId=NationalityId,
				@rHobby=Hobby,
				@rFatherQualification=FatherQualification,
				@rMotherQualification=MotherQualification,
				@rFatherOccupation=FatherOccupation,
				@rMotherOccupation=MotherOccupation,
				@rPreviousSchool=PreviousSchool,
				@rAdmissionCategoryId=AdmissionCategoryId,
				@rDOBFromDate=DOBFromDate,
				@rDOBToDate=DOBToDate,
				@rDOAFromDate=DOAFromDate,
				@rDOAToDate=DOAToDate,
				@rDOLFromDate=DOLFromDate,
				@rDOLToDate=DOLToDate,
				@rIsPysicalDeformity=IsPysicalDeformity,
				@rIsMajorIllness=IsMajorIllness,
				@rIsBlackList=IsBlackList,
				@rFromCode=FromCode,
				@rToCode=ToCode,
				@rCustomTagId=CustomTag,
				@rCustomGroupId = CustomGroup,
	            @rClubId = Club,
	            @rRepeatCount = RepeatCount,
	            @rStudentStatusId =StudentStatusId,
	            @rHostelId = Hostel,
	            @rStudentGroupId = StudentGroup,
	            @rStudentOtherGroupId = StudentOtherGroup,
	            
	           @rFeeExemption =FeeExemption
		FROM
			sStudent.tStudentCustomSearch
		WHERE
			Id=@rId
	END
	
	SET @rColumnName=Replace(@rColumnName,'ID No','Code')
	SET @rOrderBy=Replace(@rOrderBy,'ID No','Code')
	SET @rColumnName=Replace(@rColumnName,'PhysicalDeformityRemark','PysicalDeformityRemark')
	SET @rColumnName=Replace(@rColumnName,'IsPhysicalDeformity','IsPysicalDeformity')
	DECLARE @Sql nvarchar(MAX)
	
	SET @rCode = sCommon.fSearchStringGet(@rCode)
	SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
	SET @rLastName = sCommon.fSearchStringGet(@rLastName)
	SET @rCountry = sCommon.fSearchStringGet(@rCountry)
	SET @rState = sCommon.fSearchStringGet(@rState)
	--SET @rCity = sCommon.fSearchStringGet(@rCity)
	
		--IF (@rCustomTagId <> '')
		--BEGIN
		--	SELECT	
		--	DISTINCT SM.Id AS StudentId1
		--	INTO sStudent.tTempStudent3
		--	FROM sStudent.tStudentMaster SM
		--	INNER JOIN sStudent.tStudentCustomTag SCT ON SCT.StudentId=SM.Id
		--	INNER JOIN sStudent.tAcademic A ON A.StudentId = SM.Id
		--	WHERE SM.OrgId = @rOrgId  AND A.BatchId = @BatchId 
		--	AND (ISNULL(SCT.CustomTagId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rCustomTagId,','))OR @rCustomTagId='')
		--END
		--ELSE
		--BEGIN
		--	SELECT 
		--	DISTINCT NULL AS StudentId1
		--	INTO sStudent.tTempStudent3
		--END
	
		-- For Custom Tag
		IF (@rCustomTagId <> '')
		BEGIN
			SELECT 
			DISTINCT SM.Id AS StudentId1
			INTO sStudent.tTempStudent5
			FROM sStudent.tStudentMaster SM
			INNER JOIN sStudent.tStudentCustomTag SCT ON SCT.StudentId=SM.Id
			INNER JOIN sStudent.tAcademic A ON A.StudentId = SM.Id
			WHERE SM.OrgId = @rOrgId  AND A.BatchId = @BatchId 
			AND (ISNULL(SCT.CustomTagId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rCustomTagId,','))OR @rCustomTagId='')
		END
		ELSE
		BEGIN
			SELECT 
			DISTINCT NULL AS StudentId1
			INTO sStudent.tTempStudent5
		END
		
		-- For Custom Group
		IF (@rCustomGroupId <> '')
		BEGIN
			SELECT 
			DISTINCT SM.Id AS StudentId2
			INTO sStudent.tTempStudent6
			FROM sStudent.tStudentMaster SM
			INNER JOIN sStudent.tAcademic A ON A.StudentId = SM.Id
			INNER JOIN sCommunication.tCustomGroupMember CGM ON CGM.SourceId = A.Id AND CGM.SourceTypeId=2001
			WHERE SM.OrgId = @rOrgId  AND A.BatchId = @BatchId 
			AND (ISNULL(CGM.CustomGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rCustomGroupId,','))OR @rCustomGroupId='')
		END
		ELSE
		BEGIN
			SELECT 
			DISTINCT NULL AS StudentId2
			INTO sStudent.tTempStudent6
		END
		
		-- For Club Group
		IF (@rClubId <> '')
		BEGIN
			SELECT 
			DISTINCT SM.Id AS StudentId3
			INTO sStudent.tTempStudent7
			FROM sStudent.tStudentMaster SM
			INNER JOIN sStudent.tAcademic A ON A.StudentId = SM.Id
			INNER JOIN sActivity.tAssignClub AC ON AC.AcademicId = A.Id
			WHERE SM.OrgId = @rOrgId  AND A.BatchId = @BatchId 
			AND (ISNULL(AC.ClubId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClubId,','))OR @rClubId='')
		END
		ELSE
		BEGIN
			SELECT 
			DISTINCT NULL AS StudentId3
			INTO sStudent.tTempStudent7
		END
		
		-- For Hostel
		IF (@rHostelId <> '')
		BEGIN
			SELECT 
			DISTINCT SM.Id AS StudentId4
			INTO sStudent.tTempStudent9
			FROM sStudent.tStudentMaster SM
			INNER JOIN sStudent.tAcademic A ON A.StudentId = SM.Id
			INNER JOIN sHostel.tAssignRoom AR ON AR.SourceId = A.StudentId
			AND ((AR.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
			INNER JOIN sHostel.tRoomMaster RM ON RM.Id = AR.RoomId
			WHERE SM.OrgId = @rOrgId --AND A.BatchId = @BatchId 
			AND (ISNULL(RM.HostelId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rHostelId,','))OR @rHostelId='')
		END
		ELSE
		BEGIN
			SELECT 
			DISTINCT NULL AS StudentId4
			INTO sStudent.tTempStudent9
		END
	
	--Transport
		IF (@rBusRouteId <> '')
		BEGIN
			SELECT 
			DISTINCT SM.Id AS StudentId5
			INTO sStudent.tTempStudent10
			FROM sStudent.tStudentMaster SM
			INNER JOIN sStudent.tAcademic A ON A.StudentId = SM.Id
			INNER JOIN sTransport.tAssignRoute AT ON AT.SourceId = A.StudentId
			INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id = AT.PickupDestinationId
			INNER JOIN sTransport.tBusRouteMaster BRM ON BRM.Id = BM.BusRouteId
			AND ((BRM.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
			WHERE SM.OrgId = @rOrgId 
			AND (ISNULL(BRM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rBusRouteId,','))OR @rBusRouteId='')
		END
		ELSE
		BEGIN
			SELECT 
			DISTINCT NULL AS StudentId5
			INTO sStudent.tTempStudent10
		END
		
		 
		SELECT 
			* into sStudent.tTempStudent
		FROM sStudent.vStudentCustomSearch SCS
		INNER JOIN sStudent.tTempStudent5 T5 ON SCS.StudentId = T5.StudentId1 OR @rCustomTagId = ''
		INNER JOIN sStudent.tTempStudent6 T6 ON SCS.StudentId = T6.StudentId2 OR @rCustomGroupId = ''
		INNER JOIN sStudent.tTempStudent7 T7 ON SCS.StudentId = T7.StudentId3 OR @rClubId = ''
		INNER JOIN sStudent.tTempStudent9 T9 ON SCS.StudentId = T9.StudentId4 OR @rHostelId = ''
	    INNER JOIN sStudent.tTempStudent10 T10 ON SCS.StudentId = T10.StudentId5 OR @rBusRouteId = ''
	   --INNER JOIN sStudent.tTempStudent11 T11 ON SCS.StudentId = T11.StudentId6 OR @rFeeExemption = ''
		WHERE 
			SCS.OrgId = @rOrgId AND SCS.BatchId = @BatchId 
			AND ((SCS.Code Like @rCode + '%') OR (@rCode = ''))
			AND ((SCS.FirstName Like @rFirstName  + '%') OR (@rFirstName = ''))	 			 
			AND ((SCS.LastName Like @rLastName + '%')OR(@rLastName = ''))
			AND ((SCS.Hobby Like '%' + @rHobby + '%') OR (@rHobby = ''))
			AND ((ISNULL(SCS.PermanentCountry,'') Like @rCountry + '%')OR(@rCountry = ''))
			AND ((ISNULL(SCS.PermanentState,'') Like @rState + '%')OR(@rState = ''))
			--AND ((ISNULL(SCS.PermanentCity,'') Like @rCity + '%')OR(@rCity = ''))
			AND ((ISNULL(SCS.DateOfBirth,'0001-01-01') >= @rDOBFromDate) OR (ISNULL(@rDOBFromDate,'') = ''))
			AND ((ISNULL(SCS.DateOfBirth,'9999-12-31') <= @rDOBToDate) OR (ISNULL(@rDOBToDate,'') = ''))
			AND ((ISNULL(SCS.AdmissionDate,'0001-01-01') >= @rDOAFromDate) OR (ISNULL(@rDOAFromDate,'') = ''))
			AND ((ISNULL(SCS.AdmissionDate,'9999-12-31') <= @rDOAToDate) OR (ISNULL(@rDOAToDate,'') = ''))
			AND ((ISNULL(SCS.LeftDate,'0001-01-01') >= @rDOLFromDate) OR (ISNULL(@rDOLFromDate,'') = ''))
			AND ((ISNULL(SCS.LeftDate,'9999-12-31') <= @rDOLToDate) OR (ISNULL(@rDOLToDate,'') = ''))
				
			--AND (SCS.ClassId In( SELECT item FROM  sCommon.fnsplit(@rClassId,','))OR @rClassId=''))
		    
		    AND (ISNULL(SCS.PermanentCity,0) IN( SELECT item FROM  sCommon.fnsplit(@rCity,','))OR @rCity='')
		    
		    AND (ISNULL(SCS.PermanentStreetThree,0) IN( SELECT item FROM  sCommon.fnsplit(@rArea,','))OR @rArea='')
		    
		    AND (SCS.DivisionId In( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionId,','))OR @rDivisionId='')
		         	          
			AND (SCS.StatusId In( SELECT cast(item as int) FROM  sCommon.fnsplit(@rStatusId,','))OR @rStatusId='')	
	        
	        AND (SCS.TransportModeId In( SELECT cast(item as int) FROM  sCommon.fnsplit(@rTransportModeId,','))OR @rTransportModeId='')
	        
	        AND (ISNULL(SCS.BloodGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rBloodGroupId,','))OR @rBloodGroupId='') 
		    
		    AND (ISNULL(SCS.GenderId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rGenderId,','))OR @rGenderId='')
		            
		    AND (ISNULL(SCS.ReligionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rReligionId,','))OR @rReligionId='')
		           
		    AND (ISNULL(SCS.CastCategoryId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rCastCategoryId,','))OR @rCastCategoryId='')
		           
		    AND (ISNULL(SCS.HouseId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rHouseId,','))OR @rHouseId='')
		                   
		    AND (ISNULL(SCS.MotherTongueId,0) IN ( SELECT cast(item as int) FROM  sCommon.fnsplit(@rMotherTongueId,','))OR @rMotherTongueId='')
		           
		    AND (ISNULL(SCS.NationalityId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rNationalityId,','))OR @rNationalityId='')
		     
		    AND (ISNULL(SCS.BusRouteDestinationId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rBusRouteDestinationId,','))OR @rBusRouteDestinationId='')		
		    
		    AND (ISNULL(SCS.FatherQualification,'') IN( SELECT item FROM  sCommon.fnsplit(@rFatherQualification,','))OR @rFatherQualification='')
		    
		    AND (ISNULL(SCS.FatherOccupation,'') IN( SELECT item FROM  sCommon.fnsplit(@rFatherOccupation,','))OR @rFatherOccupation='')
		    
		    AND (ISNULL(SCS.MotherQualification,'') IN( SELECT item FROM  sCommon.fnsplit(@rMotherQualification,','))OR @rMotherQualification='')
		    
		    AND (ISNULL(SCS.MotherOccupation,'') IN( SELECT item FROM  sCommon.fnsplit(@rMotherOccupation,','))OR @rMotherOccupation='')
			
		    AND (ISNULL(SCS.AdmissionCategoryId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rAdmissionCategoryId,','))OR @rAdmissionCategoryId='')
		    
			AND (ISNULL(SCS.PreviousSchool,'') IN( SELECT item FROM  sCommon.fnsplit(@rPreviousSchool,','))OR @rPreviousSchool='')
		
			AND (ISNULL(SCS.RepeatCount,0) IN( SELECT item FROM  sCommon.fnsplit(@rRepeatCount,','))OR @rRepeatCount='')
			
			AND (ISNULL(SCS.StudentStatusId,0) IN( SELECT item FROM  sCommon.fnsplit(@rStudentStatusId,','))OR @rStudentStatusId='')
			
			 AND (ISNULL(SCS.StudentGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rStudentGroupId,','))OR @rStudentGroupId='')
			  
			AND (ISNULL(SCS.StudentOtherGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rStudentOtherGroupId,','))OR @rStudentOtherGroupId='')
		  
		  
			AND ((SCS.IsPysicalDeformity=@rIsPysicalDeformity) OR (@rIsPysicalDeformity=0))
		    AND ((SCS.IsMajorIllness=@rIsMajorIllness) OR (@rIsMajorIllness=0)) 
		    AND ((SCS.IsBlackList=@rIsBlackList) OR (@rIsBlackList=0))
		    AND ((SCS.Code >= @rFromCode) OR (@rFromCode=0))
		    AND ((SCS.Code <= @rToCode) OR (@rToCode=0))
			AND ((SCS.StatusId = @rDropDownStatusId) OR (@rDropDownStatusId=0))
			AND ((SCS.ClassId = @rDropDownClassId) OR (@rDropDownClassId=0))
			AND ((SCS.DivisionId = @rDropDownDivisionId) OR (@rDropDownDivisionId=0))
			AND (ISNULL(SCS.BusRouteId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rBusRouteId,','))OR @rBusRouteId='')		
			 AND (ISNULL(SCS.ExemptionTypeId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeExemption,','))OR @rFeeExemption='')		
		SET @rColumnName=Replace(@rColumnName,',Code',',Code AS [ID No]')
		--SET @rColumnName=Replace(@rColumnName,',UIDNumber',','  +'&#39;+UIDNumber AS UIDNumber')
		--SET @rColumnName=Replace(@rColumnName,',UIDNumber',',' + '''''''''' +'+UIDNumber AS UIDNumber')
		 
			--select @rColumnName
		
		
		SET @sql=
		'SELECT '+
		@rColumnName+' 
		FROM sStudent.tTempStudent ORDER BY '+@rOrderBy
		SET @sql=Replace(@sql,'SELECT Code','SELECT Code AS [ID No]')
		exec(@Sql)
		
		DROP Table sStudent.tTempStudent
		DROP Table sStudent.tTempStudent5
		DROP Table sStudent.tTempStudent6
		DROP Table sStudent.tTempStudent7
		DROP Table sStudent.tTempStudent9
		DROP Table sStudent.tTempStudent10


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


GO
 

ALTER PROCEDURE [sStudent].[pStudentImportGet]
	 
	@rClassId int=0,
	@rDivisionId int=0,
	@rOrgId int,
	@rBatchId int,
	@rStatusId int=0
	
	
	
	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,
			ISNULL(SA.FeeStructureId,0) AS FeeStructureId
			
			
    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)
		AND ((STM.Id=@rStatusId) OR (@rStatusId=0))
		
ORDER BY SA.RollNo

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


GO
ALTER PROCEDURE [sStudent].[pStudentMasterAdd]
	 
	@rId bigint,
	@rCode nvarchar(20),
	@rRegistrationNumber nvarchar(20),
	@rNumber bigint,
	@rFirstName nvarchar(100),
	@rMiddleName nvarchar(100),
	@rLastName nvarchar(100),
	@rOrgId int,
	--@rDepartmentId int,
	@rAdmissionCategoryId int,
	@rStatusId smallint,
	@rRecordStatusId smallint,
	@rCreatedUserId bigint,
	@rUpdatedUserId bigint,
	@OutStudentId BIGINT = NULL OUTPUT,
	@rSUId nvarchar(20) = '',
	@rOrgGroupId int = 0,
	@rMobileNo nvarchar(50)='',
	@rStudentGroupId int=0,
	@rStudentOtherGroupId int=0,
	@rDateOfBirth Date=NULL,
    @rGenderId int=0,
    @rOrgGroupBatchId int 
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	Declare @lStudCap int,@lOrgStudentCap int
	IF(@rNumber=0)
	SET @rNumber=NULL
	IF(@rId=0)
	BEGIN		 
	 
		--IF((@rCode = Null) OR (@rCode = ''))	
		--BEGIN

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

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

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


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


GO
ALTER PROCEDURE [sStudent].[pStudentMasterGet]
	 
	 @rCode nvarchar(20),
	 @rOrgId int,
	 @rNumber bigint,
	 @rBatchId int,
	 @rStudentId bigint,
	 @rOrgGroupBatchId int=0
	 --@rIsSearch bit
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

	DECLARE @lAcademicId bigint
	DECLARE @lIsAdmissionCategoryChange bit
	SET @lIsAdmissionCategoryChange=1
	SELECT @lAcademicId=AcademicId FROM sStudent.vStudentAcademic SA 
	WHERE 
			((SA.Code=@rCode)OR(ISNULL(@rCode,'')=''))
			AND ((SA.StudentId=@rStudentId)OR(@rStudentId=0))
			AND(SA.OrgId=@rOrgId)
			AND(SA.BatchId=@rBatchId)
			
	IF(ISNULL(@lAcademicId,0) != 0)
	BEGIN
		IF EXISTS (SELECT 1 FROM sFee.tFeeAllocation WHERE SourceTypeId=2001 AND SourceId=@lAcademicId)
		BEGIN
			SET @lIsAdmissionCategoryChange=0
		END
		ELSE IF EXISTS (SELECT 1 FROM sFee.tFeeOptional WHERE SourceTypeId=2001 AND SourceId=@lAcademicId)
		BEGIN
			SET @lIsAdmissionCategoryChange=0
		END
		ELSE IF EXISTS (SELECT 1 FROM sFee.tReceipt WHERE SourceTypeId=2001 AND SourceId=@lAcademicId)
		BEGIN
			SET @lIsAdmissionCategoryChange=0
		END
	END	
			
	 --IF(@rIsSearch=1)
		--BEGIN
		--	SET @rCode = sCommon.fSearchStringGet(@rCode)
		--	SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		--END
	
	SELECT 
			SA.StudentId AS Id,
			ISNULL(SA.Code,'') AS Code,
			ISNULL(SA.Number,0)AS Number,
			ISNULL(SA.RegistrationNumber,'') AS RegistrationNumber,
			SA.FirstName,
			ISNULL(SA.MiddleName,'')AS MiddleName,
			SA.LastName,
			SA.OrgId,
			ISNULL(SA.AdmissionCategoryId,0) AS AdmissionCategoryId,
			SA.StatusId,
			SA.RecordStatusId,
			SA.FirstName+' '+SA.LastName AS Name,
			SA.AcademicId,
			SA.ClassId,
			SA.DivisionId,
			ISNULL(SA.RollNo,0) AS RollNo,
			SA.BatchId,
			ISNULL(SO.DateOfBirth,'') AS DateOfBirth,
			ISNULL(SO.GenderId,0) AS GenderId,
			SA.ClassName+'-'+SA.DivisionName AS ClassDiv,
			ISNULL(SA.AdmissionCategoryId,0) AS AdmissionCategoryId,
			@lIsAdmissionCategoryChange AS IsAdmissionCategoryChange,
			SA.SUId,
			ISNULL(AD.RepeatCount,1) AS RepeatCount,
			ISNULL(SA.DepartmentId,0) AS DepartmentId,
			ISNULL(RM.HostelId,0) AS HostelId,
			ISNULL(AR.RoomId,0) AS RoomId,
			ISNULL(A.TransportId,0) AS TransportId,
			ISNULL(A.BusRouteId,0) AS BusRouteId,
			ISNULL(A.PickupDestinationId,0) AS PickupDestinationId,
			ISNULL(SA.StudentGroupId,0) AS StudentGroupId,
			ISNULL(SA.StudentOtherGroupId,0) AS StudentOtherGroupId
			
  FROM 
           sStudent.vStudentAcademic SA
     LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=SA.StudentId
     LEFT JOIN sStudent.tAcademicDetail AD ON AD.AcademicID = SA.AcademicId
     LEFT JOIN sHostel.tAssignRoom AR ON AR.SourceId = SA.StudentId AND AR.SourceTypeId = 2003  AND AR.OrgGroupBatchId=@rOrgGroupBatchId
     LEFT JOIN sHostel.tRoomMaster RM ON RM.Id = AR.RoomId
     LEFT JOIN
     (SELECT ATR.SourceId,ISNULL(ATR.PickupDestinationId,0) AS PickupDestinationId,	ISNULL(BRM.TransportId,0) AS TransportId,ISNULL(BRM.Id,0) AS BusRouteId FROM sTransport.tAssignRoute ATR 
     INNER JOIN sTransport.tBusRouteDestinationMaster BRDM ON BRDM.Id=ATR.PickupDestinationId
     INNER JOIN sTransport.tBusRouteMaster BRM ON BRM.Id=BRDM.BusRouteId  AND BRM.OrgGroupBatchId=@rOrgGroupBatchId   AND ATR.SourceTypeId = 2003 ) A ON A.SourceId = SA.StudentId AND SA.OrgGroupBatchId=@rOrgGroupBatchId
     LEFT JOIN  sStudent.tStudentGroupMaster GM ON GM.Id=SA.StudentGroupId
     LEFT JOIN sStudent.tStudentOtherGroupMaster OGM  ON OGM.Id=SA.StudentOtherGroupId
  WHERE 
 
			((SA.Code=@rCode)OR(ISNULL(@rCode,'')=''))
			AND ((SA.StudentId=@rStudentId)OR(@rStudentId=0))
			AND((SA.Number=@rNumber) OR (@rNumber=0))
			AND(SA.OrgId=@rOrgId)
			AND(SA.BatchId=@rBatchId)
END
GO
PRINT N'Altering [sStudent].[pStudentViewProfileGet]...';


GO

ALTER PROCEDURE [sStudent].[pStudentViewProfileGet]
	 
	 @rBatchId int,
	 @rAcademicId bigint,
	 @rReportId int=0,
	 @rOrgId int,
	 @rOrgGroupBatchId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	
	SELECT 
			
			SA.StudentId AS Id,
			SA.FirstName + ' ' + ISNULL(SA.MiddleName,'') + ' ' + 	SA.LastName AS StudentName,
			ISnull(SA.Batch,'') AS AcademicYear,
			ISNULL(SA.Code,' ') AS Code,
			SA.ClassDivision AS ClassDiv,			
			Isnull(SA.RollNo,'') AS RollNo,
			convert(varchar,ISNULL(SA.DateOfBirth,'0001/01/01'),103) AS DateOfBirth,
			ISNULL(SM.Title,'-') AS House,
			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,
			ISNULL(SA.AdmissionStandard,'') AS AdmissionStandard,
			convert(varchar,ISNULL(SA.AdmissionDate,'0001/01/01'),103) AS AdmissionDate,
			ISNULL(SA.PreviousSchool,'') AS PreviousSchool,
			ISNULL(SA.AdmissionCategory,'') AS StudentAdmissionCategory,
            convert(varchar,ISNULL(SA.LeftDate,'0001/01/01'),103) AS LeftDate,
			ISNULL(SA.LeftStandard,'') AS LeftStandard,
			convert(varchar,ISNULL(SA.InactiveDate,'01/01/0001'),103) AS InactiveDate,
			ISNULL(SA.LCNumber,'') AS LCNumber,
			convert(varchar,ISNULL(SA.LCDate,'01/01/0001'),103) AS LCDate,
			ISNULL(SA.PresentStreetone,'') + ' ' + ISNULL(SA.PresentStreetTwo,'') + ' ' + ISNULL(SA.PresentStreetThree,'') AS PresentAddress,
			ISNULL(SA.PresentCity,'') AS PresentCity,
			ISNULL(SA.PresentState,'') AS PresentState,
			ISNULL(SA.PresentCountry,'') AS PresentCountry,
			ISNULL(SA.PresentZipCode,'') AS PresentZipCode,
			ISNULL(SA.PresentContactNo,'') AS PresentContactNo,
			ISNULL(SA.EmergencyStreetOne,'') + ' ' + ISNULL(SA.EmergencyStreetTwo,'') + ' ' + ISNULL(SA.EmergencyStreetThree,'') AS EmergencyAddress,
			ISNULL(SA.EmergencyCity,'') AS EmergencyCity,
			ISNULL(SA.EmergencyState,'') AS EmergencyState,
			ISNULL(SA.EmergencyCountry,'') AS EmergencyCountry,
			ISNULL(SA.EmergencyZipCode,'') AS EmergencyZipCode,
			ISNULL(SA.EmergencyContactNo,'') AS EmergencyContactNo,
			ISNULL(SA.PermanentStreetOne,'') + ' ' + ISNULL(SA.PermanentStreetTwo,'') + ' ' + ISNULL(SA.PermanentStreetThree,'') AS PermanentAddress,
			ISNULL(SA.PermanentCity,'') AS PermanentCity,
			ISNULL(SA.PermanentState,'') AS PermanentState,
			ISNULL(SA.PermanentCountry,'') AS PermanentCountry,
			ISNULL(SA.PermanentZipCode,'') AS PermanentZipCode,
			ISNULL(SA.PermanentContactNo,'') AS PermanentContactNo,
			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,
			ISNULL(SA.BloodGroup,'') AS BloodGroup,
			ISNULL(SH.IdentificationMark1,'')+' '+ISNULL(SH.IdentificationMark2,'') as IdentificationMark,
			ISNULL(SH.FamilyDoctorName,'') AS FamilyDoctorName,
			ISNULL(SH.FamilyDoctorContactNo,'') AS FamilyDoctorContactNo,
			case When isnull(SH.IsPysicalDeformity,0)=0 then 'NO' Else 'Yes' End As IsPysicalDeformity,
			SH.PysicalDeformityRemark ,
			case When isnull(SH.IsMajorIllness,0)=0 then 'NO' Else 'Yes' End As IsMajorIllness,
			ISNULL(SH.MajorIllnessRemark,'') As MajorIllnessRemark,
			 case When isnull(SH.IsAllergy,0)=0 then 'NO' Else 'Yes' End As IsAllergy,
			ISNULL(SH.AllergyRemark,'') As AllergyRemark,
			 case When isnull(SH.IsPastHistory,0)=0 then 'NO' Else 'Yes' End As IsPastHistory,
			ISNULL(SH.PastHistoryRemark,'') As PastHistoryRemark,
			ISNULL(RM.Title,'') AS RoomNo,			
			ISNULL(HM.Title,'') AS Hostel,
			ISNULL(EMW.FirstName,'')+' '+ISNULL(EMW.LastName,'') AS WardenName,
			ISNULL(ECW.PhoneNoCompany,'') As WardenPhoneNo,
			ISNULL(ECW.ExtensionNo,'') AS WardenExtNo,
			ISNULL(ECW.MobileNumber,'') AS WardenMobileNo,
			ISNULL(EMA.FirstName,'')+' '+ISNULL(EMA.LastName,'') AS AssignedRoomBy,	
			ISNULL(ECA.PhoneNoCompany,'') AS AssignedRoomByPhoneNo,
			ISNULL(ECA.ExtensionNo,'') AS AssignedRoomByExtNo,
			ISNULL(ECA.MobileNumber,'') AS AssignedRoomByMobileNo,
			--Notification Details
			ISNULL(SA.ParentEmail,'') AS ParentEmail,
			ISNULL(SA.ParentContactNo,'') As ParentContactNo,
			ISNULL(SA.StudentEmail,'') AS StudentEmail,
			ISNULL(SA.StudentContactNo,'') AS StudentContactNo,
		   ISnull( A.VehicleName,'') AS VehicleName,
		    ISNULL( A.VehicleRegistrationNumber,'') AS VehicleRegistrationNumber,
		      ISNULL(A.TypeOfVehicle ,'') AS TypeOfVehicle ,
		   ISNULL(A.BusRoute,'') AS BusRoute,
		   ISNULL( A.DriverName,'') AS DriverName,
		     ISNULL(A.DriverMobileNo,'') AS DriverMobileNo,
		   ISNULL( A.ConductorName,'') AS ConductorName,
		   ISNULL( A.ConductorMobileNo,'') AS ConductorMobileNo ,
		    ISNULL(A.BusRouteDestination,'') AS BusRouteDestination,
		    isnull(A.DropVehicleName,'') AS DropVehicleName,
		    isnull(A.DropVehicleRegistrationNumber,'') AS DropVehicleRegistrationNumber,
		    isnull(A.DropTypeOfVehicle,'') AS DropTypeOfVehicle,
		    ISNULL(A.DropRoute,'') AS DropRoute,
		   isnull( A.DriverName,'') AS DropRouteDriverName,
		   isnull(A.DriverMobileNo,'') AS DropRouteDriverMobileNo,
		    isnull(A.ConductorName,'') AS DropRouteConductorName,
		    isnull(A.ConductorMobileNo,'') AS DropRouteConductorMobileNo,
		    ISNULL(A.DropDestination,'') AS DropDestination,
		   ISNULL( EMT.FirstName+' '+EMT.MiddleName+' '+EMT.LastName,'') AS TeacherFullName,
		    isnull( EDM.Title,'') AS TeacherDesignation,
		   ISNULL( EPD.Qualification,'') AS TeacherQualification,
		    ISNULL(DF.IsDisplayFamilyDetail,0) AS IsDisplayFamilyDetail,
		    ISNULL(DF.IsDisplaySiblingDetail,0) AS IsDisplaySiblingDetail,
		    ISNULL(DF.IsDisplayPassportDetail,0) AS IsDisplayPassportDetail,
		    ISNULL(DF.IsDisplayBankDetail,0) AS IsDisplayBankDetail,
		    ISNULL(DF.IsDisplayCBSEREGDetail,0) AS IsDisplayCBSEREGDetail,
		    ISNULL(DF.IsDisplayCollegeDetail,0) AS IsDisplayCollegeDetail,
		    ISNULL(DF.IsDisplayGOVREGNoDetail,0) AS IsDisplayGOVREGNoDetail,
		    ISNULL(DF.IsDisplayHealthDetail,0) AS IsDisplayHealthDetail,
		    ISNULL(DF.IsDisplayTransportDetail,0) AS IsDisplayTransportDetail,
		    ISNULL(DF.IsDisplayHostelDetail,0) AS IsDisplayHostelDetail,
		    ISNULL(DF.IsDisplayClubDetail,0) AS IsDisplayClubDetail,
		    
		    ISNULL(DF.IsDisplaySSCResultDDetail,0) AS IsDisplaySSCResultDDetail,
		    ISNULL(DF.IsDisplayHSCResultDetail,0) AS IsDisplayHSCResultDetail,
		    ISNULL(DF.IsDisplayJeeDetail,0) AS IsDisplayJeeDetail,
		    ISNULL(DF.IsDisplayDiplomaDetail,0) AS IsDisplayDiplomaDetail,
		
		    isnull(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,
	       	convert(varchar,ISNULL(SAD.PassportExpiryDate,'01/01/0001'),103) AS PassportExpiryDate,
	       	convert(varchar,ISNULL(SAD.PassportIssueDate,'01/01/0001'),103) AS PassportIssueDate,
	      ISNULL(SA.UIDNumber,'')AS UIDNumber,
	      ISNULL(SA.AdhaarNumber,'') AS AdhaarNumber,
	      case When isnull(SA.IsTransfer,0)=0 then 'No' Else 'Yes' End As IsTransfer,
	      ISNULL(SA.TransferFrom,'') AS TransferFrom,
	      ISNULL(SA.CertificateName,'') AS CertificateName,
	       case When isnull(SA.IsTFWS,0)=0 then 'No' Else 'Yes 'End As IsTFWS,
	      case When isnull(SA.IsCertificateHolder,0)=0 then 'No' Else 'Yes' End 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.SSCMathMarks,0) AS SSCMathMarks,
	       ISNULL(CD.SSCMathOutOfMarks,0) AS SSCMathOutOfMarks,
	       ISNULL(CD.SSCPercentage,0) AS SSCPercentage,
	       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(MS.Title,'') AS MaritalStatus,
	      ISNULL(ACD.RepeatCount,1)AS RepeatCount,
	      ISNULL(SA.MotherTongue,'') As MotherTongue,
	      ISNULL(SA.FamilyCast,'') AS FamilyCast,
	      ISNULL(CM.Nationality,'') AS Nationality,
           ISNULL(CT.Title,'') AS CasteCategory,
          --StudentPhoto = case when SA.StudentPhoto is null then '' else SA.StudentPhoto end,
	    StudentPhoto=(SELECT CAST(SA.StudentPhoto as varbinary(max)) FOR XML PATH(''), BINARY BASE64) ,
		TeacherPhoto=(SELECT CAST(EI.EmployeePhoto as varbinary(max)) FOR XML PATH(''), BINARY BASE64) ,
		 FatherPhoto=(SELECT CAST(SA.FatherPhoto as varbinary(max)) FOR XML PATH(''), BINARY BASE64) ,
		MotherPhoto=(SELECT CAST(SA.MotherPhoto as varbinary(max)) FOR XML PATH(''), BINARY BASE64) ,
		RelativePhoto=(SELECT CAST(SA.RelativePhoto as varbinary(max)) FOR XML PATH(''), BINARY BASE64) ,
		 ISNULL(SA.PreviousStandard,'')AS PreviousStandard 
		    
  FROM 
           sStudent.vStudentAllDetail SA
         --  LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
           LEFT JOIN sStudent.tStudentHealth SH ON SA.StudentId=SH.StudentId
           LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SA.StudentId 
          -- LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId = SA.StudentId
           LEFT JOIN sActivity.tHouseMaster SM ON SM.ID = SA.HouseId
           LEFT JOIN sHostel.tAssignRoom AR ON AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003  AND ((AR.OrgGroupBatchId=@rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
           LEFT JOIN sHostel.tRoomMaster RM ON RM.Id=AR.RoomId
           LEFT JOIN 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 
           (SELECT AR1.SourceId ,
           		   ISnull( VM.Title,'') AS VehicleName,
		    ISNULL( VM.RegistrationNumber,'') AS VehicleRegistrationNumber,
		      ISNULL(TV.Title ,'') AS TypeOfVehicle ,
		   ISNULL(BRM.Title,'') AS BusRoute,
		   ISNULL( BRM.DriverName,'') AS DriverName,
		     ISNULL(BRM.DriverMobileNo,'') AS DriverMobileNo,
		   ISNULL( BRM.ConductorName,'') AS ConductorName,
		   ISNULL( BRM.ConductorMobileNo,'') AS ConductorMobileNo ,
		    ISNULL(BRDM.Title,'') AS BusRouteDestination,
		    isnull(VM.Title,'') AS DropVehicleName,
		    isnull(VM.RegistrationNumber,'') AS DropVehicleRegistrationNumber,
		    isnull(TV1.Title,'') AS DropTypeOfVehicle,
		    ISNULL(BRM1.Title,'') AS DropRoute,
		   isnull( BRM1.DriverName,'') AS DropRouteDriverName,
		   isnull(BRM1.DriverMobileNo,'') AS DropRouteDriverMobileNo,
		    isnull(BRM1.ConductorName,'') AS DropRouteConductorName,
		    isnull(BRM1.ConductorMobileNo,'') AS DropRouteConductorMobileNo,
		    ISNULL(BRDM1.Title,'') AS DropDestination
		     FROM sTransport.tAssignRoute AR1 
           INNER JOIN sTransport.tBusRouteDestinationMaster BRDM ON BRDM.Id=AR1.PickupDestinationId AND AR1.SourceTypeId=2003
           INNER JOIN sTransport.tBusRouteMaster BRM ON BRM.Id=BRDM.BusRouteId  AND ((BRM.OrgGroupBatchId=@rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
           LEFT JOIN sTransport.tVehicleMaster VM ON VM.Id=BRM.VehicleId
           LEFT JOIN sTransport.tVehicleTypeMaster TV ON TV.Id = VM.VehicleTypeId
           LEFT JOIN sTransport.tBusRouteDestinationMaster BRDM1 ON BRDM1.Id=AR1.DropDestinationId
           LEFT JOIN sTransport.tBusRouteMaster BRM1 ON BRM1.Id=BRDM1.BusRouteId AND ((BRM1.OrgGroupBatchId=@rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
           LEFT JOIN sTransport.tVehicleMaster VM1 ON VM1.Id=BRM1.VehicleId
           LEFT JOIN sTransport.tVehicleTypeMaster TV1 ON TV1.Id = VM1.VehicleTypeId)A ON A.SourceId=SA.StudentId
           LEFT JOIN sSetup.tDivisionMaster DM ON  DM.Id=SA.DivisionId
           LEFT JOIN sHrm.tEmployeeMaster EMT ON EMT.Id=DM.InchargeEmployeeId
           LEFT JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EMT.Id
           LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id=EJD.EmployeeDesignationId
           LEFT JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId=EMT.Id
           LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId=EMT.Id
           LEFT JOIN sStudent.tStudentSibling  SS ON SS.StudentId=SA.StudentId 
           LEFT JOIN sStudent.tStudentAdditional  SAD ON SAD.StudentId=SA.StudentId 
           LEFT JOIN sStudent.tCollegeDetail  CD ON CD.StudentId=SA.StudentId 
           LEFT JOIN sStudent.tAcademicDetail  ACD ON ACD.AcademicId=SA.AcademicId 
           LEFT JOIN sCommon.tMaritalStatusMaster  MS ON MS.Id=CD.MaritalStatusId
           LEFT JOIN sConfig.fDisplayFieldGet(@rOrgId) AS DF ON DF.OrgId=SA.OrgId
           LEFT JOIN sCommon.tCastCategoryMaster CT ON CT.Id = SA.CastCategoryId
           LEFT JOIN sCommon.tCountryMaster CM ON CM.Id=SA.NationalityId
             
  WHERE 
			((SA.AcademicId=@rAcademicId)OR(@rAcademicId=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,
			FeeStructureId
			)
		SELECT
		
			@lNextNumber+ ROW_NUMBER() OVER(ORDER BY StudentId),
			StudentId,
			@lToClassId,
			@rToBatchId,
			@rToDivisionId,
			0,
			@rToOrgId,
			@rCreatedUserId,
			sCommon.fGetDate(),
			1,
			ExemptionTypeId,
			FeeStructureId
		FROM OPENXML (@loDoc, '/Table/StudentImportDetail', 1)
		WITH ( 
				StudentId bigint,
				ExemptionTypeId int,
				FeeStructureId 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 [sTimetable].[pTimeTableAdd]...';


GO

ALTER PROCEDURE [sTimetable].[pTimeTableAdd]
		
		@rOrgId int,
		@rId int,
		@rTimeTableSchemaID int,
		@rEmployeeId bigint,
		@rDivisionId int,
		@rSubjectId int,
		@rDayId smallint,
		@rLectureNumber smallint,
		@rLockNo bigint,
		@rLockColour varchar(50)
		
		
           	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	 
 
BEGIN 

	 BEGIN TRY	
	 BEGIN TRANSACTION 
	 
	IF NOT EXISTS(Select 1 FROM sTimetable.tTimeTable Where EmployeeId = @rEmployeeId AND LectureNumber = @rLectureNumber AND DayId = @rDayId and TimeTableSchemaId=@rTimeTableSchemaId)
	 
	BEGIN
	DECLARE @lNextNumber BIGINT
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sTimetable.tTimeTable', 0, 1, 1,@outNextNumber = @lNextNumber output
	  
	 
	  BEGIN
		   INSERT INTO sTimetable.tTimeTable		 
		   (
				[Id]
			   ,[TimeTableSchemaId]
			   ,[EmployeeId]
			   ,[DivisionId]
			   ,[SubjectId]
			   ,[DayId]
			   ,[LectureNumber]
			   ,[LockNo]
			   ,[LockColour]
            )		 
			VALUES
			(	
				@lNextNumber,
				@rTimeTableSchemaID,
				@rEmployeeId,
				@rDivisionId,
				@rSubjectId,
				@rDayId,
				@rLectureNumber,
				@rLockNo,
				@rLockColour
			)		
			SELECT @lNextNumber AS Result
    	END
      END
    ELSE
    BEGIN       
      SELECT -101 AS Result
    END
	
	COMMIT TRANSACTION
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
	
	
END 	             
	
		
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
DELETE FROM [sSetup].[tClassGroupMaster]

DELETE FROM sCommon.tTemplateSourceMaster
DELETE FROM sErp.tCustomerStatusMaster
DELETE FROM sErp.tInstallationTypeMaster
DELETE FROM sRecruitment.tRecruitmentStatusMaster

DELETE FROM sAssessment.tStaticCCECSMaster
DELETE FROM sAssessment.tStaticCCECSGroupMaster

DELETE FROM siTax.tStaticIncomeTaxGroup
DELETE FROM siTax.tStaticIncomeTaxSubGroup

DELETE FROM sCommon.tImportFieldMaster
DELETE FROM sCRM.tHostingTypeMaster
DELETE FROM sHrm.tMainLeaveTypeMaster

DELETE FROM sAppraisal.tConductIndicatorMaster
DELETE FROM sHrm.tTravelPeriodMaster
DELETE FROM sLoan.tInsterestTypeMaster

DELETE FROM sAppraisal.tBHRatingStatus
DELETE FROM sAppraisal.tConductIndicatorMaster
DELETE FROM sAppraisal.tKPAMeasureMaster
DELETE FROM sAppraisal.tKPATypeMaster
DELETE FROM sAppraisal.tRatingStatus
DELETE FROM sCommon.tHeaderDisplayMaster
DELETE FROM sCommon.tModuleGroupMaster
DELETE FROM sHrm.tLeaveTransactionMaster
DELETE FROM sCommon.tCheckFrequencyMaster

DELETE FROM sErp.tLeadAffiliationMaster
DELETE FROM sErp.tLeadSourceMaster
DELETE FROM sErp.tLeadStatusMaster

DELETE FROM sSystem.tStaticVersion

DELETE FROM sCommunication.tFeedBackAnswerGroupMaster

DELETE FROM sCommon.tSubmitDocumentFunctionalityMaster
DELETE FROM sSetup.tMandatoryFeild
DELETE FROM sSetup.tMandatoryFeildFunctionalityMaster

END
GO
PRINT N'Altering [sTransport].[pAssignRouteGet]...';


GO

ALTER PROCEDURE [sTransport].[pAssignRouteGet]
           
           @rClassId int,
           @rDivisionId int,
           @rBusRouteId int,
           @rBusRouteDestinationId int,
           @rBusRouteDestination nvarchar(100),
           @rOrgId int,
           @rStudentName nvarchar(100),
           @rStudentCode nvarchar(100),
           @rOrgGroupBatchId int,
           @rStudentId bigint,
           @rTransportId int = 0,
           @rSUID nvarchar(20)
AS
SET NOCOUNT ON

BEGIN
	
		SET @rBusRouteDestination = sCommon.fSearchStringGet(@rBusRouteDestination)

SELECT  
		SM.Id as SourceId,
		SM.Code,
		SM.FirstName+' '+SM.LastName as Name,
		CM.Title+'-'+DM.Title as ClassDivisionName,
		ISNULL(V.BusRouteId,0) AS BusRouteId,
		ISNULL(V.BusRouteDestinationId,0) AS BusRouteDestinationId,
		ISNULL(V.DropRouteId,0) AS DropRouteId,
		ISNULL(V.DropDestinationId,0) AS DropDestinationId,
		O.DisplayTitle AS Organization,
		SC.PresentStreetOne+' '+ SC.PresentStreetTwo+' '+SC.PresentStreetThree+' '+SC.PresentCity AS StudentAddress ,
		ISNULL(SM.SUId,'') AS SUId,
		ISNULL(V.Pickuppoint,'') As Pickuppoint,
		Isnull(V.Droppoint,'') As Droppoint
		
		
  FROM sStudent.tAcademic A
	INNER JOIN sStudent.tStudentMaster SM ON A.StudentId=SM.Id AND SM.StatusId=1
	LEFT JOIN sStudent.tStudentCommunication SC ON SC.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 
	  (SElect AR.Sourceid ,ISNULL(BRDM.BusRouteId,0)AS BusRouteId,
			ISNULL(AR.PickupDestinationId,0) AS BusRouteDestinationId,
			ISNULL(BRDM2.BusRouteId,0)AS DropRouteId,
			ISNULL(AR.DropDestinationId,0) AS DropDestinationId,
			Isnull(BRDM.Title,'') AS Pickuppoint,
			Isnull(BRDM2.Title,'') AS Droppoint FROM sTransport.tAssignRoute AR
			 INNER JOIN sTransport.tBusRouteDestinationMaster BRDM ON BRDM.Id=AR.PickupDestinationId
			 INNER JOIN sTransport.tBusRouteMaster BRM On BRm.id=BRDM.BusRouteId AnD BRM.OrgGroupBatchId=@rOrgGroupBatchId
			 LEFT JOIN sTransport.tBusRouteDestinationMaster BRDM2 ON BRDM2.Id=AR.DropDestinationId	
			 LEFT JOIN sTransport.tBusRouteMaster BRM2 On BRM2.Id=BRDM2.BusRouteId AND BRM2.OrgGroupBatchId=@rOrgGroupBatchId
	 WHERE 
		 (BRDM.Id=@rBusRouteDestinationId OR @rBusRouteDestinationId=0) 
		AND (BRDM2.Id=@rBusRouteDestinationId OR @rBusRouteDestinationId=0)
		AND (BRDM.BusRouteId=@rBusRouteId OR @rBusRouteId=0) 
		AND (BRDM2.BusRouteId=@rBusRouteId OR @rBusRouteId=0)
		AND (BRDM.Title Like @rBusRouteDestination OR ISNULL(@rBusRouteDestination,'') = '')
		AND (BRDM2.Title Like @rBusRouteDestination OR ISNULL(@rBusRouteDestination,'') = '')	
	    AND BRM.TransportId=@rTransportId ) V  ON V.SourceId=A.StudentId 
	   INNER JOIN sSetup.tBatchMaster BM ON BM.Id=A.BatchId 
	--AND BM.IsActive = 1
	  INNER JOIN sSetup.tOrgGroupBatchMaster OB ON BM.OrgGroupBatchId = ob.iD
	  INNER JOIN sSetup.tOrganizationMaster O ON O.id = BM.OrgId AND O.OrgGroupId = OB.OrgGroupId
	--and bM.OrgGroupBatchId = ob.id
	
  WHERE 
		(A.ClassId=@rClassId OR @rClassId=0)
	AND (A.DivisionId=@rDivisionId OR @rDivisionId=0)
	--AND (BRDM.Id=@rBusRouteDestinationId OR @rBusRouteDestinationId=0) 
	--AND (BRDM2.Id=@rBusRouteDestinationId OR @rBusRouteDestinationId=0)
	  AND (V.BusRouteId=@rBusRouteId OR @rBusRouteId=0) 
	--AND (BRDM2.BusRouteId=@rBusRouteId OR @rBusRouteId=0)
	--AND (BRDM.Title Like @rBusRouteDestination OR ISNULL(@rBusRouteDestination,'') = '')
	--AND (BRDM2.Title Like @rBusRouteDestination OR ISNULL(@rBusRouteDestination,'') = '')
	
	  AND (V.BusRouteDestinationId=@rBusRouteDestinationId OR @rBusRouteDestinationId=0) 
	  AND (V.DropDestinationId=@rBusRouteDestinationId OR @rBusRouteDestinationId=0)
	  AND (V.DropRouteId=@rBusRouteId OR @rBusRouteId=0)
	  AND (V.Pickuppoint Like @rBusRouteDestination OR ISNULL(@rBusRouteDestination,'') = '')
	  AND (V.Droppoint Like @rBusRouteDestination OR ISNULL(@rBusRouteDestination,'') = '')
	
	 AND (A.Id = @rStudentId OR ISNULL(@rStudentId,0) = 0)
	 AND (SM.Code = @rStudentCode  OR ISNULL(@rStudentCode,'')='')
	--AND ((SM.FirstName + ' ' + SM.LastName) like @rStudentName + '%' OR ISNULL(@rStudentName,'') = '')	
	 AND (A.OrgId = @rOrgId OR @rOrgId = 0)
	--AND (OB.Id=@rOrgGroupBatchId)
	AND(A.OrgId in (select OrgId from sTransport.tAssignTransportOrg where TransportId = @rTransportId))
	AND (SM.SUId = @rSUID  OR ISNULL(@rSUID,'')='')
	AND BM.OrgGroupBatchId=@rOrgGroupBatchId
	
END
GO
PRINT N'Altering [sTransport].[pRptBuswiseCapacityUtilizationListGet]...';


GO

ALTER PROCEDURE [sTransport].[pRptBuswiseCapacityUtilizationListGet]
	 
	 @rOrgGroupBatchId int,
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rRouteId int=0,
	 @rVehicleId int=0,
	 @rTransportId int =0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

	SELECT 
	        @rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			BRM.Id AS BusRouteId,
			BRM.Title AS BusRoute,
			BRM.OrderIndex AS RouteOrder,
			VM.Id AS VehicleId,
			VM.Title AS Vehicle,
			VM.NoOfSeats,
			ISNULL(VM.RegistrationNumber,'') AS RegistrationNumber,
			(SELECT COUNT(1) FROM sTransport.tAssignRoute AR INNER JOIN sTransport.tBusRouteDestinationMaster DM
			 ON AR.PickupDestinationId = DM.Id AND DM.BusRouteId = BRM.Id) AS SeatAllocated
	FROM 
		 sTransport.tBusRouteMaster BRM 
		 INNER JOIN sTransport.tVehicleMaster VM ON VM.Id=BRM.VehicleId
			
	WHERE 
			(BRM.OrgGroupBatchId=@rOrgGroupBatchId)
			AND 
			((BRM.Id=@rRouteId) OR (@rRouteId=0))
			AND ((VM.Id=@rVehicleId) OR (@rVehicleId=0))
			AND ((VM.TransportId=@rTransportId) OR (@rTransportId=0))
	END
GO
PRINT N'Altering [sTransport].[pRptRoutewiseStudentListGet]...';


GO

ALTER PROCEDURE [sTransport].[pRptRoutewiseStudentListGet]
	 
	
	 
	 @rOrgGroupBatchId int=0,
	 @rOrgId int=0,
	 @rDepartmentId int=0,
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rRouteId int=0,
	 @rDestinationId int=0,
	 @rTransportId int =0,
	 @rDropDestinationId int=0,
	 @rDropBusRouteId int=0
	 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 


	SELECT 
	        @rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			AR.SourceId,
			SM.Code,
			SM.FirstName+' '+SM.LastName AS Name,
			DM.Id AS DivisionId,
			CM.DisplayTitle AS Class,
			DM.DisplayTitle AS Division,
			CM.DisplayTitle+' - '+DM.DisplayTitle AS ClassDivision,
			BRDM.Title AS DestinationPoint,
			BRM.Id AS BusRouteId,
			BRM.Title AS BusRoute,
			A.RollNo,
			VM.Title AS Vehicle,
			VM.NoOfSeats,
			BRM.OrderIndex AS RouteOrder,
			BRDM.OrderIndex AS PickupOrder,
			DM.OrderIndex AS DivisionOrderIndex,
			OM.Id AS OrgId,
			OM.DisplayTitle AS OrganizationName,
			DMast.Id AS DepartmentId,
			DMast.Title AS DepartmentName,
			SC.ParentContactNo AS ParentContactNo,
			ISNULL(SC.PresentStreetone,'')+' '+ISNULL(SC.PresentStreetTwo,'')+' '+ISNULL(SC.PresentStreetThree,'')+' '+ISNULL(SC.PresentCity,'')+' '+ISNULL(SC.PresentState,'')+' '+ISNULL(SC.PresentZipCode,'') AS PresentAddress,
			ISNULL(VM.RegistrationNumber,'') AS RegistrationNumber,
			ISNULL(BRM.DriverName,'') AS DriverName,
			ISNULL(BRM.DriverMobileNo,'') AS DriverMobileNo,
			ISNULL(BRM.ConductorName,'') AS ConductorName,
			ISNULL(BRM.ConductorMobileNo,'') AS ConductorMobileNo,
			BRDM.Amount,
			ISNULL(BRM1.DriverName,'') AS DropRoutDriverName,
			ISNULL(BRM1.DriverMobileNo,'') AS DropRoutDriverMobileNo,
			ISNULL(BRM1.ConductorName,'') AS DropRoutConductorName,
			ISNULL(BRM1.ConductorMobileNo,'') AS DropRoutConductorMobileNo,
			BRM1.Id AS DropRoutBusRouteId,
			BRM1.Title AS DropRoutBusRoute,
			ISNULL(VM1.RegistrationNumber,'') AS DropRoutRegistrationNumber,
			VM1.Title AS DropRoutVehicle,
			VM1.NoOfSeats AS DropRoutVehicleNoOfSeats,
			BRM1.OrderIndex AS DropRoutRouteOrder,
			BRDM1.OrderIndex AS DropRoutOrder,
			BRDM1.Title AS DropDestinationPoint ,
			BRDM1.DropTime,
			BRDM.PickUpTime
			
	FROM 
			sTransport.tAssignRoute AR
			INNER JOIN sStudent.tAcademic A ON A.StudentId=AR.SourceId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId 
			INNER JOIN sStudent.tStudentMaster SM ON A.StudentId=SM.Id AND SM.StatusId=1
			LEFT JOIN sStudent.tStudentCommunication SC ON A.StudentId=SC.StudentId AND SM.StatusId=1
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId
			INNER JOIN sSetup.tDepartmentMaster DMast ON DMast.Id=CM.DepartmentId
			INNER JOIN sTransport.tBusRouteDestinationMaster BRDM ON BRDM.Id=AR.PickupDestinationId
			INNER JOIN sTransport.tBusRouteMaster BRM ON BRM.Id=BRDM.BusRouteId
			LEFT JOIN sTransport.tVehicleMaster VM ON VM.Id=BRM.VehicleId
			LEFT JOIN sTransport.tBusRouteDestinationMaster BRDM1 ON BRDM1.Id=AR.DropDestinationId 
			LEFT JOIN sTransport.tBusRouteMaster BRM1 ON BRM1.Id=BRDM1.BusRouteId AND (BRM1.OrgGroupBatchId=@rOrgGroupBatchId)
			 
			LEFT JOIN sTransport.tVehicleMaster VM1 ON VM1.Id=BRM1.VehicleId
	WHERE 
			--((AR.SourceId=@rAcademicId) OR (@rAcademicId=0))
			(BRM.OrgGroupBatchId=@rOrgGroupBatchId)
			AND 
			BM.OrgGroupBatchId = @rOrgGroupBatchId
			AND ((OM.Id=@rOrgId) OR (@rOrgId=0))
			AND ((DMast.Id=@rDepartmentId) OR (@rDepartmentId=0))
			AND ((CM.Id=@rClassId) OR (@rClassId=0))
			AND ((DM.Id=@rDivisionId) OR (@rDivisionId=0))
			 AND ((BRM.Id=@rRouteId) OR (@rRouteId=0))
			 --AND ((BRM.TransportId=@rTransportId) OR (@rTransportId=0))
			 AND ((BRDM.Id=@rDestinationId) OR (@rDestinationId=0))
			AND ((BRDM1.BusRouteId=@rDropBusRouteId) OR (@rDropBusRouteId=0))
			 AND ((BRDM1.Id=@rDropDestinationId) OR (@rDropDestinationId=0))
	END
GO
PRINT N'Creating [sAccounting].[pBudgetAdd]...';


GO

CREATE PROCEDURE [sAccounting].[pBudgetAdd]
	@rId	int,
	@rLedgerId	int,
	@rBudgetAmount	decimal(12, 2),
	@rAccountingYearId	int,
	@rUserId	bigint,
	@rOrgGroupId int
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 	
BEGIN TRY
 BEGIN TRANSACTION
 DECLARE @lNextNumber int
 IF(@rId = 0)	
	BEGIN
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sAccounting.tBudget', 0, 1, 1,@outNextNumber = @lNextNumber output
	INSERT INTO sAccounting.tBudget
	          (
	            Id,
				LedgerId,
				BudgetAmount,
				AccountingYearId,
				CreatedUserId,
				CreatedDateTime
			)
				VALUES
				( 
				@lNextNumber,
				@rLedgerId,
				@rBudgetAmount,
				@rAccountingYearId,
				@rUserId,
				sCommon.fGetDate()
				)
				SELECT 1 AS Result
	END
	  ELSE
	BEGIN
			UPDATE  sAccounting.tBudget SET
 
				LedgerId=@rLedgerId,
				BudgetAmount=@rBudgetAmount,
				UpdatedUserId=	@rUserId,
				UpdatedDateTime=sCommon.fGetDate()
			  WHERE AccountingYearId=@rAccountingYearId AND LedgerId=@rLedgerId AND 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'Creating [sAccounting].[pBudgetGet]...';


GO

CREATE PROCEDURE [sAccounting].[pBudgetGet]
	 
	 @rAccountYearId int,
	 @rAccountId int,
	 @rAccountYearString NVARCHAR(MAX)
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
    DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX)
    select @cols = STUFF((SELECT ',' + QUOTENAME(Title) 
                    from  sAccounting.tAccountingYearMaster WHERE  IsActive=0 AND AccountId=@rAccountId  AND Id!=@rAccountYearId
                    AND (ISNULL(Id,'') IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rAccountYearString,',')) ) 
                    Order by Id 
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')
      If(ISNULL(@Cols,'')='')
		 BEGIN
		    SELECT -101 AS Result
		 RETURN
		 END
  set @query = 'SELECT Ladger,ISNULL(BudgetAmount,0) As BudgetAmount,ISNULL(LedgerId,0) AS LedgerId,ISNULL(BudgetId,0) AS BudgetId,' + @cols + ' from 
             (
               SELECT
                ISNULL(L.Title,'''') AS Ladger ,ISNULL(L.OpeningBalance,''0'') AS OpeningBalance,ISNULL(A.Title,'''') AS AccountingYear,ISNULL(L.Id,0) AS LedgerId,ISNULL(S.BudgetAmount,0) As BudgetAmount,ISNULL(S.BudgetId,0) As BudgetId
               FROM sAccounting.tLedgerMaster L
               INNER JOIN sAccounting.tAccountingYearMaster A ON A.Id=L.AccountingYearId 
               LEFT JOIN 
               (SELECT ISNULL(BudgetAmount,0) AS BudgetAmount,ISNULL(B.Id,0) AS BudgetId,ISNULL(B.LedgerId,0) AS LedgerId FROM sAccounting.tBudget B
                WHERE ((B.AccountingYearId=' + CAST(@rAccountYearId AS NVARCHAR(30))+'))) S ON  S.LedgerId=L.Id
		        WHERE 
	        ((A.AccountId=' + CAST(@rAccountId AS NVARCHAR(30))+'))
              ) x
            pivot 
            (
                SUM(OpeningBalance)
                for AccountingYear in (' + @cols + ')  
            ) p order by LedgerId'
            
  print @query
 execute(@query)
END
GO
PRINT N'Creating [sAccounting].[pOpeningBalanceApproveGet]...';


GO
CREATE PROCEDURE [sAccounting].[pOpeningBalanceApproveGet]
	    @rLedgerId [int] = 0,	@rAccountingYearId [int]

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	Declare @OpBalance decimal
	Declare @LedgerTypeId Int
	Declare @TraBalance decimal

	Select @OpBalance=OpeningBalance FROM sAccounting.tLedgerMaster WHERE ID = @rLedgerId
	Select @LedgerTypeId=LedgerTypeId FROM sAccounting.tLedgerMaster WHERE ID = @rLedgerId
	
	
	
	SELECT @TraBalance=ISNULL(SUM(AMOUNT),0) FROM sAccounting.tTransactionApproveDetail  TD
	INNER JOIN sAccounting.tTransactionApprove T on T.Id=TD.TransactionId
	WHERE T.AccountingYearId = 	@rAccountingYearId AND 
	      TD.LedgerId = @rLedgerId
	
	
	IF (@LedgerTypeId =1)
		BEGIN
			SELECT ' ( ' + Convert(nvarchar(20),@OpBalance - @TraBalance)   + ' ) CR' AS OpBalance
		END
	ELSE
		BEGIN
			SELECT ' ( ' + Convert(nvarchar(20),@OpBalance + @TraBalance)   + ' ) DR' AS OpBalance
		END
	      
END
GO
PRINT N'Creating [sAccounting].[pTransactionApproveAdd]...';


GO

CREATE PROCEDURE [sAccounting].[pTransactionApproveAdd]
	 
	        @rId bigint
	       ,@rOrgGroupId int
           ,@rAccountingYearId int
           ,@rTransactionDate date
           ,@rNarration nvarchar(150)           
           ,@rVoucherNumber bigint
           ,@rVoucherTypeId tinyint
           ,@rIsProfitAndLoss int
           ,@rRepeatLedger int
           ,@rCreatedUserId bigint
           ,@rChequeNo nvarchar(10)
           ,@rBankName nvarchar(100)
           ,@rChequeDate datetime
           
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	BEGIN TRANSACTION	
	DECLARE @lNextNumber BIGINT
	DECLARE @1AccountId int 
	
	IF (@rId = 0)  AND  EXISTS (Select 1 FROM sAccounting.tTransactionApprove where AccountingYearId = @rAccountingYearId AND VoucherNumber = @rVoucherNumber AND VoucherTypeId = @rVoucherTypeId AND OrgGroupId = @rOrgGroupId)
	  BEGIN
	        SELECT -111 AS Result
	  END
  
    ELSE IF(@rId = 0)	
	BEGIN
		
    Select @1AccountId = AccountId from sAccounting.tAccountingYearMaster where Id = @rAccountingYearId 
    EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sAccounting.tTransactionApprove', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sAccounting.tTransactionApprove
			   (
			    [Id]
			   ,OrgGroupId
			   ,[AccountingYearId]
			   ,[TransactionDate]
			   ,[Narration]
			   ,[VoucherNumber]
			   ,[VoucherTypeId]
			   ,[IsProfitAndLoss]
			   ,[RepeatLedger]
			   ,[CreatedUserId]
			   ,[CreatedDateTime]
			   ,AccountId
			   ,[ChequeNo]
			   ,[BankName]
			   ,[ChequeDate]
			   )
		 VALUES
			   (
				@lNextNumber
			   ,@rOrgGroupId
			   ,@rAccountingYearId
			   ,@rTransactionDate
			   ,@rNarration
			   ,@rVoucherNumber
			   ,@rVoucherTypeId
			   ,@rIsProfitAndLoss
			   ,@rRepeatLedger
			   ,@rCreatedUserId
			   ,sCommon.fGetDate()
			   ,@1AccountId
			   ,@rChequeNo
			   ,@rBankName
			   ,@rChequeDate
			   )
		    SELECT @lNextNumber AS Result
	
	 
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sAccounting.tTransactionApprove
	    SET
			 
	          AccountingYearId=@rAccountingYearId
	         ,TransactionDate = @rTransactionDate 
             ,Narration = @rNarration
             ,VoucherNumber=@rVoucherNumber
             ,VoucherTypeId=@rVoucherTypeId
             ,IsProfitAndLoss=@rIsProfitAndLoss
             ,RepeatLedger=@rRepeatLedger
             ,UpdatedUserId=@rCreatedUserId
             ,UpdatedDateTime= sCommon.fGetDate() 
             ,ChequeNo = @rChequeNo
             ,ChequeDate = @rChequeDate
             ,BankName = @rBankName         
             
	      WHERE Id = @rId 	   
	      SELECT @lNextNumber AS Result
	
		
	 END  	

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


GO

CREATE PROCEDURE [sAccounting].[pTransactionApproveDetailAdd]
	 
	        @rId bigint
           ,@rTransactionId bigint
           ,@rNumber bigint
		   ,@rTransactionTypeId int
		   ,@rLedgerId bigint
		   ,@rAmount decimal(12,2)
		   ,@rOrgId int
		  	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

IF(@rId = 0)	
BEGIN
EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAccounting.tTransactionApproveDetail', 0, 1, 1,@outNextNumber = @lNextNumber output
	INSERT INTO sAccounting.tTransactionApproveDetail
			   (
			    [Id]
			   ,[TransactionId] 
			   ,[Number] 
			   ,[TransactionTypeId]
			   ,[LedgerId]
			   ,[Amount]
			   )
		 VALUES
			   (
				@lNextNumber
			   ,@rTransactionId
			   ,@rNumber
			   ,@rTransactionTypeId
			   ,@rLedgerId
			   ,@rAmount
			   )
		    SELECT @lNextNumber AS Result
	
		
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sAccounting.tTransactionApproveDetail
	    SET
			 
	          Number=@rNumber
	         ,TransactionTypeId=@rTransactionTypeId
	         ,LedgerId=@rLedgerId
			 ,Amount=@rAmount
	      WHERE Id = @rId 	   
	      SELECT @lNextNumber AS Result
	 END  

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


GO

CREATE PROCEDURE [sAccounting].[pVoucherApproveListGet]

	 @rVoucherTypeId int = 0,
	 @rTransactionDate Date,
	 @rTransactionDateTo Date,
	 @rVoucherNumber int,
	 @rVoucherNumberTo int,
	 @rLedgerId int,
	 @rNarration nvarchar(100),
	 @rAmount int,
	 @rAccountingYearId int = 0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	  BEGIN
			SET @rNarration = sCommon.fSearchStringGet(@rNarration)
	  END
	 
  SELECT  
		  T.Id
		  ,VTM.Title AS VoucherType
		  ,T.VoucherNumber AS VoucherNo
		  ,T.TransactionDate AS VoucherDate
		  ,LM.Title AS Ledger
		  ,CASE WHEN ISNULL(TD.Amount,0) < 0 THEN ISNULL(TD.Amount,0) * -1 ELSE 0 END AS Credit
		  ,CASE WHEN ISNULL(TD.Amount,0) > 0 THEN ISNULL(TD.Amount,0) ELSE 0 END AS Debit
		  ,T.Narration AS Narration
		  ,AM.ReportOrgTitle As OrgTitle
		  ,AM.SmallAddress1 AS SmallAddress1
		  ,AM.SmallAddress2 AS SmallAddress2
		 
		
  FROM 
          sAccounting.tTransactionApprove T
          INNER JOIN sAccounting.tTransactionApproveDetail TD ON T.Id=TD.TransactionId
          INNER JOIN sAccounting.tVoucherTypeMaster VTM ON VTM.Id = T.VoucherTypeId
          INNER JOIN sAccounting.tLedgerMaster LM ON LM.Id=TD.LedgerId 
          INNER JOIN sAccounting.tAccountMaster AM ON AM.Id=T.AccountId
         
        
         WHERE 
		  (T.VoucherTypeId=@rVoucherTypeId OR @rVoucherTypeId = 0) 
			AND ((T.Narration like @rNarration) OR (ISNULL(@rNarration,'') = '')) 		
			AND (T.TransactionDate >= @rTransactionDate OR ISNULL(@rTransactionDate,'') = '') 
			And (T.TransactionDate <= @rTransactionDateTo OR ISNULL(@rTransactionDateTo,'') = '')
			AND (T.VoucherNumber >= @rVoucherNumber OR @rVoucherNumber=0) 
			AND (T.VoucherNumber <=@rVoucherNumberTo OR @rVoucherNumberTo=0)
			AND (TD.LedgerId = @rLedgerId OR @rLedgerId=0)
			AND (TD.Amount = @rAmount OR ISNULL(@rAmount,0) = 0)
			AND LM.AccountingYearId = @rAccountingYearId
			AND T.AccountingYearId = @rAccountingYearId
			AND  NOT EXISTS( SELECT 1 FROM sAccounting.tTransaction TA Where TA.TransactionApproveId=T.Id AND  TA.AccountingYearId = @rAccountingYearId )
			
            Order By T.VoucherTypeId,T.TransactionDate,T.VoucherNumber,Credit,Debit
END
GO
PRINT N'Creating [sAccounting].[pVoucherApproveNoGet]...';


GO
CREATE PROCEDURE [sAccounting].[pVoucherApproveNoGet]
	@rVoucherTypeId [int] = 0,
	@rAccountingYearId [int]

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 SELECT ISNULL(Max(VoucherNumber),0) + 1 AS VoucherNo
	   FROM sAccounting.tTransactionApprove
	  WHERE
	   (VoucherTypeId=@rVoucherTypeId OR @rVoucherTypeId=0)
		AND 	AccountingYearId  = @rAccountingYearId
END
GO
PRINT N'Creating [sAccounting].[pVoucherApproveSearchListGet]...';


GO
CREATE PROCEDURE [sAccounting].[pVoucherApproveSearchListGet]
	
	 @rId bigint = 0 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN  
	 
  SELECT T.Id
		 ,T.AccountId
		 ,T.AccountingYearId
		 ,T.TransactionDate
		 ,T.Narration
		 ,T.VoucherNumber
		 ,T.VoucherTypeId
		 ,T.SourceTypeId
		 ,T.SourceId
		 ,T.IsProfitAndLoss
		 ,T.RepeatLedger
		 ,T.CreatedDateTime
		 ,T.CreatedUserId
		 ,T.OrgGroupId
		 ,ISNULL(T.PayTypeId,0) AS PayTypeId
		 ,ISNULL(T.ChequeNo,'') AS ChequeNo
		 ,ISNULL(T.BankName,'') AS BankName
		 ,ISNULL(T.ChequeDate,'1900-01-01') AS ChequeDate
		 ,TD.Id as TransactionDetailId	 
		 ,TD.TransactionTypeId 
		 ,TD.LedgerId
		 ,TD.Amount
		 ,TD.Number    
  FROM 
       sAccounting.tTransactionApprove T
       INNER JOIN sAccounting.tTransactionApproveDetail TD ON T.Id=TD.TransactionId
      
  WHERE 
			(T.Id=@rId OR @rId = 0 )        
   Order By T.VoucherTypeId,T.VoucherNumber
END
GO
PRINT N'Creating [sAssessment].[pOptionalSubjectAdd]...';


GO
CREATE PROCEDURE [sAssessment].[pOptionalSubjectAdd]
	 
	 @rAcademicId  bigint,
     @rAssignSubjectXml [nvarchar](max)
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rAssignSubjectXml
BEGIN
BEGIN TRY
	
	 BEGIN TRANSACTION	
	 
	 DELETE FROM sAssessment.tOptionalSubject  WHERE  AcademicId=@rAcademicId
	
		INSERT INTO sAssessment.tOptionalSubject
		(
			 AcademicId,
			ClassSubjectId
		)
		SELECT
		
		    @rAcademicId,
			ClassSubjectId
		  
		FROM OPENXML (@loDoc, '/Table/AssignSubject', 1)
		WITH ( 
			
				ClassSubjectId int
			  ) 
	
	SELECT 1 AS Result
	
	COMMIT TRANSACTION
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
END
GO
PRINT N'Creating [sAttendance].[pRptDivisionWiseOverallLEctureList]...';


GO
CREATE PROCEDURE [sAttendance].[pRptDivisionWiseOverallLEctureList]
	
		@rBuilder1 nvarchar(max)='',
		@rBuilder2 nvarchar(max)='', 
		 @rBatchId int,
		@rDivisionId int ,
		@rSubjectID int,
		@rOrgId int
	 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	SELECT 
		 
			 
			AB.SubjectId,
			 
			--Count(A.Id),
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2, 
			AB.NoOfLecture AS NoOfLecture ,
			TM.TItle+'-'+VM.Title As DivisionTitle,
			AB.DivisionId,
			SM.Code As SubjectTitle,
			Isnull((
				Select Distinct
					--Count( A.Id) ,
					isnull(count(ST.SubjectId),0)
				From sAttendance.tStudentRegister ST
				--INNER JOIN sStudent.tAcademic A On A.Id=ST.AcademiciD   
				Where A.BatchID=@rBatchId    AND A.DivisionId=@rDivisionId  AND A.Id=ST.AcademiciD   
				AND AB.SubjectId=ST.SubjectId 				
				group by ST.SubjectId
				 
			),0) AS TotalLEcture,
			ST.FirstName+' ' +MiddleName AS Name,
			ST.Code
			
	FROM 
			 sTimetable.tAnnualSubjectWorkLoad AB
			 INNER JOIN sSetup.tDivisionMaster VM ON VM.Id=AB.DivisionId
			 INNER JOIN sSetup.tClassMaster TM on TM.Id=Vm.CLassID
			 INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=AB.SubjectID
			 INNER JOIN sStudent.tAcademic A On A.DivisionId=VM.Id AND A.BatchID=@rBatchId
			 INNER JOIN sStudent.tStudentMaster ST On ST.Id=A.StudentId
			--INNER JOIN  sAttendance.tStudentRegister SG  On SG.Academicid=A.Id
			--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 
		 ((AB.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		 AND ((AB.SubjectID=@rSubjectID) OR (@rSubjectID=0))
		 AND ST.OrgId=@rOrgId 
		 --AND AB.BatchID=@rBatchId ANd AB.DivisionId=@rDivisionId
	 AND AB.BatchID=@rBatchId  
	 
END
GO
PRINT N'Creating [sBiometric].[pLateTimeSheetGet]...';


GO
CREATE PROCEDURE [sBiometric].[pLateTimeSheetGet]
	 
	 @rEmployeeId bigint=0,
	 @rEmployeeManagerId bigint =0,	
	 @rFromDate Date,
	 @rToDate Date,
	 @rStatus nvarchar(10) = '0',
	 @rEmployeeCode nvarchar(100)='',
     @rEmployeeName nvarchar(100)='',
	 @rOrgGroupId int =0

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

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


	CREATE TABLE #TempMonthTrans
	(
	Id int Identity,
	EmployeeId bigint,	
	Attn_Date DateTime,
	PresentStatus nvarchar(5),
	FirstIn nvarchar(20),
	LastOut nvarchar(20),
	OverTime nvarchar(20),
	LateBy nvarchar(20),
	Duration nvarchar(20),	
	EarlyBy nvarchar(20)
	)
	
	INSERT INTO #TempMonthTrans
	
	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 01) as datetime),D01,D01_IN,D01_OUT,D01_O,D01_L,D01_T,D01_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 02) as datetime),D02,D02_IN,D02_OUT,D02_O,D02_L,D02_T,D02_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 03) as datetime),D03,D03_IN,D03_OUT,D03_O,D03_L,D03_T,D03_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 04) as datetime),D04,D04_IN,D04_OUT,D04_O,D04_L,D04_T,D04_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 05) as datetime),D05,D05_IN,D05_OUT,D05_O,D05_L,D05_T,D05_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 06) as datetime),D06,D06_IN,D06_OUT,D06_O,D06_L,D06_T,D06_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 07) as datetime),D07,D07_IN,D07_OUT,D07_O,D07_L,D07_T,D07_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 08) as datetime),D08,D08_IN,D08_OUT,D08_O,D08_L,D08_T,D08_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 09) as datetime),D09,D09_IN,D09_OUT,D09_O,D09_L,D09_T,D09_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 10) as datetime),D10,D10_IN,D10_OUT,D10_O,D10_L,D10_T,D10_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 11) as datetime),D11,D11_IN,D11_OUT,D11_O,D11_L,D11_T,D11_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 12) as datetime),D12,D12_IN,D12_OUT,D12_O,D12_L,D12_T,D12_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 13) as datetime),D13,D13_IN,D13_OUT,D13_O,D13_L,D13_T,D13_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 14) as datetime),D14,D14_IN,D14_OUT,D14_O,D14_L,D14_T,D14_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 15) as datetime),D15,D15_IN,D15_OUT,D15_O,D15_L,D15_T,D15_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 16) as datetime),D16,D16_IN,D16_OUT,D16_O,D16_L,D16_T,D16_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 17) as datetime),D17,D17_IN,D17_OUT,D17_O,D17_L,D17_T,D17_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 18) as datetime),D18,D18_IN,D18_OUT,D18_O,D18_L,D18_T,D18_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 19) as datetime),D19,D19_IN,D19_OUT,D19_O,D19_L,D19_T,D19_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 20) as datetime),D20,D20_IN,D20_OUT,D20_O,D20_L,D20_T,D20_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 21) as datetime),D21,D21_IN,D21_OUT,D21_O,D21_L,D21_T,D21_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 22) as datetime),D22,D22_IN,D22_OUT,D22_O,D22_L,D22_T,D22_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 23) as datetime),D23,D23_IN,D23_OUT,D23_O,D23_L,D23_T,D23_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 24) as datetime),D24,D24_IN,D24_OUT,D24_O,D24_L,D24_T,D24_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 25) as datetime),D25,D25_IN,D25_OUT,D25_O,D25_L,D25_T,D25_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 26) as datetime),D26,D26_IN,D26_OUT,D26_O,D26_L,D26_T,D26_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 27) as datetime),D27,D27_IN,D27_OUT,D27_O,D27_L,D27_T,D27_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 28) as datetime),D28,D28_IN,D28_OUT,D28_O,D28_L,D28_T,D28_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	IF  Month(@rFromDate) <> 2 or (((YEAR(@rFromDate) % 4 = 0 AND YEAR(@rFromDate) % 100 <> 0) OR YEAR(@rFromDate) % 400 = 0 And Month(@rFromDate)  =2)) 
	BEGIN
		INSERT INTO #TempMonthTrans
	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 29) as datetime),D29,D29_IN,D29_OUT,D29_O,D29_L,D29_T,D29_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
	END
	
	IF Month(@rFromDate) <> 2
	BEGIN
	INSERT INTO #TempMonthTrans
	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 30) as datetime),D30,D30_IN,D30_OUT,D30_O,D30_L,D30_T,D30_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
	END
	
	IF Month(@rFromDate) NOT IN (2,4,6,9,11)
	BEGIN
	INSERT INTO #TempMonthTrans
	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 31) as datetime),D31,D31_IN,D31_OUT,D31_O,D31_L,D31_T,D31_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
	END
	
	SELECT 
	TM.*,
	MT.Tot_Attn + Tot_WeekOff + Tot_Holiday  AS TotalPresent,
	Tot_Abs AS TotalAbsent,
	Tot_WeekOff AS TotalWeekOff,
	Tot_Holiday AS Totalholiday,
	Tot_Leave AS TotalLeave,
	EM.FirstName + ' ' + EM.LastName AS Name,
	EM.Code,
	ISNULL(ELS.Id,0) AS EmployeeLateStatusId,
	ISNULL(ELS.EarlyLeaveRemark,'') AS EarlyLeaveRemark,
	ISNULL(SM.Id,0) AS StatusId,
	ISNULL(SM.Title,'') AS Status,
	convert(float,replace(LateBy,':','.')) + convert(float,replace(EarlyBy,':','.')) AS EarlyHrs,
	'EL' AS PresentStatus1
	FROM #TempMonthTrans TM 
	INNER JOIN sBiometric.tMonthTrans MT ON MT.EmployeeId=TM.EmployeeId
	INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = TM.EmployeeId
	INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = TM.EmployeeId
	LEFT JOIN sBiometric.tEmployeeLateStatus ELS ON ELS.EmployeeId = TM.EmployeeId AND CONVERT(date,TM.Attn_Date) = CONVERT(date,ELS.LateDate)
	LEFT JOIN sCommon.tStatusMaster SM ON SM.Id = ELS.StatusId
	WHERE 
	TM.ATTN_DATE >= @rFromDate AND TM.ATTN_DATE <=@rToDate 	
	AND (EJD.EmployeeManagerId = @rEmployeeManagerId OR @rEmployeeManagerId = 0)
	AND MT.Attn_dt=cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime)
	--AND (PresentStatus = @rStatus OR @rStatus='0') AND PresentStatus IN ('LH','HD')
	AND (EM.Code = @rEmployeeCode OR ISNULL(@rEmployeeCode,'') = '')
    AND (EM.EmployeeName like @rEmployeeName+'%' OR ISNULL(@rEmployeeName,'') = '')
	AND Convert(decimal(10,2),Replace(TM.Duration,':','.')) >= convert(decimal(10,2),SUBSTRING(@lItemValue,1,CHARINDEX ( ';',@lItemValue)-1))
	AND Convert(decimal(10,2),Replace(TM.Duration,':','.')) <= Convert(decimal(10,2),SUBSTRING(@lItemValue,CHARINDEX (';',@lItemValue)+1,4))
	ORDER BY TM.EmployeeId,TM.Attn_Date
END
GO
PRINT N'Creating [sBiometric].[pYearlyPresenceSUMmaryGet]...';


GO
 
CREATE PROCEDURE [sBiometric].[pYearlyPresenceSUMmaryGet]
	 
	 @rCode nvarchar(20)='',
	 @rOrgId int,
	 @rFromDate date,
	 @rToDate date,
	 @rIsMonthly bit=0

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	 
	DECLARE @lOrgGroupId int=0
	SELECT @lOrgGroupId = OrgGroupId FROM sSetup.tOrganizationMaster WHERE Id = @rOrgId
		
	DECLARE @lItemValue nvarchar(20) = ''
	SELECT @lItemValue = CASE WHEN CS.Id IS NOT NULL THEN ISNULL(CS.ItemValue,'') ELSE ISNULL(CM.ItemValue,'') END
	FROM sConfig.tConfigurationMaster CM
	LEFT JOIN sConfig.tConfigurationSetup CS ON CM.Id = CS.ConfigurationId
	AND SourceTypeId = 2010 AND SourceId = @lOrgGroupId WHERE CM.Id = 204


	IF(@rIsMonthly = 1)
	BEGIN
		SELECT
			ROW_NUMBER() OVER (ORDER BY Code ASC) AS SrNo,
			EM.Code,
			EM.FirstName + ' ' + EM.Lastname AS Name,
			CONVERT(nvarchar(20), DATENAME(MONTH,(MT.attn_dt))) +' - '+ CONVERT(nvarchar(10),YEAR(MT.attn_dt)) AS MonthYear,
			ISNULL((SELECT COUNT(value) FROM sBiometric.tMonthTrans
			UNPIVOT
			(value FOR col IN (d01_t, d02_t, d03_t, d04_t, d05_t, d06_t, d07_t, d08_t, d09_t, d10_t, d11_t, d12_t, d13_t, d14_t, d15_t, d16_t, d17_t, d18_t, d19_t, d20_t, d21_t, d22_t, d23_t, d24_t, d25_t, d26_t, d27_t, d28_t, d29_t, d30_t, d31_t)) PT
			WHERE CONVERT(FLOAT,REPLACE(value,':','.')) >= CONVERT(FLOAT,REPLACE(@lItemValue,':','.')) AND attn_dt = MT.attn_dt AND EM.Id = PT.EmployeeId GROUP BY empcode),0) AS DinnerAllowance,

			ISNULL((SELECT COUNT(value) FROM sBiometric.tMonthTrans
			UNPIVOT
			(value FOR col IN (d01, d02, d03, d04, d05, d06, d07, d08, d09, d10, d11, d12, d13, d14, d15, d16, d17, d18, d19, d20, d21, d22, d23, d24, d25, d26, d27, d28, d29, d30, d31)) PT
			WHERE value LIKE 'PW' AND attn_dt = MT.attn_dt AND EM.Id = PT.EmployeeId GROUP BY empcode),0) AS CompOff,

			SUM(CONVERT(FLOAT,REPLACE(Tot_Early,':','.'))) + ISNULL((SELECT SUM(CONVERT(DECIMAL(10,2),Replace(value,':','.'))) FROM sBiometric.tMonthTrans
			UNPIVOT
			(value FOR col IN (d01_l, d02_l, d03_l, d04_l, d05_l, d06_l, d07_l, d08_l, d09_l, d10_l, d11_l, d12_l, d13_l, d14_l, d15_l, d16_l, d17_l, d18_l, d19_l, d20_l, d21_l, d22_l, d23_l, d24_l, d25_l, d26_l, d27_l, d28_l, d29_l, d30_l, d31_l)) PT 
			WHERE CONVERT(FLOAT,REPLACE(value,':','.')) >= CONVERT(FLOAT,REPLACE('00:30',':','.')) AND attn_dt = MT.attn_dt AND EM.Id = PT.EmployeeId GROUP BY empcode),0) - SUM(ISNULL(A.EarlyHrs,0)) AS EarlyLeave,

			SUM(CONVERT(float,REPLACE(Tot_OT,':','.'))) AS Tot_OT,		

			CASE WHEN (SUM(CONVERT(decimal(10,2),REPLACE(Tot_OT,':','.'))) - CONVERT(decimal(10,2),REPLACE((
			SUM(CONVERT(FLOAT,REPLACE(Tot_Early,':','.'))) +
			ISNULL((SELECT SUM(CONVERT(DECIMAL(10,2),
			Replace(value,':','.')
			)) FROM sBiometric.tMonthTrans
			UNPIVOT
			(value FOR col IN (d01_l, d02_l, d03_l, d04_l, d05_l, d06_l, d07_l, d08_l, d09_l, d10_l, d11_l, d12_l, d13_l, d14_l, d15_l, d16_l, d17_l, d18_l, d19_l, d20_l, d21_l, d22_l, d23_l, d24_l, d25_l, d26_l, d27_l, d28_l, d29_l, d30_l, d31_l)) PT
			WHERE CONVERT(FLOAT,REPLACE(value,':','.')) >= CONVERT(FLOAT,REPLACE('00:30',':','.')) AND attn_dt = MT.attn_dt AND EM.Id = PT.EmployeeId GROUP BY empcode),0) - SUM(ISNULL(A.EarlyHrs,0))
			),':','.'))) > 0 Then 
			Convert(nvarchar(20),SUM(Convert(decimal(10,2),Replace(Tot_OT,':','.'))) - Convert(decimal(10,2),Replace((
			SUM(CONVERT(FLOAT,REPLACE(Tot_Early,':','.'))) +
			ISNULL((SELECT SUM(CONVERT(DECIMAL(10,2),
			Replace(value,':','.')
			)) FROM sBiometric.tMonthTrans
			UNPIVOT
			(value FOR col IN (d01_l, d02_l, d03_l, d04_l, d05_l, d06_l, d07_l, d08_l, d09_l, d10_l, d11_l, d12_l, d13_l, d14_l, d15_l, d16_l, d17_l, d18_l, d19_l, d20_l, d21_l, d22_l, d23_l, d24_l, d25_l, d26_l, d27_l, d28_l, d29_l, d30_l, d31_l)) PT
			WHERE CONVERT(FLOAT,REPLACE(value,':','.')) >= CONVERT(FLOAT,REPLACE('00:30',':','.')) AND attn_dt = MT.attn_dt AND EM.Id = PT.EmployeeId GROUP BY empcode),0) - SUM(ISNULL(A.EarlyHrs,0))
			),':','.')))
		
			ELSE

			'-' + Convert(nvarchar(10),Convert(decimal(10,2),Replace(
			(
			SUM(CONVERT(FLOAT,REPLACE(Tot_Early,':','.'))) +
			ISNULL((SELECT SUM(CONVERT(DECIMAL(10,2),
			Replace(value,':','.')
			)) FROM sBiometric.tMonthTrans
			UNPIVOT
			(value FOR col IN (d01_l, d02_l, d03_l, d04_l, d05_l, d06_l, d07_l, d08_l, d09_l, d10_l, d11_l, d12_l, d13_l, d14_l, d15_l, d16_l, d17_l, d18_l, d19_l, d20_l, d21_l, d22_l, d23_l, d24_l, d25_l, d26_l, d27_l, d28_l, d29_l, d30_l, d31_l)) PT
			WHERE CONVERT(FLOAT,REPLACE(value,':','.')) >= CONVERT(FLOAT,REPLACE('00:30',':','.')) AND attn_dt = MT.attn_dt AND EM.Id = PT.EmployeeId GROUP BY empcode),0) - SUM(ISNULL(A.EarlyHrs,0))
			),':','.')) - SUM(Convert(decimal(10,2),Replace(Tot_OT,':','.'))))
			END	AS Tot_OT_EL,
		
			CONVERT(nvarchar(20), DATENAME(MONTH,(MT.attn_dt))) +' - '+ CONVERT(nvarchar(10),YEAR(MT.attn_dt)) AS MonthYear,
			ISNULL((SELECT COUNT(value) FROM sBiometric.tMonthTrans
			UNPIVOT
			(value FOR col IN (d01_t, d02_t, d03_t, d04_t, d05_t, d06_t, d07_t, d08_t, d09_t, d10_t, d11_t, d12_t, d13_t, d14_t, d15_t, d16_t, d17_t, d18_t, d19_t, d20_t, d21_t, d22_t, d23_t, d24_t, d25_t, d26_t, d27_t, d28_t, d29_t, d30_t, d31_t)) PT
			WHERE CONVERT(FLOAT,REPLACE(value,':','.')) > 09.15 AND CONVERT(FLOAT,REPLACE(value,':','.')) <= CONVERT(FLOAT,REPLACE(@lItemValue,':','.')) AND attn_dt = MT.attn_dt AND EM.Id = PT.EmployeeId GROUP BY empcode),0) AS OT_DinnerAllowance
		FROM 
			sBiometric.tMonthTrans MT
			INNER JOIN sHrm.tEmployeeMaster EM ON MT.EMployeeId = EM.Id AND MT.attn_dt >= @rFromDate  AND MT.attn_dt <= @rToDate
			LEFT JOIN
			(
			SELECT SUM(ISNULL(ELS.EarlyHrs,0)) AS EarlyHrs,ELS.EmployeeId FROM sBiometric.tEmployeeLateStatus ELS 
			WHERE ELS.StatusId = 550 AND  CONVERT(DATE,ELS.LateDate)>= CONVERT(DATE,@rFromDate)
			AND CONVERT(DATE,ELS.LateDate) <= CONVERT(DATE,DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, @rToDate) + 1, 0)))
			GROUP BY ELS.EmployeeId
			) A ON A.EMployeeId = MT.EMployeeId 
			LEFT JOIN
			(
			SELECT ELS1.EmployeeId,COUNT(ELS1.LateStatus) AS LateStatus FROM sBiometric.tEmployeeLateStatus ELS1 
			WHERE ELS1.StatusId = 550 AND LateStatus = 'EL' AND CONVERT(DATE,ELS1.LateDate)>= CONVERT(DATE,@rFromDate)
			AND CONVERT(DATE,ELS1.LateDate) <=CONVERT(DATE,DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, @rToDate) + 1, 0)))
			GROUP BY ELS1.EmployeeId
			) A1 ON A1.EMployeeId = MT.EMployeeId 
			LEFT JOIN
			(
			SELECT ELS1.EmployeeId,COUNT(ELS1.LateStatus) AS TotalLate FROM sBiometric.tEmployeeLateStatus ELS1 
			WHERE LateStatus = 'EL' AND CONVERT(DATE,ELS1.LateDate)>= CONVERT(DATE,@rFromDate)
			AND CONVERT(DATE,ELS1.LateDate) <=CONVERT(DATE,DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, @rToDate) + 1, 0)))
			GROUP BY ELS1.EmployeeId
			) A2 ON A2.EMployeeId = MT.EMployeeId 
	
		WHERE (EM.Code = @rCode OR ISNULL(@rCode,'') = '')
		GROUP BY EM.Id,EM.Code,EM.FirstName,EM.Lastname,MT.attn_dt,A1.LateStatus
		ORDER BY EM.Code
	END

	ELSE

	BEGIN
		DECLARE @lYearlyPresence TABLE(Code nvarchar(20),Name nvarchar(100),DinnerAllowance decimal(8,2),CompOff decimal(8,2), EarlyLeave decimal(8,2),	Total_OT decimal(8,2),Total_OT_EL decimal(8,2),OT_DinnerAllowance decimal(8,2))

		INSERT INTO @lYearlyPresence
		SELECT
			EM.Code,
			EM.FirstName + ' ' + EM.Lastname AS Name,
			ISNULL((SELECT COUNT(value) FROM sBiometric.tMonthTrans
			UNPIVOT
			(value FOR col IN (d01_t, d02_t, d03_t, d04_t, d05_t, d06_t, d07_t, d08_t, d09_t, d10_t, d11_t, d12_t, d13_t, d14_t, d15_t, d16_t, d17_t, d18_t, d19_t, d20_t, d21_t, d22_t, d23_t, d24_t, d25_t, d26_t, d27_t, d28_t, d29_t, d30_t, d31_t)) PT
			WHERE CONVERT(FLOAT,REPLACE(value,':','.')) >= CONVERT(FLOAT,REPLACE(@lItemValue,':','.')) AND attn_dt = MT.attn_dt AND EM.Id = PT.EmployeeId GROUP BY empcode),0) AS DinnerAllowance,

			ISNULL((SELECT COUNT(value) FROM sBiometric.tMonthTrans
			UNPIVOT
			(value FOR col IN (d01, d02, d03, d04, d05, d06, d07, d08, d09, d10, d11, d12, d13, d14, d15, d16, d17, d18, d19, d20, d21, d22, d23, d24, d25, d26, d27, d28, d29, d30, d31)) PT
			WHERE value LIKE 'PW' AND attn_dt = MT.attn_dt AND EM.Id = PT.EmployeeId GROUP BY empcode),0) AS CompOff,

			SUM(CONVERT(FLOAT,REPLACE(Tot_Early,':','.'))) + ISNULL((SELECT SUM(CONVERT(DECIMAL(10,2),Replace(value,':','.'))) FROM sBiometric.tMonthTrans
			UNPIVOT
			(value FOR col IN (d01_l, d02_l, d03_l, d04_l, d05_l, d06_l, d07_l, d08_l, d09_l, d10_l, d11_l, d12_l, d13_l, d14_l, d15_l, d16_l, d17_l, d18_l, d19_l, d20_l, d21_l, d22_l, d23_l, d24_l, d25_l, d26_l, d27_l, d28_l, d29_l, d30_l, d31_l)) PT 
			WHERE CONVERT(FLOAT,REPLACE(value,':','.')) >= CONVERT(FLOAT,REPLACE('00:30',':','.')) AND attn_dt = MT.attn_dt AND EM.Id = PT.EmployeeId GROUP BY empcode),0) - SUM(ISNULL(A.EarlyHrs,0)) AS EarlyLeave,

			SUM(CONVERT(float,REPLACE(Tot_OT,':','.'))) AS Tot_OT,		

			CASE WHEN (SUM(CONVERT(decimal(10,2),REPLACE(Tot_OT,':','.'))) - CONVERT(decimal(10,2),REPLACE((
			SUM(CONVERT(FLOAT,REPLACE(Tot_Early,':','.'))) +
			ISNULL((SELECT SUM(CONVERT(DECIMAL(10,2),
			Replace(value,':','.')
			)) FROM sBiometric.tMonthTrans
			UNPIVOT
			(value FOR col IN (d01_l, d02_l, d03_l, d04_l, d05_l, d06_l, d07_l, d08_l, d09_l, d10_l, d11_l, d12_l, d13_l, d14_l, d15_l, d16_l, d17_l, d18_l, d19_l, d20_l, d21_l, d22_l, d23_l, d24_l, d25_l, d26_l, d27_l, d28_l, d29_l, d30_l, d31_l)) PT
			WHERE CONVERT(FLOAT,REPLACE(value,':','.')) >= CONVERT(FLOAT,REPLACE('00:30',':','.')) AND attn_dt = MT.attn_dt AND EM.Id = PT.EmployeeId GROUP BY empcode),0) - SUM(ISNULL(A.EarlyHrs,0))
			),':','.'))) > 0 Then 
			Convert(nvarchar(20),SUM(Convert(decimal(10,2),Replace(Tot_OT,':','.'))) - Convert(decimal(10,2),Replace((
			SUM(CONVERT(FLOAT,REPLACE(Tot_Early,':','.'))) +
			ISNULL((SELECT SUM(CONVERT(DECIMAL(10,2),
			Replace(value,':','.')
			)) FROM sBiometric.tMonthTrans
			UNPIVOT
			(value FOR col IN (d01_l, d02_l, d03_l, d04_l, d05_l, d06_l, d07_l, d08_l, d09_l, d10_l, d11_l, d12_l, d13_l, d14_l, d15_l, d16_l, d17_l, d18_l, d19_l, d20_l, d21_l, d22_l, d23_l, d24_l, d25_l, d26_l, d27_l, d28_l, d29_l, d30_l, d31_l)) PT
			WHERE CONVERT(FLOAT,REPLACE(value,':','.')) >= CONVERT(FLOAT,REPLACE('00:30',':','.')) AND attn_dt = MT.attn_dt AND EM.Id = PT.EmployeeId GROUP BY empcode),0) - SUM(ISNULL(A.EarlyHrs,0))
			),':','.')))
		
			ELSE

			'-' + Convert(nvarchar(10),Convert(decimal(10,2),Replace(
			(
			SUM(CONVERT(FLOAT,REPLACE(Tot_Early,':','.'))) +
			ISNULL((SELECT SUM(CONVERT(DECIMAL(10,2),
			Replace(value,':','.')
			)) FROM sBiometric.tMonthTrans
			UNPIVOT
			(value FOR col IN (d01_l, d02_l, d03_l, d04_l, d05_l, d06_l, d07_l, d08_l, d09_l, d10_l, d11_l, d12_l, d13_l, d14_l, d15_l, d16_l, d17_l, d18_l, d19_l, d20_l, d21_l, d22_l, d23_l, d24_l, d25_l, d26_l, d27_l, d28_l, d29_l, d30_l, d31_l)) PT
			WHERE CONVERT(FLOAT,REPLACE(value,':','.')) >= CONVERT(FLOAT,REPLACE('00:30',':','.')) AND attn_dt = MT.attn_dt AND EM.Id = PT.EmployeeId GROUP BY empcode),0) - SUM(ISNULL(A.EarlyHrs,0))
			),':','.')) - SUM(Convert(decimal(10,2),Replace(Tot_OT,':','.'))))
			END	AS Tot_OT_EL,
		
			ISNULL((SELECT COUNT(value) FROM sBiometric.tMonthTrans
			UNPIVOT
			(value FOR col IN (d01_t, d02_t, d03_t, d04_t, d05_t, d06_t, d07_t, d08_t, d09_t, d10_t, d11_t, d12_t, d13_t, d14_t, d15_t, d16_t, d17_t, d18_t, d19_t, d20_t, d21_t, d22_t, d23_t, d24_t, d25_t, d26_t, d27_t, d28_t, d29_t, d30_t, d31_t)) PT
			WHERE CONVERT(FLOAT,REPLACE(value,':','.')) > 09.15  AND CONVERT(FLOAT,REPLACE(value,':','.')) <= CONVERT(FLOAT,REPLACE(@lItemValue,':','.')) AND attn_dt = MT.attn_dt AND EM.Id = PT.EmployeeId GROUP BY empcode),0) AS OT_DinnerAllowance
		FROM 
			sBiometric.tMonthTrans MT
			INNER JOIN sHrm.tEmployeeMaster EM ON MT.EMployeeId = EM.Id AND MT.attn_dt >= @rFromDate  AND MT.attn_dt <= @rToDate
			LEFT JOIN
			(
			SELECT SUM(ISNULL(ELS.EarlyHrs,0)) AS EarlyHrs,ELS.EmployeeId FROM sBiometric.tEmployeeLateStatus ELS 
			WHERE ELS.StatusId = 550 AND  CONVERT(DATE,ELS.LateDate)>= CONVERT(DATE,@rFromDate)
			AND CONVERT(DATE,ELS.LateDate) <= CONVERT(DATE,DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, @rToDate) + 1, 0)))
			GROUP BY ELS.EmployeeId
			) A ON A.EMployeeId = MT.EMployeeId 
			LEFT JOIN
			(
			SELECT ELS1.EmployeeId,COUNT(ELS1.LateStatus) AS LateStatus FROM sBiometric.tEmployeeLateStatus ELS1 
			WHERE ELS1.StatusId = 550 AND LateStatus = 'EL' AND CONVERT(DATE,ELS1.LateDate)>= CONVERT(DATE,@rFromDate)
			AND CONVERT(DATE,ELS1.LateDate) <=CONVERT(DATE,DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, @rToDate) + 1, 0)))
			GROUP BY ELS1.EmployeeId
			) A1 ON A1.EMployeeId = MT.EMployeeId 
			LEFT JOIN
			(
			SELECT ELS1.EmployeeId,COUNT(ELS1.LateStatus) AS TotalLate FROM sBiometric.tEmployeeLateStatus ELS1 
			WHERE LateStatus = 'EL' AND CONVERT(DATE,ELS1.LateDate)>= CONVERT(DATE,@rFromDate)
			AND CONVERT(DATE,ELS1.LateDate) <=CONVERT(DATE,DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, @rToDate) + 1, 0)))
			GROUP BY ELS1.EmployeeId
			) A2 ON A2.EMployeeId = MT.EMployeeId 
	
		WHERE (EM.Code = @rCode OR ISNULL(@rCode,'') = '')
		GROUP BY EM.Id,EM.Code,EM.FirstName,EM.Lastname,MT.attn_dt,A1.LateStatus
		ORDER BY EM.Code

		SELECT ROW_NUMBER() OVER (ORDER BY Code ASC) AS SrNo, Code,Name, '' AS MonthYear,SUM(DinnerAllowance) AS DinnerAllowance,SUM(CompOff) AS CompOff,SUM(EarlyLeave) AS EarlyLeave,SUM(Total_OT) AS Tot_OT,SUM(Total_OT_EL) AS Tot_OT_EL,SUM(OT_DinnerAllowance) AS OT_DinnerAllowance FROM @lYearlyPresence GROUP BY Code,Name
	END
END
GO
PRINT N'Creating [sCommon].[pStockPrefixSetupGet]...';


GO
CREATE PROCEDURE [sCommon].[pStockPrefixSetupGet]
	@rOrgId [smallint] = 0,
	@rId [int] = 0,
	@rPrefix [nvarchar](10) = '',
	@rPrefixFunctionalityId [int] = 0,
	@rIsIncludeObsoleted [bit] = 1,
	@rStoreLocationId int  = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

SET @rPrefix = sCommon.fSearchStringGet(@rPrefix)

	 SELECT ISNULL(PS.Id,0) AS Id, 
			ISNULL(PF.Id,0) AS PrefixFunctionalityId, 
			ISNULL(PS.Prefix,'') AS Prefix, 
			--(CONVERT(NVARCHAR(12), PS.EffectiveDate, 101)) AS EffectiveDate, 
			ISNULL(PS.EffectiveDate,sCommon.fGetDate()) AS EffectiveDate,
			ISNULL(PS.IsObsolete,0) AS IsObsolete, 
			ISNULL(PF.Title,'') AS Title, 
			ISNULL(PS.NumberLength,0) AS SpecifiedPrefixLength, 
			ISNULL(PF.NumberMaxLength,0) AS MaxPrefixLength, 
			ISNULL(PS.Prefix +  CONVERT(NVARCHAR(10), ISNULL(PS.CurrentNumber, 0)),'') AS CurrentPrefix
	   FROM sCommon.tPrefixFunctionality PF		
	   LEFT JOIN sCommon.tPrefixSetup   PS	  
	   ON PS.PrefixFunctionalityId = PF.Id AND (PS.StoreLocationId = @rStoreLocationId OR PS.StoreLocationId=0) AND PS.OrgId = @rOrgId AND PF.IsObsolete=0
	   
	   WHERE  PF.IsObsolete = 0 AND	   
	         ISNULL(PS.IsObsolete,0) = (CASE WHEN @rIsIncludeObsoleted = 1 THEN PS.IsObsolete ELSE 0 END)
			 AND ((PS.Id = @rId) OR (@rId = 0)) 
	         AND ((PS.Prefix LIKE @rPrefix) OR (@rPrefix = '')) 
	         AND ((PS.PrefixFunctionalityId = @rPrefixFunctionalityId) OR (@rPrefixFunctionalityId = 0)) 
	         AND (ISNULL(PS.EffectiveDate,sCommon.fGetDate()) <= (CASE WHEN @rPrefixFunctionalityId > 0 THEN (sCommon.fGetDate()) ELSE (ISNULL(PS.EffectiveDate,sCommon.fGetDate())) END)) 
	          AND PF.Id in (27,1005,1004,1006,26,52,53,1007) 
	          --AND PS.OrgId = @rOrgId
	         --AND (PS.StoreLocationid = @rStoreLocationId )OR (@rStoreLocationId = 0)
	         order by PF.Title
	         
	         
END
GO
PRINT N'Creating [sCommon].[pSubmitDocumentMasterAdd]...';


GO
CREATE PROCEDURE [sCommon].[pSubmitDocumentMasterAdd]
	 
	@rId int,
	@rSubmitDocumentFunctionalityId smallint,
	@rDocumentName nvarchar(100),
	@rOrgId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	IF(@rId = 0)	
	BEGIN  
		
		If Exists(select 1 from sCommon.tSubmitDocumentMaster where DocumentName=@rDocumentName AND OrgId=@rOrgId AND SubmitDocumentFunctionalityId=@rSubmitDocumentFunctionalityId )
		Begin
			select -102 as Result
			RETURN
		End
	END
	ELSE
	BEGIN
		If  Exists(select 1  from sCommon.tSubmitDocumentMaster where DocumentName=@rDocumentName AND OrgId=@rOrgId AND SubmitDocumentFunctionalityId=@rSubmitDocumentFunctionalityId AND Id<>@rId)
		Begin
			select -102 as Result
			RETURN
		End

	END
	 BEGIN TRANSACTION	
 IF(@rId = 0)	
BEGIN

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


	INSERT INTO sCommon.tSubmitDocumentMaster
		(
			Id,
			SubmitDocumentFunctionalityId,
			DocumentName,
			OrgId
		)
	VALUES
		(
			@lNextNumber,
			@rSubmitDocumentFunctionalityId,
			@rDocumentName,
			@rOrgId
			
		)
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sCommon.tSubmitDocumentMaster
	    SET
			SubmitDocumentFunctionalityId=@rSubmitDocumentFunctionalityId,
			DocumentName=@rDocumentName,
			OrgId=@rOrgId
	      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'Creating [sCommon].[pSubmitDocumentMasterGet]...';


GO
CREATE PROCEDURE [sCommon].[pSubmitDocumentMasterGet]
	 @rId int = 0,
	 @rDocumentName nvarchar(100),
	 @rOrgId int,
	 @rIsSearch bit,
	 @rSubmitDocumentFunctionalityId Smallint
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 IF(@rIsSearch=1)
		BEGIN
			
			SET @rDocumentName = sCommon.fSearchStringGet(@rDocumentName)
		END
	SELECT 
	
			DM.Id,
			DM.SubmitDocumentFunctionalityId,
			DM.DocumentName,
			FM.Title AS DocumentFunctionalityType
  FROM 
          sCommon.tSubmitDocumentMaster DM
          INNER JOIN sCommon.tSubmitDocumentFunctionalityMaster FM ON FM.Id=DM.SubmitDocumentFunctionalityId
             
  WHERE 
  
       ((DM.Id = @rId) OR (@rId = 0))
		AND  ((DM.DocumentName like @rDocumentName) OR (ISNULL(@rDocumentName,'') = '')) 
		AND(DM.OrgId=@rOrgId)
		AND ((FM.Id = @rSubmitDocumentFunctionalityId) OR (@rSubmitDocumentFunctionalityId = 0))
  
		
END
GO
PRINT N'Creating [sFee].[pFeecancelReceiptListviewGet]...';


GO

CREATE PROCEDURE [sFee].[pFeecancelReceiptListviewGet]
		
		@rOrgId smallint,
		@rBatchId int,
		@rAcademicId bigint
		
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
			
BEGIN 	
DECLARE @lcancellist nvarchar(max)	=''
	SELECT @lcancellist=@lcancellist+'<tr>
	<td align="left" scope="col">'+ convert(varchar,Isnull(R.ReceiptNumber,0)) +'</td>
	<td align="left" scope="col">'+convert(varchar,ISNULL(R.ReceiptDate,'01/01/0001'),103)+'</td>
    <td align="left" scope="col">'+Convert(varchar,ISNULL(R.ReceiptAmount,0))+'</td>
    <td align="left" scope="col">'+ISNULL(PTM.Title,'')+'</td>
    <td align="left" scope="col">'+ISNULL(R.ChequeNo,'')+'</td>
    <td align="left" scope="col">'+ISNULL(R.BankName,'')+'</td>
    <td align="left" scope="col">'+ISNULL(RBM.Title,'')+'</td>
    <td align="left" scope="col">'+convert(varchar,ISNULL(FI.InvoiceNumber,0))+'</td>
    <tr>'
  FROM 
		sFee.tReceipt R
		INNER JOIN sStudent.vStudentAcademic A
			ON A.AcademicId=R.SourceId
		INNER JOIN sFinanceCommon.tPayTypeMaster PTM
		ON PTM.Id=R.PayTypeId
		INNER JOIN sFee.tReceiptBookMaster RBM
			ON RBM.Id=R.ReceiptBookId
		LEFT JOIN sFee.tFeeInvoice FI ON FI.Id = R.FeeInvoiceId
WHERE 
	    R.SourceTypeId=2001 AND R.IsObsolete=1
		AND A.OrgId=@rOrgId AND R.BatchId=@rBatchId
		AND A.AcademicId=@rAcademicId
	   ORDER BY R.ReceiptNumber DESC
	   
		SELECT ISNULL(@lcancellist,'') AS cancellist
END

--
--    
--    
--    
--    
--    
--    
GO
PRINT N'Creating [sHrm].[pIDNoGenerationGet]...';


GO
CREATE PROCEDURE [sHrm].[pIDNoGenerationGet]
	 
	  
	 
	 @rOrgId smallint 
	  

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	SELECT 
			EM.Id AS EmployeeId,
			EM.Code, 
			EM.FirstName,
			EM.LastName,
			EM.FirstName+' '+ EM.MiddleName+' ' +EM.LastName AS Name
  FROM 
			sHrm.tEmployeeMaster  EM 
		
  WHERE 
			--(SO.ClassId=@rClassId OR @rClassId=0)
			--AND (SO.DivisionId=@rDivisionId OR @rDivisionId=0)
			--AND (SO.RecordStatusId=@rRecordStatusId OR @rRecordStatusId=0)
			--AND SO.BatchId=@rBatchId
			  EM.OrgId=@rOrgId 
			   
END
GO
PRINT N'Creating [sHrm].[pIDNoGenerationUpdate]...';


GO
CREATE PROCEDURE [sHrm].[pIDNoGenerationUpdate]
	 
	@rEmployeeId bigint,
	@rIDNo nvarchar(20),
	@rCreatedUserId bigint,
	@rOrgId smallint 
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

		   DECLARE @lCode nvarchar(20)
		   SELECT @lCode=Code FROM sHrm.tEmployeeMaster WHERE Code=@rIDNo AND OrgId=@rOrgId AND Id<>@rEmployeeId
		   IF @lCode IS NOT NULL
		   BEGIN
					SELECT -103 AS Result,@lCode AS Code
					RETURN
		   END 
		   
		 --  IF EXISTS(SELECT @lCode=Code FROM sStudent.tStudentMaster WHERE Code=@rIDNo AND OrgId=@rOrgId AND Id<>@rStudentId)
			--	BEGIN
			--	SELECT -103 AS RESULT
			--	RETURN
			--END 
	BEGIN TRY
	 BEGIN TRANSACTION	
	 BEGIN
	    UPDATE  sHrm.tEmployeeMaster
	    SET
		    Code=@rIDNo, 	  
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate() 
	      WHERE Id = @rEmployeeId 	   
	 END  
		SELECT 1 AS RESULT
		COMMIT TRANSACTION
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS RESULT
	END CATCH	
		
END
GO
PRINT N'Creating [sSetup].[pScreenMandatoryFeildAdd]...';


GO
CREATE PROCEDURE [sSetup].[pScreenMandatoryFeildAdd]
	 
	 @rOrgGroupId  int,
     @rAssignStringXml [nvarchar](max),
     @rMandatoryFeildFunctionalityId  smallint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rAssignStringXml
BEGIN
BEGIN TRY
	
	 BEGIN TRANSACTION	
	 
	 DELETE M FROM sSetup.tScreenMandatoryFeild M
	 INNER JOIN sSetup.tMandatoryFeild F ON M.MandatoryFeildId=F.Id WHERE  OrgGroupId=@rOrgGroupId AND F.MandatoryFeildFunctionalityId=@rMandatoryFeildFunctionalityId
	
		INSERT INTO sSetup.tScreenMandatoryFeild
		(
			 MandatoryFeildId,
			 OrgGroupId
		)
		SELECT
		    MandatoryFeildId,
		    @rOrgGroupId
			
		  
		FROM OPENXML (@loDoc, '/Table/ScreenMandatoryFeild', 1)
		WITH ( 
			
				MandatoryFeildId int
			  ) 
	
	SELECT 1 AS Result
	
	COMMIT TRANSACTION
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
END
GO
PRINT N'Creating [sSetup].[pScreenMandatoryFeildGET]...';


GO
CREATE PROCEDURE [sSetup].[pScreenMandatoryFeildGET]
	 
	 @rOrgGroupId  int,
	 @rMandatoryFeildFunctionalityId smallint
	 
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

		SELECT 
		FieldName,
		Id AS MandatoryFeildId,
	   (CASE WHEN MandatoryFeildId Is Null THEN 'False' ELSE 'True' END) AS Selected 
		FROM
		sSetup.tMandatoryFeild  M 
		LEFT JOIN  sSetup.tScreenMandatoryFeild S ON M.Id=S.MandatoryFeildId
		AND S.OrgGroupId=@rOrgGroupId
		 WHERE M.MandatoryFeildFunctionalityId=@rMandatoryFeildFunctionalityId
GO
PRINT N'Creating [sStudent].[pRptincopleteFieldGet]...';


GO

CREATE PROCEDURE [sStudent].[pRptincopleteFieldGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rOrgId smallint,
	 @rBatchId int,
	 @rStrCode nvarchar(max),
	 @rClassId int,
	 @rDivisionId int,
	 @rStudentId bigint,
	 @rFromRollNo int,
	 @rToRollNo int,
	 @rStatusId int,
	 @rDateOfBirth int,
	 @rDepartmentId int,
     @rOrgGroupId int,
     @rStrMandatoryFeildId nvarchar(max)='',
     @rStrStudentId nvarchar(max)='',
	 @rHouseGroupId 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.Name,		
		SA.ClassName,
		SA.DivisionName,
		SA.DivisionOrder,
		--M.FieldName,
		--M.Id AS MandatoryFeildId,
		SA.MiddleName AS FatherName,
		ISNULL(SA.Religion,'') AS Religion,
		ISNULL(SA.BloodGroup,'') AS BloodGroup,
		ISNULL(SA.BirthPlace,'') AS BirthPlace,	
		ISNULL(SA.BirthDistrict,'') AS BirthDistrict,
		SA.BirthState,
		SA.BirthCountry,
		ISNULL(SA.BirthTaluka,'') AS BirthTaluka,
		ISNULL(SA.FamilyCast,'') AS FamilyCast,
		ISNULL(SA.FamilySubCast,'') AS FamilySubCast,
		ISNULL(SA.Nationality,'') AS Nationality,
		ISNULL(CT.Title,'') AS CasteCategory,
		ISNULL(HM.Title,'-') AS House,
		ISNULL(SF.MotherName,'') AS MotherName,
		SO.ReferenceRemark,
		ISNULL(SA.ParentEmail,'') AS ParentEmail,
		ISNULL(SA.ParentContactNo,'') As ParentContactNo,
		ISNULL(SA.StudentEmail,'') AS StudentEmail,
		ISNULL(SA.StudentContactNo,'') AS StudentContactNo,
		ISNULL(SA.PresentStreetone,'') AS LocalAddress1,
		ISNULL(SA.PresentStreetTwo,'') AS LocalAddress2,
		ISNULL(SA.PresentStreetThree,'') AS LocalAddress3,
		ISNULL(SA.PresentCity,'') AS PresentCity,
		ISNULL(SA.PresentState,'') AS PresentState,
		ISNULL(SA.PresentCountry,'') AS PresentCountry,
		ISNULL(SA.PresentZipCode,'') AS PresentZipCode,
		ISNULL(SA.PresentContactNo,'') AS PresentContactNo,
		ISNULL(SO.MotherTongue,'') As MotherTongue,
		ISNUll(MF.IsDisplayFatherName,0)  AS IsDisplayFatherName,
		ISNUll(MF.IsDisplayReligion,0)  AS IsDisplayReligion,
		ISNUll(MF.IsDisplayBloodGroup,0)  AS IsDisplayBloodGroup,
		ISNUll(MF.IsDisplayBirthPlace,0)  AS IsDisplayBirthPlace,
		ISNUll(MF.IsDisplayBirthTaluka,0)  AS IsDisplayBirthTaluka,
		ISNUll(MF.IsDisplayBirthDistrict,0)  AS IsDisplayBirthDistrict,
		ISNUll(MF.IsDisplayBirthState,0)  AS IsDisplayBirthState,
		ISNUll(MF.IsDisplayBirthCountry,0)  AS IsDisplayBirthCountry,
		ISNUll(MF.IsDisplayFamilyCaste,0)  AS IsDisplayFamilyCaste,
		ISNUll(MF.IsDisplayFamilySubCaste,0)  AS IsDisplayFamilySubCaste,
		ISNUll(MF.IsDisplayCasteCategory,0)  AS IsDisplayCasteCategory,
		ISNUll(MF.IsDisplayHouse,0)  AS IsDisplayHouse,
		ISNUll(MF.IsDisplayMotherTongue,0)  AS IsDisplayMotherTongue,
		ISNUll(MF.IsDisplayNationality,0)  AS IsDisplayNationality,
		ISNUll(MF.IsDisplayReferenceRemark,0)  AS IsDisplayReferenceRemark,
		ISNUll(MF.IsDisplayParentContactNo,0)  AS IsDisplayParentContactNo,
		ISNUll(MF.IsDisplayParentEmail,0)  AS IsDisplayParentEmail,
		ISNUll(MF.IsDisplayStudentContactNo,0)  AS IsDisplayStudentContactNo,
		ISNUll(MF.IsDisplayStudentEmail,0)  AS IsDisplayStudentEmail,
		ISNUll(MF.IsDisplayLocalAddress1,0)  AS IsDisplayLocalAddress1,
		ISNUll(MF.IsDisplayLocalAddress2,0)  AS IsDisplayLocalAddress2,
		ISNUll(MF.IsDisplayLocalAddress3,0)  AS IsDisplayLocalAddress3,
		ISNUll(MF.IsDisplayLocalAddressCity,0)  AS IsDisplayLocalAddressCity,
		ISNUll(MF.IsDisplayLocalAddressState,0)  AS IsDisplayLocalAddressState,
		ISNUll(MF.IsDisplayLocalAddressCountry,0)  AS IsDisplayLocalAddressCountry,
		ISNUll(MF.IsDisplayLocalAddressPINCode,0)  AS IsDisplayLocalAddressPINCode,
		ISNUll(MF.IsDisplayLocalAddressContactNo,0)  AS IsDisplayLocalAddressContactNo

	FROM 
		sStudent.vStudentAllDetail SA
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=SA.OrgId
		LEFT JOIN sCommon.tCastCategoryMaster CT ON CT.Id = SA.CastCategoryId
		LEFT JOIN sActivity.tHouseMaster HM ON HM.ID = SA.HouseId
		LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SA.StudentId 
		LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId = SA.StudentId 
		INNER JOIN  [sStudent].[fMandatoryFieldGet](@rOrgGroupId,@rStrMandatoryFeildId) MF ON  MF.OrgGroupId=OM.OrgGroupId
		 
	WHERE 
		SA.OrgId=@rOrgId
		AND	SA.BatchId = @rBatchId
		AND (ISNULL(SA.Code,'') IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rStrCode,',')) OR @rStrCode='') 
		AND (ISNULL(SA.StudentId,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rStrStudentId,',')) OR @rStrStudentId=0) 
		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))
		AND ((HM.HouseGroupId=@rHouseGroupId) OR (@rHouseGroupId=0))

END
GO
PRINT N'Creating [sStudent].[pStudentDocumentAdd]...';


GO

CREATE PROCEDURE [sStudent].[pStudentDocumentAdd]
	 
        @rStudentId bigint,
		@rDocumenetXml [nvarchar](max)
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rDocumenetXml
BEGIN 	
 
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	 
		DELETE FROM sStudent.tStudentDocument WHERE StudentId=@rStudentId
	
		INSERT INTO sStudent.tStudentDocument
		(
			StudentId, 
			SubmitDocumentMasterId,
			DocumentName
		)
		SELECT
		   @rStudentId,
		   SubmitDocumentMasterId,
		   DocumentName
		FROM OPENXML (@loDoc, '/Table/SubmitDocument', 1)
		WITH ( 
				SubmitDocumentMasterId int,
				DocumentName nvarchar(150)
			  ) 
	
	SELECT 1 AS Result
	
	COMMIT TRANSACTION
	
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
		
END
GO
PRINT N'Creating [sStudent].[pStudentDocumentget]...';


GO

CREATE PROCEDURE [sStudent].[pStudentDocumentget]
	 
	 @rOrgId int,
	 @rClassId int,
	 @rDivisionId int=0,
	 @rCode nvarchar(20),
	 @rStatusId smallint,
	 @rBatchId int,
	 @rDepartmentId int,
	 @rSUId nvarchar(20)
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
		SET @rCode= sCommon.fSearchStringGet(@rCode)
		SET @rSUId= sCommon.fSearchStringGet(@rSUId)
    DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX)
    select @cols = STUFF((SELECT ',' + QUOTENAME(DocumentName) 
                    from  sCommon.tSubmitDocumentMaster WHERE  OrgId=@rOrgId  AND SubmitDocumentFunctionalityId=1
                    Order by Id 
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')
      If(ISNULL(@Cols,'')='')
		 BEGIN
		    SELECT -101 AS Result
		 RETURN
		 END
  set @query = 'SELECT Name,Code,SUID,Class,RollNo,' + @cols + ' from 
             (
               SELECT
               SA.Name,SA.Code,SA.SUID,SA.RollNo,(SA.ClassName+''-''+SA.DivisionName) AS Class,S.DocumentName,CASE WHEN D.SubmitDocumentMasterId IS NULL  THEN ''No'' ELSE ''Yes'' END AS DocumentId
               FROM  sStudent.vStudentAcademic SA 
               LEFT JOIN sStudent.tStudentDocument D ON SA.StudentId=D.StudentId 
               LEFT JOIN sCommon.tSubmitDocumentMaster  S ON S.Id=D.SubmitDocumentMasterId AND SubmitDocumentFunctionalityId=1
		        WHERE 
	          ((SA.OrgId=' + CAST(@rOrgId AS NVARCHAR(50))+'))
	          AND ((SA.BatchId=' + CAST(@rBatchId AS NVARCHAR(50))+'))
	          AND ((SA.DivisionId=' + CAST(@rDivisionId AS NVARCHAR(30))+') OR ('+CAST(@rDivisionId AS NVARCHAR(50))+'= 0))
	          AND ((SA.BatchId=' + CAST(@rBatchId AS NVARCHAR(30))+') OR ('+CAST(@rBatchId AS NVARCHAR(50))+'= 0))
	          AND ((SA.ClassId=' + CAST(@rClassId AS NVARCHAR(30))+') OR ('+CAST(@rClassId AS NVARCHAR(50))+'= 0))
	          AND ((SA.BatchId=' + CAST(@rBatchId AS NVARCHAR(30))+') OR ('+CAST(@rBatchId AS NVARCHAR(50))+'= 0))
	          AND ((SA.DepartmentId=' + CAST(@rDepartmentId AS NVARCHAR(30))+') OR ('+CAST(@rDepartmentId AS NVARCHAR(50))+'= 0))
	          AND ((SA.Code  like  '''+ convert(varchar,@rCode )+''') OR ('''+convert(varchar,@rCode )+'''= ''''))
	          AND ((SA.Suid  like  '''+ ISNULL(@rSUId,'') +''') OR ('''+@rSUId +'''= ''''))
	         AND ((SA.StatusId=' + CAST(@rStatusId AS NVARCHAR(30))+') OR ('+CAST(@rStatusId AS NVARCHAR(50))+'= 0))
              ) x
            pivot 
            (
                MIN(DocumentId)
                for DocumentName in (' + isnull(@cols,0) + ')  
            ) p order by RollNo'
            
  print @query
 execute(@query)
END
GO
PRINT N'Creating [sTimetable].[pAnnualSubjectGet]...';


GO

CREATE  PROCEDURE [sTimetable].[pAnnualSubjectGet]
	 
	 
	@rDivisionId int=0,
	@rOrgId int=0,
	@rClassId int ,
	@rBatchId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON			 

BEGIN 	 
		 Select 
			Sm.Id,Sm.Title,
			
			AT.NoOfLecture 
		 from 
			sSetup.tSubjectMaster Sm  
			INNER JOIN sSetup.tClassSubject SP On SP.SubjectId=SM.Id
			LEFT JOIN sTimetable.tAnnualSubjectWorkLoad AT ON AT.SubjectId=Sm.Id AND AT.DivisionId=@rDivisionId AND AT.BatchId=@rBatchId
			Where Sm.OrgId=@rOrgId
			AND ((SP.ClassId=@rClassId) OR (@rClassId=0))
			AND  Sm.IsObsolete=0
			 
		 
END
GO
PRINT N'Creating [sTimetable].[pAnnualSubjectWorkLoadAdd]...';


GO

CREATE PROCEDURE [sTimetable].[pAnnualSubjectWorkLoadAdd]
	 
	 
	@rDivisionId int=0,
	@rBatchId int=0,
	@rDetail nvarchar(max),
	@rCreatedUserId bigint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON			 
DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rDetail	
BEGIN 	 
		
		 DELETE  FROM sTimetable.tAnnualSubjectWorkLoad
		  
		  WHERE DivisionId=@rDivisionId AND BatchId =@rBatchId
		   
		 Insert Into sTimetable.tAnnualSubjectWorkLoad
		 (
			BatchId,
			DivisionId,
			SubjectId,
			NoOfLecture,
			CreatedUserId,
			CreatedDateTime
		 )
		 Select
			@rBatchId,@rDivisionId,SubjectId,NoOfLecture,@rCreatedUserId,sCommon.fGetDate()
		 	FROM OPENXML (@loDoc, '/Table/AnnualSubject', 1)
		 	WITH ( 
		 		SubjectId int,
		 		NoOfLecture tinyint
		 	)
			Select 1 As Result
		  
		 
		 
END
GO
PRINT N'Creating [sTimetable].[pRptSubejctTimeTableGet]...';


GO
 
 

 
CREATE PROCEDURE [sTimetable].[pRptSubejctTimeTableGet]

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

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  (TT.SubjectId = @rSubjectId OR @rSubjectId=0)	
	  AND (TT.EmployeeId=@rEmployeeId OR @rEmployeeId=0)
	  AND TT.TimeTableSchemaId=@rTimeTableSchemaId
	 
	  )
	  A  ORDER BY A.DivisionOrderIndex
	 
END
GO
PRINT N'Creating [sTimetable].[pSubjectTimeTableGet]...';


GO

CREATE PROCEDURE [sTimetable].[pSubjectTimeTableGet]
	
	 @rSubjectId int,
	 @rTimeTableSchemaId int ,
	 @rDivisionId int

	 
	 
	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(Title) 
                    from sCommon.tDayMaster
                    group by Title,Id 
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')
        
     
 
set @query = 'SELECT LectureNumber , ' + @cols + ' from 
             (
            Select LectureNumber, ISNULL(EM.ShortName + '+ ''' - ''' +' + SM.Title + '+ ''' - ''' +' + CL.TItle +'' ''+ MV.Title '+','''') AS EmployeeName , DM.Title AS DayNames 
            from
            sTimetable.tTimeTable T 
            INNER JOIN sCommon.tDayMaster DM ON DM.Id = T.DayId
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id=T.EmployeeId
	        INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=T.SubjectId
	        INNER JOIN sSetup.tDivisionMaster MV ON MV.Id=T.DivisionId
	        INNER JOIN sSetup.tClassMaster CL ON CL.Id=MV.ClassId
	        
	         WHERE    
	        ((T.SubjectId=' + CAST(@rSubjectId AS NVARCHAR(30))+') OR ('+CAST(@rSubjectId AS NVARCHAR(30))+'= 0) )
	           AND ((T.TimeTableSchemaId=' + CAST(@rTimeTableSchemaId AS NVARCHAR(30))+') OR ('+CAST(@rTimeTableSchemaId AS NVARCHAR(30))+'= 0))
	       
            ) x
            pivot 
            (
                max(EmployeeName)
                for DayNames in (' + @cols + ')
            ) p '
            
print @query
 execute(@query)
     
        
	
		
END
GO
  
 
  
GO
INSERT INTO [sSystem].[tVersionUpdate] ([VersionNumber],[VersionId],[Status],[UpdateScript],[StartDateTime],[EndDateTime],[OrgGroupId])
VALUES('17.10.03',171003,'END','Script',sCommon.fGetDate(),sCommon.fGetDate(),0)
GO