

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


Drop FUNCTION [sFee].[fPendingFeeNamesGet]
GO
Drop TYPE [dbo].[TempPendingFee]
GO
CREATE TYPE [dbo].[TempPendingFee] AS TABLE (
    [AcademicId]         BIGINT          NULL,
    [RollNo]             INT             NULL,
    [Name]               NVARCHAR (200)  NULL,
    [Code]               NVARCHAR (20)   NULL,
    [ClassId]            INT             NULL,
    [DivisionId]         INT             NULL,
    [ClassName]          NVARCHAR (100)  NULL,
    [DivisionName]       NVARCHAR (100)  NULL,
    [ClassDivision]      NVARCHAR (200)  NULL,
    [FeeSetupId]         INT             NULL,
    [IsVariable]         INT             NULL,
    [Amount]             DECIMAL (12, 2) NULL,
    [StartDate]          DATE            NULL,
    [EndDate]            DATE            NULL,
    [FAAmount]           DECIMAL (12, 2) NULL,
    [DiscountAmount]     DECIMAL (12, 2) NULL,
    [AdditionalAmount]   DECIMAL (12, 2) NULL,
    [PaidAmount]         DECIMAL (12, 2) NULL,
    [PendingAmount]      DECIMAL (12, 2) NULL,
    [Remark]             NVARCHAR (200)  NULL,
    [ReceiptBookId]      INT             NULL,
    [FeeName]            NVARCHAR (100)  NULL,
    [FeeCode]            NVARCHAR (100)  NULL,
    [OrgId]              INT             NULL,
    [OrgName]            NVARCHAR (200)  NULL,
    [OrgOrderIndex]      INT             NULL,
    [ReceiptBookTitle]   NVARCHAR (200)  NULL,
    [ReceiptOrderIndex]  INT             NULL,
    [BatchId]            INT             NULL,
    [BatchName]          NVARCHAR (100)  NULL,
    [Pickup]             NVARCHAR (100)  NULL,
    [DRoppoint]          NVARCHAR (100)  NULL,
    [PresentContactNo]   NVARCHAR (20)   NULL,
    [SUID]               NVARCHAR (50)   NULL,
    [ClassOrderIndex]    INT             NULL,
    [DivisionOrderIndex] INT             NULL,
    [FeeOrderIndex]      INT             NULL,
    [FatherContactNo]    NVARCHAR (50)   NULL,
    [MotherContactNo]    NVARCHAR (50)   NULL);


GO
PRINT N'Altering Table [sAcademic].[tClasswork]...';


GO
ALTER TABLE [sAcademic].[tClasswork] ALTER COLUMN [Homework] NVARCHAR (MAX) NULL;


GO
PRINT N'Altering Table [sAcademic].[tTopicMaster]...';


GO
ALTER TABLE [sAcademic].[tTopicMaster]
    ADD [IsObsolete] BIT NULL;


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


GO
BEGIN TRANSACTION;

SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;

SET XACT_ABORT ON;

CREATE TABLE [sBiometric].[tmp_ms_xx_tCloudTransactionData] (
    [AutoId]          BIGINT        IDENTITY (1, 1) NOT NULL,
    [SourceId]        BIGINT        NOT NULL,
    [In_Out_Time]     DATETIME      NOT NULL,
    [ShiftCode]       INT           NOT NULL,
    [Attn_Dt]         DATE          NOT NULL,
    [Mode]            NVARCHAR (10) NOT NULL,
    [CreatedDateTime] DATETIME      NOT NULL,
    [DeviceIP]        NVARCHAR (20) NOT NULL,
    [EntryMode]       TINYINT       NOT NULL,
    [PunchId]         NVARCHAR (50) NULL,
    [TransactionId]   BIGINT        NOT NULL,
    [SourceTypeId]    SMALLINT      NULL,
    [IsProcessed]     BIT           NULL
);

IF EXISTS (SELECT TOP 1 1 
           FROM   [sBiometric].[tCloudTransactionData])
    BEGIN
        INSERT INTO [sBiometric].[tmp_ms_xx_tCloudTransactionData] ([SourceId], [In_Out_Time], [ShiftCode], [Attn_Dt], [Mode], [CreatedDateTime], [DeviceIP], [EntryMode], [PunchId], [TransactionId], [SourceTypeId], [IsProcessed])
        SELECT [SourceId],
               [In_Out_Time],
               [ShiftCode],
               [Attn_Dt],
               [Mode],
               [CreatedDateTime],
               [DeviceIP],
               [EntryMode],
               [PunchId],
               [TransactionId],
               [SourceTypeId],
               [IsProcessed]
        FROM   [sBiometric].[tCloudTransactionData];
    END

DROP TABLE [sBiometric].[tCloudTransactionData];

EXECUTE sp_rename N'[sBiometric].[tmp_ms_xx_tCloudTransactionData]', N'tCloudTransactionData';

COMMIT TRANSACTION;

SET TRANSACTION ISOLATION LEVEL READ COMMITTED;


GO
PRINT N'Altering Table [sCommunication].[tRegisteredUsers]...';


GO
ALTER TABLE [sCommunication].[tRegisteredUsers]
    ADD [DeviceDetail] NVARCHAR (MAX) NULL;


GO
PRINT N'Creating Table [sActivity].[tEmployeeHealthTrack]...';


GO
CREATE TABLE [sActivity].[tEmployeeHealthTrack] (
    [Id]                  BIGINT         NOT NULL,
    [EmployeeId]          BIGINT         NOT NULL,
    [HealthCheckupTypeId] TINYINT        NOT NULL,
    [CheckupFromDate]     DATE           NOT NULL,
    [CheckupToDate]       DATE           NOT NULL,
    [ChiefComplain]       NVARCHAR (100) NOT NULL,
    [Diagnosis]           NVARCHAR (100) NOT NULL,
    [ActionTaken]         NVARCHAR (100) NOT NULL,
    [Remark]              NVARCHAR (200) NULL,
    [ExaminedBy]          NVARCHAR (100) NULL,
    [CreatedUserId]       BIGINT         NOT NULL,
    [CreatedDateTime]     DATETIME       NOT NULL,
    [UpdatedUserId]       BIGINT         NULL,
    [UpdatedDateTime]     DATETIME       NULL,
    [InTime]              TIME (7)       NULL,
    [OutTime]             TIME (7)       NULL,
    CONSTRAINT [PK_tEmployeeHealthTrack] PRIMARY KEY CLUSTERED ([Id] ASC)
);


GO
PRINT N'Creating Table [sActivity].[tHealthCheckupEmployee]...';


GO
CREATE TABLE [sActivity].[tHealthCheckupEmployee] (
    [HealthCheckupId]  INT            NOT NULL,
    [EmployeeId]       BIGINT         NOT NULL,
    [HeightInCm]       DECIMAL (6, 2) NULL,
    [WeightInKg]       DECIMAL (6, 2) NULL,
    [Dental]           NVARCHAR (150) NULL,
    [Nails]            NVARCHAR (150) NULL,
    [Hair]             NVARCHAR (150) NULL,
    [Skin]             NVARCHAR (150) NULL,
    [Ear]              NVARCHAR (150) NULL,
    [Nose]             NVARCHAR (150) NULL,
    [Throat]           NVARCHAR (150) NULL,
    [Respiratory]      NVARCHAR (150) NULL,
    [Cardiovascular]   NVARCHAR (150) NULL,
    [Nervous]          NVARCHAR (150) NULL,
    [Eye]              NVARCHAR (150) NULL,
    [Other]            NVARCHAR (150) NULL,
    [ImportantFinding] NVARCHAR (150) NULL,
    [Remarks]          NVARCHAR (150) NULL,
    [FollowupDetail]   NVARCHAR (150) NULL,
    [StatusId]         SMALLINT       NOT NULL,
    [BloodGroupId]     TINYINT        NULL
);


GO
PRINT N'Creating Table [sAssessment].[tTempAllExamWithAllTerm]...';


GO
CREATE TABLE [sAssessment].[tTempAllExamWithAllTerm] (
    [AcademicIdText]                 NVARCHAR (20)   NULL,
    [ExamIdText]                     NVARCHAR (20)   NULL,
    [CoScholasticScopeIdText]        NVARCHAR (20)   NULL,
    [IsDisplayMonthlyAttendanceText] NVARCHAR (20)   NULL,
    [ClassIdText]                    NVARCHAR (50)   NULL,
    [AcademicId]                     BIGINT          NULL,
    [ExamName]                       NVARCHAR (150)  NULL,
    [StudCode]                       NVARCHAR (20)   NULL,
    [StudentName]                    NVARCHAR (150)  NULL,
    [RollNo]                         INT             NULL,
    [ResultStatus]                   NVARCHAR (20)   NULL,
    [ClassName]                      NVARCHAR (50)   NULL,
    [Division]                       NVARCHAR (50)   NULL,
    [TotalMark]                      DECIMAL (8, 2)  NULL,
    [TotalObtain]                    DECIMAL (8, 2)  NULL,
    [Percentage]                     DECIMAL (8, 2)  NULL,
    [RankNumber]                     INT             NULL,
    [ResultGrade]                    NVARCHAR (50)   NULL,
    [MaximumMark1]                   DECIMAL (8, 2)  NULL,
    [SubjectGrade1]                  NVARCHAR (50)   NULL,
    [Obtain1]                        DECIMAL (8, 2)  NULL,
    [ExamMaximum1]                   DECIMAL (8, 2)  NULL,
    [IsPresent1]                     BIT             NULL,
    [MaximumMark2]                   DECIMAL (8, 2)  NULL,
    [SubjectGrade2]                  NVARCHAR (50)   NULL,
    [Obtain2]                        DECIMAL (8, 2)  NULL,
    [ExamMaximum2]                   DECIMAL (8, 2)  NULL,
    [IsPresent2]                     BIT             NULL,
    [MaximumMark3]                   DECIMAL (8, 2)  NULL,
    [SubjectGrade3]                  NVARCHAR (50)   NULL,
    [Obtain3]                        DECIMAL (8, 2)  NULL,
    [ExamMaximum3]                   DECIMAL (8, 2)  NULL,
    [IsPresent3]                     BIT             NULL,
    [MaximumMark4]                   DECIMAL (8, 2)  NULL,
    [SubjectGrade4]                  NVARCHAR (50)   NULL,
    [Obtain4]                        DECIMAL (8, 2)  NULL,
    [ExamMaximum4]                   DECIMAL (8, 2)  NULL,
    [IsPresent4]                     BIT             NULL,
    [MaximumMark5]                   DECIMAL (8, 2)  NULL,
    [SubjectGrade5]                  NVARCHAR (50)   NULL,
    [Obtain5]                        DECIMAL (8, 2)  NULL,
    [ExamMaximum5]                   DECIMAL (8, 2)  NULL,
    [IsPresent5]                     BIT             NULL,
    [MaximumMark6]                   DECIMAL (8, 2)  NULL,
    [SubjectGrade6]                  NVARCHAR (50)   NULL,
    [Obtain6]                        DECIMAL (8, 2)  NULL,
    [ExamMaximum6]                   DECIMAL (8, 2)  NULL,
    [IsPresent6]                     BIT             NULL,
    [MaximumMark7]                   DECIMAL (8, 2)  NULL,
    [SubjectGrade7]                  NVARCHAR (50)   NULL,
    [Obtain7]                        DECIMAL (8, 2)  NULL,
    [ExamMaximum7]                   DECIMAL (8, 2)  NULL,
    [IsPresent7]                     BIT             NULL,
    [MaximumMark8]                   DECIMAL (8, 2)  NULL,
    [SubjectGrade8]                  NVARCHAR (50)   NULL,
    [Obtain8]                        DECIMAL (8, 2)  NULL,
    [ExamMaximum8]                   DECIMAL (8, 2)  NULL,
    [IsPresent8]                     BIT             NULL,
    [MaximumMark9]                   DECIMAL (8, 2)  NULL,
    [SubjectGrade9]                  NVARCHAR (50)   NULL,
    [Obtain9]                        DECIMAL (8, 2)  NULL,
    [ExamMaximum9]                   DECIMAL (8, 2)  NULL,
    [IsPresent9]                     BIT             NULL,
    [MaximumMark10]                  DECIMAL (8, 2)  NULL,
    [SubjectGrade10]                 NVARCHAR (50)   NULL,
    [Obtain10]                       DECIMAL (8, 2)  NULL,
    [ExamMaximum10]                  DECIMAL (8, 2)  NULL,
    [IsPresent10]                    BIT             NULL,
    [MaximumMark11]                  DECIMAL (8, 2)  NULL,
    [SubjectGrade11]                 NVARCHAR (50)   NULL,
    [Obtain11]                       DECIMAL (8, 2)  NULL,
    [ExamMaximum11]                  DECIMAL (8, 2)  NULL,
    [IsPresent11]                    BIT             NULL,
    [MaximumMark12]                  DECIMAL (8, 2)  NULL,
    [SubjectGrade12]                 NVARCHAR (50)   NULL,
    [Obtain12]                       DECIMAL (8, 2)  NULL,
    [ExamMaximum12]                  DECIMAL (8, 2)  NULL,
    [IsPresent12]                    BIT             NULL,
    [MaximumMark13]                  DECIMAL (8, 2)  NULL,
    [SubjectGrade13]                 NVARCHAR (50)   NULL,
    [Obtain13]                       DECIMAL (8, 2)  NULL,
    [ExamMaximum13]                  DECIMAL (8, 2)  NULL,
    [IsPresent13]                    BIT             NULL,
    [SubjectGradeTerm1]              NVARCHAR (50)   NULL,
    [SubjectGradeTerm2]              NVARCHAR (50)   NULL,
    [SubjectGradeTerm3]              NVARCHAR (50)   NULL,
    [SubjectGradeTerm4]              NVARCHAR (50)   NULL,
    [IsMarksInDecimal]               BIT             NULL,
    [column_visible]                 BIT             NULL,
    [Percentile]                     DECIMAL (5, 2)  NULL,
    [ResultDetailId]                 BIGINT          NULL,
    [ResultId]                       BIGINT          NULL,
    [Remark1]                        NVARCHAR (1000) NULL,
    [Remark2]                        NVARCHAR (1000) NULL,
    [Remark3]                        NVARCHAR (1000) NULL,
    [DisplayTitle]                   NVARCHAR (150)  NULL,
    [IsRankNo]                       BIT             NULL,
    [IsGrade]                        BIT             NULL,
    [IsPercentile]                   BIT             NULL,
    [IsPercentage]                   BIT             NULL,
    [IsSubjectPercentile]            BIT             NULL,
    [IsProcessResult]                BIT             NULL,
    [IsNegativeMarks]                BIT             NULL,
    [IsIncludeCoScholastic]          BIT             NULL,
    [IsOnPrePrinted]                 BIT             NULL,
    [IsDisplayPhoto]                 BIT             NULL,
    [IsDisplayBirthDate]             BIT             NULL,
    [IsLockForEdit]                  BIT             NULL,
    [IsDisplaySchoolName]            BIT             NULL,
    [IsDisplayAttendance]            BIT             NULL,
    [IsDisplayHeightWeight]          BIT             NULL,
    [IsResultStatus]                 BIT             NULL,
    [FooterAdjustmentText]           NVARCHAR (MAX)  NULL,
    [DetailAdjustmentText]           NVARCHAR (MAX)  NULL,
    [FooterAdjustment]               SMALLINT        NULL,
    [DetailAdjustment]               SMALLINT        NULL,
    [ResultRemark]                   NVARCHAR (200)  NULL,
    [DateOfBirth]                    DATE            NULL,
    [HeightTerm1]                    DECIMAL (5, 2)  NULL,
    [WeightTerm1]                    DECIMAL (5, 2)  NULL,
    [HeightTerm2]                    DECIMAL (5, 2)  NULL,
    [WeightTerm2]                    DECIMAL (5, 2)  NULL,
    [HeightAnnual]                   DECIMAL (5, 2)  NULL,
    [WeightAnnual]                   DECIMAL (5, 2)  NULL,
    [PresentDaysTerm1]               SMALLINT        NULL,
    [PresentDaysTerm2]               SMALLINT        NULL,
    [PresentDaysAnnual]              SMALLINT        NULL,
    [TotalDaysTerm1]                 SMALLINT        NULL,
    [TotalDaysTerm2]                 SMALLINT        NULL,
    [TotalDaysAnnual]                SMALLINT        NULL,
    [TotalMarkTerm1]                 DECIMAL (8, 2)  NULL,
    [TotalObtainTerm1]               DECIMAL (8, 2)  NULL,
    [PercentageTerm1]                DECIMAL (8, 2)  NULL,
    [RankNumberTerm1]                INT             NULL,
    [ResultGradeTerm1]               NVARCHAR (50)   NULL,
    [PercentileTerm1]                DECIMAL (8, 2)  NULL,
    [ResultStatusTerm1]              NVARCHAR (20)   NULL,
    [TotalMarkTerm2]                 DECIMAL (8, 2)  NULL,
    [TotalObtainTerm2]               DECIMAL (8, 2)  NULL,
    [PercentageTerm2]                DECIMAL (8, 2)  NULL,
    [RankNumberTerm2]                INT             NULL,
    [ResultGradeTerm2]               NVARCHAR (50)   NULL,
    [PercentileTerm2]                DECIMAL (8, 2)  NULL,
    [ResultStatusTerm2]              NVARCHAR (20)   NULL,
    [TotalMarkTerm3]                 DECIMAL (8, 2)  NULL,
    [TotalObtainTerm3]               DECIMAL (8, 2)  NULL,
    [PercentageTerm3]                DECIMAL (8, 2)  NULL,
    [RankNumberTerm3]                INT             NULL,
    [ResultGradeTerm3]               NVARCHAR (50)   NULL,
    [PercentileTerm3]                DECIMAL (8, 2)  NULL,
    [ResultStatusTerm3]              NVARCHAR (20)   NULL,
    [TotalMarkTerm4]                 DECIMAL (8, 2)  NULL,
    [TotalObtainTerm4]               DECIMAL (8, 2)  NULL,
    [PercentageTerm4]                DECIMAL (8, 2)  NULL,
    [RankNumberTerm4]                INT             NULL,
    [ResultGradeTerm4]               NVARCHAR (50)   NULL,
    [PercentileTerm4]                DECIMAL (8, 2)  NULL,
    [ResultStatusTerm4]              NVARCHAR (20)   NULL,
    [TermScopeId]                    TINYINT         NULL,
    [StudentPhoto]                   VARBINARY (MAX) NULL,
    [GradeString]                    NVARCHAR (1000) NULL,
    [IsDisplayGradeString]           BIT             NULL,
    [IsDisplayInMarksheet]           BIT             NULL,
    [IsShowSubjectGrade]             BIT             NULL,
    [IsIncludeInTotal]               BIT             NULL,
    [ClassSubjectID]                 INT             NULL,
    [SubjectId]                      INT             NULL,
    [SubjectOrderIndex]              SMALLINT        NULL,
    [SubjectGrade]                   NVARCHAR (50)   NULL,
    [SubjectName]                    NVARCHAR (150)  NULL,
    [SubjectCode]                    NVARCHAR (50)   NULL,
    [SubjectMinimum]                 DECIMAL (8, 2)  NULL,
    [SubjectMaximum]                 DECIMAL (8, 2)  NULL,
    [SubjectObtain]                  DECIMAL (8, 2)  NULL,
    [Exam1Name]                      NVARCHAR (150)  NULL,
    [TotalMarks1]                    DECIMAL (8, 2)  NULL,
    [TotalObtain1]                   DECIMAL (8, 2)  NULL,
    [Percentage1]                    DECIMAL (8, 2)  NULL,
    [RankNumber1]                    INT             NULL,
    [ResultGrade1]                   NVARCHAR (50)   NULL,
    [Percentile1]                    DECIMAL (8, 2)  NULL,
    [ResultStatus1]                  NVARCHAR (20)   NULL,
    [Exam1CombineExamName]           NVARCHAR (150)  NULL,
    [Exam2Name]                      NVARCHAR (150)  NULL,
    [TotalMarks2]                    DECIMAL (8, 2)  NULL,
    [TotalObtain2]                   DECIMAL (8, 2)  NULL,
    [Percentage2]                    DECIMAL (8, 2)  NULL,
    [RankNumber2]                    INT             NULL,
    [ResultGrade2]                   NVARCHAR (50)   NULL,
    [Percentile2]                    DECIMAL (8, 2)  NULL,
    [ResultStatus2]                  NVARCHAR (20)   NULL,
    [Exam2CombineExamName]           NVARCHAR (150)  NULL,
    [Exam3Name]                      NVARCHAR (150)  NULL,
    [TotalMarks3]                    DECIMAL (8, 2)  NULL,
    [TotalObtain3]                   DECIMAL (8, 2)  NULL,
    [Percentage3]                    DECIMAL (8, 2)  NULL,
    [RankNumber3]                    INT             NULL,
    [ResultGrade3]                   NVARCHAR (50)   NULL,
    [Percentile3]                    DECIMAL (8, 2)  NULL,
    [ResultStatus3]                  NVARCHAR (20)   NULL,
    [Exam3CombineExamName]           NVARCHAR (150)  NULL,
    [Exam4Name]                      NVARCHAR (150)  NULL,
    [TotalMarks4]                    DECIMAL (8, 2)  NULL,
    [TotalObtain4]                   DECIMAL (8, 2)  NULL,
    [Percentage4]                    DECIMAL (8, 2)  NULL,
    [RankNumber4]                    INT             NULL,
    [ResultGrade4]                   NVARCHAR (50)   NULL,
    [Percentile4]                    DECIMAL (8, 2)  NULL,
    [ResultStatus4]                  NVARCHAR (20)   NULL,
    [Exam4CombineExamName]           NVARCHAR (150)  NULL,
    [Exam5Name]                      NVARCHAR (150)  NULL,
    [TotalMarks5]                    DECIMAL (8, 2)  NULL,
    [TotalObtain5]                   DECIMAL (8, 2)  NULL,
    [Percentage5]                    DECIMAL (8, 2)  NULL,
    [RankNumber5]                    INT             NULL,
    [ResultGrade5]                   NVARCHAR (50)   NULL,
    [Percentile5]                    DECIMAL (8, 2)  NULL,
    [ResultStatus5]                  NVARCHAR (20)   NULL,
    [Exam5CombineExamName]           NVARCHAR (150)  NULL,
    [Exam6Name]                      NVARCHAR (150)  NULL,
    [TotalMarks6]                    DECIMAL (8, 2)  NULL,
    [TotalObtain6]                   DECIMAL (8, 2)  NULL,
    [Percentage6]                    DECIMAL (8, 2)  NULL,
    [RankNumber6]                    INT             NULL,
    [ResultGrade6]                   NVARCHAR (50)   NULL,
    [Percentile6]                    DECIMAL (8, 2)  NULL,
    [ResultStatus6]                  NVARCHAR (20)   NULL,
    [Exam6CombineExamName]           NVARCHAR (150)  NULL,
    [Exam7Name]                      NVARCHAR (150)  NULL,
    [TotalMarks7]                    DECIMAL (8, 2)  NULL,
    [TotalObtain7]                   DECIMAL (8, 2)  NULL,
    [Percentage7]                    DECIMAL (8, 2)  NULL,
    [RankNumber7]                    INT             NULL,
    [ResultGrade7]                   NVARCHAR (50)   NULL,
    [Percentile7]                    DECIMAL (8, 2)  NULL,
    [ResultStatus7]                  NVARCHAR (20)   NULL,
    [Exam7CombineExamName]           NVARCHAR (150)  NULL,
    [Exam8Name]                      NVARCHAR (150)  NULL,
    [TotalMarks8]                    DECIMAL (8, 2)  NULL,
    [TotalObtain8]                   DECIMAL (8, 2)  NULL,
    [Percentage8]                    DECIMAL (8, 2)  NULL,
    [RankNumber8]                    INT             NULL,
    [ResultGrade8]                   NVARCHAR (50)   NULL,
    [Percentile8]                    DECIMAL (8, 2)  NULL,
    [ResultStatus8]                  NVARCHAR (20)   NULL,
    [Exam8CombineExamName]           NVARCHAR (150)  NULL,
    [Exam9Name]                      NVARCHAR (150)  NULL,
    [TotalMarks9]                    DECIMAL (8, 2)  NULL,
    [TotalObtain9]                   DECIMAL (8, 2)  NULL,
    [Percentage9]                    DECIMAL (8, 2)  NULL,
    [RankNumber9]                    INT             NULL,
    [ResultGrade9]                   NVARCHAR (50)   NULL,
    [Percentile9]                    DECIMAL (8, 2)  NULL,
    [ResultStatus9]                  NVARCHAR (20)   NULL,
    [Exam9CombineExamName]           NVARCHAR (150)  NULL,
    [Exam10Name]                     NVARCHAR (150)  NULL,
    [TotalMarks10]                   DECIMAL (8, 2)  NULL,
    [TotalObtain10]                  DECIMAL (8, 2)  NULL,
    [Percentage10]                   DECIMAL (8, 2)  NULL,
    [RankNumber10]                   INT             NULL,
    [ResultGrade10]                  NVARCHAR (50)   NULL,
    [Percentile10]                   DECIMAL (8, 2)  NULL,
    [ResultStatus10]                 NVARCHAR (20)   NULL,
    [Exam10CombineExamName]          NVARCHAR (150)  NULL,
    [Exam11Name]                     NVARCHAR (150)  NULL,
    [TotalMarks11]                   DECIMAL (8, 2)  NULL,
    [TotalObtain11]                  DECIMAL (8, 2)  NULL,
    [Percentage11]                   DECIMAL (8, 2)  NULL,
    [RankNumber11]                   INT             NULL,
    [ResultGrade11]                  NVARCHAR (50)   NULL,
    [Percentile11]                   DECIMAL (8, 2)  NULL,
    [ResultStatus11]                 NVARCHAR (20)   NULL,
    [Exam11CombineExamName]          NVARCHAR (150)  NULL,
    [Exam12Name]                     NVARCHAR (150)  NULL,
    [TotalMarks12]                   DECIMAL (8, 2)  NULL,
    [TotalObtain12]                  DECIMAL (8, 2)  NULL,
    [Percentage12]                   DECIMAL (8, 2)  NULL,
    [RankNumber12]                   INT             NULL,
    [ResultGrade12]                  NVARCHAR (50)   NULL,
    [Percentile12]                   DECIMAL (8, 2)  NULL,
    [ResultStatus12]                 NVARCHAR (20)   NULL,
    [Exam12CombineExamName]          NVARCHAR (150)  NULL,
    [Exam13Name]                     NVARCHAR (150)  NULL,
    [TotalMarks13]                   DECIMAL (8, 2)  NULL,
    [TotalObtain13]                  DECIMAL (8, 2)  NULL,
    [Percentage13]                   DECIMAL (8, 2)  NULL,
    [RankNumber13]                   INT             NULL,
    [ResultGrade13]                  NVARCHAR (50)   NULL,
    [Percentile13]                   DECIMAL (8, 2)  NULL,
    [ResultStatus13]                 NVARCHAR (20)   NULL,
    [Exam13CombineExamName]          NVARCHAR (150)  NULL,
    [ResultRemark1]                  NVARCHAR (200)  NULL,
    [ResultRemark2]                  NVARCHAR (200)  NULL,
    [TotalDays]                      DECIMAL (6, 2)  NULL,
    [PresentDays]                    DECIMAL (6, 2)  NULL,
    [StudentHeight]                  DECIMAL (6, 2)  NULL,
    [StudentWeight]                  DECIMAL (6, 2)  NULL,
    [ExamSeatNo]                     NVARCHAR (20)   NULL,
    [ExamId]                         INT             NULL,
    [ExamCode]                       NVARCHAR (20)   NULL,
    [Exam1Code]                      NVARCHAR (20)   NULL,
    [Exam2Code]                      NVARCHAR (20)   NULL,
    [Exam3Code]                      NVARCHAR (20)   NULL,
    [Exam4Code]                      NVARCHAR (20)   NULL,
    [Exam5Code]                      NVARCHAR (20)   NULL,
    [Exam6Code]                      NVARCHAR (20)   NULL,
    [Exam7Code]                      NVARCHAR (20)   NULL,
    [Exam8Code]                      NVARCHAR (20)   NULL,
    [Exam9Code]                      NVARCHAR (20)   NULL,
    [Exam10Code]                     NVARCHAR (20)   NULL,
    [Exam11Code]                     NVARCHAR (20)   NULL,
    [Exam12Code]                     NVARCHAR (20)   NULL,
    [Exam13Code]                     NVARCHAR (20)   NULL,
    [IsDisplayParentName]            BIT             NULL,
    [FatherName]                     NVARCHAR (100)  NULL,
    [MotherName]                     NVARCHAR (100)  NULL,
    [IsShowSubjectMark]              BIT             NULL,
    [IsOptionalSubject]              BIT             NULL,
    [CoScholasticScopeId]            TINYINT         NULL,
    [IsDisplayPrincipalSign]         BIT             NULL,
    [IsDisplayTeacherSign]           BIT             NULL,
    [EmployeeSign]                   VARBINARY (MAX) NULL,
    [Batch]                          NVARCHAR (100)  NULL,
    [ExamNameTerm1]                  NVARCHAR (100)  NULL,
    [ExamNameTerm2]                  NVARCHAR (100)  NULL,
    [ExamNameTerm3]                  NVARCHAR (100)  NULL,
    [ExamNameTerm4]                  NVARCHAR (100)  NULL,
    [ClassTeacherName]               NVARCHAR (100)  NULL,
    [FirstName]                      NVARCHAR (50)   NULL,
    [LastName]                       NVARCHAR (50)   NULL,
    [IsDisplayMonthlyAttendance]     BIT             NULL,
    [MarksheetHeaderA4]              VARBINARY (MAX) NULL,
    [IsImageHeader]                  BIT             NULL,
    [MyGoal]                         NVARCHAR (200)  NULL,
    [AreaOfInterest]                 NVARCHAR (200)  NULL,
    [Responsibility]                 NVARCHAR (200)  NULL,
    [MyInterestHobby]                NVARCHAR (200)  NULL,
    [MyStrength]                     NVARCHAR (200)  NULL,
    [Achievements]                   NVARCHAR (1000) NULL,
    [DentalHygiene]                  NVARCHAR (200)  NULL,
    [VisionLeft]                     NVARCHAR (50)   NULL,
    [VisionRight]                    NVARCHAR (50)   NULL,
    [IsDetail]                       BIT             NULL,
    [SubjectGroupId]                 INT             NULL,
    [SubjectGroupTitle]              NVARCHAR (50)   NULL,
    [SubjectGroupCode]               NVARCHAR (50)   NULL,
    [DecimalFormat]                  NVARCHAR (10)   NULL,
    [SubjectRemark]                  NVARCHAR (1000) NULL,
    [GraceMark]                      DECIMAL (5, 2)  NULL,
    [KrupaMark]                      DECIMAL (5, 2)  NULL,
    [GradeStringHtml]                NVARCHAR (500)  NULL,
    [ResultRemark3]                  NVARCHAR (200)  NULL,
    [IsDisplayTotalMark]             BIT             NULL,
    [SubjectObtainTerm1]             DECIMAL (8, 2)  NULL,
    [SubjectObtainTerm2]             DECIMAL (8, 2)  NULL,
    [SubjectObtainTerm3]             DECIMAL (8, 2)  NULL,
    [SubjectObtainTerm4]             DECIMAL (8, 2)  NULL,
    [SubjectMaxTerm1]                DECIMAL (8, 2)  NULL,
    [SubjectMaxTerm2]                DECIMAL (8, 2)  NULL,
    [SubjectMaxTerm3]                DECIMAL (8, 2)  NULL,
    [SubjectMaxTerm4]                DECIMAL (8, 2)  NULL,
    [ContactNo]                      NVARCHAR (50)   NULL,
    [PresentAddress]                 NVARCHAR (MAX)  NULL,
    [TeacherSignCaption]             NVARCHAR (100)  NULL,
    [PrincipalSignCaption]           NVARCHAR (100)  NULL,
    [ParentSignCaption]              NVARCHAR (100)  NULL,
    [ImprovementArea]                NVARCHAR (200)  NULL,
    [ProgressArea]                   NVARCHAR (200)  NULL,
    [GeneralRemark]                  NVARCHAR (1000) NULL,
    [MyActivity]                     NVARCHAR (200)  NULL,
    [ClassTeacherRemark]             NVARCHAR (1000) NULL,
    [HouseRemark]                    NVARCHAR (1000) NULL,
    [BloodGroup]                     NVARCHAR (100)  NULL,
    [TotalDays1]                     DECIMAL (6, 2)  NULL,
    [PresentDays1]                   DECIMAL (6, 2)  NULL,
    [TotalDays2]                     DECIMAL (6, 2)  NULL,
    [PresentDays2]                   DECIMAL (6, 2)  NULL,
    [TotalDays3]                     DECIMAL (6, 2)  NULL,
    [PresentDays3]                   DECIMAL (6, 2)  NULL,
    [TotalDays4]                     DECIMAL (6, 2)  NULL,
    [PresentDays4]                   DECIMAL (6, 2)  NULL,
    [TotalDays5]                     DECIMAL (6, 2)  NULL,
    [PresentDays5]                   DECIMAL (6, 2)  NULL,
    [TotalDays6]                     DECIMAL (6, 2)  NULL,
    [PresentDays6]                   DECIMAL (6, 2)  NULL,
    [TotalDays7]                     DECIMAL (6, 2)  NULL,
    [PresentDays7]                   DECIMAL (6, 2)  NULL,
    [TotalDays8]                     DECIMAL (6, 2)  NULL,
    [PresentDays8]                   DECIMAL (6, 2)  NULL,
    [TotalDays9]                     DECIMAL (6, 2)  NULL,
    [PresentDays9]                   DECIMAL (6, 2)  NULL,
    [TotalDays10]                    DECIMAL (6, 2)  NULL,
    [PresentDays10]                  DECIMAL (6, 2)  NULL,
    [TotalDays11]                    DECIMAL (6, 2)  NULL,
    [PresentDays11]                  DECIMAL (6, 2)  NULL,
    [TotalDays12]                    DECIMAL (6, 2)  NULL,
    [PresentDays12]                  DECIMAL (6, 2)  NULL,
    [TotalDays13]                    DECIMAL (6, 2)  NULL,
    [PresentDays13]                  DECIMAL (6, 2)  NULL,
    [BatchIdText]                    NVARCHAR (20)   NULL,
    [IsShowWithDetail]               BIT             NULL,
    [IsPresent]                      BIT             NULL,
    [GradeTitle]                     NVARCHAR (50)   NULL,
    [SubjectHighestDivisionGrade]    NVARCHAR (50)   NULL,
    [SubjectHighestDivisionMark]     DECIMAL (5, 2)  NULL,
    [AchievementsTerm1]              NVARCHAR (1000) NULL,
    [AchievementsTerm2]              NVARCHAR (1000) NULL,
    [GeneralRemarkTerm1]             NVARCHAR (200)  NULL,
    [GeneralRemarkTerm2]             NVARCHAR (200)  NULL,
    [ResultRemark1Term1]             NVARCHAR (200)  NULL,
    [ResultRemark2Term1]             NVARCHAR (200)  NULL,
    [ResultRemark1Term2]             NVARCHAR (200)  NULL,
    [ResultRemark2Term2]             NVARCHAR (200)  NULL,
    [SR_HeightTerm1]                 DECIMAL (5, 2)  NULL,
    [SR_WeightTerm1]                 DECIMAL (5, 2)  NULL,
    [SR_HeightTerm2]                 DECIMAL (5, 2)  NULL,
    [SR_WeightTerm2]                 DECIMAL (5, 2)  NULL,
    [SR_PresentDaysTerm1]            DECIMAL (6, 2)  NULL,
    [SR_PresentDaysTerm2]            DECIMAL (6, 2)  NULL,
    [SR_TotalDaysTerm1]              DECIMAL (6, 2)  NULL,
    [SR_TotalDaysTerm2]              DECIMAL (6, 2)  NULL,
    [HouseId]                        INT             NULL,
    [HouseName]                      NVARCHAR (100)  NULL,
    [AdhaarNumber]                   NVARCHAR (100)  NULL,
    [UIdNumber]                      NVARCHAR (100)  NULL,
    [FatherContactNo]                NVARCHAR (50)   NULL,
    [MotherContactNo]                NVARCHAR (50)   NULL,
    [FatherMail]                     NVARCHAR (MAX)  NULL,
    [MotherMail]                     NVARCHAR (MAX)  NULL,
    [Gender]                         NVARCHAR (100)  NULL,
    [CoordinatorEmployeeSign]        VARBINARY (MAX) NULL,
    [StudentAddress]                 NVARCHAR (MAX)  NULL,
    [SUId]                           NVARCHAR (50)   NULL,
    [HighestDivisionMark]            DECIMAL (5, 2)  NULL,
    [HighestDivisionGrade]           NVARCHAR (50)   NULL,
    [StreamTitle]                    NVARCHAR (50)   NULL,
    [AdmissionNo]                    NVARCHAR (50)   NULL,
    [AdmissionDate]                  DATE            NULL,
    [MiddleName]                     NVARCHAR (50)   NULL,
    [FatherOccupation]               NVARCHAR (50)   NULL,
    [ResultSheetAdditionalTitle]     NVARCHAR (100)  NULL,
    [IsDecimal]                      BIT             NULL,
    [IsAbsentRemark]                 BIT             NULL,
    [FinalAbsentRemark]              NVARCHAR (100)  NULL,
    [AbsentRemark1]                  NVARCHAR (100)  NULL,
    [AbsentRemark2]                  NVARCHAR (100)  NULL,
    [AbsentRemark3]                  NVARCHAR (100)  NULL,
    [AbsentRemark4]                  NVARCHAR (100)  NULL,
    [AbsentRemark5]                  NVARCHAR (100)  NULL,
    [AbsentRemark6]                  NVARCHAR (100)  NULL,
    [AbsentRemark7]                  NVARCHAR (100)  NULL,
    [AbsentRemark8]                  NVARCHAR (100)  NULL,
    [AbsentRemark9]                  NVARCHAR (100)  NULL,
    [AbsentRemark10]                 NVARCHAR (100)  NULL,
    [AbsentRemark11]                 NVARCHAR (100)  NULL,
    [AbsentRemark12]                 NVARCHAR (100)  NULL,
    [AbsentRemark13]                 NVARCHAR (100)  NULL,
    [ExamMaximumTerm1]               DECIMAL (6, 2)  NULL,
    [ExamMaximumTerm2]               DECIMAL (6, 2)  NULL,
    [ExamMaximumTerm3]               DECIMAL (6, 2)  NULL,
    [ExamMaximumTerm4]               DECIMAL (6, 2)  NULL
);


GO
PRINT N'Creating Table [sAttendance].[tPeriodNoMaster]...';


GO
CREATE TABLE [sAttendance].[tPeriodNoMaster] (
    [Id]         SMALLINT      NOT NULL,
    [Title]      NVARCHAR (10) NOT NULL,
    [IsObsolete] BIT           NOT NULL
);


GO
PRINT N'Creating Table [sBiometric].[tTempBiometricAlertData]...';


GO
CREATE TABLE [sBiometric].[tTempBiometricAlertData] (
    [AutoId]                 BIGINT           IDENTITY (1, 1) NOT NULL,
    [MobileNo]               NVARCHAR (50)    NULL,
    [EmailId]                NVARCHAR (50)    NULL,
    [MsgText]                NVARCHAR (MAX)   NULL,
    [Subject]                NVARCHAR (100)   NULL,
    [ReceiverSourceTypeId]   INT              NULL,
    [ReceiverSourceId]       BIGINT           NULL,
    [StudentName]            NVARCHAR (300)   NULL,
    [Code]                   NVARCHAR (20)    NULL,
    [WhatsAppContactNo]      NVARCHAR (20)    NULL,
    [SourceTypeId]           INT              NULL,
    [SourceId]               BIGINT           NULL,
    [OrgId]                  SMALLINT         NULL,
    [OrgGroupId]             SMALLINT         NULL,
    [Time]                   TIME (7)         NULL,
    [OrganizationTitle]      NVARCHAR (100)   NULL,
    [CloudTransactionDataId] BIGINT           NULL,
    [SchedularFromDateTime]  DATETIME         NULL,
    [SchedularToDateTime]    DATETIME         NULL,
    [CreatedDateTime]        DATETIME         NULL,
    [AlertId]                INT              NULL,
    [AlertUniqueId]          UNIQUEIDENTIFIER NULL
);


GO
PRINT N'Creating Default Constraint unnamed constraint on [sAssessment].[tTempAllExamWithAllTerm]...';


GO
ALTER TABLE [sAssessment].[tTempAllExamWithAllTerm]
    ADD DEFAULT ((0)) FOR [Obtain9];


GO
PRINT N'Creating Default Constraint unnamed constraint on [sAssessment].[tTempAllExamWithAllTerm]...';


GO
ALTER TABLE [sAssessment].[tTempAllExamWithAllTerm]
    ADD DEFAULT ((0)) FOR [Obtain4];


GO
PRINT N'Creating Default Constraint unnamed constraint on [sAssessment].[tTempAllExamWithAllTerm]...';


GO
ALTER TABLE [sAssessment].[tTempAllExamWithAllTerm]
    ADD DEFAULT ((0)) FOR [Obtain10];


GO
PRINT N'Creating Default Constraint unnamed constraint on [sAssessment].[tTempAllExamWithAllTerm]...';


GO
ALTER TABLE [sAssessment].[tTempAllExamWithAllTerm]
    ADD DEFAULT ((0)) FOR [Obtain7];


GO
PRINT N'Creating Default Constraint unnamed constraint on [sAssessment].[tTempAllExamWithAllTerm]...';


GO
ALTER TABLE [sAssessment].[tTempAllExamWithAllTerm]
    ADD DEFAULT ((0)) FOR [Obtain1];


GO
PRINT N'Creating Default Constraint unnamed constraint on [sAssessment].[tTempAllExamWithAllTerm]...';


GO
ALTER TABLE [sAssessment].[tTempAllExamWithAllTerm]
    ADD DEFAULT ((0)) FOR [Obtain2];


GO
PRINT N'Creating Default Constraint unnamed constraint on [sAssessment].[tTempAllExamWithAllTerm]...';


GO
ALTER TABLE [sAssessment].[tTempAllExamWithAllTerm]
    ADD DEFAULT ((0)) FOR [Obtain12];


GO
PRINT N'Creating Default Constraint unnamed constraint on [sAssessment].[tTempAllExamWithAllTerm]...';


GO
ALTER TABLE [sAssessment].[tTempAllExamWithAllTerm]
    ADD DEFAULT ((0)) FOR [Obtain13];


GO
PRINT N'Creating Default Constraint unnamed constraint on [sAssessment].[tTempAllExamWithAllTerm]...';


GO
ALTER TABLE [sAssessment].[tTempAllExamWithAllTerm]
    ADD DEFAULT ((0)) FOR [Obtain8];


GO
PRINT N'Creating Default Constraint unnamed constraint on [sAssessment].[tTempAllExamWithAllTerm]...';


GO
ALTER TABLE [sAssessment].[tTempAllExamWithAllTerm]
    ADD DEFAULT ((0)) FOR [Obtain3];


GO
PRINT N'Creating Default Constraint unnamed constraint on [sAssessment].[tTempAllExamWithAllTerm]...';


GO
ALTER TABLE [sAssessment].[tTempAllExamWithAllTerm]
    ADD DEFAULT ((0)) FOR [Obtain5];


GO
PRINT N'Creating Default Constraint unnamed constraint on [sAssessment].[tTempAllExamWithAllTerm]...';


GO
ALTER TABLE [sAssessment].[tTempAllExamWithAllTerm]
    ADD DEFAULT ((0)) FOR [Obtain6];


GO
PRINT N'Creating Default Constraint unnamed constraint on [sAssessment].[tTempAllExamWithAllTerm]...';


GO
ALTER TABLE [sAssessment].[tTempAllExamWithAllTerm]
    ADD DEFAULT ((0)) FOR [Obtain11];


GO
PRINT N'Creating Function [sFee].[fPendingFeeNamesGet]...';



GO
   CREATE FUNCTION [sFee].[fPendingFeeNamesGet](@rAcademicId bigint,@rReceiptBookId bigint
,@Fee TempPendingFee readonly
)
RETURNS nvarchar(2000) WITH EXECUTE AS CALLER
AS 
BEGIN

DECLARE @rFeeDetail nvarchar(2000)
SELECT 
			@rFeeDetail=COALESCE(@rFeeDetail+',','') +  F.FeeCode
			 FROM
			 @Fee F			  
			 WHERE AcademicId = @rAcademicId  
			 AND ReceiptBookId = @rReceiptBookId
			 Order By F.FeeOrderIndex
		
    RETURN ISNULL(@rFeeDetail,'') 
 
END
GO
PRINT N'Altering Procedure [sAcademic].[pClassworkAdd]...';


GO

ALTER PROCEDURE [sAcademic].[pClassworkAdd]
	 
	 	@rBatchId int,
        @rId bigint,
        @rSubjectId int,
        @rClassId int,
        @rDivisionId int,
		@rClasswork nvarchar(max),
		@rHomework nvarchar(max),
		@rClassWorkDate date,
		@rHomeWorkEndDate date,
		@rEmployeeId bigint,
		@rCreatedUserId bigint,
		@rOrgId int,
		@rClassworkStatusId smallint = 1,
		@rHomeWorkStatusId smallint = 1,
		@rIsSubmitHomework bit =0
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	DECLARE @lNextNumber BIGINT 
	
	-- Temp Basis Update due to Wrong OrgId,BatchId paseed from Mobile End
	DECLARE @lOrgId smallint, @lOrgGroupBatchId int, @lBatchId int
	SELECT @lOrgId = OrgId from sSetup.tSubjectMaster Where Id = @rSubjectId
	SELECT @lOrgGroupBatchId =  OrgGroupBatchId from sSetup.tBatchMaster Where Id = @rBatchId
	SELECT @lBatchId = Id from sSetup.tBatchMaster Where OrgId = @lOrgId AND OrgGroupBatchId = @lOrgGroupBatchId 
	
	SET @rBatchId = @lBatchId
	SET @rOrgId = @lOrgId
	-- Ends
	
	SELECT @rId = Id FROM sAcademic.tClasswork WHERE	
	        BatchId=@rBatchId AND
			SubjectId=@rSubjectId AND
			ClassId=@rClassId AND
			DivisionId=@rDivisionId AND
			EmployeeId = @rEmployeeId AND
			ClassWorkDate = @rClassWorkDate
	        
	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAcademic.tClasswork', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sAcademic.tClasswork
		(
			BatchId,
			Id,
			SubjectId,
			ClassId,
			DivisionId,
			Classwork,
			Homework,
			ClassWorkDate,
			HomeWorkEndDate,
			EmployeeId,
			CreatedUserId,
			CreatedDateTime,
			ClassworkStatusId,
			HomeWorkStatusId,
			IsSubmitHomework
		)
	VALUES
		(
			@rBatchId,
			@lNextNumber,
			@rSubjectId,
			@rClassId,
			@rDivisionId,
			CASE WHEN @rClassworkStatusId=1 THEN @rClasswork ELSE 'NA' END,
			CASE WHEN @rHomeWorkStatusId=1 THEN @rHomework ELSE 'NA' END,
			@rClassWorkDate,
			@rHomeWorkEndDate,
			@rEmployeeId,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rClassworkStatusId,
		    @rHomeWorkStatusId,
			@rIsSubmitHomework
		)
		    SELECT @lNextNumber AS Result
	END	 

ELSE
	 BEGIN
	 
			If @rClassworkStatusId=2 SET @rClasswork='NA'
			If @rHomeWorkStatusId=2 SET  @rHomework='NA'
	 --SET @lNextNumber = @rId
	    UPDATE  sAcademic.tClasswork
	    SET
			BatchId=@rBatchId,
			SubjectId=@rSubjectId,
			ClassId=@rClassId,
			DivisionId=@rDivisionId,
			Classwork=@rClasswork,
			Homework=@rHomework,
			ClassWorkDate=@rClassWorkDate,
			HomeWorkEndDate=@rHomeWorkEndDate,
			EmployeeId=@rEmployeeId,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate(),
			ClassworkStatusId=@rClassworkStatusId,
			HomeWorkStatusId=@rHomeWorkStatusId,
	      IsSubmitHomework = @rIsSubmitHomework
	      WHERE Id = @rId
	      SELECT 11 AS Result
	 END  	

	
	END TRY
	
	BEGIN CATCH 
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering Procedure [sAcademic].[pClassworkCloneAdd]...';


GO

ALTER PROCEDURE [sAcademic].[pClassworkCloneAdd]
	 
	 	@rBatchId int,
        @rId bigint,
        @rSubjectId int,
        @rClassId int,
        @rDivisionId int,
		@rClasswork nvarchar(max),
		@rHomework nvarchar(max),
		@rClassWorkDate date,
		@rHomeWorkEndDate date,
		@rEmployeeId bigint,
		@rCreatedUserId bigint,
		@rOrgId int,
		@rClassworkStatusId smallint = 1,
		@rHomeWorkStatusId smallint = 1
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	DECLARE @lNextNumber BIGINT 
	
	-- Temp Basis Update due to Wrong OrgId,BatchId paseed from Mobile End
	DECLARE @lOrgId smallint, @lOrgGroupBatchId int, @lBatchId int
	SELECT @lOrgId = OrgId from sSetup.tSubjectMaster Where Id = @rSubjectId
	SELECT @lOrgGroupBatchId =  OrgGroupBatchId from sSetup.tBatchMaster Where Id = @rBatchId
	SELECT @lBatchId = Id from sSetup.tBatchMaster Where OrgId = @lOrgId AND OrgGroupBatchId = @lOrgGroupBatchId 
	
	SET @rBatchId = @lBatchId
	SET @rOrgId = @lOrgId
	-- Ends
	
	--SELECT @rId = Id FROM sAcademic.tClasswork WHERE	
	--        BatchId=@rBatchId AND
	--		SubjectId=@rSubjectId AND
	--		ClassId=@rClassId AND
	--		DivisionId=@rDivisionId AND
	--		EmployeeId = @rEmployeeId AND
	--		ClassWorkDate = @rClassWorkDate
	        
	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAcademic.tClasswork', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sAcademic.tClasswork
		(
			BatchId,
			Id,
			SubjectId,
			ClassId,
			DivisionId,
			Classwork,
			Homework,
			ClassWorkDate,
			HomeWorkEndDate,
			EmployeeId,
			CreatedUserId,
			CreatedDateTime,
			ClassworkStatusId,
			HomeWorkStatusId
		)
	VALUES
		(
			@rBatchId,
			@lNextNumber,
			@rSubjectId,
			@rClassId,
			@rDivisionId,
			CASE WHEN @rClassworkStatusId=1 THEN @rClasswork ELSE 'NA' END,
			CASE WHEN @rHomeWorkStatusId=1 THEN @rHomework ELSE 'NA' END,
			@rClassWorkDate,
			@rHomeWorkEndDate,
			@rEmployeeId,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rClassworkStatusId,
		    @rHomeWorkStatusId
		)
		    SELECT @lNextNumber AS Result
	END	 

ELSE
	 BEGIN
	 
			If @rClassworkStatusId=2 SET @rClasswork='NA'
			If @rHomeWorkStatusId=2 SET  @rHomework='NA'
	 --SET @lNextNumber = @rId
	    UPDATE  sAcademic.tClasswork
	    SET
			BatchId=@rBatchId,
			SubjectId=@rSubjectId,
			ClassId=@rClassId,
			DivisionId=@rDivisionId,
			Classwork=@rClasswork,
			Homework=@rHomework,
			ClassWorkDate=@rClassWorkDate,
			HomeWorkEndDate=@rHomeWorkEndDate,
			EmployeeId=@rEmployeeId,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate(),
			ClassworkStatusId=@rClassworkStatusId,
			HomeWorkStatusId=@rHomeWorkStatusId
	      
	      WHERE Id = @rId
	      SELECT 11 AS Result
	 END  	

	
	END TRY
	
	BEGIN CATCH 
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering Procedure [sAcademic].[pClassworkHomeworkQueueGet]...';


GO


ALTER PROCEDURE [sAcademic].[pClassworkHomeworkQueueGet]

	 @rId bigint=0,	 
	 @rSubjectId int=0,
	 @rClassId int=0,
	 @rEmployeeId bigint=0,
	 @rDivisionid int=0,
	 @rFromDate datetime='',
     @rToDate datetime='',
     @rOrgId int=0,
     --@rBatchId int
     @rOrgGroupBatchId int=0,
    @rUserId bigint =0,
	@rStatusId int=0
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON


DECLARE @rSourceId bigint
DECLARE @rSourceTypeId int

set @rSourceId = ( SELECT SourceId FROM sSecurity.tUser where Id=@rUserId)
set @rSourceTypeId = ( SELECT ISNULL(SourceTypeId,0) FROM sSecurity.tUser where Id=@rUserId)


BEGIN 


	--if(@rId = 0)
		--BEGIN

			if(@rSourceTypeId = 95)
				BEGIN

				CREATE TABLE #TempData
				( 
					Id bigint,
					EmployeeId bigint,
					ClassId int,
					DivisionId int,
					SubjectId int,
					ClassWorkDate Date,
					Classwork nvarchar(max),
					Homework nvarchar(max),
					ClassworkStatusId int,
					HomeWorkStatusId int,
					HomeWorkEndDate date,
					CreatedDateTime datetime,
					BatchId bigint,
					Batch nvarchar(100),
					SubjectName nvarchar(100),
					TeacherName nvarchar(200),
					ClassName nvarchar(100),
					DivisionName nvarchar(100),
					OrgId int,
					Organization nvarchar(200),
					UniqueId nvarchar(500),
					StatusId int,
					SubjectCordinatorEmployeeId bigint,
					Status nvarchar(200),
					IsSubmitHomework bit
				)
				INSERT INTO #TempData  
					SELECT 
					AC.Id,
					AC.EmployeeId,
					AC.ClassId,
					AC.DivisionId,
					AC.SubjectId,
					AC.ClassWorkDate,
					AC.Classwork,
					AC.Homework,
					ISNULL(ClassworkStatusId,1) AS ClassworkStatusId,
					ISNULL(HomeWorkStatusId,1) AS HomeWorkStatusId,
					--AC.HomeWorkEndDate,
					ISNULL(AC.HomeWorkEndDate,'') AS HomeWorkEndDate,
					AC.CreatedDateTime,
					AC.BatchId,
					BM.Title AS Batch,
					ISNULL(vTSD.SubjectName,'') as SubjectName,
					ISNULL(EM.FirstName + ' ' + EM.LastName,'') AS TeacherName,
					ISNULL(vTSD.ClassTitle,'') AS ClassName,
					ISNULL(vTSD.DivisionTitle,'') AS DivisionName,
					BM.OrgId,
					OM.DisplayTitle AS Organization,
					REPLACE(CONVERT(VARCHAR(20), AC.ClassWorkDate, 103),'/','') +'_'+ CONVERT(nvarchar(10),AC.DivisionId) +'_'+CONVERT(nvarchar(10),AC.SubjectId) AS UniqueId,
					ISNULL(AC.StatusId,549) AS StatusId,vTSD.SubjectCordinatorEmployeeId,
					CASE WHEN ISNULL(AC.StatusId,549) = 549 then 'Pending' WHEN AC.StatusId=550 then 'Approve' ELSE  'Reject' END  AS Status,
					ISNULL(AC.IsSubmitHomework,0) AS IsSubmitHomework
			FROM 
					sAcademic.tClasswork AC
					INNER JOIN sAcademic.vTeacherSubjectDivision vTSD ON vTSD.SubjectId = AC.SubjectId AND vTSD.DivisionId = AC.DivisionId AND vTSD.ClassId=AC.ClassId
					INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = vTSD.OrgId
					INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OM.OrgGroupId
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId = OGM.Id
					INNER JOIN sHrm.tEmployeeMaster EM ON  AC.EmployeeId = EM.Id AND vTSD.EmployeeId = AC.EmployeeId
					--INNER JOIN sHrm.tEmployeeMaster EM ON  AC.EmployeeId = EM.Id 
					INNER JOIN sHrm.tEmployeeJobdetail EJD ON EJD.EmployeeId = EM.Id
					INNER JOIN sSetup.tBatchMaster BM On BM.Id= AC.BatchId AND BM.OrgGroupBatchId = OGBM.Id
					INNER JOIN sSecurity.tUserOrganization U ON U.OrgId = OM.Id 
			WHERE 
					--((AC.BatchId = @rBatchId) OR (@rBatchId = 0))
					((AC.Id = @rId) OR (@rId = 0))
					AND ((AC.EmployeeId= @rEmployeeId) OR (@rEmployeeId = 0))
					AND	((AC.ClassId = @rClassId) OR (@rClassId = 0))
					AND	((vTSD.OrgId = @rOrgId) OR (@rOrgId = 0))
					AND ((AC.SubjectId =@rSubjectId) OR (@rSubjectId=0))
					AND ((AC.DivisionId =@rDivisionId) OR (@rDivisionId=0))
					--AND (AC.ClassWorkDate>=@rFromDate OR ISNULL(@rFromDate,'')='')
					--AND (AC.ClassWorkDate<=@rToDate OR ISNULL(@rToDate,'')='')
					AND (OGBM.Id = @rOrgGroupBatchId) 
					AND ((U.UserId = @rUserId)OR(@rUserId=0))
					AND ((ISNULL(AC.StatusId,549) = @rStatusId) OR (@rStatusId=0)) 
					AND ((ISNULL(vTSD.SubjectCordinatorEmployeeId,0) = @rSourceId) or (@rSourceId=0))
					AND ISNULL(EM.IsOtherUser,0) = 0 
			order by 
					AC.HomeWorkEndDate DESC
						
				if (EXISTS (select 1 from #TempData))
				BEGIN
				
					Select * FROM #TempData tmp
					WHERE (tmp.ClassWorkDate>=@rFromDate OR ISNULL(@rFromDate,'')='')
					AND (tmp.ClassWorkDate<=@rToDate OR ISNULL(@rToDate,'')='')
				END
				ELSE
				BEGIN
					SELECT 
			AC.Id,
			AC.EmployeeId,
			AC.ClassId,
			AC.DivisionId,
			AC.SubjectId,
			AC.ClassWorkDate,
			AC.Classwork,
			AC.Homework,
			ISNULL(ClassworkStatusId,1) AS ClassworkStatusId,
			ISNULL(HomeWorkStatusId,1) AS HomeWorkStatusId,
			--AC.HomeWorkEndDate,
			ISNULL(AC.HomeWorkEndDate,'') AS HomeWorkEndDate,
			AC.CreatedDateTime,
			AC.BatchId,
			BM.Title AS Batch,
		    ISNULL(vTSD.SubjectName,'') as SubjectName,
		    ISNULL(EM.FirstName + ' ' + EM.LastName,'') AS TeacherName,
		    ISNULL(vTSD.ClassTitle,'') AS ClassName,
		    ISNULL(vTSD.DivisionTitle,'') AS DivisionName,
		    BM.OrgId,
		    OM.DisplayTitle AS Organization,
		    REPLACE(CONVERT(VARCHAR(20), AC.ClassWorkDate, 103),'/','') +'_'+ CONVERT(nvarchar(10),AC.DivisionId) +'_'+CONVERT(nvarchar(10),AC.SubjectId) AS UniqueId,
			ISNULL(AC.StatusId,549) AS StatusId,vTSD.SubjectCordinatorEmployeeId,
			CASE WHEN ISNULL(AC.StatusId,549) = 549 then 'Pending' WHEN AC.StatusId=550 then 'Approve' ELSE  'Reject' END  AS Status,
			ISNULL(AC.IsSubmitHomework,0) AS IsSubmitHomework
	FROM 
			sAcademic.tClasswork AC
			INNER JOIN sAcademic.vTeacherSubjectDivision vTSD ON vTSD.SubjectId = AC.SubjectId AND vTSD.DivisionId = AC.DivisionId AND vTSD.ClassId=AC.ClassId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = vTSD.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OM.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId = OGM.Id
			INNER JOIN sHrm.tEmployeeMaster EM ON  AC.EmployeeId = EM.Id AND vTSD.EmployeeId = AC.EmployeeId
			--INNER JOIN sHrm.tEmployeeMaster EM ON  AC.EmployeeId = EM.Id 
			INNER JOIN sHrm.tEmployeeJobdetail EJD ON EJD.EmployeeId = EM.Id
			INNER JOIN sSetup.tBatchMaster BM On BM.Id= AC.BatchId AND BM.OrgGroupBatchId = OGBM.Id
			INNER JOIN sSecurity.tUserOrganization U ON U.OrgId = OM.Id 
	WHERE 
	        --((AC.BatchId = @rBatchId) OR (@rBatchId = 0))
			((AC.Id = @rId) OR (@rId = 0))
			AND ((AC.EmployeeId= @rEmployeeId) OR (@rEmployeeId = 0))
			AND	((AC.ClassId = @rClassId) OR (@rClassId = 0))
			AND	((vTSD.OrgId = @rOrgId) OR (@rOrgId = 0))
			AND ((AC.SubjectId =@rSubjectId) OR (@rSubjectId=0))
			AND ((AC.DivisionId =@rDivisionId) OR (@rDivisionId=0))
			AND (AC.ClassWorkDate>=@rFromDate OR ISNULL(@rFromDate,'')='')
			AND (AC.ClassWorkDate<=@rToDate OR ISNULL(@rToDate,'')='')
			AND (OGBM.Id = @rOrgGroupBatchId) 
			AND ((U.UserId = @rUserId)OR(@rUserId=0))
			AND ((ISNULL(AC.StatusId,549) = @rStatusId) OR (@rStatusId=0)) 
			AND ((ISNULL(vTSD.EmployeeId,0) = @rSourceId) or (@rSourceId=0))
			AND ISNULL(EM.IsOtherUser,0) = 0 
	order by 
			AC.HomeWorkEndDate DESC
				END

									
				DROP TABLE #TempData
				END

			ELSE IF (@rUserId = 0)
			BEGIN
			SELECT 
			AC.Id,
			AC.EmployeeId,
			AC.ClassId,
			AC.DivisionId,
			AC.SubjectId,
			AC.ClassWorkDate,
			AC.Classwork,
			AC.Homework,
			ISNULL(ClassworkStatusId,1) AS ClassworkStatusId,
			ISNULL(HomeWorkStatusId,1) AS HomeWorkStatusId,
			--AC.HomeWorkEndDate,
			ISNULL(AC.HomeWorkEndDate,'') AS HomeWorkEndDate,

			AC.CreatedDateTime,
			AC.BatchId,
			BM.Title AS Batch,
		    ISNULL(vTSD.SubjectName,'') as SubjectName,
		    ISNULL(EM.FirstName + ' ' + EM.LastName,'') AS TeacherName,
		    ISNULL(vTSD.ClassTitle,'') AS ClassName,
		    ISNULL(vTSD.DivisionTitle,'') AS DivisionName,
		    BM.OrgId,
		    OM.DisplayTitle AS Organization,
		    REPLACE(CONVERT(VARCHAR(20), AC.ClassWorkDate, 103),'/','') +'_'+ CONVERT(nvarchar(10),AC.DivisionId) +'_'+CONVERT(nvarchar(10),AC.SubjectId) AS UniqueId,
			ISNULL(AC.StatusId,549) AS StatusId,vTSD.SubjectCordinatorEmployeeId,
			CASE WHEN ISNULL(AC.StatusId,549) = 549 then 'Pending' WHEN AC.StatusId=550 then 'Approve' ELSE  'Reject' END  AS Status,
			ISNULL(AC.IsSubmitHomework,0) AS IsSubmitHomework
	FROM 
			sAcademic.tClasswork AC
			INNER JOIN sAcademic.vTeacherSubjectDivision vTSD ON vTSD.SubjectId = AC.SubjectId AND vTSD.DivisionId = AC.DivisionId AND vTSD.ClassId=AC.ClassId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = vTSD.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OM.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId = OGM.Id
			INNER JOIN sHrm.tEmployeeMaster EM ON  AC.EmployeeId = EM.Id AND vTSD.EmployeeId = AC.EmployeeId
			--INNER JOIN sHrm.tEmployeeMaster EM ON  AC.EmployeeId = EM.Id 
			--INNER JOIN sHrm.tEmployeeJobdetail EJD ON EJD.EmployeeId = EM.Id
			INNER JOIN sSetup.tBatchMaster BM On BM.Id= AC.BatchId AND BM.OrgGroupBatchId = OGBM.Id
			--INNER JOIN sSecurity.tUserOrganization U ON U.OrgId = OM.Id 
	WHERE 
	        --((AC.BatchId = @rBatchId) OR (@rBatchId = 0))
			((AC.Id = @rId) OR (@rId = 0))
			AND ((AC.EmployeeId= @rEmployeeId) OR (@rEmployeeId = 0))
			AND	((AC.ClassId = @rClassId) OR (@rClassId = 0))
			AND	((vTSD.OrgId = @rOrgId) OR (@rOrgId = 0))
			AND ((AC.SubjectId =@rSubjectId) OR (@rSubjectId=0))
			AND ((AC.DivisionId =@rDivisionId) OR (@rDivisionId=0))
			AND (AC.ClassWorkDate>=@rFromDate OR ISNULL(@rFromDate,'')='')
			AND (AC.ClassWorkDate<=@rToDate OR ISNULL(@rToDate,'')='')
			AND (OGBM.Id = @rOrgGroupBatchId) 
			--AND ((U.UserId = @rUserId)OR(@rUserId=0))
			AND ((ISNULL(AC.StatusId,549) = @rStatusId) OR (@rStatusId=0)) 
			AND ISNULL(EM.IsOtherUser,0) = 0 
	order by 
			AC.HomeWorkEndDate DESC
			END

			ELSE
				BEGIN
					SELECT 
			AC.Id,
			AC.EmployeeId,
			AC.ClassId,
			AC.DivisionId,
			AC.SubjectId,
			AC.ClassWorkDate,
			AC.Classwork,
			AC.Homework,
			ISNULL(ClassworkStatusId,1) AS ClassworkStatusId,
			ISNULL(HomeWorkStatusId,1) AS HomeWorkStatusId,
			--AC.HomeWorkEndDate,
			ISNULL(AC.HomeWorkEndDate,'') AS HomeWorkEndDate,

			AC.CreatedDateTime,
			AC.BatchId,
			BM.Title AS Batch,
		    ISNULL(vTSD.SubjectName,'') as SubjectName,
		    ISNULL(EM.FirstName + ' ' + EM.LastName,'') AS TeacherName,
		    ISNULL(vTSD.ClassTitle,'') AS ClassName,
		    ISNULL(vTSD.DivisionTitle,'') AS DivisionName,
		    BM.OrgId,
		    OM.DisplayTitle AS Organization,
		    REPLACE(CONVERT(VARCHAR(20), AC.ClassWorkDate, 103),'/','') +'_'+ CONVERT(nvarchar(10),AC.DivisionId) +'_'+CONVERT(nvarchar(10),AC.SubjectId) AS UniqueId,
			ISNULL(AC.StatusId,549) AS StatusId,vTSD.SubjectCordinatorEmployeeId,
			CASE WHEN ISNULL(AC.StatusId,549) = 549 then 'Pending' WHEN AC.StatusId=550 then 'Approve' ELSE  'Reject' END  AS Status,
			ISNULL(AC.IsSubmitHomework,0) AS IsSubmitHomework
	FROM 
			sAcademic.tClasswork AC
			INNER JOIN sAcademic.vTeacherSubjectDivision vTSD ON vTSD.SubjectId = AC.SubjectId AND vTSD.DivisionId = AC.DivisionId AND vTSD.ClassId=AC.ClassId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = vTSD.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OM.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId = OGM.Id
			INNER JOIN sHrm.tEmployeeMaster EM ON  AC.EmployeeId = EM.Id AND vTSD.EmployeeId = AC.EmployeeId
			--INNER JOIN sHrm.tEmployeeMaster EM ON  AC.EmployeeId = EM.Id 
			--INNER JOIN sHrm.tEmployeeJobdetail EJD ON EJD.EmployeeId = EM.Id
			INNER JOIN sSetup.tBatchMaster BM On BM.Id= AC.BatchId AND BM.OrgGroupBatchId = OGBM.Id
			INNER JOIN sSecurity.tUserOrganization U ON U.OrgId = OM.Id 
	WHERE 
	        --((AC.BatchId = @rBatchId) OR (@rBatchId = 0))
			((AC.Id = @rId) OR (@rId = 0))
			AND ((AC.EmployeeId= @rEmployeeId) OR (@rEmployeeId = 0))
			AND	((AC.ClassId = @rClassId) OR (@rClassId = 0))
			AND	((vTSD.OrgId = @rOrgId) OR (@rOrgId = 0))
			AND ((AC.SubjectId =@rSubjectId) OR (@rSubjectId=0))
			AND ((AC.DivisionId =@rDivisionId) OR (@rDivisionId=0))
			AND (AC.ClassWorkDate>=@rFromDate OR ISNULL(@rFromDate,'')='')
			AND (AC.ClassWorkDate<=@rToDate OR ISNULL(@rToDate,'')='')
			AND (OGBM.Id = @rOrgGroupBatchId) 
			AND ((U.UserId = @rUserId)OR(@rUserId=0))
			AND ((ISNULL(AC.StatusId,549) = @rStatusId) OR (@rStatusId=0)) 
			AND ISNULL(EM.IsOtherUser,0) = 0 
	order by 
			AC.HomeWorkEndDate DESC
				END

		--END 
	--ELSE
	--	BEGIN
	--	SELECT 
	--		AC.Id,
	--		AC.EmployeeId,
	--		AC.ClassId,
	--		AC.DivisionId,
	--		AC.SubjectId,
	--		AC.ClassWorkDate,
	--		AC.Classwork,
	--		AC.Homework,
	--		ISNULL(ClassworkStatusId,1) AS ClassworkStatusId,
	--		ISNULL(HomeWorkStatusId,1) AS HomeWorkStatusId,
	--		--AC.HomeWorkEndDate,
	--		ISNULL(AC.HomeWorkEndDate,'') AS HomeWorkEndDate,
	--		AC.CreatedDateTime,
	--		AC.BatchId,
	--		BM.Title AS Batch,
	--	    ISNULL(vTSD.SubjectName,'') as SubjectName,
	--	    ISNULL(EM.FirstName + ' ' + EM.LastName,'') AS TeacherName,
	--	    ISNULL(vTSD.ClassTitle,'') AS ClassName,
	--	    ISNULL(vTSD.DivisionTitle,'') AS DivisionName,
	--	    BM.OrgId,
	--	    OM.DisplayTitle AS Organization,
	--	    REPLACE(CONVERT(VARCHAR(20), AC.ClassWorkDate, 103),'/','') +'_'+ CONVERT(nvarchar(10),AC.DivisionId) +'_'+CONVERT(nvarchar(10),AC.SubjectId) AS UniqueId
			
	--FROM 
	--		sAcademic.tClasswork AC
	--		INNER JOIN sAcademic.vTeacherSubjectDivision vTSD ON vTSD.SubjectId = AC.SubjectId AND vTSD.DivisionId = AC.DivisionId AND vTSD.ClassId=AC.ClassId
	--		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = vTSD.OrgId
	--		INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OM.OrgGroupId
	--		INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId = OGM.Id
	--		INNER JOIN sHrm.tEmployeeMaster EM ON  AC.EmployeeId = EM.Id AND vTSD.EmployeeId = AC.EmployeeId
	--		INNER JOIN sHrm.tEmployeeJobdetail EJD ON EJD.EmployeeId = EM.Id
	--		INNER JOIN sSetup.tBatchMaster BM On BM.Id= AC.BatchId AND BM.OrgGroupBatchId = OGBM.Id
	--		INNER JOIN sSecurity.tUserOrganization U ON U.OrgId = OM.Id 
	--WHERE 
	--        --((AC.BatchId = @rBatchId) OR (@rBatchId = 0))
	--		((AC.Id = @rId) OR (@rId = 0))
	--		AND ((AC.EmployeeId= @rEmployeeId) OR (@rEmployeeId = 0))
	--		AND	((AC.ClassId = @rClassId) OR (@rClassId = 0))
	--		AND	((vTSD.OrgId = @rOrgId) OR (@rOrgId = 0))
	--		AND ((AC.SubjectId =@rSubjectId) OR (@rSubjectId=0))
	--		AND ((AC.DivisionId =@rDivisionId) OR (@rDivisionId=0))
	--		AND (AC.ClassWorkDate>=@rFromDate OR ISNULL(@rFromDate,'')='')
	--		AND (AC.ClassWorkDate<=@rToDate OR ISNULL(@rToDate,'')='')
	--		AND (OGBM.Id = @rOrgGroupBatchId) 
	--		AND ((U.UserId = @rUserId)OR(@rUserId=0))
	--		GROUP BY AC.Id,
	--		AC.EmployeeId,
	--		AC.ClassId,
	--		AC.DivisionId,
	--		AC.SubjectId,
	--		AC.ClassWorkDate,
	--		AC.Classwork,
	--		AC.Homework,
	--		ClassworkStatusId,
	--		HomeWorkStatusId,
	--		--AC.HomeWorkEndDate,
	--		AC.HomeWorkEndDate,
	--		AC.CreatedDateTime,
	--		AC.BatchId,
	--		BM.Title,
	--	  vTSD.SubjectName,
	--	    EM.FirstName,  EM.LastName,
	--	    vTSD.ClassTitle,
	--	   vTSD.DivisionTitle,
	--	    BM.OrgId,
	--	    OM.DisplayTitle,
	--	     AC.ClassWorkDate, AC.DivisionId,AC.SubjectId
	--order by 
	--		AC.HomeWorkEndDate DESC
	--	END
	
END
GO
PRINT N'Altering Procedure [sAcademic].[pTopicMasterAdd]...';


GO


ALTER PROCEDURE [sAcademic].[pTopicMasterAdd]
	 
        @rId int,
        @rNumber smallint,
        @rTitle nvarchar(100),
        @rSubjectId int,
        @rClassId int,
        @rOrgId smallint,
        @rCreatedUserId bigint,
		@rIsObsolete bit
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	IF(@rId = 0)	
	BEGIN
		If Exists(select Id from sAcademic.tTopicMaster where Title=@rTitle AND OrgId=@rOrgId AND ClassId=@rClassId AND SubjectId=@rSubjectId)
			BEGIN
			select -102 as Result
			RETURN
		END 
	
		If Exists(select Id from sAcademic.tTopicMaster where Number=@rNumber AND OrgId=@rOrgId AND ClassId=@rClassId AND SubjectId=@rSubjectId)
			BEGIN
			select -103 as Result
			RETURN
		END 
	END
	ELSE
	BEGIN
		If  Exists(select Id from sAcademic.tTopicMaster where Title=@rTitle AND OrgId=@rOrgId AND ClassId=@rClassId AND SubjectId=@rSubjectId AND Id<>@rId)
		Begin
			select -102 as Result
			RETURN
		End
		If  Exists(select Id from sAcademic.tTopicMaster where Number=@rNumber AND OrgId=@rOrgId AND ClassId=@rClassId AND SubjectId=@rSubjectId AND Id<>@rId)
		Begin
			select -103 as Result
			RETURN
		End

	END
	
	
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAcademic.tTopicMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sAcademic.tTopicMaster
		(
			Id,
			Number,
			Title,
			SubjectId,
			ClassId,
			OrgId,
			CreatedUserId,
			CreatedDateTime,
			----added by megha for 0024270
			IsObsolete
		)
	VALUES
		(
			@lNextNumber,
			@rNumber,
			@rTitle,
			@rSubjectId,
			@rClassId,
			@rOrgId,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rIsObsolete
		)
		    SELECT 1 AS Result
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sAcademic.tTopicMaster
	    SET
			Number=@rNumber,
			Title=@rTitle,
			SubjectId=@rSubjectId,
			ClassId=@rClassId,
			OrgId=@rOrgId,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate(),
			IsObsolete = @rIsObsolete
	      
	      WHERE Id = @rId
	      SELECT 11 AS Result
	 END  	

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


GO

ALTER PROCEDURE [sAcademic].[pTopicMasterGet]

	 @rId int,
	 @rOrgId smallint,
	 @rClassId int,
	 @rSubjectId int,
	 @rEmployeeId bigint,
	 @rSourceTypeId smallint = 0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	IF(@rSourceTypeId = 0)
	BEGIN
		SELECT 
				DISTINCT TM.Id,
				TM.Number,
				TM.Title,
				TM.OrgId,
				TM.ClassId,
				TM.SubjectId,
				TM.CreatedUserId,
				TM.CreatedDateTime,
				CM.DisplayTitle AS ClassName,
				SM.Title AS SubjectName,
				CM.OrderIndex,
				SM.OrderIndex,
				--added by megha for 0024270
				ISNULL(TM.IsObsolete,0) AS IsObsolete,
				'' As StatusMessage
		FROM 
				sAcademic.tTopicMaster TM
				INNER JOIN sSetup.tClassMaster CM ON CM.Id = TM.ClassId
				INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = TM.SubjectId
				LEFT JOIN sAcademic.vTeacherSubjectDivision vTSD ON vTSD.ClassId = TM.ClassId 			
				--AND vTSD.SubjectId = TM.SubjectId 
				AND vTSD.EmployeeId = @rEmployeeId
		WHERE 
			(TM.OrgId=@rOrgId)
			AND ((TM.Id = @rId) OR (@rId = 0))
			AND ((TM.ClassId = @rClassId) OR (@rClassId = 0))
			AND ((TM.SubjectId = @rSubjectId) OR (@rSubjectId = 0))
			--AND ((vTSD.EmployeeId = @rEmployeeId) OR (vTSD.EmployeeId = 0))
			--ORDER BY CM.OrderIndex
		ORDER BY CM.OrderIndex,SM.OrderIndex,TM.Number ASC
	END
	ELSE IF (@rSourceTypeId = 95)
	BEGIN
		SELECT 
				DISTINCT TM.Id,
				TM.Number,
				TM.Title,
				TM.OrgId,
				TM.ClassId,
				TM.SubjectId,
				TM.CreatedUserId,
				TM.CreatedDateTime,
				CM.DisplayTitle AS ClassName,
				SM.Title AS SubjectName,
				CM.OrderIndex,
				SM.OrderIndex,
				ISNULL(TM.IsObsolete,0) AS IsObsolete,
				'' As StatusMessage
		FROM 
				sAcademic.tTopicMaster TM
				INNER JOIN sSetup.tClassMaster CM ON CM.Id = TM.ClassId
				INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = TM.SubjectId
				INNER JOIN sAcademic.vTeacherSubjectDivision vTSD ON vTSD.ClassId = TM.ClassId AND vTSD.SubjectId = TM.SubjectId 
				AND vTSD.EmployeeId = @rEmployeeId
		WHERE 
			(TM.OrgId=@rOrgId)
			AND ((TM.Id = @rId) OR (@rId = 0))
			AND ((TM.ClassId = @rClassId) OR (@rClassId = 0))
			AND ((TM.SubjectId = @rSubjectId) OR (@rSubjectId = 0))
		ORDER BY CM.OrderIndex,SM.OrderIndex,TM.Number ASC
	END
END
GO
PRINT N'Altering Procedure [sAlert].[pEmployeeBiometricLastOutTimeGet]...';


GO

ALTER PROCEDURE [sAlert].[pEmployeeBiometricLastOutTimeGet]
	@rTemplate nvarchar(max)='',
	@rSubject nvarchar(100)='',
	@rOrgId int,
	@rOrgGroupId int,
	@rIntervalTime int=0,
	@rToDateTime dateTime=null,
	@rFromDateTime DateTime=null
 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY	
		BEGIN TRANSACTION 
			if object_id('tempdb..#tShift') is not null
			BEGIN
				DROP TABLE #tShift
			END
			CREATE TABLE #tShift(
					ShiftCode int NOT NULL,
					OutTimeAlertTime time not NUll
				)
			insert #tShift
			Select 
				ShiftCode, 
				CAST(OutTimeAlertTime AS Time)
				--case When DATEDIFF(MINUTE,CAST(OutTimeAlertTime AS Time),cast([sCommon].[fGetDate]() as Time)) < @rIntervalTime then DATEDIFF(MINUTE,CAST(OutTimeAlertTime AS Time),cast([sCommon].[fGetDate]() as Time)) else @rIntervalTime end 
			  FROM sBiometric.tShiftMasterCloud
			where  ((OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))  
			AND IsOutTimeAlertTime=1
			--AND CAST(OutTimeAlertTime AS Time)<=cast([sCommon].[fGetDate]() as Time)
			--AND CAST(OutTimeAlertTime AS Time) > CAST(DATEADD(minute,-(@rIntervalTime),[sCommon].[fGetDate]()) AS Time)
			AND CAST(OutTimeAlertTime AS Time)<cast(@rToDateTime as Time)
			AND CAST(OutTimeAlertTime AS Time) >= CAST(@rFromDateTime AS Time)

			declare @lcount int=(SELECT COUNT(ShiftCode) FROM #tShift)
	 
			--select * from #tShift
			if object_id('tempdb..#tTable') is not null
			BEGIN
				DROP TABLE #tTable
			END
			CREATE TABLE #tTable(
						SourceId bigint NOT NULL,
						In_Out_Time [datetime] NOT NULL,
						SourceTypeId int NOT NULL,
						OutTimeAlertTime time NOT NULL,
						CreatedDateTime [datetime] NOT NULL
					)
			if(@lcount>0)
			BEGIN
				insert into #tTable
				select SourceId,MAX(In_Out_Time),SourceTypeId,tempShift.OutTimeAlertTime,Max(CreatedDateTime) 
				from [sBiometric].[tCloudTransactionData] CDT 
				inner join #tShift tempShift ON tempShift.ShiftCode=CDT.ShiftCode
				WHERE Attn_Dt=CONVERT(date,[sCommon].[fGetDate]())  AND SourceTypeId=95 Group by SourceId,SourceTypeId,tempShift.OutTimeAlertTime
			END

			--select * from #tTable

			SELECT 
				EM.MobileNumber AS MobileNo,	
				EM.CompanyEmail AS EmailId,
				replace (
				replace(@rTemplate,'[EmployeeName]',EM.EmployeeName),
				'[TimeStamp]',ISNULL(Convert(varchar,temp.In_Out_Time,108),''))
				 AS MsgText,
				@rSubject AS Subject,
				95 AS ReceiverSourceTypeId,
				EM.EmployeeId AS ReceiverSourceId,
				EM.EmployeeName AS EmployeeName,
				ISNULL(EC.WhatsAppContactNo,'') AS WhatsAppContactNo,
				95 AS SourceTypeId,
				EM.EmployeeId AS SourceId,
				EM.OrgId,
				OM.OrgGroupId,
				OM.DisplayTitle AS OrganizationTitle
			FROM 
				#tTable temp
				Inner join sHrm.vEmployeeCommonDetail EM ON temp.SourceId=EM.EmployeeId
				LEFT JOIN sHrm.tEmployeeCommunications EC ON EC.EmployeeId = EM.EmployeeId
				INNER JOIN sSetup.tOrganizationMaster OM ON EM.OrgID = OM.Id
			WHERE
				--temp.OutTimeAlertTime <= CAST([sCommon].[fGetDate]() AS Time)
				--AND temp.OutTimeAlertTime > CAST(DATEADD(minute,-(@rIntervalTime),[sCommon].[fGetDate]()) AS Time)
				temp.OutTimeAlertTime < cast(@rToDateTime as Time)
				AND temp.OutTimeAlertTime >= Cast(@rFromDateTime As Time)
				AND EM.OrgID =@rOrgId

			DROP TABLE #tTable
			DROP TABLE #tShift
		COMMIT TRANSACTION
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
END
GO
PRINT N'Altering Procedure [sAlert].[pStudentBiometricLastOutTimeGet]...';


GO


ALTER PROCEDURE [sAlert].[pStudentBiometricLastOutTimeGet]
	@rTemplate nvarchar(max)='',
	@rSubject nvarchar(100)='',
	@rOrgId int,
	@rOrgGroupId int,
	@rIntervalTime int=0,
	@rToDateTime dateTime,
	@rFromDateTime DateTime
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY	
		BEGIN TRANSACTION 
			if object_id('tempdb..#tShift') is not null
			BEGIN
				DROP TABLE #tShift
			END
			CREATE TABLE #tShift(
					ShiftCode int NOT NULL,
					OutTimeAlertTime time not NUll,
					LastOutAlertBasedOnId int not NUll
				)

			insert #tShift
			Select 
				ShiftCode,
				 case when LastOutAlertBasedOnId=3 THEN 
				 --case When DATEDIFF(MINUTE,CAST(EndTime AS Time),cast([sCommon].[fGetDate]() as Time)) < @rIntervalTime THEN CAST(DATEADD(minute,-(GraceBefore),EndTime) AS Time) else  CAST(DATEADD(minute,-(@rIntervalTime),[sCommon].[fGetDate]()) AS Time) end 
				 case When DATEDIFF(MINUTE,CAST(EndTime AS Time),cast(@rToDateTime as Time)) < DATEDIFF(MINUTE,CAST(@rFromDateTime AS Time),cast(@rToDateTime as Time))  THEN CAST(DATEADD(minute,-(GraceBefore),EndTime) AS Time) else  CAST(@rFromDateTime AS Time) end 
				 else  CAST(OutTimeAlertTime AS Time) end,
				 isnull(LastOutAlertBasedOnId,1)
				--case When DATEDIFF(MINUTE,CAST(@rIntervalTime AS Time),cast([sCommon].[fGetDate]() as Time)) < @rIntervalTime then DATEDIFF(MINUTE,CAST(OutTimeAlertTime AS Time),cast([sCommon].[fGetDate]() as Time)) else @rIntervalTime end 
			FROM sBiometric.tShiftMasterCloud
			where  ((OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))  
			AND IsOutTimeAlertTime=1
			AND (
			 ( (LastOutAlertBasedOnId=1 OR LastOutAlertBasedOnId=2) AND CAST(OutTimeAlertTime AS Time)<cast(@rToDateTime as Time)
			AND CAST(OutTimeAlertTime AS Time) > CAST(@rFromDateTime AS Time)) 
			OR 
			(LastOutAlertBasedOnId=3 AND CAST(DATEADD(minute,-@rIntervalTime,EndTime) AS Time)<cast(@rToDateTime as Time)
			AND CAST(OutTimeAlertTime AS Time) > CAST(@rFromDateTime AS Time))
			)
			--AND (
			-- ( (LastOutAlertBasedOnId=1 OR LastOutAlertBasedOnId=2) AND CAST(OutTimeAlertTime AS Time)<cast([sCommon].[fGetDate]() as Time)
			--AND CAST(OutTimeAlertTime AS Time) > CAST(DATEADD(minute,-(@rIntervalTime),[sCommon].[fGetDate]()) AS Time)) 
			--OR 
			--(LastOutAlertBasedOnId=3 AND CAST(DATEADD(minute,-@rIntervalTime,EndTime) AS Time)<cast([sCommon].[fGetDate]() as Time)
			--AND CAST(OutTimeAlertTime AS Time) > CAST(DATEADD(minute,-(@rIntervalTime),[sCommon].[fGetDate]()) AS Time))
			--)

			--select * from #tShift
			declare @lcount int=(SELECT COUNT(ShiftCode) FROM #tShift)

			if object_id('tempdb..#tTable') is not null
			BEGIN
				DROP TABLE #tTable
			END
			CREATE TABLE #tTable(
				SourceId bigint NOT NULL,
				In_Out_Time [datetime] NOT NULL,
				SourceTypeId int NOT NULL,
				OutTimeAlertTime time NOT NULL,
				CreatedDateTime [datetime] NOT NULL,
				LastOutAlertBasedOnId int NOT NULL,
				ShiftCode int NOT NULL
			)
			if(@lcount>0)
			BEGIN
				insert into #tTable
				select SourceId,MAX(In_Out_Time),SourceTypeId,tempShift.OutTimeAlertTime,Max(CreatedDateTime),tempShift.LastOutAlertBasedOnId,CDT.ShiftCode
				from [sBiometric].[tCloudTransactionData] CDT 
				inner join #tShift tempShift ON tempShift.ShiftCode=CDT.ShiftCode
				WHERE Attn_Dt=CONVERT(date,[sCommon].[fGetDate]())  AND SourceTypeId=2003 Group by SourceId,SourceTypeId,tempShift.OutTimeAlertTime,tempShift.LastOutAlertBasedOnId,CDT.ShiftCode
			End
			--select * from #tTable

			SELECT 
				SC.ParentContactNo AS MobileNo,	
				SC.ParentEmail AS EmailId,
				replace (
				replace(@rTemplate,'[StudentName]',SC.Name),
				'[TimeStamp]',ISNULL(Convert(varchar,temp.In_Out_Time,108),''))
				 AS MsgText,
				@rSubject AS Subject,
				2003 AS ReceiverSourceTypeId,
				SC.StudentId AS ReceiverSourceId,
				SC.Name AS StudentName,
				SC.Code,
				ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo,
				2003 AS SourceTypeId,
				SC.StudentId AS SourceId,
				SC.OrgId,
				OM.OrgGroupId,
				OM.DisplayTitle AS OrganizationTitle


			FROM 
				#tTable temp
				Inner Join sBiometric.tShiftMasterCloud SMC on SMC.ShiftCode=temp.ShiftCode
				Inner join sStudent.vStudentCommunication SC ON temp.SourceId=SC.StudentId AND SC.IsActiveBatch=1
				INNER JOIN sSetup.tOrganizationMaster OM ON SC.OrgID = OM.Id
			WHERE
			((temp.LastOutAlertBasedOnId=1 ) AND temp.OutTimeAlertTime <= CAST(@rToDateTime AS Time)
				AND temp.OutTimeAlertTime > CAST(@rFromDateTime AS Time)
				
				OR( temp.LastOutAlertBasedOnId=2 AND CAST(DATEADD(minute,-(SMC.GraceBefore),SMC.EndTime) AS Time) <= CAST(temp.In_Out_Time  AS Time)
				AND CAST(temp.In_Out_Time AS Time) < CAST(@rToDateTime AS Time)
				)
				OR 
				(  
					(temp.LastOutAlertBasedOnId=3 
					AND (CAST(temp.In_Out_Time  AS Time)  >= CAST(temp.OutTimeAlertTime AS Time) 
					AND CAST(temp.In_Out_Time  AS Time)  <= CAST([sCommon].[fGetDate]() AS Time)))
					))

				--((temp.LastOutAlertBasedOnId=1 ) AND temp.OutTimeAlertTime <= CAST([sCommon].[fGetDate]() AS Time)
				--AND temp.OutTimeAlertTime > CAST(DATEADD(minute,-(@rIntervalTime),[sCommon].[fGetDate]()) AS Time)
				
				--OR( temp.LastOutAlertBasedOnId=2 AND CAST(DATEADD(minute,-(SMC.GraceBefore),SMC.EndTime) AS Time) <= CAST(temp.In_Out_Time  AS Time)
				--AND CAST(temp.In_Out_Time AS Time) < CAST([sCommon].[fGetDate]() AS Time)
				--)
				--OR 
				--(  
				--	(temp.LastOutAlertBasedOnId=3 
				--	AND (CAST(temp.In_Out_Time  AS Time)  >= CAST(temp.OutTimeAlertTime AS Time) 
				--	AND CAST(temp.In_Out_Time  AS Time)  <= CAST([sCommon].[fGetDate]() AS Time)))
				--	))
				AND SC.OrgID =@rOrgId
				AND SC.StatusId = 1

			DROP TABLE #tTable
			DROP TABLE #tShift
		COMMIT TRANSACTION
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
END
GO
PRINT N'Altering Procedure [sAlert].[pStudentBiometricFirstInTimeGet]...';


GO

ALTER PROCEDURE [sAlert].[pStudentBiometricFirstInTimeGet]
	@rTemplate nvarchar(max)='',
	@rSubject nvarchar(100)='',
	@rOrgId int,
	@rIntervalTime int=0,
	@rToDateTime dateTime,
	@rFromDateTime DateTime

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY	
		BEGIN TRANSACTION 
		declare @lDateTimeNow datetime=[sCommon].[fGetDate]()
		declare @lLastStudentFirstInAlertSendTime datetime
		
			if object_id('tempdb..#tTable') is not null
			BEGIN
				DROP TABLE #tTable
			END
			CREATE TABLE #tTable(
					SourceId bigint NOT NULL,
					In_Out_Time [datetime] NOT NULL,
					SourceTypeId int NOT NULL,
					CreatedDateTime [datetime] NOT NULL,
					AutoId bigint not null,

				)
			insert into #tTable
			select CDT.SourceId,min(CDT.In_Out_Time),CDT.SourceTypeId,min(CDT.CreatedDateTime),min(CDT.Autoid)
			from [sBiometric].[tCloudTransactionData] CDT
			inner join sBiometric.tShiftMasterCloud SMC ON SMC.ShiftCode=CDT.ShiftCode
			WHERE CDT.Attn_Dt=CONVERT(date,@lDateTimeNow)  AND CDT.SourceTypeId=2003
				AND (isnull(SMC.IsStopInTimeAlertTime,0)=0 OR (SMC.IsStopInTimeAlertTime=1 
				AND CAST(SMC.StopInTimeAlertTime as Time)>=CAST(@rFromDateTime AS Time)
				AND  CAST(SMC.StopInTimeAlertTime as Time)>=CAST(CDT.In_Out_Time AS Time)))
			 Group by CDT.SourceId,CDT.SourceTypeId
	
			--select * from #tTable
			
			DECLARE @AlertUniqueId uniqueidentifier = NEWID();
			
			Insert Into sBiometric.tTempBiometricAlertData
			SELECT 
				SC.ParentContactNo AS MobileNo,	
				SC.ParentEmail AS EmailId,
				replace (
				replace (
				replace (
				replace(@rTemplate,'[StudentName]',SC.Name),
				'[TimeStamp]',ISNULL(Convert(varchar,temp.In_Out_Time,108),'')),
				'[PresentTime]',ISNULL(Convert(varchar,temp.In_Out_Time,108),'')),
				'[PresentDate]',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''))
				 AS MsgText,
				@rSubject AS Subject,
				2003 AS ReceiverSourceTypeId,
				SC.StudentId AS ReceiverSourceId,
				SC.Name AS StudentName,
				SC.Code AS Code,
				ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo,
				2003 AS SourceTypeId,
				SC.StudentId AS SourceId,
				SC.OrgId,
				OM.OrgGroupId,
				ISNULL(Convert(varchar,temp.In_Out_Time,108),'') as Time,
				OM.DisplayTitle AS OrganizationTitle,
				temp.AutoId,
				@rFromDateTime,
				@rToDateTime,
				sCommon.fGetDate(),
				129,
				@AlertUniqueId
			FROM 
				#tTable temp
				Inner join sStudent.vStudentCommunication SC ON temp.SourceId=SC.StudentId AND SC.IsActiveBatch=1
				INNER JOIN sSetup.tOrganizationMaster OM ON SC.OrgID = OM.Id
			WHERE
				temp.CreatedDateTime < @rToDateTime
				AND temp.CreatedDateTime >= @rFromDateTime
				AND SC.OrgID =@rOrgId
				AND SC.StatusId = 1

			SELECT 
				MobileNo AS MobileNo,	
				EmailId AS EmailId,
				MsgText AS MsgText,
				Subject AS Subject,
				2003 AS ReceiverSourceTypeId,
				ReceiverSourceId AS ReceiverSourceId,
				StudentName AS StudentName,
				Code AS Code,
				WhatsAppContactNo AS WhatsAppContactNo,
				2003 AS SourceTypeId,
				SourceId AS SourceId,
				OrgId,
				OrgGroupId,
				 Time,
				 OrganizationTitle
			FROM 
				sBiometric.tTempBiometricAlertData
			WHERE
			   AlertUniqueId=@AlertUniqueId


			DROP TABLE #tTable
		COMMIT TRANSACTION
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH

END
GO
PRINT N'Altering Procedure [sBiometric].[pMonthTransProcess]...';


GO
 

--ALTER PROCEDURE [sBiometric].[pMonthTransProcess]

--AS
--SET NOCOUNT ON

--BEGIN
--	CREATE TABLE #tTable(
--	Id bigint identity,
--	[SourceId] [bigint] NOT NULL,
--	[In_Out_Time] [datetime] NOT NULL,
--	[ShiftCode] [int] NOT NULL,
--	[Attn_Dt] [date] NOT NULL,
--	[Mode] [nvarchar](10) NOT NULL,
--	[CreatedDateTime] [datetime] NOT NULL,
--	[DeviceIP] [nvarchar](20) NOT NULL,
--	[EntryMode] [tinyint] NOT NULL,
--	[PunchId] [nvarchar](50) NOT NULL,
--	[TransactionId] [bigint] NOT NULL,
--	[SourceTypeId] [smallint] NULL,
--	[IsProcessed] [bit] NULL
--)

--DECLARE @lPrevAttn_Dt date = ''
--DECLARE @lPrevSourceId bigint = 0
--DECLARE @lPrevSourceTypeId smallint = 0

--IF(DAY(sCommon.fGetDate()) > 10)
--BEGIN
--	INSERT INTO #tTable
--	SELECT [SourceId],[In_Out_Time],[ShiftCode],[Attn_Dt] ,[Mode],[CreatedDateTime],[DeviceIP],[EntryMode],[PunchId],[TransactionId],[SourceTypeId],[IsProcessed] 
--	FROM [sBiometric].[tCloudTransactionData] WHERE MONTH(Attn_Dt) = MONTH(sCommon.fGetDate()) AND YEAR(Attn_Dt) = YEAR(sCommon.fGetDate()) AND IsProcessed = 0
--END
--ELSE
--BEGIN
--	INSERT INTO #tTable
--	SELECT [SourceId],[In_Out_Time],[ShiftCode],[Attn_Dt] ,[Mode],[CreatedDateTime],[DeviceIP],[EntryMode],[PunchId],[TransactionId],[SourceTypeId],[IsProcessed] 
--	 FROM [sBiometric].[tCloudTransactionData] WHERE YEAR(Attn_Dt) = YEAR(sCommon.fGetDate()) AND MONTH(Attn_Dt) IN (MONTH(sCommon.fGetDate()),MONTH(sCommon.fGetDate() - 1)) AND IsProcessed = 0
--END

--	SELECT * FROM #tTable
--	DECLARE @lCount int = 1
--	DECLARE @lTotal int = (SELECT COUNT(Id) FROM #tTable)
--	WHILE @lCount <= @lTotal
--	BEGIN
--		DECLARE @lQuery nvarchar(max) = ''	
--		DECLARE @lAttn_Dt date = (SELECT Attn_Dt FROM #tTable WHERE Id = @lCount)
--		DECLARE @lSourceId bigint = (SELECT SourceId FROM #tTable WHERE Id = @lCount)
--		DECLARE @lSourceTypeId smallint = (SELECT SourceTypeId FROM #tTable WHERE Id = @lCount)
--		DECLARE @lTransactionId bigint = (SELECT TransactionId FROM #tTable WHERE Id = @lCount)

--		IF(@lPrevAttn_Dt = @lAttn_Dt AND @lPrevSourceId = @lSourceId AND @lPrevSourceTypeId = @lSourceTypeId)
--		BEGIN
--			print('same employee')
--			UPDATE sBiometric.tCloudTransactionData SET IsProcessed = 1 WHERE TransactionId = @lTransactionId
--		END
--		ELSE
--		BEGIN
--			DECLARE @lCode int = (SELECT ISNULL(MAX(EmpCode),0) + 1 FROM sBiometric.tMonthTrans)
--			IF EXISTS (SELECT 1 FROM sBiometric.tMonthTrans WHERE EmployeeId = @lSourceId AND SourceTypeId = @lSourceTypeId)
--			BEGIN
--				SET @lCode = (SELECT TOP 1 EmpCode FROM sBiometric.tMonthTrans WHERE EmployeeId = @lSourceId AND SourceTypeId = @lSourceTypeId)
--			END					
--			DECLARE @lShift varchar(25) = (SELECT ShiftName FROM sBiometric.tShiftMasterCloud WHERE ShiftCode IN (SELECT ShiftCode FROM #tTable WHERE Id = @lCount))
--			DECLARE @lShiftStartTime datetime = (SELECT StartTime FROM sBiometric.tShiftMasterCloud WHERE ShiftCode IN (SELECT ShiftCode FROM #tTable WHERE Id = @lCount))
--			DECLARE @lShiftEndTime datetime = (SELECT EndTime FROM sBiometric.tShiftMasterCloud WHERE ShiftCode IN (SELECT ShiftCode FROM #tTable WHERE Id = @lCount))
--			DECLARE @lMinHoursHalfDay time = CAST(CAST((SELECT MinHrsHalfDay FROM sBiometric.tShiftMasterCloud WHERE ShiftCode IN (SELECT ShiftCode FROM #tTable WHERE Id = @lCount)) AS nvarchar) AS time)
--			DECLARE @lMinHoursFullDay time = CAST(CAST((SELECT MinHrsFullDay FROM sBiometric.tShiftMasterCloud WHERE ShiftCode IN (SELECT ShiftCode FROM #tTable WHERE Id = @lCount)) AS nvarchar) AS time)
--			DECLARE @lIn time = CONVERT(time,(SELECT MIN(In_Out_Time) FROM sBiometric.tCloudTransactionData WHERE Attn_Dt = @lAttn_Dt AND SourceId = @lSourceId AND SourceTypeId = @lSourceTypeId))
--			DECLARE @lOut time = CASE WHEN (SELECT COUNT(In_Out_Time) FROM sBiometric.tCloudTransactionData WHERE Attn_Dt = @lAttn_Dt AND SourceId = @lSourceId AND SourceTypeId = @lSourceTypeId) > 1 THEN CONVERT(time,(SELECT MAX(In_Out_Time) FROM #tTable WHERE Attn_Dt = @lAttn_Dt AND SourceId = @lSourceId AND SourceTypeId = @lSourceTypeId))
--									ELSE '00:00' END

--			DECLARE @lTotalTime varchar(10) = CASE WHEN @lOut <> '00:00' THEN (SELECT CONVERT(varchar(10), DATEADD(minute, DATEDIFF(minute, @lIn, @lOut), 0), 114))	
--												ELSE '00:00' END

--			DECLARE @lEarlyBy varchar(10) = '00:00'
--			DECLARE @lLateBy varchar(10) = '00:00'
--			DECLARE @lOverTime varchar(10) = ''
--			DECLARE @lStatus varchar(10) = ''

--			--Add by Nimesh MantisId:0027752
--			--Start
--			IF(DATEDIFF(minute, @lShiftStartTime,@lIn) > 0 AND @lIn<>'00:00')
--			BEGIN
--				--SET @lLateBy = '00:00'
--				SET @lLateBy = (SELECT CONVERT(varchar(10), DATEADD(minute, DATEDIFF(minute, @lShiftStartTime, @lIn), 0), 114))
--			END
--			IF(DATEDIFF(minute,@lShiftEndTime, @lOut) < 0 AND @lOut<> '00:00')
--			BEGIN
--				--SET @lEarlyBy = '00:00'
--				SET @lEarlyBy = (SELECT CONVERT(varchar(10), DATEADD(minute, DATEDIFF(minute, @lOut, @lShiftEndTime), 0), 114))
--			END
--			--End

--			IF(DATEDIFF(minute, @lShiftEndTime,@lOut) < 0)
--			BEGIN
--				SET @lOverTime = '00:00'
--			END
--			ELSE
--			BEGIN
--				SET @lOverTime  = CASE WHEN @lOut <> '00:00' THEN (SELECT CONVERT(varchar(10), DATEADD(minute, DATEDIFF(minute, @lShiftEndTime, @lOut), 0), 114))
--												ELSE '00:00' END
--			END			

--			IF(CAST(@lTotalTime AS TIME) >= @lMinHoursFullDay)
--			BEGIN
--				SET @lStatus = 'P'
--			END
--			IF(CAST(@lTotalTime AS TIME) >= @lMinHoursHalfDay AND CAST(@lTotalTime AS TIME) < @lMinHoursFullDay)
--			BEGIN
--				SET @lStatus = 'HD'
--			END
--			IF(CAST(@lTotalTime AS TIME) < @lMinHoursHalfDay)
--			BEGIN
--				SET @lStatus = 'LH'
--			END
--			IF (@lOut = '00:00' AND @lIn <> '00:00')
--			BEGIN
--				SET @lStatus = 'E'
--			END		
			
--			 --Uncomment this for testing purposes
--			--PRINT('In Time: ' + CONVERT(VARCHAR(5),@lIn,108))
--			--PRINT('Out Time: ' + CONVERT(VARCHAR(5),@lOut,108))
--			--PRINT('Total Time : ' + CONVERT(VARCHAR(5),@lTotalTime,108))
--			--PRINT('Overtime : ' + CONVERT(VARCHAR(5),@lOverTime,108))
--			--PRINT('Min Hours Half Day : ' + CONVERT(VARCHAR(5),@lMinHoursHalfDay,108))
--			--PRINT('Min Hours Full Day : ' + CONVERT(VARCHAR(5),@lMinHoursFullDay,108))
--			--PRINT('EarlyBy : ' + CONVERT(VARCHAR(5),@lEarlyBy,108))
--			--PRINT('LateBy : ' + CONVERT(VARCHAR(5),@lLateBy,108))
--			--PRINT('Status : ' + CONVERT(VARCHAR(5),@lStatus,108))
--			--BREAK


--			DECLARE @lDay nvarchar(10) = (SELECT DAY(IN_Out_Time) FROM #tTable WHERE Id = @lCount)
--			SET @lDay = (SELECT CASE WHEN @lDay BETWEEN 0 AND 9 THEN RIGHT('0' + CAST(@lDay AS VARCHAR(2)), 2) ELSE CAST(@lDay AS NVARCHAR(10)) END)
--			DECLARE @lMonthTransAttn_DtTemp datetime = (select cast((cast(YEAR(@lAttn_Dt) as varchar(255)) + '-' + cast(MONTH(@lAttn_Dt) as varchar(255)) + '-' + '01') as datetime))

--			DECLARE @lMonthTransAttn_Dt varchar(20) = convert(varchar(20), @lMonthTransAttn_DtTemp, 20)
--			PRINT(@lMonthTransAttn_Dt)

--			IF NOT EXISTS(SELECT 1 FROM sBiometric.tMonthTrans WHERE EmployeeId = @lSourceId AND SourceTypeId = @lSourceTypeId AND Attn_Dt = @lMonthTransAttn_Dt)
--			BEGIN
--				--Insert 
--				INSERT INTO sBiometric.tMonthTrans(EmpCode,EmployeeId,Attn_Dt,
--				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,
--				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_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,
--				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,
--				[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,SourceTypeId
--				) 
--				VALUES(@lCode,@lSourceId,@lMonthTransAttn_Dt,
--				'XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX',
--				'00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00',
--				'00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00',
--				'00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00',
--				'00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00',
--				'00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00',
--				'XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX',
--				'00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00',
--				0,0,0,0,'',0,'','','',0,0,0,0,0,0,0,0,0,0,0,0,@lSourceTypeId)
--			END
--			 --Update
--			SET @lQuery = 'UPDATE sBiometric.tMonthTrans
--			SET D'+CAST(@lDay AS VARCHAR)+'_IN = '''+CONVERT(VARCHAR(5),@lIn,108)+''',
--			D'+CAST(@lDay AS VARCHAR)+'_OUT = '''+CONVERT(VARCHAR(5),@lOut,108)+''',
--			D'+CAST(@lDay AS VARCHAR)+'_E = '''+CONVERT(VARCHAR(5),@lEarlyBy,108)+''',
--			D'+CAST(@lDay AS VARCHAR)+'_L = '''+CONVERT(VARCHAR(5),@lLateBy,108)+''',
--			D'+CAST(@lDay AS VARCHAR)+'_O = '''+CONVERT(VARCHAR(5),@lOverTime,108)+''',
--			D'+CAST(@lDay AS VARCHAR)+'_T = '''+CONVERT(VARCHAR(5),@lTotalTime,108)+''',
--			D'+CAST(@lDay AS VARCHAR)+' = '''+CONVERT(VARCHAR(5),@lStatus,108)+''',
--			D'+CAST(@lDay AS VARCHAR)+'_S = '''+CAST(@lShift AS VARCHAR)+'''
--			WHERE EmployeeId = '+CAST(@lSourceId AS VARCHAR) + ' AND Attn_Dt = ''' + CAST(@lMonthTransAttn_Dt AS VARCHAR) + ''' AND SourceTypeId = '+CAST(@lSourceTypeId AS VARCHAR)

--			PRINT ('Query : '+ @lQuery)

--			EXEC (@lQuery)			
			
			 
--			CREATE TABLE #tSummary (PresentStatus varchar(10), PresentStatusCount int)
--			INSERT INTO #tSummary
--			SELECT [Status],COUNT(*)
--			AS [Count] FROM (
--				SELECT 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
--				FROM sBiometric.tMonthTrans WHERE EmployeeId = @lSourceId AND CAST(Attn_Dt AS DATE) = @lMonthTransAttn_Dt AND SourceTypeId = @lSourceTypeId ) as Temp
--				UNPIVOT
--				(
--					[Status]   
--				   for [Dd] 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)
--				) as [unpivoted] 	
--				GROUP BY
--					[Status]
--				HAVING 
--					COUNT(*) > 0
			
--			--SELECT * FROM #tSummary
--			--BREAK

--			DECLARE @lTotal_HalfDay int = (SELECT ISNULL(SUM(PresentStatusCount),0) FROM #tSummary WHERE PresentStatus IN ('HD'))
--			DECLARE @lTotal_Present float = (SELECT ISNULL(SUM(PresentStatusCount),0) FROM #tSummary WHERE PresentStatus IN ('P')) + @lTotal_HalfDay*0.5
--			DECLARE @lTotal_Absent float = (SELECT ISNULL(SUM(PresentStatusCount),0) FROM #tSummary WHERE PresentStatus IN ('A','XX','LH')) + @lTotal_HalfDay*0.5
--			DECLARE @lTotal_WeekOff int = (SELECT ISNULL(SUM(PresentStatusCount),0) FROM #tSummary WHERE PresentStatus IN ('W','PW'))
--			DECLARE @lTotal_Holiday int = (SELECT ISNULL(SUM(PresentStatusCount),0) FROM #tSummary WHERE PresentStatus IN ('H','PH'))

--			DECLARE @lTotal_Hours varchar(50) = (SELECT CAST(t.time_sum/3600 AS VARCHAR(10)) + ':'
--													 + CAST(t.time_sum%3600/60 AS VARCHAR(10)) 
--												FROM
--												(
--													SELECT SUM(DATEDIFF(S, '00:00', [Status])) AS time_sum FROM (
--													SELECT 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				
--													FROM sBiometric.tMonthTrans WHERE EmployeeId = @lSourceId AND CAST(Attn_Dt AS DATE) = @lMonthTransAttn_Dt AND SourceTypeId = @lSourceTypeId) as Temp
--													UNPIVOT
--													(
--														[Status]   
--														for [Dd] 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)
--													) as [unpivoted]				
--												) t)

--			DECLARE @lTotal_Early varchar(50) = (SELECT CAST(t.time_sum/3600 AS VARCHAR(10)) + ':'
--													 + CAST(t.time_sum%3600/60 AS VARCHAR(10)) 
--												FROM
--												(
--													SELECT SUM(DATEDIFF(S, '00:00', [Status])) AS time_sum FROM (
--													SELECT 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				
--													FROM sBiometric.tMonthTrans WHERE EmployeeId = @lSourceId AND CAST(Attn_Dt AS DATE) = @lMonthTransAttn_Dt AND SourceTypeId = @lSourceTypeId) as Temp
--													UNPIVOT
--													(
--														[Status]   
--														for [Dd] in (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)
--													) as [unpivoted]				
--												) t)

--			DECLARE @lTotal_Late varchar(50) = (SELECT CAST(t.time_sum/3600 AS VARCHAR(10)) + ':'
--													 + CAST(t.time_sum%3600/60 AS VARCHAR(10)) 
--												FROM
--												(
--													SELECT SUM(DATEDIFF(S, '00:00', [Status])) AS time_sum FROM (
--													SELECT 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				
--													FROM sBiometric.tMonthTrans WHERE EmployeeId = @lSourceId AND CAST(Attn_Dt AS DATE) = @lMonthTransAttn_Dt AND SourceTypeId = @lSourceTypeId) as Temp
--													UNPIVOT
--													(
--														[Status]   
--														for [Dd] 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)
--													) as [unpivoted]				
--												) t)

--			DECLARE @lTotal_OverTime varchar(50) = (SELECT CAST(t.time_sum/3600 AS VARCHAR(10)) + ':'
--													 + CAST(t.time_sum%3600/60 AS VARCHAR(10)) 
--												FROM
--												(
--													SELECT SUM(DATEDIFF(S, '00:00', [Status])) AS time_sum FROM (
--													SELECT 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				
--													FROM sBiometric.tMonthTrans WHERE EmployeeId = @lSourceId AND CAST(Attn_Dt AS DATE) = @lMonthTransAttn_Dt AND SourceTypeId = @lSourceTypeId) as Temp
--													UNPIVOT
--													(
--														[Status]   
--														for [Dd] in (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)
--													) as [unpivoted]				
--												) t)

--			UPDATE sBiometric.tMonthTrans SET [Tot_Attn] = @lTotal_Present,[Tot_Abs] = @lTotal_Absent,[Tot_WeekOFF] = @lTotal_WeekOff,
--			[Tot_Holiday] = @lTotal_Holiday,[TotalHour] = @lTotal_Hours,[Tot_HD] = @lTotal_HalfDay,[Tot_Early] = @lTotal_Early,[Tot_Late] = @lTotal_Late,
--			[Tot_OT] = @lTotal_OverTime
--			WHERE EmployeeId = @lSourceId AND CAST(Attn_Dt AS DATE) = @lMonthTransAttn_Dt AND SourceTypeId = @lSourceTypeId			
			
--			UPDATE sBiometric.tCloudTransactionData SET IsProcessed = 1 WHERE TransactionId = @lTransactionId

--			DROP TABLE #tSummary

--		END
			
--		SET @lPrevAttn_Dt = @lAttn_Dt
--		SET @lPrevSourceId = @lSourceId
--		SET @lPrevSourceTypeId = @lSourceTypeId
		

--		SET @lCount = @lCount + 1
--	END
--END
--GO
PRINT N'Altering Procedure [sCommunication].[pMyUpdateGet]...';


GO


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

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


IF(LEN(ISNULL(@rAppVersion,'')) > 0 AND LEN(ISNULL(@rAppVersion,'')) > 0)
BEGIN
	UPDATE sCommunication.tRegisteredUsers
	SET
		AppVersion = @rAppVersion,
		AppName = @rAppName,
		UpdatedDateTime = sCommon.fGetDate(),
		DeviceDetail = @rVersionNumber
	WHERE 
		DeviceToken = @rDeviceToken 
		AND OsTypeId = @rOSTypeId
		AND OrgId=@rOrgId AND UserId=@rUserId 
		AND UserSourceId=@rUserSourceId AND UserSourceTypeId = @rUserSourceTypeId
END
CREATE TABLE #Module (  
Id int,  
Title nvarchar(2000),  
IsNew bit )  
INSERT INTO #Module VALUES (1,'IsActiveCheck',CONVERT(bit,@lIsActive))  
INSERT INTO #Module VALUES (2,'IsOptimizeAppImageUpload',@lIsOptimizeAppImageUpload)  
INSERT INTO #Module VALUES (3,ISNULL(@lAlertRemark,''),1)  
INSERT INTO #Module VALUES (4,ISNULL(@lMobileAppModuleAutoSyncToken,0),1)  
INSERT INTO #Module VALUES (5,'Is Stop Application Access',@lIsStopApplicationAccess)  
INSERT INTO #Module VALUES (6,@lStudentCustomAlert,1)  
INSERT INTO #Module VALUES (20085,'Circular',0)  
INSERT INTO #Module VALUES (20088,'Query',0)  
INSERT INTO #Module VALUES (20099,'Blog',0)  
INSERT INTO #Module VALUES (20104,'News',0)  
INSERT INTO #Module VALUES (20172,'AssignTask',0)  
INSERT INTO #Module VALUES (20183,'Gallery',0)  
INSERT INTO #Module VALUES (20204,'Poll',0)  
INSERT INTO #Module VALUES (20093,'Assignment',0)  
INSERT INTO #Module VALUES (20209,'Activity',0)  
INSERT INTO #Module VALUES (20130,'Behaviour',0)  
INSERT INTO #Module VALUES (20180,'Result',0)  
INSERT INTO #Module VALUES (7,@lActiceClassBatchId,1)  
   
SELECT * FROM #Module  
   
--SELECT @lAssignmentStatus AS Assignment,@lCircularStatus AS Circular,@lPollStatus AS Poll,@lQueryStatus AS Query,  
--@lBlogStatus AS Blog,@lNewsStatus AS News,@lBehaviourStatus AS Behaviour,  
--@lActivityStatus AS Activity,@lResultStatus AS Result,@lAssignTaskStatus AS AssignTask,@lPhotoCategoryStatus AS Gallery  
  
END
GO
PRINT N'Altering Procedure [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, 
		'' AS Pickup,
		'' AS DRoppoint,
		'' AS PresentContactNo,
		ISNULL(SA.SUID,'') AS SUID,
		SA.ClassOrderIndex,
		SA.DivisionOrder,
		FS.OrderIndex,
		'' AS FatherContactNo,
		'' AS MotherContactNo
  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,
				FM.OrderIndex
			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,
				FM.OrderIndex
			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,
			isnull(SC.ParentContactNo,'') AS ParentContactNo,
			P.SUID,
			P.ClassOrderIndex,
			P.DivisionOrderIndex,
			'' AS FatherContactNo,
		    '' AS MotherContactNo
			
			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
			LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId =  VA.StudentId
			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,SC.ParentContactNo	,P.SUID,P.ClassOrderIndex,P.DivisionOrderIndex
			ORDER BY P.AcademicId
 
END
GO
PRINT N'Altering Procedure [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,
		@rOrgGroupId int = 0,
		@rOrgIds nvarchar(max) = '',
		@rReportType int=1,    
	    @rClassStatusId int=0,
		@rClassIds nvarchar(max) = '',
		@rDivisionIds nvarchar(max) = ''

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 	
	
	DECLARE @p as TempPendingFee

	IF(@rReportType=1)
	BEGIN
	
		INSERT INTO  @p 
	 
	SELECT 
	
		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,
	    RT.Pickup  AS Pickup,
		RT.DRoppoint As DRoppoint,
		SC.PresentContactNo,
		ISNULL(SA.SUID,'') AS SUID,
		SA.ClassOrderIndex,
		SA.DivisionOrder,
		FS.OrderIndex,
		--change by megha for 0027384
	    '' AS FatherContactNo,
		'' AS MotherContactNo
  FROM 
  
			 sStudent.vStudentAcademic SA
			 Left join [sStudent].[tStudentCommunication] SC ON SC.studentId=SA.studentId
			
		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,
				FM.OrderIndex
			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 (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			WHERE 
				(CAST(LEFT(SA1.OrgGroupBatchId, 4) AS int) = @rOrgGroupId OR @rOrgGroupId=0)
			    AND ((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='')
				AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
				AND ((SA1.Code=@rCode) OR (@rCode=''))
				AND (ISNULL(FS1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
				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,
				FM.OrderIndex
			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 = FS1.ClassId
			AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) 
			AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
			AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
			AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
		WHERE
				(CAST(LEFT(SA1.OrgGroupBatchId, 4) AS int) = @rOrgGroupId OR @rOrgGroupId=0)
		        AND ((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='')
				AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
				AND ((SA1.Code=@rCode) OR (@rCode=''))
				AND (ISNULL(FS1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
		) 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 (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
			WHERE	
				(CAST(LEFT(SA1.OrgGroupBatchId, 4) AS int) = @rOrgGroupId OR @rOrgGroupId=0)
				AND (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='')
				AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
				AND ((SA1.Code=@rCode) OR (@rCode=''))
		
				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,B.Title As Pickup,B1.Title As DRoppoint FROM sTransport.tAssignRoute AT 
    INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
    INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))
	Left JOIN sTransport.tBusRouteDestinationMaster BM1 ON BM1.Id=AT.DropDestinationId
    LEFT JOIN sTransport.tBusRouteMaster B1 ON B1.Id=BM1.BusRouteId AND  AT.SourceTypeId=2003 AND ((B1.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))
 ) RT
    ON RT.SourceId = SA.StudentId 
    AND ((SA.OrgGroupBatchId = RT.OrgGroupBatchId))
    AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
	WHERE	
			(CAST(LEFT(SA.OrgGroupBatchId, 4) AS int) = @rOrgGroupId OR @rOrgGroupId=0)
			AND ((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)))
			    )
		   AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
		   AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))	   
			Order by SA.RollNo
 
		SELECT
			@rBuilder1 AS Builder1,
			@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,
		    Pickup,
			DRoppoint,
			PresentContactNo,
			SUID,
			ClassOrderIndex,
			DivisionOrderIndex,
			'' AS FatherContactNo,
		    '' AS MotherContactNo
			FROM @p 
			
			GROUP By 
			OrgId,AcademicId,ReceiptBookId,DivisionId,BatchId,
			ClassDivision,RollNo, Name,Code,ReceiptBookTitle,OrgName,ReceiptOrderIndex,BatchName,Pickup,DRoppoint,PresentContactNo,SUID,ClassOrderIndex,DivisionOrderIndex,FatherContactNo,MotherContactNo
			ORDER BY AcademicId Desc
	END
	ELSE
	BEGIN
	
	INSERT INTO  @p 
	SELECT 
	
		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(FAS.FeeAmount,0)AS Amount,
		ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
		ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
		ISNULL(FAS.VariableAmount,0.00)AS FAAmount,
		ISNULL(FAS.DiscountAmount,0.00)AS DiscountAmount,
		ISNULL(FAS.AdditionalAmount,0.00)AS AdditionalAmount,
		ISNULL(FAS.PaidAmount,0) AS PaidAmount,
		ISNULL(FAS.ToPayAmount,0) AS PendingAmount,
		--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(FAS.Remark,'') AS Remark,
		FS.ReceiptBookId,
		--FS.FeeName,
		FM.Title AS FeeName, 
		FM.Code AS FeeCode,
		--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,
	    RT.Pickup  AS Pickup,
		RT.DRoppoint As DRoppoint,
		SC.PresentContactNo,
		ISNULL(SA.SUID,'') AS SUID,
		SA.ClassOrderIndex,
		SA.DivisionOrder,
		FM.OrderIndex,
		'' AS FatherContactNo,
		'' AS MotherContactNo
  FROM	 sStudent.vStudentAcademic SA
        INNER JOIN sFee.tFeeAllocationStudent FAS ON FAS.AcademicId = SA.AcademicId
		INNER JOIN sFee.tFeeSetup FS ON FS.ID=FAS.FeeSetupId	
		INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS.FeeId
		INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
		INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id		
		INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
		LEFT JOIN sStudent.tStudentCommunication SC	ON SC.StudentId = SA.StudentId 
		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,B.Title As Pickup,B1.Title As DRoppoint FROM sTransport.tAssignRoute AT 
		INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
        INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))
	    Left JOIN sTransport.tBusRouteDestinationMaster BM1 ON BM1.Id=AT.DropDestinationId
        LEFT JOIN sTransport.tBusRouteMaster B1 ON B1.Id=BM1.BusRouteId AND  AT.SourceTypeId=2003 AND ((B1.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))
        ) RT
        ON RT.SourceId = SA.StudentId 
        AND ((SA.OrgGroupBatchId = RT.OrgGroupBatchId))
        AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
	   
	    WHERE	
			(CAST(LEFT(SA.OrgGroupBatchId, 4) AS int) = @rOrgGroupId OR @rOrgGroupId=0)
			AND ((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 ISNULL(FAS.ToPayAmount,0) !=0
		   AND (
				 (@rFilterId = 0) -- All
				 OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel
				 OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport
				 OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))
			    )
			AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
			AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
		   AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
		   AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))  
			Order by SA.RollNo

			
				SELECT
			@rBuilder1 AS Builder1,
			@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,
		    Pickup,
			DRoppoint,
			PresentContactNo,
			SUID,
			ClassOrderIndex,
			DivisionOrderIndex,
			'' AS FatherContactNo,
		    '' AS MotherContactNo
			FROM @p 
			
			GROUP By 
			OrgId,AcademicId,ReceiptBookId,DivisionId,BatchId,
			ClassDivision,RollNo, Name,Code,ReceiptBookTitle,OrgName,ReceiptOrderIndex,BatchName,Pickup,DRoppoint,PresentContactNo,SUID,ClassOrderIndex,
			DivisionOrderIndex
			
			ORDER BY AcademicId
	END
END
GO
PRINT N'Altering Procedure [sFee].[pRptFeePendingWithFeeNameGet]...';


GO

 
ALTER PROCEDURE [sFee].[pRptFeePendingWithFeeNameGet]
		@rReportId int=0,
		@rReceiptBookId int,
		@rAdmissionCategoryId int,
		@rClassId int,
		@rDivisionId int,
		@rUptoDate date,
		@rBatchId int,
		@rUserId bigint,
		@rBuilder1 nvarchar(max),
		@rBuilder2 nvarchar(max),
		@rIsDetail bit,
		@rOrgId int,
		@rOrgGroupBatchId int,
		@rStatusId int,
		@rCommonBatch nvarchar(100),
		@rDepartmentId int=0,
		@rFromRollNo int=0,
	    @rToRollNo int=0,
	    @rCode nvarchar(20)='',
	    @rIsFilter bit=0,
		@rIsHeader bit=0,		
		@rCreatedUserName nvarchar(20) = '',
		@rIsReceiptBookGroup bit=0	,
		@rFeeHeadId nvarchar(max) = '',
		@rIsDisplayOrgGroup bit=0,
		@rFeeId nvarchar(max) = '',
		@rFilterId int=0,
		@rOrgIds nvarchar(max) = '' ,
		@rReportType int=1,
		@rClassStatusId int=0,
		@rClassIds nvarchar(max) = '',
		@rDivisionIds nvarchar(max) = '',
		@rFromAmount decimal = 0.00,
		@rToAmount decimal = 0.00
	    
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 	

	IF(@rReportType=1)

		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,
		ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
		ISNULL(SC.StudentContactNo,'') AS StudentContactNo,
		'',
		ISNULL(SA.SUID,'') AS SUID,
		SA.ClassOrderIndex,
		SA.DivisionOrder,
		FS.FeeOrderIndex,
		--change by megha for 0027384
	    ISNULL(SF.FatherContactNo,'')AS FatherContactNo,
		ISNULL(SF.MotherContactNo,'')AS MotherContactNo
			
  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,
				FM.OrderIndex AS FeeOrderIndex
			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 (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			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 (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
				AND (ISNULL(FS1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
				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,
				FM.OrderIndex AS FeeOrderIndex
			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 = FS1.ClassId 
			AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0)) 
			AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
			AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
			AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
		WHERE
		       (SA1.OrgGroupBatchId = @rOrgGroupBatchId)
				AND ((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=1)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
				AND (ISNULL(FS1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
		) 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 (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))  
				AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
			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 (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
				GROUP BY FeeSetupId,R.SourceId) R ON R.FeeSetupId = FS.Id 
				AND SA.AcademicId = R.SourceId
		       INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
		       INNER JOIN sFee.tReceiptBookMaster RBM 
			ON FS.ReceiptBookId=RBM.Id
			LEFT JOIN sStudent.tStudentCommunication SC 
			ON SC.StudentId = SA.StudentId
			
		LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
         LEFT JOIN
	(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
    INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
    INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
    ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
		    --change by megha for 0027384
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SA.StudentId
	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 (
				 (@rFilterId = 0) -- All
				 OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel
				 OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport
				 OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))
			     )
			AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
			AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))  
			Order by SA.RollNo

	SELECT
			@rBuilder1 as Builder1,
			@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
			(CASE WHEN @rIsReceiptBookGroup = 0 THEN 0
			 WHEN @rIsReceiptBookGroup = 1 THEN	ReceiptBookId
			 END) AS ReceiptBookId,	
			(CASE WHEN @rIsReceiptBookGroup = 0 THEN 'ALL'
			 WHEN @rIsReceiptBookGroup = 1 THEN	ReceiptBookTitle
			 END) AS ReceiptBookTitle,
			(CASE WHEN @rIsReceiptBookGroup = 0 THEN 0
			 WHEN @rIsReceiptBookGroup = 1 THEN	ReceiptOrderIndex
			 END) AS ReceiptOrderIndex,	 
			
			OrgId,			 
			--ReceiptBookId,
			AcademicId,
			DivisionId,
			ClassDivision,RollNo, Name,Code,
			--ReceiptBookTitle,
			OrgName,
			SUM(PendingAmount) AS PendingAmount, 
			[sFee].[fPendingFeeNamesGet](AcademicId,ReceiptBookId,	@p) AS PendingFeeName,
			Pickup AS ParentContactNo,
			DRoppoint AS StudentContactNo,
			SUID,
			ClassOrderIndex,
			DivisionOrderIndex,
			FeeOrderIndex,
			--ReceiptOrderIndex,
			FatherContactNo,
		    MotherContactNo
			FROM @p 
			GROUP By ReceiptBookId,OrgId,AcademicId,DivisionId,
			ClassDivision,RollNo, Name,Code,
			ReceiptBookTitle,OrgName,ReceiptOrderIndex,Pickup,DRoppoint,SUID,ClassOrderIndex,
			DivisionOrderIndex,
			FeeOrderIndex,FatherContactNo,MotherContactNo
			HAVING
			((SUM(PendingAmount) >= @rFromAmount) OR (@rFromAmount=0.00))
			AND (( SUM(PendingAmount)<= @rToAmount) OR (@rToAmount=0.00))
			ORDER BY AcademicId

END

	ELSE
		BEGIN

	INSERT INTO  @p
SELECT 

		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(FAS.VariableAmount,0.00)AS FAAmount,
		ISNULL(FAS.DiscountAmount,0.00)AS DiscountAmount,
		ISNULL(FAS.AdditionalAmount,0.00)AS AdditionalAmount,
		ISNULL(FAS.PaidAmount,0) AS PaidAmount,
		ISNULL(FAS.ToPayAmount,0) AS PendingAmount,
		--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(FAS.Remark,'') AS Remark,
		FS.ReceiptBookId,
		--FS.FeeName,
		--FS.FeeCode,
		FM.Title AS FeeName, 
		FM.Code AS 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,
		ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
		ISNULL(SC.StudentContactNo,'') AS StudentContactNo,
		'',
		ISNULL(SA.SUID,'') AS SUID,
		SA.ClassOrderIndex,
		SA.DivisionOrder,
		FM.OrderIndex AS FeeOrderIndex,
	    ISNULL(SF.FatherContactNo,'')AS FatherContactNo,
		ISNULL(SF.MotherContactNo,'') AS MotherContactNo
  FROM  sStudent.vStudentAcademic SA
		INNER JOIN sFee.tFeeAllocationStudent FAS ON FAS.AcademicId = SA.AcademicId
		INNER JOIN sFee.tFeeSetup FS ON FS.ID=FAS.FeeSetupId	
		INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS.FeeId
		INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
		INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id		
		INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
		--LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=SF.FeeSetupId AND FA.SourceId=SA.AcademicId
		LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
        LEFT JOIN
		(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
		INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
		INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
		ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))
		LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId 
		LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SA.StudentId 
		
	WHERE	
			(SA.OrgGroupBatchId = @rOrgGroupBatchId)
			AND ((SA.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 ISNULL(FAS.ToPayAmount,0) !=0
			AND (
				 (@rFilterId = 0) -- All
				 OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel
				 OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport
				 OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))
			     )
			AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
			AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
			AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')  
			AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))
			Order by   SA.RollNo
			--FM.OrderIndex 
			

	SELECT
			@rBuilder1 as Builder1,
			@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
			(CASE WHEN @rIsReceiptBookGroup = 0 THEN 0
			 WHEN @rIsReceiptBookGroup = 1 THEN	ReceiptBookId
			 END) AS ReceiptBookId,	
			(CASE WHEN @rIsReceiptBookGroup = 0 THEN 'ALL'
			 WHEN @rIsReceiptBookGroup = 1 THEN	ReceiptBookTitle
			 END) AS ReceiptBookTitle,
			(CASE WHEN @rIsReceiptBookGroup = 0 THEN 0
			 WHEN @rIsReceiptBookGroup = 1 THEN	ReceiptOrderIndex
			 END) AS ReceiptOrderIndex,	 
			
			OrgId,			 
			--ReceiptBookId,
			AcademicId,
			DivisionId,
			ClassDivision,RollNo, Name,Code,
			--ReceiptBookTitle,
			OrgName,
			SUM(PendingAmount) AS PendingAmount, 
			[sFee].[fPendingFeeNamesGet](AcademicId,ReceiptBookId,	@p) AS PendingFeeName,
			Pickup AS ParentContactNo,
			DRoppoint AS StudentContactNo,
			SUID,
			ClassOrderIndex,
			DivisionOrderIndex,
			--ReceiptOrderIndex,
			FeeOrderIndex,
			FatherContactNo,
		    MotherContactNo
			FROM @p 
			GROUP By ReceiptBookId,OrgId,AcademicId,DivisionId,
			ClassDivision,RollNo, Name,Code,
			ReceiptBookTitle,OrgName,ReceiptOrderIndex,Pickup,DRoppoint,SUID,ClassOrderIndex,
			DivisionOrderIndex,FeeOrderIndex,FatherContactNo,MotherContactNo
			HAVING
			((SUM(PendingAmount) >= @rFromAmount) OR (@rFromAmount=0.00))
			AND (( SUM(PendingAmount)<= @rToAmount) OR (@rToAmount=0.00))
			ORDER BY AcademicId

END 
END
GO
PRINT N'Altering Procedure [sFee].[pUpdatePendingAsNAGet]...';


GO

 
ALTER PROCEDURE [sFee].[pUpdatePendingAsNAGet]
	 
		@rOrgGroupBatchId int=0,
		@rOrgId int=0,
		@rBatchId int=0,	 
		@rFromLeftDate Date=NULL,
		@rToLeftDate Date=NULL,
	    @rStatusId int=3

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 	
	
	DECLARE @p AS TempPendingFee
	
	INSERT INTO @p 
	SELECT 
		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,
		'',
		'',
		'',
		ISNULL(SA.SUID,'') AS SUID,
		SA.ClassOrderIndex,
		SA.DivisionOrder,
		FS.OrderIndex,
		'' AS FatherContactNo,
		'' AS MotherContactNo
  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,
				FM.OrderIndex
			FROM 
				sFee.tFeeSetup FS1
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
				AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId				
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			WHERE 
			    ((SA1.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND (FS1.IsOptional=0)
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND SA1.StatusId = @rStatusId
				
			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,
				FM.OrderIndex
			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
			WHERE
		        ((SA1.OrgGroupBatchId = @rOrgGroupBatchId)  OR (@rOrgGroupBatchId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND (FS1.IsOptional=1)
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND SA1.StatusId = @rStatusId
				
		) FS ON FS.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
		LEFT JOIN
		(
		    SELECT 
					ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
		    FROM
				sFee.tReceipt R 
				INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
				INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
				INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId				
			WHERE		
				(R.SourceTypeId = 2001)
				AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND (R.IsObsolete = 0) 
				AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
				AND SA1.StatusId = @rStatusId
				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 (ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00) -ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00) != 0)			
			AND SA.	StatusId = @rStatusId
			
			ORDER BY SA.RollNo
	 
			SELECT
				Temp.OrgId,			 
				Temp.ReceiptBookId,
				Temp.AcademicId,
				Temp.DivisionId,
				ClassDivision,
				Temp.RollNo, 
				Name,
				Temp.Code,
				ReceiptBookTitle,
				OrgName,
				SUM(PendingAmount) AS PendingAmount, 
				[sFee].[fPendingFeeNamesGet](Temp.AcademicId,Temp.ReceiptBookId,	@p) AS PendingFeeName,
				ReceiptOrderIndex,
				Temp.BatchId,
				BatchName,
				'' AS SUId,
				SA.LeftDate,
				Temp.ClassOrderIndex,
				Temp.DivisionOrderIndex,
				'' AS FatherContactNo,
		        '' AS  MotherContactNo
			FROM @p Temp
				INNER JOIN sStudent.tAcademic A ON A.Id =  Temp.AcademicId
				INNER JOIN sStudent.tStudentMaster SM ON SM.Id = A.StudentId AND SM.StatusId = @rStatusId
				INNER JOIN sStudent.tStudentAdmission SA ON SA.StudentId = A.StudentId
			WHERE 
			    ( (@rStatusId = 3 AND ((SA.LeftDate >= @rFromLeftDate) OR (ISNULL(@rFromLeftDate,'') = ''))
				  AND ((SA.LeftDate <= @rToLeftDate) OR (ISNULL(@rToLeftDate,'') = '')) )
				OR (@rStatusId = 2 AND ((SA.InActiveDate >= @rFromLeftDate) OR (ISNULL(@rFromLeftDate,'') = ''))
				  AND ((SA.InActiveDate <= @rToLeftDate) OR (ISNULL(@rToLeftDate,'') = '')) )
				)
				AND SM.StatusId = @rStatusId
				GROUP BY 
				Temp.OrgId,Temp.AcademicId,Temp.ReceiptBookId,Temp.DivisionId,Temp.BatchId,
				ClassDivision,Temp.RollNo, Name,Temp.Code,ReceiptBookTitle,
				OrgName,ReceiptOrderIndex,BatchName,SA.LeftDate,Temp.ClassOrderIndex,
				Temp.DivisionOrderIndex
				ORDER BY Temp.AcademicId
END
GO
PRINT N'Altering Procedure [sFee].[pFeePendingListGet]...';


GO

ALTER PROCEDURE [sFee].[pFeePendingListGet]
		
		@rOrgGroupBatchId int=0,
		@rAdmissionCategoryId int=0,
		@rClassId int=0,
		@rDivisionId int=0,
		@rCode nvarchar(20)='',
		@rFirstName nvarchar(100)='',
		@rLastName nvarchar(100) = '',
		@rReceiptBookId int=0,
		@rOrgId int=0,
		@rBatchId int=0,
		@rDepartmentId int=0,
		@rSUId nvarchar(50) = '',
		@rUptoDate date='',
		@rFromNextFollowupDate date='',
		@rToNextFollowupDate date=''
		
		
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
		BEGIN
			SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
			SET @rLastName = sCommon.fSearchStringGet(@rLastName)
		END		 
BEGIN 	
	
	DECLARE @p AS TempPendingFee
	
	INSERT INTO @p 
	SELECT 
		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,
		'',
		'',
		'',
		ISNULL(SA.SUID,'') AS SUID,
		SA.ClassOrderIndex,
		SA.DivisionOrder,
		FS.OrderIndex,
		--change by megha for 0027384
	    '' AS FatherContactNo,
		'' AS MotherContactNo

  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,
				FM.OrderIndex
			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 ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				
			UNION ALL
				
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName,
				FM.Code AS FeeCode,
				FM.OrderIndex
			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 ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
		) FS ON FS.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
		LEFT JOIN
		(
		    SELECT 
					ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
		    FROM
				sFee.tReceipt R 
				INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
				INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
				INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId				
				AND (SA1.ClassId=@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))
				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.Code=@rCode) OR (@rCode=''))
			AND ((SA.Code=@rSUId) OR (@rSUId=''))
			AND ((SA.FirstName like @rFirstName) OR(ISNULL(@rFirstName,'')=''))
			AND ((SA.LastName like @rLastName) OR (ISNULL(@rLastName,'')=''))
			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 SA.	StatusId = 1
			AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			
			ORDER BY SA.RollNo
 
			SELECT
				Temp.OrgId,			 
				Temp.ReceiptBookId,
				Temp.AcademicId,
				Temp.DivisionId,
				Temp.ClassDivision,
				Temp.RollNo, 
				Temp.Name,
				Temp.Code,
				Temp.ReceiptBookTitle,
				Temp.OrgName,
				SUM(Temp.PendingAmount) AS PendingAmount, 
				[sFee].[fPendingFeeNamesGet](Temp.AcademicId,Temp.ReceiptBookId,	@p) AS PendingFeeName,
				Temp.ReceiptOrderIndex,
				Temp.BatchId,
				Temp.BatchName,
				SA.SUId AS SUId,
				FF.NextFollowupDate,
				ISNULL(SC.IsStopApplicationAccess,0) as IsStopApplicationAccess,
				ISNULL(SC.StudentCustomAlert,'') as StudentCustomAlert,
				ISNULL(SC.ParentContactNo,'')AS ParentContactNo,
				ISNULL(SC.StudentContactNo,'')AS StudentContactNo,
				ISNULL(SC.WhatsAppContactNo,'')AS WhatsAppContactNo,
				Temp.ClassOrderIndex,
				Temp.DivisionOrderIndex,
				'' AS FatherContactNo,
		        '' AS MotherContactNo
			FROM @p Temp
			LEFT JOIN 
			(
				SELECT AcademicId,ReceiptBookId,NextFollowupDate 
				FROM 
				(
				SELECT AcademicId,ReceiptBookId,NextFollowupDate, 
				ROW_NUMBER() OVER(PARTITION BY AcademicId,ReceiptBookId ORDER BY NextFollowupDate DESC) AS RowNumber
				FROM sFee.tFeeFollowup FF 
				) AS T
				WHERE RowNumber = 1 
			) FF ON FF.AcademicId = Temp.AcademicId AND FF.ReceiptBookId = Temp.ReceiptBookId
			INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = Temp.AcademicId AND SA.OrgId = Temp.OrgId
			LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId 
			--change by megha for 0027384
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SA.StudentId 
		WHERE 
			((FF.NextFollowupDate >= @rFromNextFollowupDate) OR (ISNULL(@rFromNextFollowupDate,'') = ''))
			AND ((FF.NextFollowupDate <= @rToNextFollowupDate) OR (ISNULL(@rToNextFollowupDate,'') = ''))
		GROUP BY 
			Temp.OrgId,Temp.AcademicId,Temp.ReceiptBookId,Temp.DivisionId,Temp.BatchId,
			Temp.ClassDivision,Temp.RollNo, Temp.Name,Temp.Code,Temp.ReceiptBookTitle,
			Temp.OrgName,Temp.ReceiptOrderIndex,Temp.BatchName,FF.NextFollowupDate,
			SC.IsStopApplicationAccess,SC.StudentCustomAlert,SC.ParentContactNo,SC.StudentContactNo,SC.WhatsAppContactNo,SA.SUId,Temp.ClassOrderIndex,
			Temp.DivisionOrderIndex
			ORDER BY Temp.AcademicId
END
GO
PRINT N'Altering Procedure [sFee].[pStudentFeeDetailGet]...';


GO
 
ALTER PROCEDURE [sFee].[pStudentFeeDetailGet]
	 
	   @rBusRouteId int,
	   @rOrgGroupId smallint, 
	   @rOrgGroupBatchId int
		
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
		
BEGIN 

DECLARE @p as TempPendingFee
	
	INSERT INTO  @p 
	 
	SELECT 
		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, 
		'' AS Pickup,
		'' AS DRoppoint,
		'' AS PresentContactNo,
		ISNULL(SA.SUID,'') AS SUID,
		SA.ClassOrderIndex,
		SA.DivisionOrder,
		FS.FeeOrderIndex,
		'' AS FatherContactNo,
		'' AS MotherContactNo	
  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,
				FM.OrderIndex AS FeeOrderIndex
			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 = FS1.ClassId
				INNER JOIN sFee.tFeeHeadMaster FH ON FH.Id = FM.FeeHeadId AND FH.Number = 1001
				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.IsOptional=1)
				AND ((BRDM.BusRouteId=@rBusRouteId) OR (@rBusRouteId=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				
				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 (R.IsObsolete = 0) 
				AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId)  )
				AND ((BRDM.BusRouteId=@rBusRouteId) OR (@rBusRouteId=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.StatusId = 1)
			AND ((BRDM.BusRouteId=@rBusRouteId) OR (@rBusRouteId=0))
			AND (BRM.OrgGroupBatchId = @rOrgGroupBatchId)
    Order by SA.DivisionOrder

			SELECT 
				 CM.DisplayTitle + '-' + DM.DisplayTitle AS ClassDivision,
			 	 SA.StudentId AS StudentId, 
			 	 SA.Code AS StudentCode,
				 0x AS StudentPhoto, 
				 SA.FirstName + ' ' + SA.LastName AS StudentName, 
				 BRDM.Title AS Destination,
				 ISNULL(P.PendingAmount,0.00) AS PendingAmount ,
				 ISNULL(P.FeeName,'')AS FeeName,
				 '' AS FatherContactNo,
		         '' AS MotherContactNo
			FROM 
				 sTransport.tAssignRoute AR 
				 INNER JOIN sStudent.vStudentAcademic SA ON SA.StudentId = AR.SourceId
		         INNER JOIN sTransport.tBusRouteDestinationMaster BRDM ON BRDM.Id = AR.PickupDestinationId 
		         INNER JOIN sTransport.tBusRouteMaster BRM ON BRM.Id = BRDM.BusRouteId 
		         INNER JOIN sSetup.tClassMaster CM ON CM.Id = SA.ClassId 
		         INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = SA.DivisionId 
                 LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId = SA.StudentId 
				 LEFT JOIN @p P ON P.AcademicId = SA.AcademicId
            WHERE 
                 BRM.Id = @rBusRouteId 
                 AND BRM.OrgGroupId = @rOrgGroupId 
                 AND BRM.OrgGroupBatchId = @rOrgGroupBatchId
                 AND SA.IsActiveBatch = 1
                 AND SA.StatusId = 1
            ORDER BY 
				 BRDM.OrderIndex,DM.OrderIndex
END
GO
PRINT N'Altering Procedure [sAcademic].[pImportLessonPlan]...';


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

	DECLARE @lCount int,@intDoc INT,@lInterrorCode INT,@loXML XML,
			@lDivisionId int,
			@lTopicId int,
			@lNoOfPeriodRequired smallint,
			@lObjective nvarchar(1000),
			@lIndicativeHomework nvarchar(1000),
			@lSummary nvarchar(1000),
			@lStartDate date,
			@lEndDate date,
			@lIsCompleted bit,
			@lEmployeeId bigint,
			@lBatchId int,
			@lCreatedUserId bigint,
			@lCreatedDateTime datetime,
			@lUpdatedUserId bigint,
			@lUpdatedDateTime datetime,
			@lLearningExperience nvarchar(1000),
			@lToolsAndTechniques nvarchar(500),
			@lEssentialMaterial nvarchar(500),
			@lAssessmentQuestion nvarchar(1000),
			@lTeacherExample nvarchar(1000),
			@lGuidedPractice nvarchar(1000),
			@lIndependentPractice nvarchar(1000),
			@lSubTopic nvarchar(1000) ,
			@lSession nvarchar(100) ,
			@lTrainingMethod  nvarchar(100) ,
			@lPeriodCount int

	SET @loXML = CAST(@rXmldoc AS XML)
	
	
	CREATE TABLE #tTable1 (
	Id int IDENTITY,
	DivisionId int,
	TopicId int,
	NoOfPeriodRequired smallint,
	Objective nvarchar(1000),
	IndicativeHomework nvarchar(1000),
	Summary nvarchar(1000),
	StartDate date,
	EndDate date,
	IsCompleted bit,
	EmployeeId bigint,
	BatchId int,
	CreatedUserId bigint,
	CreatedDateTime datetime,
	UpdatedUserId bigint,
	UpdatedDateTime datetime,
	LearningExperience nvarchar(1000),
	ToolsAndTechniques nvarchar(500),
	EssentialMaterial nvarchar(500),
	AssessmentQuestion nvarchar(1000),
	TeacherExample nvarchar(1000),
	GuidedPractice nvarchar(1000),
	IndependentPractice nvarchar(1000),
	SubTopic nvarchar(1000),
	Session nvarchar(100) ,
	TrainingMethod  nvarchar(100) ,
	PeriodCount int)
	 
	INSERT INTO #tTable1(
			DivisionId
           ,TopicId
           ,NoOfPeriodRequired
           ,Objective
           ,IndicativeHomework
           ,Summary
           ,StartDate
           ,EndDate
           ,IsCompleted
           ,EmployeeId
		   ,BatchId
		   ,CreatedUserId
           ,LearningExperience
           ,ToolsAndTechniques
           ,EssentialMaterial
           ,AssessmentQuestion
           ,TeacherExample
           ,GuidedPractice
           ,IndependentPractice
           ,SubTopic
		   ,Session 
		   ,TrainingMethod
		   ,PeriodCount)
	SELECT
		 T.c.value('@DivisionId','int') AS DivisionId,
		 T.c.value('@TopicId','int') AS TopicId,
		 T.c.value('@PerioNo','smallint') AS NoOfPeriodRequired,
		 T.c.value('@Objective','nvarchar(1000)') AS Objective,
		 T.c.value('@IndicativeHomework','nvarchar(1000)') AS IndicativeHomework,
		 T.c.value('@Summary','nvarchar(1000)') AS Summary,
		 T.c.value('@StartDate','Date') AS StartDate,
		 T.c.value('@EndDate','Date') AS EndDate,
		 T.c.value('@Completed','bit') AS IsCompleted,
		 T.c.value('@EmployeeId','bigint') AS EmployeeId,
		 @rBatchId,
		 T.c.value('@CreatedUserId','bigint') AS CreatedUserId,
		 T.c.value('@LearningExperience','nvarchar(1000)') AS LearningExperience,
		 T.c.value('@ToolsAndTechniques','nvarchar(500)') AS ToolsAndTechniques,
		 T.c.value('@EssentialMaterial','nvarchar(500)') AS EssentialMaterial,
		 T.c.value('@AssessmentQuestion','nvarchar(1000)') AS AssessmentQuestion,
		 T.c.value('@TeacherExample','nvarchar(1000)') AS TeacherExample,
		 T.c.value('@GuidedPractice','nvarchar(1000)') AS GuidedPractice,
		 T.c.value('@IndependentPractice','nvarchar(1000)') AS IndependentPractice,
		 T.c.value('@SubTopic','nvarchar(1000)') AS SubTopic,
		 T.c.value('@Session','nvarchar(100)') AS Session ,
		 T.c.value('@TrainingMethod','nvarchar(100)') AS TrainingMethod,
		 T.c.value('@PeriodCount','int') AS PeriodCount

	FROM @loXML.nodes('/Table/ImportLessonPlan')T(c)
	
		SELECT @lCount =  COUNT(Id) FROM #tTable1
	
		WHILE @lCount > 0 

		BEGIN				
	   
			SELECT	
				@lDivisionId = DivisionId,
				@lTopicId = TopicId,
				@lNoOfPeriodRequired = NoOfPeriodRequired,
				@lObjective = Objective,
				@lIndicativeHomework = IndicativeHomework,
				@lSummary = Summary,
				@lStartDate = StartDate,
				@lEndDate = EndDate,
				@lIsCompleted = IsCompleted,
				@lEmployeeId = EmployeeId,
				@lBatchId = BatchId,
				@lCreatedUserId = CreatedUserId,
				@lLearningExperience = LearningExperience,
				@lToolsAndTechniques = ToolsAndTechniques,
				@lEssentialMaterial = EssentialMaterial,
				@lAssessmentQuestion = AssessmentQuestion,
				@lTeacherExample = TeacherExample,
				@lGuidedPractice = GuidedPractice,
				@lIndependentPractice = IndependentPractice,
				@lSubTopic = SubTopic ,
				@lSession = Session ,
			    @lTrainingMethod  = TrainingMethod ,
			    @lPeriodCount = PeriodCount 
			FROM #tTable1 WHERE Id = @lCount 

			IF EXISTS(SELECT Id FROM sAcademic.tLessonPlan WHERE DivisionId=@lDivisionId AND TopicId = @lTopicId AND StartDate = @lStartDate AND EndDate = @lEndDate)
			BEGIN
				Declare @lTopicName nvarchar(500), @lDivisionName nvarchar(100)
				SET  @lTopicName =(select Title from sAcademic.tTopicMaster where Id =@lTopicId)
				SET  @lDivisionName =(select Title from sSetup.tDivisionMaster Where Id =@lDivisionId)

				SELECT -101 AS Result, 'Lesson Plan Already Exists for for Division - '+@lDivisionName+', Topic - '+@lTopicName+', Start Date - '+Convert(nvarchar(10), @lStartDate, 103)+', End Date - '+Convert(nvarchar(10), @lEndDate, 103)+'' AS Message
				RETURN
			END 

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

			INSERT INTO sAcademic.tLessonPlan
				(
					Id,
					TopicId,
					DivisionId,
					NoOfPeriodRequired,
					Objective,
					IndicativeHomework,
					Summary,
					StartDate,
					EndDate,
					IsCompleted,
					EmployeeId,
					BatchId,
					CreatedUserId,
					CreatedDateTime,
					LearningExperience,
					ToolsAndTechniques,
					EssentialMaterial,
					AssessmentQuestion,
					TeacherExample,
					GuidedPractice,
					IndependentPractice,
					SubTopic ,
					Session ,
					TrainingMethod ,
					PeriodCount
				)
			VALUES
				(
					@lNextNumber,
					@lTopicId,
					@lDivisionId,
					ISNULL(@lNoOfPeriodRequired,0),
					ISNULL(@lObjective,''),
					ISNULL(@lIndicativeHomework,''),
					ISNULL(@lSummary,''),
					@lStartDate,
					@lEndDate,
					@lIsCompleted,
					@lEmployeeId,
					@lBatchId,
					@lCreatedUserId,
					sCommon.fGetDate(),
					ISNULL(@lLearningExperience,''),
					ISNULL(@lToolsAndTechniques,''),
					ISNULL(@lEssentialMaterial,''),
					ISNULL(@lAssessmentQuestion,''),
					ISNULL(@lTeacherExample,''),
					ISNULL(@lGuidedPractice,''),
					ISNULL(@lIndependentPractice,''),
					ISNULL(@lSubTopic,''),
					ISNULL(@lSession,''),
					ISNULL(@lTrainingMethod,''),
					ISNULL(@lPeriodCount,0)
				)
				
			SET @lCount = @lCount - 1
			SELECT 1 AS Result 		

		 END
END
GO
PRINT N'Altering Procedure [sAccounting].[pRptProfitAndLossGet]...';


GO
ALTER PROCEDURE [sAccounting].[pRptProfitAndLossGet]

	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='', 
	@rStartDate Date,
	@rEndDate Date,
	@rOrgGroupId int = 0,
	@rAccountingYearId [int],
	@rAccountId int=0
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

	Declare @lLedgerId int 
	Declare @lOpeningBalance Decimal (12,2)
	Declare @ltIncome Decimal (12,2)
	Declare @ltExpense Decimal (12,2)
	Declare @lInIncome Decimal(12,2)
	Declare @lInClosing Decimal(12,2)
	Declare @lExOpening Decimal(12,2)
	Declare @lExExpense Decimal(12,2)
	Declare @lGrossProfit Decimal(12,2)
	Declare @lGrossLoss Decimal(12,2)
	Declare @lCount int
	Declare @lLedgerName Nvarchar(150)
	Declare @lLedgerGroupName Nvarchar(150)
	Declare @lLedgerMainGroupName Nvarchar(150) 
	DECLARE @1ExpenceCount int
	DECLARE @1IncomeCount 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  
  
	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,'',''
		
	--SELECT * FROM #tempUpdateClosingBalance

	CREATE TABLE #TempExpenseGroup
	(
	   Id INT IDENTITY(1,1),
	   ExpenseGroupId int,
	   ExpenseGroup nvarchar(200),
	   ExpenseLedger nvarchar(200),
	   Expense decimal(22,2),
	   OpeningBalance decimal(22,2),
	   ExpenseTransactionBalance decimal(12,2) 
	)
		
	CREATE TABLE #TempIncomeGroup
	(
	   Id INT IDENTITY(1,1),
	   IncomeGroupId int,
	   IncomeGroup nvarchar(200),
	   IncomeLedger nvarchar(200),
	   Income decimal(22,2),
	   ClosingBalance decimal,
	   IncomeTransactionBalance decimal(12,2)
	)
		
	INSERT INTO #TempExpenseGroup
	SELECT 
        ISNULL(Lg.Id,0) as ExpenseGroupId,		
		ISNULL(LG.Title,'') AS ExpenseGroup,
		ISNULL(L.Title,'') AS ExpenseLedger,	
		ISNULL(SUM(UC.Closing_Balance),0) AS Expense,
	    ISNULL(SUM(L.OpeningBalance),0) AS OpeningBalance,
		ISNULL(SUM(UC.Transaction_Balance),0) AS ExpenseTransactionBalance
	FROM 
		sAccounting.tLedgerMaster L
		INNER JOIN sAccounting.tLedgerGroupMaster LG ON L.LedgerGroupId = LG.Id
		INNER JOIN sAccounting.tLedgerMainGroupMaster LMG ON LG.LedgerMainGroupId = LMG.Id
		INNER JOIN #tempUpdateClosingBalance UC ON L.Id=UC.LedgerId
	WHERE LMG.ID  = 4 AND L.AccountingYearId = @rAccountingYearId AND LG.AccountingYearId = @rAccountingYearId
	GROUP BY LG.Title,LMG.ID,L.Title,LG.Id	HAVING ISNULL(SUM(UC.Closing_Balance),0) > 0
	ORDER BY LMG.Id	
		
		
	INSERT INTO #TempIncomeGroup
    SELECT  
        ISNULL(Lg.Id,0) as IncomeGroupId,		
		ISNULL(LG.Title,'') AS IncomeGroup,
		ISNULL(L.Title,'') AS IncomeLedger,
		ISNULL(SUM(UC.Closing_Balance),0) AS Income,
		ISNULL(SUM(UC.Closing_Balance),0) AS ClosingBalance,
		ISNULL(SUM(UC.Transaction_Balance),0) AS IncomeTransactionBalance
	FROM sAccounting.tLedgerMaster L 
		INNER JOIN sAccounting.tLedgerGroupMaster LG ON L.LedgerGroupId = LG.Id
		INNER JOIN sAccounting.tLedgerMainGroupMaster LMG ON LG.LedgerMainGroupId = LMG.Id
		INNER JOIN #tempUpdateClosingBalance UC ON L.Id=UC.LedgerId
	WHERE LMG.ID = 3 AND L.AccountingYearId = @rAccountingYearId AND LG.AccountingYearId = @rAccountingYearId
	GROUP BY LG.Title,LMG.ID,L.Title,LG.Id HAVING ISNULL(SUM(UC.Closing_Balance),0) > 0	
	ORDER BY LMG.Id	
	      
	     
	SELECT @1ExpenceCount = count(Id) From #TempExpenseGroup
	SELECT @1IncomeCount = Count(Id) From #TempIncomeGroup

	IF(@1InComeCount >= @1ExpenceCount)
	BEGIN		    
		SELECT 
			@ReportOrgTitle  AS OrgTitle,
			@SmallAddress1 AS SmallAddress1,
			@SmallAddress2 AS SmallAddress2, 
	        @rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			ISNULL(IncomeGroupId,0) AS IncomeGroupId,
	        IncomeGroup, 
	        IncomeLedger,
	        ClosingBalance,
	        Income,
	        ISNULL(ExpenseGroupId,0) AS ExpenseGroupId,
	        ISNULL(ExpenseGroup,'') AS ExpenseGroup,
	        ISNULL(ExpenseLedger,'') AS ExpenseLedger,
			ISNULL(OpeningBalance,0) AS OpeningBalance,	          
			ISNULL(Expense,0.00) AS Expense,
			ISNULL(IG.IncomeTransactionBalance,0.00) AS IncomeTransactionBalance,
			ISNULL(EG.ExpenseTransactionBalance,0.00) AS ExpenseTransactionBalance
		FROM #TempIncomeGroup IG 
			LEFT JOIN #TempExpenseGroup EG ON EG.Id = IG.Id	  
	          
	END
	ELSE
	BEGIN
	    SELECT 
			@ReportOrgTitle  AS OrgTitle,
	        @SmallAddress1 AS SmallAddress1,
			@SmallAddress2 AS SmallAddress2, 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2, 
			ISNULL(IncomeGroupId,0) AS IncomeGroupId,
	        ISNULL(IncomeGroup,'') AS IncomeGroup, 
	        ISNULL(IncomeLedger,'') AS IncomeLedger,
	        ISNULL(ClosingBalance,0) AS ClosingBalance,
	        ISNULL(Income,0) AS Income,
	        ISNULL(ExpenseGroupId,0) AS ExpenseGroupId,
	        ExpenseGroup AS ExpenseGroup,
	        ExpenseLedger,
			OpeningBalance,
			Expense,
			ISNULL(EG.ExpenseTransactionBalance,0.00) AS ExpenseTransactionBalance,
			ISNULL(IG.IncomeTransactionBalance,0.00) AS IncomeTransactionBalance
	    FROM #TempExpenseGroup EG  
			LEFT JOIN #TempIncomeGroup IG ON EG.Id = IG.Id	
	 END	
	     
	 DROP TABLE #TempExpenseGroup
	 DROP TABLE #TempIncomeGroup
		

--SELECT
--	'' AS OrgTitle,
--	'' AS SmallAddress1,
--	'' AS SmallAddress2,
--	'' AS Builder1,
--	'' AS Builder2,
--	0 AS IncomeGroupId,
--	'' AS IncomeGroup,
--	'' AS IncomeLedger,
--	0.00 AS ClosingBalance,
--	0.00 AS Income,
--	0 AS ExpenseGroupId,
--	'' AS ExpenseGroup,
--	'' AS ExpenseLedger,
--	0.00 AS OpeningBalance,
--	0.00 AS Expense,
--	0.00 AS ExpenseTransactionBalance,
--	0.00 AS IncomeTransactionBalance
	    
END
GO
PRINT N'Altering Procedure [sAlert].[pEventEmployeeAttendanceGet]...';


GO


ALTER PROCEDURE [sAlert].[pEventEmployeeAttendanceGet]

	 	 --@rEventScheduleId int,
		 @rEventName nvarchar(max),
	 	 --@rEmployeeId bigint,
		 @rFromDate Date,
		 @rToDate Date,
		 --@rAttendanceType nvarchar(max),
		 @rIsPresent bit,
	 	 @rTemplate nvarchar(max),
	 	 @rMailSubject nvarchar(500)='',
		 @rEventAttendanceXml nvarchar(max)

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rEventAttendanceXml
BEGIN
	CREATE TABLE #EventAttendanctemp  
	(
		EmployeeId bigint,
		IsPresent bit
	)
	INSERT INTO #EventAttendanctemp
	(
		EmployeeId ,
		IsPresent 
	)
	SELECT *
			FROM OPENXML (@loDoc, '/Table/EventAttendance', 1)
			WITH
			(						
				SourceId bigint,
				IsSelfPresent bit
			)
	Select
			EC.EmployeeId,
			EC.Code,
			EC.EmployeeName,
			ISNULL(EC.MobileNumber,'') AS MobileNo,
			ISNULL(EC.CompanyEmail,'') AS EmailId,
			REPLACE (
			REPLACE (
			REPLACE (
			REPLACE (
			REPLACE(@rTemplate,'[EventName]',@rEventName),
			'[EmployeeName]',EC.EmployeeName),
			'[Code]',EC.Code), 
			'[Date]',convert(varchar, @rFromDate, 103)  + '-' + convert(varchar, @rToDate, 103)),
			'[Type]',
			' Present : ' + CASE WHEN tmp.IsPresent = 1 THEN 'YES' ELSE 'NO' END) 
			AS MsgText,
			@rMailSubject AS Subject,
			EC.EmployeeId AS SourceId,
			95 AS SourceTypeId,
			EC.OrgId,
			OM.OrgGroupId,
			EC.EmployeeId AS ReceiverSourceId,
			95 AS ReceiverSourceTypeId,
			EC.WhatsAppContactNo

	From
		sHrm.vEmployeeCommunication EC
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EC.OrgId
		INNER JOIN #EventAttendanctemp tmp ON EC.EmployeeId = tmp.EmployeeId
		WHERE 
		--EC.EmployeeId = @rEmployeeId
		EC.StatusId = 7

END
GO
PRINT N'Altering Procedure [sAlert].[pEventStudentAttendanceGet]...';


GO


ALTER PROCEDURE [sAlert].[pEventStudentAttendanceGet]

	 	 --@rEventScheduleId int,
		 @rEventName nvarchar(max),
	 	 --@rAcademicId bigint,
		 @rFromDate Date,
		 @rToDate Date,
		 @rAttendanceType nvarchar(max),
		 --@rIsStudentPresent bit,
		 --@rIsFatherPresent bit,
		 --@rIsMotherPresent bit,
		 --@rIsGuardianPresent bit,
	 	 @rTemplate nvarchar(max),
	 	 @rMailSubject nvarchar(500)='',
		 @rEventAttendanceXml nvarchar(max)

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rEventAttendanceXml
BEGIN
	CREATE TABLE #EventAttendanctemp  
	(
		AcademicId bigint,
		IsStudentPresent bit,
		IsFatherPresent bit,
		IsMotherPresent bit,
		IsGuardianPresent bit
	)
	INSERT INTO #EventAttendanctemp
	(
		AcademicId ,
		IsStudentPresent ,
		IsFatherPresent ,
		IsMotherPresent ,
		IsGuardianPresent 
	)
	SELECT *
			FROM OPENXML (@loDoc, '/Table/EventAttendance', 1)
			WITH
			(						
				SourceId bigint,
				IsSelfPresent bit,
				IsFatherPresent bit,
				IsMotherPresent bit,
				IsGuardianPresent bit
			)

	Select
			SC.AcademicId,
			SC.Code,
			SC.Name,
			SC.ParentContactNo AS MobileNo,
			SC.ParentEmail AS EmailId,
			REPLACE (
			REPLACE (
			REPLACE (
			REPLACE (
			REPLACE (
			REPLACE(@rTemplate,'[EventName]',@rEventName),
			'[StudentName]',vSA.Name),
			'[Code]',vSA.Code), 
			'[Date]',convert(varchar, @rFromDate, 103)  + '-' + convert(varchar, @rToDate, 103)),
			'[AttendanceType]',@rAttendanceType),
			'[Type]',
			' Student Present : ' + CASE WHEN tmp.IsStudentPresent = 1 THEN 'YES' ELSE 'NO' END + 
			', Father Present : ' + CASE WHEN tmp.IsFatherPresent = 1 THEN 'YES' ELSE 'NO' END + 
			', Mother Present : ' + CASE WHEN tmp.IsMotherPresent = 1 THEN 'YES' ELSE 'NO' END + 
			', Guardian Present : ' + CASE WHEN tmp.IsGuardianPresent = 1 THEN 'YES' ELSE 'NO' END) 
			AS MsgText,
			@rMailSubject AS Subject,
			SC.AcademicId AS SourceId,
			2001 AS SourceTypeId,
			SC.OrgId,
			SC.OrgGroupId,
			SC.AcademicId AS ReceiverSourceId,
			2001 AS ReceiverSourceTypeId,
			SC.WhatsAppContactNo

	From
	
		--sActivity.tEventSchedule ES
		--INNER JOIN sActivity.tEventAttendance EA ON ES.Id = EA.EventScheduleId
		sStudent.vStudentAcademic vSA 
		INNER JOIN sStudent.vStudentCommunication SC ON SC.AcademicId = vSA.AcademicId
		INNER JOIN #EventAttendanctemp tmp ON vSA.AcademicId =  tmp.AcademicId
		WHERE 
		--vSA.AcademicId = @rAcademicId
		SC.IsBlockAllAlert=0
		AND (SC.StatusId=1)

	DROP TABLE #EventAttendanctemp

END
GO
PRINT N'Altering Procedure [sAssessment].[pRptBatchWiseResultGradeGet]...';


GO
ALTER PROCEDURE [sAssessment].[pRptBatchWiseResultGradeGet]
	  @rCode nvarchar(20)='',
	  @rOrgId int=0,
	  @rClassId int=0,
	  @rDivisionId int=0,
	  @rBatchId int=0,
	  @rTotalDaysPresentDays int=0,
	  @rStudentHeightWeight int=0
	  	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 

	DECLARE @quer varchar(max)=''
	DECLARE @lOrgId int,@lCode nvarchar(20),@lClassId int,@lDivisionId int,@lBatchId int
	DECLARE @lClassGroupId int
	
  		SET @lOrgId=ISNULL(@rOrgId,0)
  		SET @lBatchId=ISNULL(@rBatchId,0)
  		SET @lClassId=ISNULL(@rClassId,0)
  		SET @lDivisionId=ISNULL(@rDivisionId,0)
  	    SET @lCode=ISNULL(@rCode,'')
		  	    
    DELETE FROM sAssessment.tAllBatchResultGrade 
	SELECT @quer = 'INSERT INTO sAssessment.tAllBatchResultGrade 
  	(
	SubjectId,StudentId
	)
	 SELECT 
			 DISTINCT SM.Id AS Subject,STM.Id AS StudentID FROM
              sStudent.tStudentMaster STM
			  INNER JOIN sStudent.tAcademic AD ON STM.Id = AD.StudentId 
			  INNER JOIN sSetup.tClassMaster CM ON CM.Id=AD.ClassId
			  INNER JOIn sSetup.tClassSubject CS ON CS.ClassId=CM.Id
			  INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId 
			  AND SM.OrgId=' + convert(varchar,@lOrgId) + '
			  INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=SM.Id 
  	          WHERE STM.OrgId=' + convert(varchar,@lOrgId) + '
  			  AND AB.OrgId =' + convert(varchar,@lOrgId) + '
  			  AND ((STM.Code = ''' + @lCode + ''') OR (''' + @lCode + ''' = ''''))
  			  AND ((AD.ClassId = ''' + convert(varchar,@lClassId) + ''') OR (' + convert(varchar,@lClassId) + ' = 0))
  			  AND ((AD.DivisionId = ''' + convert(varchar,@lDivisionId) + ''') OR (' + convert(varchar,@lDivisionId) + ' = 0))
  			  AND  AD.BatchId='+Convert(varchar,@lBatchId)+''
  			--SELECT  @quer
  	     EXEC (@quer)
  	     
 -- Add New Field :  Height, Weight
 If( @rStudentHeightWeight = 1)
 BEGIN
	select @quer = 'INSERT INTO sAssessment.tAllBatchResultGrade 
  		(
		SubjectId,StudentId
		)
		 SELECT 
			 -1,STM.Id AS StudentID FROM
              sStudent.tStudentMaster STM
			  INNER JOIN sStudent.tAcademic AD ON STM.Id = AD.StudentId			   
			  AND STM.OrgId=' + convert(varchar,@lOrgId) + '			  
  	          WHERE STM.OrgId=' + convert(varchar,@lOrgId) + '  			  
  			  AND ((STM.Code = ''' + @lCode + ''') OR (''' + @lCode + ''' = ''''))
  			  AND ((AD.ClassId = ''' + convert(varchar,@lClassId) + ''') OR (' + convert(varchar,@lClassId) + ' = 0))
  			  AND ((AD.DivisionId = ''' + convert(varchar,@lDivisionId) + ''') OR (' + convert(varchar,@lDivisionId) + ' = 0))
  			  AND  AD.BatchId='+Convert(varchar,@lBatchId)+''  			
  	   EXEC (@quer)
  	   
  	select @quer = 'INSERT INTO sAssessment.tAllBatchResultGrade 
  		(
		SubjectId,StudentId
		)
		 SELECT 
			 -2,STM.Id AS StudentID FROM
              sStudent.tStudentMaster STM
			  INNER JOIN sStudent.tAcademic AD ON STM.Id = AD.StudentId			   
			  AND STM.OrgId=' + convert(varchar,@lOrgId) + '			  
  	          WHERE STM.OrgId=' + convert(varchar,@lOrgId) + '  			  
  			  AND ((STM.Code = ''' + @lCode + ''') OR (''' + @lCode + ''' = ''''))
  			  AND ((AD.ClassId = ''' + convert(varchar,@lClassId) + ''') OR (' + convert(varchar,@lClassId) + ' = 0))
  			  AND ((AD.DivisionId = ''' + convert(varchar,@lDivisionId) + ''') OR (' + convert(varchar,@lDivisionId) + ' = 0))
  			  AND  AD.BatchId='+Convert(varchar,@lBatchId)+''  			
  	   EXEC (@quer)
END
 
If( @rTotalDaysPresentDays = 1)
BEGIN   
  	select @quer = 'INSERT INTO sAssessment.tAllBatchResultGrade 
  		(
		SubjectId,StudentId
		)
		 SELECT 
			 -3,STM.Id AS StudentID FROM
              sStudent.tStudentMaster STM
			  INNER JOIN sStudent.tAcademic AD ON STM.Id = AD.StudentId			   
			  AND STM.OrgId=' + convert(varchar,@lOrgId) + '			  
  	          WHERE STM.OrgId=' + convert(varchar,@lOrgId) + '  			 
  			  AND ((STM.Code = ''' + @lCode + ''') OR (''' + @lCode + ''' = ''''))
  			  AND ((AD.ClassId = ''' + convert(varchar,@lClassId) + ''') OR (' + convert(varchar,@lClassId) + ' = 0))
  			  AND ((AD.DivisionId = ''' + convert(varchar,@lDivisionId) + ''') OR (' + convert(varchar,@lDivisionId) + ' = 0))
  			  AND  AD.BatchId='+Convert(varchar,@lBatchId)+''  			
  	   EXEC (@quer)
  	   
  	select @quer = 'INSERT INTO sAssessment.tAllBatchResultGrade 
  		(
		SubjectId,StudentId
		)
		 SELECT 
			 -4,STM.Id AS StudentID FROM
              sStudent.tStudentMaster STM
			  INNER JOIN sStudent.tAcademic AD ON STM.Id = AD.StudentId			   
			  AND STM.OrgId=' + convert(varchar,@lOrgId) + '			 
  	          WHERE STM.OrgId=' + convert(varchar,@lOrgId) + '  			  
  			  AND ((STM.Code = ''' + @lCode + ''') OR (''' + @lCode + ''' = ''''))
  			  AND ((AD.ClassId = ''' + convert(varchar,@lClassId) + ''') OR (' + convert(varchar,@lClassId) + ' = 0))
  			  AND ((AD.DivisionId = ''' + convert(varchar,@lDivisionId) + ''') OR (' + convert(varchar,@lDivisionId) + ' = 0))
  			  AND  AD.BatchId='+Convert(varchar,@lBatchId)+''  			
  	   EXEC (@quer)
END  	   
-- Ends here 
  	     
	    DEClare @query varchar(max)
	    DEClare @query1 varchar(max)

  		select @query=  ' UPDATE  AR  SET PG = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=101 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
		exec (@query)
		 	
		select @query=  ' UPDATE  AR  SET Nursary = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=102 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
		exec (@query)
		 	
		select @query=  ' UPDATE  AR  SET SrKg = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=104 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
		exec (@query)
		
		select @query=  ' UPDATE  AR  SET JrKg = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=103 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
		exec (@query)
		 	
        select @query=  ' UPDATE  AR  SET First = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
	 		INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId 
			WHERE CGM.ClassGroupId=1 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
		exec (@query)
		 
        select @query=  ' UPDATE  AR  SET Second = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=2 AND ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
		exec (@query)
		 	
		 
	    select @query=  ' UPDATE  AR  SET Third = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=3 AND ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
		exec (@query)
		  
	    select @query=  ' UPDATE  AR  SET Fourth = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=4 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) +''
		exec (@query)
		 
        select @query=  ' UPDATE  AR  SET Fifth = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=5 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
		exec (@query)
		 	
        select @query=  ' UPDATE  AR  SET Sixth = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=6 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
		exec (@query)
		 	
        select @query=  ' UPDATE  AR  SET Seventh = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=7 AND ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
		exec (@query)
		 
	    select @query=  ' UPDATE  AR  SET Eighth = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=8 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
		exec (@query)
		 	
	    select @query=  ' UPDATE  AR  SET Ninth = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=9 AND ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
		exec (@query)
		 	
       select @query=  ' UPDATE  AR  SET Tenth = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=10 AND ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
	   exec (@query)
		 	
	   select @query=  ' UPDATE  AR  SET Eleventh = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=11 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
	   exec (@query)
		 
	   select @query=  ' UPDATE  AR  SET Twelfth = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=12 AND ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
	   exec (@query)
			
	   select @query=  ' UPDATE  AR  SET PG1 = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=101 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
	   exec (@query)
		 	
	   select @query=  ' UPDATE  AR  SET Nursary1 = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=102 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
	   exec (@query)
	
	   select @query=  ' UPDATE  AR  SET SrKg1 = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=104 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
	   exec (@query)
	   
	   select @query=  ' UPDATE  AR  SET JrKg1 = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=103 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
	   exec (@query)
		 
       select @query=  ' UPDATE  AR  SET First1 = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId 
			WHERE CGM.ClassGroupId=1 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
	   exec (@query)
		
       select @query=  ' UPDATE  AR  SET Second1 = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=2 AND ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
	   exec (@query)
		 	
	   select @query=  ' UPDATE  AR  SET Third1 = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=3 AND ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
	   exec (@query)
		  
	   select @query=  ' UPDATE  AR  SET Fourth1 = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=4 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
	   exec (@query)
		 	
       select @query=  ' UPDATE  AR  SET Fifth1 = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=5 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
	   exec (@query)
		 
       select @query=  ' UPDATE  AR  SET Sixth1 = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=6 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
	   exec (@query)
		 	
       select @query=  ' UPDATE  AR  SET Seventh1 = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=7 AND ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
	   exec (@query)
		 	
	   select @query=  ' UPDATE  AR  SET Eighth1 = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=8 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
	   exec (@query)
		 
	   select @query=  ' UPDATE  AR  SET Ninth1 = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=9 AND ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
	   exec (@query)
		 
       select @query=  ' UPDATE  AR  SET Tenth1 = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=10 AND ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
	   exec (@query)
		 	
		 	
	   select @query=  ' UPDATE  AR  SET Eleventh1 = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=11 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
	   exec (@query)
		 	
	   select @query=  ' UPDATE  AR  SET Twelfth1 = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=12 AND ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
	   exec (@query)
		 
	   select @query=  ' UPDATE  AR  SET PG2 = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=101 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
	   exec (@query)
	   
	   select @query=  ' UPDATE  AR  SET Nursary2 = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=102 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
	   exec (@query)
	   
	   select @query=  ' UPDATE  AR  SET SrKg2 = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=104 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
	   exec (@query)
	   
	   select @query=  ' UPDATE  AR  SET JrKg2 = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=103 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) +''
	  exec (@query)
		 
      select @query=  ' UPDATE  AR  SET First2 = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId 
			WHERE CGM.ClassGroupId=1 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
	 exec (@query)
		 
		
	  select @query=  ' UPDATE  AR  SET Second2 = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=2 AND ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
	  exec (@query)
		 	
	  select @query=  ' UPDATE  AR  SET Third2 = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=3 AND ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
	  exec (@query)
		   	
	  select @query=  ' UPDATE  AR  SET Fourth2 = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=4 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
	  exec (@query)
		 	
	  select @query=  ' UPDATE  AR  SET Fifth2 = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=5 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
	  exec (@query)
		 	
	  select @query=  ' UPDATE  AR  SET Sixth2 = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=6 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
	   exec (@query)
			
	   select @query=  ' UPDATE  AR  SET Seventh2 = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=7 AND ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
	   exec (@query)
		 		
	   select @query=  ' UPDATE  AR  SET Eighth2 = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=8 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
	   exec (@query)
		 	
	   select @query=  ' UPDATE  AR  SET Ninth2 = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=9 AND ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
	   exec (@query)
		 		
	   select @query=  ' UPDATE  AR  SET Tenth2 = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=10 AND ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
	   exec (@query)
		 	
	   select @query=  ' UPDATE  AR  SET Eleventh2 = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=11 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
	   exec (@query)
		 	
	   select @query=  ' UPDATE  AR  SET Twelfth2 = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=12 AND ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
	   exec (@query)
	
---- Start Here Height, Weight, TotalDays, PresentDays Value Update

 DECLARE @Updatequery varchar(max)
	
  ---Sub Exam 1 Starts
 If( @rStudentHeightWeight = 1)
 BEGIN
	select @Updatequery=  ' UPDATE  AR  SET PG = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=101 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET PG = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=101 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN  
   select @Updatequery=  ' UPDATE  AR  SET PG = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=101 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET PG = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=101 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''
   exec (@Updatequery)
END  

If( @rStudentHeightWeight = 1)
BEGIN
	select @Updatequery=  ' UPDATE  AR  SET Nursary = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=102 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Nursary = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=102 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN 
   select @Updatequery=  ' UPDATE  AR  SET Nursary = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=102 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Nursary = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=102 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rStudentHeightWeight = 1)
BEGIN
   select @Updatequery=  ' UPDATE  AR  SET JrKg = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=103 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET JrKg = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=103 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''
   exec (@Updatequery)
END  

If( @rTotalDaysPresentDays = 1)
BEGIN  
   select @Updatequery=  ' UPDATE  AR  SET JrKg = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=103 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET JrKg = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=103 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''
   exec (@Updatequery)
END

If( @rStudentHeightWeight = 1)
BEGIN  
    select @Updatequery=  ' UPDATE  AR  SET SrKg = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=104 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET SrKg = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=104 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN    
   select @Updatequery=  ' UPDATE  AR  SET SrKg = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=104 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET SrKg = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=104 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rStudentHeightWeight = 1)
BEGIN   
       select @Updatequery=  ' UPDATE  AR  SET First = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=1 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET First = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=1 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN  
   select @Updatequery=  ' UPDATE  AR  SET First = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=1 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET First = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=1 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rStudentHeightWeight = 1)
BEGIN   
        select @Updatequery=  ' UPDATE  AR  SET Second = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=2 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Second = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=2 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN   
   select @Updatequery=  ' UPDATE  AR  SET Second = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=2 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Second = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=2 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rStudentHeightWeight = 1)
BEGIN   
   select @Updatequery=  ' UPDATE  AR  SET Third = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=3 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Third = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=3 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN  
   select @Updatequery=  ' UPDATE  AR  SET Third = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=3 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Third = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=3 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rStudentHeightWeight = 1)
BEGIN  
   select @Updatequery=  ' UPDATE  AR  SET Fourth = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=4 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Fourth = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=4 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN    
   select @Updatequery=  ' UPDATE  AR  SET Fourth = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=4 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Fourth = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=4 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''
   exec (@Updatequery)
END

If( @rStudentHeightWeight = 1)
BEGIN   
     select @Updatequery=  ' UPDATE  AR  SET Fifth = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=5 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Fifth = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=5 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN   
   select @Updatequery=  ' UPDATE  AR  SET Fifth = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=5 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Fifth = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=5 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rStudentHeightWeight = 1)
BEGIN  
     select @Updatequery=  ' UPDATE  AR  SET Sixth = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=6 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Sixth = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=6 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN  
   select @Updatequery=  ' UPDATE  AR  SET Sixth = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=6 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Sixth = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=6 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rStudentHeightWeight = 1)
BEGIN  
    select @Updatequery=  ' UPDATE  AR  SET Seventh = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=7 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Seventh = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=7 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN     
   select @Updatequery=  ' UPDATE  AR  SET Seventh = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=7 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Seventh = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=7 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rStudentHeightWeight = 1)
BEGIN   
   select @Updatequery=  ' UPDATE  AR  SET Eighth = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=8 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Eighth = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=8 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN 
   select @Updatequery=  ' UPDATE  AR  SET Eighth = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=8 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Eighth = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=8 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rStudentHeightWeight = 1)
BEGIN   
    select @Updatequery=  ' UPDATE  AR  SET Ninth = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=9 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Ninth = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=9 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN    
   select @Updatequery=  ' UPDATE  AR  SET Ninth = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=9 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Ninth = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=9 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rStudentHeightWeight = 1)
BEGIN 
   select @Updatequery=  ' UPDATE  AR  SET Tenth = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=10 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Tenth = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=10 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN    
   select @Updatequery=  ' UPDATE  AR  SET Tenth = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=10 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Tenth = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=10 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rStudentHeightWeight = 1)
BEGIN   
   select @Updatequery=  ' UPDATE  AR  SET Eleventh = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=11 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Eleventh = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=11 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN    
   select @Updatequery=  ' UPDATE  AR  SET Eleventh = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=11 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Eleventh = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=11 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rStudentHeightWeight = 1)
BEGIN
   select @Updatequery=  ' UPDATE  AR  SET Twelfth = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=12 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Twelfth = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=12 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN  
   select @Updatequery=  ' UPDATE  AR  SET Twelfth = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=12 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Twelfth = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=12 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END   
  ---Sub Exam 1 Ends   
  ---Sub Exam 2 Starts

If( @rStudentHeightWeight = 1)
BEGIN   
   	select @Updatequery=  ' UPDATE  AR  SET PG1 = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=101 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET PG1 = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=101 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN   
   select @Updatequery=  ' UPDATE  AR  SET PG1 = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=101 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET PG1 = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=101 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END   

If( @rStudentHeightWeight = 1)
BEGIN   
	select @Updatequery=  ' UPDATE  AR  SET Nursary1 = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=102 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Nursary1 = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=102 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN     
   select @Updatequery=  ' UPDATE  AR  SET Nursary1 = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=102 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Nursary1 = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=102 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
	exec (@Updatequery)
END

If( @rStudentHeightWeight = 1)
BEGIN
   select @Updatequery=  ' UPDATE  AR  SET JrKg1 = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=103 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET JrKg1 = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=103 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN 
   select @Updatequery=  ' UPDATE  AR  SET JrKg1 = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=103 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET JrKg1 = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=103 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rStudentHeightWeight = 1)
BEGIN
   select @Updatequery=  ' UPDATE  AR  SET SrKg1 = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=104 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET SrKg1 = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=104 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN   
   select @Updatequery=  ' UPDATE  AR  SET SrKg1 = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=104 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET SrKg1 = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=104 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rStudentHeightWeight = 1)
BEGIN   
    select @Updatequery=  ' UPDATE  AR  SET First1 = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=1 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET First1 = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=1 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN    
   select @Updatequery=  ' UPDATE  AR  SET First1 = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=1 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET First1 = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=1 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''
   exec (@Updatequery)
END

If( @rStudentHeightWeight = 1)
BEGIN
    select @Updatequery=  ' UPDATE  AR  SET Second1 = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=2 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Second1 = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=2 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN
   select @Updatequery=  ' UPDATE  AR  SET Second1 = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=2 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Second1 = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=2 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rStudentHeightWeight = 1)
BEGIN
   select @Updatequery=  ' UPDATE  AR  SET Third1 = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=3 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Third1 = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=3 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN
   select @Updatequery=  ' UPDATE  AR  SET Third1 = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=3 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Third1 = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=3 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rStudentHeightWeight = 1)
BEGIN
   select @Updatequery=  ' UPDATE  AR  SET Fourth1 = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=4 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Fourth1 = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=4 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN 
   select @Updatequery=  ' UPDATE  AR  SET Fourth1 = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=4 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Fourth1 = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=4 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rStudentHeightWeight = 1)
BEGIN   
     select @Updatequery=  ' UPDATE  AR  SET Fifth1 = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=5 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Fifth1 = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=5 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN  
   select @Updatequery=  ' UPDATE  AR  SET Fifth1 = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=5 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Fifth1 = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=5 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rStudentHeightWeight = 1)
BEGIN
   select @Updatequery=  ' UPDATE  AR  SET Sixth1 = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=6 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Sixth1 = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=6 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN
   select @Updatequery=  ' UPDATE  AR  SET Sixth1 = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=6 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Sixth1 = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=6 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rStudentHeightWeight = 1)
BEGIN
    select @Updatequery=  ' UPDATE  AR  SET Seventh1 = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=7 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Seventh1 = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=7 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN
   select @Updatequery=  ' UPDATE  AR  SET Seventh1 = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=7 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Seventh1 = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=7 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rStudentHeightWeight = 1)
BEGIN
   select @Updatequery=  ' UPDATE  AR  SET Eighth1 = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=8 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Eighth1 = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=8 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN  
   select @Updatequery=  ' UPDATE  AR  SET Eighth1 = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=8 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Eighth1 = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=8 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rStudentHeightWeight = 1)
BEGIN 
    select @Updatequery=  ' UPDATE  AR  SET Ninth1 = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=9 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Ninth1 = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=9 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN    
   select @Updatequery=  ' UPDATE  AR  SET Ninth1 = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=9 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Ninth1 = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=9 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rStudentHeightWeight = 1)
BEGIN   
   select @Updatequery=  ' UPDATE  AR  SET Tenth1 = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=10 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Tenth1 = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=10 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN    
   select @Updatequery=  ' UPDATE  AR  SET Tenth1 = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=10 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Tenth1 = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=10 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rStudentHeightWeight = 1)
BEGIN   
   select @Updatequery=  ' UPDATE  AR  SET Eleventh1 = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=11 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Eleventh1 = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=11 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN    
   select @Updatequery=  ' UPDATE  AR  SET Eleventh1 = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=11 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Eleventh1 = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=11 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rStudentHeightWeight = 1)
BEGIN   
    select @Updatequery=  ' UPDATE  AR  SET Twelfth1 = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=12 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Twelfth1 = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=12 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN     
   select @Updatequery=  ' UPDATE  AR  SET Twelfth1 = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=12 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Twelfth1 = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=12 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END   
  ---Sub Exam 2 Ends   
  ---Sub Exam 3 Starts

If( @rStudentHeightWeight = 1)
BEGIN   
   select @Updatequery=  ' UPDATE  AR  SET PG2 = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=101 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET PG2 = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=101 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN   
   select @Updatequery=  ' UPDATE  AR  SET PG2 = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=101 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET PG2 = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=101 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''
   exec (@Updatequery)
END

If( @rStudentHeightWeight = 1)
BEGIN
	select @Updatequery=  ' UPDATE  AR  SET Nursary2 = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=102 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Nursary2 = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=102 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN   
   select @Updatequery=  ' UPDATE  AR  SET Nursary2 = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=102 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Nursary2 = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=102 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''
   exec (@Updatequery)
END

If( @rStudentHeightWeight = 1)
BEGIN   
   select @Updatequery=  ' UPDATE  AR  SET JrKg2 = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=103 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET JrKg2 = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=103 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN    
   select @Updatequery=  ' UPDATE  AR  SET JrKg2 = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=103 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET JrKg2 = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=103 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rStudentHeightWeight = 1)
BEGIN   
    select @Updatequery=  ' UPDATE  AR  SET SrKg2 = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=104 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET SrKg2 = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=104 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN    
   select @Updatequery=  ' UPDATE  AR  SET SrKg2 = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=104 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET SrKg2 = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=104 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rStudentHeightWeight = 1)
BEGIN   
       select @Updatequery=  ' UPDATE  AR  SET First2 = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=1 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET First2 = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=1 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN    
   select @Updatequery=  ' UPDATE  AR  SET First2 = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=1 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET First2 = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=1 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END
   
If( @rStudentHeightWeight = 1)
BEGIN
     select @Updatequery=  ' UPDATE  AR  SET Second2 = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=2 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Second2 = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=2 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN    
   select @Updatequery=  ' UPDATE  AR  SET Second2 = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=2 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Second2 = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=2 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rStudentHeightWeight = 1)
BEGIN   
   select @Updatequery=  ' UPDATE  AR  SET Third2 = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=3 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Third2 = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=3 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN    
   select @Updatequery=  ' UPDATE  AR  SET Third2 = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=3 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Third2 = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=3 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rStudentHeightWeight = 1)
BEGIN   
   select @Updatequery=  ' UPDATE  AR  SET Fourth2 = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=4 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Fourth2 = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=4 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN   
   select @Updatequery=  ' UPDATE  AR  SET Fourth2 = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=4 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Fourth2 = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=4 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rStudentHeightWeight = 1)
BEGIN   
   select @Updatequery=  ' UPDATE  AR  SET Fifth2 = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=5 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Fifth2 = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=5 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN   
   select @Updatequery=  ' UPDATE  AR  SET Fifth2 = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=5 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Fifth2 = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=5 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rStudentHeightWeight = 1)
BEGIN   
   select @Updatequery=  ' UPDATE  AR  SET Sixth2 = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=6 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Sixth2 = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=6 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN    
   select @Updatequery=  ' UPDATE  AR  SET Sixth2 = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=6 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Sixth2 = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=6 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rStudentHeightWeight = 1)
BEGIN   
    select @Updatequery=  ' UPDATE  AR  SET Seventh2 = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=7 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Seventh2 = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=7 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN    
   select @Updatequery=  ' UPDATE  AR  SET Seventh2 = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=7 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Seventh2 = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=7 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rStudentHeightWeight = 1)
BEGIN   
   select @Updatequery=  ' UPDATE  AR  SET Eighth2 = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=8 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Eighth2 = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=8 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN   
   select @Updatequery=  ' UPDATE  AR  SET Eighth2 = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=8 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Eighth2 = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=8 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rStudentHeightWeight = 1)
BEGIN   
    select @Updatequery=  ' UPDATE  AR  SET Ninth2 = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=9 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Ninth2 = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=9 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN   
   select @Updatequery=  ' UPDATE  AR  SET Ninth2 = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=9 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Ninth2 = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=9 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rStudentHeightWeight = 1)
BEGIN   
   select @Updatequery=  ' UPDATE  AR  SET Tenth2 = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=10 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Tenth2 = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=10 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN    
   select @Updatequery=  ' UPDATE  AR  SET Tenth2 = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=10 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Tenth2 = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=10 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rStudentHeightWeight = 1)
BEGIN   
   select @Updatequery=  ' UPDATE  AR  SET Eleventh2 = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=11 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Eleventh2 = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=11 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN   
   select @Updatequery=  ' UPDATE  AR  SET Eleventh2 = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=11 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Eleventh2 = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=11 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rStudentHeightWeight = 1)
BEGIN   
   select @Updatequery=  ' UPDATE  AR  SET Twelfth2 = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=12 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Twelfth2 = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=12 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN   
   select @Updatequery=  ' UPDATE  AR  SET Twelfth2 = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=12 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Twelfth2 = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=12 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END
END  
   -- Sub Exam 3 Ends   
 --   End Here Height, Weight, TotalDays, PresentDays Update 

 --add for 27332 mantis start
	CREATE TABLE #TempAllBatchClassGroup
	(
		ClassGroupId int,
		ClassGroupName nvarchar(50),
		IsObsolete bit
	)
	INSERT INTO #TempAllBatchClassGroup
	SELECT CM.Id AS ClassGroupId ,
		CM.Title AS ClassGroupName,
		CASE  WHEN BG.ClassGroupId IS null THEN 0 Else 1 END AS IsObsolete
	FROM sSetup.tClassGroupMaster CM
		LEFT JOIN  sAssessment.tAllBatchClassGroup BG  ON CM.Id=BG.ClassGroupId AND BG.OrgId=@rOrgId
	WHERE CM.Id In (103,101,102,104,1,2,3,4,5,6,7,8,9,10,11,12)

	DECLARE @lIsObsoletePG bit, @lIsObsoleteNursary bit, @lIsObsoleteJrKg bit, @lIsObsoleteSrKg bit, @lIsObsoleteFirst bit, @lIsObsoleteSecond bit, @lIsObsoleteThird bit, @lIsObsoleteFourth bit, @lIsObsoleteFifth bit, @lIsObsoleteSixth bit, @lIsObsoleteSeventh bit, @lIsObsoleteEighth bit, @lIsObsoleteNinth bit, @lIsObsoleteTenth bit, @lIsObsoleteEleventh bit, @lIsObsoleteTwelfth bit

	SELECT @lIsObsoletePG = IsObsolete from #TempAllBatchClassGroup WHERE ClassGroupId = 101
	SELECT @lIsObsoleteNursary = IsObsolete from #TempAllBatchClassGroup WHERE ClassGroupId = 102
	SELECT @lIsObsoleteJrKg = IsObsolete from #TempAllBatchClassGroup WHERE ClassGroupId = 103
	SELECT @lIsObsoleteSrKg = IsObsolete from #TempAllBatchClassGroup WHERE ClassGroupId = 104
	SELECT @lIsObsoleteFirst = IsObsolete from #TempAllBatchClassGroup WHERE ClassGroupId = 1
	SELECT @lIsObsoleteSecond = IsObsolete from #TempAllBatchClassGroup WHERE ClassGroupId = 2
	SELECT @lIsObsoleteThird = IsObsolete from #TempAllBatchClassGroup WHERE ClassGroupId = 3
	SELECT @lIsObsoleteFourth = IsObsolete from #TempAllBatchClassGroup WHERE ClassGroupId = 4
	SELECT @lIsObsoleteFifth = IsObsolete from #TempAllBatchClassGroup WHERE ClassGroupId = 5
	SELECT @lIsObsoleteSixth = IsObsolete from #TempAllBatchClassGroup WHERE ClassGroupId = 6
	SELECT @lIsObsoleteSeventh = IsObsolete from #TempAllBatchClassGroup WHERE ClassGroupId = 7
	SELECT @lIsObsoleteEighth = IsObsolete from #TempAllBatchClassGroup WHERE ClassGroupId = 8
	SELECT @lIsObsoleteNinth = IsObsolete from #TempAllBatchClassGroup WHERE ClassGroupId = 9
	SELECT @lIsObsoleteTenth = IsObsolete from #TempAllBatchClassGroup WHERE ClassGroupId = 10
	SELECT @lIsObsoleteEleventh = IsObsolete from #TempAllBatchClassGroup WHERE ClassGroupId = 11
	SELECT @lIsObsoleteTwelfth = IsObsolete from #TempAllBatchClassGroup WHERE ClassGroupId = 12
--27332 mantis end

	If( @rTotalDaysPresentDays = 1 AND @rStudentHeightWeight = 1)	
	BEGIN
	   select @query='SELECT AR.StudentId,
			Case When AR.SubjectId > 0 then SM.Id 
			When AR.SubjectId = -1 then 999999991 
		 	When AR.SubjectId = -2 then 999999992 
		 	When AR.SubjectId = -3 then 999999993
		 	When AR.SubjectId = -4 then 999999994 end AS SubjectId,
			Isnull(PG,'''') AS PG,Isnull(Nursary,'''') AS Nursary,Isnull(SrKg,'''') AS SrKg , Isnull(JrKg,'''') AS JrKg,Isnull(First,'''') AS FirstAnnual,
		 	Isnull(Second,'''') AS Second, Isnull(Third,'''') As  Third, Isnull(Fourth,'''') AS Fourth,Isnull(Fifth,'''') AS Fifth, Isnull(Sixth,'''') AS Sixth, Isnull(Seventh,'''') AS Seventh, Isnull(Eighth,'''') AS Eighth, Isnull(Ninth,'''') AS Ninth, 
		 	Isnull(Tenth,'''') As Tenth, Isnull(Eleventh,'''') As Eleventh, Isnull(Twelfth,'''') As Twelfth ,
		 	Isnull(PG1,'''') AS PG1,Isnull(Nursary1,'''') AS Nursary1,Isnull(SrKg1,'''') AS SrKg1 , Isnull(JrKg1,'''') AS JrKg1,Isnull(First1,'''') AS First1,
		 	Isnull(Second1,'''') AS Second1, Isnull(Third1,'''') As  Third1, Isnull(Fourth1,'''') AS Fourth1,Isnull(Fifth1,'''') AS Fifth1, Isnull(Sixth1,'''') AS Sixth1, Isnull(Seventh1,'''') AS Seventh1, Isnull(Eighth1,'''') AS Eighth1, Isnull(Ninth1,'''') AS Ninth1, 
		 	Isnull(Tenth1,'''') As Tenth1, Isnull(Eleventh1,'''') As Eleventh1, Isnull(Twelfth1,'''') As Twelfth1,
		 	Isnull(PG2,'''') AS PG2,Isnull(Nursary2,'''') AS Nursary2,Isnull(SrKg2,'''') AS SrKg2 , Isnull(JrKg2,'''') AS JrKg2,Isnull(First2,'''') AS First2,
		 	Isnull(Second2,'''') AS Second2, Isnull(Third2,'''') As  Third2, Isnull(Fourth2,'''') AS Fourth2,Isnull(Fifth2,'''') AS Fifth2, Isnull(Sixth2,'''') AS Sixth2, Isnull(Seventh2,'''') AS Seventh2, Isnull(Eighth2,'''') AS Eighth2, Isnull(Ninth2,'''') AS Ninth2, 
		 	Isnull(Tenth2,'''') As Tenth2, Isnull(Eleventh2,'''') As Eleventh2, Isnull(Twelfth2,'''') As Twelfth2
		 	,Case When AR.SubjectId > 0 then SM.Code 
		 	When AR.SubjectId = -1 then ''HEIGHT'' 
		 	When AR.SubjectId = -2 then ''WEIGHT'' 
		 	When AR.SubjectId = -3 then ''TOTAL DAYS'' 
		 	When AR.SubjectId = -4 then ''PRESENT DAYS''		 	
		 	end As SubjectCode,A.Code,A.Name,A.BatchName,A.BatchId,SM.OrderIndex,A.RollNo,
			'+convert(varchar,@lIsObsoletePG)+' AS IsObsoletePG, ' + convert(varchar,@lIsObsoleteNursary) + ' AS IsObsoleteNursary, 
			' + convert(varchar,@lIsObsoleteJrKg) + ' AS IsObsoleteJrKg, ' + convert(varchar,@lIsObsoleteSrKg) + ' AS IsObsoleteSrKg,
			' + convert(varchar,@lIsObsoleteFirst) + ' AS IsObsoleteFirst, ' + convert(varchar,@lIsObsoleteSecond) + ' AS IsObsoleteSecond, 
			' + convert(varchar,@lIsObsoleteThird) + ' AS IsObsoleteThird, ' + convert(varchar,@lIsObsoleteFourth) + ' AS IsObsoleteFourth,
			' + convert(varchar,@lIsObsoleteFifth) + ' AS IsObsoleteFifth, ' + convert(varchar,@lIsObsoleteSixth) + ' AS IsObsoleteSixth, 
			' + convert(varchar,@lIsObsoleteSeventh) + ' AS IsObsoleteSeventh, ' + convert(varchar,@lIsObsoleteEighth) + ' AS IsObsoleteEighth,
			' + convert(varchar,@lIsObsoleteNinth) + ' AS IsObsoleteNinth, ' + convert(varchar,@lIsObsoleteTenth) + ' AS IsObsoleteTenth, 
			' + convert(varchar,@lIsObsoleteEleventh) + ' AS IsObsoleteEleventh, ' + convert(varchar,@lIsObsoleteTwelfth) + ' AS IsObsoleteTwelfth 	
		    FROM sStudent.vStudentLastAcademic A  
		    INNER JOIN  sAssessment.tAllBatchResultGrade AR ON  AR.StudentId=A.StudentId 
	        LEFT JOIN sSetup.tSubjectMaster SM ON SM.Id=AR.SubjectId 
		    WHERE A.OrgId=' + convert(varchar,@lOrgId) + ''
		execute (@query)	
	END
	
	If( @rStudentHeightWeight = 1)	
	BEGIN
	   select @query='SELECT AR.StudentId,
			Case When AR.SubjectId > 0 then SM.Id 
			When AR.SubjectId = -1 then 999999991 
		 	When AR.SubjectId = -2 then 999999992 end AS SubjectId,		 	
			Isnull(PG,'''') AS PG,Isnull(Nursary,'''') AS Nursary,Isnull(SrKg,'''') AS SrKg , Isnull(JrKg,'''') AS JrKg,Isnull(First,'''') AS FirstAnnual,
		 	Isnull(Second,'''') AS Second, Isnull(Third,'''') As  Third, Isnull(Fourth,'''') AS Fourth,Isnull(Fifth,'''') AS Fifth, Isnull(Sixth,'''') AS Sixth, Isnull(Seventh,'''') AS Seventh, Isnull(Eighth,'''') AS Eighth, Isnull(Ninth,'''') AS Ninth, 
		 	Isnull(Tenth,'''') As Tenth, Isnull(Eleventh,'''') As Eleventh, Isnull(Twelfth,'''') As Twelfth ,
		 	Isnull(PG1,'''') AS PG1,Isnull(Nursary1,'''') AS Nursary1,Isnull(SrKg1,'''') AS SrKg1 , Isnull(JrKg1,'''') AS JrKg1,Isnull(First1,'''') AS First1,
		 	Isnull(Second1,'''') AS Second1, Isnull(Third1,'''') As  Third1, Isnull(Fourth1,'''') AS Fourth1,Isnull(Fifth1,'''') AS Fifth1, Isnull(Sixth1,'''') AS Sixth1, Isnull(Seventh1,'''') AS Seventh1, Isnull(Eighth1,'''') AS Eighth1, Isnull(Ninth1,'''') AS Ninth1, 
		 	Isnull(Tenth1,'''') As Tenth1, Isnull(Eleventh1,'''') As Eleventh1, Isnull(Twelfth1,'''') As Twelfth1,
		 	Isnull(PG2,'''') AS PG2,Isnull(Nursary2,'''') AS Nursary2,Isnull(SrKg2,'''') AS SrKg2 , Isnull(JrKg2,'''') AS JrKg2,Isnull(First2,'''') AS First2,
		 	Isnull(Second2,'''') AS Second2, Isnull(Third2,'''') As  Third2, Isnull(Fourth2,'''') AS Fourth2,Isnull(Fifth2,'''') AS Fifth2, Isnull(Sixth2,'''') AS Sixth2, Isnull(Seventh2,'''') AS Seventh2, Isnull(Eighth2,'''') AS Eighth2, Isnull(Ninth2,'''') AS Ninth2, 
		 	Isnull(Tenth2,'''') As Tenth2, Isnull(Eleventh2,'''') As Eleventh2, Isnull(Twelfth2,'''') As Twelfth2
		 	,Case When AR.SubjectId > 0 then SM.Code 
		 	When AR.SubjectId = -1 then ''HEIGHT'' 
		 	When AR.SubjectId = -2 then ''WEIGHT'' 
		 	end As SubjectCode,A.Code,A.Name,A.BatchName,A.BatchId,SM.OrderIndex,A.RollNo,
			'+convert(varchar,@lIsObsoletePG)+' AS IsObsoletePG, ' + convert(varchar,@lIsObsoleteNursary) + ' AS IsObsoleteNursary, 
			' + convert(varchar,@lIsObsoleteJrKg) + ' AS IsObsoleteJrKg, ' + convert(varchar,@lIsObsoleteSrKg) + ' AS IsObsoleteSrKg,
			' + convert(varchar,@lIsObsoleteFirst) + ' AS IsObsoleteFirst, ' + convert(varchar,@lIsObsoleteSecond) + ' AS IsObsoleteSecond, 
			' + convert(varchar,@lIsObsoleteThird) + ' AS IsObsoleteThird, ' + convert(varchar,@lIsObsoleteFourth) + ' AS IsObsoleteFourth,
			' + convert(varchar,@lIsObsoleteFifth) + ' AS IsObsoleteFifth, ' + convert(varchar,@lIsObsoleteSixth) + ' AS IsObsoleteSixth, 
			' + convert(varchar,@lIsObsoleteSeventh) + ' AS IsObsoleteSeventh, ' + convert(varchar,@lIsObsoleteEighth) + ' AS IsObsoleteEighth,
			' + convert(varchar,@lIsObsoleteNinth) + ' AS IsObsoleteNinth, ' + convert(varchar,@lIsObsoleteTenth) + ' AS IsObsoleteTenth, 
			' + convert(varchar,@lIsObsoleteEleventh) + ' AS IsObsoleteEleventh, ' + convert(varchar,@lIsObsoleteTwelfth) + ' AS IsObsoleteTwelfth 	
		    FROM sStudent.vStudentLastAcademic A  
		    INNER JOIN  sAssessment.tAllBatchResultGrade AR ON  AR.StudentId=A.StudentId 
	        LEFT JOIN sSetup.tSubjectMaster SM ON SM.Id=AR.SubjectId 
		    WHERE A.OrgId=' + convert(varchar,@lOrgId) + ''
	   execute (@query)	
	END
	
	IF( @rTotalDaysPresentDays = 1)	
	BEGIN
       select @query='SELECT AR.StudentId,
			Case When AR.SubjectId > 0 then SM.Id
		 	When AR.SubjectId = -3 then 999999993
		 	When AR.SubjectId = -4 then 999999994 end AS SubjectId,
			Isnull(PG,'''') AS PG,Isnull(Nursary,'''') AS Nursary,Isnull(SrKg,'''') AS SrKg , Isnull(JrKg,'''') AS JrKg,Isnull(First,'''') AS FirstAnnual,
		 	Isnull(Second,'''') AS Second, Isnull(Third,'''') As  Third, Isnull(Fourth,'''') AS Fourth,Isnull(Fifth,'''') AS Fifth, Isnull(Sixth,'''') AS Sixth, Isnull(Seventh,'''') AS Seventh, Isnull(Eighth,'''') AS Eighth, Isnull(Ninth,'''') AS Ninth, 
		 	Isnull(Tenth,'''') As Tenth, Isnull(Eleventh,'''') As Eleventh, Isnull(Twelfth,'''') As Twelfth ,
		 	Isnull(PG1,'''') AS PG1,Isnull(Nursary1,'''') AS Nursary1,Isnull(SrKg1,'''') AS SrKg1 , Isnull(JrKg1,'''') AS JrKg1,Isnull(First1,'''') AS First1,
		 	Isnull(Second1,'''') AS Second1, Isnull(Third1,'''') As  Third1, Isnull(Fourth1,'''') AS Fourth1,Isnull(Fifth1,'''') AS Fifth1, Isnull(Sixth1,'''') AS Sixth1, Isnull(Seventh1,'''') AS Seventh1, Isnull(Eighth1,'''') AS Eighth1, Isnull(Ninth1,'''') AS Ninth1, 
		 	Isnull(Tenth1,'''') As Tenth1, Isnull(Eleventh1,'''') As Eleventh1, Isnull(Twelfth1,'''') As Twelfth1,
		 	Isnull(PG2,'''') AS PG2,Isnull(Nursary2,'''') AS Nursary2,Isnull(SrKg2,'''') AS SrKg2 , Isnull(JrKg2,'''') AS JrKg2,Isnull(First2,'''') AS First2,
		 	Isnull(Second2,'''') AS Second2, Isnull(Third2,'''') As  Third2, Isnull(Fourth2,'''') AS Fourth2,Isnull(Fifth2,'''') AS Fifth2, Isnull(Sixth2,'''') AS Sixth2, Isnull(Seventh2,'''') AS Seventh2, Isnull(Eighth2,'''') AS Eighth2, Isnull(Ninth2,'''') AS Ninth2, 
		 	Isnull(Tenth2,'''') As Tenth2, Isnull(Eleventh2,'''') As Eleventh2, Isnull(Twelfth2,'''') As Twelfth2
		 	,Case When AR.SubjectId > 0 then SM.Code
		 	When AR.SubjectId = -3 then ''TOTAL DAYS'' 
		 	When AR.SubjectId = -4 then ''PRESENT DAYS''
		 	end As SubjectCode,A.Code,A.Name,A.BatchName,A.BatchId,SM.OrderIndex,A.RollNo,
			'+convert(varchar,@lIsObsoletePG)+' AS IsObsoletePG, ' + convert(varchar,@lIsObsoleteNursary) + ' AS IsObsoleteNursary, 
			' + convert(varchar,@lIsObsoleteJrKg) + ' AS IsObsoleteJrKg, ' + convert(varchar,@lIsObsoleteSrKg) + ' AS IsObsoleteSrKg,
			' + convert(varchar,@lIsObsoleteFirst) + ' AS IsObsoleteFirst, ' + convert(varchar,@lIsObsoleteSecond) + ' AS IsObsoleteSecond, 
			' + convert(varchar,@lIsObsoleteThird) + ' AS IsObsoleteThird, ' + convert(varchar,@lIsObsoleteFourth) + ' AS IsObsoleteFourth,
			' + convert(varchar,@lIsObsoleteFifth) + ' AS IsObsoleteFifth, ' + convert(varchar,@lIsObsoleteSixth) + ' AS IsObsoleteSixth, 
			' + convert(varchar,@lIsObsoleteSeventh) + ' AS IsObsoleteSeventh, ' + convert(varchar,@lIsObsoleteEighth) + ' AS IsObsoleteEighth,
			' + convert(varchar,@lIsObsoleteNinth) + ' AS IsObsoleteNinth, ' + convert(varchar,@lIsObsoleteTenth) + ' AS IsObsoleteTenth, 
			' + convert(varchar,@lIsObsoleteEleventh) + ' AS IsObsoleteEleventh, ' + convert(varchar,@lIsObsoleteTwelfth) + ' AS IsObsoleteTwelfth 	
		    FROM sStudent.vStudentLastAcademic A  
		    INNER JOIN  sAssessment.tAllBatchResultGrade AR ON  AR.StudentId=A.StudentId 
	        LEFT JOIN sSetup.tSubjectMaster SM ON SM.Id=AR.SubjectId 
		    WHERE A.OrgId=' + convert(varchar,@lOrgId) + ''
		execute (@query)	
	END
	
	ELSE
	BEGIN	
	   select @query='SELECT AR.StudentId,SM.Id AS SubjectId,Isnull(PG,'''') AS PG,Isnull(Nursary,'''') AS Nursary,Isnull(SrKg,'''') AS SrKg , Isnull(JrKg,'''') AS JrKg,Isnull(First,'''') AS FirstAnnual,
		 	Isnull(Second,'''') AS Second, Isnull(Third,'''') As  Third, Isnull(Fourth,'''') AS Fourth,Isnull(Fifth,'''') AS Fifth, Isnull(Sixth,'''') AS Sixth, Isnull(Seventh,'''') AS Seventh, Isnull(Eighth,'''') AS Eighth, Isnull(Ninth,'''') AS Ninth, 
		 	Isnull(Tenth,'''') As Tenth, Isnull(Eleventh,'''') As Eleventh, Isnull(Twelfth,'''') As Twelfth ,
		 	Isnull(PG1,'''') AS PG1,Isnull(Nursary1,'''') AS Nursary1,Isnull(SrKg1,'''') AS SrKg1 , Isnull(JrKg1,'''') AS JrKg1,Isnull(First1,'''') AS First1,
		 	Isnull(Second1,'''') AS Second1, Isnull(Third1,'''') As  Third1, Isnull(Fourth1,'''') AS Fourth1,Isnull(Fifth1,'''') AS Fifth1, Isnull(Sixth1,'''') AS Sixth1, Isnull(Seventh1,'''') AS Seventh1, Isnull(Eighth1,'''') AS Eighth1, Isnull(Ninth1,'''') AS Ninth1, 
		 	Isnull(Tenth1,'''') As Tenth1, Isnull(Eleventh1,'''') As Eleventh1, Isnull(Twelfth1,'''') As Twelfth1,
		 	Isnull(PG2,'''') AS PG2,Isnull(Nursary2,'''') AS Nursary2,Isnull(SrKg2,'''') AS SrKg2 , Isnull(JrKg2,'''') AS JrKg2,Isnull(First2,'''') AS First2,
		 	Isnull(Second2,'''') AS Second2, Isnull(Third2,'''') As  Third2, Isnull(Fourth2,'''') AS Fourth2,Isnull(Fifth2,'''') AS Fifth2, Isnull(Sixth2,'''') AS Sixth2, Isnull(Seventh2,'''') AS Seventh2, Isnull(Eighth2,'''') AS Eighth2, Isnull(Ninth2,'''') AS Ninth2, 
		 	Isnull(Tenth2,'''') As Tenth2, Isnull(Eleventh2,'''') As Eleventh2, Isnull(Twelfth2,'''') As Twelfth2
		 	,SM.Code As SubjectCode,A.Code,A.Name,A.BatchName,A.BatchId,SM.OrderIndex,A.RollNo,
			'+convert(varchar,@lIsObsoletePG)+' AS IsObsoletePG, ' + convert(varchar,@lIsObsoleteNursary) + ' AS IsObsoleteNursary, 
			' + convert(varchar,@lIsObsoleteJrKg) + ' AS IsObsoleteJrKg, ' + convert(varchar,@lIsObsoleteSrKg) + ' AS IsObsoleteSrKg,
			' + convert(varchar,@lIsObsoleteFirst) + ' AS IsObsoleteFirst, ' + convert(varchar,@lIsObsoleteSecond) + ' AS IsObsoleteSecond, 
			' + convert(varchar,@lIsObsoleteThird) + ' AS IsObsoleteThird, ' + convert(varchar,@lIsObsoleteFourth) + ' AS IsObsoleteFourth,
			' + convert(varchar,@lIsObsoleteFifth) + ' AS IsObsoleteFifth, ' + convert(varchar,@lIsObsoleteSixth) + ' AS IsObsoleteSixth, 
			' + convert(varchar,@lIsObsoleteSeventh) + ' AS IsObsoleteSeventh, ' + convert(varchar,@lIsObsoleteEighth) + ' AS IsObsoleteEighth,
			' + convert(varchar,@lIsObsoleteNinth) + ' AS IsObsoleteNinth, ' + convert(varchar,@lIsObsoleteTenth) + ' AS IsObsoleteTenth, 
			' + convert(varchar,@lIsObsoleteEleventh) + ' AS IsObsoleteEleventh, ' + convert(varchar,@lIsObsoleteTwelfth) + ' AS IsObsoleteTwelfth 	
		    FROM sStudent.vStudentLastAcademic A  
		    INNER JOIN sAssessment.tAllBatchResultGrade AR ON  AR.StudentId=A.StudentId 
	        LEFT JOIN sSetup.tSubjectMaster SM ON SM.Id=AR.SubjectId 
		    WHERE A.OrgId=' + convert(varchar,@lOrgId) + ''	
	    execute (@query)
		print @query

		DROP TABLE #TempAllBatchClassGroup

	--SELECT
	--	CONVERT(BIGINT, 0) AS StudentId,
	--	0 AS SubjectId,
	--	CONVERT(NVARCHAR(10),'') AS PG,
	--	CONVERT(NVARCHAR(10),'') AS Nursary,
	--	CONVERT(NVARCHAR(10),'') AS SrKg,
	--	CONVERT(NVARCHAR(10),'') AS JrKg,
	--	CONVERT(NVARCHAR(10),'') AS FirstAnnual,
	--	CONVERT(NVARCHAR(10),'') AS Second, 
	--	CONVERT(NVARCHAR(10),'') As  Third, 
	--	CONVERT(NVARCHAR(10),'') AS Fourth,
	--	CONVERT(NVARCHAR(10),'') AS Fifth, 
	--	CONVERT(NVARCHAR(10),'') AS Sixth, 
	--	CONVERT(NVARCHAR(10),'') AS Seventh, 
	--	CONVERT(NVARCHAR(10),'') AS Eighth, 
	--	CONVERT(NVARCHAR(10),'') AS Ninth, 
	--	CONVERT(NVARCHAR(10),'') As Tenth, 
	--	CONVERT(NVARCHAR(10),'') As Eleventh, 
	--	CONVERT(NVARCHAR(10),'') As Twelfth ,
	--	CONVERT(NVARCHAR(10),'') AS PG1,
	--	CONVERT(NVARCHAR(10),'') AS Nursary1,
	--	CONVERT(NVARCHAR(10),'') AS SrKg1 , 
	--	CONVERT(NVARCHAR(10),'') AS JrKg1,
	--	CONVERT(NVARCHAR(10),'') AS First1,
	--	CONVERT(NVARCHAR(10),'') AS Second1, 
	--	CONVERT(NVARCHAR(10),'') As  Third1, 
	--	CONVERT(NVARCHAR(10),'') AS Fourth1,
	--	CONVERT(NVARCHAR(10),'') AS Fifth1, 
	--	CONVERT(NVARCHAR(10),'') AS Sixth1, 
	--	CONVERT(NVARCHAR(10),'') AS Seventh1, 
	--	CONVERT(NVARCHAR(10),'') AS Eighth1, 
	--	CONVERT(NVARCHAR(10),'') AS Ninth1, 
	--	CONVERT(NVARCHAR(10),'') As Tenth1, 
	--	CONVERT(NVARCHAR(10),'') As Eleventh1, 
	--	CONVERT(NVARCHAR(10),'') As Twelfth1,
	--	CONVERT(NVARCHAR(10),'') AS PG2,
	--	CONVERT(NVARCHAR(10),'') AS Nursary2,
	--	CONVERT(NVARCHAR(10),'') AS SrKg2 , 
	--	CONVERT(NVARCHAR(10),'') AS JrKg2,
	--	CONVERT(NVARCHAR(10),'') AS First2,
	--	CONVERT(NVARCHAR(10),'') AS Second2, 
	--	CONVERT(NVARCHAR(10),'') As  Third2, 
	--	CONVERT(NVARCHAR(10),'') AS Fourth2,
	--	CONVERT(NVARCHAR(10),'') AS Fifth2, 
	--	CONVERT(NVARCHAR(10),'') AS Sixth2, 
	--	CONVERT(NVARCHAR(10),'') AS Seventh2, 
	--	CONVERT(NVARCHAR(10),'') AS Eighth2, 
	--	CONVERT(NVARCHAR(10),'') AS Ninth2, 
	--	CONVERT(NVARCHAR(10),'') As Tenth2, 
	--	CONVERT(NVARCHAR(10),'') As Eleventh2, 
	--	CONVERT(NVARCHAR(10),'') As Twelfth2,
	--	CONVERT(NVARCHAR(20),'') AS SubjectCode,
	--	CONVERT(NVARCHAR(20),'') as Code,
	--	CONVERT(NVARCHAR(300),'') as Name,
	--	CONVERT(NVARCHAR(100),'') as BatchName,
	--	0 as BatchId,
	--	CONVERT(SMALLINT,0) AS OrderIndex,
	--	0 AS RollNo,
	--	CONVERT(BIT,0) AS IsObsoletePG,
	--	CONVERT(BIT,0) AS IsObsoleteNursary,
	--	CONVERT(BIT,0) AS IsObsoleteJrKg,
	--	CONVERT(BIT,0) AS IsObsoleteSrKg,
	--	CONVERT(BIT,0) AS IsObsoleteFirst,
	--	CONVERT(BIT,0) AS IsObsoleteSecond,
	--	CONVERT(BIT,0) AS IsObsoleteThird,
	--	CONVERT(BIT,0) AS IsObsoleteFourth,
	--	CONVERT(BIT,0) AS IsObsoleteFifth,
	--	CONVERT(BIT,0) AS IsObsoleteSixth,
	--	CONVERT(BIT,0) AS IsObsoleteSeventh,
	--	CONVERT(BIT,0) AS IsObsoleteEighth,
	--	CONVERT(BIT,0) AS IsObsoleteNinth,
	--	CONVERT(BIT,0) AS IsObsoleteTenth,
	--	CONVERT(BIT,0) AS IsObsoleteEleventh,
	--	CONVERT(BIT,0) AS IsObsoleteTwelfth
		
END
GO
PRINT N'Altering Procedure [sAssessment].[pRptProgressCardGet]...';


GO

ALTER PROCEDURE [sAssessment].[pRptProgressCardGet]	 	 
	 @rClassId int,
	 @rBatchId int,
	 @rDivisionId int,	 
	 @rClassSubjectIdStr nvarchar(max),
	 @rExamGroupIdStr nvarchar(max),
	 @rFromDate Date='',
	 @rToDate Date='',
	 @rFromRollNo int=0,
	 @rToRollNo int=0,
	 @rAcadedmidId bigint=0
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 

 --Select * from dbo.TempTableForProgress
	--SELECT 
	--	Convert(BigInt,0) AS AcademicId,
	--	Convert(date,'') AS ExamDate,
	--	Convert(Decimal,0) AS Maximum,
	--	Convert(Decimal,0) AS Obtain,
	--	Convert(Decimal,0) AS Percentage,
	--	'' AS ExamTopic,
	--	'' AS SubjectName,
	--	'' AS ExamGroup,
	--	Convert(varbinary,0) AS StudentPhoto,
	--	'' AS ClassName,
	--	'' AS DivisionName,
	--	'' AS StudentName,
	--	0 AS RollNo,
	--    Convert(bit,0) AS IsMarksInDecimal,
	--	'' AS Year,
	--	'' AS MonthFrom,
	--	'' AS MonthTo,
	--	'' AS Code,
	--	'' AS EXAMNAME,
	--	'' AS ResultStatus,
	--	Convert(bit,0) As IsPresent

		

	CREATE TABLE #tempProgressCard
	(
		Id int Identity,
		AcademicId Bigint,
		ClassSubjectId bigint,
		ExamDate Date,
		Obtain Decimal(6,2),
		Maximum Decimal(6,2),
		Percentage Decimal(6,2),
		ExamId int,
		IsPresent bit
		
	)
 
 DECLARE @query  AS NVARCHAR(MAX)
 set @query = 'INSERT INTO #tempProgressCard 
 SELECT	R.AcademicId,ED.ClassSubjectId,ED.ExamDate ,SUM(RD.Obtain) AS Obtain,SUM(ED.Maximum) AS Maximum,
 (SUM(RD.Obtain)/SUM(ED.Maximum))*100 AS PERCENTAGE,ED.ExamId,RD.IsPresent
FROM sAssessment.tExamMaster EM INNER JOIN sAssessment.tResult R ON R.ExamId = EM.Id
INNER JOIN sAssessment.tResultDetail RD ON RD.ResultId = R.Id
INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId = EM.Id AND ED.Id = RD.ExamDetailId
INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId
INNER JOIN sAssessment.tExamGroupMaster EGM ON EGM.Id = ESGM.ExamGroupId
INNER JOIN sStudent.tAcademic AM ON AM.Id = R.AcademicId
WHERE EM.ClassId =' + CONVERT(NVARCHAR,@rClassId) + '
 

AND AM.DivisionId = ' + CONVERT(NVARCHAR(500),@rDivisionId) + '
AND EGM.Id IN (' + CONVERT(NVARCHAR(500),@rExamGroupIdStr) + ')
AND ED.ClassSubjectId IN (' + CONVERT(NVARCHAR(500),@rClassSubjectIdStr) + ')
AND ED.EXAMDATE >= ''' + CONVERT(NVARCHAR,@rFromDate) +
''' AND ED.EXAMDATE <= ''' + CONVERT(NVARCHAR,@rToDate) +
''' AND ((AM.RollNo >= '''+ CONVERT(NVARCHAR(10),@rFromRollNo)+''') OR (' + CONVERT(NVARCHAR(10),@rFromRollNo)+'='''+ CONVERT(NVARCHAR(10),0) + ''')) 
AND ((AM.RollNo <= '''+ CONVERT(NVARCHAR(10),@rToRollNo) + ''' ) OR (' + CONVERT(NVARCHAR(10),@rToRollNo)+'='''+ CONVERT(NVARCHAR(10),0) + ''')) 
AND ((AM.Id = '''+ CONVERT(NVARCHAR(20),@rAcadedmidId) + ''' ) OR (' + CONVERT(NVARCHAR(20),@rAcadedmidId)+'='''+ CONVERT(NVARCHAR(20),0) + ''')) 
GROUP BY R.AcademicId,ED.ClassSubjectId,ED.ExamDate,ED.ExamId,RD.IsPresent'
-- Remove RD.IsPresent = 1 Condition from @query (As requirement Absent and present students data should be visibled) Mantis :0027445
 --print @query
execute(@query)

-- To maintain Group Footer length add in report row	
--select 1, '.' + replicate('`', 600)  + '.'   font size 1

SELECT
T.AcademicId,
T.ExamDate,
T.Maximum,T.Obtain,T.Percentage,
CASE WHEN ED.ExamTopic = '0' THEN '' ELSE ED.ExamTopic  END AS ExamTopic,
CS.SubjectName AS SubjectName,
EGM.Title AS ExamGroup,
SF.StudentPhoto as StudentPhoto , 
SF.ClassName,
SF.DivisionName,
SF.Name AS StudentName,SF.RollNo, 
EM.IsMarksInDecimal,
SF.Code,
sCommon.fGetMonthName(DatePart(MM,@rFromDate)) AS MonthFrom,
sCommon.fGetMonthName(DatePart(MM,@rToDate)) AS MonthTo,
BM.Title AS Year,
ISNULL(ESGM.Title,'') AS EXAMNAME ,
(Select ResultStatus FROM sAssessment.tResult Where AcademicId = T.AcademicId AND  ExamId = EM.Id)AS ResultStatus,
T.IsPresent



FROM #tempProgressCard T 
INNER JOIN sAssessment.tExamMaster EM on EM.Id=T.ExamId
INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId = T.ExamId AND EM.Id=ED.ExamId AND T.ExamDate = ED.ExamDate
INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.EXAMSUBGROUPID
INNER JOIN sAssessment.tExamGroupMaster EGM ON EGM.Id = ESGM.ExamGroupId
--INNER JOIN sAssessment.tExamCombine EC ON EC.SubExamId=EM.Id
INNER JOIN sSetup.vClassSubject CS ON CS.ClassSubjectId = ED.ClassSubjectId AND CS.ClassSubjectId=T.ClassSubjectId 
INNER JOIN sStudent.vStudentFull SF ON SF.AcademicId	= T.AcademicId AND SF.StatusId=1
INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SF.BatchId
Order By SF.RollNo,CS.OrderIndex,T.ExamDate Desc



DROP TABLE #tempProgressCard

END
GO
PRINT N'Altering Procedure [sAssessment].[pRptProgressCardSubjectWiseDetailsGet]...';


GO


ALTER PROCEDURE [sAssessment].[pRptProgressCardSubjectWiseDetailsGet]
	 
	 @rBuilder1 nvarchar(max)='', 
	 @rBuilder2 nvarchar(max)='', 
	 @rBatchId int = 0,
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rExamId int,
	 @rCode nvarchar(20)='',
	 @rFromRollNo int,
	 @rToRollNo int,
	 @rStatusId int=0,
	 @rClassStatusId int=0
	 
	
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	--Select
	--	'' AS Builder1,
	--	'' AS Builder2,
	--	'' AS AcademicIdText,
	--	'' Code,
	--	'' AS Name,
	--		0 AS RollNo,
	--	Convert(BigInt,0) AcademicId,			
	--	'' ResultStatus,
	--	'' AS Class,
	--	'' AS Division,
	--  0 AS ExamId,
	--	'' AS ExamName,
	--  Convert(Date,null) AS ExamDate,
	--		Convert(Decimal,0) TotalMark,
	--	Convert(Decimal,0) TotalObtain,
	--	0 AS RankNumber,
	--	Convert(Decimal,0) Percentage,
	--	'' AS ResultGrade,
	--	Convert(Decimal,0) Percentile,
	--	Convert(BigInt,0) ResultDetailId,		
	--	Convert(Bit,0) IsDisplayInMarksheet,
	--	Convert(Bit,0) IsShowSubjectGrade,
	--	Convert(Bit,0) IsIncludeInTotal,
	--	Convert(Decimal,0) AS SubjectObtain,
	--  '' AS SubjectGrade,
	--	Convert(Decimal,0) AS SubjectMinimum,
	--	Convert(Decimal,0) AS SubjectMaximum,
	--		'' AS SubjectCode,
	--	'' AS SubjectName,
	--	0 AS SubjectOrderIndex,
	--	Convert(BigInt,0) AS ResultId,
	--	0 AS SubjectId,			 	
	--	Convert(Bit,0) IsMarksInDecimal,		
	--	'' AS Remark1,
	--	'' AS Remark2,
	--	'' AS Remark3,
	--	'' AS DisplayTitle,
	--	Convert(Bit,0) IsRankNo, 
	--	Convert(Bit,0) IsGrade,
	--	Convert(Bit,0) IsPercentile,
	--	Convert(Bit,0) IsPercentage,
	--	Convert(Bit,0) IsSubjectPercentile,
	--	Convert(Bit,0) IsProcessResult,			 
	--	Convert(Bit,0) IsNegativeMarks,
	--	Convert(Bit,0) IsIncludeCoScholastic,
	--	Convert(Bit,0) IsOnPrePrinted,
	--	Convert(Bit,0) IsDisplayPhoto,
	--	Convert(Bit,0) IsDisplayBirthDate,
	--	Convert(Bit,0) IsLockForEdit,
	--	Convert(Bit,0) IsDisplaySchoolName,			
	--	Convert(Bit,0) IsDisplayAttendance,
	--	Convert(Bit,0) IsDisplayHeightWeight,
	--	Convert(Bit,0) IsResultStatus,
	--  '' AS IsDisplayMonthlyAttendanceText,
	--  Convert(Bit,0) IsDisplayMonthlyAttendance,
	--	'' AS FooterAdjustmentText,
	--	'' AS DetailAdjustmentText,
	--	0 AS FooterAdjustment,
	--	0 AS DetailAdjustment,		 		 		 
	--	Convert(Bit,0) IsPresent,			
	--	'' SmallAddress1,
	--	Convert(Bit,0) IsDisplayParentName,				
	--	Convert(Bit,0) AS IsShowSubjectMark,			
	--	Convert(Bit,0) IsDisplayTeacherSign,
	--	Convert(Bit,0) IsDisplayPrincipalSign,		 			 
	--	Convert(Bit,0) AS IsImageHeader,			 
	--	'' AS DecimalFormat,	 			 
	--	'' AS FatherName,
	--	'' AS MotherName,
	--  0 AS SubjectCount
	

CREATE TABLE #TempExam
(
    Id int IDENTITY(1,1) PRIMARY KEY,
    ExamId int,
    Exam nvarchar(100)
)

INSERT INTO #TempExam
(
	 ExamId,
	 Exam 	
)

SELECT 
@rExamId AS ExamId,
ESGM.Title AS Exam
FROM [sAssessment].[tExamMaster] EM 
INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.ID = EM.ExamSubGroupId 
WHERE EM.ClassId=@rClassId AND EM.BatchId =@rBatchId AND EM.Id = @rExamId

UNION ALL

SELECT 
EM.Id AS ExamId,
ESGM.Code AS Exam
FROM [sAssessment].[tExamMaster] EM 
INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.ID = EM.ExamSubGroupId 
INNER JOIN sAssessment.tExamCombine EC ON EC.SubExamId=EM.Id AND EC.ExamId =@rExamId  AND (EM.ClassId=@rClassId) AND EM.BatchId =@rBatchId

UNION ALL 

SELECT
EM.Id AS ExamId,
ESGM.Title AS Exam
FROM [sAssessment].[tExamMaster] EM 
INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.ID = EM.ExamSubGroupId 
INNER JOIN sAssessment.tExamCombine EC ON EC.SubExamId=EM.Id AND EC.ExamId IN (SELECT SUBEXAMID FROM sAssessment.tExamCombine WHERE ExamId  = @rExamId)  AND (EM.ClassId=@rClassId) AND EM.BatchId =@rBatchId

CREATE TABLE #TempSubjectCount(
ExamId int,
AcademicId BigInt,
SubjectCount int
)
INSERT INTO #TempSubjectCount(ExamId, AcademicId, SubjectCount)
    SELECT R.ExamId, R.AcademicId, COUNT(RD.Id) AS SubjectCount
    FROM sAssessment.tResultDetail RD
	INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
    INNER JOIN #TempExam TE ON TE.ExamId = R.ExamId
    GROUP BY R.ExamId,R.AcademicId

--select * from #TempExam
	
	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			Convert(nvarchar(20),A.Id) AS AcademicIdText,
			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,
			EC.ExamId,
			EC.Exam AS ExamName,
			ED.ExamDate,
			R.TotalMarks AS TotalMark,
			R.TotalObtain,
			R.RankNumber,
			R.Percentage,
			R.ResultGrade,
			R.Percentile,			
			RD.Id AS ResultDetailId,		
			ED.IsDisplayInMarksheet,
			ED.IsShowSubjectGrade,
			ED.IsIncludeInTotal,
			RD.Obtain AS SubjectObtain,
			RD.SubjectGrade,
			ED.Minimum AS SubjectMinimum,
			ED.Maximum AS SubjectMaximum,			
			SM.Code AS SubjectCode,
			SM.Title AS SubjectName,
			(CASE ISNULL(ED.DisplayOrder,0)
			WHEN 0 THEN CS.OrderIndex
			ELSE ED.DisplayOrder END) AS SubjectOrderIndex,
			R.Id AS ResultId,
			CS.Id AS SubjectId,			 	
			EM.IsMarksInDecimal,			
			ISNULL(EM.Remark1,'') AS Remark1,
			ISNULL(EM.Remark2,'') AS Remark2,
			ISNULL(EM.Remark3,'') AS Remark3,
			EM.DisplayTitle,
			EM.IsRankNo, 
			EM.IsGrade,
			EM.IsPercentile,
			EM.IsPercentage,
			EM.IsSubjectPercentile,
			EM.IsProcessResult,			 
			EM.IsNegativeMarks,
			EM.IsIncludeCoScholastic,
			EM.IsOnPrePrinted,
			EM.IsDisplayPhoto,
			EM.IsDisplayBirthDate,
			EM.IsLockForEdit,
			EM.IsDisplaySchoolName,			
			EM.IsDisplayAttendance,
			EM.IsDisplayHeightWeight,
			EM.IsResultStatus,
			Convert(nvarchar(20),ISNULL(EM.IsDisplayMonthlyAttendance,0)) AS IsDisplayMonthlyAttendanceText,
			ISNULL(EM.IsDisplayMonthlyAttendance,0) AS IsDisplayMonthlyAttendance,
			REPLICATE(',',EM.FooterAdjustment) AS FooterAdjustmentText,
			REPLICATE(',',EM.DetailAdjustment) AS DetailAdjustmentText,
			EM.FooterAdjustment,
			EM.DetailAdjustment,		 		 		 
			RD.IsPresent,	
			OM.SmallAddress1,
			EM.IsDisplayParentName,			 
			ISNULL(ED.IsShowSubjectMark,1) AS IsShowSubjectMark,			
			EM.IsDisplayTeacherSign,
			Em.IsDisplayPrincipalSign,		 		 
			ISNULL(EM.IsDisplayImageHeader,0) AS IsImageHeader,			 
			EM.DecimalFormat,						 
			SF.FatherName,
			SF.MotherName,
			TSC.SubjectCount AS SubjectCount
						
	FROM 
			sAssessment.tResultDetail RD
			INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
			INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
			INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId		
			INNER JOIN #TempExam EC ON EC.ExamId = EM.Id 	
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId					 
			INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId	
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId		
			INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId			
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId			
			INNER JOIN sSetup.tOrganizationMaster OM ON StuM.OrgId = OM.Id			
			LEFT JOIN sAssessment.tStudentRemark SR ON R.AcademicId = SR.AcademicId AND  SR.ExamId=EC.ExamId
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = StuM.Id
			INNER JOIN #TempSubjectCount TSC ON TSC.ExamId = EM.Id  AND TSC.AcademicId = A.Id 
			
	WHERE 
			
		((EM.BatchId = @rBatchId) OR  (@rBatchId = 0))
		AND ((A.ClassId=@rClassId) OR (@rClassId=0)) 
		AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((StuM.Code=@rCode) OR (@rCode=''))
		AND ((StuM.StatusId=@rStatusId)OR(@rStatusId=0))
		AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))

	ORDER BY A.RollNo , EC.Id
		
	 DROP TABLE #TempExam
	 DROP TABLE #TempSubjectCount
	 
END
GO
PRINT N'Altering Procedure [sAssessment].[pRptResultSheetStandardMultiMaxExamGet]...';


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

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
 begin
 
  
DECLARE @GradeString nvarchar(1000)
DECLARE @GradeStringRemark nvarchar(500),
@GradeSetId int , @IsIncludeSubExam bit,@GradeStringHtml nvarchar(500)
SELECT @GradeSetId = GradesetId,
	   @IsIncludeSubExam = ISNULL(IsIncludeSubExam,0)  FROM sAssessment.tExamMaster WHERE Id = @rExamId
SELECT @GradeString = [sAssessment].[fGradeStringGet](@GradeSetId)

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

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

--#TempAllExam
	CREATE TABLE #TempAllExam
	(
		AcademicIdText nvarchar(20),
		ExamIdText nvarchar(20),
		CoScholasticScopeIdText nvarchar(20),
		IsDisplayMonthlyAttendanceText nvarchar(20),
		ClassIdText nvarchar(50),
		AcademicId bigint,
		ExamName Nvarchar(150),
		StudCode NVarchar(20),
		StudentName Nvarchar(150),
		RollNo int,
		ResultStatus Nvarchar(20),	
		ClassName NVarchar(50),		
		Division NVarchar(50),
		TotalMark decimal(8,2),
		TotalObtain decimal(8,2),
		Percentage decimal(8,2),
		RankNumber int,
		ResultGrade NVarchar(50),
		
		MaximumMark1 decimal(8,2),		
		SubjectGrade1 NVarchar(50),
		Obtain1 decimal(8,2),
		ExamMaximum1 decimal(8,2),
		ObtainedMaximum1 decimal(8,2),
		IsPresent1 bit,
						
		MaximumMark2 decimal(8,2),	
		SubjectGrade2 NVarchar(50),
		Obtain2 decimal(8,2),
		ExamMaximum2 decimal(8,2),
		ObtainedMaximum2 decimal(8,2),
		IsPresent2 bit,
				
		MaximumMark3 decimal(8,2),
		SubjectGrade3 NVarchar(50),
		Obtain3 decimal(8,2),
		ExamMaximum3 decimal(8,2),
		ObtainedMaximum3 decimal(8,2),
		IsPresent3 bit,		
		
		MaximumMark4 decimal(8,2),	
		SubjectGrade4 NVarchar(50),
		Obtain4 decimal(8,2),
		ExamMaximum4 decimal(8,2),
		ObtainedMaximum4 decimal(8,2),
		IsPresent4 bit,	
				
		MaximumMark5 decimal(8,2),		
		SubjectGrade5 NVarchar(50),
		Obtain5 decimal(8,2),
		ExamMaximum5 decimal(8,2),
		IsPresent5 bit,	
				
		MaximumMark6 decimal(8,2),		
		SubjectGrade6 NVarchar(50),
		Obtain6 decimal(8,2),
		ExamMaximum6 decimal(8,2),
		IsPresent6 bit,	
		
		MaximumMark7 decimal(8,2),		
		SubjectGrade7 NVarchar(50),
		Obtain7 decimal(8,2),
		ExamMaximum7 decimal(8,2),
		IsPresent7 bit,	
		
		MaximumMark8 decimal(8,2),	
		SubjectGrade8 NVarchar(50),
		Obtain8 decimal(8,2),
		ExamMaximum8 decimal(8,2),
		IsPresent8 bit,	
		
		MaximumMark9 decimal(8,2),		
		SubjectGrade9 NVarchar(50),
		Obtain9 decimal(8,2),
		ExamMaximum9 decimal(8,2),
		IsPresent9 bit,	
		
		
		MaximumMark10 decimal(8,2),		
		SubjectGrade10 NVarchar(50),
		Obtain10 decimal(8,2),
		ExamMaximum10 decimal(8,2),
		IsPresent10 bit,	
		
		MaximumMark11 decimal(8,2),		
		SubjectGrade11 NVarchar(50),
		Obtain11 decimal(8,2),
		ExamMaximum11 decimal(8,2),
		IsPresent11 bit,
		
		MaximumMark12 decimal(8,2),		
		SubjectGrade12 NVarchar(50),
		Obtain12 decimal(8,2),
		ExamMaximum12 decimal(8,2),
		IsPresent12 bit,		
		 
		 
		SubjectGradeTerm1 NVarchar(50),
		SubjectGradeTerm2 NVarchar(50),
		SubjectGradeTerm3 NVarchar(50),
		IsMarksInDecimal bit,
		column_visible bit,
		Percentile decimal(5,2),
		ResultDetailId bigint,
		ResultId bigint,	
		Remark1 nvarchar(1000),
		Remark2 nvarchar(300),
		Remark3 nvarchar(300),
		DisplayTitle nvarchar(150),		
		IsRankNo bit, 
		IsGrade bit,
		IsPercentile bit,
		IsPercentage bit,
		IsSubjectPercentile bit,
		IsProcessResult bit,
		IsNegativeMarks bit,
		IsIncludeCoScholastic bit,
		IsOnPrePrinted bit,
		IsDisplayPhoto bit,
		IsDisplayBirthDate bit,
		IsLockForEdit bit,
		IsDisplaySchoolName bit,			
		IsDisplayAttendance bit,
		IsDisplayHeightWeight bit,
		IsResultStatus bit,
		FooterAdjustmentText nvarchar(max),
		DetailAdjustmentText nvarchar(max),
		FooterAdjustment smallint,
		DetailAdjustment smallint,
		ResultRemark nvarchar(200),
		DateOfBirth date,
		HeightTerm1 decimal(5,2),
		WeightTerm1 decimal(5,2),
		HeightTerm2 decimal(5,2),
		WeightTerm2 decimal(5,2),
		HeightAnnual decimal(5,2),
		WeightAnnual decimal(5,2),
		PresentDaysTerm1 smallint,
		PresentDaysTerm2 smallint,
		PresentDaysAnnual smallint,
		TotalDaysTerm1 smallint,
		TotalDaysTerm2 smallint,
		TotalDaysAnnual smallint,
		TotalMarkTerm1 decimal(8,2),
		TotalObtainTerm1 decimal(8,2),
		PercentageTerm1 decimal(8,2),
		RankNumberTerm1 int,
		ResultGradeTerm1 NVarchar(50),
		PercentileTerm1 decimal(8,2),
		ResultStatusTerm1 Nvarchar(20),		   
		TotalMarkTerm2 decimal(8,2),
		TotalObtainTerm2 decimal(8,2),
		PercentageTerm2 decimal(8,2),
		RankNumberTerm2 int,
		ResultGradeTerm2 NVarchar(50),
		PercentileTerm2 decimal(8,2),
		ResultStatusTerm2 Nvarchar(20), 
		TotalMarkTerm3 		decimal(8,2),
		TotalObtainTerm3 decimal(8,2),
		PercentageTerm3 decimal(8,2),
		RankNumberTerm3 int,
		ResultGradeTerm3 NVarchar(50),
		PercentileTerm3 decimal(8,2),
		ResultStatusTerm3 Nvarchar(20), 
		
		TermScopeId tinyint,		 
		StudentPhoto varbinary(max),
		GradeString nvarchar(1000),
		IsDisplayGradeString bit,		 
		IsDisplayInMarksheet bit,
		IsShowSubjectGrade bit,
		IsIncludeInTotal bit,
		ClassSubjectID int,
		SubjectId int,
		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 decimal(6,2),
		PresentDays decimal(6,2),
		StudentHeight decimal(6,2),
		StudentWeight decimal(6,2),
		ExamSeatNo nvarchar(20),
		ExamId int,
		
		ExamCode nvarchar(20),
		Exam1Code nvarchar(20),
		Exam2Code nvarchar(20),
		Exam3Code nvarchar(20),
		Exam4Code nvarchar(20),
		Exam5Code nvarchar(20),
		Exam6Code Nvarchar(20),
		Exam7Code Nvarchar(20),
		Exam8Code nvarchar(20),
		Exam9Code nvarchar(20),
		Exam10Code nvarchar(20),
		Exam11Code nvarchar(20),
		Exam12Code nvarchar(20),
		
		IsDisplayParentName bit,
		FatherName nvarchar(100),
		MotherName nvarchar(100),
		IsShowSubjectMark bit, 
		IsOptionalSubject bit,
		CoScholasticScopeId tinyint,
		IsDisplayPrincipalSign bit,
		IsDisplayTeacherSign bit,
		EmployeeSign varbinary(max),
		Batch nvarchar(100),
		ExamNameTerm1 NVarchar(100),
		ExamNameTerm2 NVarchar(100) ,
		ExamNameTerm3 NVarchar(100),
		ClassTeacherName Nvarchar(100),
		FirstName nvarchar(50),
		LastName nvarchar(50),
		IsDisplayMonthlyAttendance bit,
		MarksheetHeaderA4 varbinary(max),
		IsImageHeader bit,
		MyGoal nvarchar(200),
		AreaOfInterest nvarchar(200),
		Responsibility nvarchar(200),
		MyInterestHobby nvarchar(200),
		MyStrength nvarchar(200),
		Achievements nvarchar(200),
		DentalHygiene nvarchar(200),
		VisionLeft nvarchar(50),
		VisionRight nvarchar(50), 
		IsDetail bit,
		SubjectGroupId int,
		SubjectGroupTitle nvarchar(50),
		SubjectGroupCode nvarchar(50),
		DecimalFormat nvarchar(10),
		SubjectRemark nvarchar(1000),
		GraceMark decimal(5,2),
		GradeStringHtml nvarchar(500),
		ResultRemark3 nvarchar(200),
		IsDisplayTotalMark bit,
		SubjectObtainTerm1 decimal(8,2),	
		SubjectObtainTerm2 decimal(8,2),
		SubjectObtainTerm3  decimal(8,2),
		SubjectMaxTerm1 decimal(8,2),
		SubjectMaxTerm2 decimal(8,2),
		SubjectMaxTerm3 decimal(8,2),
		ContactNo nvarchar(20),
		PresentAddress nvarchar(max),
		TeacherSignCaption nvarchar(100),
		PrincipalSignCaption nvarchar(100),
		ParentSignCaption nvarchar(100),
		ImprovementArea nvarchar(200),
		ProgressArea nvarchar(200),
		GeneralRemark nvarchar(200),
		MyActivity nvarchar(200),
		ClassTeacherRemark nvarchar(1000),
		 
		HouseRemark nvarchar(1000),
		BloodGroup Nvarchar(100),
		TotalDays1 decimal(6,2),
		PresentDays1 decimal(6,2),
		TotalDays2 decimal(6,2),
		PresentDays2 decimal(6,2),
		TotalDays3 decimal(6,2),
		PresentDays3 decimal(6,2),
		TotalDays4 decimal(6,2),
		PresentDays4 decimal(6,2),
		TotalDays5 decimal(6,2),
		PresentDays5 decimal(6,2),
		TotalDays6 decimal(6,2),
		PresentDays6 decimal(6,2),
		TotalDays7 decimal(6,2),
		PresentDays7 decimal(6,2), 
		TotalDays8 decimal(6,2),
		PresentDays8 decimal(6,2),
		TotalDays9 decimal(6,2),
		PresentDays9 decimal(6,2),
		TotalDays10 decimal(6,2),
		PresentDays10 decimal(6,2),
		TotalDays11 decimal(6,2),
		PresentDays11 decimal(6,2),
		TotalDays12 decimal(6,2),
		PresentDays12 decimal(6,2),
		BatchIdText nvarchar(20),
		IsShowWithDetail bit,
		IsPresent bit,
		GradeTitle nvarchar(50),
		SubjectHighestDivisionGrade nvarchar(50),
		SubjectHighestDivisionMark decimal(5, 2),
		HouseId int,
		HouseName nvarchar(100),
		IsDecimal bit
	)	
	 
	INSERT INTO  #TempAllExam 
	(
	AcademicIdText,
	ExamIdText,
	CoScholasticScopeIdText,
	IsDisplayMonthlyAttendanceText,
	ClassIdText,
	AcademicId,
	ExamName,
	StudCode,
	StudentName,
	RollNo,
	ResultStatus,
	ClassName,
	Division,
	TotalMark,
	TotalObtain,
	Percentage,
	RankNumber,
	ResultGrade,
	IsMarksInDecimal,
	column_visible,
	Percentile,
	ResultDetailId,
	ResultId,

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


		EM.IsMarksInDecimal,
		
		
		1,
		R.Percentile,
		RD.Id AS ResultDetailId,
		R.Id AS ResultId,

		ISNULL(EM.Remark1,'') AS Remark1,
		ISNULL(EM.Remark2,'') AS Remark2,
		ISNULL(EM.Remark3,'') AS Remark3,
		EM.DisplayTitle,
		EM.IsRankNo, 
		EM.IsGrade,
		EM.IsPercentile,
		EM.IsPercentage,
		EM.IsSubjectPercentile,
		EM.IsProcessResult,
		EM.IsNegativeMarks,
		EM.IsIncludeCoScholastic,
		EM.IsOnPrePrinted,
		EM.IsDisplayPhoto,
		EM.IsDisplayBirthDate,
		EM.IsLockForEdit,
		EM.IsDisplaySchoolName,			
		EM.IsDisplayAttendance,
		EM.IsDisplayHeightWeight,
		EM.IsResultStatus,
		REPLICATE(',',EM.FooterAdjustment) AS FooterAdjustmentText,
		REPLICATE(',',EM.DetailAdjustment) AS DetailAdjustmentText,
		EM.FooterAdjustment,
		EM.DetailAdjustment,
		ISNULL(R.ResultRemark,'') AS ResultRemark,
		SO.DateOfBirth,
		AD.HeightTerm1,
		AD.WeightTerm1,
		AD.HeightTerm2,
		AD.WeightTerm2,
		AD.HeightAnnual,
		AD.WeightAnnual,
		AD.PresentDaysTerm1,
		AD.PresentDaysTerm2,
		AD.PresentDaysAnnual,
		AD.TotalDaysTerm1,
		AD.TotalDaysTerm2,
		AD.TotalDaysAnnual,
		EM.TermScopeId,
		(CASE EM.IsDisplayPhoto WHEN 1 THEN
			SI.StudentPhoto
		ELSE NULL END)AS StudentPhoto,
		CASE @GradeStringRemark WHEN '' THEN @GradeString ELSE @GradeStringRemark END AS GradeString,
		EM.IsDisplayGradeString,
		ED.IsDisplayInMarksheet,
		ED.IsShowSubjectGrade,
		ED.IsIncludeInTotal,
	    ED.ClassSubjectId,
		CS.SubjectId AS SubjectId,
		(CASE ISNULL(ED.DisplayOrder,0)
		WHEN 0 THEN CS.OrderIndex
		ELSE ED.DisplayOrder END) AS SubjectOrderIndex,
		
		RD.SubjectGrade,
		SM.Title AS SubjectName,
		ISNULL(SM.Code,'') AS SubjectCode,
		ED.Minimum,
		ED.Maximum,
		RD.Obtain,
		SR.ResultRemark1,
		SR.ResultRemark2,
		ISNULL(SR.TotalDays,0)AS TotalDays,
		ISNULL(SR.PresentDays,0)AS PresentDays,
		SR.StudentHeight,
		SR.StudentWeight,
		SR.ExamSeatNo,
		@rExamId,
		ISNULL(ESGM.Code,'') AS ExamCode,
		EM.IsDisplayParentName,
		SF.FatherName,
		SF.MotherName,
		ED.IsShowSubjectMark,
		(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,
		(CASE EM.IsDisplayImageHeader WHEN 1 THEN 
		OI.MarksheetHeaderA4 
		ELSE 
			NULL END) AS MarksheetHeaderA4,
		ISNULL(EM.IsDisplayImageHeader,0) AS IsImageHeader,
		ISNULL(SR.MyGoal,'') AS MyGoal,
		ISNULL(SR.AreaOfInterest,'') AS AreaOfInterest,
		ISNULL(SR.Responsibility,'') AS Responsibility,
		ISNULL(SR.MyInterestHobby,'') AS MyInterestHobby,
		ISNULL(SR.MyStrength,'') AS MyStrength,
		ISNULL(SR.Achievements,'') AS Achievements,
		ISNULL(SR.DentalHygiene,'') AS DentalHygiene,
		ISNULL(SR.VisionLeft,'') AS VisionLeft,
		ISNULL(SR.VisionRight,'') AS VisionRight,
		@rIsDetail AS IsDetail,
		ISNULL(SM.SubjectGroupId,0) AS SubjectGroupId,
		ISNULL(SG.Title,'')AS SubjectGroupTitle,
		ISNULL(SG.Code,'') AS SubjectGroupCode,
		ISNULL(EM.DecimalFormat,0) AS DecimalFormat,
		ISNULL(RD.Remark,'') AS SubjectRemark,
		RD.GraceMark,
		@GradeStringHtml,
		SR.ResultRemark3,
		EM.IsDisplayTotalMark,
		ISNULL(SC.ParentContactNo,'') AS ContactNo,
		ISNULL(SC.PresentStreetOne,'')+' '+ISNULL(SC.PresentStreetTwo,'')+' '+ISNULL(SC.PresentStreetThree,'')+' '+ISNULL(SC.PresentCity,'')+' '+ISNULL(SC.PresentState,'') AS PresentAddress,
		ISNULL(EM.TeacherSignCaption,'') AS TeacherSignCaption,
		ISNULL(EM.PrincipalSignCaption,'') AS PrincipalSignCaption,
		ISNULL(Em.ParentSignCaption,'') As ParentSignCaption,
		ISNULL(SR.ImprovementArea,'') As ImprovementArea,
		ISNULL(SR.ProgressArea,'') AS ProgressArea,
		ISNULL(SR.GeneralRemark,'') As GeneralRemark,
		ISNULL(SR.MyActivity,'') AS MyActivity,
		ISNULL(SR.ClassTeacherRemark,'') As ClassTeacherRemark,
		ISNULL(Sr.HouseRemark,'') As HouseRemark,
		ISNULL(BGM.Title,'') AS BloodGroup,
		Convert(nvarchar(20),@rBatchId),
		@rIsShowWithDetail AS IsShowWithDetail,
		IsPresent,
		GradeTitle ,
		RAD.SubjectHighestDivisionGrade,
		RAD.SubjectHighestDivisionMark ,
		HM.Title As HouseName,HM.Id as HouseId,
		CONVERT(bit,@lDecimalConfig) AS IsDecimal
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 sActivity.tHouseMaster HM ON SO.HouseId = HM.Id
	LEFT JOIN sStudent.tAcademicDetail AD ON AD.AcademicId=A.Id
	LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=StuM.Id
	LEFT JOIN sAssessment.tStudentRemark SR ON R.AcademicId = SR.AcademicId AND R.ExamId = SR.ExamId
	LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = StuM.Id
	LEFT JOIN sAssessment.tOptionalSubject OS ON OS.AcademicId = R.AcademicId AND OS.ClassSubjectId = ED.ClassSubjectId  AND ED.ExamId = R.ExamId
	LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=A.StudentId
	LEFT JOIN 	sCommon.tBloodGroupMaster BGM ON BGM.Id=So.BloodGroupId
	LEFT JOIN sAssessment.tGradeSetDetail GS ON GS.GradeSetId=ED.GradeSetId AND ED.GradeSetId = @GradeSetId and RD.SubjectGrade = GS.GradeCode
	LEFT JOIN sAssessment.tResultAnalysisDivisionDetail RAD ON RAD.ClassSubjectId = CS.Id AND RAD.DivisionId = A.DivisionId AND RAD.ExamId = Em.Id
			  
	
	WHERE
		R.ExamId = @rExamId 
		AND ((A.DivisionId =  @rDivisionId) OR (@rDivisionId=0))
		AND ((A.ClassId =  @rClassId) OR (@rClassId=0))		 
		AND ((A.BatchId =  @rBatchId) OR (@rBatchId=0))
		AND ((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))
		 AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))
	 AND  ISNULL(EMP.IsOtherUser,0) = 0
	 AND (ISNULL(StuM.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rMultiCode,',')) OR @rMultiCode='')
	Order By ED.DisplayOrder
 
	create TABLE #tempcombineExam
	(	Id int IDENTITY,
		ExamID int )

	IF (@IsIncludeSubExam = 0)
	BEGIN	
	INSERT INTO #tempcombineExam (ExamID) 
	SELECT SUBEXAMID FROM sAssessment.tExamCombine WHERE ExamId  = @rExamId Order By ExamOrder ASC
 	END
 	ELSE
 	BEGIN
 	INSERT INTO #tempcombineExam (ExamID) 
	SELECT C.SUBEXAMID FROM sAssessment.tExamCombine C
	INNER JOIN (SELECT SUBEXAMID,ExamOrder FROM sAssessment.tExamCombine WHERE ExamId  = @rExamId) E
	ON C.ExamId = E.SubExamId
	ORDER BY E.ExamOrder,C.ExamOrder
	END
	
	DECLARE @lCount int,@query  AS NVARCHAR(MAX),@lSubExamId int,@lCount1 int
  
	Select @lCount = MAX(Id) from #tempcombineExam
	DECLARE @ExamTitle nvarchar(150)
	while (@lCount > 0)
	begin
		
		select @lSubExamId = ExamID from #tempcombineExam Where Id = @lCount
		if(@lCount <= 4)
		BEGIN
			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,
					
						 ObtainedMaximum' + convert(nvarchar(15),@lCount)+ '= CASE WHEN EM.IsDisplayHighestDivisionMark = 1
									THEN [sAssessment].[fGetHighestDivisionMark](A.DivisionId ,RD.ExamDetailId)
									ELSE 0  END,
						 				
						 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 sStudent.tAcademic A ON A.Id=R.AcademicId
							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)
			
		END
		
		ELSE
		
		BEGIN
			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 sStudent.tAcademic A ON A.Id=R.AcademicId
							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)
			
		END
						
			set @query ='update T set 
				    TotalMarks' + convert(nvarchar(15),@lCount)+ '=R.TotalMarks,
					TotalObtain' + convert(nvarchar(15),@lCount)+ '=R.TotalObtain,
					Percentage' + convert(nvarchar(15),@lCount)+ '=R.Percentage,
					RankNumber' + convert(nvarchar(15),@lCount)+'=R.RankNumber,
					ResultGrade' + convert(nvarchar(15),@lCount)+'=R.ResultGrade,
					Percentile' + convert(nvarchar(15),@lCount)+'=R.Percentile,
					ResultStatus' + convert(nvarchar(15),@lCount)+'=R.ResultStatus,
					Exam' + convert(nvarchar(15),@lCount)+ 'Name=ESGM.Title,
					Exam' + convert(nvarchar(15),@lCount)+ 'Code=ESGM.Code,
					ExamMaximum' + convert(nvarchar(15),@lCount)+'=ISNULL(EM.ExamMaximum,0)
					 From						
						sAssessment.tResult R						
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON  T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
						
		execute(@query)
		
		
	set @lCount = @lCount -1
	end
	

	IF (@IsIncludeSubExam = 1)
	BEGIN	
		select @lSubExamId = SubExamId from sAssessment.tExamCombine  Where ExamId  = @rExamId AND ExamOrder = 1
		
			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
		set @query ='update T set					 
					SubjectGradeTerm2=RD.SubjectGrade,
					SubjectObtainTerm2 = RD.Obtain,
					SubjectMaxTerm2= ED.Maximum				 
					 From
						sAssessment.tResultDetail RD
						INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
		execute(@query)
		
		
				set @query ='update T set
 
					TotalMarkTerm2 = R.TotalMarks,
					TotalObtainTerm2=R.TotalObtain,
					PercentageTerm2=R.Percentage,
					RankNumberTerm2=R.RankNumber,
					ResultGradeTerm2=R.ResultGrade,
					PercentileTerm2 = R.Percentile,
					ResultStatusTerm2 = R.ResultStatus,
					ExamNameTerm2 = ESGM.Code			
					 From						 
					   sAssessment.tResult R  				 
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON  T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
		execute(@query)
		
		select @lSubExamId = SubExamId from sAssessment.tExamCombine  Where ExamId  = @rExamId AND ExamOrder = 3
		set @query ='update T set					 
					SubjectGradeTerm3=RD.SubjectGrade,
					SubjectObtainTerm3 = RD.Obtain,
					SubjectMaxTerm3= ED.Maximum				 
					 From
						sAssessment.tResultDetail RD
						INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
		execute(@query)
		set @query ='update T set
 
					TotalMarkTerm3 = R.TotalMarks,
					TotalObtainTerm3=R.TotalObtain,
					PercentageTerm3=R.Percentage,
					RankNumberTerm3=R.RankNumber,
					ResultGradeTerm3=R.ResultGrade,
					PercentileTerm3 = R.Percentile,
					ResultStatusTerm3 = R.ResultStatus,
					ExamNameTerm3 = ESGM.Code			
					 From						 
					   sAssessment.tResult R  				 
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON  T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
		execute(@query)
	END
	
	-- For Getting Highest Mark in Class in 2nd and 3rd Exam in One Field
	
	CREATE TABLE #HighestMarkTerm2Term3
	(
		SubjectId int,
		Term2Term3ClassHighestMarkSum decimal(8,2)
	)
	INSERT INTO #HighestMarkTerm2Term3 
	(
		SubjectId,
		Term2Term3ClassHighestMarkSum
	)
	SELECT 
		CS.SubjectId,		 
		MAX(RD.Obtain) AS Term2Term3ClassHighestMarkSum
	FROM
	sAssessment.tResultDetail RD INNER JOIN sAssessment.tResult R ON RD.ResultId = R.Id
	 INNER JOIN sAssessment.tExamDetail ED ON RD.ExamDetailId = ED.Id
	INNER JOIN sAssessment.tExamMaster EM ON ED.ExamId = EM.Id
	INNER JOIN  sSetup.tClassSubject CS  ON ED.ClassSubjectId = CS.Id
	INNER JOIN sStudent.tAcademic A ON R.AcademicId = A.Id
	WHERE
	A.BatchId = @rBatchId
	AND EM.BatchId =  @rBatchId
	AND	((A.ClassId = @rClassId) OR (@rClassId = 0)) 
		AND ((A.DivisionId = @rDivisionId) OR (@rDivisionId = 0)) 
		--AND ((CS.Id = @rSubjectId) OR (@rSubjectId = 0))
		AND ((EM.Id = @rExamId) OR (@rExamId = 0))
		AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))
		group by CS.SubjectId,A.DivisionId 
		
	
	
	
	
	SELECT 
		  @rBuilder1,@rBuilder2, T.*,H.Term2Term3ClassHighestMarkSum
	FROM 
	      #TempAllExam T
		  INNER JOIN #HighestMarkTerm2Term3 H ON H.SubjectId = T.SubjectId
	
	
	Drop table #tempcombineExam
	
	Drop table #TempAllExam
	
	Drop table #HighestMarkTerm2Term3
	
	END
	
	
	--SELECT @rBuilder1,@rBuilder2,T.* FROM sAssessment.tTempAllExam T
 -- end
GO
PRINT N'Altering Procedure [sAssessment].[pRptResultWithAllSubjectListGet]...';


GO


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

BEGIN 

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


	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			ESGM.Title AS Exam,
			StuM.Code,
		    [sStudent].[fStudentNameGet](StuM.FirstName , StuM.MiddleName, StuM.LastName,OM.StudentNameFormatId ) AS Name,
			A.RollNo,
			R.AcademicId,
			RD.Obtain,
			R.ResultStatus,
			CM.DisplayTitle AS Class,
			Cm.Id AS ClassId,
			DM.DisplayTitle AS Division,
			DM.Id AS DivisionId,
			DM.OrderIndex AS DivisinOrderIndex,
			R.TotalMarks,
			R.TotalObtain,
			R.Percentage,
			R.RankNumber,
			R.ResultGrade,
			SM.Title AS ClassSubject,
			RD.Id AS ResultDetailId,
			R.Id AS ResultId,
			CS.Id AS SubjectId,
			ED.Maximum,
			RD.SubjectGrade, 
			EM.IsMarksInDecimal,
			SM.Code AS SubjectCode,
			ED.DisplayOrder AS SubjectOrderIndex,
			CM.OrderIndex AS ClassOrderIndex,
			RD.IsPresent,
			EM.IsGrade,
			EM.IsPercentage,
			EM.IsResultStatus,
			EM.IsRankNo ,
			ED.Minimum,
			RD.GraceMark,
			EM.DecimalFormat,
			CS.IsOptional,
			(EmpM.FirstName + ' ' +EmpM.LastName ) AS InchargeEmployeeName,
			CONVERT(bit,@lAbsentRemarkConfig) AS IsAbsentRemark,
			ISNULL(RD.AbsentRemark,'') AS AbsentRemark
      
	FROM 
	
	sStudent.tAcademic A 
	INNER JOIN sAssessment.tResult R ON A.Id=R.AcademicId    
	INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
	INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
	INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
	INNER JOIN sSetup.tOrganizationMaster OM ON StuM.OrgId = OM.Id
	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId AND	((EM.Id=@rExamId )	OR (@rExamId = 0))AND EM.BatchId = @rBatchId	
	INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId AND ((ESGM.Id = @rExamSubGroupId) OR (@rExamSubGroupId = 0))
	INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId = EM.Id
	INNER JOIN sSetup.tClassSubject CS ON Cs.Id = Ed.ClassSubjectId
	INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId	
	LEFT JOIN sAssessment.tResultDetail RD ON ED.Id=RD.ExamDetailId 
		AND ((SM.Id=@rSubjectId) OR (RD.ExamDetailId=@rSubjectId) OR (@rSubjectId=0)) 
		AND R.Id = RD.ResultId
	LEFT JOIN sHrm.tEmployeeMaster EmpM ON EmpM.Id = DM.InchargeEmployeeId AND EmpM.StatusId = 7
	INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
	LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=StuM.Id AND AR.SourceTypeId=2003 AND BM.OrgGroupBatchId = AR.OrgGroupBatchId
	LEFT JOIN
	(SELECT AT.SourceId,B.OrgGroupBatchId FROM sTransport.tAssignRoute AT 
    INNER JOIN sTransport.tBusRouteDestinationMaster BRD ON BRD.Id=AT.PickupDestinationId 
    INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BRD.BusRouteId AND  AT.SourceTypeId=2003 ) RT
    ON RT.SourceId = StuM.Id AND RT.OrgGroupBatchId = BM.OrgGroupBatchId
	
			
	WHERE 
	     
	   --(CS.ClassId=@rClassId OR @rClassId=0) 
		 EM.BatchId = @rBatchId 
		AND (A.ClassId=@rClassId OR @rClassId=0) 
		--AND((SM.Id=@rSubjectId) OR (RD.ExamDetailId=@rSubjectId) OR (@rSubjectId=0))
		AND (A.DivisionId=@rDivisionId OR @rDivisionId=0)
		AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((R.RankNumber >= @rFromRank) OR (@rFromRank=0))
		AND ((R.RankNumber <= @rToRank) OR (@rToRank=0))
		AND ((R.ResultGrade = @rGrade) OR (@rGrade=''))
		AND ((ESGM.Id = @rExamSubGroupId) OR (@rExamSubGroupId = 0))		
		AND ((EM.Id=@rExamId )	OR (@rExamId = 0))		
		AND ((StuM.Code=@rCode) OR (@rCode=''))
		AND ((StuM.StatusId=@rStatusId)OR(@rStatusId=0))	
		AND ((R.Percentage>=@rFromPercentage) OR (@rFromPercentage=0))
		AND ((R.Percentage<=@rToPercentage) OR(@rToPercentage=0))	
		AND ((R.ResultStatus=@rResultStatus) OR (@rResultStatus=''))
		AND ((CM.DepartmentId = @rDepartmentId) OR (@rDepartmentId=0))
	    AND	A.BatchId = @rBatchId 
		AND (A.ClassStatusId=@rClassStatusId OR @rClassStatusId=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 A.RollNo,CS.OrderIndex 

		
END
GO
PRINT N'Altering Procedure [sAssessment].[pRptSubjectActivityExamDetailGet]...';


GO
ALTER PROCEDURE [sAssessment].[pRptSubjectActivityExamDetailGet]
	 
		@rOrgId int=0,
		@rExamId int=0,
		@rClass int=0,
		@rDivisionId int=0,
		@rBatchId int=0,
		@rBuilder1 nvarchar(max)='',
		@rAcademicId bigint=0,
		@rCode nvarchar(20)='',
		@rFromRollNo int=0,
		@rToRollNo int=0,
		@rMultiCode nvarchar(max)=''
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON 
BEGIN 	 

Declare @GradeSetId int,@GradeString nvarchar(1000),@GradeStringRemark nvarchar(1000)
SELECT @GradeSetId = GradesetId FROM sAssessment.tExamMaster WHERE Id = @rExamId
SELECT @GradeString = [sAssessment].[fGradeStringGet](@GradeSetId)
Select @GradeStringRemark = GradeStringText from sAssessment.tGradeSetMaster Where Id =@GradeSetId

Declare @DecimalConfid nvarchar(20)=''
SELECT @DecimalConfid =ItemValue From sConfig.tConfigurationSetup WHERE ConfigurationId = 496 AND SourceTypeId = 1016 AND SourceId = @rOrgId

	SELECT 			 
			Convert(nvarchar(20),SA.Id) AS AcademicIdText,	
			CONVERT (nvarchar(20),@rExamId) AS ExamIdText, 
			@rBuilder1 AS Builder1,
			SA.Id AS AcademicId,
			SA.RollNo,
			StuM.Number,
			AIS.Grade,
			SAM.Title AS SubjectActivityTitle,
			SSA.Title AS SubjectSubActivityTitle,
			SAM.Id AS ActivityId,
			SSA.Id AS SubjectSubActivityId,
			SAM.OrderIndex AS ActivityOrderIndex,
			SSA.OrderIndex AS SubjectSubActivityOrderIndex ,
			ISNULL(EM.Remark1,'') AS Remark1,
			ISNULL(EM.Remark2,'') AS Remark2,
			ISNULL(EM.Remark3,'') AS Remark3,
			EM.DisplayTitle,
			EM.IsRankNo, 
			EM.IsGrade, 
			EM.IsPercentile,
			EM.IsPercentage,
			EM.IsSubjectPercentile,
			EM.IsProcessResult,
			EM.IsNegativeMarks,
			EM.IsIncludeCoScholastic,
			EM.IsOnPrePrinted,
			EM.IsDisplayPhoto,
			EM.IsDisplayBirthDate,
			EM.IsLockForEdit,
			EM.IsDisplaySchoolName,			
			EM.IsDisplayAttendance,
			EM.IsDisplayHeightWeight,
			EM.IsResultStatus,
			REPLICATE(',',EM.FooterAdjustment) AS FooterAdjustmentText,
			REPLICATE(',',EM.DetailAdjustment) AS DetailAdjustmentText,
			EM.FooterAdjustment,
			EM.DetailAdjustment,
			EM.IsDisplayGradeString,
			EM.IsDisplayParentName,
			[sStudent].[fStudentNameGet](StuM.FirstName , ISNULL(StuM.MiddleName,'') , StuM.LastName,OM.StudentNameFormatId ) AS Name,
			SO.DateOfBirth,
			CMM.Title AS ClassName,
			StuM.code,
			SF.FatherName,
			SF.MotherName,
			SAM.ClassSubjectId ,
			SM.Title AS SubjectName,
			SM.OrderIndex AS SubjectOrderIndex,
			CMM.DisplayTitle AS Class,
			DM.DisplayTitle AS Division,
			CASE WHEN EM.IsDisplayPhoto = 1 THEN SI.StudentPhoto ELSE NULL END AS StudentPhoto, 
			ISNULL(AIS.DescriptiveIndicator,'') AS DescriptiveIndicator,
			CASE WHEN CS.OrderIndex % 2 = 0 THEN 2 
			ELSE 1 END AS ColumnSubjectCount,
			CS.OrderIndex,
			EM.SubjectGroupPerPage,
			AIS.GradeIndicator,
			EM.IsCoScholasticGradeIndicator,
			CASE WHEN EM.IsDisplayTeacherSign = 1 THEN EI.EmployeeSign ELSE NULL END AS EmployeeSign,
			Em.IsDisplayPrincipalSign,
			EM.IsDisplayTeacherSign,
			EM.IsCoScholasticGradeDesIndicator,
			EM.IsCoScholasticGrade,
			Em.IsDisplayParentName,
			(CASE EM.IsDisplayImageHeader WHEN 1 THEN 
			OI.MarksheetHeaderA4 
			ELSE 
			NULL END) AS MarksheetHeaderA4,
			ISNULL(EM.IsDisplayImageHeader,0) AS IsImageHeader,
			RD.Remark,
			
			HM.Title AS House,
			BM.Title AS BAtch ,
			[sAttendance].[fSubjectTeacherGet](SA.DivisionId,SM.ID) AS TEacherName,
			ED.IsShowSubjectGrade,
			CASE @GradeStringRemark WHEN '' THEN @GradeString  ELSE @GradeStringRemark END AS GradeString,
			--@GradeString AS GradeString,
			Convert(nvarchar(20),ISNULL(Em.IsDisplayMonthlyAttendance,0)) As IsDisplayMonthlyAttendanceText,
			TeacherSignCaption,
			EM.PrincipalSignCaption,
			ParentSignCaption,
			--CASE WHEN EM.IsDisplayTeacherSign = 1 THEN EM.TeacherSignCaption ELSE NULL END AS TeacherSignCaption,
			--CASE WHEN EM.IsDisplayPrincipalSign = 1 THEN EM.PrincipalSignCaption ELSE NULL END AS PrincipalSignCaption,
			SR.ResultRemark1,
			SR.ResultRemark2,	
			SR.ResultRemark3,
			SR.ClassTeacherRemark,
			SR.HouseRemark,
			ISNULL(SR.PresentDays,0)AS PresentDays,			
			ISNULL(SR.TotalDays,0)AS TotalDays,
			SR.StudentHeight,
			SR.StudentWeight,
			
			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(SR.ImprovementArea,'') As ImprovementArea,
			ISNULL(SR.ProgressArea,'') AS ProgressArea,
			ISNULL(SR.GeneralRemark,'') As GeneralRemark,
			ISNULL(SR.MyActivity,'') AS MyActivity,
			ISNULL(SF.FatherContactNo,'') AS FatherContactNo,
			ISNULL(SF.MotherContactNo,'') AS MotherContactNo,
			ISNULL(SF.FatherMail,'') AS FatherMail,
			ISNULL(SF.MotherMail,'') AS MotherMail,
			ISNULL(SC.PresentStreetONe,'')+' '+ISNULL(SC.PresentStreetTwo,'')+' '+ISNULL(SC.PresentStreetThree,'')+' '+ISNULL(SC.PresentCity,'')+' '+ISNULL(SC.PresentState,'') AS PresentAddress,
			DivisionId,
			SM.ID,
			( EmpM.FirstName + ' ' +EmpM.LastName ) AS InchargeEmployeeName,
			ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
			CONVERT(bit,@DecimalConfid) AS IsDecimal,
			AIS.Marks,
			SR.ExamSeatNo AS ExamSeatNo					--add for 27710 mantis

	 FROM 
			sAssessment.tCCESubjectSubActivityExamScore AIS 
			INNER JOIN sAssessment.tCCESubjectSubActivityMaster SSA ON AIS.SubjectSubActivityId = SSA.Id 
			INNER JOIN	sAssessment.tCCESubjectActivityMaster SAM  ON SAM.Id = SSA.SubjectActivityId			
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=SAM.ClassSubjectId		
			INNER JOIN sStudent.tAcademic SA ON SA.Id = AIS.AcademicId 
			INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=SA.StudentId
			INNER JOIN sAssessment.tExamMaster EM ON EM.Id=AIS.ExamId
			INNER JOIN sAssessment.tExamDetail ED ON EM.Id=ED.ExamId AND ED.ClassSubjectId = CS.Id 		 			 
			INNER JOIN sAssessment.tResult AR ON AR.ExamId = AIS.ExamId AND AIS.AcademicId = AR.AcademicId
			INNER JOIN sAssessment.tResultDetail ARD ON ARD.ResultId = AR.Id AND ARD.ExamDetailId = ED.Id
			LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=SA.StudentId
			LEFT JOIN sActivity.tHouseMaster HM ON HM.Id=SO.HouseId
			LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=SA.StudentId	
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=SA.divisionId	
			INNER JOIN sSetup.tClassMaster CMM ON CMM.Id=DM.ClassId 
			LEFT JOIN sHrm.tEmployeeMaster EmpM 
				ON EmpM.Id = DM.InchargeEmployeeId AND EmpM.IsObsolete = 0
			LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = Dm.InchargeEmployeeId
			--LEFT JOIN sAcademic.tTeacherSubjectDivision TSD ON TSD.DivisionId = DM.Id AND TSD.SubjectId = SM.Id 
			--LEFT JOIN sHrm.tEmployeeMaster EMP ON EMP.Id = TSD.EmployeeId
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SA.StudentId
			LEFT JOIN sAssessment.tStudentRemark SR ON SA.Id = SR.AcademicId	AND EM.Id = SR.ExamId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = Stum.OrgId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id= SA.BatchID
			LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = Om.Id
			LEFT JOIN sAssessment.tResultDetailOther RD ON RD.AcademicId = SA.Id AND EM.ID=RD.ExamId AND CS.Id=RD.ClassSubjectID 
			LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId =StuM.ID
	    --LEFT JOIN @lAcademicId A ON A.AcademicId = SA.AcademicId AND A.ClassSubjectId = ED.ClassSubjectId
			----------------------------------------------------------------------------
			--sAssessment.tCCESubjectActivityMaster SAM 	
			--INNER JOIN sAssessment.tCCESubjectSubActivityMaster SSA ON SAM.Id=SSA.SubjectActivityId 
			--INNER JOIN sAssessment.vCCEExamClassSubject CS ON CS.ClassSubjectId=SAM.ClassSubjectId
			--INNER JOIN sSetup.tClassMaster CMM ON CMM.Id=CS.ClassId 
			--INNER JOIN sStudent.vStudentAcademic SA ON SA.ClassId = CS.ClassId 
			--INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=SA.StudentId			 
			--LEFT JOIN sAssessment.tCCESubjectSubActivityExamScore AIS ON AIS.AcademicId =SA.AcademicId AND AIS.SubjectSubActivityId= SSA.Id 	
			--LEFT JOIN sAssessment.tExamMaster EM ON EM.Id=AIS.ExamId
			--LEFT JOIN sAssessment.tExamDetail ED ON EM.Id=ED.ExamId	AND ED.ClassSubjectId = CS.ClassSubjectId 		 
			--LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=SA.StudentId
			--LEFT JOIN sActivity.tHouseMaster HM ON HM.Id=SO.HouseId
			--LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=SA.StudentId	
			--INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId	
			--INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=SA.divisionId
			--LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = Dm.InchargeEmployeeId
			--LEFT JOIN sAcademic.tTeacherSubjectDivision TSD ON TSD.DivisionId = DM.Id AND TSD.SubjectId = SM.Id 
			--LEFT JOIN sHrm.tEmployeeMaster EMP ON EMP.Id = TSD.EmployeeId
			--LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SA.StudentId
			--LEFT JOIN sAssessment.tStudentRemark SR ON SA.AcademicId = SR.AcademicId	AND EM.Id = SR.ExamId
			--INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = Stum.OrgId
			--INNER JOIN sSetup.tBatchMaster BM ON BM.Id= SA.BatchID
			--LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = Om.Id
			--LEFT JOIN sAssessment.tResultDetailOther RD ON RD.AcademicId = SA.AcademicId AND EM.ID=RD.ExamId AND CS.ClassSubjectId=RD.ClassSubjectID 
		WHERE
			((SA.Id=@rAcademicId) OR(@rAcademicId=0))
			AND ((CS.ClassId=@rClass) OR (@rClass=0))
			And ((SA.DivisionId =@rDivisionId) or(@rDivisionId=0))	
			And ((SA.BatchId =@rBatchId) OR (@rBatchId=0))
			and ((SA.OrgId=@rOrgId) OR (@rOrgId=0))
			And AIS.ExamId=@rExamId
			AND ((STum.Code = @rCode) OR(@rCode=''))
			AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
			AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
			AND StuM.StatusId = 1
			AND (ISNULL(STum.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rMultiCode,',')) OR @rMultiCode='')
			AND SAM.IsObsolete = 0
		ORDER BY 
			SA.RollNo ASC,
			SAM.OrderIndex ASC,
			SSA.OrderIndex ASC;
END
GO
PRINT N'Altering Procedure [sAttendance].[pSubjectwiseAttendanceGet]...';


GO
 

ALTER PROCEDURE [sAttendance].[pSubjectwiseAttendanceGet]
	 	 
	 	 @rClassId int,
	 	 @rDivisionId int,
		 @rAttendanceDate date,
		 @rSubjectId int,
	 	 @rBatchId int,
	 	 @rOrgId int,
	 	 @rAttendanceGroupId int = 0,
	 	 @rPeriodNo int

	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 

    DECLARE @lIsOptional bit=0
	SELECT @lIsOptional = ISNULL(IsOptional,0) FROM sSetup.vClassSubject  WHERE SubjectId=@rSubjectId and classid = @rClassId
	IF (@lIsOptional=0)
	BEGIN
		IF(@rAttendanceGroupId=0)
		BEGIN
			SELECT 
				SA.AcademicId,
				ISNULL(SA.RollNo,0) as RollNo,
				SA.Name,
				SA.Code,
				ISNULL(SR.IsPresent,'true') as IsPresent,
				ISNULL(SR.AbsentReasonId,0) as AbsentReasonId,
				case when SR.CreatedUserId IS NULL then 'false' else 'true' end as IsDeleted,
				SR.RepeatCount,
				EM.EmployeeId,
				EM.Code AS EmployeeCode,
				EM.EmployeeName,
				ISNULL(SR.AttendanceTagId,0) AS AttendanceTagId,
				ISNULL(SR.PeriodNo,0) AS PeriodNo,
				SA.ClassName+' - '+SA.DivisionName AS Class,
				ISNULL(SI.StudentPhoto, CONVERT(VARBINARY(MAX), 0)) AS StudentPhoto,
				SA.StudentId
			FROM 
				sStudent.vStudentAcademic SA 
				 LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=SA.StudentId
				INNER JOIN sStudent.tStudentAdmission AD ON SA.StudentId = AD.StudentId
				LEFT JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.AcademicId 
					AND (SR.AttendanceTypeId=5)
					AND (SR.AttendanceDate=@rAttendanceDate)
					AND ((ISNULL(SR.SubjectId,0)=@rSubjectId) OR (@rSubjectId=0))
					AND ((ISNULL(SR.PeriodNo,0)=@rPeriodNo) OR (@rPeriodNo=0))
					AND  ISNULL(SR.AttendanceGroupId,0) = @rAttendanceGroupId
				LEFT JOIN sHrm.vExtEmployeeMaster EM ON EM.EmployeeId=SA.InchargeEmployeeId
			WHERE 
				((SA.ClassId=@rClassId) OR (@rClassId=0))
				AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
				AND (SA.OrgId = @rOrgId)
				AND (SA.BatchId = @rBatchID)
				AND (AD.LeftDate > @rAttendanceDate OR ISNULL(AD.LeftDate,'')= '')
				AND (AD.AdmissionDate <= @rAttendanceDate)
				AND (SA.StatusId NOT IN(2,3))
				ORDER BY SA.ClassOrderIndex,SA.DivisionOrder,RollNo
		END
		ELSE
		BEGIN
			SELECT 
				SA.AcademicId,
				ISNULL(SA.RollNo,0) as RollNo,
				SA.Name,
				SA.Code,
				ISNULL(SR.IsPresent,'true') as IsPresent,
				ISNULL(SR.AbsentReasonId,0) as AbsentReasonId,
				case when SR.CreatedUserId IS NULL then 'false' else 'true' end as IsDeleted,
				SR.RepeatCount,
				EM.EmployeeId,
				EM.Code AS EmployeeCode,
				EM.EmployeeName,
				ISNULL(SR.AttendanceTagId,0) AS AttendanceTagId,
				ISNULL(SR.PeriodNo,0) AS PeriodNo,
				SA.ClassName+' - '+SA.DivisionName AS Class,
				ISNULL(SI.StudentPhoto, CONVERT(VARBINARY(MAX), 0)) AS StudentPhoto,
				SA.StudentId
			FROM 
			sStudent.vStudentAcademic SA 
			 LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=SA.StudentId
			INNER JOIN sAttendance.tAttendanceGroupStudent AGS ON AGS.AcademicId = SA.AcademicId 
				AND AGS.AttendanceGroupId=@rAttendanceGroupId
			INNER JOIN sStudent.tStudentAdmission AD ON SA.StudentId = AD.StudentId
			LEFT JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.AcademicId 
				AND (SR.AttendanceTypeId=5)
				AND (SR.AttendanceDate=@rAttendanceDate)
				AND ((ISNULL(SR.SubjectId,0)=@rSubjectId) OR (@rSubjectId=0))
				AND ((ISNULL(SR.PeriodNo,0)=@rPeriodNo) OR (@rPeriodNo=0))
				AND SR.AttendanceGroupId=@rAttendanceGroupId
			LEFT JOIN sHrm.vExtEmployeeMaster EM ON EM.EmployeeId=SA.InchargeEmployeeId
			WHERE 
			(SA.OrgId = @rOrgId)
			AND (SA.BatchId = @rBatchID)
			AND (AD.LeftDate > @rAttendanceDate OR ISNULL(AD.LeftDate,'')= '')
			AND (AD.AdmissionDate <= @rAttendanceDate)
			AND (SA.StatusId NOT IN(2,3))
			ORDER BY SA.ClassOrderIndex,SA.DivisionOrder,RollNo
		END	
	END 
	ELSE 
	BEGIN
		IF(@rAttendanceGroupId=0)
		BEGIN
			SELECT 
				SA.AcademicId,
				ISNULL(SA.RollNo,0) as RollNo,
				SA.Name,
				SA.Code,
				ISNULL(SR.IsPresent,'true') as IsPresent,
				ISNULL(SR.AbsentReasonId,0) as AbsentReasonId,
				case when SR.CreatedUserId IS NULL then 'false' else 'true' end as IsDeleted,
				SR.RepeatCount,
				EM.EmployeeId,
				EM.Code AS EmployeeCode,
				EM.EmployeeName,
				ISNULL(SR.AttendanceTagId,0) AS AttendanceTagId,
				ISNULL(SR.PeriodNo,0) AS PeriodNo,
				SA.ClassName+' - '+SA.DivisionName AS Class,
				ISNULL(SI.StudentPhoto, CONVERT(VARBINARY(MAX), 0)) AS StudentPhoto,
				SA.StudentId
			FROM 
				sStudent.vStudentAcademic SA 
				 LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=SA.StudentId
				INNER JOIN sStudent.tStudentAdmission AD ON SA.StudentId = AD.StudentId
				INNER JOIN sAssessment.tOptionalSubject OS ON OS.AcademicId= SA.AcademicId
				INNER JOIN sSetup.tClassSubject CS ON CS.Id = OS.ClassSubjectId 
				INNER JOIN sSetup.tSubjectMaster SM ON SM.Id= CS.SubjectId AND (SubjectId=@rSubjectId OR @rSubjectId=0)
				LEFT JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.AcademicId 
					AND (SR.AttendanceTypeId=5)
					AND (SR.AttendanceDate=@rAttendanceDate)
					AND ((ISNULL(SR.SubjectId,0)=@rSubjectId) OR (@rSubjectId=0))
					AND ((ISNULL(SR.PeriodNo,0)=@rPeriodNo) OR (@rPeriodNo=0))
					AND  ISNULL(SR.AttendanceGroupId,0) = @rAttendanceGroupId
				LEFT JOIN sHrm.vExtEmployeeMaster EM ON EM.EmployeeId=SA.InchargeEmployeeId
			WHERE 
				((SA.ClassId=@rClassId) OR (@rClassId=0))
				AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
				AND (SA.OrgId = @rOrgId)
				AND (SA.BatchId = @rBatchID)
				AND (AD.LeftDate > @rAttendanceDate OR ISNULL(AD.LeftDate,'')= '')
				AND (AD.AdmissionDate <= @rAttendanceDate)
				AND (SA.StatusId NOT IN(2,3))
				ORDER BY SA.ClassOrderIndex,SA.DivisionOrder,RollNo
		END
		ELSE
		BEGIN
			SELECT 
				SA.AcademicId,
				ISNULL(SA.RollNo,0) as RollNo,
				SA.Name,
				SA.Code,
				ISNULL(SR.IsPresent,'true') as IsPresent,
				ISNULL(SR.AbsentReasonId,0) as AbsentReasonId,
				case when SR.CreatedUserId IS NULL then 'false' else 'true' end as IsDeleted,
				SR.RepeatCount,
				EM.EmployeeId,
				EM.Code AS EmployeeCode,
				EM.EmployeeName,
				ISNULL(SR.AttendanceTagId,0) AS AttendanceTagId,
				ISNULL(SR.PeriodNo,0) AS PeriodNo,
				SA.ClassName+' - '+SA.DivisionName AS Class,
				ISNULL(SI.StudentPhoto, CONVERT(VARBINARY(MAX), 0)) AS StudentPhoto,
				SA.StudentId
			FROM 
			sStudent.vStudentAcademic SA 
			 LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=SA.StudentId
			INNER JOIN sAttendance.tAttendanceGroupStudent AGS ON AGS.AcademicId = SA.AcademicId 
				AND AGS.AttendanceGroupId=@rAttendanceGroupId
			INNER JOIN sStudent.tStudentAdmission AD ON SA.StudentId = AD.StudentId
			INNER JOIN sAssessment.tOptionalSubject OS ON OS.AcademicId= SA.AcademicId
				INNER JOIN sSetup.tClassSubject CS ON CS.Id = OS.ClassSubjectId 
				INNER JOIN sSetup.tSubjectMaster SM ON SM.Id= CS.SubjectId AND (SubjectId=@rSubjectId OR @rSubjectId=0)
			LEFT JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.AcademicId 
				AND (SR.AttendanceTypeId=5)
				AND (SR.AttendanceDate=@rAttendanceDate)
				AND ((ISNULL(SR.SubjectId,0)=@rSubjectId) OR (@rSubjectId=0))
				AND ((ISNULL(SR.PeriodNo,0)=@rPeriodNo) OR (@rPeriodNo=0))
				AND SR.AttendanceGroupId=@rAttendanceGroupId
			LEFT JOIN sHrm.vExtEmployeeMaster EM ON EM.EmployeeId=SA.InchargeEmployeeId
			WHERE 
			(SA.OrgId = @rOrgId)
			AND (SA.BatchId = @rBatchID)
			AND (AD.LeftDate > @rAttendanceDate OR ISNULL(AD.LeftDate,'')= '')
			AND (AD.AdmissionDate <= @rAttendanceDate)
			AND (SA.StatusId NOT IN(2,3))
			ORDER BY SA.ClassOrderIndex,SA.DivisionOrder,RollNo
		END 
	END
END
GO
PRINT N'Altering Procedure [sBiometric].[pRptTimeSheetListGet]...';


GO
ALTER PROCEDURE [sBiometric].[pRptTimeSheetListGet]
  @rBuilder1 nvarchar(max)='',
  @rBuilder2 nvarchar(max)='',
  @rEmployeeId bigint=0,  
  @rFromDate DateTime,  
  @rToDate DateTime,  
  @rTimeSheetStatus nvarchar(10) = '0',  
  @rOrgId int = 0  ,
  @rOrgGroupId int,
  @rEmployeeStatusId int = 0,
  @rOrganizationDepartmentId int=0,
  @rOrgGroupDepartmentId int = 0,
  @rGradeId nvarchar(max)= '0'

WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  
BEGIN 

CREATE TABLE #TempMonthTrans  
 (  
 Id int,  
 EmployeeId bigint,   
 Attn_Date DateTime,  
 PresentStatus nvarchar(15),  
 FirstIn nvarchar(20),  
 LastOut nvarchar(20),  
 OverTime nvarchar(20),  
 LateBy nvarchar(20),  
 Duration nvarchar(20),   
 EarlyBy nvarchar(20),
 ShiftName nvarchar(25)  
 )  
    Declare @ldate datetime,@lDays int
		declare @Days int
		Declare @Firstdate datetime
		Declare @Lastdate datetime
		DECLARE @lBatchID int
		DECLARE @lForYear nvarchar(20),@lForMonth nvarchar(20)
		Set @lForYear = Year(@rFromDate)
		
		Set @lForMonth = Month(@rFromDate)
		
		Set @ldate= CONVERT(nvarchar(20), @lForYear)+ '-' +  CONVERT(nvarchar(20), @lForMonth) + '-' + CONVERT(nvarchar(20), 01)
		Select @lDays=day(dateadd(mm,DateDiff(mm, -1, @ldate),0) -1) 
		select @Days=sCommon.fGetDaysInMonth(@lForMonth,@lForYear)
		
		set @Firstdate=CONVERT(nvarchar(20), @lForYear)+ '-' +  CONVERT(nvarchar(20), @lForMonth) + '-' + CONVERT(nvarchar(20), 01)
		set @Lastdate=CONVERT(nvarchar(20), @lForYear)+ '-' +  CONVERT(nvarchar(20), @lForMonth) + '-' + CONVERT(nvarchar(20), @Days)

 INSERT INTO #TempMonthTrans 
  select *
   from [sBiometric].[fBiometricTempMonthTransGet](@rOrgId ,@rOrganizationDepartmentId ,@rFromDate,@rToDate,@rEmployeeId)  
 

		
	 SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 as Builder2,
		TM.Id,
		TM.EmployeeId,
		TM.Attn_Date,
		OGD.Title AS [OrganizationGroupDepartment],
		TM.PresentStatus as PresentStatus,
		TM.FirstIn,
		TM.LastOut,
		TM.OverTime,
		TM.LateBy,
		TM.Duration,
		TM.EarlyBy,
		TM.ShiftName,
		 MT.Tot_Attn,
		 EM.FirstName + ' ' + EM.LastName As ShortName,
		 EM.Code as EmpCode ,   
		[sBiometric].[fEmployeeLeaveTypeGet] (TM.ATTN_DATE,TM.EmployeeId) AS LeaveStatus ,  
		ISNULL(ELS.Id,0) AS EmployeeLateStatusId, 
		ISNULL(SM.Id,0) AS StatusId,  
		ISNULL(SM.Title,'') AS Status ,
		 OM.Id AS OrgId,
		OM.Title AS OrganizationTitle  
	 FROM #TempMonthTrans TM   
	 INNER JOIN sBiometric.tMonthTrans MT ON MT.EmployeeId=TM.EmployeeId AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)  
	 INNER JOIN sHRM.tEmployeeMaster EM ON EM.Id=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  
	 INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id AND (TM.ATTN_DATE >= ISNULL(cast(rtrim(YEAR(EJD.DateOfJoining) *10000+ Month(EJD.DateOfJoining) *100+ 01) as datetime),'1900/01/01'))
	 INNER JOIN sSetup.tDepartmentMaster ODM ON EJD.OrganizationDepartmentId = ODM.Id 
	 LEFT JOIN sCommon.tOrgGroupDepartmentMaster OGD ON  EJD.OrgGroupDepartmentId=OGD.Id
	 INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgId
	 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 (( @rTimeSheetStatus = '1' AND (TM.Duration < '09:30')) OR ( @rTimeSheetStatus != '1' AND ((PresentStatus = @rTimeSheetStatus OR @rTimeSheetStatus='0'))))
	 AND (EM.OrgId = @rOrgId OR @rOrgId = 0)
	 AND (OM.OrgGroupId = @rOrgGroupId)
	 AND ((EM.StatusId = @rEmployeeStatusId) OR (@rEmployeeStatusId = 0))
	 AND((EJD.OrganizationDepartmentId=@rOrganizationDepartmentId) OR (@rOrganizationDepartmentId=0))
	 AND ((EJD.OrgGroupDepartmentId = @rOrgGroupDepartmentId) OR (@rOrgGroupDepartmentId=0)) 
	 AND  ISNULL(EM.IsOtherUser,0) = 0
	 AND (EJD.DateOfJoining<= @Lastdate OR ISNULL(EJD.DateOfJoining,'')='')
	 AND (EJD.DateOfleaving>= @Firstdate OR ISNULL(EJD.DateOfleaving,'')='')
	 AND (EmployeeGradeId in ( SELECT cast(item as int) FROM  sCommon.fnsplit(@rGradeId,',')) OR @rGradeId=0) 
	 Order By TM.EmployeeId,TM.Attn_Date

 --SELECT  @rBuilder1 AS Builder1,
	--@rBuilder2 as Builder2,
	--0 as Id,
	--CAST(0 AS bigint) AS EmployeeId,
	--CAST('1999-01-01 00:00:00' AS datetime) as Attn_Date,
	--'' AS OldPresentStatus,
	--'' AS [OrganizationGroupDepartment],
	--'' as PresentStatus,
	--'' as FirstIn,
	--'' AS LastOut,
	--'' as OverTime,
	--'' as LateBy,
	--'' as Duration,
	--'' as EarlyBy,
	--'' as ShiftName, 
	--'' As ShortName,
	--'' as EmpCode ,
	--'' AS LeaveStatus , 
	--'' AS LeavePendingStatus, 
	--'' AS EmployeeTravel,
	--0 AS EmployeeLateStatusId, 
	--0 AS StatusId, 
	--'' AS Status,
	--0 AS OrgId,
 --  '' AS OrganizationTitle  

 end
GO
PRINT N'Altering Procedure [sCommunication].[pAssignmentGet]...';


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

BEGIN 
	 IF @rIsSearch = 1
		BEGIN
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		END
	
	SELECT 
			DISTINCT
			A.Id as AssignmentId,
			A.SubjectId,
			SM.Title as SubjectName,
			A.Title,
			A.Remark,
			A.StartDate,
			A.EndDate,
			U.DisplayTitle as CreatedUserName,
			ISNULL(IsAssignmentDocumentUpload,0) AS IsAssignmentDocumentUpload
			--ISNULL(AV.Remark,'') AS ViewRemark
		    
  FROM 
   --         sCommunication.tAssignment A
			--INNER JOIN [sCommunication].[tAssignmentScope] CAS on A.Id = CAS.AssignmentId
   --         INNER JOIN sSecurity.tUser U ON U.Id=A.CreatedUserId
   --         INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=A.SubjectId
			--INNER JOIN [sSetup].[tClassSubject] CS on CS.SubjectId = SM.Id	
			--LEFT JOIN [sSetup].[tDivisionMaster] DM on DM.Id = CAS.SourceId and CS.ClassId = Dm.classId 
			--LEFT JOIN sCommunication.tAssignmentView AV ON A.Id = AV.AssignmentId
			 sCommunication.tAssignment A
			INNER JOIN [sCommunication].[tAssignmentScope] CAS on A.Id = CAS.AssignmentId
            INNER JOIN sSecurity.tUser U ON U.Id=A.CreatedUserId
            INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=A.SubjectId
			LEFT JOIN [sSetup].[tDivisionMaster] DM on DM.Id = CAS.SourceId AND CAS.SourceTypeId = 2005
			--LEFT JOIN sCommunication.tAssignmentView AV ON A.Id = AV.AssignmentId  -- Comment for duplicate data in mobile side for MantisId: 0027677
  WHERE 
  
      ((A.Id = @rId) OR (@rId = 0))
    AND ((A.SubjectId = @rSubjectId) OR (@rSubjectId = 0))
	AND ((A.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
	AND ((A.StartDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	AND ((A.StartDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
	AND ((A.CreatedUserId = @rCreatedUserId) OR (@rCreatedUserId = 0))
	AND A.BatchId=@rBatchId
END
GO
PRINT N'Altering Procedure [sFee].[pChargeAccountMappingGet]...';


GO
ALTER PROCEDURE [sFee].[pChargeAccountMappingGet]
				
		   @rBuilder1 nvarchar(max)='',
		   @rBuilder2 nvarchar(max)='', 
		 
           --@rChargeCategoryId int,
		   --@rBatchId int,
		   @rOrgGroupId int, 
		   @rChargeCategoryId int,
		   @rPayTypeId int=0			--add for 27383 mantis
		   
           
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 
	SELECT  
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			 ISNULL(CM.Id,0)AS ChargeId,
			ISNULL(AM.ChargeId,0)AS AMChargeId,
			--ISNULL(FS.ClassId,0)AS ClassId,
			 
			ISNULL(CM.ChargeCategoryId,0) AS ChargeCategoryId,
			--ISNULL(CR.BatchId,0)AS BatchId,
			 
			ISNULL(AYM.AccountId,0) AS AccountId,
			ISNULL(AM.CreditLedgerId,0) AS CreditLedgerId,
			ISNULL(AM.DebitLedgerId,0) AS DebitLedgerId,
			ISNULL(AM.AccountingYearId,0) AS AccountingYearId,
			ISNULL(AM.PayTypeId,0) AS AMPayTypeId,
			ISNULL(PTM.Id,0) AS PayTypeId,
			ISNULL(PTM.Title,'') AS PayTypeName,
			ISNULL(RB.TItle,'') AS ReceiptBookTitle,
			ISNULL(RB.Id,0) AS ReceiptBookId ,
			CM.Title AS ChargeTitle
  FROM 
		  sFee.tChargeMaster CM
		  inner join  sFee.tChargeCategoryMaster CCM ON CCM.Id = CM.ChargeCategoryId AND CM.ChargeCategoryId=@rChargeCategoryId
		 --INNER JOIN sFee.tChargeReceiptDetail CE ON CE.ChargeId = CM.Id AND CM.ChargeCategoryId=@rChargeCategoryId
		 --INNER JOIN sFee.tChargeReceipt CR ON CR.Id=CE.ChargeReceiptId
		INNER JOIN  sFee.tChargeReceiptBookMaster RB ON CCM.ChargeReceiptBookId = RB.Id
		Cross JOIN sFinanceCommon.tPayTypeMaster PTM
		LEFT JOIN sFee.tChargeAccountMapping AM ON AM.ChargeId=CM.Id AND AM.PayTypeId=PTM.Id	
		LEFT JOIN sAccounting.tLedgerMaster CLM ON (CLM.Id=AM.CreditLedgerId)  AND CLM.AccountingYearId = AM.AccountingYearId
		LEFT JOIN sAccounting.tLedgerMaster DLM ON (DLM.Id=AM.DebitLedgerId) AND DLM.AccountingYearId = AM.AccountingYearId
		LEFT JOIN sAccounting.tAccountingYearMaster AYM ON AYM.Id=CLM.AccountingYearId AND AYM.Id=DLM.AccountingYearId
WHERE 
		CM.OrgGroupId=@rOrgGroupId
		AND ((PTM.Id=@rPayTypeId) or (@rPayTypeId=0))		--add for 27383 mantis

ORDER BY  PTM.Id

END
GO
PRINT N'Altering Procedure [sFee].[pConsolidateFeeStatusDashboardGet]...';


GO
ALTER PROCEDURE [sFee].[pConsolidateFeeStatusDashboardGet]
	@rType int =0,
	@rCommonOrgGroupBatchId int=0,
	@rOrgGroupId smallint=0,
	@rReceiptBookId int =0,
	@rOrgId int  =0,
	@rFeeHeadId int =0,
	@rFeeId int =0
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	
	IF OBJECT_ID('tempdb..#TempFeeSetupData') IS NOT NULL DROP TABLE #TempFeeSetupData
	
	SELECT * 
	INTO #TempFeeSetupData
	FROM 
	(
		SELECT 
			FS1.FeeId,
			FS1.Id,
			ISNULL(FS1.Amount,0)AS Amount,
			ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
			FM.Title AS FeeName,
			FM.Id AS FeeMasterId,
			SA1.AcademicId,
			FM.FeeHeadId,
			FM.OrderIndex
		FROM sFee.tFeeSetup FS1
		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
		INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		WHERE FS1.IsOptional=0

		UNION ALL
				
		SELECT 
			FS1.FeeId,
			FS1.Id,
			ISNULL(FS1.Amount,0)AS Amount,
			ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
			FM.Title AS FeeName,
			FM.Id AS FeeMasterId,
			SA1.AcademicId,
			FM.FeeHeadId,
			FM.OrderIndex
		FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id 
		INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND FS1.BatchId = SA1.BatchId
		AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
		WHERE FS1.IsOptional=1
	) AS A

	IF (@rType = 1)
	BEGIN
		
		SELECT 
			RBM.Id AS ReceiptBookId,
			RBM.Title AS ReceiptBook,
			SUM(ISNULL(R.PaidAmount,0)) AS PaidAmount,
			SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00))AS PendingAmount,
			SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)) AS Total,
			RBM.OrderIndex
		FROM 
			sStudent.vStudentAcademic SA
			INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA.StudentId
			INNER JOIN #TempFeeSetupData 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 
					INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA1.StudentId
					INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA1.OrgId
					INNER JOIN sSetup.tOrgGroupMaster OMM ON OMM.Id = OM.OrgGroupId 
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=SA1.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				WHERE		
					(R.SourceTypeId = 2001) AND (R.IsObsolete = 0) 
					AND COGBM.Id = @rCommonOrgGroupBatchId
					AND((OMM.Id = @rOrgGroupId) OR (@rOrgGroupId = 0))
				GROUP BY FeeSetupId,R.SourceId
			) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
			LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003  
			LEFT JOIN (
				SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
				INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
				INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=B.OrgGroupBatchId
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				WHERE COGBM.Id = @rCommonOrgGroupBatchId
			) RT ON RT.SourceId = SA.StudentId 
			INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
			INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
			INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FS.FeeHeadId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OMM ON OMM.Id = OM.OrgGroupId 
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=SA.OrgGroupBatchId
			INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
		WHERE  
			COGBM.Id = @rCommonOrgGroupBatchId
			AND((OMM.Id = @rOrgGroupId) OR (@rOrgGroupId = 0))
		GROUP BY RBM.Title,RBM.Id,RBM.OrderIndex
		Order By RBM.OrderIndex, RBM.Id
	END
	ELSE IF (@rType = 11)
	BEGIN
		SELECT 
			ISNULL(SA.AcademicId,0) AS SourceId,
			ISNULL(SA.ClassName,'') AS ClassName,
			ISNULL(SA.DivisionId,0) AS DivisionId,
			ISNULL(SA.DivisionName,'') AS DivisionName,
			ISNULL(SA.ClassName+'-'+SA.DivisionName,'') AS ClassDivision,
			ISNULL(SA.Code,'') As Code,
			ISNULL(SA.Name,'') AS Name,
			ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
			SUM(ISNULL(R.PaidAmount,0)) AS PaidAmount,
			SA.ClassOrderIndex,  
			SA.DivisionOrder,
			SA.RollNo 
		FROM 
			sStudent.vStudentAcademic SA
			INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA.StudentId
			LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
			INNER JOIN 
			(
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					FM.Title AS FeeName,
					SA1.AcademicId,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		
				WHERE 
					(FS1.IsOptional=0)

				UNION ALL
				
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					FM.Title AS FeeName,
					SA1.AcademicId,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1
				INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id 
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND FS1.BatchId = SA1.BatchId
				AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				WHERE
					 (FS1.IsOptional=1)
			
				) 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 
						INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA1.StudentId
					WHERE		
						(R.SourceTypeId = 2001)
						AND (R.IsObsolete = 0) 
					GROUP BY FeeSetupId,R.SourceId
				) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
				LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003  
				LEFT JOIN
				(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
					INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
					INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=B.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					WHERE COGBM.Id = @rCommonOrgGroupBatchId) RT ON RT.SourceId = SA.StudentId 
				 INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
				 INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
				 INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FS.FeeHeadId
				 INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
				 INNER JOIN sSetup.tOrgGroupMaster OMM ON OMM.Id = OM.OrgGroupId 
				 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=SA.OrgGroupBatchId
				 INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
		WHERE  
			COGBM.Id = @rCommonOrgGroupBatchId
			AND((OMM.Id = @rOrgGroupId) OR (@rOrgGroupId = 0))
			AND ((RBM.Id = @rReceiptBookId) OR (@rReceiptBookId = 0))
		GROUP by SA.ClassName,SA.DivisionName,SA.Name,SC.ParentContactNo,SA.Code,SA.ClassOrderIndex,SA.DivisionOrder,SA.RollNo,SA.DivisionId,SA.AcademicId
		Having SUM(ISNULL(R.PaidAmount,0)) >0
		ORDER BY SA.ClassOrderIndex,SA.DivisionOrder,SA.RollNo
	END
	ELSE IF (@rType = 12)
	BEGIN
		SELECT 
			ISNULL(SA.AcademicId,0) AS SourceId,
			ISNULL(SA.ClassName,'') AS ClassName,
			ISNULL(SA.DivisionId,0) AS DivisionId,
			ISNULL(SA.DivisionName,'') AS DivisionName,
			ISNULL(SA.ClassName+'-'+SA.DivisionName,'') AS ClassDivision,
			ISNULL(SA.Code,'') As Code,
			ISNULL(SA.Name,'') AS Name,
			ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
			SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00))AS PendingAmount,
			SA.ClassOrderIndex,  
			SA.DivisionOrder,
			SA.RollNo 
		FROM 
			sStudent.vStudentAcademic SA
			INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA.StudentId
			LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
			INNER JOIN 
			(
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					FM.Title AS FeeName,
					SA1.AcademicId,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		
				WHERE 
					(FS1.IsOptional=0)

				UNION ALL
				
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					FM.Title AS FeeName,
					SA1.AcademicId,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1
				INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id 
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND FS1.BatchId = SA1.BatchId
				AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				WHERE
					 (FS1.IsOptional=1)
			
				) 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 
						INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA1.StudentId
					WHERE		
						(R.SourceTypeId = 2001)
						AND (R.IsObsolete = 0) 
					GROUP BY FeeSetupId,R.SourceId
				) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
				LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003  
				LEFT JOIN
				(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
					INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
					INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=B.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					WHERE COGBM.Id = @rCommonOrgGroupBatchId) RT ON RT.SourceId = SA.StudentId 
				 INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
				 INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
				 INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FS.FeeHeadId
				 INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
				 INNER JOIN sSetup.tOrgGroupMaster OMM ON OMM.Id = OM.OrgGroupId 
				 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=SA.OrgGroupBatchId
				 INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
		WHERE  
			COGBM.Id = @rCommonOrgGroupBatchId
			AND((OMM.Id = @rOrgGroupId) OR (@rOrgGroupId = 0))
			AND ((RBM.Id = @rReceiptBookId) OR (@rReceiptBookId = 0))
		GROUP by SA.ClassName,SA.DivisionName,SA.Name,SC.ParentContactNo,SA.Code,SA.ClassOrderIndex,SA.DivisionOrder,SA.RollNo,SA.DivisionId,SA.AcademicId
		Having SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)) >0
		ORDER BY SA.ClassOrderIndex,SA.DivisionOrder,SA.RollNo
	END
	ELSE IF (@rType = 13)
	BEGIN
		SELECT 
			ISNULL(SA.AcademicId,0) AS SourceId,
			ISNULL(SA.ClassName,'') AS ClassName,
			ISNULL(SA.DivisionId,0) AS DivisionId,
			ISNULL(SA.DivisionName,'') AS DivisionName,
			ISNULL(SA.ClassName+'-'+SA.DivisionName,'') AS ClassDivision,
			ISNULL(SA.Code,'') As Code,
			ISNULL(SA.Name,'') AS Name,
			ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
			SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)) AS TotalAmount,
			SA.ClassOrderIndex,  
			SA.DivisionOrder,
			SA.RollNo 
		FROM 
			sStudent.vStudentAcademic SA
			INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA.StudentId
			LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
			INNER JOIN 
			(
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					FM.Title AS FeeName,
					SA1.AcademicId,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		
				WHERE 
					(FS1.IsOptional=0)

				UNION ALL
				
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					FM.Title AS FeeName,
					SA1.AcademicId,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1
				INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id 
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND FS1.BatchId = SA1.BatchId
				AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				WHERE
					 (FS1.IsOptional=1)
			
				) 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 
						INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA1.StudentId
					WHERE		
						(R.SourceTypeId = 2001)
						AND (R.IsObsolete = 0) 
					GROUP BY FeeSetupId,R.SourceId
				) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
				LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003  
				LEFT JOIN
				(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
					INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
					INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=B.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					WHERE COGBM.Id = @rCommonOrgGroupBatchId) RT ON RT.SourceId = SA.StudentId 
				 INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
				 INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
				 INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FS.FeeHeadId
				 INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
				 INNER JOIN sSetup.tOrgGroupMaster OMM ON OMM.Id = OM.OrgGroupId 
				 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=SA.OrgGroupBatchId
				 INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
		WHERE  
			COGBM.Id = @rCommonOrgGroupBatchId
			AND((OMM.Id = @rOrgGroupId) OR (@rOrgGroupId = 0))
			AND ((RBM.Id = @rReceiptBookId) OR (@rReceiptBookId = 0))
		GROUP by SA.ClassName,SA.DivisionName,SA.Name,SC.ParentContactNo,SA.Code,SA.ClassOrderIndex,SA.DivisionOrder,SA.RollNo,SA.DivisionId,SA.AcademicId
		Having SUM(ISNULL(R.PaidAmount,0)+ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)) >0
		ORDER BY SA.ClassOrderIndex,SA.DivisionOrder,SA.RollNo
	END
	ELSE IF(@rType = 2)
	BEGIN
		SELECT 
			OM.Id AS OrgId,
			OM.Title AS Organization,
			SUM(ISNULL(R.PaidAmount,0)) AS PaidAmount,
			SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00))AS PendingAmount,
			SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)) AS Total,
			OM.OrderIndex
		FROM 
			sStudent.vStudentAcademic SA
			INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA.StudentId
			INNER JOIN #TempFeeSetupData 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 
						INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA1.StudentId
					WHERE		
						(R.SourceTypeId = 2001)
						AND (R.IsObsolete = 0) 
					GROUP BY FeeSetupId,R.SourceId
				) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
				LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003  
				LEFT JOIN
				(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
					INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
					INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=B.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					WHERE COGBM.Id = @rCommonOrgGroupBatchId) RT ON RT.SourceId = SA.StudentId 
				 INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
				 INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
				 INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FS.FeeHeadId
				 INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
				 INNER JOIN sSetup.tOrgGroupMaster OMM ON OMM.Id = OM.OrgGroupId 
				 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=SA.OrgGroupBatchId
				 INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
		WHERE  
			COGBM.Id = @rCommonOrgGroupBatchId
			AND((OMM.Id = @rOrgGroupId) OR (@rOrgGroupId = 0))
		GROUP BY OM.Title,OM.Id,OM.OrderIndex
		Order BY OM.OrderIndex
	END
	ELSE IF (@rType = 21)
	BEGIN
		SELECT 
			ISNULL(SA.AcademicId,0) AS SourceId,
			ISNULL(SA.ClassName,'') AS ClassName,
			ISNULL(SA.DivisionId,0) AS DivisionId,
			ISNULL(SA.DivisionName,'') AS DivisionName,
			ISNULL(SA.ClassName+'-'+SA.DivisionName,'') AS ClassDivision,
			ISNULL(SA.Code,'') As Code,
			ISNULL(SA.Name,'') AS Name,
			ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
			SUM(ISNULL(R.PaidAmount,0)) AS PaidAmount,
			SA.ClassOrderIndex,  
			SA.DivisionOrder,
			SA.RollNo 
		FROM 
			sStudent.vStudentAcademic SA
			INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA.StudentId
			LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
			INNER JOIN 
			(
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					FM.Title AS FeeName,
					SA1.AcademicId,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		
				WHERE 
					(FS1.IsOptional=0)

				UNION ALL
				
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					FM.Title AS FeeName,
					SA1.AcademicId,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1
				INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id 
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND FS1.BatchId = SA1.BatchId
				AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				WHERE
					 (FS1.IsOptional=1)
			
				) 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 
						INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA1.StudentId
					WHERE		
						(R.SourceTypeId = 2001)
						AND (R.IsObsolete = 0) 
					GROUP BY FeeSetupId,R.SourceId
				) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
				LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003  
				LEFT JOIN
				(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
					INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
					INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=B.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					WHERE COGBM.Id = @rCommonOrgGroupBatchId) RT ON RT.SourceId = SA.StudentId 
				 INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
				 INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
				 INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FS.FeeHeadId
				 INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
				 INNER JOIN sSetup.tOrgGroupMaster OMM ON OMM.Id = OM.OrgGroupId 
				 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=SA.OrgGroupBatchId
				 INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
		WHERE  
			COGBM.Id = @rCommonOrgGroupBatchId
			AND((OMM.Id = @rOrgGroupId) OR (@rOrgGroupId = 0))
			AND ((O.Id = @rOrgId) OR (@rOrgId = 0))
		GROUP by SA.ClassName,SA.DivisionName,SA.Name,SC.ParentContactNo,SA.Code,SA.ClassOrderIndex,SA.DivisionOrder,SA.RollNo,SA.DivisionId,SA.AcademicId
		Having SUM(ISNULL(R.PaidAmount,0)) >0
		ORDER BY SA.ClassOrderIndex,SA.DivisionOrder,SA.RollNo
	END
	ELSE IF (@rType = 22)
	BEGIN
		SELECT 
			ISNULL(SA.AcademicId,0) AS SourceId,
			ISNULL(SA.ClassName,'') AS ClassName,
			ISNULL(SA.DivisionId,0) AS DivisionId,
			ISNULL(SA.DivisionName,'') AS DivisionName,
			ISNULL(SA.ClassName+'-'+SA.DivisionName,'') AS ClassDivision,
			ISNULL(SA.Code,'') As Code,
			ISNULL(SA.Name,'') AS Name,
			ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
			SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00))AS PendingAmount,
			SA.ClassOrderIndex,  
			SA.DivisionOrder,
			SA.RollNo 
		FROM 
			sStudent.vStudentAcademic SA
			INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA.StudentId
			LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
			INNER JOIN 
			(
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					FM.Title AS FeeName,
					SA1.AcademicId,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		
				WHERE 
					(FS1.IsOptional=0)

				UNION ALL
				
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					FM.Title AS FeeName,
					SA1.AcademicId,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1
				INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id 
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND FS1.BatchId = SA1.BatchId
				AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				WHERE
					 (FS1.IsOptional=1)
			
				) 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 
						INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA1.StudentId
					WHERE		
						(R.SourceTypeId = 2001)
						AND (R.IsObsolete = 0) 
					GROUP BY FeeSetupId,R.SourceId
				) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
				LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003  
				LEFT JOIN
				(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
					INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
					INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=B.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					WHERE COGBM.Id = @rCommonOrgGroupBatchId) RT ON RT.SourceId = SA.StudentId 
				 INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
				 INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
				 INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FS.FeeHeadId
				 INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
				 INNER JOIN sSetup.tOrgGroupMaster OMM ON OMM.Id = OM.OrgGroupId 
				 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=SA.OrgGroupBatchId
				 INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
		WHERE  
			COGBM.Id = @rCommonOrgGroupBatchId
			AND((OMM.Id = @rOrgGroupId) OR (@rOrgGroupId = 0))
			AND ((O.Id = @rOrgId) OR (@rOrgId = 0))
		GROUP by SA.ClassName,SA.DivisionName,SA.Name,SC.ParentContactNo,SA.Code,SA.ClassOrderIndex,SA.DivisionOrder,SA.RollNo,SA.DivisionId,SA.AcademicId
		Having SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)) >0
		ORDER BY SA.ClassOrderIndex,SA.DivisionOrder,SA.RollNo
	END
	ELSE IF (@rType = 23)
	BEGIN
		SELECT 
			ISNULL(SA.AcademicId,0) AS SourceId,
			ISNULL(SA.ClassName,'') AS ClassName,
			ISNULL(SA.DivisionId,0) AS DivisionId,
			ISNULL(SA.DivisionName,'') AS DivisionName,
			ISNULL(SA.ClassName+'-'+SA.DivisionName,'') AS ClassDivision,
			ISNULL(SA.Code,'') As Code,
			ISNULL(SA.Name,'') AS Name,
			ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
			SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)) AS TotalAmount,
			SA.ClassOrderIndex,  
			SA.DivisionOrder,
			SA.RollNo 
		FROM 
			sStudent.vStudentAcademic SA
			INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA.StudentId
			LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
			INNER JOIN 
			(
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					FM.Title AS FeeName,
					SA1.AcademicId,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		
				WHERE 
					(FS1.IsOptional=0)

				UNION ALL
				
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					FM.Title AS FeeName,
					SA1.AcademicId,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1
				INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id 
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND FS1.BatchId = SA1.BatchId
				AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				WHERE
					 (FS1.IsOptional=1)
			
				) 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 
						INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA1.StudentId
					WHERE		
						(R.SourceTypeId = 2001)
						AND (R.IsObsolete = 0) 
					GROUP BY FeeSetupId,R.SourceId
				) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
				LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003  
				LEFT JOIN
				(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
					INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
					INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=B.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					WHERE COGBM.Id = @rCommonOrgGroupBatchId) RT ON RT.SourceId = SA.StudentId 
				 INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
				 INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
				 INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FS.FeeHeadId
				 INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
				 INNER JOIN sSetup.tOrgGroupMaster OMM ON OMM.Id = OM.OrgGroupId 
				 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=SA.OrgGroupBatchId
				 INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
		WHERE  
			COGBM.Id = @rCommonOrgGroupBatchId
			AND((OMM.Id = @rOrgGroupId) OR (@rOrgGroupId = 0))
			AND ((O.Id = @rOrgId) OR (@rOrgId = 0))
		GROUP by SA.ClassName,SA.DivisionName,SA.Name,SC.ParentContactNo,SA.Code,SA.ClassOrderIndex,SA.DivisionOrder,SA.RollNo,SA.DivisionId,SA.AcademicId
		Having SUM(ISNULL(R.PaidAmount,0)+ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)) >0
		ORDER BY SA.ClassOrderIndex,SA.DivisionOrder,SA.RollNo
	END
	ELSE IF (@rType = 24)
	BEGIN
		SELECT 
			ISNULL(SA.DivisionId,0) AS DivisionId,
			ISNULL(SA.ClassName,'') AS ClassName,
			ISNULL(SA.DivisionName,'') AS DivisionName,
			ISNULL(SA.ClassName+'-'+SA.DivisionName,'') AS ClassDivision,
			SUM(ISNULL(R.PaidAmount,0)) AS PaidAmount,
			SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00))AS PendingAmount,
			SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)) AS Total,
			SA.DivisionOrder
		FROM 
			sStudent.vStudentAcademic SA
			INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA.StudentId
			INNER JOIN 
			(
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					FM.Title AS FeeName,
					SA1.AcademicId,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		
				WHERE 
					(FS1.IsOptional=0)

				UNION ALL
				
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					FM.Title AS FeeName,
					SA1.AcademicId,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1
				INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id 
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND FS1.BatchId = SA1.BatchId
				AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				WHERE
					 (FS1.IsOptional=1)
			
				) 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 
						INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA1.StudentId
					WHERE		
						(R.SourceTypeId = 2001)
						AND (R.IsObsolete = 0) 
					GROUP BY FeeSetupId,R.SourceId
				) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
				LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003  
				LEFT JOIN
				(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
					INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
					INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=B.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					WHERE COGBM.Id = @rCommonOrgGroupBatchId) RT ON RT.SourceId = SA.StudentId 
				 INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
				 INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
				 INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FS.FeeHeadId
				 INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
				 INNER JOIN sSetup.tOrgGroupMaster OMM ON OMM.Id = OM.OrgGroupId 
				 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=SA.OrgGroupBatchId
				 INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
		WHERE  
			COGBM.Id = @rCommonOrgGroupBatchId
			AND((OMM.Id = @rOrgGroupId) OR (@rOrgGroupId = 0))
			AND ((O.Id = @rOrgId) OR (@rOrgId = 0))
		GROUP BY  SA.ClassName,SA.DivisionName,SA.DivisionId,SA.DivisionOrder
		Order BY SA.DivisionOrder
	END
	ELSE IF(@rType = 3)
	BEGIN
		SELECT 
			FHM.Id AS FeeHeadId,
			FHM.Title AS FeeHeadTitle,
			SUM(ISNULL(R.PaidAmount,0)) AS PaidAmount,
			SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00))AS PendingAmount,
			SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)) AS Total,
			FHM.OrderIndex
		FROM 
			sStudent.vStudentAcademic SA
			INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA.StudentId
			INNER JOIN #TempFeeSetupData 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 
						INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA1.StudentId
					WHERE		
						(R.SourceTypeId = 2001)
						AND (R.IsObsolete = 0) 
					GROUP BY FeeSetupId,R.SourceId
				) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
				LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003  
				LEFT JOIN
				(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
					INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
					INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=B.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					WHERE COGBM.Id = @rCommonOrgGroupBatchId) RT ON RT.SourceId = SA.StudentId 
				 INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
				 INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
				 INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FS.FeeHeadId
				 INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
				 INNER JOIN sSetup.tOrgGroupMaster OMM ON OMM.Id = OM.OrgGroupId 
				 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=SA.OrgGroupBatchId
				 INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
		WHERE  
			COGBM.Id = @rCommonOrgGroupBatchId
			AND((OMM.Id = @rOrgGroupId) OR (@rOrgGroupId = 0))
		GROUP BY FHM.Title,FHM.Id,FHM.OrderIndex
		Order By FHM.OrderIndex
	END
	ELSE IF (@rType = 31)
	BEGIN
		SELECT 
			ISNULL(SA.AcademicId,0) AS SourceId,
			ISNULL(SA.ClassName,'') AS ClassName,
			ISNULL(SA.DivisionId,0) AS DivisionId,
			ISNULL(SA.DivisionName,'') AS DivisionName,
			ISNULL(SA.ClassName+'-'+SA.DivisionName,'') AS ClassDivision,
			ISNULL(SA.Code,'') As Code,
			ISNULL(SA.Name,'') AS Name,
			ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
			SUM(ISNULL(R.PaidAmount,0)) AS PaidAmount,
			SA.ClassOrderIndex,  
			SA.DivisionOrder,
			SA.RollNo 
		FROM 
			sStudent.vStudentAcademic SA
			INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA.StudentId
			LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
			INNER JOIN 
			(
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					FM.Title AS FeeName,
					SA1.AcademicId,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		
				WHERE 
					(FS1.IsOptional=0)

				UNION ALL
				
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					FM.Title AS FeeName,
					SA1.AcademicId,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1
				INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id 
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND FS1.BatchId = SA1.BatchId
				AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				WHERE
					 (FS1.IsOptional=1)
			
				) 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 
						INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA1.StudentId
					WHERE		
						(R.SourceTypeId = 2001)
						AND (R.IsObsolete = 0) 
					GROUP BY FeeSetupId,R.SourceId
				) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
				LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003  
				LEFT JOIN
				(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
					INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
					INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=B.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					WHERE COGBM.Id = @rCommonOrgGroupBatchId) RT ON RT.SourceId = SA.StudentId 
				 INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
				 INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
				 INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FS.FeeHeadId
				 INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
				 INNER JOIN sSetup.tOrgGroupMaster OMM ON OMM.Id = OM.OrgGroupId 
				 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=SA.OrgGroupBatchId
				 INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
		WHERE  
			COGBM.Id = @rCommonOrgGroupBatchId
			AND((OMM.Id = @rOrgGroupId) OR (@rOrgGroupId = 0))
			AND ((FHM.Id = @rFeeHeadId) OR (@rFeeHeadId =0))
		GROUP by SA.ClassName,SA.DivisionName,SA.Name,SC.ParentContactNo,SA.Code,SA.ClassOrderIndex,SA.DivisionOrder,SA.RollNo,SA.DivisionId,SA.AcademicId
		Having SUM(ISNULL(R.PaidAmount,0)) >0
		ORDER BY SA.ClassOrderIndex,SA.DivisionOrder,SA.RollNo
	END
	ELSE IF (@rType = 32)
	BEGIN
		SELECT 
			ISNULL(SA.AcademicId,0) AS SourceId,
			ISNULL(SA.ClassName,'') AS ClassName,
			ISNULL(SA.DivisionId,0) AS DivisionId,
			ISNULL(SA.DivisionName,'') AS DivisionName,
			ISNULL(SA.ClassName+'-'+SA.DivisionName,'') AS ClassDivision,
			ISNULL(SA.Code,'') As Code,
			ISNULL(SA.Name,'') AS Name,
			ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
			SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00))AS PendingAmount,
			SA.ClassOrderIndex,  
			SA.DivisionOrder,
			SA.RollNo 
		FROM 
			sStudent.vStudentAcademic SA
			INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA.StudentId
			LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
			INNER JOIN 
			(
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					FM.Title AS FeeName,
					SA1.AcademicId,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		
				WHERE 
					(FS1.IsOptional=0)

				UNION ALL
				
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					FM.Title AS FeeName,
					SA1.AcademicId,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1
				INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id 
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND FS1.BatchId = SA1.BatchId
				AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				WHERE
					 (FS1.IsOptional=1)
			
				) 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 
						INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA1.StudentId
					WHERE		
						(R.SourceTypeId = 2001)
						AND (R.IsObsolete = 0) 
					GROUP BY FeeSetupId,R.SourceId
				) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
				LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003  
				LEFT JOIN
				(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
					INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
					INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=B.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					WHERE COGBM.Id = @rCommonOrgGroupBatchId) RT ON RT.SourceId = SA.StudentId 
				 INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
				 INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
				 INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FS.FeeHeadId
				 INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
				 INNER JOIN sSetup.tOrgGroupMaster OMM ON OMM.Id = OM.OrgGroupId 
				 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=SA.OrgGroupBatchId
				 INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
		WHERE  
			COGBM.Id = @rCommonOrgGroupBatchId
			AND((OMM.Id = @rOrgGroupId) OR (@rOrgGroupId = 0))
			AND ((FHM.Id = @rFeeHeadId) OR (@rFeeHeadId = 0))
		GROUP by SA.ClassName,SA.DivisionName,SA.Name,SC.ParentContactNo,SA.Code,SA.ClassOrderIndex,SA.DivisionOrder,SA.RollNo,SA.DivisionId,SA.AcademicId
		Having SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)) >0
		ORDER BY SA.ClassOrderIndex,SA.DivisionOrder,SA.RollNo
	END
	ELSE IF (@rType = 33)
	BEGIN
		SELECT 
			ISNULL(SA.AcademicId,0) AS SourceId,
			ISNULL(SA.ClassName,'') AS ClassName,
			ISNULL(SA.DivisionId,0) AS DivisionId,
			ISNULL(SA.DivisionName,'') AS DivisionName,
			ISNULL(SA.ClassName+'-'+SA.DivisionName,'') AS ClassDivision,
			ISNULL(SA.Code,'') As Code,
			ISNULL(SA.Name,'') AS Name,
			ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
			SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)) AS TotalAmount,
			SA.ClassOrderIndex,  
			SA.DivisionOrder,
			SA.RollNo 
		FROM 
			sStudent.vStudentAcademic SA
			INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA.StudentId
			LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
			INNER JOIN 
			(
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					FM.Title AS FeeName,
					SA1.AcademicId,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		
				WHERE 
					(FS1.IsOptional=0)

				UNION ALL
				
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					FM.Title AS FeeName,
					SA1.AcademicId,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1
				INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id 
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND FS1.BatchId = SA1.BatchId
				AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				WHERE
					 (FS1.IsOptional=1)
			
				) 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 
						INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA1.StudentId
					WHERE		
						(R.SourceTypeId = 2001)
						AND (R.IsObsolete = 0) 
					GROUP BY FeeSetupId,R.SourceId
				) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
				LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003  
				LEFT JOIN
				(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
					INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
					INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=B.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					WHERE COGBM.Id = @rCommonOrgGroupBatchId) RT ON RT.SourceId = SA.StudentId 
				 INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
				 INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
				 INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FS.FeeHeadId
				 INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
				 INNER JOIN sSetup.tOrgGroupMaster OMM ON OMM.Id = OM.OrgGroupId 
				 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=SA.OrgGroupBatchId
				 INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
		WHERE  
			COGBM.Id = @rCommonOrgGroupBatchId
			AND((OMM.Id = @rOrgGroupId) OR (@rOrgGroupId = 0))
			AND ((FHM.Id = @rFeeHeadId) OR (@rFeeHeadId = 0))
		GROUP by SA.ClassName,SA.DivisionName,SA.Name,SC.ParentContactNo,SA.Code,SA.ClassOrderIndex,SA.DivisionOrder,SA.RollNo,SA.DivisionId,SA.AcademicId
		Having SUM(ISNULL(R.PaidAmount,0)+ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)) >0
		ORDER BY SA.ClassOrderIndex,SA.DivisionOrder,SA.RollNo
	END
	ELSE IF(@rType = 4)
	BEGIN
		SELECT 
			FS.FeeMasterId AS FeeId,
			FS.FeeName AS FeeName,
			SUM(ISNULL(R.PaidAmount,0)) AS PaidAmount,
			SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00))AS PendingAmount,
			SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)) AS Total,
			FS.OrderIndex
		FROM 
			sStudent.vStudentAcademic SA
			INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA.StudentId
			INNER JOIN #TempFeeSetupData 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 
						INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA1.StudentId
					WHERE		
						(R.SourceTypeId = 2001)
						AND (R.IsObsolete = 0) 
					GROUP BY FeeSetupId,R.SourceId
				) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
				LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003  
				LEFT JOIN
				(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
					INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
					INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=B.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					WHERE COGBM.Id = @rCommonOrgGroupBatchId) RT ON RT.SourceId = SA.StudentId 
				 INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
				 INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
				 INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FS.FeeHeadId
				 INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
				 INNER JOIN sSetup.tOrgGroupMaster OMM ON OMM.Id = OM.OrgGroupId 
				 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=SA.OrgGroupBatchId
				 INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
		WHERE  
			COGBM.Id = @rCommonOrgGroupBatchId
			AND((OMM.Id = @rOrgGroupId) OR (@rOrgGroupId = 0))
		GROUP BY FS.FeeName,FS.FeeMasterId,FS.OrderIndex
		Order By FS.OrderIndex 
	END
	ELSE IF (@rType = 41)
	BEGIN
		SELECT 
			ISNULL(SA.AcademicId,0) AS SourceId,
			ISNULL(SA.ClassName,'') AS ClassName,
			ISNULL(SA.DivisionId,0) AS DivisionId,
			ISNULL(SA.DivisionName,'') AS DivisionName,
			ISNULL(SA.ClassName+'-'+SA.DivisionName,'') AS ClassDivision,
			ISNULL(SA.Code,'') As Code,
			ISNULL(SA.Name,'') AS Name,
			ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
			SUM(ISNULL(R.PaidAmount,0)) AS PaidAmount,
			SA.ClassOrderIndex,  
			SA.DivisionOrder,
			SA.RollNo 
		FROM 
			sStudent.vStudentAcademic SA
			INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA.StudentId
			LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
			INNER JOIN 
			(
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					FM.Title AS FeeName,
					FM.Id AS FeeMasterId,
					SA1.AcademicId,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		
				WHERE 
					(FS1.IsOptional=0)

				UNION ALL
				
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					FM.Title AS FeeName,
					FM.Id AS FeeMasterId,
					SA1.AcademicId,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1
				INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id 
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND FS1.BatchId = SA1.BatchId
				AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				WHERE
					 (FS1.IsOptional=1)
			
				) 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 
						INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA1.StudentId
					WHERE		
						(R.SourceTypeId = 2001)
						AND (R.IsObsolete = 0) 
					GROUP BY FeeSetupId,R.SourceId
				) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
				LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003  
				LEFT JOIN
				(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
					INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
					INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=B.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					WHERE COGBM.Id = @rCommonOrgGroupBatchId) RT ON RT.SourceId = SA.StudentId 
				 INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
				 INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
				 INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FS.FeeHeadId
				 INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
				 INNER JOIN sSetup.tOrgGroupMaster OMM ON OMM.Id = OM.OrgGroupId 
				 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=SA.OrgGroupBatchId
				 INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
		WHERE  
			COGBM.Id = @rCommonOrgGroupBatchId
			AND((OMM.Id = @rOrgGroupId) OR (@rOrgGroupId = 0))
			AND ((FS.FeeMasterId = @rFeeId) OR (@rFeeId = 0))
		GROUP by SA.ClassName,SA.DivisionName,SA.Name,SC.ParentContactNo,SA.Code,SA.ClassOrderIndex,SA.DivisionOrder,SA.RollNo,SA.DivisionId,SA.AcademicId
		Having SUM(ISNULL(R.PaidAmount,0)) >0
		ORDER BY SA.ClassOrderIndex,SA.DivisionOrder,SA.RollNo
	END
	ELSE IF (@rType = 42)
	BEGIN
		SELECT 
			ISNULL(SA.AcademicId,0) AS SourceId,
			ISNULL(SA.ClassName,'') AS ClassName,
			ISNULL(SA.DivisionId,0) AS DivisionId,
			ISNULL(SA.DivisionName,'') AS DivisionName,
			ISNULL(SA.ClassName+'-'+SA.DivisionName,'') AS ClassDivision,
			ISNULL(SA.Code,'') As Code,
			ISNULL(SA.Name,'') AS Name,
			ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
			SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00))AS PendingAmount,
			SA.ClassOrderIndex,  
			SA.DivisionOrder,
			SA.RollNo 
		FROM 
			sStudent.vStudentAcademic SA
			INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA.StudentId
			LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
			INNER JOIN 
			(
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					FM.Title AS FeeName,
					FM.Id AS FeeMasterId,
					SA1.AcademicId,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		
				WHERE 
					(FS1.IsOptional=0)

				UNION ALL
				
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					FM.Title AS FeeName,
					FM.Id AS FeeMasterId,
					SA1.AcademicId,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1
				INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id 
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND FS1.BatchId = SA1.BatchId
				AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				WHERE
					 (FS1.IsOptional=1)
			
				) 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 
						INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA1.StudentId
					WHERE		
						(R.SourceTypeId = 2001)
						AND (R.IsObsolete = 0) 
					GROUP BY FeeSetupId,R.SourceId
				) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
				LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003  
				LEFT JOIN
				(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
					INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
					INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=B.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					WHERE COGBM.Id = @rCommonOrgGroupBatchId) RT ON RT.SourceId = SA.StudentId 
				 INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
				 INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
				 INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FS.FeeHeadId
				 INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
				 INNER JOIN sSetup.tOrgGroupMaster OMM ON OMM.Id = OM.OrgGroupId 
				 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=SA.OrgGroupBatchId
				 INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
		WHERE  
			COGBM.Id = @rCommonOrgGroupBatchId
			AND((OMM.Id = @rOrgGroupId) OR (@rOrgGroupId = 0))
			AND ((FS.FeeMasterId = @rFeeId) OR (@rFeeId = 0))
		GROUP by SA.ClassName,SA.DivisionName,SA.Name,SC.ParentContactNo,SA.Code,SA.ClassOrderIndex,SA.DivisionOrder,SA.RollNo,SA.DivisionId,SA.AcademicId
		Having SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)) >0
		ORDER BY SA.ClassOrderIndex,SA.DivisionOrder,SA.RollNo
	END
	ELSE IF (@rType = 43)
	BEGIN
		SELECT 
			ISNULL(SA.AcademicId,0) AS SourceId,
			ISNULL(SA.ClassName,'') AS ClassName,
			ISNULL(SA.DivisionId,0) AS DivisionId,
			ISNULL(SA.DivisionName,'') AS DivisionName,
			ISNULL(SA.ClassName+'-'+SA.DivisionName,'') AS ClassDivision,
			ISNULL(SA.Code,'') As Code,
			ISNULL(SA.Name,'') AS Name,
			ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
			SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)) AS TotalAmount,
			SA.ClassOrderIndex,  
			SA.DivisionOrder,
			SA.RollNo 
		FROM 
			sStudent.vStudentAcademic SA
			INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA.StudentId
			LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
			INNER JOIN 
			(
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					FM.Title AS FeeName,
					FM.Id AS FeeMasterId,
					SA1.AcademicId,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		
				WHERE 
					(FS1.IsOptional=0)

				UNION ALL
				
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					FM.Title AS FeeName,
					FM.Id AS FeeMasterId,
					SA1.AcademicId,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1
				INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id 
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND FS1.BatchId = SA1.BatchId
				AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				WHERE
					 (FS1.IsOptional=1)
			
				) 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 
						INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA1.StudentId
					WHERE		
						(R.SourceTypeId = 2001)
						AND (R.IsObsolete = 0) 
					GROUP BY FeeSetupId,R.SourceId
				) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
				LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003  
				LEFT JOIN
				(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
					INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
					INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=B.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					WHERE COGBM.Id = @rCommonOrgGroupBatchId) RT ON RT.SourceId = SA.StudentId 
				 INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
				 INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
				 INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FS.FeeHeadId
				 INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
				 INNER JOIN sSetup.tOrgGroupMaster OMM ON OMM.Id = OM.OrgGroupId 
				 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=SA.OrgGroupBatchId
				 INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
		WHERE  
			COGBM.Id = @rCommonOrgGroupBatchId
			AND((OMM.Id = @rOrgGroupId) OR (@rOrgGroupId = 0))
			AND ((FS.FeeMasterId = @rFeeId) OR (@rFeeId = 0))
		GROUP by SA.ClassName,SA.DivisionName,SA.Name,SC.ParentContactNo,SA.Code,SA.ClassOrderIndex,SA.DivisionOrder,SA.RollNo,SA.DivisionId,SA.AcademicId
		Having SUM(ISNULL(R.PaidAmount,0)+ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)) >0
		ORDER BY SA.ClassOrderIndex,SA.DivisionOrder,SA.RollNo
	END
END
GO
PRINT N'Altering Procedure [sFee].[pFeeImportAdd]...';


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

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

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

BEGIN CATCH 
Drop Table #TempFeeMaster 
		ROLLBACK TRANSACTION
		
		SELECT -1 AS Result
END CATCH	
END
GO
PRINT N'Altering Procedure [sFee].[pPendingFeeDashboardGet]...';


GO
ALTER PROCEDURE [sFee].[pPendingFeeDashboardGet]

		@rOrgGroupBatchId int = 0,
		@rCommonOrgGroupBatchId int = 0,
		@rType int,
		@rFilterType nvarchar(Max),
		@rFeeType nvarchar(Max),
		@rStudentStatus int = 0,
		@rUptoDate date = '',
		@rDepartmentId int=0,
	    @rOrgId int,
		@rReceiptBookId int,
		@rOrgGroupId int = 0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

SELECT @rOrgGroupBatchId = Id FROM sSetup.tOrgGroupBatchMaster WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND OrgGroupId = @rOrgGroupId

IF (@rType = 1)
 BEGIN
IF(@rFilterType = 'Organizationwise')		
	BEGIN 
	 IF(@rFeeType = 'FeeHeadwise')
	 BEGIN
		--SELECT
		--	SA.OrgId,
		--	O.Title AS OrgName,
		--	SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00))AS PendingAmount,
		--	FHM.Id AS FeeHeadId,
		--	FHM.Title AS FeeHeadName,
		--	FHM.OrderIndex
		--FROM
		--	sStudent.vStudentAcademic SA
		--	INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
		--	INNER JOIN 
		--	(
		--		SELECT 
		--			ISNULL(FS1.Amount,0)AS Amount,
		--			FM.Title AS FeeName,
		--			FM.FeeHeadId,
		--			SA1.Id As AcademicId,
		--			FS1.Id,
		--			FS1.StartDate
 	--			FROM sFee.tFeeSetup FS1
		--		INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
		--		INNER JOIN sStudent.tStudentMaster SM ON SA1.StudentId = SM.Id			 
		--		AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
		--		INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		--		INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
		--		WHERE 
		--			BM.OrgGroupBatchId = @rOrgGroupBatchId
		--			AND (FS1.IsOptional=0)
		--			-- IsInContext
		--			AND BM.IsInContext = 1
		--		UNION ALL
		--		SELECT 
		--			ISNULL(FS1.Amount,0)AS Amount,
		--			FM.Title AS FeeName,
		--			FM.FeeHeadId,
		--			SA1.AcademicId As AcademicId,
		--			FS1.Id,
		--			FS1.StartDate
		--		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 = FS1.ClassId
		--		INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
		--		WHERE
		--				SA1.OrgGroupBatchId = @rOrgGroupBatchId
		--				AND (FS1.IsOptional=1)
		--				-- IsInContext
		--				AND BM.IsInContext = 1
		--		) FS ON FS.AcademicId=SA.AcademicId
		--		LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
		--		LEFT JOIN
		--		(
		--			SELECT 
		--			    ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
		--			FROM
		--				sFee.tReceipt R 
		--				INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
		--				INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
		--				INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
		--				INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=R.SourceId
		--				INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA1.BatchId			
		--			WHERE		
		--				(R.SourceTypeId = 2001)
		--				AND (R.IsObsolete = 0) 
		--				AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId))
		--				AND (R.OrgGroupBatchId = @rOrgGroupBatchId)
		--				AND (R.ReceiptDate <= @rUptoDate) 
		--				-- IsInContext
		--				AND BM.IsInContext = 1 
		--				GROUP BY FeeSetupId,R.SourceId
		--		) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
		--		INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FS.FeeHeadId	
		--		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
		--	WHERE
		--	  SA.OrgGroupBatchId = @rOrgGroupBatchId
		--	  AND (SA.StatusId = @rStudentStatus OR @rStudentStatus=0)
		--	  AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
		--	  -- IsInContext
		--	  AND BM.IsInContext = 1
		--	GROUP BY SA.OrgId,O.Title,FHM.Id,FHM.Title,FHM.OrderIndex
		--	ORDER BY OrgId,FHM.OrderIndex

		CREATE TABLE #FeeHeadwisetmp
		(
		Amount decimal (12,2),
		FeeName nvarchar(100),
		FeeHeadId int,
		AcademicId bigint,
		Id int,
		StartDate date
		--ReceiptBookId int 
		)

		INSERT INTO #FeeHeadwisetmp
		SELECT 
					ISNULL(FS1.Amount,0)AS Amount,
					FM.Title AS FeeName,
					FM.FeeHeadId,
					SA1.Id As AcademicId,
					FS1.Id,
					FS1.StartDate
 				FROM sFee.tFeeSetup FS1
				INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
				INNER JOIN sStudent.tStudentMaster SM ON SA1.StudentId = SM.Id			 
				AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				WHERE 
					BM.OrgGroupBatchId = @rOrgGroupBatchId
					AND (FS1.IsOptional=0)
					-- IsInContext
					AND BM.IsInContext = 1
				UNION ALL
				SELECT 
					ISNULL(FS1.Amount,0)AS Amount,
					FM.Title AS FeeName,
					FM.FeeHeadId,
					SA1.AcademicId As AcademicId,
					FS1.Id,
					FS1.StartDate
				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 = FS1.ClassId
				INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				WHERE
						SA1.OrgGroupBatchId = @rOrgGroupBatchId
						AND (FS1.IsOptional=1)
						-- IsInContext
						AND BM.IsInContext = 1

		SELECT
			SA.OrgId,
			O.Title AS OrgName,
			SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00))AS PendingAmount,
			FHM.Id AS FeeHeadId,
			FHM.Title AS FeeHeadName,
			FHM.OrderIndex
		FROM
			sStudent.vStudentAcademic SA
			INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
			INNER JOIN #FeeHeadwisetmp FS ON FS.AcademicId=SA.AcademicId
			LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
			LEFT JOIN
			(
				SELECT 
					ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
				FROM
					sFee.tReceipt R 
					INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
					INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
					INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
					INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=R.SourceId
					INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA1.BatchId			
				WHERE		
					(R.SourceTypeId = 2001)
					AND (R.IsObsolete = 0) 
					AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId))
					AND (R.OrgGroupBatchId = @rOrgGroupBatchId)
					AND (R.ReceiptDate <= @rUptoDate) 
					-- IsInContext
					AND BM.IsInContext = 1 
					GROUP BY FeeSetupId,R.SourceId
			) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
			INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FS.FeeHeadId	
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
			WHERE
			  SA.OrgGroupBatchId = @rOrgGroupBatchId
			  AND (SA.StatusId = @rStudentStatus OR @rStudentStatus=0)
			  AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			  -- IsInContext
			  AND BM.IsInContext = 1
			GROUP BY SA.OrgId,O.Title,FHM.Id,FHM.Title,FHM.OrderIndex,O.OrderIndex
			ORDER BY O.OrderIndex,OrgId,FHM.OrderIndex

		DROP TABLE #FeeHeadwisetmp
	 END
	 ELSE IF(@rFeeType = 'FeeMasterwise')
	 BEGIN
		CREATE TABLE #FeeMasterwisetmp
		(
			FeeId int,
			Amount decimal (12,2),
			FeeName nvarchar(100),
			FeeHeadId int,
			AcademicId bigint,
			Id int,
			StartDate date,
			OrderIndex int
		)
	 
	 INSERT INTO #FeeMasterwisetmp
		 SELECT 
			FS1.FeeId,
			ISNULL(FS1.Amount,0)AS Amount,
			FM.Title AS FeeName,
			FM.FeeHeadId,
			SA1.Id As AcademicId,
			FS1.Id,
			FS1.StartDate,
			FM.OrderIndex
 		FROM sFee.tFeeSetup FS1
		INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
		INNER JOIN sStudent.tStudentMaster SM ON SA1.StudentId = SM.Id			 
		AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
		INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
		WHERE 
			BM.OrgGroupBatchId = @rOrgGroupBatchId
			AND (FS1.IsOptional=0)
			-- IsInContext
			AND BM.IsInContext = 1
		UNION ALL
		SELECT 
			FS1.FeeId,
			ISNULL(FS1.Amount,0)AS Amount,
			FM.Title AS FeeName,
			FM.FeeHeadId,
			SA1.AcademicId As AcademicId,
			FS1.Id,
			FS1.StartDate,
			FM.OrderIndex
		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 = FS1.ClassId
		INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
		WHERE
				SA1.OrgGroupBatchId = @rOrgGroupBatchId
				AND (FS1.IsOptional=1)
				-- IsInContext
				AND BM.IsInContext = 1

	 SELECT
			SA.OrgId,
			O.Title AS OrgName,
			SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00))AS PendingAmount,
			FS.FeeId,
			FS.FeeName,
			FS.OrderIndex
		FROM
			sStudent.vStudentAcademic SA
				INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
				INNER JOIN #FeeMasterwisetmp FS ON FS.AcademicId=SA.AcademicId
				LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
				LEFT JOIN
				(
					SELECT 
						ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
					FROM
						sFee.tReceipt R 
						INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
						INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
						INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
						INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=R.SourceId
						INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA1.BatchId			
					WHERE		
						(R.SourceTypeId = 2001)
						AND (R.IsObsolete = 0) 
						AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId))
						AND (R.OrgGroupBatchId = @rOrgGroupBatchId)
						AND (R.ReceiptDate <= @rUptoDate) 
						-- IsInContext
						AND BM.IsInContext = 1 
						GROUP BY FeeSetupId,R.SourceId
				) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
				INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FS.FeeHeadId	
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
			WHERE
				SA.OrgGroupBatchId = @rOrgGroupBatchId
				AND (SA.StatusId = @rStudentStatus OR @rStudentStatus=0)
				AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
				-- IsInContext
				AND BM.IsInContext = 1
			GROUP BY SA.OrgId,O.Title,FS.FeeId,FS.FeeName,FS.OrderIndex,O.OrderIndex
			ORDER BY O.OrderIndex,OrgId,FS.FeeId
	 DROP TABLE #FeeMasterwisetmp
	 END
	 ELSE IF(@rFeeType = 'CollectionGroupwise')
	 BEGIN
		CREATE TABLE #CollectionGroupwisetmp
		(
			FeeId int,
			Amount decimal (12,2),
			FeeName nvarchar(100),
			FeeHeadId int,
			AcademicId bigint,
			Id int,
			StartDate date,
			CollectionGroupId int
		)
	 INSERT INTO #CollectionGroupwisetmp
	 SELECT 
			FS1.FeeId,
			ISNULL(FS1.Amount,0)AS Amount,
			FM.Title AS FeeName,
			FM.FeeHeadId,
			SA1.Id As AcademicId,
			FS1.Id,
			FS1.StartDate,
			FS1.CollectionGroupId
 		FROM sFee.tFeeSetup FS1
		INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
		INNER JOIN sStudent.tStudentMaster SM ON SA1.StudentId = SM.Id			 
		AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
		INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
		WHERE 
			BM.OrgGroupBatchId = @rOrgGroupBatchId
			AND (FS1.IsOptional=0)
			-- IsInContext
			AND BM.IsInContext = 1
		UNION ALL
		SELECT 
			FS1.FeeId,
			ISNULL(FS1.Amount,0)AS Amount,
			FM.Title AS FeeName,
			FM.FeeHeadId,
			SA1.AcademicId As AcademicId,
			FS1.Id,
			FS1.StartDate,
			FS1.CollectionGroupId
		FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id
		INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId 
		AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.ClassId = FS1.ClassId
		INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
		WHERE
				SA1.OrgGroupBatchId = @rOrgGroupBatchId
				AND (FS1.IsOptional=1)
				-- IsInContext
				AND BM.IsInContext = 1

	 SELECT
			SA.OrgId,
			O.Title AS OrgName,
			SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00))AS PendingAmount,
			ISNULL(CGM.Id,0) AS CollectionGroupId,
			ISNULL(CGM.Title,'') AS CollectionGroupName,
			ISNULL(CGM.OrderIndex,0) AS OrderIndex
		FROM
			sStudent.vStudentAcademic SA
			INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
			INNER JOIN #CollectionGroupwisetmp FS ON FS.AcademicId=SA.AcademicId
				LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
				LEFT JOIN
				(
					SELECT 
					    ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
					FROM
						sFee.tReceipt R 
						INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
						INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
						INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
						INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=R.SourceId
						INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA1.BatchId			
					WHERE		
						(R.SourceTypeId = 2001)
						AND (R.IsObsolete = 0) 
						AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId))
						AND (R.OrgGroupBatchId = @rOrgGroupBatchId)
						AND (R.ReceiptDate <= @rUptoDate) 
						-- IsInContext
						AND BM.IsInContext = 1 
						GROUP BY FeeSetupId,R.SourceId
				) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
				LEFT JOIN sFee.tCollectionGroupMaster CGM ON FS.CollectionGroupId=CGM.Id
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
			WHERE
			  SA.OrgGroupBatchId = @rOrgGroupBatchId
			  AND (SA.StatusId = @rStudentStatus OR @rStudentStatus=0)
			  AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			  -- IsInContext
			  AND BM.IsInContext = 1
			GROUP BY SA.OrgId,O.Title,CGM.Id,CGM.Title,CGM.OrderIndex,O.OrderIndex
			ORDER BY O.OrderIndex,OrgId,CGM.Id

	 DROP TABLE #CollectionGroupwisetmp
	 END
	END
ELSE IF(@rFilterType = 'Departmentwise')
	BEGIN
	 IF(@rFeeType = 'FeeHeadwise')
	 BEGIN
		IF OBJECT_ID('tempdb..#tmpDepartFeeHeadWise') IS NOT NULL DROP TABLE #tmpDepartFeeHeadWise
		CREATE TABLE #tmpDepartFeeHeadWise
		(
		Amount decimal (12,2),
		FeeName nvarchar(100),
		FeeHeadId int,
		AcademicId bigint,
		Id int,
		StartDate date
		)

		Insert Into #tmpDepartFeeHeadWise
		SELECT 
					ISNULL(FS1.Amount,0)AS Amount,
					FM.Title AS FeeName,
					FM.FeeHeadId,
					SA1.Id As AcademicId,
					FS1.Id,
					FS1.StartDate
 				FROM sFee.tFeeSetup FS1
				INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
				INNER JOIN sStudent.tStudentMaster SM ON SA1.StudentId = SM.Id			 
				AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				WHERE 
					BM.OrgGroupBatchId = @rOrgGroupBatchId
					AND (FS1.IsOptional=0)
					-- IsInContext
					AND BM.IsInContext = 1
				UNION ALL
				SELECT 
					ISNULL(FS1.Amount,0)AS Amount,
					FM.Title AS FeeName,
					FM.FeeHeadId,
					SA1.AcademicId As AcademicId,
					FS1.Id,
					FS1.StartDate
				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 = FS1.ClassId
				INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				WHERE
						SA1.OrgGroupBatchId = @rOrgGroupBatchId
						AND (FS1.IsOptional=1)
						-- IsInContext
						AND BM.IsInContext = 1

		SELECT
			SA.DepartmentId,
		    SA.DepartmentName,
			SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00))AS PendingAmount,
			FHM.Id AS FeeHeadId,
			FHM.Title AS FeeHeadName,
			FHM.OrderIndex
		FROM
			sStudent.vStudentAcademic SA
		INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
		INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id = SA.DepartmentId
		INNER JOIN #tmpDepartFeeHeadWise FS ON FS.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
		LEFT JOIN
		(
			SELECT 
				ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
			FROM
				sFee.tReceipt R 
				INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
				INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
				INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
				INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=R.SourceId
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA1.BatchId			
			WHERE		
				(R.SourceTypeId = 2001)
				AND (R.IsObsolete = 0) 
				AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId))
				AND (R.OrgGroupBatchId = @rOrgGroupBatchId)
				AND (R.ReceiptDate <= @rUptoDate)
				-- IsInContext
				AND BM.IsInContext = 1  
				GROUP BY FeeSetupId,R.SourceId
		) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
		INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FS.FeeHeadId	
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
		WHERE
			  SA.OrgGroupBatchId = @rOrgGroupBatchId
			  AND (SA.StatusId = @rStudentStatus OR @rStudentStatus=0)
			  AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			  -- IsInContext
			  AND BM.IsInContext = 1 
		GROUP BY SA.DepartmentId,SA.DepartmentName,FHM.Id,FHM.Title,FHM.OrderIndex,DM.OrderIndex
		ORDER BY DM.OrderIndex,DepartmentId,FHM.Id
	 END
	 ELSE IF(@rFeeType = 'FeeMasterwise')
	 BEGIN

		IF OBJECT_ID('tempdb..#tmpDepartFeeMasterwise') IS NOT NULL DROP TABLE #tmpDepartFeeMasterwise
		CREATE TABLE #tmpDepartFeeMasterwise
		(
		FeeId int,
		Amount decimal (12,2),
		FeeName nvarchar(100),
		FeeHeadId int,
		AcademicId bigint,
		Id int,
		StartDate date,
		OrderIndex int
		)

		Insert Into #tmpDepartFeeMasterwise
		SELECT 
					FS1.FeeId,
					ISNULL(FS1.Amount,0)AS Amount,
					FM.Title AS FeeName,
					FM.FeeHeadId,
					SA1.Id As AcademicId,
					FS1.Id,
					FS1.StartDate,
					FM.OrderIndex
 				FROM sFee.tFeeSetup FS1
				INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
				INNER JOIN sStudent.tStudentMaster SM ON SA1.StudentId = SM.Id			 
				AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				WHERE 
					BM.OrgGroupBatchId = @rOrgGroupBatchId
					AND (FS1.IsOptional=0)
					-- IsInContext
					AND BM.IsInContext = 1
				UNION ALL
				SELECT 
					FS1.FeeId,
					ISNULL(FS1.Amount,0)AS Amount,
					FM.Title AS FeeName,
					FM.FeeHeadId,
					SA1.AcademicId As AcademicId,
					FS1.Id,
					FS1.StartDate,
					FM.OrderIndex
				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 = FS1.ClassId
				INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				WHERE
						SA1.OrgGroupBatchId = @rOrgGroupBatchId
						AND (FS1.IsOptional=1)
						-- IsInContext
						AND BM.IsInContext = 1


		SELECT
			SA.DepartmentId,
		    SA.DepartmentName,
			SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00))AS PendingAmount,
			FS.FeeId,
			FS.FeeName,
			FS.OrderIndex
		FROM
			sStudent.vStudentAcademic SA
				INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
				INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id = SA.DepartmentId
				INNER JOIN #tmpDepartFeeMasterwise FS ON FS.AcademicId=SA.AcademicId
				LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
				LEFT JOIN
				(
					SELECT 
					    ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
					FROM
						sFee.tReceipt R 
						INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
						INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
						INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
						INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=R.SourceId
						INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA1.BatchId			
					WHERE		
						(R.SourceTypeId = 2001)
						AND (R.IsObsolete = 0) 
						AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId))
						AND (R.OrgGroupBatchId = @rOrgGroupBatchId)
						AND (R.ReceiptDate <= @rUptoDate)  
						-- IsInContext
						AND BM.IsInContext = 1
						GROUP BY FeeSetupId,R.SourceId
				) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
				INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FS.FeeHeadId	
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
			WHERE
			  SA.OrgGroupBatchId = @rOrgGroupBatchId
			  AND (SA.StatusId = @rStudentStatus OR @rStudentStatus=0)
			  AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			  -- IsInContext
			  AND BM.IsInContext = 1
			GROUP BY SA.DepartmentId,SA.DepartmentName,FS.FeeId,FS.FeeName,FS.OrderIndex,DM.OrderIndex
			ORDER BY DM.OrderIndex,DepartmentId,FS.FeeId
	 END
	 ELSE IF(@rFeeType = 'CollectionGroupwise')
	 BEGIN
		IF OBJECT_ID('tempdb..#tmpDepartCollectionGroupwise') IS NOT NULL DROP TABLE #tmpDepartCollectionGroupwise
		CREATE TABLE #tmpDepartCollectionGroupwise
		(
		FeeId int,
		Amount decimal (12,2),
		FeeName nvarchar(100),
		FeeHeadId int,
		AcademicId bigint,
		Id int,
		StartDate date,
		CollectionGroupId int
		)

		INSERT INTO #tmpDepartCollectionGroupwise
		SELECT 
					FS1.FeeId,
					ISNULL(FS1.Amount,0)AS Amount,
					FM.Title AS FeeName,
					FM.FeeHeadId,
					SA1.Id As AcademicId,
					FS1.Id,
					FS1.StartDate,
					FS1.CollectionGroupId
 				FROM sFee.tFeeSetup FS1
				INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
				INNER JOIN sStudent.tStudentMaster SM ON SA1.StudentId = SM.Id			 
				AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				WHERE 
					BM.OrgGroupBatchId = @rOrgGroupBatchId
					AND (FS1.IsOptional=0)
					-- IsInContext
					AND BM.IsInContext = 1
				UNION ALL
				SELECT 
					FS1.FeeId,
					ISNULL(FS1.Amount,0)AS Amount,
					FM.Title AS FeeName,
					FM.FeeHeadId,
					SA1.AcademicId As AcademicId,
					FS1.Id,
					FS1.StartDate,
					FS1.CollectionGroupId
				FROM sFee.tFeeSetup FS1
				INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId 
				AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.ClassId = FS1.ClassId
				INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				WHERE
						SA1.OrgGroupBatchId = @rOrgGroupBatchId
						AND (FS1.IsOptional=1)
						-- IsInContext
						AND BM.IsInContext = 1


		SELECT
			SA.DepartmentId,
		    SA.DepartmentName,
			SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00))AS PendingAmount,
			ISNULL(CGM.Id,0) AS CollectionGroupId,
			ISNULL(CGM.Title,'') AS CollectionGroupName,
			ISNULL(CGM.OrderIndex,0) AS OrderIndex
		FROM
			sStudent.vStudentAcademic SA
				INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
				INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id = SA.DepartmentId
				INNER JOIN #tmpDepartCollectionGroupwise FS ON FS.AcademicId=SA.AcademicId
				LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
				LEFT JOIN
				(
					SELECT 
					    ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
					FROM
						sFee.tReceipt R 
						INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
						INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
						INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
						INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=R.SourceId
						INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA1.BatchId			
					WHERE		
						(R.SourceTypeId = 2001)
						AND (R.IsObsolete = 0) 
						AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId))
						AND (R.OrgGroupBatchId = @rOrgGroupBatchId)
						AND (R.ReceiptDate <= @rUptoDate)  
						-- IsInContext
						AND BM.IsInContext = 1
						GROUP BY FeeSetupId,R.SourceId
				) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
				LEFT JOIN sFee.tCollectionGroupMaster CGM ON FS.CollectionGroupId=CGM.Id
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
			WHERE
			  SA.OrgGroupBatchId = @rOrgGroupBatchId
			  AND (SA.StatusId = @rStudentStatus OR @rStudentStatus=0)
			  AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			  -- IsInContext
			  AND BM.IsInContext = 1
			GROUP BY SA.DepartmentId,SA.DepartmentName,CGM.Id,CGM.Title,CGM.OrderIndex,DM.OrderIndex
			ORDER BY DM.OrderIndex,DepartmentId,CGM.Id
	 END
	END
ELSE IF(@rFilterType = 'ReceiptBookwise')
	BEGIN
	IF(@rFeeType = 'FeeHeadwise')
	BEGIN
		-- For Timeout issue
		CREATE TABLE #tmp
		(
		Amount decimal (12,2),
		FeeName nvarchar(100),
		FeeHeadId int,
		AcademicId bigint,
		Id int,
		StartDate date,
		ReceiptBookId int 
		)

		INSERT INTO #tmp
		SELECT 
			ISNULL(FS1.Amount,0)AS Amount,
			FM.Title AS FeeName,
			FM.FeeHeadId,
			SA1.Id As AcademicId,
			FS1.Id,
			FS1.StartDate,
			FS1.ReceiptBookId
 		FROM sFee.tFeeSetup FS1
		INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
		INNER JOIN sStudent.tStudentMaster SM ON SA1.StudentId = SM.Id			 
		AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
		INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
		WHERE 
			BM.OrgGroupBatchId = @rOrgGroupBatchId
			AND (FS1.IsOptional=0)
			-- IsInContext
			AND BM.IsInContext = 1
		UNION ALL
		SELECT 
			ISNULL(FS1.Amount,0)AS Amount,
			FM.Title AS FeeName,
			FM.FeeHeadId,
			SA1.AcademicId As AcademicId,
			FS1.Id,
			FS1.StartDate,
			FS1.ReceiptBookId
		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 = FS1.ClassId
		INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
		WHERE
				SA1.OrgGroupBatchId = @rOrgGroupBatchId
				AND (FS1.IsOptional=1)
				-- IsInContext
				AND BM.IsInContext = 1



	 SELECT
			FS.ReceiptBookId,
		    ISNULL(RBM.Title,'') AS ReceiptBookTitle,
			SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00))AS PendingAmount,
			FHM.Id AS FeeHeadId,
			FHM.Title AS FeeHeadName,
			FHM.OrderIndex
		FROM
			sStudent.tAcademic SA
			INNER JOIN [sStudent].[tStudentMaster] SM ON SA.StudentId = SM.Id 
			INNER JOIN [sSetup].[tBatchMaster] BM ON SA.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
			--INNER JOIN 
			--(
				--SELECT 
				--	ISNULL(FS1.Amount,0)AS Amount,
				--	FM.Title AS FeeName,
				--	FM.FeeHeadId,
				--	SA1.Id As AcademicId,
				--	FS1.Id,
				--	FS1.StartDate,
				--	FS1.ReceiptBookId
 			--	FROM sFee.tFeeSetup FS1
				--INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
				--INNER JOIN sStudent.tStudentMaster SM ON SA1.StudentId = SM.Id			 
				--AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				--INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				--INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				--WHERE 
				--	BM.OrgGroupBatchId = @rOrgGroupBatchId
				--	AND (FS1.IsOptional=0)
				--	-- IsInContext
				--	AND BM.IsInContext = 1
				--UNION ALL
				--SELECT 
				--	ISNULL(FS1.Amount,0)AS Amount,
				--	FM.Title AS FeeName,
				--	FM.FeeHeadId,
				--	SA1.AcademicId As AcademicId,
				--	FS1.Id,
				--	FS1.StartDate,
				--	FS1.ReceiptBookId
				--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 = FS1.ClassId
				--INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				--WHERE
				--		SA1.OrgGroupBatchId = @rOrgGroupBatchId
				--		AND (FS1.IsOptional=1)
				--		-- IsInContext
				--		AND BM.IsInContext = 1
				--) 
				INNER JOIN #tmp FS ON FS.AcademicId=SA.Id
				LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.Id
				LEFT JOIN
				(
					SELECT 
					    ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
					FROM
						sFee.tReceipt R 
						INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
						INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
						INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
						INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=R.SourceId
						INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA1.BatchId			
					WHERE		
						(R.SourceTypeId = 2001)
						AND (R.IsObsolete = 0) 
						AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId))
						AND (R.OrgGroupBatchId = @rOrgGroupBatchId)
						AND (R.ReceiptDate <= @rUptoDate)  
						-- IsInContext
						AND BM.IsInContext = 1
						GROUP BY FeeSetupId,R.SourceId
				) R ON R.FeeSetupId = FS.Id AND SA.Id = R.SourceId
				INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FS.FeeHeadId	
				INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
			WHERE
			  BM.OrgGroupBatchId = @rOrgGroupBatchId
			  AND (SM.StatusId = @rStudentStatus OR @rStudentStatus=0)
			  AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			  -- IsInContext
			  AND BM.IsInContext = 1
			GROUP BY FS.ReceiptBookId,RBM.Title,FHM.Id,FHM.Title,FHM.OrderIndex,RBM.OrderIndex
			ORDER BY RBM.OrderIndex,ReceiptBookId,FHM.Id

		DROP TABLE #tmp
	 END
	ELSE IF(@rFeeType = 'FeeMasterwise')
	BEGIN

		IF OBJECT_ID('tempdb..#tmpReceiptFeeMasterwise') IS NOT NULL DROP TABLE #tmpReceiptFeeMasterwise
		CREATE TABLE #tmpReceiptFeeMasterwise
		(
		FeeId int,
		Amount decimal (12,2),
		FeeName nvarchar(100),
		FeeHeadId int,
		AcademicId bigint,
		Id int,
		StartDate date,
		ReceiptBookId int,
		OrderIndex int
		)

		INSERT INTO  #tmpReceiptFeeMasterwise
		SELECT 
					FS1.FeeId,
					ISNULL(FS1.Amount,0)AS Amount,
					FM.Title AS FeeName,
					FM.FeeHeadId,
					SA1.Id As AcademicId,
					FS1.Id,
					FS1.StartDate,
					FS1.ReceiptBookId,
					FM.OrderIndex
 				FROM sFee.tFeeSetup FS1
				INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
				INNER JOIN sStudent.tStudentMaster SM ON SA1.StudentId = SM.Id			 
				AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				WHERE 
					BM.OrgGroupBatchId = @rOrgGroupBatchId
					AND (FS1.IsOptional=0)
					-- IsInContext
					AND BM.IsInContext = 1
				UNION ALL
				SELECT 
					FS1.FeeId,
					ISNULL(FS1.Amount,0)AS Amount,
					FM.Title AS FeeName,
					FM.FeeHeadId,
					SA1.AcademicId As AcademicId,
					FS1.Id,
					FS1.StartDate,
					FS1.ReceiptBookId,
					FM.OrderIndex
				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 = FS1.ClassId
				INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				WHERE
						SA1.OrgGroupBatchId = @rOrgGroupBatchId
						AND (FS1.IsOptional=1)
						-- IsInContext
						AND BM.IsInContext = 1

		SELECT
			FS.ReceiptBookId,
		    ISNULL(RBM.Title,'') AS ReceiptBookTitle,
			SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00))AS PendingAmount,
			FS.FeeId,
			FS.FeeName,
			FS.OrderIndex
		FROM
			sStudent.vStudentAcademic SA
				INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
				INNER JOIN #tmpReceiptFeeMasterwise FS ON FS.AcademicId=SA.AcademicId
				LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
				LEFT JOIN
				(
					SELECT 
					    ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
					FROM
						sFee.tReceipt R 
						INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
						INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
						INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
						INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=R.SourceId
						INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA1.BatchId			
					WHERE		
						(R.SourceTypeId = 2001)
						AND (R.IsObsolete = 0) 
						AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId))
						AND (R.OrgGroupBatchId = @rOrgGroupBatchId)
						AND (R.ReceiptDate <= @rUptoDate) 
						-- IsInContext
						AND BM.IsInContext = 1 
						GROUP BY FeeSetupId,R.SourceId
				) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
				INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FS.FeeHeadId	
				INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
				INNER JOIN sSetup.tBatchMaster BM ON SA.BatchId = BM.Id
			WHERE
			  SA.OrgGroupBatchId = @rOrgGroupBatchId
			  AND (SA.StatusId = @rStudentStatus OR @rStudentStatus=0)
			  AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			  -- IsInContext
			  AND BM.IsInContext = 1
			GROUP BY FS.ReceiptBookId,RBM.Title,FS.FeeId,FS.FeeName,FS.OrderIndex,RBM.OrderIndex
			ORDER BY RBM.OrderIndex,ReceiptBookId,FS.FeeId
	END
	ELSE IF(@rFeeType = 'CollectionGroupwise')
	BEGIN

		IF OBJECT_ID('tempdb..#tmpReceiptCollectionGroupwise') IS NOT NULL DROP TABLE #tmpReceiptCollectionGroupwise
		CREATE TABLE #tmpReceiptCollectionGroupwise
		(
		FeeId int,
		Amount decimal (12,2),
		FeeName nvarchar(100),
		FeeHeadId int,
		AcademicId bigint,
		Id int,
		StartDate date,
		CollectionGroupId int,
		ReceiptBookId int
		)

		INSERT INTO #tmpReceiptCollectionGroupwise
		SELECT 
					FS1.FeeId,
					ISNULL(FS1.Amount,0)AS Amount,
					FM.Title AS FeeName,
					FM.FeeHeadId,
					SA1.Id As AcademicId,
					FS1.Id,
					FS1.StartDate,
					FS1.CollectionGroupId,
					FS1.ReceiptBookId
 				FROM sFee.tFeeSetup FS1
				INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
				INNER JOIN sStudent.tStudentMaster SM ON SA1.StudentId = SM.Id			 
				AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				WHERE 
					BM.OrgGroupBatchId = @rOrgGroupBatchId
					AND (FS1.IsOptional=0)
					-- IsInContext
					AND BM.IsInContext = 1
				UNION ALL
				SELECT 
					FS1.FeeId,
					ISNULL(FS1.Amount,0)AS Amount,
					FM.Title AS FeeName,
					FM.FeeHeadId,
					SA1.AcademicId As AcademicId,
					FS1.Id,
					FS1.StartDate,
					FS1.CollectionGroupId,
					FS1.ReceiptBookId
				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 = FS1.ClassId
				INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				WHERE
						SA1.OrgGroupBatchId = @rOrgGroupBatchId
						AND (FS1.IsOptional=1)
						-- IsInContext
						AND BM.IsInContext = 1

		SELECT
			FS.ReceiptBookId,
		    ISNULL(RBM.Title,'') AS ReceiptBookTitle,
			SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00))AS PendingAmount,
			ISNULL(CGM.Id,0) AS CollectionGroupId,
			ISNULL(CGM.Title,'') AS CollectionGroupName,
			ISNULL(CGM.OrderIndex,0) AS OrderIndex
		FROM
			sStudent.vStudentAcademic SA
				INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
				INNER JOIN #tmpReceiptCollectionGroupwise FS ON FS.AcademicId=SA.AcademicId
				LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
				LEFT JOIN
				(
					SELECT 
					    ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
					FROM
						sFee.tReceipt R 
						INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
						INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
						INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
						INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=R.SourceId
						INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA1.BatchId			
					WHERE		
						(R.SourceTypeId = 2001)
						AND (R.IsObsolete = 0) 
						AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId))
						AND (R.OrgGroupBatchId = @rOrgGroupBatchId)
						AND (R.ReceiptDate <= @rUptoDate)  
						-- IsInContext
						AND BM.IsInContext = 1
						GROUP BY FeeSetupId,R.SourceId
				) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
				LEFT JOIN sFee.tCollectionGroupMaster CGM ON FS.CollectionGroupId=CGM.Id
				INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
				INNER JOIN sSetup.tBatchMaster BM ON SA.BatchId = BM.Id
			WHERE
			  SA.OrgGroupBatchId = @rOrgGroupBatchId
			  AND (SA.StatusId = @rStudentStatus OR @rStudentStatus=0)
			  AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			  -- IsInContext
			  AND BM.IsInContext = 1
			GROUP BY FS.ReceiptBookId,RBM.Title,CGM.Id,CGM.Title,CGM.OrderIndex,RBM.OrderIndex
			--ORDER BY ReceiptBookId,CGM.Id
			ORDER BY RBM.OrderIndex,CGM.OrderIndex
	END
	END 
  END
ELSE IF(@rType = 2)
		BEGIN

			IF OBJECT_ID('tempdb..#tmptbl') IS NOT NULL DROP TABLE #tmptbl
			CREATE TABLE #tmptbl
			(
				FeeId int,
				Id int,
				IsOptional bit,
				IsVariable bit,
				Amount decimal (12,2),
				StartDate date,
				EndDate date,
				BatchId int,
				ReceiptBookId int,
				AcademicId bigint,
				FeeName nvarchar(100),
				FeeHeadId int,
				CollectionGroupId int,
				FeeOrderIndex int
			)
			INSERT INTO #tmptbl 
			SELECT 
							FS1.FeeId,
							FS1.Id,
							ISNULL(FS1.IsOptional,0)AS IsOptional,
							ISNULL(FS1.IsVariable,0)AS IsVariable,
							ISNULL(FS1.Amount,0)AS Amount,
							ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
							ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
							FS1.BatchId,
							ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
							SA1.Id AS AcademicId,
							FM.Title AS FeeName,
							FM.FeeHeadId,
							FS1.CollectionGroupId,
							FM.OrderIndex AS FeeOrderIndex			 
						FROM sFee.tFeeSetup FS1
						INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
						INNER JOIN sStudent.tStudentMaster SM ON SA1.StudentId = SM.Id			 
						AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
						INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
						INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
						WHERE 
							BM.OrgGroupBatchId = @rOrgGroupBatchId
							AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
							AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
							AND (FS1.IsOptional=0)
							-- IsInContext
							AND BM.IsInContext = 1
						UNION ALL
				
						SELECT 
							FS1.FeeId,
							FS1.Id,
							ISNULL(FS1.IsOptional,0)AS IsOptional,
							ISNULL(FS1.IsVariable,0)AS IsVariable,
							ISNULL(FS1.Amount,0)AS Amount,
							ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
							ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
							FS1.BatchId,
							ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
							SA1.AcademicId,
							FM.Title AS FeeName,
							FM.FeeHeadId,
							FS1.CollectionGroupId,
							FM.OrderIndex AS FeeOrderIndex			 			 
						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.AdmissionCategoryId = FS1.AdmissionCategoryId
						INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
						WHERE
							SA1.OrgGroupBatchId = @rOrgGroupBatchId
							AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
							AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
							AND (FS1.IsOptional=1)
							-- IsInContext
							AND BM.IsInContext = 1
	
				SELECT 
					SA.OrgId,
					SA.OrganizationName as OrgName,
					SA.ClassId,
					SA.ClassName,
					SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00))AS PendingAmount
				FROM 
					sStudent.vStudentAcademic SA
					INNER JOIN #tmptbl  FS ON FS.AcademicId=SA.AcademicId
					LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
					LEFT JOIN
					(
						SELECT 
								ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
						FROM
							sFee.tReceipt R 
							INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
							INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
							INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
							INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=R.SourceId
							INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA1.BatchId			
							 
						WHERE		
							(R.SourceTypeId = 2001)
							AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
							AND (R.IsObsolete = 0) 
							AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId))
							AND (R.OrgGroupBatchId = @rOrgGroupBatchId)
							AND (R.ReceiptDate <= @rUptoDate) -- added condition after nes issue on 09/08/2016
							-- IsInContext
							AND BM.IsInContext = 1
							GROUP BY FeeSetupId,R.SourceId
					) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
					 INNER JOIN sSetup.tOrganizationMaster O ON	
					 SA.OrgId = O.Id
					 INNER JOIN sFee.tReceiptBookMaster RBM 
						ON FS.ReceiptBookId=RBM.Id
					 LEFT JOIN sFee.tCollectionGroupMaster CGM
						ON FS.CollectionGroupId=CGM.Id	
					 LEFT JOIN sStudent.tStudentCommunication SC 
						ON SC.StudentId = SA.StudentId
					 LEFT JOIN sStudent.tStudentOther SO 
						ON SO.StudentId = SA.StudentId
					 INNER JOIN sFee.tFeeHeadMaster FHM
						ON FHM.Id = FS.FeeHeadId
					INNER JOIN sSetup.tBatchMaster BM ON SA.BatchId = BM.Id	
				  LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
				  LEFT JOIN
					(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
					INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
					INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
					ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  
				WHERE	
				 SA.OrgGroupBatchId = @rOrgGroupBatchId
                 AND (SA.StatusId = @rStudentStatus OR @rStudentStatus=0)
                 AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
				 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)			
				 -- IsInContext
				 AND BM.IsInContext = 1
				GROUP BY 
						SA.ClassId,SA.ClassName,SA.OrgId,SA.OrganizationName
				Order By
						SA.ClassId
		END
END
GO
PRINT N'Altering Procedure [sHrm].[pEmployeeReplacementGet]...';


GO
ALTER PROCEDURE [sHrm].[pEmployeeReplacementGet]
	 
        @rEmployeeId bigint
	

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	Declare @lTeacherSubjectId bigint = 0 , @lTeacherDivisionId bigint = 0
	IF OBJECT_ID('tempdb..#tmpTable') IS NOT NULL DROP TABLE #tmpTable
	CREATE Table #tmpTable 
	(
		Id bigint IDENTITY,
		Title nvarchar(50)
	)

	IF EXISTS(select top 1 1 from sTimetable.tAssignTeacher where EmployeeId = @rEmployeeId)
	BEGIN
		Insert INTO #tmpTable Values
		(
			'Assign Teacher'
		)
	END


	set @lTeacherSubjectId = (select top 1 1 from sAcademic.tTeacherSubject where EmployeeId = @rEmployeeId)
	SET @lTeacherDivisionId = (select top 1 1 from sAcademic.tTeacherSubjectDivision where EmployeeId = @rEmployeeId)
	IF ((@lTeacherSubjectId = 1) OR (@lTeacherDivisionId = 1))
	BEGIN
		Insert INTO #tmpTable Values
		(
			'Teacher Subject Division'
		)
	END

	IF EXISTS (select top 1 1 from sTimetable.tTimeTable where EmployeeId = @rEmployeeId)
	BEGIN
		Insert INTO #tmpTable Values
		(
			'Time Table'
		)
	END
		
	declare @lUserId bigint= (select top 1 Id from sSecurity.tUser where SourceId = @rEmployeeId AND SourceTypeId = 95)
	declare @lUserOrganizationId int ,@lUserAccessId int
	SET @lUserOrganizationId = (SELECT Top 1 1 FROM sSecurity.tUserOrganization WHERE UserId=@lUserId)
	SET @lUserAccessId= (SELECT top 1 1 FROM sSecurity.tUserAccess WHERE UserId=@lUserId)
	IF ((@lUserOrganizationId = 1) OR (@lUserAccessId = 1))
	BEGIN
		Insert INTO #tmpTable Values
		(
			'User Access'
		)
	END

	IF EXISTS (select top 1 1 from sSetup.tDivisionMaster where InchargeEmployeeId = @rEmployeeId)
	BEGIN
		Insert INTO #tmpTable Values
		(
			'Class Teacher'
		)
	END	

	--IF EXISTS (select top 1 1 from sAcademic.tLessonPlan where EmployeeId = @rEmployeeId)
	--BEGIN
	--	Insert INTO #tmpTable Values
	--	(
	--		'Lesson Plan'
	--	)
	--END

	select * from #tmpTable --order by Title

	Drop Table #tmpTable
END
GO
PRINT N'Altering Procedure [sHrm].[pImportEmployees_Update_Dynamicly]...';


GO
ALTER proc [sHrm].[pImportEmployees_Update_Dynamicly] 
@rOrgId int,
@rCreatedUserId bigint,
@rCode varchar(200) = '',
@rShortName varchar(200) = '',
@rFirstName varchar(200) = '',
@rMiddleName varchar(200) = '',
@rLastName varchar(200) = '',
@rGender varchar(50) = '',
@rEmpType varchar(100) = '',
@rEmpGroup varchar(100) = '',
@rEmpGrade varchar(100) = '',
@rDepartment varchar(150) = '',
@rDesignation varchar(150) = '',
@rQualification varchar(150) = '',
@rDOB datetime = '',
@rDateOfJoining datetime = '',
@rReligion varchar(150) = '',
@rCompayPhoneNo varchar(15) = '',
@rExtensionNo varchar(15)='',
@rCompayMailId varchar(100)='',
@rPersonalEmailid varchar(100)='',
@rMobileNo varchar(50)='',
@rPresentStreetOne varchar(200)='',
@rPresentStreetTwo varchar(200)='',
@rPresentStreetThree varchar(200)='',
@rPresentCity varchar(100)='',
@rPresentZipCode varchar(15)='',
@rPresentState varchar(100)='',
@rPresentCountry varchar(100)='',
@rPresentContactNo varchar(50)='',
@rCastCategory varchar(50)='',
@rFamilyCast varchar(100)='',
@rAccountNumber varchar(100)='',
@rBankName varchar(100)='',
@rBranch varchar(100)=0,
@rEPFNumber varchar(100)=0,
@rPanNumber  varchar(100)='',
@rAdhaarNumber varchar(100)='',
@rValidate varchar(250)='' ,
@rOrgGroupId int,
@rIdentificationMark1  varchar(200)='',
@rUIDNumber varchar(50)='',
@rDateOfLeaving datetime = '',
@rReason varchar(200)='',
@rBloodGroup varchar(50)='',
@rNumber Bigint,
@rProbationUptoDate date = '',
@rAhdocUptoDate date = '',
@rPermanentDate date = '',
@rDateOfResignation date = '',
@rWhatsAppContactNo nvarchar(20) = ''

as
begin	

	IF(@rDateOfLeaving='') 
	SET @rDateOfLeaving = NULL
	IF(@rDOB='') 
	SET @rDOB = NULL
	IF(@rDateOfJoining='') 
	SET @rDateOfJoining = NULL
	IF(@rProbationUptoDate='')
	SET @rProbationUptoDate = NULL
	IF(@rAhdocUptoDate='')
	SET @rAhdocUptoDate = NULL
	IF(@rPermanentDate='')
	SET @rPermanentDate = NULL
	IF(@rDateOfResignation='')
	SET @rDateOfResignation = NULL
	
	declare @EmpId bigint = 0
	select @EmpId = Id from sHrm.tEmployeeMaster where Code = @rCode and OrgID = @rOrgId AND ISNULL(IsOtherUser,0) = 0
	select @EmpId = isnull(@EmpId,0)
	
	declare @genderid int,@emptypeid int,@cmpanyid int,@departmenttid int,@designationid int, 
	 @employeegradeid int,@empgroupid int,@religionId int,@castcatagoryId int,@bloodgroupid int
	 
	
	select @rGender = case when upper(@rGender) = 'M' then 'Male'
	when  upper(@rGender) = 'MALE' then 'Male'
	when upper(@rGender) ='FEMALE' then 'Female'
	when upper(@rGender) = 'F' then 'Female' when upper(@rGender) = 'N' then 'Not Known' else 'Not Known' end
	 
	select @genderid = isnull(Id,0) from sCommon.tGenderMaster where Title = @rGender
	
	select @emptypeid = isnull(Id,0) from sHrm.tEmployeeTypeMaster where Title = @rEmpType and OrgId = @rOrgId
 
	select @empgroupid = isnull(Id,0) from sHrm.tEmployeeGroupMaster where Title = @rEmpGroup
	
	select @employeegradeid = isnull(Id,0) from sHrm.tEmployeeGradeMaster where Title = @rEmpGrade and OrgId = @rOrgId
	 
	 select @departmenttid = isnull(Id,0) from sSetup.tDepartmentMaster where Title = @rDepartment and OrgId = @rOrgId
	 
	  select @bloodgroupid = isnull(Id,0) from sCommon.tBloodGroupMaster where Title = @rBloodGroup 
	
	if (isnull(@rDesignation,'') <> '')
	select @designationid =  isnull(Id,0) from sHrm.tEmployeeDesignationMaster where Title = @rDesignation and OrgId = @rOrgId
	else
	select @designationid = 0
	
	 if (isnull(@rReligion,'') <> '')
			select @religionId =  isnull(Id,0) from sCommon.tReligionMaster where Title = @rReligion and OrgGroupId = @rOrgGroupId
	else
			select @religionId = 0
	
	 if (isnull(@rCastCategory,'') <> '')
	 select @castcatagoryId =  isnull(Id,0) from sCommon.tCastCategoryMaster where Title = @rCastCategory and OrgGroupId = @rOrgGroupId
	 else
	select @castcatagoryId = 0
			
	select @genderid = isnull(@genderid,0),@emptypeid = isnull(@emptypeid,0),@empgroupid = isnull(@empgroupid,0),
	@employeegradeid = isnull(@employeegradeid,0),@departmenttid = isnull(@departmenttid,0),@designationid = isnull(@designationid,0),
	@religionId = isnull(@religionId,0),@castcatagoryId = isnull(@castcatagoryId,0) 
	
	declare @lNextNumber bigint,@Title varchar(100)=''
	
	if @rEmpGroup = ''
	begin
		
		if exists (select 1 from sHrm.tEmployeeGroupMaster where  Title = @Title)
		begin
			select @empgroupid = Id from sHrm.tEmployeeGroupMaster where Title = @Title
		end
		
	end
	
	 
	
	if @rEmpType = ''
	begin		
		
		if exists (select 1 from sHrm.tEmployeeTypeMaster where OrgId = @rOrgId and Title = @Title)
		begin
			select @emptypeid = Id from sHrm.tEmployeeTypeMaster where OrgId = @rOrgId and Title = @Title
		end
	end
	
	 
	if @rEmpGrade = ''
	begin
		 
		if exists(select 1 from sHrm.tEmployeeGradeMaster where OrgId = @rOrgId and Title = @Title)
		begin
			select @employeegradeid = Id from sHrm.tEmployeeGradeMaster where OrgId = @rOrgId and Title = @Title
		end
	end
	
	
	if @rDepartment = ''
	begin		
		 
		if exists (select * from sSetup.tDepartmentMaster  where Title = @Title and OrgId = @rOrgId)
		begin
			select @departmenttid = Id from sSetup.tDepartmentMaster  where Title = @Title and OrgId = @rOrgId
		end
	end
		

	if @rDesignation = ''
	begin
		select @Title = Title from sHrm.tEmployeeDesignationMaster where Id = 1
		if exists (select * from sHrm.tEmployeeDesignationMaster where Title = @Title and OrgId = @rOrgId)
		begin
			select @designationid = Id from sHrm.tEmployeeDesignationMaster where Title = @Title and OrgId = @rOrgId			
		end
	end
	 
	 if @rCastCategory = ''
	begin
		
		if exists (select 1 from sCommon.tCastCategoryMaster where  Title = @Title and OrgGroupId=@rOrgGroupId)
		begin
			select @castcatagoryId = Id from sCommon.tCastCategoryMaster where Title = @Title and OrgGroupId=@rOrgGroupId
		end
		
	end
	
	 
	 if @rReligion = ''
	begin
		
		if exists (select 1 from sCommon.tReligionMaster where  Title = @Title and OrgGroupId=@rOrgGroupId)
		begin
			select @religionId = Id from sCommon.tReligionMaster where Title = @Title and OrgGroupId=@rOrgGroupId
		end
		
	end
	
	if @rShortName <> ''
	select @rShortName = [sSetup].[fPortalXMLTagsReplaceReverse](@rShortName)
	if @rFirstName <> ''
	select @rFirstName = [sSetup].[fPortalXMLTagsReplaceReverse](@rFirstName)
	if @rMiddleName <> ''
	select @rMiddleName = [sSetup].[fPortalXMLTagsReplaceReverse](@rMiddleName)
	if @rLastName <> ''
	select @rLastName = [sSetup].[fPortalXMLTagsReplaceReverse](@rLastName)
	if @rCompayPhoneNo <> ''
	select @rCompayPhoneNo = [sSetup].[fPortalXMLTagsReplaceReverse](@rCompayPhoneNo)
	if @rExtensionNo <> ''
	select @rExtensionNo = [sSetup].[fPortalXMLTagsReplaceReverse](@rExtensionNo)
	if @rCompayMailId <> ''
	select @rCompayMailId = [sSetup].[fPortalXMLTagsReplaceReverse](@rCompayMailId)
	if @rPersonalEmailid <> ''
	select @rPersonalEmailid = [sSetup].[fPortalXMLTagsReplaceReverse](@rPersonalEmailid)
	if @rMobileNo <> ''
	select @rMobileNo = [sSetup].[fPortalXMLTagsReplaceReverse](@rMobileNo)
	if @rPresentStreetOne <> ''
	select @rPresentStreetOne = [sSetup].[fPortalXMLTagsReplaceReverse](@rPresentStreetOne)
	if @rPresentStreetTwo <> ''
	select @rPresentStreetTwo = [sSetup].[fPortalXMLTagsReplaceReverse](@rPresentStreetTwo)
	if @rPresentStreetThree <> ''
	select @rPresentStreetThree = [sSetup].[fPortalXMLTagsReplaceReverse](@rPresentStreetThree)
	if @rPresentCity <> ''
	select @rPresentCity = [sSetup].[fPortalXMLTagsReplaceReverse](@rPresentCity)
	if @rPresentZipCode <> ''
	select @rPresentZipCode = [sSetup].[fPortalXMLTagsReplaceReverse](@rPresentZipCode)
	if @rPresentState <> ''
	select @rPresentState = [sSetup].[fPortalXMLTagsReplaceReverse](@rPresentState)
	if @rPresentCountry <> ''
	select @rPresentCountry = [sSetup].[fPortalXMLTagsReplaceReverse](@rPresentCountry)
	if @rPresentContactNo <> ''
	select @rPresentContactNo = [sSetup].[fPortalXMLTagsReplaceReverse](@rPresentContactNo)
	if @rFamilyCast <> ''
	select @rFamilyCast = [sSetup].[fPortalXMLTagsReplaceReverse](@rFamilyCast)
	if @rAccountNumber <> ''
	select @rAccountNumber = [sSetup].[fPortalXMLTagsReplaceReverse](@rAccountNumber)
	if @rBankName <> ''
	select @rBankName = [sSetup].[fPortalXMLTagsReplaceReverse](@rBankName)
	if @rBranch <> ''
	select @rBranch = [sSetup].[fPortalXMLTagsReplaceReverse](@rBranch)
	if @rEPFNumber<> ''
	select @rEPFNumber = [sSetup].[fPortalXMLTagsReplaceReverse](@rEPFNumber)
	if @rPanNumber <> ''
	select @rPanNumber = [sSetup].[fPortalXMLTagsReplaceReverse](@rPanNumber)
	if @rAdhaarNumber <> ''
	select @rAdhaarNumber = [sSetup].[fPortalXMLTagsReplaceReverse](@rAdhaarNumber)
	if @rWhatsAppContactNo <> ''
	select @rWhatsAppContactNo = [sSetup].[fPortalXMLTagsReplaceReverse](@rWhatsAppContactNo)
	  
	 
	begin

		UPDATE sHrm.tEmployeeMaster 
		SET 
		ShortName = case when isnull(@rShortName,'') <> '' then @rShortName else ShortName end
		,FirstName = case when isnull(@rFirstName,'') <> '' then @rFirstName else FirstName end
		,MiddleName   = case when isnull(@rMiddleName,'') <> '' then @rMiddleName else MiddleName end
		,LastName     = case when isnull(@rLastName,'') <> '' then @rLastName else LastName end
		--,StatusId     = case when isnull(@statusid,0) <> 0 then @statusid else StatusId end
		,IsObsolete   = case when isnull(IsObsolete,'') <> '' then IsObsolete else IsObsolete end
		,UpdatedUserId = @rCreatedUserId
		,UpdatedDateTime = sCommon.fGetDate()
		,Number = @rNumber
		WHERE Id = @EmpId and OrgId = @rOrgId AND ISNULL(IsOtherUser,0) = 0

		  
		UPDATE sHrm.tEmployeeJobDetail
		SET 
			EmployeeDesignationId = case when isnull(@designationid,0) <> 0 then @designationid else EmployeeDesignationId end,	 
			OrganizationDepartmentId = case when isnull(@departmenttid,0) <> 0 then @departmenttid else OrganizationDepartmentId end,
			DateOfJoining =	case when isnull(@rDateOfJoining,'') <> '' then @rDateOfJoining else DateOfJoining end,
			UpdatedUserId = @rCreatedUserId,
			UpdatedDateTime = sCommon.fGetDate(),
			EmployeeTypeId = case when isnull(@emptypeid,0) <> 0 then @emptypeid else EmployeeTypeId end,
			EmployeeGroupId = case when isnull(@empgroupid,0) <> 0 then @empgroupid else EmployeeGroupid end,
			EmployeeGradeId = case when isnull(@employeegradeid,0) <> 0 then @employeegradeid else EmployeeGradeId  end ,
			DateOfleaving =  case when isnull(@rDateOfLeaving,'') <> '' then @rDateOfLeaving else DateOfleaving end,
			ReasonOfleaving = case when isnull(@rReason,'') <> '' then @rReason else ReasonOfleaving end,
			ProbationUptoDate = @rProbationUptoDate,
			AhdocUptoDate = @rAhdocUptoDate,
			PermanentDate = @rPermanentDate,
			DateOfResignation = @rDateOfResignation
			  
	  WHERE EmployeeId = @EmpId and OrgId = @rOrgId
	  
		Update sHrm.tEmployeePersonalDetail 
		set  
		GenderId = case when isnull(@genderid,0) <> 0 then @genderid else GenderId  end,
		ReligionId =  case when isnull(@religionId,0) <> 0 then @religionId else ReligionId  end,
		Qualification =  case when isnull(@rQualification,'') <> '' then @rQualification else Qualification  end,
		BloodGroupId =  case when isnull(@bloodgroupid,0) <> 0 then @bloodgroupid else BloodGroupId  end,
		DateOfBirth =  case when isnull(@rDOB,0) <> 0 then @rDOB else DateOfBirth  end,
		IdentificationMark1 =  case when isnull(@rIdentificationMark1,0) <> 0 then @rIdentificationMark1 else IdentificationMark1  end,
		UIDNumber =  case when isnull(@rUIDNumber,0) <> 0 then @rUIDNumber else UIDNumber  end,
		UpdatedUserId = @rCreatedUserId,
		UpdatedDateTime = sCommon.fGetDate(),
		FamilyCast =case when isnull(@rFamilyCast,'') <> '' then @rFamilyCast else FamilyCast  end,
		AdhaarNumber =case when isnull(@rAdhaarNumber,'') <> '' then @rAdhaarNumber else AdhaarNumber  end,
		CastCategoryId =case when isnull(@castcatagoryId,0) <> 0 then @castcatagoryId else FamilyCast  end
		where EmployeeId = @EmpId and OrgId = @rOrgId
		
  		UPDATE [sHrm].[tEmployeeCommunications]
		SET 
	      
		   [PresentStreetOne] = case when isnull(@rPresentStreetOne,'') <> '' then @rPresentStreetOne else [PresentStreetOne] end 
		  ,[PresentStreetTwo] =  case when isnull(@rPresentStreetTwo,'') <> '' then @rPresentStreetTwo else [PresentStreetTwo] end 
		  ,[PresentStreetThree] = case when isnull(@rPresentStreetThree,'') <> '' then @rPresentStreetThree else [PresentStreetThree] end 
		  ,[PresentCountry] = case when isnull(@rPresentCountry,'') <> '' then @rPresentCountry else [PresentCountry] end 
		  ,[PresentState] =  case when isnull(@rPresentState,'') <> '' then @rPresentState else [PresentState] end 
		  ,[PresentCity] =  case when isnull(@rPresentCity,'') <> '' then @rPresentCity else [PresentCity] end 
		  ,[EmergencyContactNo] = case when isnull(@rMobileNo,'') <> '' then @rMobileNo else [EmergencyContactNo] end 
		  ,[PhoneNoCompany] = case when isnull(@rCompayPhoneNo,'') <> '' then @rCompayPhoneNo else [PhoneNoCompany] end 
		  ,[ExtensionNo] = case when isnull(@rExtensionNo,'') <> '' then @rExtensionNo else [ExtensionNo] end  
		  ,[CompanyEmail] =  case when isnull(@rCompayMailId,'') <> '' then @rCompayMailId else [CompanyEmail]  end   
		  ,[PersonalEmail] =  case when isnull(@rPersonalEmailid,'') <> '' then @rPersonalEmailid else [PersonalEmail]  end   
		  ,[MobileNumber] =  case when isnull(@rMobileNo,'') <> '' then @rMobileNo else [MobileNumber]  end      
		  ,[UpdatedUserId] = @rCreatedUserId
		  ,[UpdatedDateTime] =  sCommon.fGetDate() 
		  ,[WhatsAppContactNo] =  case when isnull(@rWhatsAppContactNo,'') <> '' then @rWhatsAppContactNo else [WhatsAppContactNo]  end    
		WHERE EmployeeId = @EmpId
			
	end	
end
GO
PRINT N'Altering Procedure [sLibrary].[pBookListGet]...';


GO
ALTER PROCEDURE [sLibrary].[pBookListGet]
	
	 @rName nvarchar(500),
	 @rResourceTypeId int,
	 @rStatusId smallint,
	 @rLibraryId int
	 	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
--DECLARE @lpaging
BEGIN 


	  --BEGIN
			--SET @rCode = sCommon.fSearchStringGet(@rCode)
			SET @rName = sCommon.fSearchStringGet(@rName)
					
	  --END
	 declare @quer varchar(max)=''
	declare @lOrgId int,@lName nvarchar(200),@lResourceTypeId int,@lStatusId smallint,@lLibraryId int

	
	select 
	@lName = isnull(@rName,''),
	@lResourceTypeId = isnull(@rResourceTypeId,0),@lStatusId = isnull(@rStatusId,0),@lLibraryId = isnull(@rLibraryId,0)

	 
	SELECT @quer='SELECT BM.Code,
	BM.Title,
	ISNULL(BM.Publisher,'''')AS Publisher,
	ISNULL(BM.Supplier,'''')AS Supplier,
	ISNULL(BM.Author,'''')AS Author,
	ISNULL(BM.BookSubject,'''') AS BookSubject,
	ISNULL(BM.BookLanguage,'''') AS BookLanguage,
	ISNULL(BM.Location,'''') AS Location,
	ISNULL(BM.Edition,'''')AS Edition,
	ISNULL(BM.ISBNNumber,'''') AS ISBNNumber,
	ISNULL(BM.Price,0) AS Price,
	ISNULL(BM.Currency,'''') AS Currency,
	ISNULL(BM.BookTag,'''')AS BookTag,
	ISNULL(BM.BookCustomTag,'''') AS BookCustomTag,
	ISNULL(BM.BookDepartment,'''') AS BookDepartment,
	ISNULL(BM.ClassNumber,'''') AS ClassNumber,
	ISNULL(BM.BookVolume,1) AS BookVolume,
	ISNULL(BM.NoOfCopies,1) AS NoOfCopies,
	SM.Title AS StatusName,
	BM.Id,
	ISNULL(AGM.Id,0)AS BookAgeGroupId,
	ISNULL(RTM.Id,0) AS ResourceTypeId,
	BM.CreatedUserId,
	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,
    ISNULL(BM.BookGroup1Id,0) AS BookGroup1Id,
    ISNULL(BM.BookGroup2Id,0) AS BookGroup2Id,
	ISNULL(BL.ReaderSourceId,0)AS ReaderSourceId
 
	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.Publisher like ''' + @lName + ''') OR (''' + @lName + ''' = '''')
	 OR (BM.Title like ''' + @lName + ''') OR (''' + @lName + ''' = '''')
	 OR (BM.Code like ''' + @lName + ''') OR (''' + @lName + ''' = '''')
	 OR (BM.Author like ''' + @lName + ''') OR (''' + @lName + ''' = '''') 
	 OR (BM.BookSubject like ''' + @lName + ''') OR (''' + @lName + ''' = ''''))
	AND ((BM.ResourceTypeId = ' + convert(varchar,@lResourceTypeId) + ') OR (' + convert(varchar,@lResourceTypeId) + ' = 0))
	AND ((BL.StatusId = ' + convert(varchar,@lStatusId) + ') OR (' + convert(varchar,@lStatusId) + '=0))
	AND BM.LibraryId = ' + convert(varchar,@lLibraryId)
	
	print(@quer);
	exec (@quer)

END
GO
PRINT N'Altering Procedure [sProcurement].[pRptStockAdjustmentRegisterGet]...';


GO
 
ALTER PROCEDURE [sProcurement].[pRptStockAdjustmentRegisterGet]
  @rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='',
	@rReportId int,
	@rStoreLocationId int,
	@rMainGroupId int,
	@rSubGroupId int,
	@rStockItemCategoryId int,
	@rItemCode nvarchar(100),
	@rItemName nvarchar(100),
	@rOrgGroupId int,
	@rFromDate date = '',
	@rToDate date = '',
	@rDetail bit =0
	
WITH EXECUTE AS CALLER
AS
BEGIN
   SELECT  
				SIM.Code AS ItemCode,
				SIM.Title AS ItemName,		
				SI.Number AS Billno, 	
				SI.CreatedDateTime AS IssuedDate,
				ID.SystemQuantity,
				ID.PhysicalQuantity,
				 
				SB.ExpiryDate,
				--SB.Price AS Amount,
				SB.Number As BatchNumber,
				SI.Id,
				@rDetail AS Detail,
				@rBuilder1 As Builder1,
				@rBuilder2 AS Builder2,
				SIM.IsObsolete
				
		FROM  sProcurement.tStockAdjustment SI		
		INNER JOIN sProcurement.tStockAdjustmentDetail ID ON SI.Id = ID.StockAdjustmentId 
		INNER JOIN sIp.tStockItemMaster SIM ON ID.StockItemId  = SIM.Id 
	    LEFT JOIN sProcurement.tStockBatch SB ON SB.Id = ID.StockBatchId
	    
	    INNER JOIN sIp.tItemSubGroupMaster ISGM ON ISGM.Id=SIM.ItemSubGroupId
		INNER JOIN sIp.tItemMainGroupMaster IMGM ON IMGM.Id=ISGM.ItemMainGroupId
		LEFT JOIN sIp.tStockItemCategoryMaster SICM ON SICM.Id=SIM.StockItemCategoryId	
		 
		  WHERE	     
	     --SIM.IsObsolete=0
		  (SB.StoreLocationId= @rStoreLocationId)
		AND (IMGM.Id = @rMainGroupId OR @rMainGroupId=0)
		AND (ISGM.Id = @rSubGroupId OR @rSubGroupId=0)
		AND (SICM.Id = @rStockItemCategoryId OR @rStockItemCategoryId = 0)
		AND (SIM.Code = @rItemCode OR @rItemCode = '')
		AND (SIM.Title = @rItemName OR @rItemName = '')
		AND ((CAST(SI.CreatedDateTime AS DATE) >= CAST(@rFromDate AS DATE)) OR (ISNULL(@rFromDate,'') = '')) 
		AND ((CAST(SI.CreatedDateTime AS DATE) <= CAST(@rToDate AS DATE)) OR (ISNULL(@rToDate,'') = '') )
		AND (SB.OrgGroupId = @rOrgGroupId)
		 
    Order  by SIM.Title	
END
GO
PRINT N'Altering Procedure [sSecurity].[pMenuGet]...';


GO
 
 -- exec [sSecurity].[pMenuGet] 9911000000003
ALTER PROCEDURE [sSecurity].[pMenuGet]
	@rUserId [bigint],
	@rMenuId int = 0,
	@rResourceTypeId int= 0 
 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN


IF EXISTS(SELECT 1 FROM sSecurity.tPermissionUser WHERE UserId = @rUserId)
BEGIN

	SELECT
		MenuID,
		ModuleId,
		ParentMenuID,
		MenuTitle,	 
		ScreenTitle,		 
		PageURL,
		ScreenId,
		Permission,
		OrderNumber,	 
		TaskId,		
	    PageURL  AS PagePath,
	    IconPath
	   
	FROM
   (SELECT Menu.Id AS MenuID, 
		ISNULL(Menu.ParentMenuID, 0) AS ParentMenuID, 
		Menu.Title AS MenuTitle,		 
		ISNULL(Screen.Title, '') AS ScreenTitle,			 
		ISNULL(Screen.Page, '') AS PageURL,
		ISNULL(Screen.ScreenGroupId,0) AS ScreenGroupId,
		ISNULL(Menu.ScreenId, 0) AS ScreenId,
		ISNULL(PermissionValue, 0) AS Permission,
		ISNULL(OrderNumber, 0) AS OrderNumber,
		ISNULL(Screen.TaskId,0) AS TaskId,
		ISNULL(Screen.IconPath,'') As IconPath, 
		ISNULL(T.ResourceTypeId,0) AS ResourceTypeId,
		ISNULL(T.ModuleId,0) AS ModuleId
	  
		 
	FROM sSecurity.tMenu Menu	
	LEFT OUTER JOIN sSecurity.tScreen Screen
		ON Menu.ScreenId = Screen.Id		
	LEFT OUTER JOIN ( 
					SELECT 
						TaskId, 
						SUM(Permission & 2) PermissionValue			   
					FROM 
						sSecurity.tPermissionUser P
						INNER JOIN sSecurity.tTask T ON T.Id = P.TaskId
						--INNER JOIN sSecuirty.tOrganizationTask OT ON OT.TaskId = T.Id AND OT.OrgGroupId = P.OrgGroupId 
						INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId = T.ModuleId AND MP.OrgGroupId = P.OrgGroupId
					WHERE
						T.IsObsolete = 0 AND P.UserId = @rUserId
					GROUP BY 
						TaskId) TBL2
					ON 
						Screen.TaskId = TBL2.TaskId 
						 LEFT OUTER JOIN sSecurity.tTask  T ON T.Id =  Screen.TaskId AND ResourceTypeId = @rResourceTypeId
						
					WHERE 
					(Menu.IsObsolete = 0)  --For ScreenGroupId Master Page
					AND	ISNULL(Screen.IsObsolete, 0) = 0) 
				    MenuTable  
					--INNER JOIN sSecurity.tTask  T ON T.Id =  MenuTable.TaskId 
	WHERE 
		MenuTable.ScreenId = 0 OR MenuTable.Permission >= 2	
		AND 
		((MenuTable.ResourceTypeId = @rResourceTypeId) OR (@rResourceTypeId = 0))
		AND ((MenuTable.MenuID = @rMenuID)OR(@rMenuID = 0))
	 		
	ORDER BY 
		ParentMenuID
END
ELSE 
BEGIN
	SELECT
		MenuID,
		ModuleId,
		ParentMenuID,
		MenuTitle,	 
		ScreenTitle,		 
		PageURL,
		ScreenId,
		Permission,
		OrderNumber,	 
		TaskId,		
	  PageURL  AS PagePath,
	  IconPath
	   
	FROM
   (SELECT Menu.Id AS MenuID, 
		ISNULL(Menu.ParentMenuID, 0) AS ParentMenuID, 
		Menu.Title AS MenuTitle,		 
		ISNULL(Screen.Title, '') AS ScreenTitle,			 
		ISNULL(Screen.Page, '') AS PageURL,
		ISNULL(Screen.ScreenGroupId,0) AS ScreenGroupId,
		ISNULL(Menu.ScreenId, 0) AS ScreenId,
		ISNULL(PermissionValue, 0) AS Permission,
		ISNULL(OrderNumber, 0) AS OrderNumber,
		ISNULL(Screen.TaskId,0) AS TaskId,
		ISNULL(Screen.IconPath,'') As IconPath, 
		ISNULL(T.ResourceTypeId,0) AS ResourceTypeId,
		ISNULL(T.ModuleId,0) AS ModuleId
	  
		 
	FROM sSecurity.tMenu Menu	
	LEFT OUTER JOIN sSecurity.tScreen Screen
		ON Menu.ScreenId = Screen.Id		
	LEFT OUTER JOIN ( 
					SELECT 
						TaskId, 
						SUM(Permission & 2) PermissionValue			   
					FROM 
						sSecurity.tPermission P
						INNER JOIN sSecurity.tTask T ON T.Id = P.TaskId
						--INNER JOIN sSecuirty.tOrganizationTask OT ON OT.TaskId = T.Id AND OT.OrgGroupId = P.OrgGroupId 
						INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId = T.ModuleId AND MP.OrgGroupId = P.OrgGroupId
						INNER JOIN
						(
						SELECT RoleId FROM sSecurity.tUserRole UR WHERE  UserId = @rUserId AND IsObsolete = 0
						) B ON B.RoleId = P.RoleId
					WHERE
						T.IsObsolete = 0
					GROUP BY 
						TaskId) TBL2
					ON 
						Screen.TaskId = TBL2.TaskId 
						 LEFT OUTER JOIN sSecurity.tTask  T ON T.Id =  Screen.TaskId AND ResourceTypeId = @rResourceTypeId
						
					WHERE 
					(Menu.IsObsolete = 0)  --For ScreenGroupId Master Page
					AND	ISNULL(Screen.IsObsolete, 0) = 0) 
				    MenuTable  
					--INNER JOIN sSecurity.tTask  T ON T.Id =  MenuTable.TaskId 
	WHERE 
		MenuTable.ScreenId = 0 OR MenuTable.Permission >= 2	
		AND 
		((MenuTable.ResourceTypeId = @rResourceTypeId) OR (@rResourceTypeId = 0))
		AND ((MenuTable.MenuID = @rMenuID)OR(@rMenuID = 0))
	 		
	ORDER BY 
		ParentMenuID

   --SELECT DISTINCT Menu.Id AS MenuID, 
	--		ISNULL(Menu.ParentMenuID, 0) AS ParentMenuID, 
	--		Menu.Title AS MenuTitle, 
	--		Menu.TitleResourceKeyId AS MenuResourceKey, 
	--		Screen.Title AS ScreenTitle,
	--		Screen.TitleResourceKeyId AS ScreenResourceKey,
	--		Screen.Page AS PageURL
	--FROM sSecurity.tMenu Menu
	--LEFT OUTER JOIN sSecurity.tScreen Screen
	--	ON Menu.ScreenId = Screen.Id
	--LEFT OUTER JOIN sSecurity.tPermission Permission
	--	ON Screen.TaskId = Permission.TaskId
	--WHERE	Menu.IsObsolete = 0 AND
	--		Screen.IsObsolete = 0 AND
	--		Permission.RoleId IN (SELECT RoleId FROM sSecurity.tUserRole WHERE UserId = @rUserId) AND
	--		(Permission.Permission & 2) = 2
	--ORDER BY ParentMenuID
END
	
END
GO
PRINT N'Altering Procedure [sStudent].[pRptCountCategorywiseStudentGet]...';


GO
 
 
ALTER PROCEDURE [sStudent].[pRptCountCategorywiseStudentGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rOrgId smallint,
	 @rBatchId int,
	 @rClassId int,
	 @rDivisionId int,
	 @rAsOnDate date,
	 @rReportId int,
	 @rDepartmentId int,
	 @rStudentCode varchar(20),
	 @rCasteCategoryIds nvarchar(max) = '',
	 @rReligionIds nvarchar(max) = '',
	 @rGenderIds nvarchar(max) = '',
	 @rAdmissionCatgoryIds nvarchar(max) = '',
	 @rClassGroup bit=0,
	 @rDivisionGroup bit=0,
	 @rTribeIds nvarchar(max) = '',
	 --added by megha for 0027269
	 @rMainCasteCategoryIds nvarchar(max) = ''
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
  
	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			CM.DisplayTitle AS Class,
			DM.DisplayTitle AS Division,
			ISNULL(GM.Title,'') As Gender,
			A.ClassId,
			A.DivisionId,
			A.Id AS AcademicId,
			A.RollNo,
			SO.DateOfBirth,
			SA.AdmissionDate,
			CM.DisplayTitle+' '+DM.DisplayTitle AS ClassDivision,
			SM.FirstName +' '+ SM.MiddleName +' '+ SM.LastName AS Name,
			SM.Code,
			CCM.OrderIndex AS CasteNumber,
			CASE WHEN  @rReportId=10135 OR @rReportId=20702-- Caste Category
			THEN ISNULL(CCM.Title,'')
		    WHEN  @rReportId=10136 OR @rReportId=20703 -- Religion
			THEN ISNULL(RM.Title,'') 
			WHEN  @rReportId=20704 -- Gender
			THEN ISNULL(GM.Title,'') 
			WHEN @rReportId=20328 OR @rReportId=20705 -- Admission Catgory 
			THEN ISNULL(SCM.Title,'')
			WHEN  @rReportId=10152 -- BloodGroupwise Summary
			THEN ISNULL(BGM.Title,'') 
			WHEN  @rReportId=20329 OR @rReportId=20706--Agegroupwise
			THEN  ([sStudent].[fStudentAgeGroupGet](SO.DateOfBirth,@rAsOnDate,@rOrgId))
			--WHEN  @rReportId=20426 OR @rReportId=20707  --Age wise
			--THEN  ([sStudent].[fStudentAgeGet](SO.DateOfBirth,@rAsOnDate,@rOrgId) + ' Y')
			WHEN    @rReportId = 20866 OR @rReportId=20426 OR @rReportId=20707
			
			THEN RIGHT('00'+ CAST([sStudent].[fStudentAgeGet](SO.DateOfBirth,@rAsOnDate,@rOrgId) AS VARCHAR(2)), 2)+' Year '
			
			WHen @rReportId=30236
			THEN ISNULL(HM.Title,'')
			WHEN  @rReportId=31039 OR @rReportId=31040 -- Tribe
			THEN ISNULL(TM.Title,'')
			--added by megha for 0027269
			WHEN @rReportId=31266
			THEN  ISNULL(MCM.Title,'')  --MainCasteCategory

			END AS Head,
			DM.OrderIndex AS DivisionOrder,
			@rClassGroup As ClassGroup,
			@rDivisionGroup As DivisionGroup,
			Cm.OrderINdex AS ClassOrderIndex,
			CASE WHEN  @rReportId=10135 OR @rReportId=20702-- Caste Category
			THEN ISNULL(CCM.OrderIndex,'')
		    WHEN  @rReportId=10136 OR @rReportId=20703 -- Religion
			THEN ISNULL(RM.OrderIndex,'')  
			ELSE ''
			END AS OrderIndex,
			A.OrgId
			FROM 
			sStudent.tAcademic A		
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId	
			LEFT JOIN sStudent.tStudentOther SO ON A.StudentId=SO.StudentId
			LEFT JOIN sStudent.tStudentAdmission SA ON SA.StudentId=A.StudentId
			LEFT JOIN sCommon.tGenderMaster GM ON GM.Id=SO.GenderId
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
			LEFT JOIN sCommon.tCastCategoryMaster CCM ON CCM.Id=SO.CastCategoryId
			LEFT JOIN sCommon.tReligionMaster RM ON RM.Id=SO.ReligionId
			LEFT JOIN sCommon.tBloodGroupMaster BGM ON BGM.Id=SO.BloodGroupId
			LEFT JOIN sStudent.tAdmissionCategoryMaster SCM ON SCM.Id=A.AdmissionCategoryId
			LEFT JOIN sActivity.tHouseMaster HM ON HM.Id=SO.HouseID
			INNER JOIN sSetup.tBatchClass BC ON BC.ClassID =  CM.Id and BC.BatchId= @rBatchId
			LEFT JOIN sCommon.tTribeMaster TM ON TM.Id=SO.TribeId   -- Tribe
			--added by megha for 0027269
			LEFT JOIN sCommon.tMainCastCategoryMaster MCM ON MCM.Id = CCM.MainCastCategoryId   -- MainCastCategory
	WHERE 
		A.OrgId=@rOrgId
		AND	A.BatchId = @rBatchId 
		AND ((A.ClassId=@rClassId) OR (@rClassId=0))
		AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND SM.StatusId = 1
		AND ((SM.Code=@rStudentCode) OR (@rStudentCode=''))
		AND ((CM.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
	    AND (ISNULL(CCM.Id,0) IN(SELECT cast(item as int) FROM  sCommon.fnsplit(@rCasteCategoryIds,','))OR @rCasteCategoryIds='')
	    AND (ISNULL(RM.Id,0) IN(SELECT cast(item as int) FROM  sCommon.fnsplit(@rReligionIds,','))OR @rReligionIds='')
	    AND (ISNULL(GM.Id,0) IN(SELECT cast(item as int) FROM  sCommon.fnsplit(@rGenderIds,','))OR @rGenderIds='')
	    AND (ISNULL(SCM.Id,0) IN(SELECT cast(item as int) FROM  sCommon.fnsplit(@rAdmissionCatgoryIds,','))OR @rAdmissionCatgoryIds='')
		AND (ISNULL(TM.Id,0) IN (SELECT cast(item as int) FROM  sCommon.fnsplit(@rTribeIds,','))OR @rTribeIds='')
	    AND ((SA.AdmissionDate<=@rAsOnDate) OR (ISNULL(@rAsOnDate,'') = ''))
		AND (ISNULL(MCM.Id,0) IN(SELECT cast(item as int) FROM  sCommon.fnsplit(@rMainCasteCategoryIds,','))OR @rMainCasteCategoryIds='')
END

 
	--Select * from sStudent.tStudentAdmission where AdmissionDate = '2013-05-12'
GO
PRINT N'Altering Procedure [sStudent].[pRptStudentLCVerificationGet]...';


GO

ALTER PROCEDURE [sStudent].[pRptStudentLCVerificationGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rOrgId int,
	 @rBatchId int,
	 @rDepartmentId int=0,
	 @rClassId int=0,
	 @rDivisionId int=0,
     @rStrCode nvarchar(20)='',
	 @rStatusId int=0,
	 @rClassStatusId int=0,
	 @rExamId int = 0
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	
	
	IF(@rExamId!=0)
	 BEGIN
	 SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			L.Id,		
			vSA.Code,
			L.AcademicId,
			vSA.FirstName,vSA.MiddleName,vSA.LastName,
			[sStudent].[fStudentNameGet](vSA.FirstName , vSA.MiddleName, vSA.LastName,OM.StudentNameFormatId ) AS Name,
			ISNULL(SF.FatherName,'') As FatherName,
			ISNULL(SF.MotherName,'') As MotherName,
			ISNULL(so.BirthPlace,'') AS BirthPlace,
			ISNULL(SO.BirthTaluka,'') AS BirthTaluka,
			ISNULL(SO.BirthDistrict,'') AS BirthDistrict,
			SO.DateOfBirth,
			ISNULL(SO.BirthDateInWord,'') AS BirthDateInWord,
			L.LCNumber,
			L.LeftDate,
			L.LCReason,
			L.LCProgress,
			L.LCConduct,
			L.LCRemark,
			L.LCDate,
			L.LCBookNumber,
			ISNULL(SO.FamilySubCast,'') AS SubCaste,
			ISNULL(SO.FamilyCast,'') AS Caste,
		    vSA.StatusId,		
		 	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,			
			vSA.ClassName AS ClassName,
			vSA.DivisionName AS DivisionName,	
			isnull(MainCastCategoryId,0) AS CastCategoryId,
			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,
			SO.UIDNumber,
			L.LCCopy
			,vSA.BatchName AS BatchName,
		    ISNULL(SA.AdmissionNumber,'') AS AdmissionNumber,
			SO.UIDNumber,	
			ISNULL(OM.ReportOrgGroupTitle,'') AS ReportOrgGroupTitle,
			OM.ReportOrgTitle,	
    		ISNULL(CMS.ClassNameInWord,'') AS ClassNameInWord,
			vSA.ClassId AS ClassId,
		    OM.PrincipalSignature,
			ISNULL(R.Percentage,0) As Percentage,
			ISNULL(SCM.Title,'') AS LeftStandard
	FROM 
			sCertificate.tLeaving L
			INNER JOIN sStudent.vStudentAcademic vSA ON vSA.AcademicId=L.AcademicId	
			LEFT JOIN sStudent.tStudentAdmission SA ON SA.StudentId=vSA.StudentId			
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=vSA.OrgId 
			LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=vSA.StudentId 		
			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.tCastCategoryMaster CSM ON CSM.Id=SO.CastCategoryId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id=vSA.BatchId 
			LEFT JOIN sStudent.tStudentAdditional SD ON SD.StudentId=vSA.StudentId
			LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=vSA.StudentId
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId=vSA.ClassId
            LEFT JOIN sAssessment.tResult R ON R.ExamId = EM.Id AND vSA.AcademicId = R.AcademicId
			LEFT JOIN sSetup.tClassMaster SCM ON SCM.Id = SA.LeftStandardId
	Where		  ((vSA.OrgId=@rOrgId) OR (@rOrgId=0))
	       AND ((vSA.BatchId=@rBatchId) OR (@rBatchId=0))
	       AND ((vSA.DepartmentId=@rDepartmentId) OR(@rDepartmentId=0))
	       AND ((vSA.ClassId=@rClassId) OR(@rClassId=0))	  
	       AND ((vSA.DivisionId=@rDivisionId) OR (@rDivisionId=0))	
		   AND (ISNULL(vSA.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rStrCode,',')) OR @rStrCode='')
           AND ((vSA.StatusId=@rStatusId)OR(@rStatusId=0))
		   AND ((vSA.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)) 
		   AND ((EM.Id = @rExamId) OR (@rExamId=0))	
    END		
	
	ELSE 
	  BEGIN
	     SELECT
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			L.Id,		
			vSA.Code,
			L.AcademicId,
			vSA.FirstName,vSA.MiddleName,vSA.LastName,
			[sStudent].[fStudentNameGet](vSA.FirstName , vSA.MiddleName, vSA.LastName,OM.StudentNameFormatId ) AS Name,
			ISNULL(SF.FatherName,'') As FatherName,
			ISNULL(SF.MotherName,'') As MotherName,
			ISNULL(so.BirthPlace,'') AS BirthPlace,
			ISNULL(SO.BirthTaluka,'') AS BirthTaluka,
			ISNULL(SO.BirthDistrict,'') AS BirthDistrict,
			SO.DateOfBirth,
			ISNULL(SO.BirthDateInWord,'') AS BirthDateInWord,
			L.LCNumber,
			L.LeftDate,
			L.LCReason,
			L.LCProgress,
			L.LCConduct,
			L.LCRemark,
			L.LCDate,
			L.LCBookNumber,
			ISNULL(SO.FamilySubCast,'') AS SubCaste,
			ISNULL(SO.FamilyCast,'') AS Caste,
		    vSA.StatusId,		
		 	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,			
			vSA.ClassName AS ClassName,
			vSA.DivisionName AS DivisionName,	
			isnull(MainCastCategoryId,0) AS CastCategoryId,
			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,
			SO.UIDNumber,
			L.LCCopy
			,vSA.BatchName AS BatchName,
		    ISNULL(SA.AdmissionNumber,'') AS AdmissionNumber,
			SO.UIDNumber,	
			ISNULL(OM.ReportOrgGroupTitle,'') AS ReportOrgGroupTitle,
			OM.ReportOrgTitle,	
    		ISNULL(CMS.ClassNameInWord,'') AS ClassNameInWord,
			vSA.ClassId AS ClassId,
		    OM.PrincipalSignature,
			0 As Percentage,
			ISNULL(SCM.Title,'') AS LeftStandard
	FROM 
			sCertificate.tLeaving L
			INNER JOIN sStudent.vStudentAcademic vSA ON vSA.AcademicId=L.AcademicId	
			LEFT JOIN sStudent.tStudentAdmission SA ON SA.StudentId=vSA.StudentId			
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=vSA.OrgId 
			LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=vSA.StudentId 
			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.tCastCategoryMaster CSM ON CSM.Id=SO.CastCategoryId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id=vSA.BatchId 
			LEFT JOIN sStudent.tStudentAdditional SD ON SD.StudentId=vSA.StudentId
			LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=vSA.StudentId
			LEFT JOIN sSetup.tClassMaster SCM ON SCM.Id = SA.LeftStandardId
	Where		
	            ((vSA.OrgId=@rOrgId) OR (@rOrgId=0))
	       AND ((vSA.BatchId=@rBatchId) OR (@rBatchId=0))
	       AND ((vSA.DepartmentId=@rDepartmentId) OR(@rDepartmentId=0))
	       AND ((vSA.ClassId=@rClassId) OR(@rClassId=0))	  
	       AND ((vSA.DivisionId=@rDivisionId) OR (@rDivisionId=0))	
		   AND (ISNULL(vSA.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rStrCode,',')) OR @rStrCode='')
           AND ((vSA.StatusId=@rStatusId)OR(@rStatusId=0))
		   AND ((vSA.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)) 
	  END 			
END
GO
PRINT N'Altering Procedure [sStudent].[pRptStudentPastLCVerificationGet]...';


GO

ALTER PROCEDURE [sStudent].[pRptStudentPastLCVerificationGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='',
	 @rOrgId int,
	 @rBatchId int,
	 @rDepartmentId int=0,
	 @rClassId int=0,
	 @rDivisionId int=0,
     @rStrCode nvarchar(20)='',
	 @rStatusId int=0,
	 @rClassStatusId int=0,
	 @rPreviousSchool nvarchar(200)=''

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
 BEGIN

	     SELECT
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,	
			OM.OrgLogo,
			OM.Title AS OrgTitle,
			OM.StreetOne+' '+OM.StreetTwo+' '+OM.StreetThree AS OrgAddress,
			OM.SmallAddress1,
			OM.SmallAddress2,
			OM.RegistrationDetail,
            vSA.ClassId AS ClassId,
			CM.OrderIndex AS ClassOrderIndex,
			vSA.ClassId AS DivisionId,	
			DM.OrderIndex AS DivisionOrderIndex,		
			vSA.ClassName AS ClassName,
			vSA.DivisionName AS DivisionName,
			ISNULL(OM.ReportOrgGroupTitle,'') AS ReportOrgGroupTitle,
			OM.ReportOrgTitle,		
			vSA.AcademicId,
			vSA.Code,
			ISNULL(SA.AdmissionNumber,'') As OldGRNo,
            vSA.FirstName,vSA.MiddleName,vSA.LastName,
			[sStudent].[fStudentNameGet](vSA.FirstName , vSA.MiddleName, vSA.LastName,OM.StudentNameFormatId ) AS Name,
			ISNULL(SO.DateOfBirth,'') AS DateOfBirth,
			ISNULL(SO.BirthDateInWord,'') AS BirthDateInWord,
			ISNULL(SA.PreviousStandard,'') AS PreviousStandard,
			ISNULL(SA.LeftDate,'') AS LeftDate,
			ISNULL(SO.BirthPlace,'') AS BirthPlace,
			ISNULL(SA.PreviousLCNumber,'') AS PreviousLCNumber,
			ISNULL(SA.PreviousLCDate,'') AS PreviousLCDate,
			ISNULL(SA.PreviousLCResult,'') AS PreviousLCResult,
			ISNULL(SO.FamilySubCast,'') AS SubCaste,
			ISNULL(SO.FamilyCast,'') AS Caste,
			isnull(MainCastCategoryId,0) AS CastCategoryId,
			ISNULL(SA.AdmissionNumber,'') AS AdmissionNumber
			 
			--SA.PreviousSchool

	FROM 
		    sStudent.vStudentAcademic vSA 	
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=vSA.OrgId 
			LEFT JOIN sStudent.tStudentAdmission SA ON SA.StudentId=vSA.StudentId
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=SA.AdmissionStandardId
			INNER JOIN sSetup.tDivisionMaster DM ON vSA.DivisionId = DM.Id  
		    LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=vSA.StudentId 
			LEFT JOIN sCommon.tCastCategoryMaster CSM ON CSM.Id=SO.CastCategoryId		
	Where		
	           ((vSA.OrgId=@rOrgId) OR (@rOrgId=0))
	       AND ((vSA.BatchId=@rBatchId) OR (@rBatchId=0))
	       AND ((vSA.DepartmentId=@rDepartmentId) OR(@rDepartmentId=0))
	       AND ((vSA.ClassId=@rClassId) OR(@rClassId=0))	  
	       AND ((vSA.DivisionId=@rDivisionId) OR (@rDivisionId=0))	
		   AND (ISNULL(vSA.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rStrCode,',')) OR @rStrCode='')
           AND ((vSA.StatusId=@rStatusId)OR(@rStatusId=0))
		   AND ((vSA.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)) 
		   --AND (ISNULL(SA.PreviousSchool,'') IN( SELECT item FROM  sCommon.fnsplit(@rPreviousSchool,','))OR @rPreviousSchool='')	
		    AND ((SA.PreviousSchool =  @rPreviousSchool) OR (@rPreviousSchool='')) 
END
GO
PRINT N'Altering Procedure [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.Name,
			@lAcademicId AS 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,
			ISNULL(SA.ClassStatusId,0) AS ClassStatusId,
			ISNULL(SA.FeesRemark,'') AS FeesRemark,
			ISNULL(SO.TransportModeId,0) AS TransportModeId,
			ISNULL(SO.BirthDateInWord, '') AS BirthDateInWord
			
  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)
  ORDER BY SA.Code
END
GO
PRINT N'Altering Procedure [sStudent].[pStudentOtherAdd]...';


GO
ALTER PROCEDURE [sStudent].[pStudentOtherAdd]
	 
		   @rStudentId bigint,
           @rUIDNumber nvarchar(50),
           @rDateOfBirth date,
           @rGenderId tinyint,
           @rReligionId int,     
           @rBloodGroupId tinyint,
           @rBirthPlace nvarchar(150),
           @rBirthTaluka nvarchar(150),
           @rBirthDistrict nvarchar(150),
           @rBirthdateInWord nvarchar(150),     
           @rFamilyCast nvarchar(100),
           @rFamilySubCast nvarchar(100),
           @rCastCategoryId int,
           @rTransportModeId int,
           --@rPickupBusRouteDestinationId int,
           --@rDropBusRouteDestinationId int,
           --@rBusRouteId int,
           --@rPickuppointId int,
           @rHouseId int,
           @rMotherTongueId int,
           @rNationalityId int,
           @rHobby nvarchar(50),           
           --@rFeeCategoryId int,      
           --@rResideModeId int,
           @rCreatedUserId bigint,
           @rUpdatedUserId bigint,
           @rReferenceRemark nvarchar(100) = '',
           @rAdhaarNumber nvarchar(20) = '',
           @rMotherTongue nvarchar(100) = '',
           @rQuotaId int =0,
           @rbirthState nvarchar(100)='',
           @rBirthCountry nvarchar(100)='',
		   @rBatchId int = 0,
		   @rTribeId int = 0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	IF NOT EXISTS(SELECT 1 FROM sStudent.tStudentOther WHERE StudentId = @rStudentId)
	 BEGIN
	 --commented by dhruvik for 27466 mantis
	  --  IF(ISNULL(@rUIDNumber,'')!='')		
		 -- BEGIN
			--IF EXISTS(SELECT 1 FROM sStudent.tStudentOther SO INNER JOIN sStudent.tStudentMaster SM ON SM.Id = SO.StudentId WHERE SM.OrgId = LEFT(@rBatchId,4) AND UIDNumber=@rUIDNumber AND StudentId NOT IN (SELECT ReferenceSourceId FROM sStudent.tStudentMaster))
			--BEGIN
			--	SELECT -101 AS Result
			--	RETURN
			--END 
		 -- END
		 
		 IF(ISNULL(@rAdhaarNumber,'')!='')		 		 
		  BEGIN

			IF EXISTS(SELECT 1 FROM sStudent.tStudentOther SO INNER JOIN sStudent.tStudentMaster SM ON SM.Id = SO.StudentId WHERE SM.OrgId = LEFT(@rBatchId,4) AND  AdhaarNumber=@rAdhaarNumber AND StudentId NOT IN (SELECT ReferenceSourceId FROM sStudent.tStudentMaster))
				BEGIN
					SELECT -102 AS Result
					RETURN
				END 
		  END
		  
	 END
	 
	 ELSE
	 
	  
	  
	  BEGIN
	  --commented by dhruvik for 27466 mantis
		 --IF(ISNULL(@rUIDNumber,'')!='')		
		 -- BEGIN
			--IF EXISTS(SELECT 1 FROM sStudent.tStudentOther SO INNER JOIN sStudent.tStudentMaster SM ON SM.Id = SO.StudentId WHERE SM.OrgId = LEFT(@rBatchId,4) AND UIDNumber=@rUIDNumber AND StudentId <> @rStudentId AND StudentId NOT IN (SELECT ReferenceSourceId FROM sStudent.tStudentMaster))
			--BEGIN
			--	SELECT -101 AS Result
			--	RETURN
			--END 
		 -- END
		  
		 IF(ISNULL(@rAdhaarNumber,'')!='')	
		  BEGIN
			IF EXISTS(SELECT 1 FROM sStudent.tStudentOther SO INNER JOIN sStudent.tStudentMaster SM ON SM.Id = SO.StudentId WHERE SM.OrgId = LEFT(@rBatchId,4) AND AdhaarNumber=@rAdhaarNumber AND StudentId <> @rStudentId AND StudentId NOT IN (SELECT ReferenceSourceId FROM sStudent.tStudentMaster))
				BEGIN
					SELECT -102 AS Result
					RETURN
				END 
		  END
		  
	 END
	  
	 BEGIN TRANSACTION
	 
IF NOT EXISTS(SELECT * FROM sStudent.tStudentOther WHERE StudentId = @rStudentId)
BEGIN

	--DECLARE @lNextNumber BIGINT     
	--EXECUTE sCommon.pTableRowIdGet 0, 'sStudent.tStudentCommunication', 0, 1, 1,@outNextNumber = @lNextNumber output

	INSERT INTO sStudent.tStudentOther
		(
		   StudentId,
           UIDNumber,
           DateOfBirth,
           GenderId,
           ReligionId,
           BloodGroupId,
           BirthPlace,
           BirthTaluka,
           BirthDistrict,
           BirthdateInWord,
      
           FamilyCast,
           FamilySubCast,
           CastCategoryId,
           TransportModeId,
           --PickupBusRouteDestinationId,
           --DropBusRouteDestinationId,
           --BusRouteId,
           --PickuppointId,
           HouseId,
           MotherTongueId,
           NationalityId,
           Hobby,
           ReferenceRemark,
           --FeeCategoryId,
         
           --ResideModeId,
           CreatedUserId,
           CreatedDateTime,
           AdhaarNumber,
           MotherTongue,
           QuotaId,
           BirthState,
           BirthCountry,
		   TribeId
		)
	VALUES
		(
		   @rStudentId,
           @rUIDNumber,
           @rDateOfBirth,
           @rGenderId,
           @rReligionId,
           @rBloodGroupId,
           @rBirthPlace,
           @rBirthTaluka,
           @rBirthDistrict,
           @rBirthdateInWord,
       
           @rFamilyCast,
           @rFamilySubCast,
           @rCastCategoryId,
           @rTransportModeId,
           --@rPickupBusRouteDestinationId,
           --@rDropBusRouteDestinationId,
           --@rBusRouteId,
           --@rPickuppointId,
           @rHouseId,
           @rMotherTongueId,
           @rNationalityId,
           @rHobby,
           @rReferenceRemark,
           --@rFeeCategoryId,
        
           --@rResideModeId,
           @rCreatedUserId,
           sCommon.fGetDate(),
           @rAdhaarNumber,
           @rMotherTongue,
           @rQuotaId,
           @rbirthState,
           @rBirthCountry,
           @rTribeId
		)
		SELECT 1 AS Result             
END	
 
ELSE

BEGIN
	 --SET @lNextNumber = @rStudentId
	    UPDATE  sStudent.tStudentOther
	    SET
			  StudentId = @rStudentId, 
			  UIDNumber = @rUIDNumber, 
			  DateOfBirth = @rDateOfBirth, 
			  GenderId = @rGenderId,
			  ReligionId = @rReligionId, 
		 
			  BloodGroupId = @rBloodGroupId, 
			  BirthPlace = @rBirthPlace, 
			  BirthTaluka = @rBirthTaluka,
			  BirthDistrict = @rBirthDistrict,
			  BirthdateInWord = @rBirthdateInWord, 
		 
			  FamilyCast = @rFamilyCast, 
			  FamilySubCast = @rFamilySubCast, 
			  CastCategoryId = @rCastCategoryId, 
			  TransportModeId = @rTransportModeId,
			  --PickupBusRouteDestinationId=@rPickupBusRouteDestinationId,
			  --DropBusRouteDestinationId=@rDropBusRouteDestinationId,
			  --BusRouteId = @rBusRouteId,
			  --PickuppointId = @rPickuppointId, 
			  HouseId = @rHouseId, 
			  MotherTongueId=@rMotherTongueId,
			  NationalityId=@rNationalityId,
			  Hobby=@rHobby,
			  ReferenceRemark=@rReferenceRemark,
			  --FeeCategoryId = @rFeeCategoryId,
	 
			  --ResideModeId = @rResideModeId,
			  UpdatedUserId = @rUpdatedUserId, 
			  UpdatedDateTime =sCommon.fGetDate(),
			  AdhaarNumber=@rAdhaarNumber,
			  MotherTongue=@rMotherTongue,
			  QuotaId = @rQuotaId,
			  BirthState =@rbirthState,
			  BirthCountry =@rBirthCountry,
			  TribeId = @rTribeId
	      WHERE StudentId = @rStudentId 
	       
END  
		SELECT 11 AS Result
	
--DECLARE @lAcademicId bigint = 0
--SELECT @lAcademicId = ISNULL(Id,0) from sStudent.tAcademic Where StudentId = @rStudentId AND BatchId = @rBatchId

--If (@lAcademicId != 0)
--BEGIN
--	IF NOT EXISTS(Select 1 from sStudent.tAcademicStudentOther Where AcademicId = @lAcademicId)
--	BEGIN
--		INSERT INTO sStudent.tAcademicStudentOther
--		(
--		   AcademicId,
--           UIDNumber,
--           DateOfBirth,
--           GenderId,
--           ReligionId,
--           BloodGroupId,
--           BirthPlace,
--           BirthTaluka,
--           BirthDistrict,
--           BirthdateInWord,
--           FamilyCast,
--           FamilySubCast,
--           CastCategoryId,
--           TransportModeId,
--           HouseId,
--           MotherTongueId,
--           NationalityId,
--           Hobby,
--           ReferenceRemark,
--           CreatedUserId,
--           CreatedDateTime,
--           AdhaarNumber,
--           MotherTongue,
--           QuotaId,
--           BirthState,
--           BirthCountry
--		)
--		VALUES
--		(
--		   @lAcademicId,
--           @rUIDNumber,
--           @rDateOfBirth,
--           @rGenderId,
--           @rReligionId,
--           @rBloodGroupId,
--           @rBirthPlace,
--           @rBirthTaluka,
--           @rBirthDistrict,
--           @rBirthdateInWord,
--           @rFamilyCast,
--           @rFamilySubCast,
--           @rCastCategoryId,
--           @rTransportModeId,
--           @rHouseId,
--           @rMotherTongueId,
--           @rNationalityId,
--           @rHobby,
--           @rReferenceRemark,
--           @rCreatedUserId,
--           sCommon.fGetDate(),
--           @rAdhaarNumber,
--           @rMotherTongue,
--           @rQuotaId,
--           @rbirthState,
--           @rBirthCountry
--		)
--	END
--	ELSE
--	BEGIN
--		UPDATE  sStudent.tAcademicStudentOther
--	    SET
--		   AcademicId = @lAcademicId, 
--		   UIDNumber = @rUIDNumber, 
--		   DateOfBirth = @rDateOfBirth, 
--		   GenderId = @rGenderId,
--		   ReligionId = @rReligionId, 
--		   BloodGroupId = @rBloodGroupId, 
--		   BirthPlace = @rBirthPlace, 
--		   BirthTaluka = @rBirthTaluka,
--		   BirthDistrict = @rBirthDistrict,
--		   BirthdateInWord = @rBirthdateInWord, 
--		   FamilyCast = @rFamilyCast, 
--		   FamilySubCast = @rFamilySubCast, 
--		   CastCategoryId = @rCastCategoryId, 
--		   TransportModeId = @rTransportModeId,
--		   HouseId = @rHouseId, 
--		   MotherTongueId=@rMotherTongueId,
--		   NationalityId=@rNationalityId,
--		   Hobby=@rHobby,
--		   ReferenceRemark=@rReferenceRemark,
--		   UpdatedUserId = @rUpdatedUserId, 
--		   UpdatedDateTime =sCommon.fGetDate(),
--		   AdhaarNumber=@rAdhaarNumber,
--		   MotherTongue=@rMotherTongue,
--		   QuotaId = @rQuotaId,
--		   BirthState =@rbirthState,
--		   BirthCountry =@rBirthCountry
--	     WHERE AcademicId = @lAcademicId 
--	END
	
--END
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering Procedure [sStudent].[pValidateImportStudent]...';


GO
ALTER PROCEDURE [sStudent].[pValidateImportStudent]

	@rOrgGroupId int,
    @rOrgId int,
	@rXmldoc [nvarchar](max),
	@rOperation int=0,   --1 For Insert,2 For Update
	@rBatchId int=0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
DECLARE @lSUIdActivate nvarchar(50)=''
DECLARE @lIsSurnameAndFatherNameMandatory nvarchar(50)=''
DECLARE @lIsActivateUniqueId bit = 0
DECLARE @lOrgGroupId int = 0
DECLARE @lIsStudentUIDNumberUnique nvarchar(50)=''		--add
SELECT @lOrgGroupId=OrgGroupId FROM sSetup.tOrganizationMaster WHERE Id = @rOrgId
SELECT @lSUIdActivate = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 167 AND SourceTypeId = 2010 AND SourceId = @lOrgGroupId
SELECT @lIsSurnameAndFatherNameMandatory =  ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 415 AND SourceTypeId = 2010 AND SourceId = @lOrgGroupId	
SELECT @lIsStudentUIDNumberUnique = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 534 AND SourceTypeId = 2010 AND SourceId = @lOrgGroupId		--add
IF (@lSUIdActivate = '') OR (@lSUIdActivate = 'False')
	SET @lIsActivateUniqueId = 0
ELSE
	SET @lIsActivateUniqueId = 1	

DECLARE @lCount INT
DECLARE @lInterrorCode INT,
		@intDoc INT,
        @lCode nvarchar(50),
        @lClass nvarchar(100),
        @lDivision nvarchar(100),        
        @lRegistrationNumber nvarchar(20),  
        @lAdmissionDate nvarchar(15),        
        @lDOB nvarchar(15),             
        @1ReturnCode int = 1,
        @1ExistStudentCode nvarchar(max) = '',
        @1NotExistStudentCode nvarchar(max) = '',
        @1ExistStudentRegistrationNumber nvarchar(max) = '',
        @1ValidAdmissionDate nvarchar(max) = '',
        @1ValidDOB nvarchar(max) = '',
        @1DuplicateStudentCode nvarchar(max) = '',
        @1DuplicateStudentRegistrationNumber nvarchar(max) = '',
        @lSUId nvarchar(50),
        @1ExistStudentSUId nvarchar(max) = '',
        @1DuplicateStudentSUId nvarchar(max) = '',
        @lLeftDate nvarchar(15),
        @lLCDate nvarchar(15),
        @1ValidLeftDate nvarchar(max) = '',
        @1ValidLCDate nvarchar(max) = '',
        @lStatusId smallint,
        
        @lAdhaarNumber nvarchar(50),  
        @1DuplicateAdhaarNumber nvarchar(max) = '',
        
        @lUIDNumber nvarchar(50),  
        @1DuplicateUIDNumber nvarchar(max) = '',
        
        @1StudentId BIGINT = 0
       
EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc
 
CREATE TABLE #tTable1 
 (
		Id bigint identity,
        Code nvarchar(50),
        RegistrationNumber nvarchar(20),
        FirstName nvarchar(100),
		MiddleName nvarchar(100),
        LastName nvarchar(100),
		Class nvarchar(100),
		Division nvarchar(100),
		AdmissionStandard nvarchar(100),
		AdmissionDate nvarchar(15),
        DOB nvarchar(15),
        Gender nvarchar(10),
        --AdmissionCategory nvarchar(100),
		Religion nvarchar(100),
		CastCategory nvarchar(100),
        SUId nvarchar(50),
        LeftDate nvarchar(15),
        LCDate nvarchar(15),
        LeftStandard nvarchar(100),
        StatusId smallint,
        AdhaarNumber varchar(100),
        UIDNumber varchar(100)
        --Id1 bigint NULL,
        --departmentId int NULL
 
  )
  INSERT INTO #tTable1
	(
	    Code,
	    RegistrationNumber, 
	    FirstName,
		MiddleName,
	    LastName,
	    Class,
	    Division,
	    AdmissionStandard,
	    AdmissionDate,
	    DOB,
	    Gender,
	    --AdmissionCategory,
	    Religion,
	    CastCategory,
	    SUId,
	    LeftDate,
        LCDate,
        LeftStandard,
        StatusId,
        AdhaarNumber,
        UIDNumber
    ) 
   SELECT
        Code,
	    RegistrationNumber, 
	    sSetup.fPortalXMLTagsReplaceReverse(FirstName) AS FirstName,
		sSetup.fPortalXMLTagsReplaceReverse(MiddleName) AS MiddleName,
	    sSetup.fPortalXMLTagsReplaceReverse(LastName) AS LastName,
	    Class,
	    Division,
	    AdmissionStandard,
	    AdmissionDate,
	    DOB,
	    Gender,
	    --AdmissionCategory,
	    sSetup.fPortalXMLTagsReplaceReverse(Religion) AS Religion,
	    sSetup.fPortalXMLTagsReplaceReverse(CastCategory) AS CastCategory,
	    SUId,
	    LeftDate,
        LCDate,
        LeftStandard,
        StatusId,
        AdhaarNumber,
        UIDNumber
   
   FROM OPENXML (@intDoc, '/Table/ImportStudent', 1)
   With
   (
        Code nvarchar(50) '@Code',
        RegistrationNumber nvarchar(20) '@RegistrationNumber',
        FirstName nvarchar(100) '@FirstName',
		MiddleName nvarchar(100) '@MiddleName',
        LastName nvarchar(100) '@LastName',
		Class nvarchar(100) '@Class',
		Division nvarchar(100) '@Division',
		AdmissionStandard nvarchar(100) '@AdmissionStandard',
		AdmissionDate nvarchar(15) '@AdmissionDate',
		DOB nvarchar(15) '@DOB',
		Gender nvarchar(10) '@Gender',
		--AdmissionCategory nvarchar(100) '@AdmissionCategory',
		Religion nvarchar(100) '@Religion',
		CastCategory nvarchar(100) '@CastCategory',
		SUId nvarchar(50) '@SUId',
		LeftDate nvarchar(15) '@LeftDate',
		LCDate nvarchar(15) '@LCDate',
		LeftStandard nvarchar(100) '@LeftStandard',
		StatusId smallint '@StatusId',
		AdhaarNumber varchar(100) '@AdhaarNumber',
		UIDNumber varchar(100) '@UIDNumber'
   )   
EXEC sp_xml_removedocument @intDoc
		
SELECT @lCount =  COUNT(Id) FROM #tTable1

WHILE @lCount > 0 
  BEGIN
  
       SELECT         
         
         @lCode = Code, 
         @lRegistrationNumber = RegistrationNumber,
         @lAdmissionDate = AdmissionDate,
         @lDOB=DOB,
         @lSUId = SUId,
         @lLeftDate = LeftDate,
         @lLCDate = LCDate,
         @lStatusId = StatusId,
         @lAdhaarNumber = AdhaarNumber,
         @lUIDNumber = UIDNumber
        FROM #tTable1 WHERE Id = @lCount 

IF(@rOperation=2)
   BEGIN   
     IF Exists(SELECT Id FROM sStudent.tStudentMaster WHERE Code COLLATE DATABASE_DEFAULT = @lCode COLLATE DATABASE_DEFAULT AND OrgId = @rOrgId)    
      SET @1StudentId = (SELECT Id FROM sStudent.tStudentMaster WHERE Code COLLATE DATABASE_DEFAULT = @lCode COLLATE DATABASE_DEFAULT AND OrgId = @rOrgId)
     ELSE
       SET @1NotExistStudentCode = @1NotExistStudentCode + @lCode + ','    
       print @1NotExistStudentCode
   END     
       
        
IF(@rOperation=1 OR @rOperation=0)     
 BEGIN    
    IF Exists ((select 1 from sStudent.tStudentMaster where Code COLLATE DATABASE_DEFAULT = @lCode COLLATE DATABASE_DEFAULT AND OrgId = @rOrgId))         
          BEGIN
  			    SET @1ExistStudentCode = @1ExistStudentCode + @lCode + ','
	       END	  
	IF Exists ((select 1 from sStudent.tStudentMaster SM INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SM.OrgId where SM.SUId COLLATE DATABASE_DEFAULT = @lSUId COLLATE DATABASE_DEFAULT AND OM.OrgGroupId = @rOrgGroupId))         
          BEGIN
  			    SET @1ExistStudentSUId = @1ExistStudentSUId + @lSUId + ','
	       END	         
	IF Exists ((select 1 from sStudent.tStudentMaster where RegistrationNumber COLLATE DATABASE_DEFAULT = @lRegistrationNumber COLLATE DATABASE_DEFAULT AND OrgId = @rOrgId))         
          BEGIN
				IF(ISNULL(@lRegistrationNumber,'')!='')
				BEGIN
  					SET @1ExistStudentRegistrationNumber = @1ExistStudentRegistrationNumber + CAST(@lRegistrationNumber as varchar(max)) + ','
				END
	       END
	IF Exists ((select * from sStudent.tStudentOther SO INNER JOIN sStudent.tStudentMaster SM ON SM.Id = SO.StudentId INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SM.OrgId where SO.AdhaarNumber COLLATE DATABASE_DEFAULT = @lAdhaarNumber COLLATE DATABASE_DEFAULT))         
          BEGIN
          
                IF(ISNULL(@lAdhaarNumber,'')!='')
                BEGIN
  			        SET @1DuplicateAdhaarNumber = @1DuplicateAdhaarNumber + @lAdhaarNumber + ','
  			    END
	       END	
	     
	IF Exists ((select * from sStudent.tStudentOther SO INNER JOIN sStudent.tStudentMaster SM ON SM.Id = SO.StudentId INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SM.OrgId where SO.UIDNumber COLLATE DATABASE_DEFAULT = @lUIDNumber COLLATE DATABASE_DEFAULT))         
	BEGIN
		IF(@lIsStudentUIDNumberUnique='True')	--add
		BEGIN
			IF(ISNULL(@lUIDNumber,'')!='')
			BEGIN
                
  				SET @1DuplicateUIDNumber = @1DuplicateUIDNumber + @lUIDNumber + ',' 
  			                 
			END 
		END
	END	
END


ELSE

BEGIN    

    IF Exists ((select 1 from sStudent.tStudentMaster where Code COLLATE DATABASE_DEFAULT = @lCode COLLATE DATABASE_DEFAULT AND OrgId = @rOrgId AND Id<>@1StudentId))         
          BEGIN
  			    SET @1ExistStudentCode = @1ExistStudentCode + @lCode + ','
	       END	  
	IF Exists ((select 1 from sStudent.tStudentMaster SM INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SM.OrgId where SM.SUId COLLATE DATABASE_DEFAULT = @lSUId COLLATE DATABASE_DEFAULT AND OM.OrgGroupId = @rOrgGroupId AND SM.Id<>@1StudentId))         
          BEGIN
  			    SET @1ExistStudentSUId = @1ExistStudentSUId + @lSUId + ','
	       END	         
	IF Exists ((select 1 from sStudent.tStudentMaster where RegistrationNumber COLLATE DATABASE_DEFAULT = @lRegistrationNumber COLLATE DATABASE_DEFAULT AND OrgId = @rOrgId AND Id<>@1StudentId))         
          BEGIN
				IF(ISNULL(@lRegistrationNumber,'')!='')
				BEGIN
  					SET @1ExistStudentRegistrationNumber = @1ExistStudentRegistrationNumber + CAST(@lRegistrationNumber as varchar(max)) + ','
				END
	       END
	IF Exists ((select * from sStudent.tStudentOther SO INNER JOIN sStudent.tStudentMaster SM ON SM.Id = SO.StudentId INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SM.OrgId where SO.AdhaarNumber COLLATE DATABASE_DEFAULT = @lAdhaarNumber COLLATE DATABASE_DEFAULT AND SM.Id<>@1StudentId))         
          BEGIN
          
                IF(ISNULL(@lAdhaarNumber,'')!='')
                BEGIN
  			        SET @1DuplicateAdhaarNumber = @1DuplicateAdhaarNumber + @lAdhaarNumber + ','
  			    END
	       END	
	     
	IF Exists ((select * from sStudent.tStudentOther SO INNER JOIN sStudent.tStudentMaster SM ON SM.Id = SO.StudentId INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SM.OrgId where SO.UIDNumber COLLATE DATABASE_DEFAULT = @lUIDNumber COLLATE DATABASE_DEFAULT AND SM.Id<>@1StudentId))         
	BEGIN
		IF(@lIsStudentUIDNumberUnique='True')		--add
		BEGIN  
			IF(ISNULL(@lUIDNumber,'')!='')
			BEGIN
                
  				SET @1DuplicateUIDNumber = @1DuplicateUIDNumber + @lUIDNumber + ',' 
  			                 
			END 
		END   
	END	
END       
	       
	
	IF(ISDATE(@lAdmissionDate) = 0 AND @lAdmissionDate!='')
	BEGIN
		SET @1ValidAdmissionDate=@1ValidAdmissionDate + @lCode + '-' + @lAdmissionDate+','
	END
	IF(ISDATE(@lDOB) = 0 AND @lDOB!='')
	BEGIN
		SET @1ValidDOB=@1ValidDOB + @lCode + '-' + @lDOB+','
	END
	
	IF(ISDATE(@lLeftDate) = 0 AND @lLeftDate!='')
	BEGIN
		SET @1ValidLeftDate=@1ValidLeftDate + @lCode + '-' + @lLeftDate+','
	END
	
	IF(ISDATE(@lLCDate) = 0 AND @lLCDate!='')
	BEGIN
		SET @1ValidLCDate=@1ValidLCDate + @lCode + '-' + @lLCDate+','
	END
	
     SET @lCount = @lCount - 1	
   END	
   
   SELECT @lCount =  COUNT(Id) FROM #tTable1
 
	WHILE @lCount > 0 
		BEGIN
			SELECT         
         
			 @lClass = Class, 
			 @lDivision = Division
     
			FROM #tTable1 WHERE Id = @lCount
			    
		 --IF(@rOperation=1)
		 BEGIN	
			IF NOT EXISTS (SELECT 1 FROM sSetup.tDivisionMaster DM 
					INNER JOIN sSetup.tClassMaster CM ON CM.Id=DM.ClassId 
						WHERE CM.Title COLLATE DATABASE_DEFAULT =@lClass COLLATE DATABASE_DEFAULT AND DM.Title COLLATE DATABASE_DEFAULT =@lDivision COLLATE DATABASE_DEFAULT AND DM.OrgId=@rOrgId)	
			BEGIN
				
				SELECT 'Enter proper value for Division ' + @lClass + ' ' + @lDivision AS StudentCode
				RETURN
			END
		  END	
			SET @lCount = @lCount - 1	
		END
   	      If(@rOperation=2)
   	      BEGIN
   			  DECLARE @lExistingClassId int
   			  DECLARE @lExcelClassId int
   			  SET @lExistingClassId=(SELECT ClassId From sStudent.tAcademic WHERE StudentId=@1StudentId AND BatchId=@rBatchId)
	   		
   			  SET @lExcelClassId=(select Id from sSetup.tClassMaster where Title=@lClass and OrgId=@rOrgId)
	   		  
   			  IF(@lExcelClassId<>@lExistingClassId)
   		       BEGIN
				  SELECT 'Class Id not match/update.' AS StudentCode
			   END
   			
   	      END
              	      
   	      
   	      
   	    
			IF EXISTS(SELECT 1 fROM #tTable1 WHERE Code IS NULL OR Code COLLATE DATABASE_DEFAULT ='' COLLATE DATABASE_DEFAULT)
			BEGIN
				SELECT 'ID No Should not be empty' AS StudentCode
			END
		
		--ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE Number IS NULL OR Number='')
		--BEGIN
		--	SELECT 'Number Should not be empty' AS StudentCode
		--END
		--ELSE IF EXISTS(SELECT 1 FROM #tTable1 WHERE LastName IS NULL OR LastName COLLATE DATABASE_DEFAULT ='' COLLATE DATABASE_DEFAULT)
		--BEGIN
		--	SELECT 'Surname Should not be empty' AS StudentCode
		--END
		ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE FirstName IS NULL OR FirstName COLLATE DATABASE_DEFAULT='' COLLATE DATABASE_DEFAULT)
		BEGIN
			SELECT 'First Name Should not be empty' AS StudentCode
		END
		ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE Class IS NULL OR Class COLLATE DATABASE_DEFAULT ='' COLLATE DATABASE_DEFAULT) AND (@rOperation=1)
		BEGIN
			SELECT 'Class Should not be empty' AS StudentCode
		END
		ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE Division IS NULL OR Division COLLATE DATABASE_DEFAULT ='' COLLATE DATABASE_DEFAULT) AND (@rOperation=1)
		BEGIN
			SELECT 'Division Should not be empty' AS StudentCode
		END
		--ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE AdmissionStandard IS NULL OR AdmissionStandard='')
		--BEGIN
		--	SELECT 'Admission Standard Should not be empty' AS StudentCode
		--END
		ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE Gender IS NULL OR Gender='')
		BEGIN
			SELECT 'Gender Should not be empty' AS StudentCode
		END
		--ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE AdmissionCategory IS NULL OR AdmissionCategory='')
		--BEGIN
		--	SELECT 'Admission Category Should not be empty' AS StudentCode
		--END
		ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE AdmissionDate IS NULL OR AdmissionDate COLLATE DATABASE_DEFAULT='' COLLATE DATABASE_DEFAULT) AND (@rOperation=1)
		BEGIN
			SELECT 'Admission Date Should not be empty or check the date format' AS StudentCode
		END
		ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE Class COLLATE DATABASE_DEFAULT NOT IN(SELECT Title FROM sSetup.tClassMaster WHERE OrgId=@rOrgId)) AND (@rOperation=1)
		BEGIN
			SELECT 'Enter proper value for Class as per Institute Setup > Class Master' AS StudentCode
		END				
		ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE AdmissionStandard  COLLATE DATABASE_DEFAULT !='' COLLATE DATABASE_DEFAULT AND AdmissionStandard COLLATE DATABASE_DEFAULT NOT IN(SELECT Title FROM sSetup.tClassMaster WHERE OrgId=@rOrgId)) AND (@rOperation=1)
		BEGIN
			SELECT 'Enter proper value for Admission Class as per Admin Tool > Institute Setup > Class Master' AS StudentCode
		END
		ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE Religion COLLATE DATABASE_DEFAULT !='' COLLATE DATABASE_DEFAULT AND Religion COLLATE DATABASE_DEFAULT NOT IN(SELECT Title FROM sCommon.tReligionMaster WHERE OrgGroupId=@rOrgGroupId))
		BEGIN
			SELECT 'Enter proper value / Check spelling for Religion per Admin Tool > Master > Religion Master' AS StudentCode
		END
		ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE Gender COLLATE DATABASE_DEFAULT !='' COLLATE DATABASE_DEFAULT AND Gender COLLATE DATABASE_DEFAULT NOT IN(SELECT Title FROM sCommon.tGenderMaster))
		BEGIN
			SELECT 'Enter proper value / Check spelling for gender ( Male / Female )' AS StudentCode
		END
		ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE CastCategory COLLATE DATABASE_DEFAULT !='' COLLATE DATABASE_DEFAULT AND CastCategory COLLATE DATABASE_DEFAULT NOT IN(SELECT Title FROM sCommon.tCastCategoryMaster))
		BEGIN
			SELECT 'Enter proper value for Cast Category (OBC,SC,ST,GENERAL)' AS StudentCode
		END
		ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE (LeftDate IS NULL OR LeftDate COLLATE DATABASE_DEFAULT ='' COLLATE DATABASE_DEFAULT AND LeftStandard COLLATE DATABASE_DEFAULT !='' COLLATE DATABASE_DEFAULT) AND @lStatusId<>1) AND (@rOperation=1)
		BEGIN
			SELECT 'Left Date Should not be empty or check the date format' AS StudentCode
		END
		ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE (LCDate IS NULL OR LCDate COLLATE DATABASE_DEFAULT ='' COLLATE DATABASE_DEFAULT AND LeftStandard COLLATE DATABASE_DEFAULT !='' COLLATE DATABASE_DEFAULT) AND @lStatusId<>1)
		BEGIN
			SELECT 'LC Date Should not be empty or check the date format' AS StudentCode
		END
	
		--ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE  LeftStandard COLLATE DATABASE_DEFAULT NOT IN(SELECT Title FROM sSetup.tClassMaster WHERE OrgId=@rOrgId) AND @lLeftDate!='')
		--BEGIN
		--	SELECT 'Enter proper value for Left Standard as per Institute Setup > Class Master' AS StudentCode
		--END	
		--ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE LeftDate IS NULL OR LeftDate COLLATE DATABASE_DEFAULT ='' COLLATE DATABASE_DEFAULT AND LeftStandard COLLATE DATABASE_DEFAULT !='' COLLATE DATABASE_DEFAULT)
		--BEGIN
		--	SELECT 'LeftDate Should not be empty or check the date format' AS StudentCode
		--END
		ELSE
		BEGIN
	
		IF (@1NotExistStudentCode IS NOT NULL AND @1NotExistStudentCode COLLATE DATABASE_DEFAULT != '' COLLATE DATABASE_DEFAULT)
		BEGIN
		
			SET @1NotExistStudentCode = 'Not Exist Code ' + @1NotExistStudentCode
			Select @1NotExistStudentCode AS StudentCode
		END		
		
		
		SELECT @1DuplicateStudentCode=COALESCE(@1DuplicateStudentCode ,'') + Code + ',' FROM #tTable1 GROUP BY Code HAVING ( COUNT(Code) > 1 )	
		
	   
			
		SELECT @1DuplicateStudentSUId=COALESCE(@1DuplicateStudentSUId ,'') + SUId + ',' FROM #tTable1 GROUP BY SUId HAVING ( COUNT(SUId) > 1 )	
			IF(@1DuplicateStudentSUId IS NOT NULL AND @1DuplicateStudentSUId != '' AND @lIsActivateUniqueId=1)
				BEGIN
				
					SET @1DuplicateStudentSUId = 'Duplicate SUId ' + @1DuplicateStudentSUId
					SELECT @1DuplicateStudentSUId AS StudentCode
				END
			ELSE IF(@1DuplicateStudentCode IS NOT NULL AND @1DuplicateStudentCode COLLATE DATABASE_DEFAULT != '' COLLATE DATABASE_DEFAULT)
				BEGIN
				  
					SET @1DuplicateStudentCode = 'Duplicate Code ' + @1DuplicateStudentCode
					
					SELECT @1DuplicateStudentCode AS StudentCode
				END
			ELSE			
				BEGIN
				SELECT @1DuplicateStudentRegistrationNumber=COALESCE(@1DuplicateStudentRegistrationNumber ,'') + CONVERT(VARCHAR(20),RegistrationNumber) + ',' FROM #tTable1 GROUP BY RegistrationNumber HAVING ( COUNT(RegistrationNumber) > 1 AND ISNULL(RegistrationNumber,'')!='')	
				IF(@1DuplicateStudentRegistrationNumber IS NOT NULL AND @1DuplicateStudentRegistrationNumber  COLLATE DATABASE_DEFAULT != '' COLLATE DATABASE_DEFAULT)
				BEGIN
					SET @1DuplicateStudentRegistrationNumber = 'Duplicate Registration Number ' + @1DuplicateStudentRegistrationNumber
					SELECT @1DuplicateStudentRegistrationNumber AS StudentCode
				END
		
		ELSE IF (@1DuplicateAdhaarNumber IS NOT NULL AND @1DuplicateAdhaarNumber COLLATE DATABASE_DEFAULT != '' COLLATE DATABASE_DEFAULT)
		BEGIN
		  
			SET @1DuplicateAdhaarNumber = 'Exist Adhaar Number ' + @1DuplicateAdhaarNumber
			Select @1DuplicateAdhaarNumber AS StudentCode
		END
		
		
		ELSE IF (@1DuplicateUIDNumber IS NOT NULL AND @1DuplicateUIDNumber COLLATE DATABASE_DEFAULT != '' COLLATE DATABASE_DEFAULT AND @lIsStudentUIDNumberUnique='True') --add
		BEGIN
			SET @1DuplicateUIDNumber = 'Exist UID Number ' + @1DuplicateUIDNumber
			Select @1DuplicateUIDNumber AS StudentCode
		END
		
		
		ELSE IF((@1ExistStudentSUId IS NULL OR @1ExistStudentSUId = '' OR @lIsActivateUniqueId=0) AND (@1ExistStudentCode IS NULL OR @1ExistStudentCode = '') AND (@1ExistStudentRegistrationNumber IS NULL OR @1ExistStudentRegistrationNumber = '')
		AND (@1ValidAdmissionDate IS NULL OR @1ValidAdmissionDate = '') AND (@1ValidDOB IS NULL OR @1ValidDOB = ''))
		BEGIN
		
			SELECT '' AS StudentCode
		END
		ELSE IF (@1ExistStudentSUId IS NOT NULL AND @1ExistStudentSUId != '' AND @lIsActivateUniqueId=1)
		BEGIN
			SET @1ExistStudentSUId = 'Exist SUId ' + @1ExistStudentSUId
			Select @1ExistStudentSUId AS StudentCode
		END
		
		
		
		
		ELSE IF (@1ExistStudentCode IS NOT NULL AND @1ExistStudentCode COLLATE DATABASE_DEFAULT != '' COLLATE DATABASE_DEFAULT)
		BEGIN
			SET @1ExistStudentCode = 'Exist Code ' + @1ExistStudentCode
			Select @1ExistStudentCode AS StudentCode
		END
		
		ELSE IF (@1ExistStudentRegistrationNumber IS NOT NULL AND @1ExistStudentRegistrationNumber COLLATE DATABASE_DEFAULT != '' COLLATE DATABASE_DEFAULT)
		BEGIN
			SET @1ExistStudentRegistrationNumber = 'Exist Registration Number ' + @1ExistStudentRegistrationNumber
			Select @1ExistStudentRegistrationNumber AS StudentCode
		END
		ELSE IF (@1ValidAdmissionDate IS NOT NULL AND @1ValidAdmissionDate != '')
		BEGIN
			SET @1ValidAdmissionDate = 'Wrong Admission Date ' + @1ValidAdmissionDate
			Select @1ValidAdmissionDate AS StudentCode
		END
		ELSE IF (@1ValidDOB IS NOT NULL AND @1ValidDOB != '')
		BEGIN
			SET @1ValidDOB = 'Wrong DOB ' + @1ValidDOB
			Select @1ValidDOB AS StudentCode
		END
		ELSE IF (@1ValidLeftDate IS NOT NULL AND @1ValidLeftDate != '' AND @lLCDate!='')
		BEGIN
			SET @1ValidLeftDate = 'Wrong LeftDate ' + @1ValidLeftDate
			Select @1ValidLeftDate AS StudentCode
		END
		ELSE IF (@1ValidLCDate IS NOT NULL AND @1ValidLCDate != '' AND @lLCDate!='')
		BEGIN
			SET @1ValidLCDate = 'Wrong LCDate ' + @1ValidLCDate
			Select @1ValidLCDate AS StudentCode
		END
		
		ELSE IF (@lIsSurnameAndFatherNameMandatory = 'True' )
		BEGIN
			IF EXISTS(SELECT 1 fROM #tTable1 WHERE MiddleName IS NULL OR MiddleName COLLATE DATABASE_DEFAULT='' COLLATE DATABASE_DEFAULT)
			BEGIN
				SELECT 'FatherName Should not be empty' AS StudentCode
			END
			IF EXISTS(SELECT 1 fROM #tTable1 WHERE LastName IS NULL OR LastName COLLATE DATABASE_DEFAULT='' COLLATE DATABASE_DEFAULT)
			BEGIN
				SELECT 'Surname Should not be empty' AS StudentCode
			END
			ELSE 
			BEGIN
				SELECT '' AS StudentCode
			END
						
		END



		END
		END
END
GO
PRINT N'Altering Procedure [sTally].[pReceiptPostingGet]...';


GO

ALTER PROCEDURE [sTally].[pReceiptPostingGet]

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

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

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

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

					WHERE	FR.ReceiptBookId= @rReceiptBookId 
							AND FR.IsObsolete = 0 
							AND FR.OrgGroupBatchId = @rOrgGroupBatchId
							AND FR.ReceiptDate >= @rReceiptDate AND FR.ReceiptDate <= @rToReceiptDate
							AND (FR.PayTypeId = @rPayTypeId OR @rPayTypeId = 0)
				group by ReceiptDate,PM.Title,FR.PayTypeId,FR.Id,isnull(FR.ReceiptNumber,'') , BatchName,ISNULL(FR.BankName,''),ISNULL(FR.ChequeNo,'')
				Order By FR.Id,ReceiptDate Desc
			END			
			
END
GO
PRINT N'Altering Procedure [sTally].[pReceiptTallyPostingAdd]...';


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

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

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

	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering Procedure [sTimetable].[pImportTimeTableSetup]...';


GO
 
ALTER PROCEDURE [sTimetable].[pImportTimeTableSetup]
	 
	@rToTimeTableSchemaId int,
	@rFromTimeTableSchemaId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN

	 
	 -- Division Work Load  	   
	 IF NOT EXISTS(SELECT 1 FROM sTimetable.tDivisionWorkLoad WHERE TimeTableSchemaID=@rFromTimeTableSchemaId) 	--- Exists --> Not Exists Put By Dhruv For Issue No. 0011093
	 BEGIN   	    
	    SELECT -101 AS Result
	    RETURN;
	 END
	 
	 -- Teacher Work Load 
	 IF NOT EXISTS(SELECT 1 FROM sTimetable.tTeacherWorkLoad WHERE TimeTableSchemaID=@rFromTimeTableSchemaId) 	   
	 BEGIN
	    SELECT -102 AS Result
	    RETURN;
	 END
	 
	 -- Time Setup
	 IF NOT EXISTS(SELECT 1 FROM sTimetable.tTimeSetup WHERE TimeTableSchemaID=@rFromTimeTableSchemaId) 
	 BEGIN	   
	    SELECT -103 AS Result
	    RETURN;
	 END
	 -- Time Table
	 IF NOT EXISTS(SELECT 1 FROM sTimetable.tTimeTable WHERE TimeTableSchemaID=@rFromTimeTableSchemaId) 	
	 BEGIN   
	    SELECT -104 AS Result
	    RETURN;
	 END
	 
	BEGIN TRY	
	BEGIN TRANSACTION 

	DECLARE @lOrgGroupId int=0, @lOrgGroupBatchId int=0	
	SELECT @lOrgGroupBatchId=OrgGroupBatchId FROM sTimetable.tTimeTableSchema WHERE Id = @rToTimeTableSchemaId
	SELECT @lOrgGroupId=OrgGroupId FROM sSetup.tOrgGroupBatchMaster WHERE Id = @lOrgGroupBatchId

	-- Division Work Load
	DELETE FROM sTimetable.tDivisionWorkLoad where TimeTableSchemaId = @rToTimeTableSchemaId 
	INSERT INTO sTimetable.tDivisionWorkLoad
	(BatchId,DivisionId,SubjectId,NoOfLecture,CreatedUserId,CreatedDateTime,TimeTableSchemaId)
	SELECT [sTimeTable].[fNextBatchIdGet](BatchId,@lOrgGroupBatchId),DivisionId,SubjectId,NoOfLecture,CreatedUserId,[sCommon].[fGetDate](),@rToTimeTableSchemaId 
	FROM sTimetable.tDivisionWorkLoad 
	WHERE TimeTableSchemaId = @rFromTimeTableSchemaId
	
	
	-- Teacher Work Load	
	DELETE FROM sTimetable.tTeacherWorkLoad WHERE TimeTableSchemaId=@rToTimeTableSchemaId
	INSERT INTO sTimetable.tTeacherWorkLoad(BatchId,EmployeeId,DivisionId,SubjectId,NoOfLecture,CreatedUserId,CreatedDateTime,TimeTableSchemaId)
	SELECT [sTimeTable].[fNextBatchIdGet](BatchId,@lOrgGroupBatchId),EmployeeId,DivisionId,SubjectId,NoOfLecture,CreatedUserId,[sCommon].[fGetDate](),@rToTimeTableSchemaId 
	FROM sTimetable.tTeacherWorkLoad 
	WHERE TimeTableSchemaId = @rFromTimeTableSchemaId
	
	
	-- Time Setup
	DELETE FROM sTimetable.tTimeSetup WHERE TimeTableSchemaId = @rToTimeTableSchemaId
	
	INSERT INTO sTimetable.tTimeSetup
	(ClassId,DayId,NoOfPeriod,BatchId,TimeTableSchemaId)
	SELECT 
	ClassId,DayId,NoOfPeriod,ISNULL([sTimeTable].[fNextBatchIdGet](BatchId,@lOrgGroupBatchId),''),@rToTimeTableSchemaId 
	FROM sTimetable.tTimeSetup WHERE Timetableschemaid = @rFromTimeTableSchemaId
	
	
	CREATE TABLE #TempTimeTable
	(
		[AutoId] int identity,
		[Id] [int] NOT NULL,
		[TimeTableSchemaId] [int] NOT NULL,
		[EmployeeId] [bigint] NOT NULL,
		[DivisionId] [int] NOT NULL,
		[SubjectId] [int] NOT NULL,
		[DayId] [tinyint] NOT NULL,
		[LectureNumber] [tinyint] NOT NULL,
		[LockNo] [bigint] NULL,
		[LockColour] [varchar](50) NULL,
		[SchoolRoomId] [int] NULL,
		[IsBreak] [bit] NULL,
		[IsMergeDivision] [bit] NULL,
		[IsBreakBefore] [bit] NULL
	)
	
	INSERT INTO #TempTimeTable SELECT * FROM sTimetable.tTimeTable WHERE Timetableschemaid = @rFromTimeTableSchemaId
	
	DECLARE @lCount int
	SELECT @lCount = COUNT(Id) FROM #TempTimeTable
	
	DELETE TD FROM sTimetable.tTimeTable T 	INNER JOIN sTimetable.tTimeTableDetail TD ON T.Id = TD.TimeTableId WHERE T.TimeTableSchemaId = @rToTimeTableSchemaId
	DELETE FROM sTimetable.tTimeTable WHERE TimeTableSchemaId = @rToTimeTableSchemaId
	
	WHILE (@lCount > 0)
	BEGIN
		DECLARE @lNextNumber BIGINT
		EXECUTE sCommon.pTableRowIdGet @lOrgGroupId, 'sTimetable.tTimeTable', 0, 1, 1,@outNextNumber = @lNextNumber output 
		DECLARE @lTimeTableId int =0
		SELECT @lTimeTableId=Id FROM #TempTimeTable WHERE AutoId = @lCount
		
		-- Time Table
		INSERT INTO sTimetable.tTimeTable
		(Id,TimeTableSchemaId,EmployeeId,DivisionId,SubjectId,DayId,LectureNumber,LockNo,LockColour,SchoolRoomId,IsBreak,IsMergeDivision,IsBreakBefore)
		SELECT 
		@lNextNumber,@rToTimeTableSchemaId,EmployeeId,DivisionId,SubjectId,DayId,LectureNumber,LockNo,LockColour,SchoolRoomId,IsBreak,IsMergeDivision,IsBreakBefore
		FROM #TempTimeTable  WHERE AutoId = @lCount
	
		DECLARE @lTimeTableDetailId int
		SELECT @lTimeTableDetailId=TimetableId FROM sTimetable.tTimeTableDetail WHERE TimetableId=@lTimeTableId
		
		-- Time Table Detail
		IF(@lTimeTableDetailId IS NOT NULL)
		BEGIN
			INSERT INTO sTimetable.tTimeTableDetail
			(TimetableId,EmployeeId,SubjectId,SchoolRoomId)
			SELECT 
			@lNextNumber,EmployeeId,SubjectId,SchoolRoomId
			FROM sTimetable.tTimeTableDetail WHERE TimetableId = @lCount
		END
		
		SET @lCount = @lCount -1
	END

	--Add By Nimesh Mantis:0027685
	--Start
	DELETE FROM sTimetable.tTimeTableTime WHERE TimeTableSchemaId = @rToTimeTableSchemaId
	INSERT INTO sTimetable.tTimeTableTime ([TimeTableSchemaId],[DivisionId],[DayId],[LectureNumber],[FromTime] ,[ToTime],[IsBreak],[IsBreakBefore])
	SELECT @rToTimeTableSchemaId,[DivisionId],[DayId],[LectureNumber],[FromTime],[ToTime],[IsBreak],[IsBreakBefore] FROM [sTimetable].[tTimeTableTime] where  Timetableschemaid = @rFromTimeTableSchemaId
	--End
	SELECT 1 AS Result
	
	 COMMIT TRANSACTION
	 END TRY
	
	 BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	 END CATCH	
END
GO
PRINT N'Altering Procedure [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

DELETE FROM sSystem.tTimeZone
DELETE FROM sTool.tTestCaseTypeMaster

DELETE FROM sAlumni.tEmployeementType

DELETE FROM sErp.tCampusTypeMaster

DELETE FROM sAlert.tMailTypeMaster
DELETE FROM sAlert.tSMSVendorMaster
DELETE FROM sCommon.tWeekOffRules

DELETE FROM sSecurity.tScreenHelp
DELETE FROM sSystem.tSettingInfo

DELETE FROM sProcurement.tOtherLocationSourceTypeMaster

DELETE FROM sCommon.tFieldTypeMaster
DELETE FROM sErp.tLeadInfrastructureMaster

DELETE FROM sHostel.tHostelEventMainTypeMaster

DELETE FROM sCertificate.tCertificateTypeMaster	
DELETE FROM sWorkflow.tActionStatusMaster
DELETE FROM sWorkflow.tApprovingDepartmentMaster
DELETE FROM sWorkflow.tWorkflowFunctionalityMaster

DELETE FROM sAcademic.tHomeworkCheckStatusMaster
DELETE FROM sAssessment.tExamTypeMaster

DELETE FROM sErp.tMarketingActivityMaster
DELETE FROM sErp.tMarketingSubActivityMaster
DELETE FROM sSetup.tCommonOrgGroupBatchMaster
DELETE FROM sWorkflow.tWorkflowFunctionalityMaster

DELETE FROM sAudit.tOperationMaster

DELETE FROM sAdmission.tInquiryMainStatusMaster
DELETE FROM sCertificate.tPrintTemplateFunctionalityMaster
DELETE FROM sErp.tTripLogStatusMaster

DELETE FROM sErp.tFollowupTypeMaster
DELETE FROM sErp.tSupportCategoryMaster
DELETE FROM sErp.tSupportPriorityMaster
DELETE FROM sErp.tSupportTicketStatusMaster


DELETE FROM sErp.tPlugInMaster
DELETE FROM sErp.tTagMaster

DELETE FROM sErp.tIssueTypeMaster

DELETE FROM sErp.tScreenFunctionalityMaster

DELETE FROM sHrm.tChangeTypeMaster


DELETE FROM sCommon.tDataMaster
DELETE FROM sCommon.tDataTypeMaster

DELETE FROM siTax.tStaticIncomeTaxSubSubGroup

DELETE FROM sCommunication.tStudentDocumentTypeMaster

DELETE FROM sCommon.tUploadFunctionalityMaster
DELETE FROM sCommunication.tEmployeeDocumentTypeMaster

DELETE FROM sErp.tCustomerMessageTypeMaster

DELETE FROM sActivity.tActivityMainTypeMaster
DELETE FROM sSecurity.tTraceabilityMaster
DELETE FROM sSecurity.tTraceabilityTrack

DELETE FROM sSecurity.tScreenScopeDetails
DELETE FROM sBiometric.tEmployeeConfigurationMaster
DELETE FROM sSetup.tEmployeeNameFormatMaster
DELETE FROM sStudent.tOnlineRegistrationDisplayFieldMaster

DELETE FROM sSetup.tFormTypeMaster
DELETE FROM sSetup.tFormButtonMaster

DELETE FROM sSecurity.tSysSuperScreen
DELETE FROM sAppraisal.tKPAStatus
DELETE FROM sAttendance.tPeriodNoMaster

END
GO
PRINT N'Altering Procedure [sTool].[pUpgradeVersion]...';


GO
ALTER PROCEDURE [sTool].[pUpgradeVersion]
	 
	@rVersionId int,
	@rVersion nvarchar(20),
	@rOrgGroupId int

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

if 	@rVersionId = 0
BEGIN
SELECT 'Enter Version Id'
return	
END


if 	@rVersion = ''
BEGIN
SELECT 'Enter Version Detail'
return	
END

if 	@rOrgGroupId = 0
BEGIN
SELECT 'Enter Org Group Id'
return	
END



--if 	@rOrgGroupId = 1
--BEGIN
--SELECT '1 OrgGroup Not Valid'
--return	
--END

IF NOT EXISTS (SELECT 1 FROM sSetup.tOrgGroupMaster WHERE Id = @rOrgGroupId)
BEGIN
SELECT 'Org Group Not Exists'
return	
END

-- For Upgrade Vesion Start
INSERT INTO [sSystem].[tVersionUpdate] ([VersionNumber],[VersionId],[Status],[UpdateScript],[StartDateTime],[EndDateTime],[OrgGroupId])
VALUES(@rVersion,@rVersionId,'BEGIN','Upgrade Vesion',sCommon.fGetDate(),sCommon.fGetDate(),@rOrgGroupId)

--exec [sTool].[pInsertStaticData]
		
-- add newly added task for admin role
exec [sSecurity].[pNewTaskAdd] @rOrgGroupId

-- update tablerowid master data from excel to table

--pass orgGroupId
-- add new table row ids added
exec [sTool].[pTableRowIdAdd] @rOrgGroupId

-- Pass OrgGroupId
-- Remove tablrowid for organization
--exec sTool.pTableRowChangeOrgToOrgGroupRemove @rOrgGroupId

update sstudent.tAcademic   set rollno = 0 where RollNo is null



delete from sSecurity.tPermission where TaskId in (select ID from sSecurity.tTask where IsObsolete = 1)
delete from sSecurity.tPermission where TaskId not in (select ID from sSecurity.tTask)




exec [sTool].[pTableRowIdCurrentNumberSet] @rOrgGroupId

IF NOT EXISTS(SELECT 1 FROM sCommunication.teContentTypeMaster WHERE Id = sCommon.fGetIntIdForOrg(1,@rOrgGroupId))
 BEGIN
				INSERT INTO sCommunication.teContentTypeMaster
					   ([Id]
					   ,[Code]
					   ,[Title]
					   ,[IsObsolete]
					   ,[CreatedUserId]
					   ,[CreatedDateTime]
					   ,[UpdatedUserId]
					   ,[UpdatedDateTime]
					   ,[OrgGroupId])
				 SELECT
						 sCommon.fGetIntIdForOrg(1,@rOrgGroupId)
						,'Subject'
						,'Subject'
						,0
						,1
						,getdate()
						,1
						,getdate()
						,@rOrgGroupId
						
 END


IF NOT EXISTS(SELECT 1 FROM sCommunication.tCircularTypeMaster WHERE Id = sCommon.fGetIntIdForOrg(1,@rOrgGroupId))
 BEGIN
				INSERT INTO sCommunication.tCircularTypeMaster
					   ([Id]
					   ,[Code]
					   ,[Title]
					   ,[IsObsolete]
					   ,[CreatedUserId]
					   ,[CreatedDateTime]
					   ,[UpdatedUserId]
					   ,[UpdatedDateTime]
					   ,[OrgGroupId]
					   ,HighlightColor)
				 SELECT
						 sCommon.fGetIntIdForOrg(1,@rOrgGroupId)
						,'Circular'
						,'Circular'
						,0
						,1
						,getdate()
						,1
						,getdate()
						,@rOrgGroupId
						,NULL
 END

IF NOT EXISTS(SELECT 1 FROM sCommon.tPublishDocumentMaster WHERE Id = sCommon.fGetIntIdForOrg(1,@rOrgGroupId))
BEGIN				
				INSERT INTO sCommon.tPublishDocumentMaster
					   ([Id]
					   ,[Code]
					   ,[Title]
					   ,[IsObsolete]
					   ,[CreatedUserId]
					   ,[CreatedDateTime]
					   ,[UpdatedUserId]
					   ,[UpdatedDateTime]
					   ,[OrgGroupId])
				 VALUES
						(sCommon.fGetIntIdForOrg(1,@rOrgGroupId),'Fee Receipt','Fee Receipt',0,1,Getdate(),1,Getdate(),@rOrgGroupId),
						(sCommon.fGetIntIdForOrg(2,@rOrgGroupId),'Bonafide','Bonafide',0,1,Getdate(),1,Getdate(),@rOrgGroupId),
						(sCommon.fGetIntIdForOrg(3,@rOrgGroupId),'Trial','Trial',0,1,Getdate(),1,Getdate(),@rOrgGroupId),
						(sCommon.fGetIntIdForOrg(4,@rOrgGroupId),'Charactor','Charactor',0,1,Getdate(),1,Getdate(),@rOrgGroupId),
						(sCommon.fGetIntIdForOrg(5,@rOrgGroupId),'Id Card','Id Card',0,1,Getdate(),1,Getdate(),@rOrgGroupId)
						
END


IF NOT EXISTS(SELECT 1 FROM sAdmission.tInquiryStatusMaster WHERE OrgGroupId = @rOrgGroupId)
BEGIN				
				INSERT INTO sAdmission.tInquiryStatusMaster
					   ([Id]
					   ,[Code]
					   ,[Title]
					   ,[IsObsolete]
					   ,[CreatedUserId]
					   ,[CreatedDateTime]
					   ,[UpdatedUserId]
					   ,[UpdatedDateTime]
					   ,[OrgGroupId]
					   ,StatusId
					   --,HighlightColor
					   --,InquiryMainStatusId
					   )
				 SELECT
						 sCommon.fGetIntIdForOrg(Id,@rOrgGroupId)
						,Title
						,Title
						,0
						,1
						,getdate()
						,NULL
						,NULL
						,@rOrgGroupId
						,Id	
						--,ISM.HighlightColor
						--,ISM.InquiryMainStatusId					
						FROM sCommon.tStatusMaster
						--INNER JOIN sAdmission.tInquiryStatusMaster ISM ON SM.Id = ISM.StatusId AND ISM.OrgGroupId = 1
						where statustypeId = 104


						UPDATE ISM  
							SET ISM.HighlightColor = ISM1.HighlightColor ,
								ISM.InquiryMainStatusId = ISM1.InquiryMainStatusId
							FROM sAdmission.tInquiryStatusMaster ISM  
							INNER JOIN sAdmission.tInquiryStatusMaster ISM1 ON ISM.StatusId = ISM1.StatusId AND ISM1.OrgGroupId = 1
							INNER JOIN sCommon.tStatusMaster SM ON SM.Id = ISM1.StatusId 
							where SM.statustypeId = 104 AND ISM.OrgGroupId = @rOrgGroupId

						
	DECLARE @lMaxId int
	SET @lMaxId = sCommon.fGetIntIdForOrg(213,@rOrgGroupId)					
	EXECUTE sCommon.pTableRowIdModify @rOrgGroupId, @rTableTitle = 'sAdmission.tInquiryStatusMaster', @rCurrentNumber = @lMaxId
						
END

--static entry in tVisitorTypeMaster

IF NOT EXISTS(SELECT 1 FROM sFrontOffice.tVisitorTypeMaster WHERE Id = 1)
BEGIN	
	INSERT INTO [sFrontOffice].[tVisitorTypeMaster]
           ([Id]
           ,[Code]
           ,[Title]
           ,[IsObsolete]
           ,[CreatedUserId]
           ,[CreatedDateTime]
           ,[UpdatedUserId]
           ,[UpdatedDateTime]
           ,[OrgGroupId])
     VALUES
           (1,
		   'Visitor',
		   'Visitor',
		   0,
		   1,
		   GetDate(),
		   NULL,
		   NULL,
		   1)
END

IF NOT EXISTS(SELECT 1 FROM sFrontOffice.tVisitorTypeMaster WHERE Id = 2)
BEGIN	
	INSERT INTO [sFrontOffice].[tVisitorTypeMaster]
           ([Id]
           ,[Code]
           ,[Title]
           ,[IsObsolete]
           ,[CreatedUserId]
           ,[CreatedDateTime]
           ,[UpdatedUserId]
           ,[UpdatedDateTime]
           ,[OrgGroupId])
     VALUES
           (2,
		   'Parents',
		   'Parents',
		   0,
		   1,
		   GetDate(),
		   NULL,
		   NULL,
		   1)
END

--OrgGoup wise VisitorTypeMaster entry
IF NOT EXISTS(SELECT 1 FROM sFrontOffice.tVisitorTypeMaster WHERE OrgGroupId = @rOrgGroupId AND Id = sCommon.fGetIntIdForOrg(1,@rOrgGroupId))
BEGIN
	INSERT INTO [sFrontOffice].[tVisitorTypeMaster]
			   (
			    [Id]
			   ,[Code]
			   ,[Title]
			   ,[IsObsolete]
			   ,[CreatedUserId]
			   ,[CreatedDateTime]
			   ,[UpdatedUserId]
			   ,[UpdatedDateTime]
			   ,[OrgGroupId])
		 VALUES
			   (
			   sCommon.fGetIntIdForOrg(1,@rOrgGroupId),
			   'Visitor',
			   'Visitor',
			   0,
			   --1,
			   [sCommon].[fGetBigIntIdForOrg](3,@rOrgGroupId),
			   GetDate(),
			   NULL,
			   NULL,
			   @rOrgGroupId)
END

IF NOT EXISTS(SELECT 1 FROM sFrontOffice.tVisitorTypeMaster WHERE OrgGroupId = @rOrgGroupId AND Id = sCommon.fGetIntIdForOrg(2,@rOrgGroupId))
BEGIN
	INSERT INTO [sFrontOffice].[tVisitorTypeMaster]
			   (
			    [Id]
			   ,[Code]
			   ,[Title]
			   ,[IsObsolete]
			   ,[CreatedUserId]
			   ,[CreatedDateTime]
			   ,[UpdatedUserId]
			   ,[UpdatedDateTime]
			   ,[OrgGroupId])
		 VALUES
			   (
			   sCommon.fGetIntIdForOrg(2,@rOrgGroupId),
			   'Parents',
			   'Parents',
			   0,
			   --1,
			   [sCommon].[fGetBigIntIdForOrg](3,@rOrgGroupId),
			   GetDate(),
			   NULL,
			   NULL,
			   @rOrgGroupId)
END

IF NOT EXISTS(SELECT 1 FROM sCommon.tCastCategoryMaster WHERE OrgGroupId = @rOrgGroupId)
BEGIN				
				INSERT INTO sCommon.tCastCategoryMaster
					   ([Id]
					   ,[Number]
					   ,[Code]
					   ,[Title]
					   ,[IsObsolete]
					   ,[CreatedUserId]
					   ,[CreatedDateTime]
					   ,[UpdatedUserId]
					   ,[UpdatedDateTime]
					   ,[OrgGroupId]
					   , MainCastCategoryId 
					   ,OrderIndex)
				 SELECT
						 sCommon.fGetIntIdForOrg(Id,@rOrgGroupId)
						,Id	
						,Code
						,Title
						,0
						,1
						,getdate()
						,1
						,getdate()
						,@rOrgGroupId
						,Id
						,Id						
						FROM sCommon.tMainCastCategoryMaster
						 
						
	DECLARE @lMaxCatId int
	SET @lMaxCatId = sCommon.fGetIntIdForOrg(100,@rOrgGroupId)					
	EXECUTE sCommon.pTableRowIdModify @rOrgGroupId, @rTableTitle = 'sCommon.tCastCategoryMaster', @rCurrentNumber = @lMaxCatId

UPDATE
    o
SET
    o.CastCategoryId	=  sCommon.fGetIntIdForOrg(o.CastCategoryId,@rOrgGroupId)
FROM
    sStudent.tStudentOther o
    INNER JOIN
    sStudent.tStudentMaster S ON S.Id = o.StudentId
WHERE
o.CastCategoryId < 100 
AND CastCategoryId IS NOT NULL
AND S.OrgId IN (SELECT Id From sSetup.tOrganizationMaster WHERE OrgGroupId = @rOrgGroupId)		
			
UPDATE sAdmission.tAdmissionForm SET CastCategoryId	= sCommon.fGetIntIdForOrg(CastCategoryId,@rOrgGroupId)	
WHERE CastCategoryId IS NOT NULL AND CastCategoryId < 100 
AND OrgId IN (SELECT Id From sSetup.tOrganizationMaster WHERE OrgGroupId = @rOrgGroupId)

UPDATE sCommon.tFamiliyCastMaster SET 	CastCategoryId	=  sCommon.fGetIntIdForOrg(CastCategoryId,@rOrgGroupId)	
WHERE CastCategoryId IS NOT NULL AND CastCategoryId < 100   AND OrgGroupId = @rOrgGroupId

UPDATE sCommon.tSurnameMaster SET 	CastCategoryId	=  sCommon.fGetIntIdForOrg(CastCategoryId,@rOrgGroupId)	
WHERE CastCategoryId IS NOT NULL AND CastCategoryId < 100 AND OrgGroupId = @rOrgGroupId
			
			
END


IF NOT EXISTS(SELECT 1 FROM sTransport.tTransportMaster WHERE OrgGroupId = @rOrgGroupId)
BEGIN				
				INSERT INTO sTransport.tTransportMaster
					   ([Id]
					   ,[Number]
					   ,[Code]
					   ,[Title]
					   ,[IsObsolete]
					   ,[CreatedUserId]
					   ,[CreatedDateTime]
					   ,[UpdatedUserId]
					   ,[UpdatedDateTime]
					   ,[OrgGroupId]					    
					   )
				 SELECT
						 sCommon.fGetIntIdForOrg(1,@rOrgGroupId)
						,1
						,'Common'
						,'Common'
						,0
						,1
						,getdate()
						,1
						,getdate()
						,@rOrgGroupId
						 
		DECLARE @lMaxTranId int
	SET @lMaxTranId = sCommon.fGetIntIdForOrg(1,@rOrgGroupId)					
	EXECUTE sCommon.pTableRowIdModify @rOrgGroupId, @rTableTitle = 'sTransport.tTransportMaster', @rCurrentNumber = @lMaxTranId
						 
					 				
	INSERT INTO sTransport.tAssignTransportOrg
					   (TransportId
					   ,OrgId					    				    
					   )
	SELECT 		
	@lMaxTranId
	,Id
	FROM
	sSetup.tOrganizationMaster
	WHERE OrgGroupId = 		@rOrgGroupId	 
						 
						

UPDATE sTransport.tBusRouteMaster
SET TransportId = @lMaxTranId WHERE OrgGroupId = @rOrgGroupId

UPDATE sTransport.tVehicleMaster
SET TransportId = @lMaxTranId WHERE OrgGroupId = @rOrgGroupId


			
			
END


IF NOT EXISTS(SELECT 1 FROM sSetup.tBatchGroupMaster WHERE OrgGroupId = @rOrgGroupId AND Id =  sCommon.fGetIntIdForOrg(1,@rOrgGroupId))
BEGIN				
				INSERT INTO sSetup.tBatchGroupMaster
					   ([Id]
					   ,[Number]
					   ,[Code]
					   ,[Title]
					   ,[OrgGroupId]					    
					   ,[OrderIndex]
					   ,[CreatedUserId]
					   ,[CreatedDateTime]
					   ,[UpdatedUserId]
					   ,[UpdatedDateTime]
					   )
				 SELECT
						 sCommon.fGetIntIdForOrg(1,@rOrgGroupId)
						,1
						,'Common'
						,'Common'
						,@rOrgGroupId
						,1
						
						,1
						,getdate()
						,1
						,getdate()
						
						 
	--DECLARE @lBatchGroupId int
	--SET @lMaxTranId = sCommon.fGetIntIdForOrg(1,@rOrgGroupId)					
	--EXECUTE sCommon.pTableRowIdModify @rOrgGroupId, @rTableTitle = 'sSetup.tBatchGroupMaster', @rCurrentNumber = @lBatchGroupId
	
	UPDATE B    
	SET BatchGroupId = sCommon.fGetIntIdForOrg(1,@rOrgGroupId)
	FROM sSetup.tBatchMaster B INNER JOIN sSetup.tOrganizationMaster O ON B.OrgId = O.ID
	WHERE O.OrgGroupId = @rOrgGroupId AND B.BatchGroupId IS NULL

END


UPDATE sSetup.tClassMaster SET DepartmentId = sCommon.fGetIntIdForOrg(OrgId,1) where DepartmentId is null

if (@rOrgGroupId <> 1154)
BEGIN
UPDATE sCommon.tReport SET IsObsolete = 1
 Where Id in (20642,20643,20644,20645,20646,20647,20648,20649,20650,20665,20718,20779,20692,20693,20694)

END

UPDATE sSystem.tDatabaseInfo SET ApplicationId = 1

UPDATE sSystem.tDatabaseInfo SET 
VersionNumber = @rVersion,
VersionId = @rVersionId,
LastVersionUpdateDateTime = getdate() ,
IsNewVersion = 1
WHERE ApplicationId = 1 
 
-- for student - remove permission for employee center
DECLARE @lRoleId int = 0
DECLARE @lDefaultRoleId int = 10
SET @lRoleId = (@rOrgGroupId * 100000) + @lDefaultRoleId
 
--DELETE P FROM sSecurity.tPermission P INNER JOIN sSecurity.tTask T ON P.TaskId = T.Id 
--WHERE P.RoleId = @lRoleId AND P.OrgGroupId=@rOrgGroupId AND T.ModuleId =  234

---- for employee - remove permisiion for student center
--SET @lDefaultRoleId = 22
--SET @lRoleId = (@rOrgGroupId * 100000) + @lDefaultRoleId
--DELETE P FROM sSecurity.tPermission P INNER JOIN sSecurity.tTask T ON P.TaskId = T.Id 
--WHERE P.RoleId = @lRoleId AND P.OrgGroupId=@rOrgGroupId AND T.ModuleId =  233

-- for SysSuperAdmin
SET @lDefaultRoleId = 1
SET @lRoleId = (@rOrgGroupId * 100000) + @lDefaultRoleId
DELETE P FROM sSecurity.tPermission P INNER JOIN sSecurity.tTask T ON P.TaskId = T.Id 
WHERE P.RoleId = @lRoleId AND P.OrgGroupId=@rOrgGroupId
AND T.Id IN (30258,30262,30266,30257,30160,30243,30244)

IF NOT EXISTS (SELECT 1 FROM sSecurity.tOrganizationTask  T   WHERE TaskId = 20596  AND OrgGroupId = @rOrgGroupId)
BEGIN
	INSERT INTO sSecurity.tOrganizationTask 
	(OrgGroupId, TaskId, AvailablePermission)
	SELECT  @rOrgGroupId,20596,2
END

--default permission for Lesson Plan Complete Task for Admin only (for execute permission)
IF NOT EXISTS (SELECT 1 FROM sSecurity.tOrganizationTask  T   WHERE TaskId = 31244  AND OrgGroupId = @rOrgGroupId)
BEGIN
	INSERT INTO sSecurity.tOrganizationTask 
	(OrgGroupId, TaskId, AvailablePermission)
	SELECT  @rOrgGroupId,31244,64
END

IF NOT EXISTS (SELECT * FROM sSecurity.tPermission   WHERE RoleId =sCommon.fGetIntIdForOrg(2,@rOrgGroupId) AND TaskId = 20596  AND OrgGroupId = @rOrgGroupId)
BEGIN
	INSERT INTO sSecurity.tPermission(TaskId, RoleId, Permission, IsObsolete, CreatedUserId, CreatedDateTime, UpdatedUserId, UpdatedDateTime,OrgGroupId)
	SELECT  20596,sCommon.fGetIntIdForOrg(2,@rOrgGroupId),2,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId
	FROM sSecurity.tOrganizationTask WHERE OrgGroupId = @rOrgGroupId
END

---- for SysSuperAdmin update password
--UPDATE sSecurity.tUser SET LoginPassword='XAqFcL/nd0bnDNhkyF/PxobplNJ+ggbN9370AHxj7oU=' WHERE Id = sCommon.fGetBigIntIdForOrg(1,@rOrgGroupId)
--UPDATE sSecurity.tUser SET LoginPassword='XAqFcL/nd0bnDNhkyF/PxobplNJ+ggbN9370AHxj7oU=' WHERE Id = 1

-- for SysSuperAdmin update password
--UPDATE sSecurity.tUser SET LoginPassword='FxYuAuSiWcl4MZWDctl++A==' WHERE Id = sCommon.fGetBigIntIdForOrg(1,@rOrgGroupId)
--UPDATE sSecurity.tUser SET LoginPassword='FxYuAuSiWcl4MZWDctl++A==' WHERE Id = 1

 -- For Upgrade Vesion END
INSERT INTO [sSystem].[tVersionUpdate] ([VersionNumber],[VersionId],[Status],[UpdateScript],[StartDateTime],[EndDateTime],[OrgGroupId])
VALUES(@rVersion,@rVersionId,'END','Upgrade Vesion',sCommon.fGetDate(),sCommon.fGetDate(),@rOrgGroupId)

END
GO
PRINT N'Altering Procedure [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,
	 @rStatusId int=0,
	 @rStrRouteId nvarchar(500)=null,
	 @rDestinationTitle nvarchar(50)=null,
	 @rIsWithDetail bit,
	 @rReportId int=0			-- add by dhruvik for 27333 mantis
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 
-- add by dhruvik for 27333 mantis start
IF(@rReportId=30177)
BEGIN
SELECT DISTINCT * FROM 
	(
		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,
			@rIsWithDetail As WithDetails ,
			SM.SUId As SUID
			
		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 
			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)
			INNER JOIN sSetup.tBatchMaster BMM ON BMM.OrgGroupBatchId = BRM.OrgGroupBatchId AND BMM.Id = A.BatchId 
			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))
			AND ((SM.StatusId = @rStatusId) OR (@rStatusId=0))
			AND BMM.IsInContext = 1
			AND (BRM.Id IN (SELECT item from sCommon.fnSplit(@rStrRouteId,',')) OR ISNULL(@rStrRouteId,'') = '')
			AND (BRDM.Title Like @rDestinationTitle OR ISNULL(@rDestinationTitle,'') = '')
	) A
END
-- 27333 mantis end
ELSE
BEGIN
	SELECT DISTINCT * FROM 
	(
		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,
			@rIsWithDetail As WithDetails ,
			SM.SUId As SUID
			
		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 
			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)
			INNER JOIN sSetup.tBatchMaster BMM ON BMM.OrgGroupBatchId = BRM.OrgGroupBatchId AND BMM.Id = A.BatchId 
			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))
			AND ((SM.StatusId = @rStatusId) OR (@rStatusId=0))
			AND BMM.IsInContext = 1
			AND (BRM.Id IN (SELECT item from sCommon.fnSplit(@rStrRouteId,',')) OR ISNULL(@rStrRouteId,'') = '')
			AND (BRDM.Title Like @rDestinationTitle OR ISNULL(@rDestinationTitle,'') = '')

		UNION ALL 

		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,
			@rIsWithDetail As WithDetails,
			SM.SUId AS SUID
			
		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 
			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.DropDestinationId
			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.PickupDestinationId
			LEFT JOIN sTransport.tBusRouteMaster BRM1 ON BRM1.Id=BRDM1.BusRouteId AND (BRM1.OrgGroupBatchId=@rOrgGroupBatchId)
			INNER JOIN sSetup.tBatchMaster BMM ON BMM.OrgGroupBatchId = BRM.OrgGroupBatchId AND BMM.Id = A.BatchId 
			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))
			AND ((SM.StatusId = @rStatusId) OR (@rStatusId=0))
			AND BMM.IsInContext = 1
			AND (BRM.Id IN (SELECT item from sCommon.fnSplit(@rStrRouteId,',')) OR ISNULL(@rStrRouteId,'') = '')
			AND (BRDM.Title Like @rDestinationTitle OR ISNULL(@rDestinationTitle,'') = '')
	) A
END
END
GO
PRINT N'Creating Procedure [sActivity].[pEmployeeHealthCheckupEntryGet]...';


GO
CREATE PROCEDURE [sActivity].[pEmployeeHealthCheckupEntryGet]
	            
           @rHealthCheckupId int,
           @rStatusId int=0,
           @rBatchId int,
           @rDepartmentId int          
	
WITH EXECUTE AS CALLER	
AS
SET NOCOUNT ON
BEGIN
	 BEGIN TRY 
	 BEGIN TRANSACTION	
	   
	SELECT      
		ISNULL([HealthCheckupId],0) AS HealthCheckupId
		,ISNULL([HeightInCm],0) AS HeightInCm 
		,ISNULL([WeightInKg],0) AS WeightInKg
		,ISNULL([Dental],'') AS Dental
		,ISNULL([Nails],'') AS Nails
		,ISNULL([Hair],'') AS Hair
		,ISNULL([Skin],'') AS Skin
		,ISNULL([Ear],'') AS Ear
		,ISNULL([Nose],'') AS Nose
		,ISNULL([Throat],'') AS Throat
		,ISNULL([Respiratory],'') AS Respiratory
		,ISNULL([Cardiovascular],'') AS Cardiovascular
		,ISNULL([Nervous],'') AS Nervous
		,ISNULL([Eye],'') AS Eye
		,ISNULL([Other],'') AS Other
		,ISNULL([ImportantFinding],'') AS ImportantFinding
		,ISNULL([Remarks],'') AS Remarks
		,ISNULL([FollowupDetail],'') AS FollowupDetail
		,ISNULL(HT.[StatusId],0) AS StatusId
		,EC.EmployeeId AS EmployeeId
		,EC.EmployeeName AS EmployeeName
		,EC.Code AS EmployeeCode
		,EC.DepartmentId
		,EC.DepartmentName AS DepartmentName
		,EC.MobileNumber As MobileNumber
		,ISNULL(HT.BloodGroupId,0)AS BloodGroupId
			  
	FROM	sHrm.vEmployeeCommunication EC
		LEFT JOIN [sActivity].[tHealthCheckupEmployee] HT ON EC.EmployeeId = HT.EmployeeId	
    	--INNER JOIN sCommon.tStatusMaster SMM ON SMM.Id = HT.StatusId	    		
  
	WHERE  (EC.StatusId = @rStatusId OR @rStatusId = 0)
		-- AND (HC.BatchId = @rBatchId OR @rBatchId = 0)
		 ANd (EC.DepartmentId = @rDepartmentId OR @rDepartmentId = 0)
			
	ORDER BY EC.Code ASC
      
	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Creating Procedure [sActivity].[pEmployeeHealthTrackAdd]...';


GO

CREATE PROCEDURE [sActivity].[pEmployeeHealthTrackAdd]
			
			@rId bigint
           ,@rEmployeeId bigint
           ,@rHealthCheckupTypeId int
           ,@rCheckupFromDate date
           ,@rCheckupToDate date
           ,@rChiefComplain nvarchar(100)
           ,@rDiagnosis nvarchar(100)
           ,@rActionTaken nvarchar(100)
           ,@rRemark nvarchar(200)
           ,@rExaminedBy nvarchar(100)
           ,@rCreatedUserId bigint
           ,@rOrgId int
		   ,@rGatePassInTime datetime
		   ,@rGatePassOutTime datetime
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
  
	
	 BEGIN TRANSACTION	
	DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sActivity.tEmployeeHealthTrack', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO [sActivity].[tEmployeeHealthTrack]
           (
            [Id]
           ,[EmployeeId]
           ,[HealthCheckupTypeId]
           ,[CheckupFromDate]
           ,[CheckupToDate]
           ,[ChiefComplain]
           ,[Diagnosis]
           ,[ActionTaken]
           ,[Remark]
           ,[ExaminedBy]
           ,[CreatedUserId]
           ,[CreatedDateTime]
           ,[UpdatedUserId]
           ,[UpdatedDateTime]
		   ,[InTime]
		   ,[OutTime]
           )
     VALUES
           (
            @lNextNumber
           ,@rEmployeeId
           ,@rHealthCheckupTypeId
           ,@rCheckupFromDate
           ,@rCheckupToDate
           ,@rChiefComplain
           ,@rDiagnosis
           ,@rActionTaken
           ,@rRemark
           ,@rExaminedBy
           ,@rCreatedUserId
           ,sCommon.fGetDate()
           ,@rCreatedUserId
           ,sCommon.fGetDate()
		   ,@rGatePassInTime
		   ,@rGatePassOutTime
           )
                                 
		   SELECT @lNextNumber AS Result	
	END	 

ELSE
	 BEGIN 
	      SET @lNextNumber = @rId
	     
	      UPDATE  [sActivity].[tEmployeeHealthTrack]
			   SET  
				   [HealthCheckupTypeId] = @rHealthCheckupTypeId 
				  ,[CheckupFromDate] = @rCheckupFromDate 
				  ,[CheckupToDate] = @rCheckupToDate 
				  ,[ChiefComplain] = @rChiefComplain 
				  ,[Diagnosis] = @rDiagnosis 
				  ,[ActionTaken] = @rActionTaken 
				  ,[Remark] = @rRemark 
				  ,[ExaminedBy] = @rExaminedBy			 
				  ,[UpdatedUserId] = @rCreatedUserId 
				  ,[UpdatedDateTime] = sCommon.fGetDate()
				  ,[InTime] = @rGatePassInTime
				  ,[OutTime] = @rGatePassOutTime
	   
	      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 Procedure [sActivity].[pEmployeeHealthTrackGet]...';


GO
CREATE PROCEDURE [sActivity].[pEmployeeHealthTrackGet]
	 
		   @rBuilder1 nvarchar(max)='',
		   @rBuilder2 nvarchar(max)='',     
           @rId bigint,
           @rEmployeeId bigint,
           @rHealthCheckUpTypeId int,
           @rCheckupFromDate date,
           @rCheckupToDate date,
           @rBatchId int,
		   @rDepartmentId int=0 
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	 BEGIN TRY 
	 BEGIN TRANSACTION	
	   
   SELECT 
   
           @rBuilder1 AS Builder1,
		   @rBuilder2 AS Builder2,
		   HT.[Id]
		  ,HT.EmployeeId
		  ,[HealthCheckupTypeId]
		  ,[CheckupFromDate]
		  ,[CheckupToDate]
		  ,[ChiefComplain]
		  ,[Diagnosis]
		  ,[ActionTaken]
		  ,[Remark]
		  ,[ExaminedBy]
		  ,EC.Code AS EmployeeCode
		  ,EC.EmployeeName AS EmployeeName
		  ,EC.DepartmentId
		  ,EC.DepartmentName
		  ,CTM.Title AS HealthCheckupType
		  ,ISNULL(HT.InTime,'') AS InTime
		  ,ISNULL(HT.OutTime,'') AS OutTime
       
	FROM  [sActivity].[tEmployeeHealthTrack]  HT 
		INNER JOIN sHrm.vEmployeeCommunication EC ON EC.EmployeeId = HT.EmployeeId	
		INNER JOIN sActivity.tHealthCheckUpTypeMaster CTM ON CTM.Id = HT.HealthCheckupTypeId
  
	WHERE   (HT.Id = @rId OR @rId = 0)	   	 	
		AND (HT.EmployeeId = @rEmployeeId OR @rEmployeeId =  0)
		AND (HealthCheckupTypeId = @rHealthCheckUpTypeId OR @rHealthCheckUpTypeId = 0)
		AND (CheckupFromDate >= @rCheckupFromDate OR ISNULL(@rCheckupFromDate,'') = '')
		AND (CheckupFromDate <= @rCheckupToDate OR ISNULL(@rCheckupToDate,'') = '')
		--AND BatchId = @rBatchId 
		AND (EC.DepartmentId=@rDepartmentId OR @rDepartmentId=0)
		
		order by HT.CheckupFromDate Asc
      
	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Creating Procedure [sActivity].[pHealthCheckupEmployeeAdd]...';


GO

CREATE PROCEDURE [sActivity].[pHealthCheckupEmployeeAdd]
			
			@rHealthCheckupId int
           ,@rEmployeeId bigint
           ,@rHeightInCm decimal(6,2)
           ,@rWeightInKg decimal(6,2)
           ,@rDental nvarchar(150)
           ,@rNails nvarchar(150)
           ,@rHair nvarchar(150)
           ,@rSkin nvarchar(150)
           ,@rEar nvarchar(150)
           ,@rNose nvarchar(150)
           ,@rThroat nvarchar(150)
           ,@rRespiratory nvarchar(150)
           ,@rCardiovascular nvarchar(150)
           ,@rNervous nvarchar(150)
           ,@rEye nvarchar(150)
           ,@rOther nvarchar(150)
           ,@rImortantFinding nvarchar(150)
           ,@rRemark nvarchar(150)
           ,@rFollowupDetail nvarchar(150)
           ,@rStatusId smallint  
           ,@rOrgId int       
           ,@rBloodGroupId int

	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY 
	
	 BEGIN TRANSACTION	 
 
	IF NOT EXISTS (Select 1 FROM sActivity.tHealthCheckupEmployee Where HealthCheckupId = @rHealthCheckupId AND EmployeeId = @rEmployeeId)
	BEGIN
	INSERT INTO  sActivity.tHealthCheckupEmployee
           ([HealthCheckupId]
           ,[EmployeeId]
           ,[HeightInCm]
           ,[WeightInKg]
           ,[Dental]
           ,[Nails]
           ,[Hair]
           ,[Skin]
           ,[Ear]
           ,[Nose]
           ,[Throat]
           ,[Respiratory]
           ,[Cardiovascular]
           ,[Nervous]
           ,[Eye]
           ,[Other]
           ,[ImportantFinding]
           ,[Remarks]
           ,[FollowupDetail]
           ,[StatusId]
		   ,[BloodGroupId])
     VALUES
           (
            @rHealthCheckupId
           ,@rEmployeeId
           ,@rHeightInCm 
           ,@rWeightInKg 
           ,@rDental 
           ,@rNails 
           ,@rHair 
           ,@rSkin 
           ,@rEar 
           ,@rNose 
           ,@rThroat 
           ,@rRespiratory 
           ,@rCardiovascular 
           ,@rNervous 
           ,@rEye 
           ,@rOther 
           ,@rImortantFinding 
           ,@rRemark
           ,@rFollowupDetail 
           ,@rStatusId 
		   ,@rBloodGroupId
           )
                                 
		   SELECT @rHealthCheckupId AS Result	
		   --COMMIT TRANSACTION         
	END	 

ELSE
	 BEGIN  
	      UPDATE [sActivity].[tHealthCheckupEmployee]
			   SET [HealthCheckupId] = @rHealthCheckupId
				  ,[EmployeeId] = @rEmployeeId
				  ,[HeightInCm] = @rHeightInCm
				  ,[WeightInKg] = @rWeightInKg 
				  ,[Dental] = @rDental 
				  ,[Nails] = @rNails 
				  ,[Hair] = @rHair 
				  ,[Skin] = @rSkin 
				  ,[Ear] = @rEar 
				  ,[Nose] = @rNose 
				  ,[Throat] = @rThroat 
				  ,[Respiratory] = @rRespiratory  
				  ,[Cardiovascular] = @rCardiovascular 
				  ,[Nervous] = @rNervous 
				  ,[Eye] = @rEye 
				  ,[Other] = @rOther 
				  ,[ImportantFinding] = @rImortantFinding 
				  ,[Remarks] = @rRemark
				  ,[FollowupDetail] = @rFollowupDetail 
				  ,[StatusId] = @rStatusId 
				  ,[BloodGroupId] = @rBloodGroupId
				 Where HealthCheckupId = @rHealthCheckupId AND EmployeeId = @rEmployeeId
	      
	       SELECT @rHealthCheckupId AS Result      		  
	 END   

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


GO
CREATE PROCEDURE [sActivity].[pHealthCheckupEmployeeGet]
	        
	       @rBuilder1 nvarchar(max)='',
		   @rBuilder2 nvarchar(max)='',     
           @rEmployeeId bigint,
           @rHealthCheckupId int,
           @rStatusId int,
           @rBatchId int,
           @rFromDate date = null,
           @rToDate date = null,
           @rDepartmentId int          
	
WITH EXECUTE AS CALLER	
AS
SET NOCOUNT ON
BEGIN
	 BEGIN TRY 
	 BEGIN TRANSACTION	
	   
  SELECT      
			  @rBuilder1 AS Builder1
			  ,@rBuilder2 AS Builder2
			  ,[HealthCheckupId]     
	          ,HT.EmployeeId 
			  ,ISNULL([HeightInCm],0) AS HeightInCm 
			  ,ISNULL([WeightInKg],0) AS WeightInKg
			  ,[Dental]
			  ,[Nails]
			  ,[Hair]
			  ,[Skin]
			  ,[Ear]
			  ,[Nose]
			  ,[Throat]
			  ,[Respiratory]
			  ,[Cardiovascular]
			  ,[Nervous]
			  ,[Eye]
			  ,[Other]
			  ,[ImportantFinding]
			  ,[Remarks]
			  ,[FollowupDetail]
			  ,HT.[StatusId]	
			  ,EC.EmployeeId AS EmployeeId
			  ,EC.EmployeeName AS EmployeeName
			  ,EC.Code AS EmployeeCode
			  ,EC.DepartmentId
			  ,EC.DepartmentName AS DepartmentName
			  ,ISNULL(EPD.GenderId,0) AS GenderId
			  ,EC.MobileNumber As MobileNumber
			  ,BGM.Title AS BloodGroup
			  ,SMM.Title AS Status
			  ,HC.Title AS HealthCheckup
			  ,HC.DoctorName
			  ,HC.CheckupDate
			  ,ISNULL(HT.BloodGroupId,0)AS BloodGroupId
			  ,ISNULL(BGM.Title,'') AS BloodGroup
			  
  FROM		[sActivity].[tHealthCheckupEmployee] HT 
			INNER JOIN sHrm.vEmployeeCommunication EC ON EC.EmployeeId = HT.EmployeeId	
    		INNER JOIN sCommon.tStatusMaster SMM ON SMM.Id = HT.StatusId	
    		INNER JOIN sActivity.tHealthCheckup HC ON HC.Id = HT.HealthCheckupId  
    		LEFT JOIN [sHrm].[tEmployeePersonalDetail] EPD ON EPD.EmployeeId = EC.EmployeeId
    		LEFT JOIN sCommon.tBloodGroupMaster BGM ON EPD.BloodGroupId=BGM.Id
    		    		
  
  WHERE  (HT.HealthCheckupId = @rHealthCheckupId OR @rHealthCheckupId = 0)	
	     AND (HT.EmployeeId = @rEmployeeId OR @rEmployeeId =  0)
	     AND (HT.StatusId = @rStatusId OR @rStatusId = 0)
         AND (HC.CheckupDate >= @rFromDate OR ISNULL(@rFromDate,'') = '')
		 AND (HC.CheckupDate <= @rToDate OR ISNULL(@rToDate,'') = '')
		 AND (HC.BatchId = @rBatchId OR @rBatchId = 0)
		 ANd (EC.DepartmentId = @rDepartmentId OR @rDepartmentId = 0)
			
		ORDER BY CheckupDate ASC
      
	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Creating Procedure [sActivity].[pHealthTrackEmployeeRemove]...';


GO

CREATE PROCEDURE [sActivity].[pHealthTrackEmployeeRemove]
	 
            @rEmployeeId bigint,
            @rHealthCheckUpId int
           
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	 BEGIN TRY 
	 BEGIN TRANSACTION	
	   
         DELETE FROM sActivity.tHealthCheckupEmployee Where HealthCheckupId = @rHealthCheckUpId AND EmployeeId = @rEmployeeId 
		
		SELECT 1 AS Result
	 
      
	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Creating Procedure [sActivity].[pRptEventSchedule]...';


GO
CREATE PROCEDURE [sActivity].[pRptEventSchedule]

	--@rId int = 0,
	@rTitle nvarchar(100),
	@rFromDate date,
	@rToDate date,
	@rBatchId int,
	--@rIsSearch bit = 1,
	@rEventTypeId int = 0
	--,@rSourceId bigint = 0
	--,@rSourceTypeId smallint = 0
	,@rBuilder1 nvarchar(max) = ''
	,@rBuilder2 nvarchar(max) = ''

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON


BEGIN

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

	--IF(@rSourceTypeId=2003)
	--BEGIN
	--	SELECT
	--		ES.Id as EventScheduleId,
	--		ES.Title,
	--		ES.FromDate,
	--		ES.ToDate,
	--		ES.Remark,
	--		ES.IsCommonForAll,
	--		ES.IsHoliday,
	--		ES.IsEnrollment,
	--		ISNULL(ES.EventTypeId,0) AS EventTypeId,
	--		ISNULL(EM.Title,'') AS EventType,
	--		EM.HighlightColor,
	--		EM.Title AS EventTypeName,
	--		OM.Id as OrgId,
	--		OM.WeekOffs,
	--		ES.BatchId
	--	FROM
	--		sActivity.tEventSchedule ES
	--		LEFT JOIN sActivity.tEventTypeMaster EM ON EM.Id = ES.EventTypeId
	--		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = ES.BatchId
	--		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
	--	WHERE
	--		((ES.Id = @rId) OR (@rId = 0))
	--		AND ((ES.Id IN(SELECT EventScheduleId FROM sActivity.tEventAssign WHERE SourceTypeId=2005 AND
	--				SourceId=(SELECT DivisionId FROM sStudent.vStudentName WHERE StudentId=@rSourceId AND
	--					OrgId= CAST(LEFT(@rBatchId,4) AS int)  AND BatchId=@rBatchId))))
	--		AND ((ES.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
	--		AND (((ES.FromDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	--			AND ((ES.FromDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
	--			OR ((ES.ToDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	--			AND ((ES.ToDate <= @rToDate) OR (ISNULL(@rToDate,'')='')))
	--		AND ES.BatchId=@rBatchId
	--		AND ((ES.EventTypeId = @rEventTypeId) OR (@rEventTypeId = 0))
	--	ORDER BY ES.FromDate DESC
	--END

	--ELSE IF(@rSourceTypeId=95)
	--BEGIN
	--	SELECT
	--		ES.Id as EventScheduleId,
	--		ES.Title,
	--		ES.FromDate,
	--		ES.ToDate,
	--		ES.Remark,
	--		ES.IsCommonForAll,
	--		ES.IsHoliday,
	--		ES.IsEnrollment,
	--		ISNULL(ES.EventTypeId,0) AS EventTypeId,
	--		ISNULL(EM.Title,'') AS EventType,
	--		EM.HighlightColor,
	--		EM.Title AS EventTypeName,
	--		OM.Id as OrgId,
	--		OM.WeekOffs,
	--		ES.BatchId
	--	FROM
	--		sActivity.tEventSchedule ES
	--		LEFT JOIN sActivity.tEventTypeMaster EM ON EM.Id = ES.EventTypeId
	--		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = ES.BatchId
	--		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
	--	WHERE
	--		((ES.Id = @rId) OR (@rId = 0))
	--		AND (ES.Id IN(SELECT EventScheduleId FROM sActivity.tEventAssign WHERE SourceTypeId IN(2004,95) AND
	--				((SourceId=(SELECT OrganizationDepartmentId FROM sHrm.vExtEmployeeJobDetail WHERE EmployeeId=@rSourceId)) OR (SourceId=@rSourceId))))
	--		AND ((ES.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
	--		AND (((ES.FromDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	--			AND ((ES.FromDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
	--			OR ((ES.ToDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	--			AND ((ES.ToDate <= @rToDate) OR (ISNULL(@rToDate,'')='')))
	--		AND ES.BatchId=@rBatchId
	--		AND (( ES.EventTypeId = @rEventTypeId) OR (@rEventTypeId = 0))
	--	ORDER BY ES.FromDate DESC
	--END

	--ELSE
	--BEGIN
		SELECT
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			ES.Id as EventScheduleId,
			ES.Title,
			ES.FromDate,
			ES.ToDate,
			ES.Remark,
			ES.IsCommonForAll,
			ES.IsHoliday,
			ES.IsEnrollment,
			ISNULL(ES.EventTypeId,0) AS EventTypeId,
			ISNULL(EM.Title,'') AS EventType,
			EM.HighlightColor,
			EM.Title AS EventTypeName,
			OM.Id as OrgId,
			OM.WeekOffs,
			ES.BatchId
		FROM
			sActivity.tEventSchedule ES
			LEFT JOIN sActivity.tEventTypeMaster EM ON EM.Id = ES.EventTypeId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = ES.BatchId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
		WHERE
			--((ES.Id = @rId) OR (@rId = 0)) AND 
			((ES.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
			AND ((ES.FromDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((ES.FromDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND ES.BatchId=@rBatchId
			AND (( ES.EventTypeId = @rEventTypeId) OR (@rEventTypeId = 0))
		ORDER BY ES.FromDate DESC
	--END
END
GO
PRINT N'Creating Procedure [sActivity].[pRptPTMStudentAttendentListGet]...';


GO
CREATE PROCEDURE [sActivity].[pRptPTMStudentAttendentListGet]

		   	
	       @rBuilder1 nvarchar(max)='',
	       @rBuilder2 nvarchar(max)='', 	
           @rClassId int,
           @rDivisionId int,
           @rOrgId int,
           @rStatusId int,
           @rOrgGroupId int=0
          
AS
SET NOCOUNT ON

BEGIN

SELECT
				@rBuilder1 AS Builder1,
				@rBuilder2 AS Builder2,	
			    2003 AS SourceType,
				vSA.AcademicId AS SourceId,
				vSA.Code,
				vSA.RollNo AS Number,
				vSA.Name AS Name,
				vSA.ClassId,
				vSA.DivisionId,
				vSA.DivisionOrder,
				vSA.ClassName AS ClassName,
				OM.Id AS OrgId,
				OM.DisplayTitle AS OrgName,
				vSA.StudentId,
				CM.DisplayTitle + '-' + DM.DisplayTitle AS ClassDivision, 
				Case When ISNULL(EAT.IsSelfPresent,0)=1 OR ISNULL(EAT.IsFatherPresent,0)=1 OR ISNULL(EAT.IsMotherPresent,0)=1 OR ISNULL(EAT.IsGuardianPresent,0)=1 
				then 1 Else 0 end AS IsPresent,
				ISNULL(EAT.IsSelfPresent,0) AS IsSelfPresent,
				ISNULL(EAT.IsFatherPresent,0) AS IsFatherPresent,
				ISNULL(EAT.IsMotherPresent,0) AS IsMotherPresent,
				ISNULL(EAT.IsGuardianPresent,0) AS IsGuardianPresent,
				ES.Title AS EventName,
				ES.Id as EventId
			FROM 
				sStudent.vStudentAcademic vSA
				INNER JOIN sSetup.tClassMaster CM ON CM.Id = vSA.ClassId
				INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vSA.DivisionId
				INNER JOIN sActivity.tEventAssign EA ON EA.SourceId=vSA.DivisionId AND EA.SourceTypeId=2005 
				--AND EA.EventScheduleId=@rEventScheduleId
				INNER JOIN sActivity.tEventAttendance EAT ON EAT.EventScheduleId = EA.EventScheduleId 
				AND EAT.SourceId = vSA.AcademicId AND EAT.SourceTypeId = 2001
				INNER JOIN sActivity.tEventSchedule ES ON ES.Id = EAT.EventScheduleId
				INNER JOiN [sActivity].[tEventTypeMaster] ETM ON ES.EventTypeId=ETM.Id 
				inner Join [sActivity].[tEventMainTypeMaster]  EMTM ON ETM.EventMainTypeId=EMTM.Id AND EMTM.id=3
				INNER JOIN sSetup.tOrganizationMaster OM ON vSA.OrgId = OM.Id
				INNER JOIN sSetup.tOrgGroupMaster OGM ON OM.OrgGroupId = OGM.Id

			WHERE
				(vSA.ClassId=@rClassId OR @rClassId=0)
				AND (vSA.DivisionId=@rDivisionId OR @rDivisionId=0)
				AND (vSA.StatusId=@rStatusId OR @rStatusId=0)
				AND (vSA.OrgId=@rOrgId OR @rOrgId=0)
				AND (vSA.IsActiveBatch=1)
				AND (OGM.Id = @rOrgGroupId OR @rOrgGroupId = 0)	
			--ORDER BY vSA.RollNo	
		
		
End
GO
PRINT N'Creating Procedure [sActivity].[pXMLModifyHealthCheckupEmployee]...';


GO

CREATE PROCEDURE [sActivity].[pXMLModifyHealthCheckupEmployee]
	
	@rXmlString [nvarchar](max),
	@rHealthCheckupId int
 
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

		DECLARE @loDoc INT
		EXEC sp_xml_preparedocument @loDoc OUTPUT, @rXmlString
		BEGIN
			UPDATE       HC  		  
			SET          HC.HeightInCm = E.HeightInCm,
			             HC.Dental	    =  E.Dental,
						 HC.Nails	    =  E.Nails,
						 HC.Hair	    =  E.Hair,
						 HC.Skin	    =  E.Skin,
						 HC.Ear	    =  E.Ear,
						 HC.Nose	    =  E.Nose,
						 HC.Throat	    =  E.Throat,
						 HC.Respiratory	    =  E.Respiratory,
						 HC.Cardiovascular	    =  E.Cardiovascular,
						 HC.Nervous	    =  E.Nervous,
						 HC.Eye	    =  E.Eye,
						 HC.Other	    =  E.Other,
						 HC.ImportantFinding	    =  E.ImportantFinding,
						 HC.Remarks	    =  E.Remarks,
						 HC.FollowupDetail	    =  E.FollowupDetail,
						 hc.WeightInKg = E.WeightInKg,
						 Hc.StatusId = E.StatusId,
						 Hc.BloodGroupId=E.BloodGroupId
						 	
			   			
			FROM sActivity.tHealthCheckupEmployee HC				 
			 INNER JOIN					
			    (
					SELECT EmployeeId AS EmployeeId,HealthCheckupId AS HealthCheckupId,HeightInCm AS HeightInCm,WeightInKg AS WeightInKg,
					Dental AS Dental,Nails AS Nails,Hair AS Hair,Skin AS Skin,
					Ear AS Ear,Nose AS Nose,Throat AS Throat,Respiratory AS Respiratory,Cardiovascular AS Cardiovascular
				   ,Nervous AS Nervous,Eye AS Eye,Other AS Other,ImportantFinding AS ImportantFinding,Remarks AS Remarks,
					FollowupDetail AS FollowupDetail,StatusId AS StatusId,BloodGroupId AS BloodGroupId
					FROM
					OPENXML (@loDoc, '/Table/HealthCheckupEmployee', 1)
					WITH    (
							      EmployeeId bigint, 
							      HealthCheckupId int,
							      HeightInCm decimal(6,2)
							     ,WeightInKg decimal(6,2)
							     ,Dental	nvarchar(150)
								 ,Nails	nvarchar(150)
								 ,Hair	nvarchar(150)
								 ,Skin	nvarchar(150)
								 ,Ear	nvarchar(150)
								 ,Nose	nvarchar(150)
								 ,Throat	nvarchar(150)
								 ,Respiratory	nvarchar(150)
								 ,Cardiovascular	nvarchar(150)
								 ,Nervous	nvarchar(150)
								 ,Eye	nvarchar(150)
								 ,Other	nvarchar(150)
								 ,ImportantFinding	nvarchar(150)
								 ,Remarks	nvarchar(150)
								 ,FollowupDetail	nvarchar(150)
								 ,StatusId	int
								 ,BloodGroupId tinyint
			                 )
			          )E ON E.EmployeeId = HC.EmployeeId AND E.HealthCheckupId = HC.HealthCheckupId
				
				Where E.EmployeeId = HC.EmployeeId AND E.HealthCheckupId = HC.HealthCheckupId
	 
	 
	 
	INSERT INTO [sActivity].[tHealthCheckupEmployee]
           (
            [HealthCheckupId]
           ,[EmployeeId]
           ,[HeightInCm]
           ,[WeightInKg]
           ,[Dental]
           ,[Nails]
           ,[Hair]
           ,[Skin]
           ,[Ear]
           ,[Nose]
           ,[Throat]
           ,[Respiratory]
           ,[Cardiovascular]
           ,[Nervous]
           ,[Eye]
           ,[Other]
           ,[ImportantFinding]
           ,[Remarks]
           ,[FollowupDetail]
           ,[StatusId]
		   ,[BloodGroupId]
           )             
			SELECT 
			      HealthCheckupId			      			      
			     ,EmployeeId
			     ,HeightInCm
			     ,WeightInKg
			     ,Dental
			     ,Nails
			     ,Hair
			     ,Skin
			     ,Ear
			     ,Nose
			     ,Throat
			     ,Respiratory
			     ,Cardiovascular
				 ,Nervous
				 ,Eye
				 ,Other
				 ,ImportantFinding
				 ,Remarks				  
				 ,FollowupDetail
				 ,StatusId
				 ,BloodGroupId
					FROM
					OPENXML (@loDoc, '/Table/HealthCheckupEmployee', 1)
					WITH    (
							          HealthCheckupId int '@HealthCheckupId'
								     ,EmployeeId bigint  '@EmployeeId'
									 ,HeightInCm decimal(6,2) '@HeightInCm'
									 ,WeightInKg decimal(6,2) '@WeightInKg'
									 ,Dental	nvarchar(150) '@Dental'
									 ,Nails	nvarchar(150) '@Nails'
									 ,Hair	nvarchar(150) '@Hair'
									 ,Skin	nvarchar(150) '@Skin'
									 ,Ear	nvarchar(150) '@Ear'
									 ,Nose	nvarchar(150) '@Nose'
									 ,Throat	nvarchar(150) '@Throat'
									 ,Respiratory	nvarchar(150) '@Respiratory'
									 ,Cardiovascular	nvarchar(150) '@Cardiovascular'
									 ,Nervous	nvarchar(150) '@Nervous'
									 ,Eye	nvarchar(150) '@Eye'
									 ,Other	nvarchar(150) '@Other'
									 ,ImportantFinding	nvarchar(150) '@ImportantFinding'
									 ,Remarks	nvarchar(150) '@Remarks'
									 ,FollowupDetail	nvarchar(150) '@FollowupDetail'
									 ,StatusId int '@StatusId'
									 ,BloodGroupId tinyint '@BloodGroupId'
 
			                 )A
		       WHERE A.EmployeeId NOT IN (Select EmployeeId FROM sActivity.tHealthCheckupEmployee Where HealthCheckupId = @rHealthCheckupId)
 
	  			 
			 Select 1 As Result 
		END	
END
GO
PRINT N'Creating Procedure [sAdmission].[pRptAdmissionListUserWiseGet]...';


GO
CREATE PROCEDURE [sAdmission].[pRptAdmissionListUserWiseGet]
	
	
	 @rBatchId int,
	 @rClassId int,
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='',
	 @rFromDate date,
	 @rToDate date,
	 @rIsDetail bit =0,
	 @rCreatedUserName nvarchar(100)=''
AS
 SET NOCOUNT ON
			 

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

	SELECT 
		 AF.FormNo,
		 AF.FirstName+' '+AF.MiddleName+' '+AF.LastName AS Name,
		 AF.ForClassId,
		 AF.BatchId,
		 AF.OrgId,
		 AF.City,
		 AF.FamilyCast,
		 CM.Title AS Class,
		 AF.FamilySubCast,
		 AF.CastCategoryId,
		 --for online and offline display same feename
		 AC.FormFeeName AS FeeName,
		 --in online entry display amount from pt  and in offline entry amount display from aff
		 CASE WHEN AF.DataEntryModeId = 561 THEN PT.PayAmount ELSE AFF.FeeAmount END  AS FeeAmount,
		 @rIsDetail AS IsDetail,
		 @rBuilder1 AS Builder1,
		 @rBuilder2 AS Builder2,
		 ISNULL(AF.CreatedDateTime,'') AS CreatedDateTime,
		 ISNULL(U.DisplayTitle,'') AS UserName
	 
	 FROM 
		sAdmission.tAdmissionForm AF	
		INNER JOIN sSetup.tClassMaster CM ON AF.ForClassId=CM.Id
		LEFT JOIN sAdmission.tAdmissionFormFee AFF ON AFF.AdmissionFormId = AF.Id
		LEFT JOIN sAdmission.tAdmissionCriteriaFee ACF ON ACF.Id = AFF.AdmissionCriteriaFeeId
		INNER JOIN sAdmission.tAdmissionCriteria AC ON AC.ClassId=CM.Id AND AC.BatchId = @rBatchId
		LEFT JOIN sOp.tPaymentTransaction PT ON AF.Id = PT.PayerSourceId AND PT.TransactionSourceTypeId = 2027 AND PT.TransactionStatusId IN (2,4)
		LEFT JOIN sSecurity.tUser U ON U.Id=AF.CreatedUserId
	WHERE 	
		AF.BatchId=@rBatchId
		--AND AF.OrgId=@rOrgId
		AND ((AF.ForClassId=@rClassId) OR (@rClassId=0))	
		AND ((CONVERT(DATE,AF.CreatedDateTime) >= @rFromDate) OR (isnull(@rFromDate,'')=''))
	    AND ((CONVERT(DATE,AF.CreatedDateTime) <= @rToDate) OR (isnull(@rToDate,'')=''))
		AND ((ISNULL(U.DisplayTitle,'') like @rCreatedUserName) OR (ISNULL(@rCreatedUserName,'')=''))
	    ORDER BY AF.FormNo
END
GO
PRINT N'Creating Procedure [sAssessment].[pRptGradeAnalysisMainCategoryWise]...';


GO
--created by megha for 0027269
CREATE PROCEDURE [sAssessment].[pRptGradeAnalysisMainCategoryWise]
	 
	 --@rAcademicId bigint=0,
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rBatchId int =0,
	 @rExamSubGroupId int=0,
	 @rBuilder1 nvarchar(max)='',
	 @rClass nvarchar(MAX)='',
	 @rStatusId int =0,
	 @rClassStatusId int=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 
		
	
	select 
	@rBuilder1 AS Builder1,
 
	
		 count(R.id),
		GM.Title AS Gender,
		R.ResultGrade,
		--ISNULL(CCM.Title,'') AS CastCatagory,
		A.ClassId,
		A.DivisionId,
		CM.Title AS ClassName,
		DM.Title AS DivisionName,
		ISNULL(MCM.Title,'') As MainCastCategory
	 
		 
 from sAssessment.tResult  R
		INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
		INNER JOIN sStudent.tAcademic A ON R.AcademicId = A.Id 
		Inner join sSetup.tClassMaster CM ON CM.Id=A.ClassId
		INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
		INNER JOIN sStudent.tStudentMaster SM ON SM.Id = A.StudentId 
		INNER JOIN sStudent.tStudentOther SO ON SO.StudentId = A.StudentId 	
		INNER JOIN sCommon.tGenderMaster GM ON GM.Id=SO.GenderId
		LEFT  JOIN sCommon.tCastCategoryMaster CCM ON CCM.Id=SO.CastCategoryId
	    LEFT JOIN sCommon.tMainCastCategoryMaster MCM ON MCM.Id = CCM.MainCastCategoryId

		
	where (A.ClassId=@rClassId OR @rClassId=0)
		AND (A.DivisionID=@rDivisionId Or @rDivisionId=0)
		and A.BatchId=@rBatchId
		and EM.ExamSubGroupId=@rExamSubGroupId
		AND    (ISNULL(A.ClassId,0) IN( SELECT item FROM  sCommon.fnsplit(@rClass,','))OR @rClass='')
		and ((sm.StatusId=@rStatusId) or (@rStatusId=0))
		AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))
		 Group by R.ResultGrade, GM.Title,MCM.Title,A.ClassId,A.DivisionId,CM.Title,DM.Title 
		 
END
GO
PRINT N'Creating Procedure [sAssessment].[pRptResultListCastCategorywiseRangeGet]...';


GO


CREATE PROCEDURE [sAssessment].[pRptResultListCastCategorywiseRangeGet]
	 
	@rBuilder1 nvarchar(max)='', 
	@rBuilder2 nvarchar(max)='', 
	@rBatchId int = 0,
	@rClassId int=0,
	@rDivisionId int=0,
	@rExamId int = 0,
	@rStatusId int=0,
	@rClassStatusId int=0,
	@rCasteCategoryIds nvarchar(max) = '',
	@rFilterId int=0,
	@rOrgGroupBatchId int=0
	 		 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

SELECT 
	@rBuilder1 AS Builder1,
	@rBuilder2 AS Builder2,
	A.Id AS AcademicId,
	EM.Id AS ExamId,
	ESGM.Title AS ExamName,
	R.Percentage,
	StuO.GenderId,
	ISNULL(CCM.Id,0) AS CasteCategoryId,
	ISNULL(CCM.Title,'') AS CasteCategory

	FROM
	sAssessment.tResult R
	INNER JOIN sStudent.tAcademic A ON A.Id = R.AcademicId
	INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId	
	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
	INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId
	INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
	LEFT JOIN sStudent.tStudentOther StuO ON StuO.StudentId = StuM.Id
	LEFT JOIN sCommon.tCastCategoryMaster CCM ON CCM.Id = StuO.CastCategoryId
	LEFT JOIN sHostel.tAssignRoom ARO ON  ARO.SourceId=StuM.Id AND ARO.SourceTypeId=2003 AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((ARO.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0) AND (BM.OrgGroupBatchId = ARO.OrgGroupBatchId)) 
	LEFT JOIN
		(SELECT AT.SourceId,B.OrgGroupBatchId FROM sTransport.tAssignRoute AT 
		INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId 
		INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT ON RT.SourceId = StuM.Id 

	WHERE
	EM.Id = @rExamId 
	AND (EM.BatchId = @rBatchId OR  @rBatchId = 0)
	AND (A.ClassId=@rClassId OR @rClassId=0) 
	AND (A.DivisionId=@rDivisionId OR @rDivisionId=0)
	AND (ISNULL(CCM.Id,0) IN(SELECT cast(item as int) FROM  sCommon.fnsplit(@rCasteCategoryIds,','))OR @rCasteCategoryIds='')
	AND ((StuM.StatusId=@rStatusId)OR(@rStatusId=0))
	AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))
	AND (
			(@rFilterId = 0) -- All
			OR (@rFilterId = 2 AND isnull(ARO.SourceId,0)!=0) -- Hostel
			OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport
			OR ((@rFilterId =1) AND ((isnull(ARO.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))
			) 
END
GO
PRINT N'Creating Procedure [sAssessment].[pRptResultSheetStandardMultiExamWithAllTermGet]...';


GO

CREATE PROCEDURE [sAssessment].[pRptResultSheetStandardMultiExamWithAllTermGet]
	 
	 @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,
	 @rFromObtain decimal(5,2)=0,
	 @rToObtain decimal(5,2)=0,
	 @rFromPercentage decimal(5,2)=0,
	 @rToPercentage decimal(5,2)=0,
	 @rIsDetail bit=0,
	 @rIsShowWithDetail bit=0,
	 @rFilterId int=0,
	 @rOrgGroupBatchId int=0,
	 @rClassStatusId int=0,
	 @rMultiCode nvarchar(max)='' 
	
	 --,@rcolumn_visible bit
	

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
begin
 
  --select * from sAssessment.tTempAllExamWithAllTerm
 IF(@rOrgGroupBatchId=0)
	SELECT @rOrgGroupBatchId=OrgGroupBatchId FROM sSetup.tBatchMaster WHERE Id=@rBatchId  
  
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

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

DECLARE @lAbsentRemarkConfig nvarchar(20) = ''
SELECT @lAbsentRemarkConfig =ItemValue From sConfig.tConfigurationSetup WHERE ConfigurationId = 515 AND SourceTypeId = 1016 AND SourceId = @lOrgId

--#TempAllExam
	CREATE TABLE #TempAllExam
	(
		AcademicIdText nvarchar(20),
		ExamIdText nvarchar(20),
		CoScholasticScopeIdText nvarchar(20),
		IsDisplayMonthlyAttendanceText nvarchar(20),
		ClassIdText nvarchar(50),
		AcademicId bigint,
		ExamName Nvarchar(150),
		StudCode NVarchar(20),
		StudentName Nvarchar(150),
		RollNo int,
		ResultStatus Nvarchar(20),	
		ClassName NVarchar(50),		
		Division NVarchar(50),
		TotalMark decimal(8,2),
		TotalObtain decimal(8,2),
		Percentage decimal(8,2),
		RankNumber int,
		ResultGrade NVarchar(50),
		
		MaximumMark1 decimal(8,2),		
		SubjectGrade1 NVarchar(50),
		Obtain1 decimal(8,2) Default 0,
		ExamMaximum1 decimal(8,2),
		IsPresent1 bit,
						
		MaximumMark2 decimal(8,2),	
		SubjectGrade2 NVarchar(50),
		Obtain2 decimal(8,2) Default 0,
		ExamMaximum2 decimal(8,2),
		IsPresent2 bit,
				
		MaximumMark3 decimal(8,2),
		SubjectGrade3 NVarchar(50),
		Obtain3 decimal(8,2) Default 0,
		ExamMaximum3 decimal(8,2),
		IsPresent3 bit,		
		
		MaximumMark4 decimal(8,2),	
		SubjectGrade4 NVarchar(50),
		Obtain4 decimal(8,2) Default 0,
		ExamMaximum4 decimal(8,2),
		IsPresent4 bit,	
				
		MaximumMark5 decimal(8,2),		
		SubjectGrade5 NVarchar(50),
		Obtain5 decimal(8,2) Default 0,
		ExamMaximum5 decimal(8,2),
		IsPresent5 bit,	
				
		MaximumMark6 decimal(8,2),		
		SubjectGrade6 NVarchar(50),
		Obtain6 decimal(8,2) Default 0,
		ExamMaximum6 decimal(8,2),
		IsPresent6 bit,	
		
		MaximumMark7 decimal(8,2),		
		SubjectGrade7 NVarchar(50),
		Obtain7 decimal(8,2) Default 0,
		ExamMaximum7 decimal(8,2),
		IsPresent7 bit,	
		
		MaximumMark8 decimal(8,2),	
		SubjectGrade8 NVarchar(50),
		Obtain8 decimal(8,2) Default 0,
		ExamMaximum8 decimal(8,2),
		IsPresent8 bit,	
		
		MaximumMark9 decimal(8,2),		
		SubjectGrade9 NVarchar(50),
		Obtain9 decimal(8,2) Default 0,
		ExamMaximum9 decimal(8,2),
		IsPresent9 bit,	
		
		
		MaximumMark10 decimal(8,2),		
		SubjectGrade10 NVarchar(50),
		Obtain10 decimal(8,2) Default 0,
		ExamMaximum10 decimal(8,2),
		IsPresent10 bit,	
		
		MaximumMark11 decimal(8,2),		
		SubjectGrade11 NVarchar(50),
		Obtain11 decimal(8,2) Default 0,
		ExamMaximum11 decimal(8,2),
		IsPresent11 bit,
		
		MaximumMark12 decimal(8,2),		
		SubjectGrade12 NVarchar(50),
		Obtain12 decimal(8,2) Default 0,
		ExamMaximum12 decimal(8,2),
		IsPresent12 bit,
		
		MaximumMark13 decimal(8,2),		
		SubjectGrade13 NVarchar(50),
		Obtain13 decimal(8,2) Default 0,
		ExamMaximum13 decimal(8,2),
		IsPresent13 bit,		
		 
		 
		SubjectGradeTerm1 NVarchar(50),
		SubjectGradeTerm2 NVarchar(50),
		SubjectGradeTerm3 NVarchar(50),
		SubjectGradeTerm4 NVarchar(50),
		IsMarksInDecimal bit,
		column_visible bit,
		--Obtain decimal(5,2),
		Percentile decimal(5,2),
		--ClassSubject nvarchar(100),
		ResultDetailId bigint,
		ResultId bigint,	
		Remark1 nvarchar(1000),
		Remark2 nvarchar(1000),
		Remark3 nvarchar(1000),
		DisplayTitle nvarchar(150),		
		IsRankNo bit, 
		IsGrade bit,
		IsPercentile bit,
		IsPercentage bit,
		IsSubjectPercentile bit,
		IsProcessResult bit,
		IsNegativeMarks bit,
		IsIncludeCoScholastic bit,
		IsOnPrePrinted bit,
		IsDisplayPhoto bit,
		IsDisplayBirthDate bit,
		IsLockForEdit bit,
		IsDisplaySchoolName bit,			
		IsDisplayAttendance bit,
		IsDisplayHeightWeight bit,
		IsResultStatus bit,
		FooterAdjustmentText nvarchar(max),
		DetailAdjustmentText nvarchar(max),
		FooterAdjustment smallint,
		DetailAdjustment smallint,
		ResultRemark nvarchar(200),
		DateOfBirth date,
		HeightTerm1 decimal(5,2),
		WeightTerm1 decimal(5,2),
		HeightTerm2 decimal(5,2),
		WeightTerm2 decimal(5,2),
		HeightAnnual decimal(5,2),
		WeightAnnual decimal(5,2),
		PresentDaysTerm1 smallint,
		PresentDaysTerm2 smallint,
		PresentDaysAnnual smallint,
		TotalDaysTerm1 smallint,
		TotalDaysTerm2 smallint,
		TotalDaysAnnual smallint,
		TotalMarkTerm1 decimal(8,2),
		TotalObtainTerm1 decimal(8,2),
		PercentageTerm1 decimal(8,2),
		RankNumberTerm1 int,
		ResultGradeTerm1 NVarchar(50),
		PercentileTerm1 decimal(8,2),
		ResultStatusTerm1 Nvarchar(20),		   
		TotalMarkTerm2 decimal(8,2),
		TotalObtainTerm2 decimal(8,2),
		PercentageTerm2 decimal(8,2),
		RankNumberTerm2 int,
		ResultGradeTerm2 NVarchar(50),
		PercentileTerm2 decimal(8,2),
		ResultStatusTerm2 Nvarchar(20), 
		TotalMarkTerm3 		decimal(8,2),
		TotalObtainTerm3 decimal(8,2),
		PercentageTerm3 decimal(8,2),
		RankNumberTerm3 int,
		ResultGradeTerm3 NVarchar(50),
		PercentileTerm3 decimal(8,2),
		ResultStatusTerm3 Nvarchar(20), 

		TotalMarkTerm4	decimal(8,2),
		TotalObtainTerm4 decimal(8,2),
		PercentageTerm4 decimal(8,2),
		RankNumberTerm4 int,
		ResultGradeTerm4 NVarchar(50),
		PercentileTerm4 decimal(8,2),
		ResultStatusTerm4 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),
		Exam1CombineExamName Nvarchar(150),
				
		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),
		Exam2CombineExamName Nvarchar(150),
		
		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),
		Exam3CombineExamName Nvarchar(150),
		
		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),
		Exam4CombineExamName Nvarchar(150),
		
		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),
		Exam5CombineExamName Nvarchar(150),
		
		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),
		Exam6CombineExamName Nvarchar(150),
		
		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),
		Exam7CombineExamName Nvarchar(150),
		
		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),
		Exam8CombineExamName Nvarchar(150),
		
		
		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),
		Exam9CombineExamName Nvarchar(150),
		
		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),
		Exam10CombineExamName Nvarchar(150),
		
		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),
		Exam11CombineExamName Nvarchar(150),
		
		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),
		Exam12CombineExamName Nvarchar(150),

		Exam13Name nvarchar(150),	
		TotalMarks13 decimal(8,2),
		TotalObtain13 decimal(8,2),
		Percentage13 decimal(8,2),
		RankNumber13 int,
		ResultGrade13 NVarchar(50),
		Percentile13 decimal(8,2),
		ResultStatus13 Nvarchar(20),
		Exam13CombineExamName Nvarchar(150),
		
		ResultRemark1 nvarchar(200),
		ResultRemark2 nvarchar(200),
		
		TotalDays decimal(6,2),
		PresentDays decimal(6,2),
		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),
		Exam13Code nvarchar(20),
		
		IsDisplayParentName bit,
		FatherName nvarchar(100),
		MotherName nvarchar(100),
		IsShowSubjectMark bit, 
		IsOptionalSubject bit,
		CoScholasticScopeId tinyint,
		IsDisplayPrincipalSign bit,
		IsDisplayTeacherSign bit,
		EmployeeSign varbinary(max),
		Batch nvarchar(100),
		ExamNameTerm1 NVarchar(100),
		ExamNameTerm2 NVarchar(100) ,
		ExamNameTerm3 NVarchar(100),
		ExamNameTerm4 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(1000),
		
		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),
		KrupaMark decimal(5,2),
		GradeStringHtml nvarchar(500),
		ResultRemark3 nvarchar(200),
		IsDisplayTotalMark bit,
		SubjectObtainTerm1 decimal(8,2),	
		SubjectObtainTerm2 decimal(8,2),
		SubjectObtainTerm3  decimal(8,2),
		SubjectObtainTerm4  decimal(8,2),
		SubjectMaxTerm1 decimal(8,2),
		SubjectMaxTerm2 decimal(8,2),
		SubjectMaxTerm3 decimal(8,2),
		SubjectMaxTerm4 decimal(8,2),
		ContactNo nvarchar(50),
		PresentAddress nvarchar(max),
		TeacherSignCaption nvarchar(100),
		PrincipalSignCaption nvarchar(100),
		ParentSignCaption nvarchar(100),
		ImprovementArea nvarchar(200),
		ProgressArea nvarchar(200),
		GeneralRemark nvarchar(1000),
		MyActivity nvarchar(200),
		ClassTeacherRemark nvarchar(1000),
		 
		HouseRemark nvarchar(1000),
		BloodGroup Nvarchar(100),
		TotalDays1 decimal(6,2),
		PresentDays1 decimal(6,2),
		TotalDays2 decimal(6,2),
		PresentDays2 decimal(6,2),
		TotalDays3 decimal(6,2),
		PresentDays3 decimal(6,2),
		TotalDays4 decimal(6,2),
		PresentDays4 decimal(6,2),
		TotalDays5 decimal(6,2),
		PresentDays5 decimal(6,2),
		TotalDays6 decimal(6,2),
		PresentDays6 decimal(6,2),
		TotalDays7 decimal(6,2),
		PresentDays7 decimal(6,2), 
		TotalDays8 decimal(6,2),
		PresentDays8 decimal(6,2),
		TotalDays9 decimal(6,2),
		PresentDays9 decimal(6,2),
		TotalDays10 decimal(6,2),
		PresentDays10 decimal(6,2),
		TotalDays11 decimal(6,2),
		PresentDays11 decimal(6,2),
		TotalDays12 decimal(6,2),
		PresentDays12 decimal(6,2),
		TotalDays13 decimal(6,2),
		PresentDays13 decimal(6,2),
		BatchIdText nvarchar(20),
		IsShowWithDetail bit,
		IsPresent bit,
		GradeTitle nvarchar(50),
		SubjectHighestDivisionGrade nvarchar(50),
		SubjectHighestDivisionMark decimal(5, 2),
		
		AchievementsTerm1 nvarchar(1000),
		AchievementsTerm2 nvarchar(1000),
		GeneralRemarkTerm1 nvarchar(200),
		GeneralRemarkTerm2 nvarchar(200),
		ResultRemark1Term1 nvarchar(200),
		ResultRemark2Term1 nvarchar(200),
		ResultRemark1Term2 nvarchar(200),
		ResultRemark2Term2 nvarchar(200),
		SR_HeightTerm1 decimal(5,2),
		SR_WeightTerm1 decimal(5,2),
		SR_HeightTerm2 decimal(5,2),
		SR_WeightTerm2 decimal(5,2),
		SR_PresentDaysTerm1 decimal(6,2),
		SR_PresentDaysTerm2 decimal(6,2),
		SR_TotalDaysTerm1 decimal(6,2),
		SR_TotalDaysTerm2 decimal(6,2),
		HouseId int,
		HouseName nvarchar(100),
		AdhaarNumber nvarchar(100),
		UIdNumber nvarchar(100),
		FatherContactNo nvarchar(50),
		MotherContactNo nvarchar(50),
		FatherMail nvarchar(max),
		MotherMail nvarchar(max),
		Gender nvarchar(100),
		CoordinatorEmployeeSign varbinary(max),
		StudentAddress nvarchar(max),
		SUId nvarchar(50),
		HighestDivisionMark decimal(5, 2),
		HighestDivisionGrade nvarchar(50),
		StreamTitle nvarchar(50),
		AdmissionNo nvarchar(50),
		AdmissionDate Date,
		MiddleName nvarchar(50) ,
		FatherOccupation nvarchar(50),
		ResultSheetAdditionalTitle nvarchar(100),
		IsDecimal bit,
		IsAbsentRemark bit,
		FinalAbsentRemark nvarchar(100),
		AbsentRemark1 nvarchar(100),
		AbsentRemark2 nvarchar(100),
		AbsentRemark3 nvarchar(100),
		AbsentRemark4 nvarchar(100),
		AbsentRemark5 nvarchar(100),
		AbsentRemark6 nvarchar(100),
		AbsentRemark7 nvarchar(100),
		AbsentRemark8 nvarchar(100),
		AbsentRemark9 nvarchar(100),
		AbsentRemark10 nvarchar(100),
		AbsentRemark11 nvarchar(100),
		AbsentRemark12 nvarchar(100),
		AbsentRemark13 nvarchar(100),
		ExamMaximumTerm1 decimal(6,2),
		ExamMaximumTerm2 decimal(6,2),
		ExamMaximumTerm3 decimal(6,2),
		ExamMaximumTerm4 decimal(6,2)

		)	
	 --print 'temp created'    	
	INSERT INTO  #TempAllExam 
	(
	AcademicIdText,
	ExamIdText,
	CoScholasticScopeIdText,
	IsDisplayMonthlyAttendanceText,
	ClassIdText,
	AcademicId,
	ExamName,
	StudCode,
	StudentName,
	RollNo,
	ResultStatus,
	ClassName,
	Division,
	TotalMark,
	TotalObtain,
	Percentage,
	RankNumber,
	ResultGrade,
	IsMarksInDecimal,
	column_visible,
	--Obtain,
	Percentile,
	--ClassSubject,
	ResultDetailId,
	ResultId,

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


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

		ISNULL(EM.Remark1,'') AS Remark1,
		ISNULL(EM.Remark2,'') AS Remark2,
		ISNULL(EM.Remark3,'') AS Remark3,
		EM.DisplayTitle,
		EM.IsRankNo, 
		EM.IsGrade,
		EM.IsPercentile,
		EM.IsPercentage,
		EM.IsSubjectPercentile,
		EM.IsProcessResult,
		EM.IsNegativeMarks,
		EM.IsIncludeCoScholastic,
		EM.IsOnPrePrinted,
		EM.IsDisplayPhoto,
		EM.IsDisplayBirthDate,
		EM.IsLockForEdit,
		EM.IsDisplaySchoolName,			
		EM.IsDisplayAttendance,
		EM.IsDisplayHeightWeight,
		EM.IsResultStatus,
		REPLICATE(',',EM.FooterAdjustment) AS FooterAdjustmentText,
		REPLICATE(',',EM.DetailAdjustment) AS DetailAdjustmentText,
		EM.FooterAdjustment,
		EM.DetailAdjustment,
		ISNULL(R.ResultRemark,'') AS ResultRemark,
		SO.DateOfBirth,
		AD.HeightTerm1,
		AD.WeightTerm1,
		AD.HeightTerm2,
		AD.WeightTerm2,
		AD.HeightAnnual,
		AD.WeightAnnual,
		AD.PresentDaysTerm1,
		AD.PresentDaysTerm2,
		AD.PresentDaysAnnual,
		AD.TotalDaysTerm1,
		AD.TotalDaysTerm2,
		AD.TotalDaysAnnual,
		EM.TermScopeId,
		(CASE EM.IsDisplayPhoto WHEN 1 THEN
		SI.StudentPhoto
		ELSE NULL END)AS StudentPhoto,
		CASE @GradeStringRemark WHEN '' THEN @GradeString ELSE @GradeStringRemark END AS GradeString,
		EM.IsDisplayGradeString,
		ED.IsDisplayInMarksheet,
		ED.IsShowSubjectGrade,
		ED.IsIncludeInTotal,
	    ED.ClassSubjectId,
		CS.SubjectId AS SubjectId,
		--ED.Maximum,
		(CASE ISNULL(ED.DisplayOrder,0)
		WHEN 0 THEN CS.OrderIndex
		ELSE ED.DisplayOrder END) AS SubjectOrderIndex,
		
		--SM.OrderIndex AS SubjectOrderIndex,
		RD.SubjectGrade,
		SM.Title AS SubjectName,
		ISNULL(SM.Code,'') AS SubjectCode,
		ED.Minimum,
		ED.Maximum,
		RD.Obtain,
		SR.ResultRemark1,
		SR.ResultRemark2,
		ISNULL(SR.TotalDays,0)AS TotalDays,
		ISNULL(SR.PresentDays,0)AS 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,
		(CASE EM.IsDisplayImageHeader WHEN 1 THEN 
		OI.MarksheetHeaderA4 
		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,
		RD.KrupaMark,
		@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) AS BatchIdText,
		@rIsShowWithDetail AS IsShowWithDetail,
		IsPresent,
		GradeTitle ,
		RAD.SubjectHighestDivisionGrade,
		RAD.SubjectHighestDivisionMark,
		
		'' AS AchievementsTerm1,
		'' AS AchievementsTerm2,
		'' AS GeneralRemarkTerm1,
		'' AS GeneralRemarkTerm2,
		'' AS ResultRemark1Term1,
		'' AS ResultRemark2Term1, 
		'' AS ResultRemark1Term2,
		'' AS ResultRemark2Term2,
		SR.StudentHeight AS SR_HeightTerm1,
		SR.StudentWeight AS SR_WeightTerm1,
		SR.StudentHeight AS SR_HeightTerm2,
		SR.StudentWeight AS SR_WeightTerm2,
		ISNULL(SR.PresentDays,0) AS SR_PresentDaysTerm1,
	    ISNULL(SR.PresentDays,0) AS SR_PresentDaysTerm2,
	    ISNULL(SR.TotalDays,0) AS SR_TotalDaysTerm1,
	    ISNULL(SR.TotalDays,0) AS SR_TotalDaysTerm2,
	    HM.Title As HouseName,HM.Id as HouseId,
	    ISNULL(SO.AdhaarNumber,'') As AdhaarNumber,
	    ISNULL(SO.UIdNumber,'') As UIdNumber,
		SF.FatherContactNo,
		SF.MotherContactNo,
		SF.FatherMail,
		SF.MotherMail,
		(CASE WHEN SO.GenderId=1 THEN 'Male' ELSE 'Female' END)AS Gender,
		(CASE  When EM.CoordinatorEmployeeId IS NOT NULL AND EM.CoordinatorEmployeeId !=0 then EICoordinator.EmployeeSign ELSE NULL END) AS CoordinatorEmployeeSign,
		(SC.PresentStreetOne +' '+ SC.PresentStreetTwo +' '+ SC.PresentStreetThree +' '+ SC.PresentCity +' '+ SC.PermanentState) AS StudentAddress,
		ISNULL(Stum.SUId,'') AS SUId,
		(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,
		ISNULL(StM.Title,'') AS StreamTitle,
		ISNULL(StuA.AdmissionNumber,0) AS AdmissionNo,
		ISNULL(StuA.AdmissionDate,'') AS AdmissionDate,
		Stum.MiddleName ,
		ISNULL(SF.FatherOccupation,'') AS FatherOccupation,
		ISNULL(EM.ResultSheetAdditionalTitle, '') AS ResultSheetAdditionalTitle,
		CONVERT(bit,@lDecimalConfig) AS IsDecimal,
		CONVERT(bit,@lAbsentRemarkConfig) AS IsAbsentRemark,
		ISNULL(RD.AbsentRemark,'') AS FinalAbsentRemark
				
FROM 
	sAssessment.tResultDetail RD
	INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
	INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId AND R.ExamId = ED.ExamId
	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.tStreamMaster StM ON CM.StreamId = Stm.Id
	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 AND  ISNULL(EMP.IsOtherUser,0) = 0
	INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.EXAMSUBGROUPID
	LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=StuM.Id
	Left JOIN sActivity.tHouseMaster HM ON SO.HouseId = HM.Id
	LEFT JOIN sStudent.tAcademicDetail AD ON AD.AcademicId=A.Id
	LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=StuM.Id
	LEFT JOIN sAssessment.tStudentRemark SR ON R.AcademicId = SR.AcademicId AND R.ExamId = SR.ExamId
	LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = StuM.Id
	LEFT JOIN sAssessment.tOptionalSubject OS ON OS.AcademicId = R.AcademicId AND OS.ClassSubjectId = ED.ClassSubjectId  AND ED.ExamId = R.ExamId
	LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=A.StudentId
	LEFT JOIN 	sCommon.tBloodGroupMaster BGM ON BGM.Id=So.BloodGroupId
	LEFT JOIN sAssessment.tGradeSetDetail GS ON GS.GradeSetId=ED.GradeSetId AND ED.GradeSetId = @GradeSetId and RD.SubjectGrade = GS.GradeCode
	LEFT JOIN sAssessment.tResultAnalysisDivisionDetail RAD ON RAD.ClassSubjectId = CS.Id AND RAD.DivisionId = A.DivisionId AND RAD.ExamId = Em.Id
	
	LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=StuM.Id AND AR.SourceTypeId=2003 AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0) AND (BM.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 = StuM.Id 
	LEFT JOIN sHrm.tEmployeeImages EICoordinator ON EICoordinator.EmployeeId = EM.CoordinatorEmployeeId		  
	--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
	LEFT JOIN sStudent.tStudentAdmission StuA ON StuM.Id = StuA.StudentId
	
	 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.TotalObtain>=@rFromObtain) OR (@rFromObtain=0))
		AND ((R.TotalObtain<=@rToObtain) OR (@rToObtain=0))
		AND ((R.Percentage>=@rFromPercentage) OR (@rFromPercentage=0))
		AND ((R.Percentage<=@rToPercentage) OR (@rToPercentage=0))
		
		 AND (
	 (@rFilterId = 0) -- All
     OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel
     OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport
     OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))
    )
	AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)) 
	AND (ISNULL(StuM.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rMultiCode,',')) OR @rMultiCode='')
	    
	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
	--print ('tempcombine')
	--SELECT * FROM #tempcombineExam
	--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)+'= ISNULL(RD.Obtain,0),
					 IsPresent' + convert(nvarchar(15),@lCount)+'=RD.IsPresent,	
					 AbsentRemark' + convert(nvarchar(15),@lCount)+'= ISNULL(RD.AbsentRemark,' + CHAR(39)+CHAR(39) + '),
					 		
					 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 AND R.ExamId = ED.ExamId
						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)  
						
--print(@query)
	 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.ExamSubGroupDisplayTitle,
					Exam' + convert(nvarchar(15),@lCount)+ 'Code=ESGM.Code,
					ExamMaximum' + convert(nvarchar(15),@lCount)+'=ISNULL(EM.ExamMaximum,0)
					 From						
						sAssessment.tResult R						
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON  T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
						
		execute(@query)
		
		Declare @lCombineExamId int
			SELECT @lCombineExamId = EC.ExamId  FROM [sAssessment].[tExamMaster] EM 
										INNER JOIN SASSESSMENT.TEXAMSUBGROUPmASTER ESGM ON ESGM.ID = EM.ExamSubGroupId  
										INNER JOIN sAssessment.tExamCombine EC ON EC.SubExamId=EM.Id AND EC.ExamId in (SELECT SubExamId  FROM sAssessment.tExamCombine WHERE examid=@rExamId) 
										WHERE   (EM.ClassId=@rClassId) AND EM.BatchId =@rBatchId AND EM.Id = @lSubExamId
			--SELECT @lSubCombineExamName
		set @query ='update T set 
					 Exam' + convert(nvarchar(15),@lCount)+ 'CombineExamName =  EM.DisplayTitle
					  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), @lCombineExamId) 
				
				--Print @query		
		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 AND R.ExamId = ED.ExamId
						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,
					AchievementsTerm1 = SR.Achievements,
					GeneralRemarkTerm1 = SR.GeneralRemark,
					ResultRemark1Term1 = SR.ResultRemark1,
					ResultRemark2Term1 = SR.ResultRemark2,
					SR_HeightTerm1 = SR.StudentHeight,
					SR_WeightTerm1 = SR.StudentWeight,
					SR_PresentDaysTerm1 = SR.PresentDays,
					SR_TotalDaysTerm1 = SR.TotalDays,
					ExamMaximumTerm1 = EM.ExamMaximum
					
					From
					 
						sAssessment.tResult  R 				
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id = R.ExamId
						LEFT JOIN sAssessment.tStudentRemark SR ON SR.AcademicId = R.AcademicId AND SR.ExamId = EM.Id
						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,
					AchievementsTerm2 = SR.Achievements,
					GeneralRemarkTerm2 = SR.GeneralRemark,
					ResultRemark1Term2 = SR.ResultRemark1,
					ResultRemark2Term2 = SR.ResultRemark2,
					SR_HeightTerm2 = SR.StudentHeight,
					SR_WeightTerm2 = SR.StudentWeight,
					SR_PresentDaysTerm2 = SR.PresentDays,
					SR_TotalDaysTerm2 = SR.TotalDays
									 
					 From
						sAssessment.tResultDetail RD
						INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId AND R.ExamId = ED.ExamId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						LEFT JOIN sAssessment.tStudentRemark SR ON SR.AcademicId = R.AcademicId AND SR.ExamId = EM.Id
						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,
					ExamMaximumTerm2 = 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)
		
		select @lSubExamId = SubExamId from sAssessment.tExamCombine  Where ExamId  = @rExamId AND ExamOrder = 3
		set @query ='update T set					 
					SubjectGradeTerm3=RD.SubjectGrade,
					SubjectObtainTerm3 = RD.Obtain,
					SubjectMaxTerm3= ED.Maximum				 
					 From
						sAssessment.tResultDetail RD
						INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId AND R.ExamId = ED.ExamId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
		execute(@query)
		set @query ='update T set
 
					TotalMarkTerm3 = R.TotalMarks,
					TotalObtainTerm3=R.TotalObtain,
					PercentageTerm3=R.Percentage,
					RankNumberTerm3=R.RankNumber,
					ResultGradeTerm3=R.ResultGrade,
					PercentileTerm3 = R.Percentile,
					ResultStatusTerm3 = R.ResultStatus,
					ExamNameTerm3 = ESGM.Code,
					ExamMaximumTerm3 = 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)

		--for 4 Term
		select @lSubExamId = SubExamId from sAssessment.tExamCombine  Where ExamId  = @rExamId AND ExamOrder = 4
		--select @ExamTitle = Title from sAssessment.tExamMaster Where Id = @lSubExamId	
		set @query ='update T set					 
					SubjectGradeTerm4=RD.SubjectGrade,
					SubjectObtainTerm4 = RD.Obtain,
					SubjectMaxTerm4= 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 AND R.ExamId = ED.ExamId
					INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
					LEFT JOIN sAssessment.tStudentRemark SR ON SR.AcademicId = R.AcademicId AND SR.ExamId = EM.Id
					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
 
					TotalMarkTerm4 = R.TotalMarks,
					TotalObtainTerm4 =R.TotalObtain,
					PercentageTerm4 =R.Percentage,
					RankNumberTerm4 =R.RankNumber,
					ResultGradeTerm4 =R.ResultGrade,
					PercentileTerm4  = R.Percentile,
					ResultStatusTerm4  = R.ResultStatus,
					ExamNameTerm4 = ESGM.Code,
					ExamMaximumTerm4 = 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)
	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
	--SELECT * FROM #TempAllExam	
	drop table #tempcombineExam
	Drop table #TempAllExam
	
	--Select
	--	'' As Builder1,
	--	'' As Builder2,
	--    '' As AcademicIdText,
	--	'' As ExamIdText,
	--	'' As CoScholasticScopeIdText ,
	--	'' As IsDisplayMonthlyAttendanceText,
	--    '' AS ClassIdText,
	--	0 As AcademicId,
	--	'' As ExamName,
	--	'' As StudCode,
	--	'' As StudentName ,
	--	0 As RollNo,
	--	'' As ResultStatus ,	
	--	'' As ClassName ,		
	--	'' As Division ,
	--	0 As TotalMark ,
	--	0 As TotalObtain,
	--	0 As Percentage ,
	--	0 As RankNumber ,
	--	'' As ResultGrade ,
 --       '' As IsMarksInDecimal,
 --             0 As column_visible,

 --             0 As Percentile ,

 --            0 As ResultDetailId, 
 --            0 As ResultId,

	--	'' As Remark1 ,
	--	'' As Remark2 ,
	--	'' As Remark3 ,
	--	'' As DisplayTitle ,		
	--	0 As IsRankNo , 
	--	0 As IsGrade ,
	--	0 As IsPercentile ,
	--	0 As IsPercentage ,
	--	0 As IsSubjectPercentile ,
	--	0 As IsProcessResult ,
	--	0 As IsNegativeMarks ,
	--	0 As IsIncludeCoScholastic ,
	--	0 As IsOnPrePrinted ,
	--	0 As IsDisplayPhoto ,
	--	0 As IsDisplayBirthDate ,
	--	0 As IsLockForEdit ,
	--	0 As IsDisplaySchoolName ,			
	--	0 As IsDisplayAttendance ,
	--	0 As IsDisplayHeightWeight ,
	--	0 As IsResultStatus ,
	--	'' As FooterAdjustmentText ,
	--	'' As DetailAdjustmentText ,
	--	0 As FooterAdjustment ,
	--	0 As DetailAdjustment ,
	--	'' As ResultRemark ,
	--	'' As DateOfBirth ,
	--	0 As HeightTerm1 ,
	--	0 As WeightTerm1 ,
	--	0 As HeightTerm2,
	--	0 As WeightTerm2 ,
	--	0 As HeightAnnual ,
	--	0 As WeightAnnual ,
	--	0 As PresentDaysTerm1,
	--	0 As PresentDaysTerm2 ,
	--	0 As PresentDaysAnnual ,
	--	0 As TotalDaysTerm1 ,
	--	0 As TotalDaysTerm2 ,
	--	0 As TotalDaysAnnual ,
	--	0 As TermScopeId ,		 
	--	0x As StudentPhoto ,
	--	'' As GradeString,
	--	0 As IsDisplayGradeString ,		 
	--	0 As IsDisplayInMarksheet ,
	--	0 As IsShowSubjectGrade ,
	--	0 As IsIncludeInTotal ,
	--	0 As ClassSubjectID ,
	--	0 As SubjectId ,
	--	--Maximum decimal(5,2),
	--	0 As SubjectOrderIndex ,
	--	'' As SubjectGrade ,
	--	'' As SubjectName ,
	--	'' As SubjectCode ,	
	--	0 As SubjectMinimum ,		
	--	0 As SubjectMaximum ,
	--	0 As SubjectObtain ,
	--	'' As ResultRemark1 ,
	--	'' As ResultRemark2,

	--	0 As TotalDays ,
	--	0 As PresentDays ,
	--	0 As StudentHeight,
	--	0 As StudentWeight ,
	--	'' As ExamSeatNo ,
	--    0 As ExamId ,

 --       '' AS ExamCode,

	--	0 As IsDisplayParentName ,
	--	'' As FatherName ,
	--	'' As MotherName ,
	--	0 As IsShowSubjectMark , 
	--	0 As IsOptionalSubject ,
	--	0 As CoScholasticScopeId ,
	--	0 As IsDisplayPrincipalSign ,
	--	0 As IsDisplayTeacherSign ,
	--	0x As EmployeeSign,
 --            '' As Batch,
 --            '' As ClassTeacherName,
 --      '' AS FirstName,
 --      '' AS LastName,
 --            0 As IsDisplayMonthlyAttendance,
	--	0x As MarksheetHeaderA4 ,
	--	0 As IsImageHeader ,
 --            '' As    MyGoal,
 --       '' As  AreaOfInterest,
 --       '' As Responsibility,
 --       '' As MyInterestHobby,
 --       '' As MyStrength,
 --       '' As Achievements,

	--	  '' As DentalHygiene ,
	--	'' As VisionLeft ,
	--	'' As VisionRight ,
 --             0 As IsDetail,
 --             0 AS   SubjectGroupId,
 --             ''   AS SubjectGroupTitle,
 --        '' AS SubjectGroupCode,
 --        '' AS DecimalFormat,
 --        '' AS SubjectRemark,
 --               0 As GraceMark,
 --               0 As KrupaMark,
 --                '' As GradeStringHtml,
 --          '' As ResultRemark3,
 --         0 As IsDisplayTotalMark,
 --         ''  As ContactNo,
	--	'' As PresentAddress ,
	--	'' As TeacherSignCaption ,
	--	'' As PrincipalSignCaption ,
	--	'' As ParentSignCaption ,
 --       '' As ImprovementArea,
 --       '' As ProgressArea,
 --       '' As GeneralRemark,
 --              '' As MyActivity,
 --        ''  As ClassTeacherRemark,

 --        '' As HouseRemark,
	--	  '' As BloodGroup ,
 --         '' As BatchIdText,
 --                0 As IsShowWithDetail,
 --                0 As IsPresent,
 --                ''  As GradeTitle,

 --         '' As SubjectHighestDivisionGrade,
 --                 0  As SubjectHighestDivisionMark,

 --         '' As  AchievementsTerm1,
 --         '' As  AchievementsTerm2,
 --         '' As GeneralRemarkTerm1,
 --         '' As GeneralRemarkTerm2,
 --         '' As ResultRemark1Term1,
 --          '' As ResultRemark2Term1,
 --          '' As ResultRemark1Term2,
 --         '' As ResultRemark2Term2,
 --         0 As SR_HeightTerm1,
 --         0 As SR_WeightTerm1,
 --         0 As SR_HeightTerm2,
 --         0 As SR_WeightTerm2,
 --         0 As SR_PresentDaysTerm1,
 --         0 As SR_PresentDaysTerm2,
 --         0 As SR_TotalDaysTerm1,
 --         0 As SR_TotalDaysTerm2,
 --         '' As HouseName,
 --         0 As HouseId,
 --         '' As AdhaarNumber,
 --         '' As UidNumber,
 --         '' As FatherContactNo,
 --         '' As MotherContactNo,
 --         '' As FatherMail,
 --         '' As MotherMail,
 --         '' AS Gender,
	--		0x AS CoordinatorEmployeeSign ,	
 --			'' As FatherOccupation ,
 --			0 AS IsDecimal,
 --			CONVERT(decimal(6,2),0) AS ExamMaximumTerm1,
 --			CONVERT(decimal(6,2),0) AS ExamMaximumTerm2,
 --			CONVERT(decimal(6,2),0) AS ExamMaximumTerm3

 --SELECT @rBuilder1 AS Builder1,@rBuilder2 AS Builder2, T.* FROM sAssessment.tTempAllExamWithAllTerm T
 
	END
	--SELECT @rBuilder1 AS Builder1,@rBuilder2 AS Builder2, T.* FROM sAssessment.tTempAllExam T
	
--end
GO
PRINT N'Creating Procedure [sTimetable].[pApplyEmployee]...';


GO
CREATE PROCEDURE [sTimetable].[pApplyEmployee]
    @rTimeTableSchemaId INT,
	@rDivisionId1 INT,
	@rDivisionId2 INT,
	@rCreatedUserId BIGINT
	

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
--First sp
--BEGIN
--	DECLARE @lClassId1 INT,
--			@lClassId2 INT,
--			@lRowCount INT = 1,
--			@lTotalRows INT,
--			@lSubjectId INT,
--			@lNoOfLecture1 TINYINT,
--			@lNoOfLecture2 TINYINT,
--			@lNoOfLecture3 TINYINT,
--			@lLectureLength TINYINT,
--			@lBatchId INT,
--			@lEmployeeId BIGINT

--	SELECT @lClassId1=ClassId FROM sSetup.tDivisionMaster WHERE Id=@rDivisionId1
--	SELECT @lClassId2=ClassId FROM sSetup.tDivisionMaster WHERE Id=@rDivisionId2

--	CREATE TABLE #TempData
--	(
--		SubjectId INT
--	)

--	INSERT INTO #TempData (SubjectId)
--	SELECT CS2.SubjectId
--	FROM sSetup.tClassSubject CS1 
--		INNER JOIN sSetup.tClassSubject CS2 ON CS1.SubjectId = CS2.SubjectId
--		INNER JOIN sTimetable.tTeacherWorkLoad TWL1 ON TWL1.SubjectId=CS2.SubjectId
--	WHERE CS1.ClassId = @lClassId1 
--		AND CS2.ClassId = @lClassId2
--		AND TWL1.TimeTableSchemaId=@rTimeTableSchemaId
--		AND TWL1.DivisionId=@rDivisionId1

--	SELECT @lTotalRows = COUNT(*) FROM #TempData

--	WHILE @lRowCount <= @lTotalRows
--	BEGIN
--		-- Fetch data from the temporary table one by one
--		SELECT TOP 1 @lSubjectId = SubjectId
--		FROM #TempData
--		WHERE SubjectId IN (SELECT TOP (@lRowCount) SubjectId FROM #TempData ORDER BY SubjectId DESC) ORDER BY SubjectId;

--		--Check Lecture
--		SELECT @lNoOfLecture1=NoOfLecture FROM sTimetable.tDivisionWorkLoad WHERE TimeTableSchemaId=@rTimeTableSchemaId AND DivisionId=@rDivisionId1 AND SubjectId=@lSubjectId
--		SELECT @lNoOfLecture2=NoOfLecture FROM sTimetable.tDivisionWorkLoad WHERE TimeTableSchemaId=@rTimeTableSchemaId AND DivisionId=@rDivisionId2 AND SubjectId=@lSubjectId
--		SELECT @lNoOfLecture3=SUM(NoOfLecture) FROM sTimetable.tTeacherWorkLoad WHERE TimeTableSchemaId=@rTimeTableSchemaId AND DivisionId=@rDivisionId2 AND SubjectId=@lSubjectId GROUP BY SubjectId

--		IF(@lNoOfLecture1!=@lNoOfLecture2)
--		BEGIN
--			SELECT -101 AS Result
--		END

--		ELSE IF (@lNoOfLecture3>=@lNoOfLecture2)
--		BEGIN
--			SELECT -102 AS Result
--		END

--		ELSE
--		BEGIN
--			-- Fetch the corresponding data from sTimetable.tTeacherWorkLoad
--			SELECT TOP 1
--				@lBatchId = BatchId,
--				@lEmployeeId = EmployeeId,
--				@lLectureLength = LectureLength
--			FROM sTimetable.tTeacherWorkLoad
--			WHERE DivisionId = @rDivisionId1 
--				AND TimeTableSchemaId = @rTimeTableSchemaId
--				AND SubjectId = @lSubjectId;

--			-- Insert data one by one into the main table
--			INSERT INTO sTimetable.tTeacherWorkLoad 
--			(
--				BatchId,
--				EmployeeId,
--				DivisionId,
--				SubjectId,
--				NoOfLecture,
--				CreatedUserId,
--				CreatedDateTime,
--				TimeTableSchemaId,
--				LectureLength
--			)
--			VALUES 
--			(
--				@lBatchId,
--				@lEmployeeId,
--				@rDivisionId2,  -- Your DivisionId value
--				@lSubjectId, -- Value from the subquery
--				@lNoOfLecture2,
--				@rCreatedUserId,
--				[sCommon].[fGetDate](),
--				@rTimeTableSchemaId,
--				@lLectureLength
--			);
--			SELECT 1 AS Result
--		END

--		-- Increment the row count
--		SET @lRowCount = @lRowCount + 1;
--	END

--	-- Drop the temporary table
--	DROP TABLE #TempData;
--END

--Second sp
--BEGIN
--	DECLARE @lClassId1 INT,
--			@lClassId2 INT
--	SELECT @lClassId1=ClassId FROM sSetup.tDivisionMaster WHERE Id=@rDivisionId1
--	SELECT @lClassId2=ClassId FROM sSetup.tDivisionMaster WHERE Id=@rDivisionId2
--	INSERT INTO sTimetable.tTeacherWorkLoad 
--	(
--		BatchId,
--		EmployeeId,
--		DivisionId,
--		SubjectId,
--		NoOfLecture,
--		CreatedUserId,
--		CreatedDateTime,
--		TimeTableSchemaId,
--		LectureLength
--	)
--	SELECT	TWL1.BatchId , 
--			TWL1.EmployeeId, 
--			@rDivisionId2,
--			TWL1.SubjectId,
--			TWL1.NoOfLecture,
--			@rCreatedUserId,
--			[sCommon].[fGetDate](), 
--			TWL1.TimeTableSchemaId,
--			TWL1.LectureLength
--	FROM sSetup.tClassSubject CS1
--	--FROM sTimetable.tTeacherWorkLoad TWL1
--	INNER JOIN sSetup.tClassSubject CS2 ON CS1.SubjectId = CS2.SubjectId
--	INNER JOIN sTimetable.tTeacherWorkLoad TWL1 ON TWL1.SubjectId=CS2.SubjectId
--	WHERE CS1.ClassId = @lClassId1
--		AND CS2.ClassId = @lClassId2
--		AND TWL1.TimeTableSchemaId=@rTimeTableSchemaId
--		AND TWL1.DivisionId=@rDivisionId1

--SELECT 1 AS Result
--END


--Third sp
BEGIN
	if exists(select Employeeid from sTimetable.tTeacherWorkLoad  where DivisionId=@rDivisionId2 AND TimeTableSchemaId=@rTimeTableSchemaId)
	BEGIN
		Select -101 As Result
	END

	ELSE
	BEGIN
		DECLARE @lClassId1 INT,
				@lClassId2 INT
		SELECT @lClassId1=ClassId FROM sSetup.tDivisionMaster WHERE Id=@rDivisionId1
		SELECT @lClassId2=ClassId FROM sSetup.tDivisionMaster WHERE Id=@rDivisionId2

		INSERT INTO sTimetable.tTeacherWorkLoad
		(
			BatchId,
			EmployeeId,
			DivisionId,
			SubjectId,
			NoOfLecture,
			CreatedUserId,
			CreatedDateTime,
			TimeTableSchemaId,
			LectureLength
		)
		SELECT	TWL1.BatchId
				,TWL1.EmployeeId
				,@rDivisionId2
				,TWL1.SubjectId
				,TWL1.NoOfLecture
				,@rCreatedUserId
				,[sCommon].[fGetDate]()
				,@rTimeTableSchemaId
				,TWL1.LectureLength
		FROM sSetup.tClassSubject CS1 
			INNER JOIN sSetup.tClassSubject CS2 ON CS2.SubjectId = CS1.SubjectId
			INNER JOIN sTimetable.tTeacherWorkLoad TWL1 ON TWL1.SubjectId=CS2.SubjectId
			INNER JOIN sTimetable.tDivisionWorkLoad DWL1 ON DWL1.SubjectId=CS2.SubjectId AND DWL1.DivisionId=TWL1.DivisionId AND DWL1.TimeTableSchemaId=TWL1.TimeTableSchemaId
			INNER JOIN sTimetable.tDivisionWorkLoad DWL2 ON DWL2.SubjectId=CS2.SubjectId AND DWL2.DivisionId=@rDivisionId2 AND DWL2.NoOfLecture=DWL1.NoOfLecture AND DWL2.TimeTableSchemaId=TWL1.TimeTableSchemaId
		WHERE CS1.ClassId = @lClassId1 
			AND CS2.ClassId = @lClassId2
			AND TWL1.TimeTableSchemaId=@rTimeTableSchemaId
			AND TWL1.DivisionId=@rDivisionId1

		SELECT 1 AS Result
	END
END
GO





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

