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

 
GO
PRINT N'Starting rebuilding table [sAdmission].[tAdmissionInquiry]...';


GO
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;

SET XACT_ABORT ON;

BEGIN TRANSACTION;

CREATE TABLE [sAdmission].[tmp_ms_xx_tAdmissionInquiry] (
    [Id]                    BIGINT          NOT NULL,
    [FirstName]             NVARCHAR (100)  NOT NULL,
    [MiddleName]            NVARCHAR (100)  NULL,
    [LastName]              NVARCHAR (100)  NULL,
    [ForClassId]            INT             NOT NULL,
    [ForBatchId]            INT             NULL,
    [ForBatch]              NVARCHAR (20)   NULL,
    [DateOfBirth]           DATE            NULL,
    [OrgId]                 SMALLINT        NOT NULL,
    [StatusId]              SMALLINT        NOT NULL,
    [StreetOne]             NVARCHAR (50)   NULL,
    [StreetTwo]             NVARCHAR (50)   NULL,
    [StreetThree]           NVARCHAR (50)   NULL,
    [Country]               NVARCHAR (50)   NULL,
    [State]                 NVARCHAR (50)   NULL,
    [City]                  NVARCHAR (50)   NULL,
    [ZipCode]               NVARCHAR (20)   NULL,
    [ContactNo]             NVARCHAR (20)   NULL,
    [ContactEmail]          NVARCHAR (50)   NULL,
    [Remark]                NVARCHAR (200)  NULL,
    [InquiryModeId]         TINYINT         NULL,
    [InquiryReferenceId]    INT             NULL,
    [AdmissionCategoryId]   INT             NULL,
    [PreviousSchool]        NVARCHAR (200)  NULL,
    [MeritMarks]            DECIMAL (10, 2) NULL,
    [MeritGrade]            NVARCHAR (20)   NULL,
    [MeritMarksBreakup]     NVARCHAR (100)  NULL,
    [GenderId]              TINYINT         NULL,
    [FollowupDate]          DATE            NULL,
    [FollowupRemark]        NVARCHAR (150)  NULL,
    [CreatedUserId]         BIGINT          NOT NULL,
    [CreatedDateTime]       DATETIME        NOT NULL,
    [UpdatedUserId]         BIGINT          NULL,
    [UpdatedDateTime]       DATETIME        NULL,
    [StudentId]             BIGINT          NULL,
    [InquiryDate]           DATE            NULL,
    [Number]                BIGINT          NULL,
    [HandledBy]             NVARCHAR (100)  NULL,
    [OrgGroupId]            INT             NULL,
    [InquiryStatusId]       INT             NULL,
    [CastCategoryId]        INT             NULL,
    [IsTransportRequired]   BIT             NULL,
    [IsHostelRequired]      BIT             NULL,
    [AdmissionFormId]       BIGINT          NULL,
    [IsGivenAdmissionForm]  BIT             NULL,
    [AlternateContactNo]    NVARCHAR (100)  NULL,
    [AlternateContactEmail] NVARCHAR (200)  NULL,
    [MotherName]            NVARCHAR (100)  NULL,
    [DataEntryModeId]       SMALLINT        NULL,
    [MinorityStatusId]      SMALLINT        NULL,
    [LiveWithId]            SMALLINT        NULL,
    [AdhaarNumber]          NVARCHAR (20)   NULL,
    [BloodGroupId]          TINYINT         NULL,
    [FatherName]            NVARCHAR (100)  NULL,
    [FatherOccupation]      NVARCHAR (50)   NULL,
    [FatherIncome]          INT             NULL,
    [FatherContactNo]       NVARCHAR (50)   NULL,
    [FatherMail]            NVARCHAR (50)   NULL,
    [FatherQualification]   NVARCHAR (50)   NULL,
    [MotherOccupation]      NVARCHAR (50)   NULL,
    [MotherIncome]          INT             NULL,
    [MotherContactNo]       NVARCHAR (50)   NULL,
    [MotherMail]            NVARCHAR (50)   NULL,
    [MotherQualification]   NVARCHAR (50)   NULL,
    [Stream]                NVARCHAR (20)   NULL,
    [Board]                 NVARCHAR (50)   NULL
);

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

IF EXISTS (SELECT TOP 1 1
           FROM   [sAdmission].[tAdmissionInquiry])
    BEGIN
        INSERT INTO [sAdmission].[tmp_ms_xx_tAdmissionInquiry] ([Id], [FirstName], [MiddleName], [LastName], [ForClassId], [ForBatchId], [ForBatch], [DateOfBirth], [OrgId], [StatusId], [StreetOne], [StreetTwo], [StreetThree], [Country], [State], [City], [ZipCode], [ContactNo], [ContactEmail], [Remark], [InquiryModeId], [InquiryReferenceId], [AdmissionCategoryId], [PreviousSchool], [MeritMarks], [MeritGrade], [MeritMarksBreakup], [GenderId], [FollowupDate], [FollowupRemark], [CreatedUserId], [CreatedDateTime], [UpdatedUserId], [UpdatedDateTime], [StudentId], [InquiryDate], [Number], [HandledBy], [OrgGroupId], [InquiryStatusId], [CastCategoryId], [IsTransportRequired], [IsHostelRequired], [AdmissionFormId], [IsGivenAdmissionForm], [AlternateContactNo], [AlternateContactEmail], [MotherName], [DataEntryModeId], [MinorityStatusId], [LiveWithId], [AdhaarNumber], [BloodGroupId], [FatherOccupation], [FatherIncome], [FatherContactNo], [FatherMail], [FatherQualification], [MotherOccupation], [MotherIncome], [MotherContactNo], [MotherMail], [MotherQualification], [Stream], [Board])
        SELECT   [Id],
                 [FirstName],
                 [MiddleName],
                 [LastName],
                 [ForClassId],
                 [ForBatchId],
                 [ForBatch],
                 [DateOfBirth],
                 [OrgId],
                 [StatusId],
                 [StreetOne],
                 [StreetTwo],
                 [StreetThree],
                 [Country],
                 [State],
                 [City],
                 [ZipCode],
                 [ContactNo],
                 [ContactEmail],
                 [Remark],
                 [InquiryModeId],
                 [InquiryReferenceId],
                 [AdmissionCategoryId],
                 [PreviousSchool],
                 [MeritMarks],
                 [MeritGrade],
                 [MeritMarksBreakup],
                 [GenderId],
                 [FollowupDate],
                 [FollowupRemark],
                 [CreatedUserId],
                 [CreatedDateTime],
                 [UpdatedUserId],
                 [UpdatedDateTime],
                 [StudentId],
                 [InquiryDate],
                 [Number],
                 [HandledBy],
                 [OrgGroupId],
                 [InquiryStatusId],
                 [CastCategoryId],
                 [IsTransportRequired],
                 [IsHostelRequired],
                 [AdmissionFormId],
                 [IsGivenAdmissionForm],
                 [AlternateContactNo],
                 [AlternateContactEmail],
                 [MotherName],
                 [DataEntryModeId],
                 [MinorityStatusId],
                 [LiveWithId],
                 [AdhaarNumber],
                 [BloodGroupId],
                 [FatherOccupation],
                 [FatherIncome],
                 [FatherContactNo],
                 [FatherMail],
                 [FatherQualification],
                 [MotherOccupation],
                 [MotherIncome],
                 [MotherContactNo],
                 [MotherMail],
                 [MotherQualification],
                 [Stream],
                 [Board]
        FROM     [sAdmission].[tAdmissionInquiry]
        ORDER BY [Id] ASC;
    END

DROP TABLE [sAdmission].[tAdmissionInquiry];

EXECUTE sp_rename N'[sAdmission].[tmp_ms_xx_tAdmissionInquiry]', N'tAdmissionInquiry';

EXECUTE sp_rename N'[sAdmission].[tmp_ms_xx_clusteredindex_PK_tAdmissionInquiry]', N'PK_tAdmissionInquiry', N'OBJECT';

COMMIT TRANSACTION;

SET TRANSACTION ISOLATION LEVEL READ COMMITTED;


GO
PRINT N'Creating [sAdmission].[tAdmissionInquiry].[UX_tAdmissionInquiry]...';


GO
CREATE NONCLUSTERED INDEX [UX_tAdmissionInquiry]
    ON [sAdmission].[tAdmissionInquiry]([ForClassId] ASC, [ForBatchId] ASC, [OrgId] ASC, [StatusId] ASC, [InquiryModeId] ASC, [InquiryReferenceId] ASC, [AdmissionCategoryId] ASC, [StudentId] ASC, [OrgGroupId] ASC, [InquiryStatusId] ASC, [CastCategoryId] ASC, [AdmissionFormId] ASC) WITH (ALLOW_PAGE_LOCKS = ON, ALLOW_ROW_LOCKS = ON, PAD_INDEX = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, IGNORE_DUP_KEY = OFF, STATISTICS_NORECOMPUTE = OFF, ONLINE = OFF, MAXDOP = 0)
    ON [PRIMARY];


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


GO
ALTER TABLE [sAssessment].[tCCEResult] ALTER COLUMN [AttendanceTerm1] DECIMAL (6, 2) NULL;

ALTER TABLE [sAssessment].[tCCEResult] ALTER COLUMN [AttendanceTerm2] DECIMAL (6, 2) NULL;

ALTER TABLE [sAssessment].[tCCEResult] ALTER COLUMN [WorkingDaysTerm1] DECIMAL (6, 2) NULL;

ALTER TABLE [sAssessment].[tCCEResult] ALTER COLUMN [WorkingDaysTerm2] DECIMAL (6, 2) NULL;


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


GO
ALTER TABLE [sAssessment].[tStudentRemark] ALTER COLUMN [PresentDays] DECIMAL (6, 2) NULL;

ALTER TABLE [sAssessment].[tStudentRemark] ALTER COLUMN [TotalDays] DECIMAL (6, 2) NULL;


GO
PRINT N'Starting rebuilding table [sAssessment].[tTempAllExam]...';


GO
/*
The type for column StudentImage in table [sAssessment].[tTempAllExam] is currently  NVARCHAR (500) NULL but is being changed to  VARBINARY (MAX) NULL. Data loss could occur.
*/
GO
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;

SET XACT_ABORT ON;

BEGIN TRANSACTION;

CREATE TABLE [sAssessment].[tmp_ms_xx_tTempAllExam] (
    [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,
    [SubjectGradeTerm1]              NVARCHAR (50)   NULL,
    [SubjectGradeTerm2]              NVARCHAR (50)   NULL,
    [SubjectGradeTerm3]              NVARCHAR (50)   NULL,
    [IsMarksInDecimal]               BIT             NULL,
    [column_visible]                 BIT             NULL,
    [Percentile]                     DECIMAL (5, 2)  NULL,
    [ResultDetailId]                 BIGINT          NULL,
    [ResultId]                       BIGINT          NULL,
    [Remark1]                        NVARCHAR (500)  NULL,
    [Remark2]                        NVARCHAR (500)  NULL,
    [Remark3]                        NVARCHAR (500)  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,
    [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,
    [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,
    [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,
    [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,
    [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,
    [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,
    [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,
    [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,
    [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,
    [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,
    [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,
    [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,
    [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,
    [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,
    [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,
    [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,
    [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,
    [SubjectMaxTerm1]                DECIMAL (8, 2)  NULL,
    [SubjectMaxTerm2]                DECIMAL (8, 2)  NULL,
    [SubjectMaxTerm3]                DECIMAL (8, 2)  NULL,
    [ContactNo]                      NVARCHAR (20)   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 (200)  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,
    [BatchIdText]                    NVARCHAR (20)   NULL,
    [IsShowWithDetail]               BIT             NULL,
    [IsPresent]                      BIT             NULL,
    [GradeTitle]                     NVARCHAR (50)   NULL,
    [SubjectHighestDivisionGrade]    NVARCHAR (50)   NULL,
    [SubjectHighestDivisionMark]     DECIMAL (5, 2)  NULL,
    [Achievements]                   NVARCHAR (200)  NULL,
    [AchievementsTerm1]              NVARCHAR (200)  NULL,
    [AchievementsTerm2]              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,
    [ObtainedMaximum1]               DECIMAL (8, 2)  NULL,
    [ObtainedMaximum2]               DECIMAL (8, 2)  NULL,
    [ObtainedMaximum3]               DECIMAL (8, 2)  NULL,
    [ObtainedMaximum4]               DECIMAL (8, 2)  NULL,
    [Term2Term3ClassHighestMarkSum]  DECIMAL (8, 2)  NULL,
    [GeneralRemarkTerm1]             NVARCHAR (200)  NULL,
    [GeneralRemarkTerm2]             NVARCHAR (200)  NULL,
    [KrupaMark]                      DECIMAL (5, 2)  NULL,
    [TotalCount]                     SMALLINT        NULL,
    [PresentCount]                   SMALLINT        NULL,
    [Remark4]                        NVARCHAR (1000) NULL,
    [HouseId]                        INT             NULL,
    [HouseName]                      NVARCHAR (100)  NULL,
    [AdhaarNumber]                   NVARCHAR (100)  NULL,
    [UIdNumber]                      NVARCHAR (100)  NULL,
    [FatherContactNo]                NVARCHAR (20)   NULL,
    [MotherContactNo]                NVARCHAR (20)   NULL,
    [FatherMail]                     NVARCHAR (MAX)  NULL,
    [MotherMail]                     NVARCHAR (MAX)  NULL,
    [ComExam1Name]                   NVARCHAR (MAX)  NULL,
    [ComExam1Grade]                  NVARCHAR (10)   NULL,
    [ComExam1Mark]                   NVARCHAR (10)   NULL,
    [ComExam2Name]                   NVARCHAR (MAX)  NULL,
    [ComExam2Grade]                  NVARCHAR (10)   NULL,
    [ComExam2Mark]                   NVARCHAR (10)   NULL,
    [ComExam3Name]                   NVARCHAR (MAX)  NULL,
    [ComExam3Grade]                  NVARCHAR (10)   NULL,
    [ComExam3Mark]                   NVARCHAR (10)   NULL,
    [ComExam4Name]                   NVARCHAR (MAX)  NULL,
    [ComExam4Grade]                  NVARCHAR (10)   NULL,
    [ComExam4Mark]                   NVARCHAR (10)   NULL,
    [ComExam5Name]                   NVARCHAR (MAX)  NULL,
    [ComExam5Grade]                  NVARCHAR (10)   NULL,
    [ComExam5Mark]                   NVARCHAR (10)   NULL,
    [ComExam6Name]                   NVARCHAR (MAX)  NULL,
    [ComExam6Grade]                  NVARCHAR (10)   NULL,
    [ComExam6Mark]                   NVARCHAR (10)   NULL,
    [ComExam7Name]                   NVARCHAR (MAX)  NULL,
    [ComExam7Grade]                  NVARCHAR (10)   NULL,
    [ComExam7Mark]                   NVARCHAR (10)   NULL,
    [ComExam8Name]                   NVARCHAR (MAX)  NULL,
    [ComExam8Grade]                  NVARCHAR (10)   NULL,
    [ComExam8Mark]                   NVARCHAR (10)   NULL,
    [ComExam9Name]                   NVARCHAR (MAX)  NULL,
    [ComExam9Grade]                  NVARCHAR (10)   NULL,
    [ComExam9Mark]                   NVARCHAR (10)   NULL,
    [ComExam10Name]                  NVARCHAR (MAX)  NULL,
    [ComExam10Grade]                 NVARCHAR (10)   NULL,
    [ComExam10Mark]                  NVARCHAR (10)   NULL,
    [ComExam11Name]                  NVARCHAR (MAX)  NULL,
    [ComExam11Grade]                 NVARCHAR (10)   NULL,
    [ComExam11Mark]                  NVARCHAR (10)   NULL,
    [ComExam12Name]                  NVARCHAR (MAX)  NULL,
    [ComExam12Grade]                 NVARCHAR (10)   NULL,
    [ComExam12Mark]                  NVARCHAR (10)   NULL,
    [Gender]                         NVARCHAR (100)  NULL,
    [InchargeEmployeeName]           NVARCHAR (100)  NULL,
    [CoordinatorEmployeeSign]        VARBINARY (MAX) NULL,
    [StudentAddress]                 NVARCHAR (MAX)  NULL,
    [GradeDetail]                    NVARCHAR (500)  NULL,
    [GradeCount]                     NVARCHAR (500)  NULL,
    [DivisionIdText]                 NVARCHAR (50)   NULL,
    [SUId]                           NVARCHAR (20)   NULL,
    [HighestDivisionMark]            DECIMAL (5, 2)  NULL,
    [HighestDivisionGrade]           NVARCHAR (50)   NULL,
    [StreamTitle]                    NVARCHAR (50)   NULL,
    [ResultSheetAdditionalTitle]     NVARCHAR (100)  NULL,
    [SchoolNameLabel]                NVARCHAR (200)  NULL,
    [MediumLabel]                    NVARCHAR (100)  NULL,
    [NameLabel]                      NVARCHAR (200)  NULL,
    [CodeLabel]                      NVARCHAR (100)  NULL,
    [SUIDLabel]                      NVARCHAR (100)  NULL,
    [ClassLabel]                     NVARCHAR (100)  NULL,
    [BirthDateLabel]                 NVARCHAR (100)  NULL,
    [RollNoLabel]                    NVARCHAR (100)  NULL,
    [FatherNameLabel]                NVARCHAR (100)  NULL,
    [MotherNameLabel]                NVARCHAR (100)  NULL,
    [TotalWorkingDaysLabel]          NVARCHAR (100)  NULL,
    [TotalPresentDaysLabel]          NVARCHAR (100)  NULL,
    [HeightLabel]                    NVARCHAR (100)  NULL,
    [WeightLabel]                    NVARCHAR (100)  NULL,
    [SubjectLabel]                   NVARCHAR (100)  NULL,
    [MaxMarksLabel]                  NVARCHAR (100)  NULL,
    [TotalLabel]                     NVARCHAR (100)  NULL,
    [GradeLabel]                     NVARCHAR (100)  NULL,
    [GrandTotalLabel]                NVARCHAR (100)  NULL,
    [ResultStatusLabel]              NVARCHAR (100)  NULL,
    [RankNoLabel]                    NVARCHAR (100)  NULL,
    [PercentileLabel]                NVARCHAR (100)  NULL,
    [PercentageLabel]                NVARCHAR (100)  NULL,
    [OverallGradeLabel]              NVARCHAR (100)  NULL,
    [DisplayAttendanceId]            INT             NULL,
    [ReportHeaderId]                 INT             NULL,
    [StudentImage]                   VARBINARY (MAX) NULL,
    [AdmissionNo]                    INT             NULL,
    [AdmissionDate]                  DATE            NULL,
    [IsPercentageDisplay]            BIT             NULL,
    [Exam1CombineExamName]           NVARCHAR (150)  NULL,
    [Exam2CombineExamName]           NVARCHAR (150)  NULL,
    [Exam3CombineExamName]           NVARCHAR (150)  NULL,
    [Exam4CombineExamName]           NVARCHAR (150)  NULL,
    [Exam5CombineExamName]           NVARCHAR (150)  NULL,
    [Exam6CombineExamName]           NVARCHAR (150)  NULL,
    [Exam7CombineExamName]           NVARCHAR (150)  NULL,
    [Exam8CombineExamName]           NVARCHAR (150)  NULL,
    [Exam9CombineExamName]           NVARCHAR (150)  NULL,
    [Exam10CombineExamName]          NVARCHAR (150)  NULL,
    [Exam11CombineExamName]          NVARCHAR (150)  NULL,
    [Exam12CombineExamName]          NVARCHAR (150)  NULL,
    [MiddleName]                     NVARCHAR (100)  NULL
);

IF EXISTS (SELECT TOP 1 1
           FROM   [sAssessment].[tTempAllExam])
    BEGIN
        INSERT INTO [sAssessment].[tmp_ms_xx_tTempAllExam] ([AcademicIdText], [ExamIdText], [CoScholasticScopeIdText], [IsDisplayMonthlyAttendanceText], [ClassIdText], [AcademicId], [ExamName], [StudCode], [StudentName], [RollNo], [ResultStatus], [ClassName], [Division], [TotalMark], [TotalObtain], [Percentage], [RankNumber], [ResultGrade], [MaximumMark1], [SubjectGrade1], [Obtain1], [ExamMaximum1], [IsPresent1], [MaximumMark2], [SubjectGrade2], [Obtain2], [ExamMaximum2], [IsPresent2], [MaximumMark3], [SubjectGrade3], [Obtain3], [ExamMaximum3], [IsPresent3], [MaximumMark4], [SubjectGrade4], [Obtain4], [ExamMaximum4], [IsPresent4], [MaximumMark5], [SubjectGrade5], [Obtain5], [ExamMaximum5], [IsPresent5], [MaximumMark6], [SubjectGrade6], [Obtain6], [ExamMaximum6], [IsPresent6], [MaximumMark7], [SubjectGrade7], [Obtain7], [ExamMaximum7], [IsPresent7], [MaximumMark8], [SubjectGrade8], [Obtain8], [ExamMaximum8], [IsPresent8], [MaximumMark9], [SubjectGrade9], [Obtain9], [ExamMaximum9], [IsPresent9], [MaximumMark10], [SubjectGrade10], [Obtain10], [ExamMaximum10], [IsPresent10], [MaximumMark11], [SubjectGrade11], [Obtain11], [ExamMaximum11], [IsPresent11], [MaximumMark12], [SubjectGrade12], [Obtain12], [ExamMaximum12], [IsPresent12], [SubjectGradeTerm1], [SubjectGradeTerm2], [SubjectGradeTerm3], [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], [TotalMarkTerm1], [TotalObtainTerm1], [PercentageTerm1], [RankNumberTerm1], [ResultGradeTerm1], [PercentileTerm1], [ResultStatusTerm1], [TotalMarkTerm2], [TotalObtainTerm2], [PercentageTerm2], [RankNumberTerm2], [ResultGradeTerm2], [PercentileTerm2], [ResultStatusTerm2], [TotalMarkTerm3], [TotalObtainTerm3], [PercentageTerm3], [RankNumberTerm3], [ResultGradeTerm3], [PercentileTerm3], [ResultStatusTerm3], [TermScopeId], [StudentPhoto], [GradeString], [IsDisplayGradeString], [IsDisplayInMarksheet], [IsShowSubjectGrade], [IsIncludeInTotal], [ClassSubjectID], [SubjectId], [SubjectOrderIndex], [SubjectGrade], [SubjectName], [SubjectCode], [SubjectMinimum], [SubjectMaximum], [SubjectObtain], [Exam1Name], [TotalMarks1], [TotalObtain1], [Percentage1], [RankNumber1], [ResultGrade1], [Percentile1], [ResultStatus1], [Exam2Name], [TotalMarks2], [TotalObtain2], [Percentage2], [RankNumber2], [ResultGrade2], [Percentile2], [ResultStatus2], [Exam3Name], [TotalMarks3], [TotalObtain3], [Percentage3], [RankNumber3], [ResultGrade3], [Percentile3], [ResultStatus3], [Exam4Name], [TotalMarks4], [TotalObtain4], [Percentage4], [RankNumber4], [ResultGrade4], [Percentile4], [ResultStatus4], [Exam5Name], [TotalMarks5], [TotalObtain5], [Percentage5], [RankNumber5], [ResultGrade5], [Percentile5], [ResultStatus5], [Exam6Name], [TotalMarks6], [TotalObtain6], [Percentage6], [RankNumber6], [ResultGrade6], [Percentile6], [ResultStatus6], [Exam7Name], [TotalMarks7], [TotalObtain7], [Percentage7], [RankNumber7], [ResultGrade7], [Percentile7], [ResultStatus7], [Exam8Name], [TotalMarks8], [TotalObtain8], [Percentage8], [RankNumber8], [ResultGrade8], [Percentile8], [ResultStatus8], [Exam9Name], [TotalMarks9], [TotalObtain9], [Percentage9], [RankNumber9], [ResultGrade9], [Percentile9], [ResultStatus9], [Exam10Name], [TotalMarks10], [TotalObtain10], [Percentage10], [RankNumber10], [ResultGrade10], [Percentile10], [ResultStatus10], [Exam11Name], [TotalMarks11], [TotalObtain11], [Percentage11], [RankNumber11], [ResultGrade11], [Percentile11], [ResultStatus11], [Exam12Name], [TotalMarks12], [TotalObtain12], [Percentage12], [RankNumber12], [ResultGrade12], [Percentile12], [ResultStatus12], [ResultRemark1], [ResultRemark2], [TotalDays], [PresentDays], [StudentHeight], [StudentWeight], [ExamSeatNo], [ExamId], [ExamCode], [Exam1Code], [Exam2Code], [Exam3Code], [Exam4Code], [Exam5Code], [Exam6Code], [Exam7Code], [Exam8Code], [Exam9Code], [Exam10Code], [Exam11Code], [Exam12Code], [IsDisplayParentName], [FatherName], [MotherName], [IsShowSubjectMark], [IsOptionalSubject], [CoScholasticScopeId], [IsDisplayPrincipalSign], [IsDisplayTeacherSign], [EmployeeSign], [Batch], [ExamNameTerm1], [ExamNameTerm2], [ExamNameTerm3], [ClassTeacherName], [FirstName], [LastName], [IsDisplayMonthlyAttendance], [MarksheetHeaderA4], [IsImageHeader], [MyGoal], [AreaOfInterest], [Responsibility], [MyInterestHobby], [MyStrength], [DentalHygiene], [VisionLeft], [VisionRight], [IsDetail], [SubjectGroupId], [SubjectGroupTitle], [SubjectGroupCode], [DecimalFormat], [SubjectRemark], [GraceMark], [GradeStringHtml], [ResultRemark3], [IsDisplayTotalMark], [SubjectObtainTerm1], [SubjectObtainTerm2], [SubjectObtainTerm3], [SubjectMaxTerm1], [SubjectMaxTerm2], [SubjectMaxTerm3], [ContactNo], [PresentAddress], [TeacherSignCaption], [PrincipalSignCaption], [ParentSignCaption], [ImprovementArea], [ProgressArea], [GeneralRemark], [MyActivity], [ClassTeacherRemark], [HouseRemark], [BloodGroup], [TotalDays1], [PresentDays1], [TotalDays2], [PresentDays2], [TotalDays3], [PresentDays3], [TotalDays4], [PresentDays4], [TotalDays5], [PresentDays5], [TotalDays6], [PresentDays6], [TotalDays7], [PresentDays7], [TotalDays8], [PresentDays8], [TotalDays9], [PresentDays9], [TotalDays10], [PresentDays10], [TotalDays11], [PresentDays11], [TotalDays12], [PresentDays12], [BatchIdText], [IsShowWithDetail], [IsPresent], [GradeTitle], [SubjectHighestDivisionGrade], [SubjectHighestDivisionMark], [Achievements], [AchievementsTerm1], [AchievementsTerm2], [ResultRemark1Term1], [ResultRemark2Term1], [ResultRemark1Term2], [ResultRemark2Term2], [SR_HeightTerm1], [SR_WeightTerm1], [SR_HeightTerm2], [SR_WeightTerm2], [SR_PresentDaysTerm1], [SR_PresentDaysTerm2], [SR_TotalDaysTerm1], [SR_TotalDaysTerm2], [ObtainedMaximum1], [ObtainedMaximum2], [ObtainedMaximum3], [ObtainedMaximum4], [Term2Term3ClassHighestMarkSum], [GeneralRemarkTerm1], [GeneralRemarkTerm2], [KrupaMark], [TotalCount], [PresentCount], [Remark4], [HouseId], [HouseName], [AdhaarNumber], [UIdNumber], [FatherContactNo], [MotherContactNo], [FatherMail], [MotherMail], [ComExam1Name], [ComExam1Grade], [ComExam1Mark], [ComExam2Name], [ComExam2Grade], [ComExam2Mark], [ComExam3Name], [ComExam3Grade], [ComExam3Mark], [ComExam4Name], [ComExam4Grade], [ComExam4Mark], [ComExam5Name], [ComExam5Grade], [ComExam5Mark], [ComExam6Name], [ComExam6Grade], [ComExam6Mark], [ComExam7Name], [ComExam7Grade], [ComExam7Mark], [ComExam8Name], [ComExam8Grade], [ComExam8Mark], [ComExam9Name], [ComExam9Grade], [ComExam9Mark], [ComExam10Name], [ComExam10Grade], [ComExam10Mark], [ComExam11Name], [ComExam11Grade], [ComExam11Mark], [ComExam12Name], [ComExam12Grade], [ComExam12Mark], [Gender], [InchargeEmployeeName], [CoordinatorEmployeeSign], [StudentAddress], [GradeDetail], [GradeCount], [DivisionIdText], [SUId], [HighestDivisionMark], [HighestDivisionGrade], [StreamTitle], [ResultSheetAdditionalTitle], [SchoolNameLabel], [MediumLabel], [NameLabel], [CodeLabel], [SUIDLabel], [ClassLabel], [BirthDateLabel], [RollNoLabel], [FatherNameLabel], [MotherNameLabel], [TotalWorkingDaysLabel], [TotalPresentDaysLabel], [HeightLabel], [WeightLabel], [SubjectLabel], [MaxMarksLabel], [TotalLabel], [GradeLabel], [GrandTotalLabel], [ResultStatusLabel], [RankNoLabel], [PercentileLabel], [PercentageLabel], [OverallGradeLabel], [DisplayAttendanceId], [ReportHeaderId], [StudentImage], [AdmissionNo], [AdmissionDate], [IsPercentageDisplay], [Exam1CombineExamName], [Exam2CombineExamName], [Exam3CombineExamName], [Exam4CombineExamName], [Exam5CombineExamName], [Exam6CombineExamName], [Exam7CombineExamName], [Exam8CombineExamName], [Exam9CombineExamName], [Exam10CombineExamName], [Exam11CombineExamName], [Exam12CombineExamName])
        SELECT [AcademicIdText],
               [ExamIdText],
               [CoScholasticScopeIdText],
               [IsDisplayMonthlyAttendanceText],
               [ClassIdText],
               [AcademicId],
               [ExamName],
               [StudCode],
               [StudentName],
               [RollNo],
               [ResultStatus],
               [ClassName],
               [Division],
               [TotalMark],
               [TotalObtain],
               [Percentage],
               [RankNumber],
               [ResultGrade],
               [MaximumMark1],
               [SubjectGrade1],
               [Obtain1],
               [ExamMaximum1],
               [IsPresent1],
               [MaximumMark2],
               [SubjectGrade2],
               [Obtain2],
               [ExamMaximum2],
               [IsPresent2],
               [MaximumMark3],
               [SubjectGrade3],
               [Obtain3],
               [ExamMaximum3],
               [IsPresent3],
               [MaximumMark4],
               [SubjectGrade4],
               [Obtain4],
               [ExamMaximum4],
               [IsPresent4],
               [MaximumMark5],
               [SubjectGrade5],
               [Obtain5],
               [ExamMaximum5],
               [IsPresent5],
               [MaximumMark6],
               [SubjectGrade6],
               [Obtain6],
               [ExamMaximum6],
               [IsPresent6],
               [MaximumMark7],
               [SubjectGrade7],
               [Obtain7],
               [ExamMaximum7],
               [IsPresent7],
               [MaximumMark8],
               [SubjectGrade8],
               [Obtain8],
               [ExamMaximum8],
               [IsPresent8],
               [MaximumMark9],
               [SubjectGrade9],
               [Obtain9],
               [ExamMaximum9],
               [IsPresent9],
               [MaximumMark10],
               [SubjectGrade10],
               [Obtain10],
               [ExamMaximum10],
               [IsPresent10],
               [MaximumMark11],
               [SubjectGrade11],
               [Obtain11],
               [ExamMaximum11],
               [IsPresent11],
               [MaximumMark12],
               [SubjectGrade12],
               [Obtain12],
               [ExamMaximum12],
               [IsPresent12],
               [SubjectGradeTerm1],
               [SubjectGradeTerm2],
               [SubjectGradeTerm3],
               [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],
               [TotalMarkTerm1],
               [TotalObtainTerm1],
               [PercentageTerm1],
               [RankNumberTerm1],
               [ResultGradeTerm1],
               [PercentileTerm1],
               [ResultStatusTerm1],
               [TotalMarkTerm2],
               [TotalObtainTerm2],
               [PercentageTerm2],
               [RankNumberTerm2],
               [ResultGradeTerm2],
               [PercentileTerm2],
               [ResultStatusTerm2],
               [TotalMarkTerm3],
               [TotalObtainTerm3],
               [PercentageTerm3],
               [RankNumberTerm3],
               [ResultGradeTerm3],
               [PercentileTerm3],
               [ResultStatusTerm3],
               [TermScopeId],
               [StudentPhoto],
               [GradeString],
               [IsDisplayGradeString],
               [IsDisplayInMarksheet],
               [IsShowSubjectGrade],
               [IsIncludeInTotal],
               [ClassSubjectID],
               [SubjectId],
               [SubjectOrderIndex],
               [SubjectGrade],
               [SubjectName],
               [SubjectCode],
               [SubjectMinimum],
               [SubjectMaximum],
               [SubjectObtain],
               [Exam1Name],
               [TotalMarks1],
               [TotalObtain1],
               [Percentage1],
               [RankNumber1],
               [ResultGrade1],
               [Percentile1],
               [ResultStatus1],
               [Exam2Name],
               [TotalMarks2],
               [TotalObtain2],
               [Percentage2],
               [RankNumber2],
               [ResultGrade2],
               [Percentile2],
               [ResultStatus2],
               [Exam3Name],
               [TotalMarks3],
               [TotalObtain3],
               [Percentage3],
               [RankNumber3],
               [ResultGrade3],
               [Percentile3],
               [ResultStatus3],
               [Exam4Name],
               [TotalMarks4],
               [TotalObtain4],
               [Percentage4],
               [RankNumber4],
               [ResultGrade4],
               [Percentile4],
               [ResultStatus4],
               [Exam5Name],
               [TotalMarks5],
               [TotalObtain5],
               [Percentage5],
               [RankNumber5],
               [ResultGrade5],
               [Percentile5],
               [ResultStatus5],
               [Exam6Name],
               [TotalMarks6],
               [TotalObtain6],
               [Percentage6],
               [RankNumber6],
               [ResultGrade6],
               [Percentile6],
               [ResultStatus6],
               [Exam7Name],
               [TotalMarks7],
               [TotalObtain7],
               [Percentage7],
               [RankNumber7],
               [ResultGrade7],
               [Percentile7],
               [ResultStatus7],
               [Exam8Name],
               [TotalMarks8],
               [TotalObtain8],
               [Percentage8],
               [RankNumber8],
               [ResultGrade8],
               [Percentile8],
               [ResultStatus8],
               [Exam9Name],
               [TotalMarks9],
               [TotalObtain9],
               [Percentage9],
               [RankNumber9],
               [ResultGrade9],
               [Percentile9],
               [ResultStatus9],
               [Exam10Name],
               [TotalMarks10],
               [TotalObtain10],
               [Percentage10],
               [RankNumber10],
               [ResultGrade10],
               [Percentile10],
               [ResultStatus10],
               [Exam11Name],
               [TotalMarks11],
               [TotalObtain11],
               [Percentage11],
               [RankNumber11],
               [ResultGrade11],
               [Percentile11],
               [ResultStatus11],
               [Exam12Name],
               [TotalMarks12],
               [TotalObtain12],
               [Percentage12],
               [RankNumber12],
               [ResultGrade12],
               [Percentile12],
               [ResultStatus12],
               [ResultRemark1],
               [ResultRemark2],
               [TotalDays],
               [PresentDays],
               [StudentHeight],
               [StudentWeight],
               [ExamSeatNo],
               [ExamId],
               [ExamCode],
               [Exam1Code],
               [Exam2Code],
               [Exam3Code],
               [Exam4Code],
               [Exam5Code],
               [Exam6Code],
               [Exam7Code],
               [Exam8Code],
               [Exam9Code],
               [Exam10Code],
               [Exam11Code],
               [Exam12Code],
               [IsDisplayParentName],
               [FatherName],
               [MotherName],
               [IsShowSubjectMark],
               [IsOptionalSubject],
               [CoScholasticScopeId],
               [IsDisplayPrincipalSign],
               [IsDisplayTeacherSign],
               [EmployeeSign],
               [Batch],
               [ExamNameTerm1],
               [ExamNameTerm2],
               [ExamNameTerm3],
               [ClassTeacherName],
               [FirstName],
               [LastName],
               [IsDisplayMonthlyAttendance],
               [MarksheetHeaderA4],
               [IsImageHeader],
               [MyGoal],
               [AreaOfInterest],
               [Responsibility],
               [MyInterestHobby],
               [MyStrength],
               [DentalHygiene],
               [VisionLeft],
               [VisionRight],
               [IsDetail],
               [SubjectGroupId],
               [SubjectGroupTitle],
               [SubjectGroupCode],
               [DecimalFormat],
               [SubjectRemark],
               [GraceMark],
               [GradeStringHtml],
               [ResultRemark3],
               [IsDisplayTotalMark],
               [SubjectObtainTerm1],
               [SubjectObtainTerm2],
               [SubjectObtainTerm3],
               [SubjectMaxTerm1],
               [SubjectMaxTerm2],
               [SubjectMaxTerm3],
               [ContactNo],
               [PresentAddress],
               [TeacherSignCaption],
               [PrincipalSignCaption],
               [ParentSignCaption],
               [ImprovementArea],
               [ProgressArea],
               [GeneralRemark],
               [MyActivity],
               [ClassTeacherRemark],
               [HouseRemark],
               [BloodGroup],
               [TotalDays1],
               [PresentDays1],
               [TotalDays2],
               [PresentDays2],
               [TotalDays3],
               [PresentDays3],
               [TotalDays4],
               [PresentDays4],
               [TotalDays5],
               [PresentDays5],
               [TotalDays6],
               [PresentDays6],
               [TotalDays7],
               [PresentDays7],
               [TotalDays8],
               [PresentDays8],
               [TotalDays9],
               [PresentDays9],
               [TotalDays10],
               [PresentDays10],
               [TotalDays11],
               [PresentDays11],
               [TotalDays12],
               [PresentDays12],
               [BatchIdText],
               [IsShowWithDetail],
               [IsPresent],
               [GradeTitle],
               [SubjectHighestDivisionGrade],
               [SubjectHighestDivisionMark],
               [Achievements],
               [AchievementsTerm1],
               [AchievementsTerm2],
               [ResultRemark1Term1],
               [ResultRemark2Term1],
               [ResultRemark1Term2],
               [ResultRemark2Term2],
               [SR_HeightTerm1],
               [SR_WeightTerm1],
               [SR_HeightTerm2],
               [SR_WeightTerm2],
               [SR_PresentDaysTerm1],
               [SR_PresentDaysTerm2],
               [SR_TotalDaysTerm1],
               [SR_TotalDaysTerm2],
               [ObtainedMaximum1],
               [ObtainedMaximum2],
               [ObtainedMaximum3],
               [ObtainedMaximum4],
               [Term2Term3ClassHighestMarkSum],
               [GeneralRemarkTerm1],
               [GeneralRemarkTerm2],
               [KrupaMark],
               [TotalCount],
               [PresentCount],
               [Remark4],
               [HouseId],
               [HouseName],
               [AdhaarNumber],
               [UIdNumber],
               [FatherContactNo],
               [MotherContactNo],
               [FatherMail],
               [MotherMail],
               [ComExam1Name],
               [ComExam1Grade],
               [ComExam1Mark],
               [ComExam2Name],
               [ComExam2Grade],
               [ComExam2Mark],
               [ComExam3Name],
               [ComExam3Grade],
               [ComExam3Mark],
               [ComExam4Name],
               [ComExam4Grade],
               [ComExam4Mark],
               [ComExam5Name],
               [ComExam5Grade],
               [ComExam5Mark],
               [ComExam6Name],
               [ComExam6Grade],
               [ComExam6Mark],
               [ComExam7Name],
               [ComExam7Grade],
               [ComExam7Mark],
               [ComExam8Name],
               [ComExam8Grade],
               [ComExam8Mark],
               [ComExam9Name],
               [ComExam9Grade],
               [ComExam9Mark],
               [ComExam10Name],
               [ComExam10Grade],
               [ComExam10Mark],
               [ComExam11Name],
               [ComExam11Grade],
               [ComExam11Mark],
               [ComExam12Name],
               [ComExam12Grade],
               [ComExam12Mark],
               [Gender],
               [InchargeEmployeeName],
               [CoordinatorEmployeeSign],
               [StudentAddress],
               [GradeDetail],
               [GradeCount],
               [DivisionIdText],
               [SUId],
               [HighestDivisionMark],
               [HighestDivisionGrade],
               [StreamTitle],
               [ResultSheetAdditionalTitle],
               [SchoolNameLabel],
               [MediumLabel],
               [NameLabel],
               [CodeLabel],
               [SUIDLabel],
               [ClassLabel],
               [BirthDateLabel],
               [RollNoLabel],
               [FatherNameLabel],
               [MotherNameLabel],
               [TotalWorkingDaysLabel],
               [TotalPresentDaysLabel],
               [HeightLabel],
               [WeightLabel],
               [SubjectLabel],
               [MaxMarksLabel],
               [TotalLabel],
               [GradeLabel],
               [GrandTotalLabel],
               [ResultStatusLabel],
               [RankNoLabel],
               [PercentileLabel],
               [PercentageLabel],
               [OverallGradeLabel],
               [DisplayAttendanceId],
               [ReportHeaderId],
               CAST ([StudentImage] AS VARBINARY (MAX)),
               [AdmissionNo],
               [AdmissionDate],
               [IsPercentageDisplay],
               [Exam1CombineExamName],
               [Exam2CombineExamName],
               [Exam3CombineExamName],
               [Exam4CombineExamName],
               [Exam5CombineExamName],
               [Exam6CombineExamName],
               [Exam7CombineExamName],
               [Exam8CombineExamName],
               [Exam9CombineExamName],
               [Exam10CombineExamName],
               [Exam11CombineExamName],
               [Exam12CombineExamName]
        FROM   [sAssessment].[tTempAllExam];
    END

DROP TABLE [sAssessment].[tTempAllExam];

EXECUTE sp_rename N'[sAssessment].[tmp_ms_xx_tTempAllExam]', N'tTempAllExam';

COMMIT TRANSACTION;

SET TRANSACTION ISOLATION LEVEL READ COMMITTED;


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


GO
ALTER TABLE [sCommunication].[tUploadResult]
    ADD [UploadTypeId] SMALLINT NULL;


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


GO
ALTER TABLE [sPayroll].[tPayrollMaster]
    ADD [HeaderDisplayId] TINYINT NULL;


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


GO
ALTER TABLE [sStudent].[tAcademic]
    ADD [FeesRemark] NVARCHAR (500) NULL;

 


GO

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


GO
 
 
ALTER FUNCTION [sHrm].[fWeekHOffGet](@rEmployeeId bigint, @rForYear smallint,@rForMonth smallint,@rDay smallint,@rBatchId int,@rDepartmentId int,@rOrgId smallint)
RETURNS nvarchar(20) WITH EXECUTE AS CALLER
AS 
BEGIN
DECLARE @lStatus nvarchar(200)='-' 
DECLARE @lWeekOff nvarchar(20)
Declare @WeekNumber int,@EmpSecondWeekOffRule int,@EmpFirstWeekOffRule int
DECLARE @lDate datetime,@lWeekDay1 nvarchar(20),@lWeekDay2  nvarchar(20)
SET @lDate = CONVERT(nvarchar(10), @rForYear)+ '-' +  CONVERT(nvarchar(10), @rForMonth) + '-' + CONVERT(nvarchar(10), @rDay)

--if exists(Select 1 from sActivity.tWeekOffSetting WHEre SourceId = @rEmployeeId AND SourceTypeId=95)
--BEGIN
--	Select @lWeekDay1 = FirstWeekOffDayId From sActivity.tWeekOffSetting  Where SourceId = @rEmployeeId AND SourceTypeId=95
--	Select @lWeekDay2 = SecondWeekOff From sActivity.tWeekOffSetting  Where SourceId = @rEmployeeId AND SourceTypeId=95  
-- END 
-- Else
-- BEGIN
--	Select @lWeekDay1 = EmployeeFirstWeekOffDayId From sSetup.tOrganizationMaster  Where Id = @rOrgId 
--	Select @lWeekDay2 = EmployeeSEcondWeekOffDayId From sSetup.tOrganizationMaster  Where Id = @rOrgId 
-- END
 
SET @lWeekOff = [sAssessment].[fGetdayNumber](@lDate)
 --Select  @lStatus =  Case When @lWeekOff = @lWeekDay1 Then 'W' Else '-' End 
Set @WeekNumber = datediff(week, dateadd(week, datediff(week, 0, dateadd(month, datediff(month, 0, @lDate), 0)), 0), @lDate - 1) + 1
 
--if exists(Select 1 from sActivity.tWeekOffSetting WHEre SourceId = @rEmployeeId AND SourceTypeId=95)
--BEGIN
	 
--	Select @EmpFirstWeekOffRule = FristWeekOffRuleId From sActivity.tWeekOffSetting WHEre SourceId = @rEmployeeId AND SourceTypeId=95
--	Select @EmpSecondWeekOffRule = SEcondWeekOffRuleId From sActivity.tWeekOffSetting WHEre SourceId = @rEmployeeId AND SourceTypeId=95
	 
-- END
-- Else
-- BEGIN
   
--	Select @EmpFirstWeekOffRule = EmployeeFirstWeekOffRuleId From sSetup.tOrganizationMaster WHEre Id = @rOrgId 
--	Select @EmpSecondWeekOffRule = EmployeeSecondWeekOffRuleId From sSetup.tOrganizationMaster WHEre Id = @rOrgId 

	IF EXISTS(SELECT 1 FROM sActivity.tWeekOffSetting WHERE SourceId = @rEmployeeId AND SourceTypeId=95)
	BEGIN
		SELECT @lWeekDay1 = FirstWeekOffDayId, @lWeekDay2 = SecondWeekOff,@EmpFirstWeekOffRule = FristWeekOffRuleId,@EmpSecondWeekOffRule = SEcondWeekOffRuleId FROM sActivity.tWeekOffSetting  WHERE SourceId = @rEmployeeId AND SourceTypeId=95
	END 
	ELSE
	BEGIN
		SELECT @lWeekDay1 = EmployeeFirstWeekOffDayId,@lWeekDay2 = EmployeeSEcondWeekOffDayId,@EmpFirstWeekOffRule = EmployeeFirstWeekOffRuleId,@EmpSecondWeekOffRule = EmployeeSecondWeekOffRuleId  FROM sSetup.tOrganizationMaster  WHERE Id = @rOrgId 
	END
	 
-- END
--IF(@lDate > GETDATE())
--BEGIN
--	SET @lStatus = ''
--	RETURN @lStatus	
--END	 
	 
--if @lStatus = 'W'
--BEGIN

	
	if @EmpFirstWeekOffRule = 1 
	BEGIN		
		if(@lWeekOff = @lWeekDay1)
			BEGIN	
				
				Set @lStatus = 'W'
				RETURN @lStatus	
			 END 

			  if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
					BEGIN 
						SET @lStatus = 'P'
					END
					 if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
					BEGIN 						
						SET @lStatus = 'A'
					END
					
					IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
						INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId 
						WHERE ES.BatchId = @rBatchId AND ((SourceId=@rDepartmentId) OR (@rDepartmentId=0)) 
						AND SourceTypeId in (2004, 3)
						AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
					 BEGIN
						 SET @lStatus = 'H'	
						 RETURN @lStatus		
					 END
				IF Exists(select 1 From sHrm.tLeave L WHERE L.StatusId = 550 AND L.EmployeeId = @rEmployeeId AND @lDate BETWEEN L.FromDate AND L.ToDate)
				BEGIN
					SELECT @lStatus=LTM.Code + ' / ' + CASE WHEN L.LeavePeriodId = 1 THEN '1' WHEN L.LeavePeriodId = 2  THEN  '0.5' ELSE '0.25' END
					FROM sHrm.tLeave L INNER JOIN sHrm.tLeaveTypeMaster LTM ON LTM.Id = L.LeaveTypeId
					WHERE L.StatusId = 550 AND L.EmployeeId = @rEmployeeId AND @lDate BETWEEN L.FromDate AND L.ToDate
					RETURN @lStatus	
				END
	END
	Else if @EmpFirstWeekOffRule = 2 
	BEGIN
		   
		IF @WeekNumber = 2 or @WeekNumber = 4 
		BEGIN
			
			if(@lWeekOff = @lWeekDay1)
			BEGIN
				Set @lStatus = 'W'
				RETURN @lStatus
			END
			
				 if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
					BEGIN 
						SET @lStatus = 'P'
					END
					 if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
					BEGIN 
						SET @lStatus = 'A'
					END
						IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
						INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId WHERE ES.BatchId = @rBatchId AND ((SourceId=@rDepartmentId) OR (@rDepartmentId=0)) 
						AND SourceTypeId in (2004, 3)
						AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
		        BEGIN
			         SET @lStatus = 'H'	
			   RETURN @lStatus		
		        END
				IF Exists(select 1 From sHrm.tLeave L WHERE L.StatusId = 550 AND L.EmployeeId = @rEmployeeId AND @lDate BETWEEN L.FromDate AND L.ToDate)
				BEGIN
					SELECT @lStatus=LTM.Code + ' / ' + CASE WHEN L.LeavePeriodId = 1 THEN '1' WHEN L.LeavePeriodId = 2  THEN  '0.5' ELSE '0.25' END
					FROM sHrm.tLeave L INNER JOIN sHrm.tLeaveTypeMaster LTM ON LTM.Id = L.LeaveTypeId
					WHERE L.StatusId = 550 AND L.EmployeeId = @rEmployeeId AND @lDate BETWEEN L.FromDate AND L.ToDate
					RETURN @lStatus
				END	
			END
		--	Else
		--	BEGIN
		--		Set @lStatus ='-'
		--	END
			 
		--END
		--Else
		--BEGIN
		--	Set @lStatus = '-'
		--	RETURN @lStatus	
		--END
	END
	else if @EmpFirstWeekOffRule = 3
	BEGIN
		if @WeekNumber = 1 or @WeekNumber = 3 
		BEGIN
			if(@lWeekOff = @lWeekDay1)
			BEGIN
				Set @lStatus = 'W'
				RETURN @lStatus	
            END 

				 if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
					BEGIN 
						SET @lStatus = 'P'
					END
					 if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
					BEGIN 
						SET @lStatus = 'A'
					END
						--Set @lStatus = 'W'
				IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
						INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId WHERE ES.BatchId = @rBatchId AND ((SourceId=@rDepartmentId) OR (@rDepartmentId=0)) 
						AND SourceTypeId in (2004, 3)
						AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
				BEGIN
					SET @lStatus = 'H'	
					RETURN @lStatus	
				END
				IF Exists(select 1 From sHrm.tLeave L WHERE L.StatusId = 550 AND L.EmployeeId = @rEmployeeId AND @lDate BETWEEN L.FromDate AND L.ToDate)
				BEGIN
					SELECT @lStatus=LTM.Code + ' / ' + CASE WHEN L.LeavePeriodId = 1 THEN '1' WHEN L.LeavePeriodId = 2  THEN  '0.5' ELSE '0.25' END
					FROM sHrm.tLeave L INNER JOIN sHrm.tLeaveTypeMaster LTM ON LTM.Id = L.LeaveTypeId
					WHERE L.StatusId = 550 AND L.EmployeeId = @rEmployeeId AND @lDate BETWEEN L.FromDate AND L.ToDate
					RETURN @lStatus	
				END
			END
		--	Else
		--	BEGIN
		--		Set @lStatus = '-'
		--	END
			 
		--END
		--else
		--BEGIN
		--	Set @lStatus = '-'
		--	RETURN @lStatus	
		--END
	END
	else if @EmpFirstWeekOffRule = 4
	BEGIN
		   
		if @WeekNumber = 1 or @WeekNumber = 3 or @WeekNumber = 5
		BEGIN
			if(@lWeekOff = @lWeekDay1)
			BEGIN
				Set @lStatus = 'W'
				RETURN @lStatus
			END

				 if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
					BEGIN 
						SET @lStatus = 'P'
					END
					 if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
					BEGIN 
						SET @lStatus = 'A'
					END
					IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
						INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId WHERE ES.BatchId = @rBatchId AND ((SourceId=@rDepartmentId) OR (@rDepartmentId=0)) 
						AND SourceTypeId in (2004, 3)
						AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
				BEGIN
					SET @lStatus = 'H'	
					RETURN @lStatus	
				END
				IF Exists(select 1 From sHrm.tLeave L WHERE L.StatusId = 550 AND L.EmployeeId = @rEmployeeId AND @lDate BETWEEN L.FromDate AND L.ToDate)
				BEGIN
					SELECT @lStatus=LTM.Code + ' / ' + CASE WHEN L.LeavePeriodId = 1 THEN '1' WHEN L.LeavePeriodId = 2  THEN  '0.5' ELSE '0.25' END
					FROM sHrm.tLeave L INNER JOIN sHrm.tLeaveTypeMaster LTM ON LTM.Id = L.LeaveTypeId
					WHERE L.StatusId = 550 AND L.EmployeeId = @rEmployeeId AND @lDate BETWEEN L.FromDate AND L.ToDate
					RETURN @lStatus	
				END
			END
		--	else
		--	BEGIN
		--		Set @lStatus = '-'
		--	END
			 
		--END
		--else
		--BEGIN
		--	Set @lStatus = '-'
		--	RETURN @lStatus	
		--END
	END
	Else if @EmpFirstWeekOffRule = 5 
	BEGIN   
		IF @WeekNumber = 2 or @WeekNumber = 3 
		BEGIN	
			if(@lWeekOff = @lWeekDay1)
			BEGIN
				Set @lStatus = 'W'
				RETURN @lStatus	
            END 

			if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
			BEGIN 
				SET @lStatus = 'P'
			END
			if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
			BEGIN 
				SET @lStatus = 'A'
			END
			IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
			INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId WHERE ES.BatchId = @rBatchId AND ((SourceId=@rDepartmentId) OR (@rDepartmentId=0)) 
			AND SourceTypeId in (2004, 3)
			AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
		    BEGIN
			        SET @lStatus = 'H'	
			RETURN @lStatus		
		    END
			IF Exists(select 1 From sHrm.tLeave L WHERE L.StatusId = 550 AND L.EmployeeId = @rEmployeeId AND @lDate BETWEEN L.FromDate AND L.ToDate)
			BEGIN
				SELECT @lStatus=LTM.Code + ' / ' + CASE WHEN L.LeavePeriodId = 1 THEN '1' WHEN L.LeavePeriodId = 2  THEN  '0.5' ELSE '0.25' END
				FROM sHrm.tLeave L INNER JOIN sHrm.tLeaveTypeMaster LTM ON LTM.Id = L.LeaveTypeId
				WHERE L.StatusId = 550 AND L.EmployeeId = @rEmployeeId AND @lDate BETWEEN L.FromDate AND L.ToDate
				RETURN @lStatus	
			END
		END
	END
	Else if @EmpFirstWeekOffRule = 6 
	BEGIN	   
		IF @WeekNumber = 1 
		BEGIN	
			if(@lWeekOff = @lWeekDay1)
			BEGIN
				Set @lStatus = 'W'
				RETURN @lStatus	
            END 
			if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
			BEGIN 
				SET @lStatus = 'P'
			END
			if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
			BEGIN 
				SET @lStatus = 'A'
			END
			IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
			INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId WHERE ES.BatchId = @rBatchId AND ((SourceId=@rDepartmentId) OR (@rDepartmentId=0)) 
			AND SourceTypeId in (2004, 3)
			AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
			BEGIN
				SET @lStatus = 'H'	
				RETURN @lStatus		
			END	
			IF Exists(select 1 From sHrm.tLeave L WHERE L.StatusId = 550 AND L.EmployeeId = @rEmployeeId AND @lDate BETWEEN L.FromDate AND L.ToDate)
			BEGIN
				SELECT @lStatus=LTM.Code + ' / ' + CASE WHEN L.LeavePeriodId = 1 THEN '1' WHEN L.LeavePeriodId = 2  THEN  '0.5' ELSE '0.25' END
				FROM sHrm.tLeave L INNER JOIN sHrm.tLeaveTypeMaster LTM ON LTM.Id = L.LeaveTypeId
				WHERE L.StatusId = 550 AND L.EmployeeId = @rEmployeeId AND @lDate BETWEEN L.FromDate AND L.ToDate
				RETURN @lStatus	
			END		 
		END 
	END
	
	Else if @EmpFirstWeekOffRule = 7 
	BEGIN  
		IF @WeekNumber = 2 
		BEGIN	
			if(@lWeekOff = @lWeekDay1)
			BEGIN
				Set @lStatus = 'W'
				RETURN @lStatus	
            END 
			if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
			BEGIN 
				SET @lStatus = 'P'
			END
				if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
			BEGIN 
				SET @lStatus = 'A'
			END
			IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
			INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId WHERE ES.BatchId = @rBatchId AND ((SourceId=@rDepartmentId) OR (@rDepartmentId=0)) 
			AND SourceTypeId in (2004, 3)
			AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
		    BEGIN
			    SET @lStatus = 'H'	
				RETURN @lStatus		
		    END
			IF Exists(select 1 From sHrm.tLeave L WHERE L.StatusId = 550 AND L.EmployeeId = @rEmployeeId AND @lDate BETWEEN L.FromDate AND L.ToDate)
			BEGIN
				SELECT @lStatus=LTM.Code + ' / ' + CASE WHEN L.LeavePeriodId = 1 THEN '1' WHEN L.LeavePeriodId = 2  THEN  '0.5' ELSE '0.25' END
				FROM sHrm.tLeave L INNER JOIN sHrm.tLeaveTypeMaster LTM ON LTM.Id = L.LeaveTypeId
				WHERE L.StatusId = 550 AND L.EmployeeId = @rEmployeeId AND @lDate BETWEEN L.FromDate AND L.ToDate
				RETURN @lStatus	
			END
		END
	END
	
	Else if @EmpFirstWeekOffRule = 8 
	BEGIN  
		IF @WeekNumber = 3 
		BEGIN	
			if(@lWeekOff = @lWeekDay1)
			BEGIN
				Set @lStatus = 'W'
				RETURN @lStatus	
            END 
			if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
			BEGIN 
				SET @lStatus = 'P'
			END
				if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
			BEGIN 
				SET @lStatus = 'A'
			END
			IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
			INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId WHERE ES.BatchId = @rBatchId AND ((SourceId=@rDepartmentId) OR (@rDepartmentId=0)) 
			AND SourceTypeId in (2004, 3)
			AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
			BEGIN
				SET @lStatus = 'H'	
				RETURN @lStatus		
			END 
			IF Exists(select 1 From sHrm.tLeave L WHERE L.StatusId = 550 AND L.EmployeeId = @rEmployeeId AND @lDate BETWEEN L.FromDate AND L.ToDate)
			BEGIN
				SELECT @lStatus=LTM.Code + ' / ' + CASE WHEN L.LeavePeriodId = 1 THEN '1' WHEN L.LeavePeriodId = 2  THEN  '0.5' ELSE '0.25' END
				FROM sHrm.tLeave L INNER JOIN sHrm.tLeaveTypeMaster LTM ON LTM.Id = L.LeaveTypeId
				WHERE L.StatusId = 550 AND L.EmployeeId = @rEmployeeId AND @lDate BETWEEN L.FromDate AND L.ToDate
				RETURN @lStatus	
			END
		END
	END
	Else if @EmpFirstWeekOffRule = 9 
	BEGIN
		IF @WeekNumber = 4 
		BEGIN			
			if(@lWeekOff = @lWeekDay1)
			BEGIN
				Set @lStatus = 'W'
				RETURN @lStatus	
            END 
			if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
			BEGIN 
				SET @lStatus = 'P'
			END
			if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
			BEGIN 
				SET @lStatus = 'A'
			END
			IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
			INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId WHERE ES.BatchId = @rBatchId AND ((SourceId=@rDepartmentId) OR (@rDepartmentId=0)) 
			AND SourceTypeId in (2004, 3)AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
			BEGIN
				SET @lStatus = 'H'	
				RETURN @lStatus		
			END	 
			IF Exists(select 1 From sHrm.tLeave L WHERE L.StatusId = 550 AND L.EmployeeId = @rEmployeeId AND @lDate BETWEEN L.FromDate AND L.ToDate)
			BEGIN
				SELECT @lStatus=LTM.Code + ' / ' + CASE WHEN L.LeavePeriodId = 1 THEN '1' WHEN L.LeavePeriodId = 2  THEN  '0.5' ELSE '0.25' END
				FROM sHrm.tLeave L INNER JOIN sHrm.tLeaveTypeMaster LTM ON LTM.Id = L.LeaveTypeId
				WHERE L.StatusId = 550 AND L.EmployeeId = @rEmployeeId AND @lDate BETWEEN L.FromDate AND L.ToDate
				RETURN @lStatus	
			END
		END		 
	END	
--END
	
--Else
--BEGIN
	   
      if @EmpSecondWeekOffRule = 1 
	BEGIN	 
		 if(@lWeekOff = @lWeekDay2)
		BEGIN
			Set @lStatus = 'W'
			RETURN @lStatus	
		END
		if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
		BEGIN 
			SET @lStatus = 'P'
		END
			if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
		BEGIN 
			SET @lStatus = 'A'
		END	
		IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
		INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId WHERE ES.BatchId = @rBatchId AND ((SourceId=@rDepartmentId) OR (@rDepartmentId=0)) 
		AND SourceTypeId in (2004, 3)
		AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
		BEGIN
			SET @lStatus = 'H'	
			RETURN @lStatus	
		END
		IF Exists(select 1 From sHrm.tLeave L WHERE L.StatusId = 550 AND L.EmployeeId = @rEmployeeId AND @lDate BETWEEN L.FromDate AND L.ToDate)
		BEGIN
			SELECT @lStatus=LTM.Code + ' / ' + CASE WHEN L.LeavePeriodId = 1 THEN '1' WHEN L.LeavePeriodId = 2  THEN  '0.5' ELSE '0.25' END
			FROM sHrm.tLeave L INNER JOIN sHrm.tLeaveTypeMaster LTM ON LTM.Id = L.LeaveTypeId
			WHERE L.StatusId = 550 AND L.EmployeeId = @rEmployeeId AND @lDate BETWEEN L.FromDate AND L.ToDate
			RETURN @lStatus	
		END
		 
	END
	Else if @EmpSecondWeekOffRule = 2 
	BEGIN
	 
		IF @WeekNumber = 2 or @WeekNumber = 4 
		BEGIN
			if(@lWeekOff = @lWeekDay2)
			BEGIN
				Set @lStatus = 'W'
				RETURN @lStatus
			END

				 if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
					BEGIN 
						SET @lStatus = 'P'
					END
					 if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
					BEGIN 
						SET @lStatus = 'A'
					END
					
					IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
						INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId WHERE ES.BatchId = @rBatchId AND ((SourceId=@rDepartmentId) OR (@rDepartmentId=0)) 
						AND SourceTypeId in (2004, 3)
						AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
				BEGIN
					SET @lStatus = 'H'	
					RETURN @lStatus	
				END
				IF Exists(select 1 From sHrm.tLeave L WHERE L.StatusId = 550 AND L.EmployeeId = @rEmployeeId AND @lDate BETWEEN L.FromDate AND L.ToDate)
				BEGIN
					SELECT @lStatus=LTM.Code + ' / ' + CASE WHEN L.LeavePeriodId = 1 THEN '1' WHEN L.LeavePeriodId = 2  THEN  '0.5' ELSE '0.25' END
					FROM sHrm.tLeave L INNER JOIN sHrm.tLeaveTypeMaster LTM ON LTM.Id = L.LeaveTypeId
					WHERE L.StatusId = 550 AND L.EmployeeId = @rEmployeeId AND @lDate BETWEEN L.FromDate AND L.ToDate
					RETURN @lStatus	
				END
			END
		--	else
		--	BEGIN
		--		Set @lStatus= '-'
		--	END
			 
		--END
		--else
		--BEGIN
		--	Set @lStatus = '-'
		--	RETURN @lStatus	
		--END
	END
	else if @EmpSecondWeekOffRule = 3
	BEGIN
		if @WeekNumber = 1 or @WeekNumber = 3 
		BEGIN
			if(@lWeekOff = @lWeekDay2)
			BEGIN
				Set @lStatus = 'W'
				RETURN @lStatus
			END
			
				 if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
					BEGIN 
						SET @lStatus = 'P'
					END
					 if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
					BEGIN 
						SET @lStatus = 'A'
					END
					IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
						INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId WHERE ES.BatchId = @rBatchId AND ((SourceId=@rDepartmentId) OR (@rDepartmentId=0)) 
						AND SourceTypeId in (2004, 3)
						AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
				BEGIN
					SET @lStatus = 'H'	
					RETURN @lStatus	
				END
				IF Exists(select 1 From sHrm.tLeave L WHERE L.StatusId = 550 AND L.EmployeeId = @rEmployeeId AND @lDate BETWEEN L.FromDate AND L.ToDate)
				BEGIN
					SELECT @lStatus=LTM.Code + ' / ' + CASE WHEN L.LeavePeriodId = 1 THEN '1' WHEN L.LeavePeriodId = 2  THEN  '0.5' ELSE '0.25' END
					FROM sHrm.tLeave L INNER JOIN sHrm.tLeaveTypeMaster LTM ON LTM.Id = L.LeaveTypeId
					WHERE L.StatusId = 550 AND L.EmployeeId = @rEmployeeId AND @lDate BETWEEN L.FromDate AND L.ToDate
					RETURN @lStatus	
				END
			END
		--	else
		--	BEGIN
		--		Set @lStatus='-'
		--	END
			 
		--END
		--else
		--BEGIN
		--	Set @lStatus = '-'
		--	RETURN @lStatus	
		--END
	END
	else if @EmpSecondWeekOffRule = 4
	BEGIN
		 
		if @WeekNumber = 1 or @WeekNumber = 3 or @WeekNumber = 5
		BEGIN
			if(@lWeekOff = @lWeekDay2)
			BEGIN
				Set @lStatus = 'W'
				RETURN @lStatus
			END

				 if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
					BEGIN 
						SET @lStatus = 'P'
					END
					 if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
					BEGIN 
						SET @lStatus = 'A'
					END
					IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
						INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId WHERE ES.BatchId = @rBatchId AND ((SourceId=@rDepartmentId) OR (@rDepartmentId=0)) 
						AND SourceTypeId in (2004, 3)
						AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
				BEGIN
					SET @lStatus = 'H'	
					RETURN @lStatus	
				END
				IF Exists(select 1 From sHrm.tLeave L WHERE L.StatusId = 550 AND L.EmployeeId = @rEmployeeId AND @lDate BETWEEN L.FromDate AND L.ToDate)
				BEGIN	
					SELECT @lStatus=LTM.Code + ' / ' + CASE WHEN L.LeavePeriodId = 1 THEN '1' WHEN L.LeavePeriodId = 2  THEN  '0.5' ELSE '0.25' END
					FROM sHrm.tLeave L INNER JOIN sHrm.tLeaveTypeMaster LTM ON LTM.Id = L.LeaveTypeId
					WHERE L.StatusId = 550 AND L.EmployeeId = @rEmployeeId AND @lDate BETWEEN L.FromDate AND L.ToDate
					RETURN @lStatus
				END	
			END
		--	else
		--	BEGIN
		--		Set @lStatus = '-'
		--	END
			 
		--END
		--else
		--BEGIN
		--	Set @lStatus = '-'
		--	RETURN @lStatus	
		--END
	END
	Else if @EmpSecondWeekOffRule = 5
	BEGIN
		IF @WeekNumber = 2 or @WeekNumber = 3 
		BEGIN
			if(@lWeekOff = @lWeekDay2)
			BEGIN
				Set @lStatus = 'W'
				RETURN @lStatus	
            END 
			if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
			BEGIN 
				SET @lStatus = 'P'
			END
				if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
			BEGIN 
				SET @lStatus = 'A'
			END
			IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
			INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId WHERE ES.BatchId = @rBatchId AND ((SourceId=@rDepartmentId) OR (@rDepartmentId=0)) 
			AND SourceTypeId in (2004, 3)
			AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
			BEGIN
				SET @lStatus = 'H'	
				RETURN @lStatus	
			END
			IF Exists(select 1 From sHrm.tLeave L WHERE L.StatusId = 550 AND L.EmployeeId = @rEmployeeId AND @lDate BETWEEN L.FromDate AND L.ToDate)
			BEGIN	
				SELECT @lStatus=LTM.Code + ' / ' + CASE WHEN L.LeavePeriodId = 1 THEN '1' WHEN L.LeavePeriodId = 2  THEN  '0.5' ELSE '0.25' END
				FROM sHrm.tLeave L INNER JOIN sHrm.tLeaveTypeMaster LTM ON LTM.Id = L.LeaveTypeId
				WHERE L.StatusId = 550 AND L.EmployeeId = @rEmployeeId AND @lDate BETWEEN L.FromDate AND L.ToDate
				RETURN @lStatus
			END	
		END
	END
	Else if @EmpSecondWeekOffRule = 6
	BEGIN
		IF @WeekNumber = 1 
		BEGIN
			if(@lWeekOff = @lWeekDay2)
			BEGIN
				Set @lStatus = 'W'
				RETURN @lStatus	
            END 
			if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
			BEGIN 
				SET @lStatus = 'P'
			END
				if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
			BEGIN 
				SET @lStatus = 'A'
			END		
			IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
			INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId WHERE ES.BatchId = @rBatchId AND ((SourceId=@rDepartmentId) OR (@rDepartmentId=0)) 
			AND SourceTypeId in (2004, 3)
			AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
			BEGIN
				SET @lStatus = 'H'	
				RETURN @lStatus	
			END
			IF Exists(select 1 From sHrm.tLeave L WHERE L.StatusId = 550 AND L.EmployeeId = @rEmployeeId AND @lDate BETWEEN L.FromDate AND L.ToDate)
			BEGIN	
				SELECT @lStatus=LTM.Code + ' / ' + CASE WHEN L.LeavePeriodId = 1 THEN '1' WHEN L.LeavePeriodId = 2  THEN  '0.5' ELSE '0.25' END
				FROM sHrm.tLeave L INNER JOIN sHrm.tLeaveTypeMaster LTM ON LTM.Id = L.LeaveTypeId
				WHERE L.StatusId = 550 AND L.EmployeeId = @rEmployeeId AND @lDate BETWEEN L.FromDate AND L.ToDate
				RETURN @lStatus
			END	
		END
	END
	Else if @EmpSecondWeekOffRule = 7
	BEGIN
		IF @WeekNumber = 2 
		BEGIN
			if(@lWeekOff = @lWeekDay2)
			BEGIN
				Set @lStatus = 'W'
				RETURN @lStatus	
            END 
			if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
			BEGIN 
				SET @lStatus = 'P'
			END
				if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
			BEGIN 
				SET @lStatus = 'A'
			END
					
			IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
				INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId WHERE ES.BatchId = @rBatchId AND ((SourceId=@rDepartmentId) OR (@rDepartmentId=0)) 
				AND SourceTypeId in (2004, 3)
				AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
			BEGIN
				SET @lStatus = 'H'	
				RETURN @lStatus	
			END
			IF Exists(select 1 From sHrm.tLeave L WHERE L.StatusId = 550 AND L.EmployeeId = @rEmployeeId AND @lDate BETWEEN L.FromDate AND L.ToDate)
			BEGIN	
				SELECT @lStatus=LTM.Code + ' / ' + CASE WHEN L.LeavePeriodId = 1 THEN '1' WHEN L.LeavePeriodId = 2  THEN  '0.5' ELSE '0.25' END
				FROM sHrm.tLeave L INNER JOIN sHrm.tLeaveTypeMaster LTM ON LTM.Id = L.LeaveTypeId
				WHERE L.StatusId = 550 AND L.EmployeeId = @rEmployeeId AND @lDate BETWEEN L.FromDate AND L.ToDate
				RETURN @lStatus
			END	
		END
	END
	
	Else if @EmpSecondWeekOffRule = 8
	BEGIN
		IF @WeekNumber = 3 
		BEGIN
			if(@lWeekOff = @lWeekDay2)
			BEGIN
				Set @lStatus = 'W'
				RETURN @lStatus	
            END 
			if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
			BEGIN 
				SET @lStatus = 'P'
			END
				if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
			BEGIN 
				SET @lStatus = 'A'
			END	
			IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
				INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId WHERE ES.BatchId = @rBatchId AND ((SourceId=@rDepartmentId) OR (@rDepartmentId=0)) 
				AND SourceTypeId in (2004, 3)
				AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
			BEGIN
				SET @lStatus = 'H'	
				RETURN @lStatus	
			END	 
			IF Exists(select 1 From sHrm.tLeave L WHERE L.StatusId = 550 AND L.EmployeeId = @rEmployeeId AND @lDate BETWEEN L.FromDate AND L.ToDate)
			BEGIN	
				SELECT @lStatus=LTM.Code + ' / ' + CASE WHEN L.LeavePeriodId = 1 THEN '1' WHEN L.LeavePeriodId = 2  THEN  '0.5' ELSE '0.25' END
				FROM sHrm.tLeave L INNER JOIN sHrm.tLeaveTypeMaster LTM ON LTM.Id = L.LeaveTypeId
				WHERE L.StatusId = 550 AND L.EmployeeId = @rEmployeeId AND @lDate BETWEEN L.FromDate AND L.ToDate
				RETURN @lStatus
			END	
		END
	END
	
	Else if @EmpSecondWeekOffRule = 9
	BEGIN
		IF @WeekNumber = 4 
		BEGIN
			if(@lWeekOff = @lWeekDay2)
			BEGIN
				Set @lStatus = 'W'
				RETURN @lStatus	
            END 
			if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
			BEGIN 
				SET @lStatus = 'P'
			END
				if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
			BEGIN 
				SET @lStatus = 'A'
			END		
			IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
				INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId WHERE ES.BatchId = @rBatchId AND ((SourceId=@rDepartmentId) OR (@rDepartmentId=0)) 
				AND SourceTypeId in (2004, 3)
				AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
			BEGIN
				SET @lStatus = 'H'	
				RETURN @lStatus	
			END
			IF Exists(select 1 From sHrm.tLeave L WHERE L.StatusId = 550 AND L.EmployeeId = @rEmployeeId AND @lDate BETWEEN L.FromDate AND L.ToDate)
			BEGIN	
				SELECT @lStatus=LTM.Code + ' / ' + CASE WHEN L.LeavePeriodId = 1 THEN '1' WHEN L.LeavePeriodId = 2  THEN  '0.5' ELSE '0.25' END
				FROM sHrm.tLeave L INNER JOIN sHrm.tLeaveTypeMaster LTM ON LTM.Id = L.LeaveTypeId
				WHERE L.StatusId = 550 AND L.EmployeeId = @rEmployeeId AND @lDate BETWEEN L.FromDate AND L.ToDate
				RETURN @lStatus
			END	
		END 
	END
--END
 
 
  
			
	RETURN @lStatus	
END
GO
PRINT N'Altering [sTimetable].[fTimeTableSubjectGet]...';


GO


ALTER FUNCTION [sTimetable].[fTimeTableSubjectGet](@rTimeTableSchemaId int,@rSubjectId int,@rLectureNumber tinyint, @rDayId tinyint,@rIsTimeTableDetail bit)
RETURNS nvarchar(2000) WITH EXECUTE AS CALLER
AS 
BEGIN
	DECLARE @rTimeTableDetail nvarchar(2000)
	
	IF EXISTS(SELECT 1 FROM sTimetable.tTimeTableSchema TS INNER JOIN sTimetable.tTimeTable TT ON TT.TimeTableSchemaId = TS.Id WHERE TS.IsDisplayPeriodTime = 1 AND TS.Id = @rTimeTableSchemaId)
	BEGIN
	IF(@rIsTimeTableDetail=0)
	BEGIN
		SELECT 
			@rTimeTableDetail=COALESCE(@rTimeTableDetail+',<br> ','') + EM.ShortName + ' - ' + VBCD.ClassDivisionName +'|'+ ISNULL(TTM.FromTime,0) +'-'+ ISNULL(TTM.ToTime,0)
		FROM 
			sTimetable.tTimeTable T 
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = T.EmployeeId
			INNER JOIN sTimetable.tTimeTableSchema TTS ON TTS.Id = T.TimeTableSchemaId
			INNER JOIN sSetup.vClassDivision VBCD ON VBCD.DivisionId=T.DivisionId
			LEFT JOIN sTimetable.tTimeTableTime TTM ON TTM.TimeTableSchemaId=T.TimeTableSchemaId AND TTM.DayId = T.DayId AND TTM.DivisionId = T.DivisionId AND TTM.LectureNumber = T.LectureNumber AND ISNULL(TTM.IsBreak,0)=0 and ISNULL(TTM.IsBreakBefore,0)=0
		WHERE 
			T.TimeTableSchemaId = @rTimeTableSchemaId
			AND T.SubjectId =  @rSubjectId
			AND T.DayId=@rDayId 
			AND T.LectureNumber = @rLectureNumber
			AND  ISNULL(EM.IsOtherUser,0) = 0

		IF(@rTimeTableDetail IS NOT NULL)
			SET @rTimeTableDetail = ',<br> '+@rTimeTableDetail
	END
	ELSE IF(@rIsTimeTableDetail=1)
	BEGIN
		SELECT 
			@rTimeTableDetail=COALESCE(@rTimeTableDetail+',<br> ','') + EM.ShortName + ' - ' + VBCD.ClassDivisionName +'|'+ ISNULL(TTM.FromTime,0) +'-'+ ISNULL(TTM.ToTime,0)
		FROM 
			sTimetable.tTimeTable T 
			INNER JOIN sTimetable.tTimeTableDetail TT ON  T.Id = TT.TimeTableId
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = TT.EmployeeId
			INNER JOIN sTimetable.tTimeTableSchema TTS ON TTS.Id = T.TimeTableSchemaId
			INNER JOIN sSetup.vClassDivision VBCD ON VBCD.DivisionId=T.DivisionId
			LEFT JOIN sTimetable.tTimeTableTime TTM ON TTM.TimeTableSchemaId=T.TimeTableSchemaId AND TTM.DayId = T.DayId AND TTM.DivisionId = T.DivisionId AND TTM.LectureNumber = T.LectureNumber AND ISNULL(TTM.IsBreak,0)=0 and ISNULL(TTM.IsBreakBefore,0)=0
		WHERE 
			T.TimeTableSchemaId = @rTimeTableSchemaId
			AND TT.SubjectId =  @rSubjectId
			AND T.DayId=@rDayId 
			AND T.LectureNumber = @rLectureNumber
			AND  ISNULL(EM.IsOtherUser,0) = 0

		IF(@rTimeTableDetail IS NOT NULL)
			SET @rTimeTableDetail = ',<br> '+@rTimeTableDetail
	END
	END
ELSE
	BEGIN
	IF(@rIsTimeTableDetail=0)
	BEGIN
		SELECT 
			@rTimeTableDetail=COALESCE(@rTimeTableDetail+',<br> ','') + EM.ShortName + ' - ' + VBCD.ClassDivisionName 
		FROM 
			sTimetable.tTimeTable T 
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = T.EmployeeId
			INNER JOIN sTimetable.tTimeTableSchema TTS ON TTS.Id = T.TimeTableSchemaId
			INNER JOIN sSetup.vClassDivision VBCD ON VBCD.DivisionId=T.DivisionId
		WHERE 
			T.TimeTableSchemaId = @rTimeTableSchemaId
			AND T.SubjectId =  @rSubjectId
			AND T.DayId=@rDayId 
			AND T.LectureNumber = @rLectureNumber
			AND  ISNULL(EM.IsOtherUser,0) = 0

		IF(@rTimeTableDetail IS NOT NULL)
			SET @rTimeTableDetail = ',<br> '+@rTimeTableDetail
	END
	ELSE IF(@rIsTimeTableDetail=1)
	BEGIN
		SELECT 
			@rTimeTableDetail=COALESCE(@rTimeTableDetail+',<br> ','') + EM.ShortName + ' - ' + VBCD.ClassDivisionName
		FROM 
			sTimetable.tTimeTable T 
			INNER JOIN sTimetable.tTimeTableDetail TT ON  T.Id = TT.TimeTableId
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = TT.EmployeeId
			INNER JOIN sTimetable.tTimeTableSchema TTS ON TTS.Id = T.TimeTableSchemaId
			INNER JOIN sSetup.vClassDivision VBCD ON VBCD.DivisionId=T.DivisionId
		WHERE 
			T.TimeTableSchemaId = @rTimeTableSchemaId
			AND TT.SubjectId =  @rSubjectId
			AND T.DayId=@rDayId 
			AND T.LectureNumber = @rLectureNumber
			AND  ISNULL(EM.IsOtherUser,0) = 0

		IF(@rTimeTableDetail IS NOT NULL)
			SET @rTimeTableDetail = ',<br> '+@rTimeTableDetail
	END
	
	END
	RETURN ISNULL(@rTimeTableDetail,'') 
END
GO
PRINT N'Altering [sStudent].[vStudentAcademic]...';


GO






 
ALTER VIEW [sStudent].[vStudentAcademic]   
AS
SELECT 
	  A.Id AS AcademicId,	  
	  A.ClassId,
	  A.DivisionId,
	  A.RollNo,
	  A.OrgId,
	  A.BatchId,
	  SM.Id AS StudentId,
	  SM.Code,
	  ISNULL(SM.Number,0) AS Number,
	  SM.RegistrationNumber,
	  SM.FirstName,
	  SM.MiddleName,
	  SM.LastName,
	   [sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Name,
	  Convert(Nvarchar(20),A.RollNo) + '-' + SM.FirstName+' '+SM.LastName AS RollNoName,	  
	  SM.StatusId,
	  CM.DisplayTitle AS ClassName,
	  DM.DisplayTitle AS DivisionName,
	  STM.Title AS StatusName,	  
	  SM.RecordStatusId,	  
	  DM.InchargeEmployeeId, 
	  BM.OrgGroupBatchId,	  
	  ISNULL(A.AdmissionCategoryId,0) AS AdmissionCategoryId,
	  --SM.AdmissionCategoryId,
	  DM.OrderIndex DivisionOrder,
	  BM.IsActive AS IsActiveBatch,
	  BM.Title AS BatchName,
	  ISNULL(DeptM.Id,0) AS DepartmentId,
	  ISNULL(DeptM.Title,'') AS DepartmentName,
	  SM.IsBlackList,
	  SM.BlackListReason,
	  CM.OrderIndex AS ClassOrderIndex,
	  ISNULL(A.ExemptionTypeId,0) AS ExemptionTypeId,
	  ISNULL(OM.DisplayTitle,'')  AS OrganizationName,
	  OM.StreetOne,
	  OM.StreetTwo,
	  OM.StreetThree,
	  OM.ZipCode,
	  ISNULL(SM.SUId,'') AS SUId ,
	  ISNULL(OM.ReportOrgGroupTitle,'') AS ReportOrgGroupTitle,
	  ISNULL(OM.ReportOrgTitle,'') AS ReportOrgTitle,
	  ISNULL(A.FeeStructureId,0) AS FeeStructureId,
	  SM.ReferenceSourceId ,
	  SM.StudentGroupId,
	  SM.StudentOtherGroupId,
	  A.BatchStatusId,
	  A.ClassStatusId,
	  STM1.Title AS ClassStatusName,
	  ISNULL(SO.GenderId,0) AS GenderId,
	   ISNULL(A.FeesRemark,'') AS FeesRemark
	  
  FROM 
	sStudent.tAcademic A
	
	INNER JOIN sStudent.tStudentMaster SM
		ON A.StudentId=SM.Id	
	INNER JOIN sSetup.tClassMaster CM
		ON CM.Id=A.ClassId
	INNER JOIN sSetup.tDivisionMaster DM
		ON DM.Id=A.DivisionId
	INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId 
	INNER JOIN sStudent.tStatusMaster STM
		ON STM.Id=SM.StatusId
	INNER JOIN sSetup.tDepartmentMaster DeptM
		ON DeptM.Id=CM.DepartmentId
	INNER JOIN sSetup.tOrganizationMaster OM 
	    ON A.OrgId = OM.Id
	INNER JOIN sStudent.tStatusMaster STM1
		ON STM1.Id=A.ClassStatusId
	LEFT JOIN sStudent.tStudentOther SO 
		ON SO.StudentId=SM.Id
GO
 


GO

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


GO

 
ALTER PROCEDURE [sAcademic].[pDailyStatusGet]

     @rSearchDate datetime,
     @rOrgId smallint,
     @rBatchId int,     
     @rYear smallint,
     @rMonth smallint,
     @rDate smallint,
	 @rAttendanceTypeId int=1
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 	
	 
 

	SELECT 				
			vCD.ClassDivisionName,
			ISNULL(EM.FirstName+' '+ EM.LastName,'') AS ClassTeacherName,
			[sAttendance].[fWeekHOffGet](@rYear,@rMonth,@rDate,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId) AS WeekOffStatus, 
			CASE WHEN COUNT(SR.AcademicId)=0 THEN CASE WHEN (Select [sCommon].[fCountAbsentStudent](A.DivisionId,  @rBatchId,@rSearchDate,@rAttendanceTypeId,0)) =0 THEN 'Pending' ELSE 'Complete' END ELSE 'Complete' END AS PresentStatus, 
            sCommon.fCountDivisionStudent(A.DivisionId,@rBatchId) AS TotalCount, 
            [sCommon].[fCountAbsentStudent](A.DivisionId,@rBatchId,@rSearchDate,@rAttendanceTypeId,1) AS PresentCount,
            [sCommon].[fCountAbsentStudent](A.DivisionId,@rBatchId,@rSearchDate,@rAttendanceTypeId,0) AS AbsentCount,
			ISNULL(MAX(SR.UpdatedDateTime),MAX(SR.CreatedDateTime)) as UpdatedDateTime,
			--ISNULL((SELECT TOP 1 U.DisplayTitle FROM sSecurity.tUser U WHERE U.Id = ISNULL(SR.UpdatedUserId,SR.CreatedUserId)),'') AS UserName
			[sCommon].[fGetUserNameforDailyStatus](A.DivisionId,@rSearchDate,@rAttendanceTypeId)AS UserName
    FROM 
			sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId AND SM.StatusId=1 
			INNER JOIN sSetup.vClassDivision vCD ON vCD.ClassId=A.ClassId 
            AND vCD.DivisionId=A.DivisionId AND A.OrgId=vCD.OrgId AND A.OrgId=@rOrgId AND A.BatchId=@rBatchId AND vCD.IsObsolete=0 
            INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vCD.DivisionId 
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId AND ISNULL(EM.IsOtherUser,0) = 0
            LEFT JOIN sAttendance.tStudentRegister SR ON A.Id = SR.AcademicId AND SR.AttendanceDate=@rSearchDate 
            AND SR.AttendanceTypeId = @rAttendanceTypeId 
			AND SR.IsPresent=1 
			 			
            GROUP BY A.DivisionId,A.BatchId,vCD.ClassDivisionName,vCD.OrderIndex,EM.FirstName,EM.LastName,SM.StatusId,A.ClassId
			--,SR.UpdatedUserId,SR.CreatedUserId
            ORDER BY vCD.OrderIndex
END
GO
PRINT N'Altering [sAcademic].[pMonthlyStatusGet]...';


GO
 
ALTER PROCEDURE [sAcademic].[pMonthlyStatusGet]

    
	 
     @rOrgId smallint,
     @rBatchId Bigint,     
     @rYear smallint,
     @rMonth smallint,
	 @rDayOfMonth smallint,
	 @rAttendanceTypeId int =1,
	 @rClassId Bigint,
	 @rDivisionId Bigint
     --@rDate smallint,
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 	
	



 SELECT 	A.ClassId ,A.DivisionId,vCD.ClassDivisionName,ISNULL(EM.FirstName+' '+ EM.LastName,'') AS ClassTeacherName,
		  

			(SELECT CASE WHEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,01,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) !='' THEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,01,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) ELSE CASE WHEN COUNT(SR.AcademicId)=0 THEN CASE WHEN (Select [sCommon].[fCountAbsentStudent](A.DivisionId,  @rBatchId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-01')),@rAttendanceTypeId,0)) =0 THEN 'P' ELSE 'C' END ELSE 'C' END END  
			   
			FROM 	sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId AND SM.StatusId=1 
			INNER JOIN sSetup.vClassDivision vCD ON vCD.ClassId=A.ClassId AND vCD.OrgId=@rOrgId
            AND vCD.DivisionId=A.DivisionId AND A.OrgId=vCD.OrgId AND A.OrgId=@rOrgId AND A.BatchId=@rBatchId AND vCD.IsObsolete=0 
            INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vCD.DivisionId  AND  DM.OrgId=@rOrgId
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId AND ISNULL(EM.IsOtherUser,0) = 0
            LEFT JOIN sAttendance.tStudentRegister SR ON A.Id = SR.AcademicId 		
			AND SR.AttendanceDate=CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-01'))		
            AND SR.AttendanceTypeId = @rAttendanceTypeId	AND SR.IsPresent=1		
			WHERE A.ClassId=@rClassId		AND A.DivisionId=@rDivisionId 
            GROUP BY A.DivisionId,A.BatchId,vCD.ClassDivisionName,vCD.OrderIndex,EM.FirstName,EM.LastName,SM.StatusId,A.ClassId	) AS P1	,

			(SELECT CASE WHEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,02,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) !='' THEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,02,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) ELSE CASE WHEN COUNT(SR.AcademicId)=0 THEN CASE WHEN (Select [sCommon].[fCountAbsentStudent](A.DivisionId,  @rBatchId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-02')),@rAttendanceTypeId,0)) =0 THEN 'P' ELSE 'C' END ELSE 'C' END END  
			   
			FROM 	sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId AND SM.StatusId=1 
			INNER JOIN sSetup.vClassDivision vCD ON vCD.ClassId=A.ClassId AND vCD.OrgId=@rOrgId
            AND vCD.DivisionId=A.DivisionId AND A.OrgId=vCD.OrgId AND A.OrgId=@rOrgId AND A.BatchId=@rBatchId AND vCD.IsObsolete=0 
            INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vCD.DivisionId  AND  DM.OrgId=@rOrgId
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId AND ISNULL(EM.IsOtherUser,0) = 0
            LEFT JOIN sAttendance.tStudentRegister SR ON A.Id = SR.AcademicId 		
			AND SR.AttendanceDate=CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-02'))		
            AND SR.AttendanceTypeId = @rAttendanceTypeId	AND SR.IsPresent=1		
			WHERE A.ClassId=@rClassId		AND A.DivisionId=@rDivisionId 
            GROUP BY A.DivisionId,A.BatchId,vCD.ClassDivisionName,vCD.OrderIndex,EM.FirstName,EM.LastName,SM.StatusId,A.ClassId	) AS P2,

			(SELECT CASE WHEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,03,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) !='' THEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,03,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) ELSE CASE WHEN COUNT(SR.AcademicId)=0 THEN CASE WHEN (Select [sCommon].[fCountAbsentStudent](A.DivisionId,  @rBatchId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-03')),@rAttendanceTypeId,0)) =0 THEN 'P' ELSE 'C' END ELSE 'C' END END  
			   
			FROM 	sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId AND SM.StatusId=1 
			INNER JOIN sSetup.vClassDivision vCD ON vCD.ClassId=A.ClassId AND vCD.OrgId=@rOrgId
            AND vCD.DivisionId=A.DivisionId AND A.OrgId=vCD.OrgId AND A.OrgId=@rOrgId AND A.BatchId=@rBatchId AND vCD.IsObsolete=0 
            INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vCD.DivisionId  AND  DM.OrgId=@rOrgId
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId AND ISNULL(EM.IsOtherUser,0) = 0
            LEFT JOIN sAttendance.tStudentRegister SR ON A.Id = SR.AcademicId 		
			AND SR.AttendanceDate=CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-03'))		
            AND SR.AttendanceTypeId = @rAttendanceTypeId	AND SR.IsPresent=1		
			WHERE A.ClassId=@rClassId		AND A.DivisionId=@rDivisionId 
            GROUP BY A.DivisionId,A.BatchId,vCD.ClassDivisionName,vCD.OrderIndex,EM.FirstName,EM.LastName,SM.StatusId,A.ClassId	) AS P3,

			(SELECT CASE WHEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,04,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) !='' THEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,04,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) ELSE CASE WHEN COUNT(SR.AcademicId)=0 THEN CASE WHEN (Select [sCommon].[fCountAbsentStudent](A.DivisionId,  @rBatchId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-04')),@rAttendanceTypeId,0)) =0 THEN 'P' ELSE 'C' END ELSE 'C' END END  
			   
			FROM 	sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId AND SM.StatusId=1 
			INNER JOIN sSetup.vClassDivision vCD ON vCD.ClassId=A.ClassId AND vCD.OrgId=@rOrgId
            AND vCD.DivisionId=A.DivisionId AND A.OrgId=vCD.OrgId AND A.OrgId=@rOrgId AND A.BatchId=@rBatchId AND vCD.IsObsolete=0 
            INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vCD.DivisionId  AND  DM.OrgId=@rOrgId
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId AND ISNULL(EM.IsOtherUser,0) = 0
            LEFT JOIN sAttendance.tStudentRegister SR ON A.Id = SR.AcademicId 		
			AND SR.AttendanceDate=CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-04'))		
            AND SR.AttendanceTypeId = @rAttendanceTypeId	AND SR.IsPresent=1		
			WHERE A.ClassId=@rClassId		AND A.DivisionId=@rDivisionId 
            GROUP BY A.DivisionId,A.BatchId,vCD.ClassDivisionName,vCD.OrderIndex,EM.FirstName,EM.LastName,SM.StatusId,A.ClassId	) AS P4,

			(SELECT CASE WHEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,05,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) !='' THEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,05,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) ELSE CASE WHEN COUNT(SR.AcademicId)=0 THEN CASE WHEN (Select [sCommon].[fCountAbsentStudent](A.DivisionId,  @rBatchId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-05')),@rAttendanceTypeId,0)) =0 THEN 'P' ELSE 'C' END ELSE 'C' END END  
			   
			FROM 	sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId AND SM.StatusId=1 
			INNER JOIN sSetup.vClassDivision vCD ON vCD.ClassId=A.ClassId AND vCD.OrgId=@rOrgId
            AND vCD.DivisionId=A.DivisionId AND A.OrgId=vCD.OrgId AND A.OrgId=@rOrgId AND A.BatchId=@rBatchId AND vCD.IsObsolete=0 
            INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vCD.DivisionId  AND  DM.OrgId=@rOrgId
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId AND ISNULL(EM.IsOtherUser,0) = 0
            LEFT JOIN sAttendance.tStudentRegister SR ON A.Id = SR.AcademicId 		
			AND SR.AttendanceDate=CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-05'))		
            AND SR.AttendanceTypeId = @rAttendanceTypeId	AND SR.IsPresent=1		
			WHERE A.ClassId=@rClassId		AND A.DivisionId=@rDivisionId 
            GROUP BY A.DivisionId,A.BatchId,vCD.ClassDivisionName,vCD.OrderIndex,EM.FirstName,EM.LastName,SM.StatusId,A.ClassId	) AS P5,

			(SELECT CASE WHEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,06,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) !='' THEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,06,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) ELSE CASE WHEN COUNT(SR.AcademicId)=0 THEN CASE WHEN (Select [sCommon].[fCountAbsentStudent](A.DivisionId,  @rBatchId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-06')),@rAttendanceTypeId,0)) =0 THEN 'P' ELSE 'C' END ELSE 'C' END END  
			   
			FROM 	sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId AND SM.StatusId=1 
			INNER JOIN sSetup.vClassDivision vCD ON vCD.ClassId=A.ClassId AND vCD.OrgId=@rOrgId
            AND vCD.DivisionId=A.DivisionId AND A.OrgId=vCD.OrgId AND A.OrgId=@rOrgId AND A.BatchId=@rBatchId AND vCD.IsObsolete=0 
            INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vCD.DivisionId  AND  DM.OrgId=@rOrgId
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId AND ISNULL(EM.IsOtherUser,0) = 0
            LEFT JOIN sAttendance.tStudentRegister SR ON A.Id = SR.AcademicId 		
			AND SR.AttendanceDate=CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-06'))		
            AND SR.AttendanceTypeId = @rAttendanceTypeId	AND SR.IsPresent=1		
			WHERE A.ClassId=@rClassId		AND A.DivisionId=@rDivisionId 
            GROUP BY A.DivisionId,A.BatchId,vCD.ClassDivisionName,vCD.OrderIndex,EM.FirstName,EM.LastName,SM.StatusId,A.ClassId	) AS P6,

			(SELECT CASE WHEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,07,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) !='' THEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,07,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) ELSE CASE WHEN COUNT(SR.AcademicId)=0 THEN CASE WHEN (Select [sCommon].[fCountAbsentStudent](A.DivisionId,  @rBatchId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-07')),@rAttendanceTypeId,0)) =0 THEN 'P' ELSE 'C' END ELSE 'C' END END  
			   
			FROM 	sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId AND SM.StatusId=1 
			INNER JOIN sSetup.vClassDivision vCD ON vCD.ClassId=A.ClassId AND vCD.OrgId=@rOrgId
            AND vCD.DivisionId=A.DivisionId AND A.OrgId=vCD.OrgId AND A.OrgId=@rOrgId AND A.BatchId=@rBatchId AND vCD.IsObsolete=0 
            INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vCD.DivisionId  AND  DM.OrgId=@rOrgId
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId AND ISNULL(EM.IsOtherUser,0) = 0
            LEFT JOIN sAttendance.tStudentRegister SR ON A.Id = SR.AcademicId 		
			AND SR.AttendanceDate=CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-07'))		
            AND SR.AttendanceTypeId = @rAttendanceTypeId	AND SR.IsPresent=1		
			WHERE A.ClassId=@rClassId		AND A.DivisionId=@rDivisionId 
            GROUP BY A.DivisionId,A.BatchId,vCD.ClassDivisionName,vCD.OrderIndex,EM.FirstName,EM.LastName,SM.StatusId,A.ClassId	) AS P7,

			(SELECT CASE WHEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,08,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) !='' THEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,08,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) ELSE CASE WHEN COUNT(SR.AcademicId)=0 THEN CASE WHEN (Select [sCommon].[fCountAbsentStudent](A.DivisionId,  @rBatchId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-08')),@rAttendanceTypeId,0)) =0 THEN 'P' ELSE 'C' END ELSE 'C' END END  
			   
			FROM 	sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId AND SM.StatusId=1 
			INNER JOIN sSetup.vClassDivision vCD ON vCD.ClassId=A.ClassId AND vCD.OrgId=@rOrgId
            AND vCD.DivisionId=A.DivisionId AND A.OrgId=vCD.OrgId AND A.OrgId=@rOrgId AND A.BatchId=@rBatchId AND vCD.IsObsolete=0 
            INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vCD.DivisionId  AND  DM.OrgId=@rOrgId
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId AND ISNULL(EM.IsOtherUser,0) = 0
            LEFT JOIN sAttendance.tStudentRegister SR ON A.Id = SR.AcademicId 		
			AND SR.AttendanceDate=CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-08'))		
            AND SR.AttendanceTypeId = @rAttendanceTypeId	AND SR.IsPresent=1		
			WHERE A.ClassId=@rClassId		AND A.DivisionId=@rDivisionId 
            GROUP BY A.DivisionId,A.BatchId,vCD.ClassDivisionName,vCD.OrderIndex,EM.FirstName,EM.LastName,SM.StatusId,A.ClassId	) AS P8,

			(SELECT CASE WHEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,09,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) !='' THEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,09,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) ELSE CASE WHEN COUNT(SR.AcademicId)=0 THEN CASE WHEN (Select [sCommon].[fCountAbsentStudent](A.DivisionId,  @rBatchId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-09')),@rAttendanceTypeId,0)) =0 THEN 'P' ELSE 'C' END ELSE 'C' END END  
			   
			FROM 	sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId AND SM.StatusId=1 
			INNER JOIN sSetup.vClassDivision vCD ON vCD.ClassId=A.ClassId AND vCD.OrgId=@rOrgId
            AND vCD.DivisionId=A.DivisionId AND A.OrgId=vCD.OrgId AND A.OrgId=@rOrgId AND A.BatchId=@rBatchId AND vCD.IsObsolete=0 
            INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vCD.DivisionId  AND  DM.OrgId=@rOrgId
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId AND ISNULL(EM.IsOtherUser,0) = 0
            LEFT JOIN sAttendance.tStudentRegister SR ON A.Id = SR.AcademicId 		
			AND SR.AttendanceDate=CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-09'))		
            AND SR.AttendanceTypeId = @rAttendanceTypeId	AND SR.IsPresent=1		
			WHERE A.ClassId=@rClassId		AND A.DivisionId=@rDivisionId 
            GROUP BY A.DivisionId,A.BatchId,vCD.ClassDivisionName,vCD.OrderIndex,EM.FirstName,EM.LastName,SM.StatusId,A.ClassId	) AS P9,

			(SELECT CASE WHEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,10,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) !='' THEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,10,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) ELSE CASE WHEN COUNT(SR.AcademicId)=0 THEN CASE WHEN (Select [sCommon].[fCountAbsentStudent](A.DivisionId,  @rBatchId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-10')),@rAttendanceTypeId,0)) =0 THEN 'P' ELSE 'C' END ELSE 'C' END END  
			   
			FROM 	sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId AND SM.StatusId=1 
			INNER JOIN sSetup.vClassDivision vCD ON vCD.ClassId=A.ClassId AND vCD.OrgId=@rOrgId
            AND vCD.DivisionId=A.DivisionId AND A.OrgId=vCD.OrgId AND A.OrgId=@rOrgId AND A.BatchId=@rBatchId AND vCD.IsObsolete=0 
            INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vCD.DivisionId  AND  DM.OrgId=@rOrgId
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId AND ISNULL(EM.IsOtherUser,0) = 0
            LEFT JOIN sAttendance.tStudentRegister SR ON A.Id = SR.AcademicId 		
			AND SR.AttendanceDate=CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-10'))		
            AND SR.AttendanceTypeId = @rAttendanceTypeId	AND SR.IsPresent=1		
			WHERE A.ClassId=@rClassId		AND A.DivisionId=@rDivisionId 
            GROUP BY A.DivisionId,A.BatchId,vCD.ClassDivisionName,vCD.OrderIndex,EM.FirstName,EM.LastName,SM.StatusId,A.ClassId	) AS P10,

			(SELECT CASE WHEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,11,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) !='' THEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,11,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) ELSE CASE WHEN COUNT(SR.AcademicId)=0 THEN CASE WHEN (Select [sCommon].[fCountAbsentStudent](A.DivisionId,  @rBatchId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-11')),@rAttendanceTypeId,0)) =0 THEN 'P' ELSE 'C' END ELSE 'C' END END  
			   
			FROM 	sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId AND SM.StatusId=1 
			INNER JOIN sSetup.vClassDivision vCD ON vCD.ClassId=A.ClassId AND vCD.OrgId=@rOrgId
            AND vCD.DivisionId=A.DivisionId AND A.OrgId=vCD.OrgId AND A.OrgId=@rOrgId AND A.BatchId=@rBatchId AND vCD.IsObsolete=0 
            INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vCD.DivisionId  AND  DM.OrgId=@rOrgId
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId AND ISNULL(EM.IsOtherUser,0) = 0
            LEFT JOIN sAttendance.tStudentRegister SR ON A.Id = SR.AcademicId 		
			AND SR.AttendanceDate=CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-11'))		
            AND SR.AttendanceTypeId = @rAttendanceTypeId	AND SR.IsPresent=1		
			WHERE A.ClassId=@rClassId		AND A.DivisionId=@rDivisionId 
            GROUP BY A.DivisionId,A.BatchId,vCD.ClassDivisionName,vCD.OrderIndex,EM.FirstName,EM.LastName,SM.StatusId,A.ClassId	) AS P11,

			(SELECT CASE WHEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,12,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) !='' THEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,12,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) ELSE CASE WHEN COUNT(SR.AcademicId)=0 THEN CASE WHEN (Select [sCommon].[fCountAbsentStudent](A.DivisionId,  @rBatchId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-12')),@rAttendanceTypeId,0)) =0 THEN 'P' ELSE 'C' END ELSE 'C' END END  
			   
			FROM 	sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId AND SM.StatusId=1 
			INNER JOIN sSetup.vClassDivision vCD ON vCD.ClassId=A.ClassId AND vCD.OrgId=@rOrgId
            AND vCD.DivisionId=A.DivisionId AND A.OrgId=vCD.OrgId AND A.OrgId=@rOrgId AND A.BatchId=@rBatchId AND vCD.IsObsolete=0 
            INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vCD.DivisionId  AND  DM.OrgId=@rOrgId
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId
            LEFT JOIN sAttendance.tStudentRegister SR ON A.Id = SR.AcademicId 		
			AND SR.AttendanceDate=CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-12'))		
            AND SR.AttendanceTypeId = @rAttendanceTypeId	AND SR.IsPresent=1		
			WHERE A.ClassId=@rClassId		AND A.DivisionId=@rDivisionId AND ISNULL(EM.IsOtherUser,0) = 0
            GROUP BY A.DivisionId,A.BatchId,vCD.ClassDivisionName,vCD.OrderIndex,EM.FirstName,EM.LastName,SM.StatusId,A.ClassId	) AS P12,

			(SELECT CASE WHEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,13,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) !='' THEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,13,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) ELSE CASE WHEN COUNT(SR.AcademicId)=0 THEN CASE WHEN (Select [sCommon].[fCountAbsentStudent](A.DivisionId,  @rBatchId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-13')),@rAttendanceTypeId,0)) =0 THEN 'P' ELSE 'C' END ELSE 'C' END END  
			   
			FROM 	sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId AND SM.StatusId=1 
			INNER JOIN sSetup.vClassDivision vCD ON vCD.ClassId=A.ClassId AND vCD.OrgId=@rOrgId
            AND vCD.DivisionId=A.DivisionId AND A.OrgId=vCD.OrgId AND A.OrgId=@rOrgId AND A.BatchId=@rBatchId AND vCD.IsObsolete=0 
            INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vCD.DivisionId  AND  DM.OrgId=@rOrgId
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId AND ISNULL(EM.IsOtherUser,0) = 0
            LEFT JOIN sAttendance.tStudentRegister SR ON A.Id = SR.AcademicId 		
			AND SR.AttendanceDate=CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-13'))		
            AND SR.AttendanceTypeId = @rAttendanceTypeId	AND SR.IsPresent=1		
			WHERE A.ClassId=@rClassId		AND A.DivisionId=@rDivisionId 
            GROUP BY A.DivisionId,A.BatchId,vCD.ClassDivisionName,vCD.OrderIndex,EM.FirstName,EM.LastName,SM.StatusId,A.ClassId	) AS P13,

			(SELECT CASE WHEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,14,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) !='' THEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,14,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) ELSE CASE WHEN COUNT(SR.AcademicId)=0 THEN CASE WHEN (Select [sCommon].[fCountAbsentStudent](A.DivisionId,  @rBatchId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-14')),@rAttendanceTypeId,0)) =0 THEN 'P' ELSE 'C' END ELSE 'C' END END  
			   
			FROM 	sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId AND SM.StatusId=1 
			INNER JOIN sSetup.vClassDivision vCD ON vCD.ClassId=A.ClassId AND vCD.OrgId=@rOrgId
            AND vCD.DivisionId=A.DivisionId AND A.OrgId=vCD.OrgId AND A.OrgId=@rOrgId AND A.BatchId=@rBatchId AND vCD.IsObsolete=0 
            INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vCD.DivisionId  AND  DM.OrgId=@rOrgId
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId AND ISNULL(EM.IsOtherUser,0) = 0
            LEFT JOIN sAttendance.tStudentRegister SR ON A.Id = SR.AcademicId 		
			AND SR.AttendanceDate=CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-14'))		
            AND SR.AttendanceTypeId = @rAttendanceTypeId	AND SR.IsPresent=1		
			WHERE A.ClassId=@rClassId		AND A.DivisionId=@rDivisionId 
            GROUP BY A.DivisionId,A.BatchId,vCD.ClassDivisionName,vCD.OrderIndex,EM.FirstName,EM.LastName,SM.StatusId,A.ClassId	) AS P14,

			(SELECT CASE WHEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,15,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) !='' THEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,15,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) ELSE CASE WHEN COUNT(SR.AcademicId)=0 THEN CASE WHEN (Select [sCommon].[fCountAbsentStudent](A.DivisionId,  @rBatchId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-15')),@rAttendanceTypeId,0)) =0 THEN 'P' ELSE 'C' END ELSE 'C' END END  
			   
			FROM 	sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId AND SM.StatusId=1 
			INNER JOIN sSetup.vClassDivision vCD ON vCD.ClassId=A.ClassId AND vCD.OrgId=@rOrgId
            AND vCD.DivisionId=A.DivisionId AND A.OrgId=vCD.OrgId AND A.OrgId=@rOrgId AND A.BatchId=@rBatchId AND vCD.IsObsolete=0 
            INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vCD.DivisionId  AND  DM.OrgId=@rOrgId
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId AND ISNULL(EM.IsOtherUser,0) = 0
            LEFT JOIN sAttendance.tStudentRegister SR ON A.Id = SR.AcademicId 		
			AND SR.AttendanceDate=CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-15'))		
            AND SR.AttendanceTypeId = @rAttendanceTypeId	AND SR.IsPresent=1		
			WHERE A.ClassId=@rClassId		AND A.DivisionId=@rDivisionId 
            GROUP BY A.DivisionId,A.BatchId,vCD.ClassDivisionName,vCD.OrderIndex,EM.FirstName,EM.LastName,SM.StatusId,A.ClassId	) AS P15,

			(SELECT CASE WHEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,16,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) !='' THEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,16,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) ELSE CASE WHEN COUNT(SR.AcademicId)=0 THEN CASE WHEN (Select [sCommon].[fCountAbsentStudent](A.DivisionId,  @rBatchId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-16')),@rAttendanceTypeId,0)) =0 THEN 'P' ELSE 'C' END ELSE 'C' END END  
			   
			FROM 	sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId AND SM.StatusId=1 
			INNER JOIN sSetup.vClassDivision vCD ON vCD.ClassId=A.ClassId AND vCD.OrgId=@rOrgId
            AND vCD.DivisionId=A.DivisionId AND A.OrgId=vCD.OrgId AND A.OrgId=@rOrgId AND A.BatchId=@rBatchId AND vCD.IsObsolete=0 
            INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vCD.DivisionId  AND  DM.OrgId=@rOrgId
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId AND ISNULL(EM.IsOtherUser,0) = 0
            LEFT JOIN sAttendance.tStudentRegister SR ON A.Id = SR.AcademicId 		
			AND SR.AttendanceDate=CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-16'))		
            AND SR.AttendanceTypeId = @rAttendanceTypeId	AND SR.IsPresent=1		
			WHERE A.ClassId=@rClassId		AND A.DivisionId=@rDivisionId 
            GROUP BY A.DivisionId,A.BatchId,vCD.ClassDivisionName,vCD.OrderIndex,EM.FirstName,EM.LastName,SM.StatusId,A.ClassId	) AS P16,

			(SELECT CASE WHEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,17,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) !='' THEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,17,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) ELSE CASE WHEN COUNT(SR.AcademicId)=0 THEN CASE WHEN (Select [sCommon].[fCountAbsentStudent](A.DivisionId,  @rBatchId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-17')),@rAttendanceTypeId,0)) =0 THEN 'P' ELSE 'C' END ELSE 'C' END END  
			   
			FROM 	sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId AND SM.StatusId=1 
			INNER JOIN sSetup.vClassDivision vCD ON vCD.ClassId=A.ClassId AND vCD.OrgId=@rOrgId
            AND vCD.DivisionId=A.DivisionId AND A.OrgId=vCD.OrgId AND A.OrgId=@rOrgId AND A.BatchId=@rBatchId AND vCD.IsObsolete=0 
            INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vCD.DivisionId  AND  DM.OrgId=@rOrgId
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId AND ISNULL(EM.IsOtherUser,0) = 0
            LEFT JOIN sAttendance.tStudentRegister SR ON A.Id = SR.AcademicId 		
			AND SR.AttendanceDate=CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-17'))		
            AND SR.AttendanceTypeId = @rAttendanceTypeId	AND SR.IsPresent=1		
			WHERE A.ClassId=@rClassId		AND A.DivisionId=@rDivisionId 
            GROUP BY A.DivisionId,A.BatchId,vCD.ClassDivisionName,vCD.OrderIndex,EM.FirstName,EM.LastName,SM.StatusId,A.ClassId	) AS P17,

			(SELECT CASE WHEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,18,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) !='' THEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,18,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) ELSE CASE WHEN COUNT(SR.AcademicId)=0 THEN CASE WHEN (Select [sCommon].[fCountAbsentStudent](A.DivisionId,  @rBatchId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-18')),@rAttendanceTypeId,0)) =0 THEN 'P' ELSE 'C' END ELSE 'C' END END  
			   
			FROM 	sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId AND SM.StatusId=1 
			INNER JOIN sSetup.vClassDivision vCD ON vCD.ClassId=A.ClassId AND vCD.OrgId=@rOrgId
            AND vCD.DivisionId=A.DivisionId AND A.OrgId=vCD.OrgId AND A.OrgId=@rOrgId AND A.BatchId=@rBatchId AND vCD.IsObsolete=0 
            INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vCD.DivisionId  AND  DM.OrgId=@rOrgId
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId AND ISNULL(EM.IsOtherUser,0) = 0
            LEFT JOIN sAttendance.tStudentRegister SR ON A.Id = SR.AcademicId 		
			AND SR.AttendanceDate=CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-18'))		
            AND SR.AttendanceTypeId = @rAttendanceTypeId	AND SR.IsPresent=1		
			WHERE A.ClassId=@rClassId		AND A.DivisionId=@rDivisionId 
            GROUP BY A.DivisionId,A.BatchId,vCD.ClassDivisionName,vCD.OrderIndex,EM.FirstName,EM.LastName,SM.StatusId,A.ClassId	) AS P18,

			(SELECT CASE WHEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,19,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) !='' THEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,19,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) ELSE CASE WHEN COUNT(SR.AcademicId)=0 THEN CASE WHEN (Select [sCommon].[fCountAbsentStudent](A.DivisionId,  @rBatchId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-19')),@rAttendanceTypeId,0)) =0 THEN 'P' ELSE 'C' END ELSE 'C' END END  
			   
			FROM 	sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId AND SM.StatusId=1 
			INNER JOIN sSetup.vClassDivision vCD ON vCD.ClassId=A.ClassId AND vCD.OrgId=@rOrgId
            AND vCD.DivisionId=A.DivisionId AND A.OrgId=vCD.OrgId AND A.OrgId=@rOrgId AND A.BatchId=@rBatchId AND vCD.IsObsolete=0 
            INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vCD.DivisionId  AND  DM.OrgId=@rOrgId
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId AND ISNULL(EM.IsOtherUser,0) = 0
            LEFT JOIN sAttendance.tStudentRegister SR ON A.Id = SR.AcademicId 		
			AND SR.AttendanceDate=CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-19'))		
            AND SR.AttendanceTypeId = @rAttendanceTypeId	AND SR.IsPresent=1		
			WHERE A.ClassId=@rClassId		AND A.DivisionId=@rDivisionId 
            GROUP BY A.DivisionId,A.BatchId,vCD.ClassDivisionName,vCD.OrderIndex,EM.FirstName,EM.LastName,SM.StatusId,A.ClassId	) AS P19,

			(SELECT CASE WHEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,20,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) !='' THEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,20,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) ELSE CASE WHEN COUNT(SR.AcademicId)=0 THEN CASE WHEN (Select [sCommon].[fCountAbsentStudent](A.DivisionId,  @rBatchId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-20')),@rAttendanceTypeId,0)) =0 THEN 'P' ELSE 'C' END ELSE 'C' END END  
			   
			FROM 	sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId AND SM.StatusId=1 
			INNER JOIN sSetup.vClassDivision vCD ON vCD.ClassId=A.ClassId AND vCD.OrgId=@rOrgId
            AND vCD.DivisionId=A.DivisionId AND A.OrgId=vCD.OrgId AND A.OrgId=@rOrgId AND A.BatchId=@rBatchId AND vCD.IsObsolete=0 
            INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vCD.DivisionId  AND  DM.OrgId=@rOrgId
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId AND ISNULL(EM.IsOtherUser,0) = 0
            LEFT JOIN sAttendance.tStudentRegister SR ON A.Id = SR.AcademicId 		
			AND SR.AttendanceDate=CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-20'))		
            AND SR.AttendanceTypeId = @rAttendanceTypeId	AND SR.IsPresent=1		
			WHERE A.ClassId=@rClassId		AND A.DivisionId=@rDivisionId 
            GROUP BY A.DivisionId,A.BatchId,vCD.ClassDivisionName,vCD.OrderIndex,EM.FirstName,EM.LastName,SM.StatusId,A.ClassId	) AS P20,

			(SELECT CASE WHEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,21,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) !='' THEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,21,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) ELSE CASE WHEN COUNT(SR.AcademicId)=0 THEN CASE WHEN (Select [sCommon].[fCountAbsentStudent](A.DivisionId,  @rBatchId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-21')),@rAttendanceTypeId,0)) =0 THEN 'P' ELSE 'C' END ELSE 'C' END END  
			   
			FROM 	sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId AND SM.StatusId=1 
			INNER JOIN sSetup.vClassDivision vCD ON vCD.ClassId=A.ClassId AND vCD.OrgId=@rOrgId
            AND vCD.DivisionId=A.DivisionId AND A.OrgId=vCD.OrgId AND A.OrgId=@rOrgId AND A.BatchId=@rBatchId AND vCD.IsObsolete=0 
            INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vCD.DivisionId  AND  DM.OrgId=@rOrgId
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId AND ISNULL(EM.IsOtherUser,0) = 0
            LEFT JOIN sAttendance.tStudentRegister SR ON A.Id = SR.AcademicId 		
			AND SR.AttendanceDate=CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-21'))		
            AND SR.AttendanceTypeId = @rAttendanceTypeId	AND SR.IsPresent=1		
			WHERE A.ClassId=@rClassId		AND A.DivisionId=@rDivisionId 
            GROUP BY A.DivisionId,A.BatchId,vCD.ClassDivisionName,vCD.OrderIndex,EM.FirstName,EM.LastName,SM.StatusId,A.ClassId	) AS P21,

				(SELECT CASE WHEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,22,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) !='' THEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,22,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) ELSE CASE WHEN COUNT(SR.AcademicId)=0 THEN CASE WHEN (Select [sCommon].[fCountAbsentStudent](A.DivisionId,  @rBatchId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-22')),@rAttendanceTypeId,0)) =0 THEN 'P' ELSE 'C' END ELSE 'C' END END  
			   
			FROM 	sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId AND SM.StatusId=1 
			INNER JOIN sSetup.vClassDivision vCD ON vCD.ClassId=A.ClassId AND vCD.OrgId=@rOrgId
            AND vCD.DivisionId=A.DivisionId AND A.OrgId=vCD.OrgId AND A.OrgId=@rOrgId AND A.BatchId=@rBatchId AND vCD.IsObsolete=0 
            INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vCD.DivisionId  AND  DM.OrgId=@rOrgId
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId AND ISNULL(EM.IsOtherUser,0) = 0
            LEFT JOIN sAttendance.tStudentRegister SR ON A.Id = SR.AcademicId 		
			AND SR.AttendanceDate=CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-22'))		
            AND SR.AttendanceTypeId = @rAttendanceTypeId	AND SR.IsPresent=1		
			WHERE A.ClassId=@rClassId		AND A.DivisionId=@rDivisionId 
            GROUP BY A.DivisionId,A.BatchId,vCD.ClassDivisionName,vCD.OrderIndex,EM.FirstName,EM.LastName,SM.StatusId,A.ClassId	) AS P22,


			(SELECT CASE WHEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,23,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) !='' THEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,23,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) ELSE CASE WHEN COUNT(SR.AcademicId)=0 THEN CASE WHEN (Select [sCommon].[fCountAbsentStudent](A.DivisionId,  @rBatchId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-23')),@rAttendanceTypeId,0)) =0 THEN 'P' ELSE 'C' END ELSE 'C' END END  
			   
			FROM 	sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId AND SM.StatusId=1 
			INNER JOIN sSetup.vClassDivision vCD ON vCD.ClassId=A.ClassId AND vCD.OrgId=@rOrgId
            AND vCD.DivisionId=A.DivisionId AND A.OrgId=vCD.OrgId AND A.OrgId=@rOrgId AND A.BatchId=@rBatchId AND vCD.IsObsolete=0 
            INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vCD.DivisionId  AND  DM.OrgId=@rOrgId
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId AND ISNULL(EM.IsOtherUser,0) = 0
            LEFT JOIN sAttendance.tStudentRegister SR ON A.Id = SR.AcademicId 		
			AND SR.AttendanceDate=CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-23'))		
            AND SR.AttendanceTypeId = @rAttendanceTypeId	AND SR.IsPresent=1		
			WHERE A.ClassId=@rClassId		AND A.DivisionId=@rDivisionId 
            GROUP BY A.DivisionId,A.BatchId,vCD.ClassDivisionName,vCD.OrderIndex,EM.FirstName,EM.LastName,SM.StatusId,A.ClassId	) AS P23,

			(SELECT CASE WHEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,24,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) !='' THEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,24,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) ELSE CASE WHEN COUNT(SR.AcademicId)=0 THEN CASE WHEN (Select [sCommon].[fCountAbsentStudent](A.DivisionId,  @rBatchId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-24')),@rAttendanceTypeId,0)) =0 THEN 'P' ELSE 'C' END ELSE 'C' END END  
			   
			FROM 	sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId AND SM.StatusId=1 
			INNER JOIN sSetup.vClassDivision vCD ON vCD.ClassId=A.ClassId AND vCD.OrgId=@rOrgId
            AND vCD.DivisionId=A.DivisionId AND A.OrgId=vCD.OrgId AND A.OrgId=@rOrgId AND A.BatchId=@rBatchId AND vCD.IsObsolete=0 
            INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vCD.DivisionId  AND  DM.OrgId=@rOrgId
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId AND ISNULL(EM.IsOtherUser,0) = 0
            LEFT JOIN sAttendance.tStudentRegister SR ON A.Id = SR.AcademicId 		
			AND SR.AttendanceDate=CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-24'))		
            AND SR.AttendanceTypeId = @rAttendanceTypeId	AND SR.IsPresent=1		
			WHERE A.ClassId=@rClassId		AND A.DivisionId=@rDivisionId 
            GROUP BY A.DivisionId,A.BatchId,vCD.ClassDivisionName,vCD.OrderIndex,EM.FirstName,EM.LastName,SM.StatusId,A.ClassId	) AS P24,

			(SELECT CASE WHEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,25,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) !='' THEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,25,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) ELSE CASE WHEN COUNT(SR.AcademicId)=0 THEN CASE WHEN (Select [sCommon].[fCountAbsentStudent](A.DivisionId,  @rBatchId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-25')),@rAttendanceTypeId,0)) =0 THEN 'P' ELSE 'C' END ELSE 'C' END END  
			   
			FROM 	sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId AND SM.StatusId=1 
			INNER JOIN sSetup.vClassDivision vCD ON vCD.ClassId=A.ClassId AND vCD.OrgId=@rOrgId
            AND vCD.DivisionId=A.DivisionId AND A.OrgId=vCD.OrgId AND A.OrgId=@rOrgId AND A.BatchId=@rBatchId AND vCD.IsObsolete=0 
            INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vCD.DivisionId  AND  DM.OrgId=@rOrgId
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId AND ISNULL(EM.IsOtherUser,0) = 0
            LEFT JOIN sAttendance.tStudentRegister SR ON A.Id = SR.AcademicId 		
			AND SR.AttendanceDate=CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-25'))		
            AND SR.AttendanceTypeId = @rAttendanceTypeId	AND SR.IsPresent=1		
			WHERE A.ClassId=@rClassId		AND A.DivisionId=@rDivisionId 
            GROUP BY A.DivisionId,A.BatchId,vCD.ClassDivisionName,vCD.OrderIndex,EM.FirstName,EM.LastName,SM.StatusId,A.ClassId	) AS P25,

			(SELECT CASE WHEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,26,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) !='' THEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,26,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) ELSE CASE WHEN COUNT(SR.AcademicId)=0 THEN CASE WHEN (Select [sCommon].[fCountAbsentStudent](A.DivisionId,  @rBatchId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-26')),@rAttendanceTypeId,0)) =0 THEN 'P' ELSE 'C' END ELSE 'C' END END  
			   
			FROM 	sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId AND SM.StatusId=1 
			INNER JOIN sSetup.vClassDivision vCD ON vCD.ClassId=A.ClassId AND vCD.OrgId=@rOrgId
            AND vCD.DivisionId=A.DivisionId AND A.OrgId=vCD.OrgId AND A.OrgId=@rOrgId AND A.BatchId=@rBatchId AND vCD.IsObsolete=0 
            INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vCD.DivisionId  AND  DM.OrgId=@rOrgId
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId AND ISNULL(EM.IsOtherUser,0) = 0
            LEFT JOIN sAttendance.tStudentRegister SR ON A.Id = SR.AcademicId 		
			AND SR.AttendanceDate=CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-26'))		
            AND SR.AttendanceTypeId = @rAttendanceTypeId	AND SR.IsPresent=1		
			WHERE A.ClassId=@rClassId		AND A.DivisionId=@rDivisionId 
            GROUP BY A.DivisionId,A.BatchId,vCD.ClassDivisionName,vCD.OrderIndex,EM.FirstName,EM.LastName,SM.StatusId,A.ClassId	) AS P26,

			(SELECT CASE WHEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,27,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) !='' THEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,27,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) ELSE CASE WHEN COUNT(SR.AcademicId)=0 THEN CASE WHEN (Select [sCommon].[fCountAbsentStudent](A.DivisionId,  @rBatchId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-27')),@rAttendanceTypeId,0)) =0 THEN 'P' ELSE 'C' END ELSE 'C' END END  
			   
			FROM 	sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId AND SM.StatusId=1 
			INNER JOIN sSetup.vClassDivision vCD ON vCD.ClassId=A.ClassId AND vCD.OrgId=@rOrgId
            AND vCD.DivisionId=A.DivisionId AND A.OrgId=vCD.OrgId AND A.OrgId=@rOrgId AND A.BatchId=@rBatchId AND vCD.IsObsolete=0 
            INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vCD.DivisionId  AND  DM.OrgId=@rOrgId
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId AND ISNULL(EM.IsOtherUser,0) = 0
            LEFT JOIN sAttendance.tStudentRegister SR ON A.Id = SR.AcademicId 		
			AND SR.AttendanceDate=CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-27'))		
            AND SR.AttendanceTypeId = @rAttendanceTypeId	AND SR.IsPresent=1		
			WHERE A.ClassId=@rClassId		AND A.DivisionId=@rDivisionId 
            GROUP BY A.DivisionId,A.BatchId,vCD.ClassDivisionName,vCD.OrderIndex,EM.FirstName,EM.LastName,SM.StatusId,A.ClassId	) AS P27,

			(SELECT CASE WHEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,28,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) !='' THEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,28,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) ELSE CASE WHEN COUNT(SR.AcademicId)=0 THEN CASE WHEN (Select [sCommon].[fCountAbsentStudent](A.DivisionId,  @rBatchId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-28')),@rAttendanceTypeId,0)) =0 THEN 'P' ELSE 'C' END ELSE 'C' END END  
			   
			FROM 	sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId AND SM.StatusId=1 
			INNER JOIN sSetup.vClassDivision vCD ON vCD.ClassId=A.ClassId AND vCD.OrgId=@rOrgId
            AND vCD.DivisionId=A.DivisionId AND A.OrgId=vCD.OrgId AND A.OrgId=@rOrgId AND A.BatchId=@rBatchId AND vCD.IsObsolete=0 
            INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vCD.DivisionId  AND  DM.OrgId=@rOrgId
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId AND ISNULL(EM.IsOtherUser,0) = 0
            LEFT JOIN sAttendance.tStudentRegister SR ON A.Id = SR.AcademicId 		
			AND SR.AttendanceDate=CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-28'))		
            AND SR.AttendanceTypeId = @rAttendanceTypeId	AND SR.IsPresent=1		
			WHERE A.ClassId=@rClassId		AND A.DivisionId=@rDivisionId 
            GROUP BY A.DivisionId,A.BatchId,vCD.ClassDivisionName,vCD.OrderIndex,EM.FirstName,EM.LastName,SM.StatusId,A.ClassId	) AS P28,

			CASE WHEN @rDayOfMonth >=29 THEN

			(SELECT CASE WHEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,29,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) !='' THEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,29,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) ELSE CASE WHEN COUNT(SR.AcademicId)=0 THEN CASE WHEN (Select [sCommon].[fCountAbsentStudent](A.DivisionId,  @rBatchId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-29')),@rAttendanceTypeId,0)) =0 THEN 'P' ELSE 'C' END ELSE 'C' END END  
			   
			FROM 	sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId AND SM.StatusId=1 
			INNER JOIN sSetup.vClassDivision vCD ON vCD.ClassId=A.ClassId AND vCD.OrgId=@rOrgId
            AND vCD.DivisionId=A.DivisionId AND A.OrgId=vCD.OrgId AND A.OrgId=@rOrgId AND A.BatchId=@rBatchId AND vCD.IsObsolete=0 
            INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vCD.DivisionId  AND  DM.OrgId=@rOrgId
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId AND ISNULL(EM.IsOtherUser,0) = 0
            LEFT JOIN sAttendance.tStudentRegister SR ON A.Id = SR.AcademicId 		
			AND SR.AttendanceDate=CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-29'))		
            AND SR.AttendanceTypeId = @rAttendanceTypeId	AND SR.IsPresent=1		
			WHERE A.ClassId=@rClassId		AND A.DivisionId=@rDivisionId 
            GROUP BY A.DivisionId,A.BatchId,vCD.ClassDivisionName,vCD.OrderIndex,EM.FirstName,EM.LastName,SM.StatusId,A.ClassId	) ELSE '' END AS P29,

			CASE WHEN @rDayOfMonth >=30 THEN

			(SELECT CASE WHEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,30,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) !='' THEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,30,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) ELSE CASE WHEN COUNT(SR.AcademicId)=0 THEN CASE WHEN (Select [sCommon].[fCountAbsentStudent](A.DivisionId,  @rBatchId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-30')),@rAttendanceTypeId,0)) =0 THEN 'P' ELSE 'C' END ELSE 'C' END END  
			   
			FROM 	sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId AND SM.StatusId=1 
			INNER JOIN sSetup.vClassDivision vCD ON vCD.ClassId=A.ClassId AND vCD.OrgId=@rOrgId
            AND vCD.DivisionId=A.DivisionId AND A.OrgId=vCD.OrgId AND A.OrgId=@rOrgId AND A.BatchId=@rBatchId AND vCD.IsObsolete=0 
            INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vCD.DivisionId  AND  DM.OrgId=@rOrgId
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId AND ISNULL(EM.IsOtherUser,0) = 0
            LEFT JOIN sAttendance.tStudentRegister SR ON A.Id = SR.AcademicId 		
			AND SR.AttendanceDate=CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-30'))		
            AND SR.AttendanceTypeId = @rAttendanceTypeId	AND SR.IsPresent=1		
			WHERE A.ClassId=@rClassId		AND A.DivisionId=@rDivisionId 
            GROUP BY A.DivisionId,A.BatchId,vCD.ClassDivisionName,vCD.OrderIndex,EM.FirstName,EM.LastName,SM.StatusId,A.ClassId	) ELSE '' END AS P30,


			CASE WHEN @rDayOfMonth =31 THEN

			(SELECT CASE WHEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,31,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) !='' THEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,31,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) ELSE CASE WHEN COUNT(SR.AcademicId)=0 THEN CASE WHEN (Select [sCommon].[fCountAbsentStudent](A.DivisionId,  @rBatchId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-31')),@rAttendanceTypeId,0)) =0 THEN 'P' ELSE 'C' END ELSE 'C' END END  
			   
			FROM 	sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId AND SM.StatusId=1 
			INNER JOIN sSetup.vClassDivision vCD ON vCD.ClassId=A.ClassId AND vCD.OrgId=@rOrgId
            AND vCD.DivisionId=A.DivisionId AND A.OrgId=vCD.OrgId AND A.OrgId=@rOrgId AND A.BatchId=@rBatchId AND vCD.IsObsolete=0 
            INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vCD.DivisionId  AND  DM.OrgId=@rOrgId
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId AND ISNULL(EM.IsOtherUser,0) = 0
            LEFT JOIN sAttendance.tStudentRegister SR ON A.Id = SR.AcademicId 		
			AND SR.AttendanceDate=CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-31'))		
            AND SR.AttendanceTypeId = @rAttendanceTypeId	AND SR.IsPresent=1		
			WHERE A.ClassId=@rClassId		AND A.DivisionId=@rDivisionId 
            GROUP BY A.DivisionId,A.BatchId,vCD.ClassDivisionName,vCD.OrderIndex,EM.FirstName,EM.LastName,SM.StatusId,A.ClassId	) ELSE '' END AS P31

			
		
			   
    FROM 
			sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId AND SM.StatusId=1 
			INNER JOIN sSetup.vClassDivision vCD ON vCD.ClassId=A.ClassId AND vCD.OrgId=@rOrgId
            AND vCD.DivisionId=A.DivisionId AND A.OrgId=vCD.OrgId AND A.OrgId=@rOrgId AND A.BatchId=@rBatchId AND vCD.IsObsolete=0 
            INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vCD.DivisionId  AND  DM.OrgId=@rOrgId
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId AND ISNULL(EM.IsOtherUser,0) = 0      
			WHERE A.ClassId=@rClassId	AND A.DivisionId=@rDivisionId 
            GROUP BY A.DivisionId,A.BatchId,vCD.ClassDivisionName,vCD.OrderIndex,EM.FirstName,EM.LastName,SM.StatusId,A.ClassId


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


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

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

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

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

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

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

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

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

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

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

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

		END
-- For Admission TypeId=1
ELSE IF(@rType='StatusClassWise')
		BEGIN
		
			SELECT CM.Id AS ClassId,CM.DisplayTitle AS ClassName,ISNULL(COUNT(AF.Id),0) AS StatusCount ,CM.OrderIndex 
			FROM sAdmission.tAdmissionForm AF 
			INNER JOIN sSetup.tClassMaster CM ON CM.Id = AF.ForClassId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AF.BatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
			INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
			INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			INNER JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AF.OrgId = OM.Id

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


				DECLARE @lSQLString nvarchar(max)=''

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

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

						print @lSQLString

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

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

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

						print @lSQLString1

						execute(@lSQLString1)
				END
			END

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

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


				DECLARE @lSQLStduentList nvarchar(max)=''

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

					--print @lSQLStduentList

					execute(@lSQLStduentList)

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

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

					print @lSQLStduentList1

						execute(@lSQLStduentList1)
			END
		END

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

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


				DECLARE @lSQLString3 nvarchar(max)=''

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

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

						print @lSQLString3

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

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

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

						print @lSQLString4

						execute(@lSQLString4)
				END
			END

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

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


				DECLARE @lSQLStduentList3 nvarchar(max)=''

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

					--print @lSQLStduentList

					execute(@lSQLStduentList3)

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

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

					print @lSQLStduentList4

						execute(@lSQLStduentList4)
			END
		END
	END
END
GO
PRINT N'Altering [sAdmission].[pAdmissionInquiryAdd]...';


GO

ALTER PROCEDURE [sAdmission].[pAdmissionInquiryAdd]
		 @rId bigint
		,@rFirstName nvarchar(100)
		,@rMiddleName nvarchar(100)
		,@rLastName nvarchar(100)
		,@rForClassId int
		,@rForBatchId	int =0
		--,@rForBatch	nvarchar(20)
		,@rDateOfBirth date
		,@rOrgId smallint
		--,@rStatusId	smallint
		,@rInquiryStatusMasterId int
		,@rStreetOne nvarchar(50)
		,@rStreetTwo nvarchar(50)
		,@rStreetThree nvarchar(50)
		,@rCountry nvarchar(50)
		,@rState nvarchar(50)
		,@rCity	nvarchar(50)
		,@rZipCode nvarchar(20)
		,@rContactNo nvarchar(20)
		,@rContactEmail	nvarchar(50)
		,@rRemark nvarchar(200)
		,@rInquiryModeId tinyint
		,@rInquiryReferenceId int
		,@rAdmissionCategoryId int
		,@rPreviousSchool nvarchar(200)
		,@rMeritMarks decimal(10,2) 
		,@rMeritGrade nvarchar(20)
		,@rMeritMarksBreakup nvarchar(100)
		,@rGenderId tinyint
		,@rFollowupDate date
		,@rFollowupRemark nvarchar(150)
		,@rCreatedUserId bigint
		,@rInquiryDate date
		,@rNumber bigint 
		,@rHandledBy nvarchar(100) 
		,@rOrgGroupId int,
		@rCastCategoryId int=0,
		@rIsHostelRequired bit=0,
		@rIsTransportRequired bit=0,
		@rIsValidateInquiryAsPerAdmission bit=0,
		@rIsGivenAdmissionForm bit=0,
		@rAlternateContactNo nvarchar(100)='',
		@rAlternateContactEmail	nvarchar(200) = '',
		@rMotherName nvarchar(100)='',
		@rDataEntryModeId smallint = 562 ,
		@rMinorityStatusId smallint = 0,
		@rLiveWithId smallint = 0,
		@rAdhaarNumber nvarchar(20)='',
		@rBloodGroupId smallint = 0,
		@rFatherName nvarchar(100)='',
		@rFatherOccupation nvarchar(50)='',
		@rFatherIncome int = 0,
		@rFatherContactNo nvarchar(50)='',
		@rFatherMail nvarchar(50)='',
		@rFatherQualification nvarchar(50)='',
	    @rMotherOccupation nvarchar(50)='',
		@rMotherIncome int=0,
		@rMotherContactNo nvarchar(50)='',
		@rMotherMail nvarchar(50)='',
		@rMotherQualification nvarchar(50)='',
		@rStream nvarchar(20)='',
		@rBoard nvarchar(50)=''
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	DECLARE @lOrgGroupBatchId int=0
	
	SELECT @lOrgGroupBatchId=OrgGroupBatchId FROM sSetup.tBatchMaster BM WHERE BM.Id = @rForBatchId
	
	DECLARE @lConfigValue nvarchar(50)=''
	SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 341 AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId
	 
	
	IF(@lConfigValue='OrgGroupBatch')
	BEGIN
		SELECT @rNumber = (ISNULL(MAX(Number),0) + 1) FROM sAdmission.tAdmissionInquiry AI
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForbatchId 
		WHERE BM.OrgGroupBatchId = @lOrgGroupBatchId
	END
	ELSE IF(@lConfigValue='Batch')
	BEGIN
		SELECT @rNumber = (ISNULL(MAX(Number),0) + 1) FROM sAdmission.tAdmissionInquiry AI
		WHERE AI.ForBatchId = @rForBatchId
	END
	ELSE IF (@lConfigValue = 'Continuous')
	BEGIN
		SELECT @rNumber =(ISNULL(MAX(Number),0) + 1) FROM sAdmission.tAdmissionInquiry  
		WHERE OrgGroupId = @rOrgGroupId
	END
	
	Declare @lStatusId smallint,@lIsValidateBirthdate bit,@lFromDateOfBirth date,@lToDateOfBirth date
	SET @lStatusId= 0
	
	if(@rIsValidateInquiryAsPerAdmission=1)
	Begin
		Select @lIsValidateBirthdate=IsValidateBirthdate,@lFromDateOfBirth=FromDateOfBirth,@lToDateOfBirth=ToDateOfBirth from  sAdmission.tAdmissionCriteria where ClassId=@rForClassId AND BatchID=@rForBatchId
		
		if(@lIsValidateBirthdate=1 AND @rDateOfBirth NOT between @lFromDateOfBirth And @lToDateOfBirth)
		BEGIN
			Select  -101 AS Result
			return
		End
	End
	 
 BEGIN TRANSACTION	
IF(@rId = 0)	
	BEGIN	

 DECLARE @lNextNumber BIGINT 
 EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAdmission.tAdmissionInquiry', 0, 1, 1,@outNextNumber = @lNextNumber output
			
	INSERT INTO sAdmission.tAdmissionInquiry
		(
			 Id
			,FirstName
			,MiddleName
			,LastName
			,ForClassId			 
			,ForBatchId
			,DateOfBirth
			,OrgId
			,StatusId
			,StreetOne
			,StreetTwo
			,StreetThree
			,Country
			,State
			,City
			,ZipCode
			,ContactNo
			,ContactEmail
			,Remark
			,InquiryModeId
			,InquiryReferenceId
			,AdmissionCategoryId
			,PreviousSchool
			,MeritMarks
			,MeritGrade
			,MeritMarksBreakup
			,GenderId
			,FollowupDate
			,FollowupRemark
			,CreatedUserId
			,CreatedDateTime
			,InquiryDate
			,Number
			,HandledBy
			,OrgGroupId
			,InquiryStatusId,
			CastCategoryId,
			IsHostelRequired,
			IsTransportRequired,
			IsGivenAdmissionForm,
			AlternateContactNo,
			AlternateContactEmail,
			MotherName,
			DataEntryModeId
			,MinorityStatusId 
		    ,LiveWithId
			,AdhaarNumber
			,BloodGroupId
			,FatherName
			,FatherOccupation
			,FatherIncome
			,FatherContactNo
			,FatherMail
			,FatherQualification
			,MotherOccupation
			,MotherIncome
			,MotherContactNo
			,MotherMail
			,MotherQualification
			,Stream
			,Board
		)
	VALUES
		(
			 @lNextNumber
			,@rFirstName
			,@rMiddleName
			,@rLastName
			,@rForClassId
			,@rForBatchId			 
			,@rDateOfBirth
			,@rOrgId
			,@lStatusId
			,@rStreetOne
			,@rStreetTwo
			,@rStreetThree
			,@rCountry
			,@rState
			,@rCity
			,@rZipCode
			,@rContactNo
			,@rContactEmail
			,@rRemark
			,@rInquiryModeId
			,@rInquiryReferenceId
			,@rAdmissionCategoryId
			,@rPreviousSchool
			,@rMeritMarks
			,@rMeritGrade
			,@rMeritMarksBreakup
			,@rGenderId
			,@rFollowupDate
			,@rFollowupRemark
			,@rCreatedUserId
			,sCommon.fGetDate()
			,@rInquiryDate
			,@rNumber
			,@rHandledBy
			,@rOrgGroupId
			,@rInquiryStatusMasterId,
			@rCastCategoryId,
			@rIsHostelRequired,
			@rIsTransportRequired,
			@rIsGivenAdmissionForm,
			@rAlternateContactNo,
			@rAlternateContactEmail,
			@rMotherName,
			@rDataEntryModeId,
			@rMinorityStatusId,
			@rLiveWithId,
			@rAdhaarNumber,
			@rBloodGroupId,
			@rFatherName,
			@rFatherOccupation,
			@rFatherIncome,
			@rFatherContactNo,
			@rFatherMail,
			@rFatherQualification,
			@rMotherOccupation,
			@rMotherIncome,
			@rMotherContactNo,
			@rMotherMail,
			@rMotherQualification,
			@rStream,
			@rBoard
		)
		    SELECT @lNextNumber AS Result         
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sAdmission.tAdmissionInquiry
	    SET
			 FirstName=@rFirstName
			,MiddleName=@rMiddleName
			,LastName=@rLastName
			,ForClassId=@rForClassId
			,ForBatchId = @rForBatchId		 
			,DateOfBirth=@rDateOfBirth
			,OrgId=@rOrgId
			,StatusId=@lStatusId
			,StreetOne=@rStreetOne
			,StreetTwo=@rStreetTwo
			,StreetThree=@rStreetThree
			,Country=@rCountry
			,State=@rState
			,City=@rCity
			,ZipCode=@rZipCode
			,ContactNo=@rContactNo
			,ContactEmail=@rContactEmail
			,Remark=@rRemark
			,InquiryModeId=@rInquiryModeId
			,InquiryReferenceId=@rInquiryReferenceId 
			,AdmissionCategoryId=@rAdmissionCategoryId
			,PreviousSchool=@rPreviousSchool
			,MeritMarks=@rMeritMarks
			,MeritGrade=@rMeritGrade
			,MeritMarksBreakup=@rMeritMarksBreakup
			,GenderId=@rGenderId
			,FollowupDate=@rFollowupDate
			,FollowupRemark=@rFollowupRemark
			,UpdatedUserId=@rCreatedUserId
			,UpdatedDateTime=sCommon.fGetDate()
			,InquiryDate=@rInquiryDate
			,HandledBy=@rHandledBy
			,InquiryStatusId = @rInquiryStatusMasterId,
			CastCategoryId = @rCastCategoryId,
			IsHostelRequired=@rIsHostelRequired,
			IsTransportRequired=@rIsTransportRequired,
			IsGivenAdmissionForm =@rIsGivenAdmissionForm,
			AlternateContactNo = @rAlternateContactNo,
			AlternateContactEmail = @rAlternateContactEmail,
			MotherName = @rMotherName,
			DataEntryModeId = @rDataEntryModeId ,
			MinorityStatusId  = @rMinorityStatusId , 
			LiveWithId = @rLiveWithId ,
			AdhaarNumber = @rAdhaarNumber ,
			BloodGroupId = @rBloodGroupId ,
			FatherName = @rFatherName,
			FatherOccupation =  @rFatherOccupation ,
			FatherIncome = @rFatherIncome ,
			FatherContactNo = @rFatherContactNo ,
			FatherMail = @rFatherMail ,
			FatherQualification =@rFatherQualification ,
			MotherOccupation = @rMotherOccupation ,
			MotherIncome = @rMotherIncome ,
			MotherContactNo =  @rMotherContactNo ,
			MotherMail = @rMotherMail ,
			MotherQualification = @rMotherQualification ,
			Stream = @rStream ,
			Board  =  @rBoard
		
		
	      WHERE Id = @rId 	   
	      SELECT @lNextNumber AS Result      
	      
	 END  
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
		SELECT ERROR_MESSAGE() AS ERROR
	END CATCH	
		
END
GO
PRINT N'Altering [sAdmission].[pAdmissionInquiryGet]...';


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

BEGIN 
	
	IF(@rIsGivenAdmissionForm=1)
		SET @rIsGivenAdmissionForm = 1
  	IF(@rIsGivenAdmissionForm=2)
		SET @rIsGivenAdmissionForm =0
	 
	 
	 SET @rToDate = DATEADD(d,1,@rToDate)
	 --IF @rIsSearch = 1
		BEGIN
			SET @rFirstName= sCommon.fSearchStringGet(@rFirstName)
			SET @rLastName= sCommon.fSearchStringGet(@rLastName)
			SET @rHandledBy= sCommon.fSearchStringGet(@rHandledBy)
			--SET @rContactNo= sCommon.fSearchStringGet(@rContactNo)
		END
	
	SELECT 
	
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			CASE WHEN @rAdmissionInquiryIdText = 0 THEN AI.Number ELSE @rAdmissionInquiryIdText END AS AdmissionInquiryIdText,
			 AI.Id
			,AI.ForBatchId
			,AI.ForClassId
			,AI.StatusId
			,ISNULL(SM.Id,0) AS InquiryStatusMasterId
			,ISNULL(AI.GenderId,0) AS GenderId
			,ISNULL(AI.InquiryModeId,0) AS InquiryModeId
			,ISNULL(IMM.Title,'') AS InquiryMode
			,ISNULL(AI.InquiryReferenceId,0) AS InquiryReferenceId		
		    ,ISNULL(AI.AdmissionCategoryId,0) AS AdmissionCategoryId
		    ,AI.OrgId
		    ,ISNULL(AI.Number,0) AS InquiryNumber
		    ,ISNULL(AI.InquiryDate,'') AS AdmissionInquiryDate 		    
		    ,OM.DisplayTitle AS OrgName
		    ,BM.Title AS ForBatch
			,ISNULL(CM.Title,'') AS ClassName	
			,AI.FirstName
			,AI.MiddleName
			,AI.LastName
			,[sStudent].[fStudentNameGet](AI.FirstName , ISNULL(AI.MiddleName,'') , AI.LastName,OM.StudentNameFormatId ) AS StudentName
			,AI.LastName +' ' +AI.FirstName+' '+AI.MiddleName as Name				
			,ISNULL(AI.DateOfBirth,'') As DateOfBirth
			,ISNULL(GM.Title,'') As Gender			
			,AI.ContactNo
			,AI.ContactEmail			
			,AI.StreetOne
			,AI.StreetTwo
			,AI.StreetThree
			,AI.Country
			,AI.State
			,AI.City
			,AI.ZipCode
			,ISNULL(AI.Remark,'') AS Remark						
		    ,ISNULL(AI.PreviousSchool,'') as PreviousSchool			
			,ISNULL(AI.MeritMarks,0) AS MeritMarks
			,ISNULL(AI.MeritGrade,'') AS MeritGrade
			,ISNULL(AI.MeritMarksBreakup,'') AS MeritMarksBreakup
			,SM.Title as StatusName	
			--,cast(replace(FollowupDate,'/','-') as date) As FollowupDate
			,ISNULL(AI.FollowupDate,'') As FollowupDate
			,ISNULL(AI.FollowupRemark,'') As FollowupRemark			
			,ISNULL(IRM.Title ,'') AS InquiryReference	
			,ISNULL(SCM.Title,'') AS AdmissionCategory		
			,ISNULL(AI.HandledBy,'') AS HandledBy
			,ISNULL(AI.CreatedDateTime,'') As CreatedDateTime
			,ISNULL(AI.StudentId,0) AS StudentId,
			ISNULL(AI.CastCategoryId,0) AS CastCategoryId,
			ISNULL(AI.IsTransportRequired,0) AS IsTransportRequired,
			ISNULL(AI.IsHostelRequired,0) AS IsHostelRequired,
			CONVERT(int,ISNULL(AI.IsGivenAdmissionForm,0)) AS IsGivenAdmissionForm,
			--ISNULL(AI.IsGivenAdmissionForm,0) AS IsGivenAdmissionForm,
			ISNULL(SM.HighlightColor,'') AS HighlightColor,
			ISNULL(SA.PreviousStandard,'') As PreviousStandard,
			AI.AlternateContactNo,
			AI.AlternateContactEmail
			,CASE WHEN AI.FollowupDate IS NULL THEN '' ELSE  CONVERT(VARCHAR(10), AI.FollowupDate, 103) END AS FollowupDateString,
			ISNULL(AIC.AgeCutOffDate,'') AS AgeCutOffDate,
			ISNULL(AI.MotherName,'') AS MotherName,
			CASE WHEN AI.DataEntryModeId = 561 THEN 'Online' ELSE 'Offline' END DataEntryMode 
			,ISNULL(AI.MinorityStatusId,0) As MinorityStatusId
		    ,ISNULL(AI.LiveWithId,0) AS LiveWithId
			,ISNULL(AI.AdhaarNumber,'') AS AdhaarNumber 
			,ISNULL(AI.BloodGroupId,0) AS BloodGroupId
			 ,ISNULL(AI.FatherName,'') AS FatherName
			,ISNULL(AI.FatherOccupation,'') AS FatherOccupation 
			,ISNULL(AI.FatherIncome,0) AS FatherIncome 
			,ISNULL(AI.FatherContactNo,'') AS FatherContactNo
			,ISNULL(AI.FatherMail,'') AS FatherMail
			,ISNULL(AI.FatherQualification,'') AS FatherQualification
			,ISNULL(AI.MotherOccupation,'') As MotherOccupation
			,ISNULL(AI.MotherIncome,0) AS MotherIncome
			,ISNULL(AI.MotherContactNo,'') AS MotherContactNo 
			,ISNULL(AI.MotherMail,'') AS MotherMail 
			,ISNULL(AI.MotherQualification,'') AS  MotherQualification
			,ISNULL(AI.Stream,'') AS Stream
			,ISNULL(AI.Board,'') AS Board
  FROM 
            sAdmission.tAdmissionInquiry AI
            LEFT JOIN sAdmission.tInquiryModeMaster IMM ON IMM.Id = AI.InquiryModeId
           --INNER JOIN sCommon.tStatusMaster SM ON SM.Id=AI.StatusId AND StatusTypeId=104
            INNER JOIN sAdmission.tInquiryStatusMaster SM ON SM.Id=AI.InquiryStatusId 
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=AI.ForClassId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=AI.OrgId
			INNER JOIN sSetup.tBatchMaster BM ON AI.ForBatchId = BM.Id
			LEFT JOIN sAdmission.tInquiryReferenceMaster IRM ON IRM.Id=AI.InquiryReferenceId
			LEFT JOIN sStudent.tAdmissionCategoryMaster SCM ON SCM.Id=AI.AdmissionCategoryId
			LEFT JOIN sCommon.tGenderMaster GM ON GM.Id=AI.GenderId  
			LEFT JOIN sStudent.tStudentAdmission SA oN SA.StudentId=AI.StudentID
			LEFT JOIN sAdmission.tAdmissionInquiryCriteria AIC ON AIC.ClassId=AI.ForClassId AND AIC.BatchId=AI.ForBatchId
  WHERE  
      ((AI.Id = @rId) OR (@rId = 0))
      AND ((AI.FirstName like @rFirstName) OR (@rFirstName=''))
      AND ((AI.LastName like @rLastName) OR (@rLastName=''))
      AND ((AI.InquiryDate>= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
      AND ((AI.InquiryDate < @rToDate) OR (ISNULL(@rToDate,'')=''))
	  AND ((AI.ForClassId=@rForClassId) OR (@rForClassId=0)) 
	  --AND ((AI.StatusId=@rStatusId) OR (@rStatusId=0))
	  AND ((SM.Id=@rInquiryStatusMasterId) OR (@rInquiryStatusMasterId=0))
	  AND (AI.OrgId=@rOrgId OR @rOrgId=0)
	  AND ((AI.ForBatchId=@rForBatchId) OR (@rForBatchId=0))
	  AND ((CM.DepartmentId=@rDepartmentId) or (@rDepartmentId = 0))
	  AND ((AI.MeritMarks >= @rFromMeritMarks) OR (@rFromMeritMarks=0))
	  AND ((AI.MeritMarks <= @rToMeritMarks) OR (@rToMeritMarks=0))
	  AND ((AI.InquiryModeId=@rInquiryModeId) OR (@rInquiryModeId=0))
	  AND ((AI.InquiryReferenceId=@rInquiryReferenceId) OR (@rInquiryReferenceId=0))
	  AND ((AI.Number=@rNumber) OR (@rNumber=0))
	  AND (BM.OrgGroupBatchid=@rOrgGroupBatchId OR @rOrgGroupBatchId=0)
	  AND ((AI.FollowUpdate=@rFollowupdate) OR (ISNULL(@rFollowUpdate,'')=''))
	  
	  AND ((ISNULL(AI.IsGivenAdmissionForm,0)=@rIsGivenAdmissionForm) OR (@rIsGivenAdmissionForm=0)OR (@rIsGivenAdmissionForm=-1))

	  AND (AI.IsTransportRequired = CASE @rIsTransportRequired
                              WHEN 0 THEN ISNULL(AI.IsTransportRequired,0)
                              WHEN 2 THEN 0
                              WHEN 1 THEN 1
                         END)
	  
	  AND (AI.IsHostelRequired = CASE @rIsHostelRequired
                              WHEN 0 THEN ISNULL(AI.IsHostelRequired,0)
                              WHEN 2 THEN 0
                              WHEN 1 THEN 1
                         END)
	 --AND ((ISNULL(AI.IsGivenAdmissionForm,0)=@rIsGivenAdmissionForm) OR (@rIsGivenAdmissionForm=-1))
      --AND (AI.IsGivenAdmissionForm = CASE @rIsGivenAdmissionForm WHEN 0 THEN ISNULL(AI.IsGivenAdmissionForm,0) WHEN 2 THEN 1 WHEN 1 THEN 0 END)
	 AND ((AI.ContactNo = @rContactNo) OR (@rContactNo=''))
	 AND ((AI.HandledBy like @rHandledBy) OR (@rHandledBy=''))
	 AND ((GM.Id = @rGenderId) OR (@rGenderId = 0))
	  --AND ((AI.IsTransportRequired=@rIsTransportRequired) OR (@rIsTransportRequired=0))	   
	    --AND ((AI.IsHostelRequired =@rIsHostelRequired) OR (@rIsHostelRequired=0))
	  Order by Case @rOrderBy When 1 then AI.MeritMarks END desc ,
			    Case @rOrderBy when 0 then AI.Number Else 
			    AI.Number END desc  
			    
END
GO
PRINT N'Altering [sAdmission].[pRptAdmissionFormGet]...';


GO

ALTER PROCEDURE [sAdmission].[pRptAdmissionFormGet]
 
	
	@rId bigint = 0,
	@rRelationShipId int=0,
	@rClassId int = 0,	 	
	@rFromDate date = '',
	@rToDate date = '',
	@rOrgId int = 0,
	@rDepartmentId int = 0,
	@rFromMeritMarks int = 0,
	@rToMeritMarks int = 0,
	@rBatchId int = 0

AS
 SET NOCOUNT ON

BEGIN 
	
	select 
	 Convert(nvarchar(20),AF.Id) AS AdmissionFormIdText,
	 Convert(nvarchar(20),@rRelationShipId) AS RelationShipIdText,
	 ISNULL(AF.Id,0) AS AdmissionFromId,
	 ISNULL(AF.FormNo,0) AS FormNo,
	 [sStudent].[fStudentNameGet](AF.FirstName , ISNULL(AF.MiddleName,'') , AF.LastName,OM.StudentNameFormatId ) AS Name,
	 ISNULL(AF.FirstName,'')AS FirstName,
	 ISNULL(AF.ForClassId,0) AS ForClassId,
	 ISNULL(AF.DateOfBirth,'') AS DateOfBirth,
	 ISNULL(AF.BatchId,0)AS BatchId,
	 ISNULL(CM.Title,'') AS ClassName,
	 ISNULL(AF.OrgId,0)AS OrgId,
	 ISNULL(AF.StreetOne,'')AS StreetOne,
	 ISNULL(AF.StreetTwo,'')AS StreetTwo,
	 ISNULL(AF.StreetThree,'')AS StreetThree,
	 ISNULL(AF.Country,'')AS Country,
	 ISNULL(AF.City,'')AS City,
	 ISNULL(AF.State,'')AS State,
	 ISNULL(AF.ZipCode,'') AS ZipCode,
	 ISNULL(AF.ContactEmail,'')AS ContactEmail,
	 ISNULL(AF.ContactNo,'') AS ContactNo,
	 ISNULL(AF.PreviousSchool,'')AS PreviousSchool,
	 ISNULL(AF.StudentPhoto,0x) As StudentPhoto,
	 ISNULL(AF.ReligionId,0) AS ReligionId,
	 IsNULL(RM.Title,'') AS ReligionName,
	 ISNULL(AF.MeritGrade,'')AS MeritGrade,
	 ISNULL(AF.MeritMarks,0) AS MeritMarks,
	 ISNULL(AF.GenderId,0) AS GenderId,
	 ISNULL(GM.Title,'') AS Gender,
	 ISNULL(AF.FamilyCast,'')AS FamilyCast,
	 ISNULL(AF.FamilySubCast,'')AS FamilySubCast,
	 ISNULL(AF.CastCategoryId,0) AS CastCategoryId,
	 ISNULL(CCM.Title,'') AS CastCategory ,
	 ISNULL(OM.DisplayTitle,'')AS DisplayTitle ,
	 ISNULL(BM.Title,'') As Batch,
	 ISNULL(AFM.FatherName,'') AS FatherName ,
	 ISNULL(AFM.FatherDateOfBirth,'')As FatherDateOfBirth,
	 ISNULL(AFM.FatherOccupation,'') AS FatherOccupation,
	 ISNULL(AFM.FatherOfficeAddress,'') AS FatherOfficeAddress,
	 ISNULL(AFM.FatherIncome,0) AS FatherIncome,
	 ISNULL(AFM.FatherQualification,'') AS FatherQualification,
	 ISNULL(AFM.FatherContactNo,'') AS FatherContactNo ,
	 ISNULL(AFM.FatherMail,'') AS FatherMail,
	 ISNULL(AFM.FatherOrganization,'') AS FatherOrganization,
	 ISNULL(AFM.MotherName,'') AS MotherName,
	 IsNull(AFM.MotherDateOfBirth,'')As MotherDateOfBirth,
	 ISNULL(AFM.MotherIncome,0) AS MotherIncome,
	 ISNULL(AFM.MotherOccupation,'') AS MotherOccupation,
	 ISNULL(AFM.MotherOfficeAddress,'') AS MotherOfficeAddress,
	 ISNULL(AFM.MotherQualification,'') AS MotherQualification,
	 ISNULL(AFM.MotherContactNo,'') AS MotherContactNo,
	 ISNULL(AFM.MotherMail,'') AS MotherMail,
	 ISNULL(AFM.MotherOrganization,'') AS MotherOrganization,
	 isnull(AFM.RelativeName,'') AS RelativeName ,
	 ISNULL(AFM.RelativeDateOfBirth,'') AS RelativeDateOfBirth,
	 ISNULL(AFM.RelativeOccupation,'') AS RelativeOccupation,
	 ISNULL(AFM.RelativeContactNo,'') AS RelativeContactNo,
	 ISNULL(AFM.RelativeMail,'') AS RelativeMail,
	 ISNULL(AFM.RelativeOfficeAddress,'') AS RelativeOfficeAddress,
	 ISNULL(AFM.RelativeIncome,0) AS RelativeIncome,
	 ISNULL(AFM.RelativeQualification,'') AS RelativeQualification,
	 ISNULL(AFM.RelationshipName,'') AS RelationshipName ,
	 ISNULL(AC.IsFixParentAcademic,0) AS IsParentAcademicRequired ,
	 ISNULL (AC.IsStudentAcademicRequired,0) AS IsStudentAcademicRequired ,
	 ISNULL(AC.IsSiblingDetailRequired,0) AS IsSiblingDetailRequired,
	 ISNULL(AC.IsReferenceDetailRequired,0) AS IsReferenceDetailRequired ,
	 ISNULL(AC.IsFamilyDetailRequired,0) AS IsFamilyDetailRequired ,
	 ISNULL(AC.IsFixStudentAcademic,0) AS IsFixStudentAcademic,
	 ISNULL(AC.ConfirmationRemark,'') AS ConfirmationRemark,
	 ISNULL(AC.IsHostelDetailRequired,0) AS IsHostelDetailRequired ,
	 ISNULL (AC.IsTransportDetailRequired,0) AS IsTransportDetailRequired ,
	 ISNULL(AC.IsHealthDetailRequired,0) AS IsHealthDetailRequired,
	 ISNULL(AC.IsBirthPlaceDetailRequired,0) AS IsBirthPlaceDetailRequired ,
	 ISNULL(AC.IsAadhaarDetailRequired,0) AS IsAadhaarDetailRequired ,
	 ISNULL(AC.IsBloodGroupDetailRequired,0) AS IsBloodGroupDetailRequired,
	
	 ISNULL(AF.IsPysicalDeformity,0) AS IsPysicalDeformity,
	 ISNULL(AF.PysicalDeformityRemark,'') AS PysicalDeformityRemark,
	 ISNULL(AF.IsMajorIllness,0) AS IsMajorIllness,
	 ISNULL(AF.MajorIllnessRemark, '') As MajorIllnessRemark,
	 ISNULL(AF.IsAllergy,0)AS IsAllergy,
	 ISNULL(AF.AllergyRemark,'') As AllergyRemark,
	 ISNULL(AF.BirthPlace,'') As BirthPlace,
	 ISNULL(AF.BirthTaluka,'') As BirthTaluka,
	 ISNULL(AF.BirthDistrict,'') As BirthDistrict,
	 Isnull(BGM.Title,'') As BloodGroupName,
	 ISNULL(AF.AdhaarNumber,'') AS AdhaarNumber,
	 ISNULL(AF.IsHostelRequired,0)AS IsHostelRequired,
	 ISNULL(AF.IsTransportRequired,0)AS IsTransportRequired,
	 ISNULL(AFM.FatherPhoto,0x)As FatherPhoto,
	  ISNULL(AFM.MotherPhoto,0x) As MotherPhoto,
	 ISNULL(AFM.RelativePhoto,0x) As RelativePhoto,
	 ISNULL(AF.BirthState,'')AS BirthState,
	 ISNULL(AF.BirthCountry,'') AS BirthCountry,
	 ISNULL(AC.CustomField1Remark,'') AS CustomField1Remark,
	 ISNULL(AC.CustomField2Remark,'') AS CustomField2Remark,
	 ISNULL(AC.CustomField3Remark,'') AS CustomField3Remark,
	 ISNULL(AF.CustomField1Answer,'')As CustomField1Answer,
	 ISNULL(AF.CustomField2Answer,'')As CustomField2Answer,
	 ISNULL(AF.CustomField3Answer,'')As CustomField3Answer,
	 ISNULL(AF.Nationality,'') AS Nationality,
	 ISNULL(AF.MotherTongue,'') AS MotherTongue,
	 ISNULL(AF.OtherInformation,'') AS OtherInformation,
	 ISNULL(LWM.Title,'') AS LiveWith,
	 ISNULL(AC.AgeCutOffDate,'') AS AgeCutOffDate,
	 ISNULL(AC.Remark1,'') AS ExtraRemark1,
	 ISNULL(AC.Remark2,'') AS ExtraRemark2,
	 ISNULL(AC.Remark3,'') AS ExtraRemark3,
	 ISNULL(AF.DateOfBirthInWord,'') AS DOBInWords,
	 ISNULL(AF.CreatedDateTime,'') As FormDate,
	  ISNULL(AC.IsFatherDetail,0) AS IsFatherDetail,
	 ISNULL(AC.IsFatherFullDetail,0) AS IsFatherFullDetail,
	 ISNULL (AC.IsFatherAcademic,0) As IsFatherAcademic,
	 ISNULL (AC.IsMotherDetail,0) As IsMotherDetail,
	 ISNULL (AC.IsMotherFullDetail,0)As IsMotherFullDetail,
	 ISNULL (AC.IsMotherAcademic,0)As IsMotherAcademic,
	 ISNULL (AC.IsGuardianDetail,0)As IsGuardianDetail,
	 ISNULL (AC.IsGuardianFullDetail,0)As IsGuardianFullDetail,
	 ISNULL (AC.IsGuardianAcademic,0)As IsGuardianAcademic,
	 ISNULL (AC.IsOtherInformationRequired,0)As IsOtherInformationRequired,
	 ISNULL (AC.IsHealthDetailRequired,0) As IsHealthDetailRequired,
	 ISNULL (AC.IsCustomField1Required,0) As IsCustomField1Required,
	 ISNULL (AC.IsCustomField2Required,0) As IsCustomField2Required,
	 ISNULL (AC.IsCustomField3Required,0) As IsCustomField3Required,
	 ISNULL (AFM.FatherAdhaarNumber,'') AS FatherAadhaarNumber,
	 ISNULL (AFM.MotherAadhaarNumber,'') AS MotherAadhaarNumber,
	 ISNULL (AFM.RelativeAadhaarNumber,'') AS RelativeAadhaarNumber,
	 ISNULL( (SELECT (CASE WHEN DFO.DisplayFieldId Is Null THEN 0  ELSE 1 END) 
	 FROM sConfig.tDisplayFieldMaster DFM LEFT JOIN sConfig.tDisplayFieldOrg DFO ON 
	 DFO.DisplayFieldId = DFM.Id AND DFO.OrgId =AF.OrgId AND DFO.OrgId=AF.OrgId
	 WHERE DFM.Id=324
	 ),0)AS IsOtherDetailsLiveWith,
	 ISNULL( (SELECT (CASE WHEN DFO.DisplayFieldId Is Null THEN 0  ELSE 1 END) 
	 FROM sConfig.tDisplayFieldMaster DFM LEFT JOIN sConfig.tDisplayFieldOrg DFO ON 
	 DFO.DisplayFieldId = DFM.Id AND DFO.OrgId =AF.OrgId AND DFO.OrgId=AF.OrgId
	 WHERE DFM.Id=323
	 ),0)AS IsOtherDetailsOtherInformation,
	 ISNULL(AF.MiddleName,'') AS MiddleName,
	 ISNULL(AF.LastName,'')AS LastName,
	 ISNULL(PT.Id,0) AS PaymentTransactionId,
	 ISNULL(PT.PayAmount,0.00) AS PayAmount,
	 ISNULL(PT.TransactionStatusId,0) AS TransactionStatusId,
	 ISNULL(PT.PayDateTime,'') AS PayDateTime,
	 ISNULL(AFM.IsFatherExStudent,0) AS IsFatherExStudent,
	 ISNULL(AFM.IsMotherExStudent,0) AS IsMotherExStudent,
	 ISNULL(AFM.IsRelativeExStudent,0)AS IsRelativeExStudent,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](302,OM.Id) AS IsBirthPlace,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](303,OM.Id) AS IsBirthTaluka,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](304,OM.Id) AS IsBirthDistrict,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](305,OM.Id) AS IsBirthState,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](306,OM.Id) AS IsBirthCountry,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](307,OM.Id) AS IsPreviousSchool,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](308,OM.Id) AS IsStudentPhoto,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](316,OM.Id) AS IsContactEmail,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](317,OM.Id) AS IsReligion,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](318,OM.Id) AS IsFamilyCaste,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](319,OM.Id) AS IsNationality,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](320,OM.Id) AS IsCasteCategory,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](388,OM.Id) AS IsFamilySubCaste,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](321,OM.Id) AS IsMotherTongue,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](322,OM.Id) AS IsAadhaarNo,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](323,OM.Id) AS IsOtherInformation,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](324,OM.Id) AS IsLiveWith,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](325,OM.Id) AS IsHotelRequired,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](326,OM.Id) AS IsTransportRequired,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](327,OM.Id) AS IsMotherFullName,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](328,OM.Id) AS IsMotherMobilNo,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](329,OM.Id) AS IsMotherQualification,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](330,OM.Id) AS IsMotherOccupation,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](331,OM.Id) AS IsMotherEmail,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](332,OM.Id) AS IsMotherIncome,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](333,OM.Id) AS IsMotherOrganization,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](334,OM.Id) AS IsMotherDesignation,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](337,OM.Id) AS IsMotherOfficeAddress,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](338,OM.Id) AS IsMotherPhoto,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](410,OM.Id) AS IsMotherAadhaarNo,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](349,OM.Id) AS IsFatherFullName,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](350,OM.Id) AS IsFatherMobileNo,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](351,OM.Id) AS IsFatherQualification,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](352,OM.Id) AS IsFatherOccupation,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](353,OM.Id) AS IsFatherEmail,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](354,OM.Id) AS IsFatherIncome,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](355,OM.Id) AS IsFatherOrganization,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](356,OM.Id) AS IsFatherDesignation,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](359,OM.Id) AS IsFatherOfficeAddress,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](360,OM.Id) AS IsFatherPhoto,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](409,OM.Id) AS IsFatherAadhaarNo,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](361,OM.Id) AS IsGuardianFullName,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](362,OM.Id) AS IsGuardianMobileNo,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](363,OM.Id) AS IsGuardianPhoto,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](396,OM.Id) AS IsGuardianQualification,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](397,OM.Id) AS IsGuardianOccupation,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](398,OM.Id) AS IsGuardianEmail,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](399,OM.Id) AS IsGuardianIncome,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](400,OM.Id) AS IsGuardianOrganization,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](401,OM.Id) AS IsGuardianDesignation,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](403,OM.Id) AS IsGuardianRelationship,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](405,OM.Id) AS IsGuardianOfficeAddress,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](411,OM.Id) AS IsGuardianAadhaarNo,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](369,OM.Id) AS IsPhysicalDeformity,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](370,OM.Id) AS IsPhysicalDeformityRemark,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](371,OM.Id) AS IsMajorIllness,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](372,OM.Id) AS IsMajorIllnessRemark,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](373,OM.Id) AS IsAllergy,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](374,OM.Id) AS IsAllergyRemark,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](407,OM.Id) AS IsMeritMarks,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](408,OM.Id) AS IsMeritGrade,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](395,OM.Id) AS IsBloodGroup,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](309,OM.Id) AS IsStreetOneAddress ,

	  ISNULL(AFM.FatherDesignation,'') AS FatherDesignation ,
	  ISNULL(AFM.FatherPassOutYear,'') AS FatherPassOutYear ,
	  ISNULL(AFM.MotherDesignation,'') AS MotherDesignation ,
	  ISNULL(AFM.MotherPassOutYear,'') AS MotherPassOutYear

  FROM  
		    sAdmission.tAdmissionForm AF 
		     
			--INNER JOIN sCommon.tStatusMaster SM ON SM.Id=AF.StatusId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=AF.OrgId
			INNER JOIN sSetup.tBatchMaster BM  ON  BM.Id=AF.BatchId
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=AF.ForClassId
			LEFT JoIN sCommon.tReligionMaster RM ON RM.Id=AF.ReligionId
			LEFT JOIN sCommon.tGenderMaster GM ON GM.Id=AF.GenderId
			LEFT JOIN sCommon.tBloodGroupMaster BGM ON BGM.Id=AF.BloodGroupId
			--LEFT JOIN sAdmission.tAdmissionFormParentAcademic PA ON PA.AdmissionFormId=AF.Id
			--INNER JOIN sCommon.tRelationshipMaster RSM ON RSM.Id=PA.RelationshipId
			LEFT JOIN sCommon.tCastCategoryMaster CCM  ON CCM.Id=AF.CastCategoryId
			LEFT JOIN sAdmission.tAdmissionFormFamilyDetail AFM ON AFM.AdmissionFormId=AF.Id
			LEFT JOIN sCommon.tLiveWithMaster LWM ON LWM.Id = AFM.LiveWithId
			LEFT JOIN  sAdmission.tAdmissionCriteria AC ON AC.ClassId=CM.Id  AND AC.BatchId=AF.BatchId		
			LEFT JOIN sOp.tPaymentTransaction PT ON PT.PayerSourceId = AF.Id AND PT.PayerSourceTypeId = 2027 AND (PT.TransactionStatusId = 2 OR PT.TransactionStatusId = 4)
 WHERE 	
  (AF.Id = @rId OR @rId = 0)
  AND ((AF.ForClassId=@rClassId) OR (@rClassId=0))	
  AND ((AF.BatchId = @rBatchId) OR (@rBatchId = 0))
	AND ((CM.DepartmentId=@rDepartmentId) OR (@rDepartmentId = 0))
	AND ((AF.MeritMarks >= @rFromMeritMarks) OR (@rFromMeritMarks=0))
	AND ((AF.MeritMarks <= @rToMeritMarks) OR (@rToMeritMarks=0))		
	AND ((CONVERT(DATE,AF.CreatedDateTime) >= @rFromDate) OR (isnull(@rFromDate,'')=''))
	AND ((CONVERT(DATE,AF.CreatedDateTime) <= @rToDate) OR (isnull(@rToDate,'')=''))
 

				
END
GO
PRINT N'Altering [sAlert].[pAdmissionInquiryGet]...';


GO

ALTER PROCEDURE [sAlert].[pAdmissionInquiryGet]
	
	@rAdmissionInquiryId bigint,
	@rTemplate nvarchar(max),
	@rSubject nvarchar(100)=''
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	SELECT 
		AI.Id AS AdmissionInquiryId,
		AI.FirstName+' '+AI.MiddleName+' '+AI.LastName AS Name,
		AI.ContactNo AS MobileNo,	
		AI.ContactEmail AS EmailId,
		REPLACE (
		REPLACE (
		REPLACE (
		REPLACE(@rTemplate,'[Name]',AI.FirstName+' '+AI.MiddleName+' '+AI.LastName),
		'[Organization]',ISNULL(OM.DisplayTitle,'')),
		'[ForClass]',ISNULL(CM.Title,'')),
		'[InquiryFormNo]', ISNULL(AI.Number,0))
		AS MsgText,
		@rSubject AS [Subject],
		0 AS ReceiverSourceTypeId,
		0 AS ReceiverSourceId,
		ISNULL(OM.DisplayTitle,'') AS Organization,
		ISNULL(CM.Title,'') AS ForClass,
		AI.ContactNo AS WhatsAppContactNo,
		AI.OrgId,
		OM.OrgGroupId,
		CONVERT(bigint,0) AS SourceId,
		CONVERT(smallint,0) AS SourceTypeId
	FROM sAdmission.tAdmissionInquiry AI 
		INNER JOIN sSetup.tClassMaster CM ON CM.Id = AI.ForClassId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = AI.OrgId
	WHERE	
		AI.Id = @rAdmissionInquiryId
END
GO
PRINT N'Altering [sAlert].[pBusRouteGet]...';


GO
ALTER PROCEDURE [sAlert].[pBusRouteGet]
	 	 
	 	 @rBatchId int,
	 	 @rClassId int,
	 	 @rDivisionId int,
	 	 @rOrgId int,
	 	 @rTemplate nvarchar(max),
	 	 @rBusRouteId int,
	 	 @rOrgGroupBatchId int,
		 @rTransportId int=0,
		 @rPickupDropIds nvarchar(max) = ''
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	Select 
			SC.AcademicId,
			SC.Code,
			SC.Name,
			SC.ParentContactNo AS MobileNo,	
			SC.ParentEmail AS EmailId,
			ISNULL(SC.StudentContactNo,'') AS StudentContactNo,
			ISNULL(SC.StudentEmail,'') AS StudentEmail,
			ISNULL(SC.FatherContactNo,'') AS FatherContactNo,
			ISNULL(SC.FatherMail,'') AS FatherMail,
			ISNULL(SC.MotherContactNo,'') AS MotherContactNo,
			ISNULL(SC.MotherMail,'') AS MotherMail,
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace(@rTemplate,'[Name]',isnull(SC.Name,'')),
			'[Class]',isnull(SC.ClassName,'')),
			'[Division]',isnull(SC.DivisionName,'')),
			'[BusRoute]',isnull(BRM.Title,'')),
			'[PickupPoint]',isnull(BRDM.Title,'')),
			'[PickupTime]',isnull(BRDM.PickupTime,'')),
			'[DropTime]',isnull(BRDM.DropTime,''))
			 AS Template,
			 isnull(SC.ClassName,'') AS Class,
			 isnull(SC.DivisionName,'') AS Division,
			 isnull(BRM.Title,'') AS BusRoute,
			 isnull(BRDM.Title,'') AS PickupPoint,
			 isnull(BRDM.PickupTime,'') AS PickupTime,
			 isnull(BRDM.DropTime,'') AS DropTime,
			 SC.WhatsAppContactNo
		
	From 
		sStudent.vStudentCommunication SC
		INNER JOIN sTransport.tAssignRoute AR ON AR.SourceId=SC.StudentId AND AR.SourceTypeId=2003
		INNER JOIN sTransport.tBusRouteDestinationMaster BRDM ON BRDM.Id=AR.PickupDestinationId
				AND ((BRDM.BusRouteId=@rBusRouteId) OR (@rBusRouteId=0))
		INNER JOIN sTransport.tBusRouteMaster BRM ON BRM.Id=BRDM.BusRouteId AND BRM.OrgGroupBatchId = SC.OrgGroupBatchId 
	WHERE
		((SC.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SC.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((SC.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((SC.BatchId=@rBatchId) OR (@rBatchId=0))
		AND (BRM.OrgGroupBatchId=@rOrgGroupBatchId)
		AND (SC.StatusId=1)
		AND ((BRM.TransportId = @rTransportId) OR (ISNULL(@rTransportId,0) = 0))
		AND (BRDM.Id IN(SELECT cast(item as int) FROM  sCommon.fnsplit(@rPickupDropIds,',')) OR @rPickupDropIds='')

	UNION

	Select 
			SC.AcademicId,
			SC.Code,
			SC.Name,
			SC.ParentContactNo AS MobileNo,	
			SC.ParentEmail AS EmailId,
			ISNULL(SC.StudentContactNo,'') AS StudentContactNo,
			ISNULL(SC.StudentEmail,'') AS StudentEmail,
			ISNULL(SC.FatherContactNo,'') AS FatherContactNo,
			ISNULL(SC.FatherMail,'') AS FatherMail,
			ISNULL(SC.MotherContactNo,'') AS MotherContactNo,
			ISNULL(SC.MotherMail,'') AS MotherMail,
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace(@rTemplate,'[Name]',isnull(SC.Name,'')),
			'[Class]',isnull(SC.ClassName,'')),
			'[Division]',isnull(SC.DivisionName,'')),
			'[BusRoute]',isnull(BRM.Title,'')),
			'[PickupPoint]',isnull(BRDM.Title,'')),
			'[PickupTime]',isnull(BRDM.PickupTime,'')),
			'[DropTime]',isnull(BRDM.DropTime,''))
			 AS Template,
			 isnull(SC.ClassName,'') AS Class,
			 isnull(SC.DivisionName,'') AS Division,
			 isnull(BRM.Title,'') AS BusRoute,
			 isnull(BRDM.Title,'') AS PickupPoint,
			 isnull(BRDM.PickupTime,'') AS PickupTime,
			 isnull(BRDM.DropTime,'') AS DropTime,
			 SC.WhatsAppContactNo
		
	From 
		sStudent.vStudentCommunication SC
		INNER JOIN sTransport.tAssignRoute AR ON AR.SourceId=SC.StudentId AND AR.SourceTypeId=2003
		INNER JOIN sTransport.tBusRouteDestinationMaster BRDM ON BRDM.Id=AR.DropDestinationId
				AND ((BRDM.BusRouteId=@rBusRouteId) OR (@rBusRouteId=0))
		INNER JOIN sTransport.tBusRouteMaster BRM ON BRM.Id=BRDM.BusRouteId AND BRM.OrgGroupBatchId = SC.OrgGroupBatchId 
	WHERE
		((SC.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SC.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((SC.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((SC.BatchId=@rBatchId) OR (@rBatchId=0))
		AND (BRM.OrgGroupBatchId=@rOrgGroupBatchId)
		AND (SC.StatusId=1)
		AND ((BRM.TransportId = @rTransportId) OR (ISNULL(@rTransportId,0) = 0))
		AND (BRDM.Id IN(SELECT cast(item as int) FROM  sCommon.fnsplit(@rPickupDropIds,',')) OR @rPickupDropIds='')

END
GO
PRINT N'Altering [sAlert].[pEmployeeProxySettingGet]...';


GO
ALTER PROCEDURE [sAlert].[pEmployeeProxySettingGet]
	
	     		
	 	 @rProxySettingId int,
         @rTemplate nvarchar(max),
         @rSubject nvarchar(100)
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	SELECT 
		EM.MobileNumber AS MobileNo,	
		EM.CompanyEmail AS EmailId,
		replace (
		replace (
		replace (
		replace (
		replace(@rTemplate,'[EmployeeName]',EM.EmployeeName),
		'[ProxyDate]',PS.ProxyDate),
		'[PeriodNo]',PS.LectureNumber),
		'[Subject]',SM.Title),
		'[ClassDivision]',CM.Title +' - '+DM.Title)
		 AS MsgText,
		@rSubject AS Subject,
		95 AS ReceiverSourceTypeId,
		EM.EmployeeId AS ReceiverSourceId,
		EM.EmployeeName AS EmployeeName,
		PS.ProxyDate AS ProxyDate,
		PS.LectureNumber AS PeriodNo,
		SM.Title AS Subject,
		CM.Title +' - '+DM.Title AS ClassDivision,
		ISNULL(EC.WhatsAppContactNo,'') AS WhatsAppContactNo,
		95 AS SourceTypeId,
		EM.EmployeeId AS SourceId,
		EM.OrgId,
		OM.OrgGroupId


	FROM 
		sHrm.vEmployeeCommonDetail EM
		INNER JOIN sTimetable.tProxySetting PS ON PS.EmployeeId = EM.EmployeeId 
		INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = PS.SubjectId
		INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = PS.DivisionId
		INNER JOIN sSetup.tClassMaster CM ON CM.Id = DM.ClassId
		LEFT JOIN sHrm.tEmployeeCommunications EC ON EC.EmployeeId = EM.EmployeeId
		INNER JOIN sSetup.tOrganizationMaster OM ON EM.OrgID = OM.Id
	WHERE
		PS.Id = @rProxySettingId 
END
GO
PRINT N'Altering [sAlert].[pFeeDueGet]...';


GO

 
ALTER PROCEDURE [sAlert].[pFeeDueGet]

		 @rBatchId int,
	 	 @rClassId int,
	 	 @rDivisionId int,
	 	 @rOrgId int,
	 	 @rTemplate nvarchar(max),
	 	 @rReceiptBookId int,
	 	 @rToDate date,
	 	 @rMailSubject nvarchar(500)='',
	 	 @rAdmissionCategoryId int=0,
	 	 @rIdNos nvarchar(500)='',
		 @rDepartmentId int=0,
		 @rCollectionGroupId int=0
		
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	CREATE TABLE #TempOptional (
		Id int,
		Amount decimal(12,2),
		StartDate date,
		EndDate date,
		ReceiptBookId int,
		AcademicId bigint
	)
	
	CREATE TABLE #TempReceipt (
		PaidAmount decimal(12,2),
		FeeSetupId int,
		SourceId bigint
	)
	
	INSERT INTO #TempOptional
	SELECT 
				FS1.Id,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId
			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 
				((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))
				AND ((FS1.StartDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
				AND (SA1.Code IN (SELECT item from sCommon.fnSplit(@rIdNos, ',')) OR ISNULL(@rIdNos,'')='')
				AND ((SA1.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
				AND ((FS1.CollectionGroupId=@rCollectionGroupId) OR (@rCollectionGroupId=0))
			
			UNION ALL

			SELECT 
				FS1.Id,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId
			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
				((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))
				AND ((FS1.StartDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
				AND (SA1.Code IN (SELECT item from sCommon.fnSplit(@rIdNos, ',')) OR ISNULL(@rIdNos,'')='')
				AND ((SA1.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
				AND ((FS1.CollectionGroupId=@rCollectionGroupId) OR (@rCollectionGroupId=0))

	
	INSERT INTO #TempReceipt
	SELECT 
				ISNULL(SUM(RD.Amount),0) AS PaidAmount,
				RD.FeeSetupId,
				R.SourceId
			FROM
				sFee.tReceipt R 

				INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
				INNER JOIN sFee.tFeeSetup FS ON FS.Id = RD.FeeSetupId
				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 ((R.BatchId=@rBatchId) OR (@rBatchId=0))
				AND (SA1.Code IN (SELECT item from sCommon.fnSplit(@rIdNos, ',')) OR ISNULL(@rIdNos,'')='')
				AND ((SA1.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
				AND ((FS.CollectionGroupId=@rCollectionGroupId) OR (@rCollectionGroupId=0))
			GROUP BY 
				FeeSetupId,R.SourceId
	
	SELECT 
		D.AcademicId,
		D.RollNo,
		D.Name,
		D.Code,
		D.MobileNo,	
		D.EmailId,
		D.StudentContactNo,
		D.StudentEmail,
		D.FatherContactNo,
		D.FatherMail,
		D.MotherContactNo,
		D.MotherMail,
		SUM(D.PendingAmount) As PendingAmount,
		REPLACE (REPLACE(
		REPLACE(REPLACE(REPLACE(@rTemplate,'[Name]',D.Name),
		'[Class]',D.ClassName),
		'[Division]',D.DivisionName),
		'[PendingAmount]',CONVERT(int,(SUM(D.PendingAmount)))),
		'[Code]',D.Code)
		AS Template,
		REPLACE (REPLACE(
		REPLACE(REPLACE(REPLACE(@rTemplate,'[Name]',D.Name),
		'[Class]',D.ClassName),
		'[Division]',D.DivisionName),
		'[PendingAmount]',CONVERT(int,(SUM(D.PendingAmount)))),
		'[Code]',D.Code)
		AS MsgText,
		@rMailSubject AS [Subject],
		D.ClassName AS Class,
		D.DivisionName AS Division,				
		D.WhatsAppContactNo,
		D.AcademicId AS ReceiverSourceId,
		2001 AS ReceiverSourceTypeId,
		D.OrgId,
		D.OrgGroupId,
		D.AcademicId AS SourceId,
		'2001' AS SourceTypeId
	FROM
	(
	SELECT
		SA.AcademicId,
		SA.RollNo,
		SA.Name,
		SA.ClassName,
		SA.DivisionName,
		SA.Code,
		SC.ParentContactNo AS MobileNo,	
		SC.ParentEmail AS EmailId,
		ISNULL(SC.StudentContactNo,'') AS StudentContactNo,
		ISNULL(SC.StudentEmail,'') AS StudentEmail,
		ISNULL(SC.FatherContactNo,'') AS FatherContactNo,
		ISNULL(SC.FatherMail,'') AS FatherMail,
		ISNULL(SC.MotherContactNo,'') AS MotherContactNo,
		ISNULL(SC.MotherMail,'') AS MotherMail,
		SA.DivisionOrder,
		((ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00))-((ISNULL(FA.NotApplicableAmount,0.00) + ISNULL(FA.DiscountAmount,0.00)+ISNULL(R.PaidAmount,0.00))))  AS PendingAmount,
		SC.WhatsAppContactNo,
		SA.OrgId,
		o.OrgGroupId
	FROM 
		sStudent.vStudentAcademic SA
		INNER JOIN  #TempOptional FS ON FS.AcademicId=SA.AcademicId 
		LEFT JOIN sFee.tFeeAllocation FA
		ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
		LEFT JOIN #TempReceipt	R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
		INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
		INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
		LEFT JOIN  sStudent.vStudentCommunication SC ON SC.AcademicId = SA.AcademicId
	WHERE	
		SA.StatusId = 1 AND SC.IsBlockAllAlert=0 
		AND	((SA.BatchId=@rBatchId) OR (@rBatchId=0)) 
		AND ((FS.StartDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
		
		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.AdmissionCategoryId = @rAdmissionCategoryId OR @rAdmissionCategoryId=0)
		AND (SC.Code IN (SELECT item from sCommon.fnSplit(@rIdNos, ',')) OR ISNULL(@rIdNos,'')='')
		AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		
		) D
	GROUP BY 
		D.AcademicId,D.RollNo,D.Name,D.ClassName,D.DivisionName,D.Code,
		D.MobileNo,D.EmailId,D.StudentContactNo,D.StudentEmail,D.FatherContactNo,D.FatherMail,D.MotherContactNo,D.MotherMail,D.DivisionOrder,D.WhatsAppContactNo,D.OrgId,D.OrgGroupId
	ORDER BY 
		D.DivisionOrder,D.Rollno	

	DROP TABLE #TempOptional
	DROP TABLE #TempReceipt
END
GO
PRINT N'Altering [sAlert].[pVisitorGatePassGet]...';


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

	ELSE

	BEGIN
		SELECT 
				VL.Id,
				VL.VisitorName,
				VL.VisitorContactNumber AS MobileNo,
				EC.CompanyEmail AS EmailId,
				replace (
				replace (
				replace(@rTemplate,'[VisitorName]',VL.VisitorName),
				'[NoOfVisitors]',VL.NoOfVisitor),
				'[PurposeOfVisit]',VL.PurposeOfVisit)
				AS MsgText,
				@rSubject AS Subject,
				95 AS ReceiverSourceTypeId,
				EM.Id AS ReceiverSourceId,
				EM.Id AS SourceId,
				95 AS SourceTypeId,
				OM.OrgGroupId,
				VL.OrgId,
				VL.NoOfVisitor AS NoOfVisitors,
				VL.PurposeOfVisit AS PurposeOfVisit,
				ISNULL(EC.WhatsAppContactNo,'') AS WhatsAppContactNo
		FROM 
			sFrontOffice.tVisitorLog VL
			LEFT JOIN [sHrm].[tEmployeeMaster] EM ON VL.WhomToMeet=EM.Id
			LEFT JOIN [sHrm].[tEmployeeCommunications] EC ON EM.Id=EC.EmployeeId
			LEFT JOIN sSetup.tOrganizationMaster OM ON VL.OrgId = OM.Id	
		WHERE
			((VL.OrgId=@rOrgId) OR (@rOrgId=0))
			AND VL.Id = @rVisitorLogId
		END
END
GO
PRINT N'Altering [sAssessment].[pCCERptFirstTermResultGet]...';


GO
 
 


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

	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 


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

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

Select @CSGradeSetId =CSGradeSetId from sAssessment.tCCEExamSetting Where CCEExamId= @rCCEExamID
	 
	
SELECT @GradeString = [sAssessment].[fGradeStringGet](@GradeSetId)
Select @CSGradeString = [sAssessment].[fCSGradeStringGet](@CSGradeSetId)

BEGIN 
	SELECT 
		
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2
			,
			
			SM.Code,
			   [sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Name,
			ISNULL(SF.FatherName,'') AS FatherName,
			ISNULL(SF.MotherName,'')AS MotherName,
			A.RollNo,
			CCER.AcademicId,
			CONVERT(NVARCHAR,CCER.AcademicId) AS AcademicIdText,
			CONVERT(NVARCHAR,EM.Id)AS ExamIdText,
			Convert(Nvarchar,@rBatchId) As BatchIdText,
			CONVERT(NVARCHAR,@rCCEExamId) AS CCEExamIdText,
			
			Convert(nvarchar(20),EM.CoScholasticScopeId)AS CoScholasticScopeIdText,--added 
			 CONVERT (nvarchar(20),EM.GradeSetId) AS GradeSetIdText,
			 REPLICATE(',',EM.FooterAdjustment) AS FooterAdjustmentText,
		REPLICATE(',',EM.DetailAdjustment) AS DetailAdjustmentText,
		ED.IsIncludeInTotal,
	
	 
		
			ISNULL(SC.ParentContactNo,'') AS ContactNo,
			ISNULL(SC.PresentStreetONe,'')+' '+ISNULL(SC.PresentStreetTwo,'')+' '+ISNULL(SC.PresentStreetThree,'')+' '+ISNULL(SC.PresentCity,'')+' '+ISNULL(SC.PresentState,'') AS PresentAddress,
			--SO.DateOfBirth,
			CONVERT(VARCHAR(10),SO.DateOfBirth,103) AS DateOfBirth,
			CM.DisplayTitle AS Class,
			DM.DisplayTitle AS Division,
			ISNULL(HM.Title,'') AS House,
			ISNULL(CCERD.GradeFA1,'') AS GradeFA1,
			ISNULL(CCERD.GradeFA2,'') AS GradeFA2,
			ISNULL(CCERD.GradeFA3,'')AS GradeFA3,
			ISNULL(CCERD.GradeFA4,'') AS GradeFA4,
			ISNULL(CCERD.GradeSA1,'') AS GradeSA1,
			ISNULL(CCERD.GradeSA2,'') AS GradeSA2,
			ISNULL(CCERD.FAGrade,'') AS FAGrade,
			ISNULL(CCERD.SAGrade,'') AS SAGrade,
			ISNULL(CCERD.GradePoint,0) AS OverallGrade,
			ISNULL(CCERD.Grade,'') AS Grade,
			ISNULL(CCER.AttendanceTerm1,0) AS AttendanceTerm1,
			ISNULL(CCER.AttendanceTerm2,0) AS AttendanceTerm2,
			ISNULL(CCER.WorkingDaysTerm1,0) AS WorkingDaysTerm1,
			ISNULL(CCER.WorkingDaysTerm2,0) AS WorkingDaysTerm2,
			ISNULL(CCER.Height,0) AS Height,
			ISNULL(CCER.Weight,0) AS Weight,
			 
			SubM.Title As ClassSubject,
			SubM.OrderIndex AS SubjectOrderIndex,
			Subm.Code AS SubjectCode,
			CCERD.classSubjectId,
			Cs.isOptional,
			ISNULL(BGM.Title,'') AS BloodGroup,
			ISNULL(CCERD.Term1GradePoint,0) AS Term1GradePoint,
			ISNULL(CCERD.Term1Grade,'') AS Term1Grade,
			ISNULL(CCERD.Term2GradePoint,0) AS Term2GradePoint,
			ISNULL(CCERD.Term2Grade,'') AS Term2Grade,
			--ISNULL(SI.StudentPhoto,CONVERT(varbinary(max),SI.StudentPhoto,1)) AS StudentPhoto
			--SI.StudentPhoto AS StudentPhoto 
		--CASE WHEN ISNULL(IsResultStatus,0) = 0 THEN 'No' ELSE 'Yes' END AS IsDisplayResultStatus,
			CCERD.FA1,
			CCERD.FA2,
			CCERD.FA3,
			CCERD.FA4,
			CCERD.SA1,
			CCERD.SA2,
			CCERD.TERM1,
			CCERD.TERM2,
			CCERD.TOTAL,
			EM.IsOnPrePrinted,
			EM.IsDisplayBirthDate,
			EM.IsDisplayPhoto,
			EM.IsDisplaySchoolName,			
			EM.IsLockForEdit,
			EM.IsIncludeCoScholastic,
			EM.IsDisplayAttendance,
			EM.IsDisplayHeightWeight,
			EM.IsResultStatus,	
			EM.Remark1,
			EM.Remark2,
			EM.Remark3,
			EM.ExamSubGroupId,
 
			ESM.Code AS ExamSubGroupTitle,	
			EM.DisplayTitle,
			SI.StudentPhoto,
			ISNULL(EM.ExamMaximum,0) AS ExamMaximum,
			ISNULL(EM.FooterAdjustment,0) AS FooterAdjustment,
			ISNULL(EM.DetailAdjustment,0) AS DetailAdjustment,
			ISNULL(EM.TermScopeId,0) AS TermScopeId,	
			TSM.Title AS TermScopeTitle,
		ISNULL(EM.ReportId,0) as ReportId,
		@GradeString AS GradeString,
			A.BatchId,
			BM.Title,
			CS.OrderIndex AS ClassSubjectOrderIndex,
			ISNULL(SR.TotalDays,0)AS TotalDays,
		ISNULL(SR.PresentDays,0)AS PresentDays,
		SR.StudentHeight,
		SR.StudentWeight,
		EM.IsDisplayGradeString,
		CCERD.IspresentFA1,
		CCERD.IsPresentFA2,
		CCERD.IspresentSA1,
		CCERD.IspresentFA3,
		CCERD.IsPresentFA4,
		CCERD.IspresentSA2,
		SR.ResultRemark1,
		SR.ResultRemark2,
		CCERD.GradePoint,
		CCERD. FATerm1,
		CCERD.FATerm2,
		CS.IsOptional,
		EM.IsDisplayPrincipalSign,
		Em.IsDisplayTeacherSign,
		EI.EmployeeSign,
		AD.TotalDaysTerm1,
		AD.PresentDaysTerm1,
		AD.TotalDaysTerm2,
		AD.PresentDaysTerm2,
		 
		CCER.CGPA,
		ISNULL(SR.AreaOfInterest,'')As AreaOfInterest,
		ISNULL(SR.Responsibility,'') AS Responsibility,
		ISNULL(SR.MyGoal,'')AS MyGoal,
		ISNULL(SR.MyInterestHobby,'')AS MyInterestHobby,
		 ISNULL(SR.MyStrength,'')AS MyStrength,
		  ISNULL(SR.Achievements,'')AS Achievements,
		  ISNULL(SR.DentalHygiene,'')AS DentalHygiene, 
		 ISNULL(SR.VisionLeft,'')AS VisionLeft,
		  ISNULL(SR.VisionRight,'')AS VisionRight,
		 ISNULL(CCER.Term1Grade,'') Term1OverAllGrade,
		 ISNULL( CCER.Term2Grade,'') Term2OverAllGrade,
		 ISNULL(CCER.AnnualGrade,'') AnnualOverAllGrade,
		  CONVERT (nvarchar(20),EM.CoScholasticGradeSetId) AS CoScholasticGradeSetIdText,
		EM.IsMarksInDecimal,
		
		CCERD.FA,
		CCERD.SA,
		
		ISNULL(CCER.Term1TotalMarks,0) AS Term1TotalMarks,
		ISNULL(CCER.Term1TotalObtain,0) AS Term1TotalObtain,
		ISNULL(CCER.Term2TotalMarks,0) AS Term2TotalMarks,
		ISNULL(CCER.Term2TotalObtain,0) AS Term2TotalObtain,
		ISNULL(CCER.AnnualTotalMarks,0) AS AnnualTotalMarks,
		ISNULL(CCER.AnnualTotalObtain,0) AS AnnualTotalObtain,
		Em.IsDisplayParentName,
		(CASE EM.IsDisplayImageHeader WHEN 1 THEN
			OI.CertificateHeaderA4 
			ELSE NULL END)AS  MarksheetHeaderA4,
			ISNULL(EM.IsDisplayImageHeader,0) AS IsImageHeader,
		EM.DecimalFormat,
		CCER.Term1CGPA,
		CCER.Term2CGPA,
		CCERD.GradePointFA1,
		CCERD.GradePointFA2,
		CCERD.GradePointSA1,
		CCERD.GradePointFA3,
		CCERD.GradePointFA4,
		CCERD.GradePointSA2,
		CCERD.FAGradePoint,
		CCERD.SAGradePoint,
		SubM.Code As SubjectCode,
		@CSGradeString AS CoScholasticGradeString ,
		@CSGradeSetId AS ABCD,
		ED.IsShowSubjectMark,
		ED.IsShowSubjectGrade,
		CCERD.FA1Max,
		CCERD.FA2Max,
		CCERD.SA1Max,
		CCERD.FA3Max,
		CCERD.FA4Max,
		
		CCERD.SA2Max,
		
		CCERD.Term1TotalGradePoint,
		ccerd.Term2TotalGradePoint,
		(Select DecimalFormat from sAssessment.tCCEExamSetting where ClassId =@rClassId AND BatchId=@rBatchId AND  CCEExamID=1) AS FA1DecimalFormat,
		(Select DecimalFormat from sAssessment.tCCEExamSetting where ClassId =@rClassId AND BatchId=@rBatchId AND  CCEExamID=2) AS FA2DecimalFOrmat,
		(Select DecimalFormat from sAssessment.tCCEExamSetting where ClassId =@rClassId AND BatchId=@rBatchId AND  CCEExamID=4) AS FA3DecimalFormat,
		(Select DecimalFormat from sAssessment.tCCEExamSetting where ClassId =@rClassId AND BatchId=@rBatchId AND  CCEExamID=5) AS FA4DecimalFormat,
		(Select DecimalFormat from sAssessment.tCCEExamSetting where ClassId =@rClassId AND BatchId=@rBatchId AND  CCEExamID=3) AS SA1DecimalFormat,
		(Select DecimalFormat from sAssessment.tCCEExamSetting where ClassId =@rClassId AND BatchId=@rBatchId AND  CCEExamID=6) AS SA2DecimalFormat,
		(Select DecimalFormat from sAssessment.tCCEExamSetting where ClassId =@rClassId AND BatchId=@rBatchId AND  CCEExamID=7) AS Term1DecimalFormat,
		(Select DecimalFormat from sAssessment.tCCEExamSetting where ClassId =@rClassId AND BatchId=@rBatchId AND  CCEExamID=8) AS Term2DecimalFormat,
		(Select DecimalFormat from sAssessment.tCCEExamSetting where ClassId =@rClassId AND BatchId=@rBatchId AND  CCEExamID=9) AS AnnualDecimalFormat ,
	 ISNULL(CCERD.IsUpgradedGrade,0) AS IsUpgradedGrade,
		ISNULL(ED.IsIncludeInTotal,0) As IsIncludeInTotal,
		(Select ED.IsDisplayInMarksheet  
		  From  sAssessment.tCCEEXAMMASTER CM 
		 --INNER JOIN sAssessment.tExamSubGroupMaster ESM ON ESM.Id = CE.ExamSubGroupId
		 --INNER JOIN sAssessment.tExamMaster eEM ON eEM.ExamSubGroupId = CE.ExamSubGroupId
		 --INNER JOIN sAssessment.tExamDetail ED ON ED.Examid = eEM.Id AND ClassSubjectId =CCERD.ClassSubjectId
		 Where CE.BatchId = @rBatchId  AND  CM.Id=@rCCEExamID 
		--ANd EM.ClassId= @rClassId  
		 ) As IsDisplayInMarksheet,
		 CE.IsUpgradGrade AS CSUpgradeGrade,
		 SR.ExamSeatNo
		
		 
		
		 
	
			
	--		--CASE WHEN ED.ClassSubjectId=CS.Id THEN 'Yes' ELSE 'false' END AS Selected
      
	FROM 
	
			sAssessment.tCCEResultDetail CCERD
			
			INNER JOIN sAssessment.tCCEResult CCER  ON CCERD.AcademicId=CCER.AcademicId
			INNER JOIN sStudent.tAcademic A ON CCER.AcademicId=A.Id
			LEFT JOIN sStudent.tAcademicDetail AD ON AD.AcademicId = A.Id
		
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId
			left Join sStudent.tStudentFamily SF ON SF.StudentId =SM.Id
			LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=A.StudentId
			
			LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
			LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = DM.InchargeEmployeeId
			LEFT JOIN sActivity.tHouseMaster HM ON HM.Id=SO.HouseId
			LEFT JOIN sSetup.tClassSubject CS ON CS.Id=CCERD.ClassSubjectId
			INNER JOIN sSetup.tSubjectMaster SubM ON SubM.Id=CS.SubjectId
			LEFT JOIN sCommon.tBloodGroupMaster BGM ON BGM.Id=SO.BloodGroupId
			LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=SM.Id
			INNER JOIN sAssessment.tCCEExamSetting CE ON CE.ClassId = CM.Id AND CE.CCEExamId = @rCCEExamId AND CE.BatchId = @rBatchId 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ExamSubGroupId = CE.ExamSubGroupId AND EM.ClassId = CE.ClassId AND EM.BatchId = @rBatchId 
			Inner Join sAssessment.tExamSubGroupMaster ESM ON ESM.Id=EM.ExamSubGroupId
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id AND ED.ClassSubjectId = CS.Id
		
			 
			LEFT JOIN sAssessment.tStudentRemark SR ON CCERD.AcademicId = SR.AcademicId AND ED.ExamId = SR.ExamId 
			
			
			
			LEFT JOIN sSetup.tTermScopeMaster TSM ON TSM.Id = EM.TermScopeId

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


GO

ALTER PROCEDURE [sAssessment].[pExamRemarkSetupGet]
          
   @rId int,
   @rTitle nvarchar(100),
   @rOrgId int,
   @rClassId int,
   @rExamId int,
   @rBatchId int=0          
          
AS
SET NOCOUNT ON

   SET @rTitle = sCommon.fSearchStringGet(@rTitle)

BEGIN
  SELECT 
	   ERS.Id as Id
	  ,ERS.Title as Title
	  ,ISNULL(ERS.Code,'') as Code
	  --,ISNULL(EM.DisplayTitle,'') AS ExamTitle
	  ,ISNULL(ESGM.Title,'') AS ExamTitle
	  ,ERS.ExamId AS ExamId
	  ,ISNULL(ERS.OrderIndex,0) AS OrderIndex
       ,ISNULL(EM.ClassId,0) AS ClassId
  FROM [sAssessment].[tExamRemarkSetup] ERS 
	   INNER JOIN [sAssessment].[tExamMaster] EM ON EM.Id = ERS.ExamId
	   --inner Join sAssessment.tExamGroupMaster EGM ON EGM.Id=EM.ExamSubGroupId 
	   INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.ID = EM.ExamSubGroupId
	   INNER JOIN sAssessment.tExamGroupMaster EGM ON EGM.Id=ESGM.ExamGroupId 
  WHERE 
	    ((ERS.Title Like @rTitle)OR(ISNULL(@rTitle,'') = ''))
	    AND (ERS.ExamId=@rExamId OR @rExamId=0)
		AND EGM.OrgId = @rOrgId
		AND (ERS.Id = @rId  OR @rId = 0)
		AND(EM.ClassId=@rClassId OR @rClassId=0)
		AND (EM.BatchId=@rBatchId OR @rBatchId=0)
   Order by OrderIndex 
END
GO
PRINT N'Altering [sAssessment].[pGenerateResultSheetStandardMultiExam]...';


GO

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

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
 begin
 

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

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

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

 

--#TempAllExam
	CREATE TABLE #TempAllExam
	(
		AcademicIdText nvarchar(20),
		ExamIdText nvarchar(20),
		CoScholasticScopeIdText nvarchar(20),
		IsDisplayMonthlyAttendanceText nvarchar(20),
		ClassIdText nvarchar(50),
		AcademicId bigint,
		ExamName Nvarchar(150),
		StudCode NVarchar(20),
		StudentName Nvarchar(150),
		RollNo int,
		ResultStatus Nvarchar(20),	
		ClassName NVarchar(50),		
		Division NVarchar(50),
		TotalMark decimal(8,2),
		TotalObtain decimal(8,2),
		Percentage decimal(8,2),
		RankNumber int,
		ResultGrade NVarchar(50),
		
		MaximumMark1 decimal(8,2),		
		SubjectGrade1 NVarchar(50),
		Obtain1 decimal(8,2),
		ExamMaximum1 decimal(8,2),
		IsPresent1 bit,
						
		MaximumMark2 decimal(8,2),	
		SubjectGrade2 NVarchar(50),
		Obtain2 decimal(8,2),
		ExamMaximum2 decimal(8,2),
		IsPresent2 bit,
				
		MaximumMark3 decimal(8,2),
		SubjectGrade3 NVarchar(50),
		Obtain3 decimal(8,2),
		ExamMaximum3 decimal(8,2),
		IsPresent3 bit,		
		
		MaximumMark4 decimal(8,2),	
		SubjectGrade4 NVarchar(50),
		Obtain4 decimal(8,2),
		ExamMaximum4 decimal(8,2),
		IsPresent4 bit,	
				
		MaximumMark5 decimal(8,2),		
		SubjectGrade5 NVarchar(50),
		Obtain5 decimal(8,2),
		ExamMaximum5 decimal(8,2),
		IsPresent5 bit,	
				
		MaximumMark6 decimal(8,2),		
		SubjectGrade6 NVarchar(50),
		Obtain6 decimal(8,2),
		ExamMaximum6 decimal(8,2),
		IsPresent6 bit,	
		
		MaximumMark7 decimal(8,2),		
		SubjectGrade7 NVarchar(50),
		Obtain7 decimal(8,2),
		ExamMaximum7 decimal(8,2),
		IsPresent7 bit,	
		
		MaximumMark8 decimal(8,2),	
		SubjectGrade8 NVarchar(50),
		Obtain8 decimal(8,2),
		ExamMaximum8 decimal(8,2),
		IsPresent8 bit,	
		
		MaximumMark9 decimal(8,2),		
		SubjectGrade9 NVarchar(50),
		Obtain9 decimal(8,2),
		ExamMaximum9 decimal(8,2),
		IsPresent9 bit,	
		
		
		MaximumMark10 decimal(8,2),		
		SubjectGrade10 NVarchar(50),
		Obtain10 decimal(8,2),
		ExamMaximum10 decimal(8,2),
		IsPresent10 bit,	
		
		MaximumMark11 decimal(8,2),		
		SubjectGrade11 NVarchar(50),
		Obtain11 decimal(8,2),
		ExamMaximum11 decimal(8,2),
		IsPresent11 bit,
		
		MaximumMark12 decimal(8,2),		
		SubjectGrade12 NVarchar(50),
		Obtain12 decimal(8,2),
		ExamMaximum12 decimal(8,2),
		IsPresent12 bit,		
		 
		 
		SubjectGradeTerm1 NVarchar(50),
		SubjectGradeTerm2 NVarchar(50),
		SubjectGradeTerm3 NVarchar(50),
		IsMarksInDecimal bit,
		column_visible bit,
		--Obtain decimal(5,2),
		Percentile decimal(5,2),
		--ClassSubject nvarchar(100),
		ResultDetailId bigint,
		ResultId bigint,	
		Remark1 nvarchar(500),
		Remark2 nvarchar(500),
		Remark3 nvarchar(500),
		DisplayTitle nvarchar(150),		
		IsRankNo bit, 
		IsGrade bit,
		IsPercentile bit,
		IsPercentage bit,
		IsSubjectPercentile bit,
		IsProcessResult bit,
		IsNegativeMarks bit,
		IsIncludeCoScholastic bit,
		IsOnPrePrinted bit,
		IsDisplayPhoto bit,
		IsDisplayBirthDate bit,
		IsLockForEdit bit,
		IsDisplaySchoolName bit,			
		IsDisplayAttendance bit,
		IsDisplayHeightWeight bit,
		IsResultStatus bit,
		FooterAdjustmentText nvarchar(max),
		DetailAdjustmentText nvarchar(max),
		FooterAdjustment smallint,
		DetailAdjustment smallint,
		ResultRemark nvarchar(200),
		DateOfBirth date,
		HeightTerm1 decimal(5,2),
		WeightTerm1 decimal(5,2),
		HeightTerm2 decimal(5,2),
		WeightTerm2 decimal(5,2),
		HeightAnnual decimal(5,2),
		WeightAnnual decimal(5,2),
		PresentDaysTerm1 smallint,
		PresentDaysTerm2 smallint,
		PresentDaysAnnual smallint,
		TotalDaysTerm1 smallint,
		TotalDaysTerm2 smallint,
		TotalDaysAnnual smallint,
		TotalMarkTerm1 decimal(8,2),
		TotalObtainTerm1 decimal(8,2),
		PercentageTerm1 decimal(8,2),
		RankNumberTerm1 int,
		ResultGradeTerm1 NVarchar(50),
		PercentileTerm1 decimal(8,2),
		ResultStatusTerm1 Nvarchar(20),		   
		TotalMarkTerm2 decimal(8,2),
		TotalObtainTerm2 decimal(8,2),
		PercentageTerm2 decimal(8,2),
		RankNumberTerm2 int,
		ResultGradeTerm2 NVarchar(50),
		PercentileTerm2 decimal(8,2),
		ResultStatusTerm2 Nvarchar(20), 
		TotalMarkTerm3 		decimal(8,2),
		TotalObtainTerm3 decimal(8,2),
		PercentageTerm3 decimal(8,2),
		RankNumberTerm3 int,
		ResultGradeTerm3 NVarchar(50),
		PercentileTerm3 decimal(8,2),
		ResultStatusTerm3 Nvarchar(20), 
		
		TermScopeId tinyint,		 
		StudentPhoto varbinary(max),
		GradeString nvarchar(1000),
		IsDisplayGradeString bit,		 
		IsDisplayInMarksheet bit,
		IsShowSubjectGrade bit,
		IsIncludeInTotal bit,
		ClassSubjectID int,
		SubjectId int,
		--Maximum decimal(5,2),
		SubjectOrderIndex smallint,
		SubjectGrade NVarchar(50),
		SubjectName NVarchar(150),
		SubjectCode Nvarchar(50),	
		SubjectMinimum decimal(8,2),		
		SubjectMaximum decimal(8,2),
		SubjectObtain  decimal(8,2),
		
		Exam1Name Nvarchar(150),		
		TotalMarks1 decimal(8,2),		
		TotalObtain1 decimal(8,2),
		Percentage1 decimal(8,2),
		RankNumber1 int,
		ResultGrade1 NVarchar(50),
		Percentile1 decimal(8,2),
		ResultStatus1 Nvarchar(20),
		
		Exam2Name nvarchar(150),	
		TotalMarks2 decimal(8,2),
		TotalObtain2 decimal(8,2),
		Percentage2 decimal(8,2),
		RankNumber2 int,
		ResultGrade2 NVarchar(50),
		Percentile2 decimal(8,2),
		ResultStatus2 Nvarchar(20),
		
		Exam3Name nvarchar(150),	
		TotalMarks3 decimal(8,2),
		TotalObtain3 decimal(8,2),
		Percentage3 decimal(8,2),
		RankNumber3 int,
		ResultGrade3 NVarchar(50),
		Percentile3 decimal(8,2),		
		ResultStatus3 Nvarchar(20),
		
		Exam4Name nvarchar(150),	
		TotalMarks4 decimal(8,2),
		TotalObtain4 decimal(8,2),
		Percentage4 decimal(8,2),
		RankNumber4 int,
		ResultGrade4 NVarchar(50),
		Percentile4 decimal(8,2),
		ResultStatus4 Nvarchar(20),
		
		Exam5Name nvarchar(150),		
		TotalMarks5 decimal(8,2),
		TotalObtain5 decimal(8,2),
		Percentage5 decimal(8,2),
		RankNumber5 int,
		ResultGrade5 NVarchar(50),
		Percentile5 decimal(8,2),
		ResultStatus5 Nvarchar(20),
		
		Exam6Name nvarchar(150),	
		TotalMarks6 decimal(8,2),
		TotalObtain6 decimal(8,2),
		Percentage6 decimal(8,2),
		RankNumber6 int,
		ResultGrade6 NVarchar(50),
		Percentile6 decimal(8,2),
		ResultStatus6 Nvarchar(20),
		
		Exam7Name nvarchar(150),		
		TotalMarks7 decimal(8,2),
		TotalObtain7 decimal(8,2),
		Percentage7 decimal(8,2),
		RankNumber7 int,
		ResultGrade7 NVarchar(50),
		Percentile7 decimal(8,2),
		ResultStatus7 Nvarchar(20),
		
		Exam8Name nvarchar(150),
		TotalMarks8 decimal(8,2),
		TotalObtain8 decimal(8,2),
		Percentage8 decimal(8,2),
		RankNumber8 int,
		ResultGrade8 NVarchar(50),
		Percentile8 decimal(8,2),
		ResultStatus8 Nvarchar(20),
		
		
		Exam9Name nvarchar(150),	
		TotalMarks9 decimal(8,2),
		TotalObtain9 decimal(8,2),
		Percentage9 decimal(8,2),
		RankNumber9 int,
		ResultGrade9 NVarchar(50),
		Percentile9 decimal(8,2),
		ResultStatus9 Nvarchar(20),
		
		Exam10Name nvarchar(150),	
		TotalMarks10 decimal(8,2),
		TotalObtain10 decimal(8,2),
		Percentage10 decimal(8,2),
		RankNumber10 int,
		ResultGrade10 NVarchar(50),
		Percentile10 decimal(8,2),
		ResultStatus10 Nvarchar(20),
		
		Exam11Name nvarchar(150),	
		TotalMarks11 decimal(8,2),
		TotalObtain11 decimal(8,2),
		Percentage11 decimal(8,2),
		RankNumber11 int,
		ResultGrade11 NVarchar(50),
		Percentile11 decimal(8,2),
		ResultStatus11 Nvarchar(20),
		
		
		Exam12Name nvarchar(150),	
		TotalMarks12 decimal(8,2),
		TotalObtain12 decimal(8,2),
		Percentage12 decimal(8,2),
		RankNumber12 int,
		ResultGrade12 NVarchar(50),
		Percentile12 decimal(8,2),
		ResultStatus12 Nvarchar(20),
		
		ResultRemark1 nvarchar(200),
		ResultRemark2 nvarchar(200),
		
		TotalDays 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)
	)	
	 --print 'temp created'    	
	INSERT INTO  #TempAllExam 
	(
	AcademicIdText,
	ExamIdText,
	CoScholasticScopeIdText,
	IsDisplayMonthlyAttendanceText,
	ClassIdText,
	AcademicId,
	ExamName,
	StudCode,
	StudentName,
	RollNo,
	ResultStatus,
	ClassName,
	Division,
	TotalMark,
	TotalObtain,
	Percentage,
	RankNumber,
	ResultGrade,
	IsMarksInDecimal,
	column_visible,
	--Obtain,
	Percentile,
	--ClassSubject,
	ResultDetailId,
	ResultId,

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


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

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

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

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

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


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

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

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

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

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

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

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

  --end
GO
PRINT N'Altering [sAssessment].[pResultSheetStandardMultiExamGet]...';


GO
ALTER PROCEDURE [sAssessment].[pResultSheetStandardMultiExamGet]	 	 	
	 @rExamId int,	
	 @rAcademicId bigint=0,
	 @rIsUseInStudent360 bit =0		 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
begin
 
  --select * from sAssessment.tTempAllExam
-- --drop table sAssessment.tTempAllExam
 
  
DECLARE @GradeString nvarchar(1000)
DECLARE @GradeStringRemark nvarchar(500),
@GradeSetId int , @IsIncludeSubExam bit,@GradeStringHtml nvarchar(500)
SELECT @GradeSetId = GradesetId,
	   @IsIncludeSubExam = ISNULL(IsIncludeSubExam,0)  FROM sAssessment.tExamMaster WHERE Id = @rExamId
SELECT @GradeString = [sAssessment].[fGradeStringGet](@GradeSetId)

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

--#TempAllExam
	CREATE TABLE #TempAllExam
	(
	    SRNO INT IDENTITY(1,1) PRIMARY KEY, 
		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,		
		 
		 
		SubjectGradeTerm1 NVarchar(50),
		SubjectGradeTerm2 NVarchar(50),
		SubjectGradeTerm3 NVarchar(50),
		IsMarksInDecimal bit,
		column_visible bit,
		--Obtain decimal(5,2),
		Percentile decimal(5,2),
		--ClassSubject nvarchar(100),
		ResultDetailId bigint,
		ResultId bigint,	
		Remark1 nvarchar(500),
		Remark2 nvarchar(500),
		Remark3 nvarchar(500),
		DisplayTitle nvarchar(150),		
		IsRankNo bit, 
		IsGrade bit,
		IsPercentile bit,
		IsPercentage bit,
		IsSubjectPercentile bit,
		IsProcessResult bit,
		IsNegativeMarks bit,
		
		
		
		IsResultStatus bit,
		
		ResultRemark nvarchar(200),
	
		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), 
		
		
		ClassSubjectID int,
		SubjectId int,
		--Maximum decimal(5,2),
		SubjectOrderIndex smallint,
		SubjectGrade NVarchar(50),
		SubjectName NVarchar(150),
		SubjectCode Nvarchar(50),	
		SubjectMinimum decimal(8,2),		
		SubjectMaximum decimal(8,2),
		SubjectObtain  decimal(8,2),
		
		Exam1Name Nvarchar(150),		
		TotalMarks1 decimal(8,2),		
		TotalObtain1 decimal(8,2),
		Percentage1 decimal(8,2),
		RankNumber1 int,
		ResultGrade1 NVarchar(50),
		Percentile1 decimal(8,2),
		ResultStatus1 Nvarchar(20),
		
		Exam2Name nvarchar(150),	
		TotalMarks2 decimal(8,2),
		TotalObtain2 decimal(8,2),
		Percentage2 decimal(8,2),
		RankNumber2 int,
		ResultGrade2 NVarchar(50),
		Percentile2 decimal(8,2),
		ResultStatus2 Nvarchar(20),
		
		Exam3Name nvarchar(150),	
		TotalMarks3 decimal(8,2),
		TotalObtain3 decimal(8,2),
		Percentage3 decimal(8,2),
		RankNumber3 int,
		ResultGrade3 NVarchar(50),
		Percentile3 decimal(8,2),		
		ResultStatus3 Nvarchar(20),
		
		Exam4Name nvarchar(150),	
		TotalMarks4 decimal(8,2),
		TotalObtain4 decimal(8,2),
		Percentage4 decimal(8,2),
		RankNumber4 int,
		ResultGrade4 NVarchar(50),
		Percentile4 decimal(8,2),
		ResultStatus4 Nvarchar(20),
		
		Exam5Name nvarchar(150),		
		TotalMarks5 decimal(8,2),
		TotalObtain5 decimal(8,2),
		Percentage5 decimal(8,2),
		RankNumber5 int,
		ResultGrade5 NVarchar(50),
		Percentile5 decimal(8,2),
		ResultStatus5 Nvarchar(20),
		
		Exam6Name nvarchar(150),	
		TotalMarks6 decimal(8,2),
		TotalObtain6 decimal(8,2),
		Percentage6 decimal(8,2),
		RankNumber6 int,
		ResultGrade6 NVarchar(50),
		Percentile6 decimal(8,2),
		ResultStatus6 Nvarchar(20),
		
		Exam7Name nvarchar(150),		
		TotalMarks7 decimal(8,2),
		TotalObtain7 decimal(8,2),
		Percentage7 decimal(8,2),
		RankNumber7 int,
		ResultGrade7 NVarchar(50),
		Percentile7 decimal(8,2),
		ResultStatus7 Nvarchar(20),
		
		Exam8Name nvarchar(150),
		TotalMarks8 decimal(8,2),
		TotalObtain8 decimal(8,2),
		Percentage8 decimal(8,2),
		RankNumber8 int,
		ResultGrade8 NVarchar(50),
		Percentile8 decimal(8,2),
		ResultStatus8 Nvarchar(20),
		
		
		Exam9Name nvarchar(150),	
		TotalMarks9 decimal(8,2),
		TotalObtain9 decimal(8,2),
		Percentage9 decimal(8,2),
		RankNumber9 int,
		ResultGrade9 NVarchar(50),
		Percentile9 decimal(8,2),
		ResultStatus9 Nvarchar(20),
		
		Exam10Name nvarchar(150),	
		TotalMarks10 decimal(8,2),
		TotalObtain10 decimal(8,2),
		Percentage10 decimal(8,2),
		RankNumber10 int,
		ResultGrade10 NVarchar(50),
		Percentile10 decimal(8,2),
		ResultStatus10 Nvarchar(20),
		
		Exam11Name nvarchar(150),	
		TotalMarks11 decimal(8,2),
		TotalObtain11 decimal(8,2),
		Percentage11 decimal(8,2),
		RankNumber11 int,
		ResultGrade11 NVarchar(50),
		Percentile11 decimal(8,2),
		ResultStatus11 Nvarchar(20),
		
		Exam12Name nvarchar(150),	
		TotalMarks12 decimal(8,2),
		TotalObtain12 decimal(8,2),
		Percentage12 decimal(8,2),
		RankNumber12 int,
		ResultGrade12 NVarchar(50),
		Percentile12 decimal(8,2),
		ResultStatus12 Nvarchar(20),
		
		ResultRemark1 nvarchar(200),
		ResultRemark2 nvarchar(200),
		
		TotalDays 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),
		
		
--		ResultDetailId int,
		ResultDetailId1 bigint,
		ResultDetailId2 bigint,
		ResultDetailId3 bigint,
		ResultDetailId4 bigint,
		ResultDetailId5 bigint,
		ResultDetailId6 bigint,
		ResultDetailId7 bigint,
		ResultDetailId8 bigint,
		ResultDetailId9 bigint,
		ResultDetailId10 bigint,
		ResultDetailId11 bigint,
		ResultDetailId12 bigint,
		
		
	
		Batch nvarchar(100),
		ExamNameTerm1 NVarchar(100),
		ExamNameTerm2 NVarchar(100) ,
		ExamNameTerm3 NVarchar(100),
		ClassTeacherName Nvarchar(100),
		FirstName nvarchar(50),
		LastName nvarchar(50),
		IsDisplayMonthlyAttendance 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),
		SubjectMaxTerm1 decimal(8,2),
		SubjectMaxTerm2 decimal(8,2),
		SubjectMaxTerm3 decimal(8,2),
		
		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),
		
		
		AchievementsTerm1 nvarchar(200),
		AchievementsTerm2 nvarchar(200),
		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)
	)	
	 --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,
	
	IsResultStatus,
	
	ResultRemark,
	
	HeightTerm1,
	WeightTerm1,
	HeightTerm2,
	WeightTerm2,
	HeightAnnual,
	WeightAnnual,
	PresentDaysTerm1,
	PresentDaysTerm2,
	PresentDaysAnnual,
	TotalDaysTerm1,
	TotalDaysTerm2,
	TotalDaysAnnual,
	
	
	ClassSubjectID,
	SubjectId,
	--Maximum,
	SubjectOrderIndex,
	SubjectGrade,
	SubjectName,
	SubjectCode,
	SubjectMinimum,
	SubjectMaximum,
	SubjectObtain,
	ResultRemark1,
	ResultRemark2,
	
	TotalDays,
	PresentDays,
	StudentHeight,
	StudentWeight,
	ExamSeatNo,
	ExamId,
	
	ExamCode,
	
	
	Batch,
	ClassTeacherName,
	FirstName,
	LastName,
	IsDisplayMonthlyAttendance,
	
	SubjectGroupId,
	--SubjectGroupTitle,
	--SubjectGroupCode,
	DecimalFormat,
	SubjectRemark,
	GraceMark,
	KrupaMark,
	GradeStringHtml,
	ResultRemark3,
	IsDisplayTotalMark,
	
    IsPresent,
    GradeTitle,
	
	AchievementsTerm1,
	AchievementsTerm2,
	GeneralRemarkTerm1,
	GeneralRemarkTerm2,
	ResultRemark1Term1,
	ResultRemark2Term1,
	ResultRemark1Term2,
	ResultRemark2Term2,
	SR_HeightTerm1,
	SR_WeightTerm1,
	SR_HeightTerm2,
	SR_WeightTerm2,
	SR_PresentDaysTerm1,
	SR_PresentDaysTerm2,
	SR_TotalDaysTerm1,
	SR_TotalDaysTerm2	
	)
	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.IsResultStatus,		
		ISNULL(R.ResultRemark,'') AS ResultRemark,		
		AD.HeightTerm1,
		AD.WeightTerm1,
		AD.HeightTerm2,
		AD.WeightTerm2,
		AD.HeightAnnual,
		AD.WeightAnnual,
		AD.PresentDaysTerm1,
		AD.PresentDaysTerm2,
		AD.PresentDaysAnnual,
		AD.TotalDaysTerm1,
		AD.TotalDaysTerm2,
		AD.TotalDaysAnnual,
	
	    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,
		
		
		BM.Title AS Batch,
		EMP.FirstName + ' ' + EMP.LastName AS ClassTeacherName,
		Stum.FirstName,
		Stum.LastName,
		 
		ISNULL(EM.IsDisplayMonthlyAttendance,0) AS IsDisplayMonthlyAttendance,
		
		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,
		
		IsPresent,
		GradeTitle ,
		
		
		'' 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	
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.tEmployeeMaster EMP ON EMP.Id = DM.InchargeEmployeeId
	INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.EXAMSUBGROUPID
	
	LEFT JOIN sStudent.tAcademicDetail AD ON AD.AcademicId=A.Id	
	LEFT JOIN sAssessment.tStudentRemark SR ON R.AcademicId = SR.AcademicId AND R.ExamId = SR.ExamId	
	LEFT JOIN sAssessment.tOptionalSubject OS ON OS.AcademicId = R.AcademicId AND OS.ClassSubjectId = ED.ClassSubjectId  AND ED.ExamId = R.ExamId	
	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.Id=@rAcademicId)OR (@rAcademicId=0))	
		 AND ISNULL(EMP.IsOtherUser,0) = 0		    
	Order By ED.DisplayOrder
 
 --print 'temp insert'
  --SET @IsIncludeSubExam = 1
	create TABLE #tempcombineExam
	(	Id int IDENTITY,
		ExamID int )

	IF (@IsIncludeSubExam = 0)
	BEGIN	
	INSERT INTO #tempcombineExam (ExamID) 
	SELECT SUBEXAMID FROM sAssessment.tExamCombine WHERE ExamId  = @rExamId Order By ExamOrder ASC
 	END
 	ELSE
 	BEGIN
 	-- if we want to display result for both the term with all exam select this option
 	INSERT INTO #tempcombineExam (ExamID) 
	SELECT C.SUBEXAMID FROM sAssessment.tExamCombine C
	INNER JOIN (SELECT SUBEXAMID,ExamOrder FROM sAssessment.tExamCombine WHERE ExamId  = @rExamId) E
	ON C.ExamId = E.SubExamId
	ORDER BY E.ExamOrder,C.ExamOrder
	END
	--ON 
	
	--If no any combine exam exist in current exam then insert current exam in combineExam for final level
	IF NOT EXISTS(select 1 FROM sAssessment.tExamCombine WHERE ExamId  = @rExamId)
	BEGIN
	  INSERT INTO #tempcombineExam (ExamID) 
	  SELECT C.Id From sAssessment.tExamMaster C WHERE C.Id  = @rExamId
	END
	
	
	-- 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
	--print @lCount
	--select * 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,	
					 --ExamDetailId' + convert(nvarchar(15),@lCount)+'=RD.ExamDetailId,
					  ResultDetailId' + convert(nvarchar(15),@lCount)+'=RD.Id,
					 				
					 SubjectGrade' + convert(nvarchar(15),@lCount)+ '=RD.SubjectGrade,
					 TotalDays'+convert(nvarchar(15),@lCount)+'=SR.TotalDays,
					 PresentDays'+convert(nvarchar(15),@lCount)+'=SR.PresentDays										
					 From
						sAssessment.tResultDetail RD
						INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId	
						LEFT JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND T.AcademicId = SR.AcademicId 									
						WHERE R.AcademicId='+convert(nvarchar(20), @rAcademicId)+' AND  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 R.AcademicId='+convert(nvarchar(20), @rAcademicId)+' AND EM.Id =' + convert(nvarchar(15), @lSubExamId)  
						
		execute(@query)
		
		
	set @lCount = @lCount -1
	end
	

	IF (@IsIncludeSubExam = 1)
	BEGIN	
		select @lSubExamId = SubExamId from sAssessment.tExamCombine  Where ExamId  = @rExamId AND ExamOrder = 1
		--select @ExamTitle = Title from sAssessment.tExamMaster Where Id = @lSubExamId	
		
		
			set @query ='update T set					 
					SubjectGradeTerm1=RD.SubjectGrade,
					SubjectObtainTerm1 = RD.Obtain,
					 SubjectMaxTerm1 = ED.Maximum
							 
					 From
						 sAssessment.tResultDetail RD
						INNER JOIN  sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId						
						WHERE R.AcademicId='+convert(nvarchar(20), @rAcademicId)+' AND 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
					
					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 R.AcademicId='+convert(nvarchar(20), @rAcademicId)+' AND 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
						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 R.AcademicId='+convert(nvarchar(20), @rAcademicId)+' AND 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 R.AcademicId='+convert(nvarchar(20), @rAcademicId)+' AND 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 R.AcademicId='+convert(nvarchar(20), @rAcademicId)+' AND 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 R.AcademicId='+convert(nvarchar(20), @rAcademicId)+' AND EM.Id =' + convert(nvarchar(15), @lSubExamId)  
		execute(@query)
	END		
	
	SELECT T.*
	FROM #TempAllExam T  where 
	T.ExamId=@rExamId AND 
	AcademicId= @rAcademicId
	
	
	--Declare @Count AS Integer
    --SET @Count=(SELECT  count(ClassSubjectID) FROM #TempAllExam T)
    DECLARE @lCounter INT
    SET @lCounter = 1
    DECLARE @lMAXID INT=0
    
    SELECT @lMAXID = COUNT(*) FROM #TempAllExam
    Declare @FinalHtml nvarchar(max)=''
	Declare @tdHtml nvarchar(max)
	Declare @trHtml nvarchar(max)
	Declare @HeaderHtml nvarchar(max)
	Declare @HeaderCounter int=0
	Declare @thHtml nvarchar(max)
	
	WHILE (@lCounter <= @lMAXID)
	BEGIN 
	     Declare @ClassSubject nvarchar(max)
	     Declare @ResultDetailId1 nvarchar(max)
	     Declare @ResultDetailId2 nvarchar(max)
	     Declare @ResultDetailId3 nvarchar(max)
	     Declare @ResultDetailId4 nvarchar(max)
	     Declare @ResultDetailId5 nvarchar(max)
	     Declare @ResultDetailId6 nvarchar(max)
	     Declare @ResultDetailId7 nvarchar(max)
	     Declare @ResultDetailId8 nvarchar(max)
	     Declare @ResultDetailId9 nvarchar(max)
	     Declare @ResultDetailId10 nvarchar(max)
	     Declare @ResultDetailId11 nvarchar(max)
	     Declare @ResultDetailId12 nvarchar(max)
	     
	     Declare @Obtain1 decimal(10,2)
	     Declare @Obtain2 decimal(10,2)
	     Declare @Obtain3 decimal(10,2)
	     Declare @Obtain4 decimal(10,2)
	     Declare @Obtain5 decimal(10,2)
	     Declare @Obtain6 decimal(10,2)
	     Declare @Obtain7 decimal(10,2)
	     Declare @Obtain8 decimal(10,2)
	     Declare @Obtain9 decimal(10,2)
	     Declare @Obtain10 decimal(10,2)
	     Declare @Obtain11 decimal(10,2)
	     Declare @Obtain12 decimal(10,2)
	     
	     
	     Declare @ExamMaximumMarks1 decimal(10,2)
	     Declare @ExamMaximumMarks2 decimal(10,2)
	     Declare @ExamMaximumMarks3 decimal(10,2)
	     Declare @ExamMaximumMarks4 decimal(10,2)
	     Declare @ExamMaximumMarks5 decimal(10,2)
	     Declare @ExamMaximumMarks6 decimal(10,2)
	     Declare @ExamMaximumMarks7 decimal(10,2)
	     Declare @ExamMaximumMarks8 decimal(10,2)
	     Declare @ExamMaximumMarks9 decimal(10,2)
	     Declare @ExamMaximumMarks10 decimal(10,2)
	     Declare @ExamMaximumMarks11 decimal(10,2)
	     Declare @ExamMaximumMarks12 decimal(10,2)
	     
	     
	     Declare @Exam1Name nvarchar(max)
	     Declare @Exam2Name nvarchar(max)
	     Declare @Exam3Name nvarchar(max)
	     Declare @Exam4Name nvarchar(max)
	     Declare @Exam5Name nvarchar(max)
	     Declare @Exam6Name nvarchar(max)
	     Declare @Exam7Name nvarchar(max)
	     Declare @Exam8Name nvarchar(max)
	     Declare @Exam9Name nvarchar(max)
	     Declare @Exam10Name nvarchar(max)
	     Declare @Exam11Name nvarchar(max)
	     Declare @Exam12Name nvarchar(max)
	     Declare @IsMarksInDecimal bit
	     
	     
	     SET @ClassSubject=(SELECT SubjectName from #TempAllExam WHERE SRNO=@lCounter)
	     SET @ResultDetailId1=(SELECT ResultDetailId1 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @ResultDetailId2=(SELECT ResultDetailId2 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @ResultDetailId3=(SELECT ResultDetailId3 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @ResultDetailId4=(SELECT ResultDetailId4 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @ResultDetailId5=(SELECT ResultDetailId5 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @ResultDetailId6=(SELECT ResultDetailId6 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @ResultDetailId7=(SELECT ResultDetailId7 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @ResultDetailId8=(SELECT ResultDetailId8 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @ResultDetailId9=(SELECT ResultDetailId9 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @ResultDetailId10=(SELECT ResultDetailId10 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @ResultDetailId11=(SELECT ResultDetailId11 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @ResultDetailId12=(SELECT ResultDetailId12 from #TempAllExam WHERE SRNO=@lCounter)
	     
	     SET @Obtain1=(SELECT Obtain1 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @Obtain2=(SELECT Obtain2 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @Obtain3=(SELECT Obtain3 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @Obtain4=(SELECT Obtain4 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @Obtain5=(SELECT Obtain5 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @Obtain6=(SELECT Obtain6 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @Obtain7=(SELECT Obtain7 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @Obtain8=(SELECT Obtain8 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @Obtain9=(SELECT Obtain9 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @Obtain10=(SELECT Obtain10 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @Obtain11=(SELECT Obtain11 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @Obtain12=(SELECT Obtain12 from #TempAllExam WHERE SRNO=@lCounter)
	     
	     
	     
	     SET @Exam1Name=(SELECT Exam1Name from #TempAllExam WHERE SRNO=@lCounter)
	     SET @Exam2Name=(SELECT Exam2Name from #TempAllExam WHERE SRNO=@lCounter)
	     SET @Exam3Name=(SELECT Exam3Name from #TempAllExam WHERE SRNO=@lCounter)
	     SET @Exam4Name=(SELECT Exam4Name from #TempAllExam WHERE SRNO=@lCounter)
	     SET @Exam5Name=(SELECT Exam5Name from #TempAllExam WHERE SRNO=@lCounter)
	     SET @Exam6Name=(SELECT Exam6Name from #TempAllExam WHERE SRNO=@lCounter)
	     SET @Exam7Name=(SELECT Exam7Name from #TempAllExam WHERE SRNO=@lCounter)
	     SET @Exam8Name=(SELECT Exam8Name from #TempAllExam WHERE SRNO=@lCounter)
	     SET @Exam9Name=(SELECT Exam9Name from #TempAllExam WHERE SRNO=@lCounter)
	     SET @Exam10Name=(SELECT Exam10Name from #TempAllExam WHERE SRNO=@lCounter)
	     SET @Exam11Name=(SELECT Exam11Name from #TempAllExam WHERE SRNO=@lCounter)
	     SET @Exam12Name=(SELECT Exam12Name from #TempAllExam WHERE SRNO=@lCounter)
	     
	     SET @ExamMaximumMarks1=(SELECT MaximumMark1 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @ExamMaximumMarks2=(SELECT MaximumMark2 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @ExamMaximumMarks3=(SELECT MaximumMark3 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @ExamMaximumMarks4=(SELECT MaximumMark4 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @ExamMaximumMarks5=(SELECT MaximumMark5 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @ExamMaximumMarks6=(SELECT MaximumMark6 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @ExamMaximumMarks7=(SELECT MaximumMark7 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @ExamMaximumMarks8=(SELECT MaximumMark8 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @ExamMaximumMarks9=(SELECT MaximumMark9 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @ExamMaximumMarks10=(SELECT MaximumMark10 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @ExamMaximumMarks11=(SELECT MaximumMark11 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @ExamMaximumMarks12=(SELECT MaximumMark12 from #TempAllExam WHERE SRNO=@lCounter)
	     
	     
	     SET @IsMarksInDecimal=(SELECT IsMarksInDecimal from #TempAllExam WHERE SRNO=@lCounter)
	     --print @IsMarksInDecimal
	  IF(@rIsUseInStudent360 = 0)
	  BEGIN
	     IF(@HeaderCounter=0)
	     BEGIN
	      SET @thHtml='<th>Subjects</th>'
	      if(@Exam1Name<>'' OR @Exam1Name IS NOT NULL)	    
	      SET @thHtml=@thHtml+'<th>'+@Exam1Name+'</th>';   
	      if(@Exam2Name<>'' OR @Exam2Name IS NOT NULL)	    	    
	      SET @thHtml=@thHtml+'<th>'+@Exam2Name+'</th>';  
	       if(@Exam3Name<>'' OR @Exam3Name IS NOT NULL)	    	  	    
	      SET @thHtml=@thHtml+'<th>'+@Exam3Name+'</th>';   
	       if(@Exam4Name<>'' OR @Exam4Name IS NOT NULL)	  	    
	      SET @thHtml=@thHtml+'<th>'+@Exam4Name+'</th>';  
	      if(@Exam5Name<>'' OR @Exam5Name IS NOT NULL)	  	    	    
	      SET @thHtml=@thHtml+'<th>'+@Exam5Name+'</th>';  
	       if(@Exam6Name<>'' OR @Exam6Name IS NOT NULL)	  	  	    
	      SET @thHtml=@thHtml+'<th>'+@Exam6Name+'</th>';  
	        if(@Exam7Name<>'' OR @Exam7Name IS NOT NULL)	  	  	    	    
	      SET @thHtml=@thHtml+'<th>'+@Exam7Name+'</th>';  
	        if(@Exam8Name<>'' OR @Exam8Name IS NOT NULL)	  	  	    		    
	      SET @thHtml=@thHtml+'<th>'+@Exam8Name+'</th>';  
	       if(@Exam9Name<>'' OR @Exam9Name IS NOT NULL)	  	  	    
	      SET @thHtml=@thHtml+'<th>'+@Exam9Name+'</th>';  
	          if(@Exam10Name<>'' OR @Exam10Name IS NOT NULL)	  	  	    
	      SET @thHtml=@thHtml+'<th>'+@Exam10Name+'</th>'; 
	       if(@Exam11Name<>'' OR @Exam11Name IS NOT NULL)	  		    
	      SET @thHtml=@thHtml+'<th>'+@Exam11Name+'</th>';  
	      if(@Exam12Name<>'' OR @Exam12Name IS NOT NULL)	  		    
	      SET @thHtml=@thHtml+'<th>'+@Exam12Name+'</th>';  
	     END   
	     SET @HeaderCounter=@HeaderCounter+1;
	    
	     
	     SET @tdHtml='<td class=Sub width=200>'+@ClassSubject+'</td>';
	     
	     Declare @SetDecimalFunction nvarchar(max)
	    --print @IsMarksInDecimal
	     IF(@IsMarksInDecimal=1)
			 BEGIN
			  SET @SetDecimalFunction='onblur="javascript:return fnValidateDecimal(this,10,2)" onKeypress="javascript:return MaskDecimal(event,10,2)"';
		
			  
		 if(@ResultDetailId1<>'' OR @ResultDetailId1 IS NOT NULL)	    
	      SET @tdHtml=@tdHtml+'<td  IsTempSave=0 ResultDetailId='+@ResultDetailId1+' class=max_obtain_mark><div class=MaxMarks>Max Marks:'+CONVERT(varchar(20),@ExamMaximumMarks1)+'</div><div class=ObtainMarks>Obtain Marks:'+CONVERT(varchar(20),@Obtain1)+'</div><input  class=numbersOnly type=text ExamMaxMarks='+CONVERT(varchar(20),@ExamMaximumMarks1)+' value='+CONVERT(varchar(20),@Obtain1)+' '+@SetDecimalFunction+' MaxLength="100"></td>';
	      ELSE IF(@Exam1Name<>'' OR  @Exam1Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td>';
	      
	      if(@ResultDetailId2 <>'' OR @ResultDetailId2 IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td  IsTempSave=0 ResultDetailId='+@ResultDetailId2+' class=max_obtain_mark><div class=MaxMarks>Max Marks:'+CONVERT(varchar(20),@ExamMaximumMarks2)+'</div><div class=ObtainMarks>Obtain Marks:'+CONVERT(varchar(20),@Obtain2)+'</div><input class=numbersOnly type=text  ExamMaxMarks='+CONVERT(varchar(20),@ExamMaximumMarks2)+' value='+CONVERT(varchar(20),@Obtain2)+' '+@SetDecimalFunction+' MaxLength="100"></td>';
	       ELSE IF(@Exam2Name<>'' OR  @Exam2Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td>';
	      
	      if(@ResultDetailId3 <>'' OR @ResultDetailId3 IS NOT NULL)	    	
	      SET @tdHtml=@tdHtml+'<td  IsTempSave=0 ResultDetailId='+@ResultDetailId3+' class=max_obtain_mark><div class=MaxMarks>Max Marks:'+CONVERT(varchar(20),@ExamMaximumMarks3)+'</div><div class=ObtainMarks>Obtain Marks:'+CONVERT(varchar(20),@Obtain3)+'</div><input class=numbersOnly type=text  ExamMaxMarks='+CONVERT(varchar(20),@ExamMaximumMarks3)+' value='+CONVERT(varchar(20),@Obtain3)+' '+@SetDecimalFunction+' MaxLength="100"></td>';
	       ELSE IF(@Exam3Name<>'' OR  @Exam3Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td>';
	      
	      if(@ResultDetailId4 <>'' OR @ResultDetailId4 IS NOT NULL)	    		
	      SET @tdHtml=@tdHtml+'<td  IsTempSave=0 ResultDetailId='+@ResultDetailId4+' class=max_obtain_mark><div class=MaxMarks>Max Marks:'+CONVERT(varchar(20),@ExamMaximumMarks4)+'</div><div class=ObtainMarks>Obtain Marks:'+CONVERT(varchar(20),@Obtain4)+'</div><input class=numbersOnly type=text  ExamMaxMarks='+CONVERT(varchar(20),@ExamMaximumMarks4)+' value='+CONVERT(varchar(20),@Obtain4)+' '+@SetDecimalFunction+' MaxLength="100"></td>';
	       ELSE IF(@Exam4Name<>'' OR  @Exam4Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td>';
	      
	      if(@ResultDetailId5 <>'' OR @ResultDetailId5 IS NOT NULL)	    		
	      SET @tdHtml=@tdHtml+'<td  IsTempSave=0 ResultDetailId='+@ResultDetailId5+' class=max_obtain_mark><div class=MaxMarks>Max Marks:'+CONVERT(varchar(20),@ExamMaximumMarks5)+'</div><div class=ObtainMarks>Obtain Marks:'+CONVERT(varchar(20),@Obtain5)+'</div><input class=numbersOnly type=text  ExamMaxMarks='+CONVERT(varchar(20),@ExamMaximumMarks5)+' value='+CONVERT(varchar(20),@Obtain5)+' '+@SetDecimalFunction+' MaxLength="100"></td>';
	        ELSE IF(@Exam5Name<>'' OR  @Exam5Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td>';
	      
	       if(@ResultDetailId6 <>'' OR @ResultDetailId6 IS NOT NULL)	    			
	      SET @tdHtml=@tdHtml+'<td  IsTempSave=0 ResultDetailId='+@ResultDetailId6+' class=max_obtain_mark><div class=MaxMarks>Max Marks:'+CONVERT(varchar(20),@ExamMaximumMarks6)+'</div><div class=ObtainMarks>Obtain Marks:'+CONVERT(varchar(20),@Obtain6)+'</div><input class=numbersOnly type=text  ExamMaxMarks='+CONVERT(varchar(20),@ExamMaximumMarks6)+' value='+CONVERT(varchar(20),@Obtain6)+' '+@SetDecimalFunction+' MaxLength="100"></td>';
	     ELSE IF(@Exam6Name<>'' OR  @Exam6Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td>';
	      
	      if(@ResultDetailId7 <>'' OR @ResultDetailId7 IS NOT NULL)	    				
	      SET @tdHtml=@tdHtml+'<td  IsTempSave=0 ResultDetailId='+@ResultDetailId7+' class=max_obtain_mark><div class=MaxMarks>Max Marks:'+CONVERT(varchar(20),@ExamMaximumMarks7)+'</div><div class=ObtainMarks>Obtain Marks:'+CONVERT(varchar(20),@Obtain7)+'</div><input class=numbersOnly type=text  ExamMaxMarks='+CONVERT(varchar(20),@ExamMaximumMarks7)+' value='+CONVERT(varchar(20),@Obtain7)+' '+@SetDecimalFunction+' MaxLength="100"></td>';
	         ELSE IF(@Exam7Name<>'' OR  @Exam7Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td>';
	      
	      
	       if(@ResultDetailId8 <>'' OR @ResultDetailId8 IS NOT NULL)	
	      SET @tdHtml=@tdHtml+'<td  IsTempSave=0 ResultDetailId='+@ResultDetailId8+' class=max_obtain_mark><div class=MaxMarks>Max Marks:'+CONVERT(varchar(20),@ExamMaximumMarks8)+'</div><div class=ObtainMarks>Obtain Marks:'+CONVERT(varchar(20),@Obtain8)+'</div><input class=numbersOnly type=text  ExamMaxMarks='+CONVERT(varchar(20),@ExamMaximumMarks8)+' value='+CONVERT(varchar(20),@Obtain8)+' '+@SetDecimalFunction+' MaxLength="100"></td>';
	       ELSE IF(@Exam8Name<>'' OR  @Exam8Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td>';
	      
	        if(@ResultDetailId9 <>'' OR @ResultDetailId9 IS NOT NULL)		 
	      SET @tdHtml=@tdHtml+'<td  IsTempSave=0 ResultDetailId='+@ResultDetailId9+' class=max_obtain_mark><div class=MaxMarks>Max Marks:'+CONVERT(varchar(20),@ExamMaximumMarks9)+'</div><div class=ObtainMarks>Obtain Marks:'+CONVERT(varchar(20),@Obtain9)+'</div><input class=numbersOnly type=text ExamMaxMarks='+CONVERT(varchar(20),@ExamMaximumMarks9)+' value='+CONVERT(varchar(20),@Obtain9)+' '+@SetDecimalFunction+' MaxLength="100"></td>';
	       ELSE IF(@Exam9Name<>'' OR  @Exam9Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td>';
	      
	       if(@ResultDetailId10 <>'' OR @ResultDetailId10 IS NOT NULL)			
	      SET @tdHtml=@tdHtml+'<td  IsTempSave=0 ResultDetailId='+@ResultDetailId10+' class=max_obtain_mark><div class=MaxMarks>Max Marks:'+CONVERT(varchar(20),@ExamMaximumMarks10)+'</div><div class=ObtainMarks>Obtain Marks:'+CONVERT(varchar(20),@Obtain10)+'</div><input class=numbersOnly type=text  ExamMaxMarks='+CONVERT(varchar(20),@ExamMaximumMarks10)+' value='+CONVERT(varchar(20),@Obtain10)+' '+@SetDecimalFunction+' MaxLength="100"></td>';
	       ELSE IF(@Exam10Name<>'' OR  @Exam10Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td>';
	      
	        if(@ResultDetailId11 <>'' OR @ResultDetailId11 IS NOT NULL)				
	     SET @tdHtml=@tdHtml+'<td  IsTempSave=0 ResultDetailId='+@ResultDetailId11+' class=max_obtain_mark><div class=MaxMarks>Max Marks:'+CONVERT(varchar(20),@ExamMaximumMarks11)+'</div><div class=ObtainMarks>Obtain Marks:'+CONVERT(varchar(20),@Obtain11)+'</div><input class=numbersOnly type=text ExamMaxMarks='+CONVERT(varchar(20),@ExamMaximumMarks11)+' value='+CONVERT(varchar(20),@Obtain11)+' '+@SetDecimalFunction+' MaxLength="100"></td>';
	      ELSE IF(@Exam11Name<>'' OR  @Exam11Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td>';
	     
	      if(@ResultDetailId12 <>'' OR @ResultDetailId12 IS NOT NULL)			
	      SET @tdHtml=@tdHtml+'<td  IsTempSave=0 ResultDetailId='+@ResultDetailId12+' class=max_obtain_mark><div class=MaxMarks>Max Marks:'+CONVERT(varchar(20),@ExamMaximumMarks12)+'</div><div class=ObtainMarks>Obtain Marks:'+CONVERT(varchar(20),@Obtain12)+'</div><input class=numbersOnly type=text ExamMaxMarks='+CONVERT(varchar(20),@ExamMaximumMarks12)+' value='+CONVERT(varchar(20),@Obtain12)+' '+@SetDecimalFunction+' MaxLength="100"/></td>';
	      ELSE IF(@Exam12Name<>'' OR  @Exam12Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td>';
			  
			  
			  
			 END
	     ELSE
			 BEGIN
			   
			  SET @SetDecimalFunction='onblur="javascript:return fnValidateDecimal(this,10,0)" onKeypress="javascript:return MaskDecimal(event,10,0)"';
			  
			  
		if(@ResultDetailId1<>'' OR @ResultDetailId1 IS NOT NULL)	    
	      SET @tdHtml=@tdHtml+'<td IsTempSave=0 ResultDetailId='+@ResultDetailId1+' class=max_obtain_mark><div class=MaxMarks>Max Marks:'+CONVERT(varchar(20),@ExamMaximumMarks1)+'</div><div class=ObtainMarks>Obtain Marks:'+CONVERT(varchar(20),CAST(@Obtain1 AS int))+'</div><input class=numbersOnly type=text ExamMaxMarks='+CONVERT(varchar(20),@ExamMaximumMarks1)+' value='+CONVERT(varchar(20),CAST(@Obtain1 AS int))+' '+@SetDecimalFunction+' MaxLength="100"></td>';
	      ELSE IF(@Exam1Name<>'' OR  @Exam1Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td>';
	      
	      if(@ResultDetailId2 <>'' OR @ResultDetailId2 IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td IsTempSave=0 ResultDetailId='+@ResultDetailId2+' class=max_obtain_mark><div class=MaxMarks>Max Marks:'+CONVERT(varchar(20),@ExamMaximumMarks2)+'</div><div class=ObtainMarks>Obtain Marks:'+CONVERT(varchar(20),CAST(@Obtain2 AS int))+'</div><input class=numbersOnly type=text   ExamMaxMarks='+CONVERT(varchar(20),@ExamMaximumMarks2)+' value='+CONVERT(varchar(20),CAST(@Obtain2 AS int))+' '+@SetDecimalFunction+' MaxLength="100"></td>';
	       ELSE IF(@Exam2Name<>'' OR  @Exam2Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td>';
	      
	      if(@ResultDetailId3 <>'' OR @ResultDetailId3 IS NOT NULL)	    	
	      SET @tdHtml=@tdHtml+'<td IsTempSave=0  ResultDetailId='+@ResultDetailId3+' class=max_obtain_mark><div class=MaxMarks>Max Marks:'+CONVERT(varchar(20),@ExamMaximumMarks3)+'</div><div class=ObtainMarks>Obtain Marks:'+CONVERT(varchar(20),CAST(@Obtain3 AS int))+'</div><input class=numbersOnly type=text  ExamMaxMarks='+CONVERT(varchar(20),@ExamMaximumMarks3)+' value='+CONVERT(varchar(20),CAST(@Obtain3 AS int))+' '+@SetDecimalFunction+' MaxLength="100"></td>';
	       ELSE IF(@Exam3Name<>'' OR  @Exam3Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td>';
	      
	      if(@ResultDetailId4 <>'' OR @ResultDetailId4 IS NOT NULL)	    		
	      SET @tdHtml=@tdHtml+'<td IsTempSave=0 ResultDetailId='+@ResultDetailId4+' class=max_obtain_mark><div class=MaxMarks>Max Marks:'+CONVERT(varchar(20),@ExamMaximumMarks4)+'</div><div class=ObtainMarks>Obtain Marks:'+CONVERT(varchar(20),CAST(@Obtain4 AS int))+'</div><input class=numbersOnly type=text ExamMaxMarks='+CONVERT(varchar(20),@ExamMaximumMarks4)+' value='+CONVERT(varchar(20),CAST(@Obtain4 AS int))+' '+@SetDecimalFunction+' MaxLength="100"></td>';
	       ELSE IF(@Exam4Name<>'' OR  @Exam4Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td>';
	      
	      if(@ResultDetailId5 <>'' OR @ResultDetailId5 IS NOT NULL)	    		
	      SET @tdHtml=@tdHtml+'<td IsTempSave=0 ResultDetailId='+@ResultDetailId5+' class=max_obtain_mark><div class=MaxMarks>Max Marks:'+CONVERT(varchar(20),@ExamMaximumMarks5)+'</div><div class=ObtainMarks>Obtain Marks:'+CONVERT(varchar(20),CAST(@Obtain5 AS int))+'</div><input class=numbersOnly type=text ExamMaxMarks='+CONVERT(varchar(20),@ExamMaximumMarks5)+' value='+CONVERT(varchar(20),CAST(@Obtain5 AS int))+' '+@SetDecimalFunction+' MaxLength="100"></td>';
	        ELSE IF(@Exam5Name<>'' OR  @Exam5Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td>';
	      
	       if(@ResultDetailId6 <>'' OR @ResultDetailId6 IS NOT NULL)	    			
	      SET @tdHtml=@tdHtml+'<td IsTempSave=0  ResultDetailId='+@ResultDetailId6+' class=max_obtain_mark><div class=MaxMarks>Max Marks:'+CONVERT(varchar(20),@ExamMaximumMarks6)+'</div><div class=ObtainMarks>Obtain Marks:'+CONVERT(varchar(20),CAST(@Obtain6 AS int))+'</div><input class=numbersOnly type=text  ExamMaxMarks='+CONVERT(varchar(20),@ExamMaximumMarks6)+' value='+CONVERT(varchar(20),CAST(@Obtain6 AS int))+' '+@SetDecimalFunction+' MaxLength="100"></td>';
	     ELSE IF(@Exam6Name<>'' OR  @Exam6Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td>';
	      
	      if(@ResultDetailId7 <>'' OR @ResultDetailId7 IS NOT NULL)	    				
	      SET @tdHtml=@tdHtml+'<td IsTempSave=0  ResultDetailId='+@ResultDetailId7+' class=max_obtain_mark><div class=MaxMarks>Max Marks:'+CONVERT(varchar(20),@ExamMaximumMarks7)+'</div><div class=ObtainMarks>Obtain Marks:'+CONVERT(varchar(20),CAST(@Obtain7 AS int))+'</div><input class=numbersOnly type=text ExamMaxMarks='+CONVERT(varchar(20),@ExamMaximumMarks7)+' value='+CONVERT(varchar(20),CAST(@Obtain7 AS int))+' '+@SetDecimalFunction+' MaxLength="100"></td>';
	         ELSE IF(@Exam7Name<>'' OR  @Exam7Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td>';
	      
	      
	       if(@ResultDetailId8 <>'' OR @ResultDetailId8 IS NOT NULL)	
	      SET @tdHtml=@tdHtml+'<td IsTempSave=0  ResultDetailId='+@ResultDetailId8+' class=max_obtain_mark><div class=MaxMarks>Max Marks:'+CONVERT(varchar(20),@ExamMaximumMarks8)+'</div><div class=ObtainMarks>Obtain Marks:'+CONVERT(varchar(20),CAST(@Obtain8 AS int))+'</div><input class=numbersOnly type=text ExamMaxMarks='+CONVERT(varchar(20),@ExamMaximumMarks8)+' value='+CONVERT(varchar(20),CAST(@Obtain8 AS int))+' '+@SetDecimalFunction+' MaxLength="100"></td>';
	       ELSE IF(@Exam8Name<>'' OR  @Exam8Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td>';
	      
	        if(@ResultDetailId9 <>'' OR @ResultDetailId9 IS NOT NULL)		 
	      SET @tdHtml=@tdHtml+'<td IsTempSave=0  ResultDetailId='+@ResultDetailId9+' class=max_obtain_mark><div class=MaxMarks>Max Marks:'+CONVERT(varchar(20),@ExamMaximumMarks9)+'</div><div class=ObtainMarks>Obtain Marks:'+CONVERT(varchar(20),CAST(@Obtain9 AS int))+'</div><input class=numbersOnly type=text ExamMaxMarks='+CONVERT(varchar(20),@ExamMaximumMarks9)+' value='+CONVERT(varchar(20),CAST(@Obtain9 AS int))+' '+@SetDecimalFunction+' MaxLength="100"></td>';
	       ELSE IF(@Exam9Name<>'' OR  @Exam9Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td>';
	      
	       if(@ResultDetailId10 <>'' OR @ResultDetailId10 IS NOT NULL)			
	      SET @tdHtml=@tdHtml+'<td IsTempSave=0 ResultDetailId='+@ResultDetailId10+' class=max_obtain_mark><div class=MaxMarks>Max Marks:'+CONVERT(varchar(20),@ExamMaximumMarks10)+'</div><div class=ObtainMarks>Obtain Marks:'+CONVERT(varchar(20),CAST(@Obtain10 AS int))+'</div><input class=numbersOnly type=text  ExamMaxMarks='+CONVERT(varchar(20),@ExamMaximumMarks10)+' value='+CONVERT(varchar(20),CAST(@Obtain10 AS int))+' '+@SetDecimalFunction+' MaxLength="100"></td>';
	       ELSE IF(@Exam10Name<>'' OR  @Exam10Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td>';
	      
	        if(@ResultDetailId11 <>'' OR @ResultDetailId11 IS NOT NULL)				
	     SET @tdHtml=@tdHtml+'<td IsTempSave=0 ResultDetailId='+@ResultDetailId11+' class=max_obtain_mark><div class=MaxMarks>Max Marks:'+CONVERT(varchar(20),@ExamMaximumMarks11)+'</div><div class=ObtainMarks>Obtain Marks:'+CONVERT(varchar(20),CAST(@Obtain11 AS int))+'</div><input class=numbersOnly type=text ExamMaxMarks='+CONVERT(varchar(20),@ExamMaximumMarks11)+' value='+CONVERT(varchar(20),CAST(@Obtain11 AS int))+' '+@SetDecimalFunction+' MaxLength="100"></td>';
	      ELSE IF(@Exam11Name<>'' OR  @Exam11Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td>';
	     
	      if(@ResultDetailId12 <>'' OR @ResultDetailId12 IS NOT NULL)			
	      SET @tdHtml=@tdHtml+'<td IsTempSave=0 ResultDetailId='+@ResultDetailId12+' class=max_obtain_mark><div class=MaxMarks>Max Marks:'+CONVERT(varchar(20),@ExamMaximumMarks12)+'</div><div class=ObtainMarks>Obtain Marks:'+CONVERT(varchar(20),CAST(@Obtain12 AS int))+'</div><input class=numbersOnly type=text ExamMaxMarks='+CONVERT(varchar(20),@ExamMaximumMarks12)+' value='+CONVERT(varchar(20),CAST(@Obtain12 AS int))+' '+@SetDecimalFunction+' MaxLength="100"/></td>';
	      ELSE IF(@Exam12Name<>'' OR  @Exam12Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td>';
			  
			  
			 END
	     
	    SET @trHtml= '<tr>'+@tdHtml+'</tr>';
	    SET @FinalHtml=@FinalHtml+@trHtml;
       END
	   ELSE
	   BEGIN
	    IF(@HeaderCounter=0)
	     BEGIN
	      SET @thHtml='<th>Subjects</th>'
	      if(@Exam1Name<>'' OR @Exam1Name IS NOT NULL)	    
	      SET @thHtml=@thHtml+'<th colspan="2">'+@Exam1Name+'</th>';   
	      if(@Exam2Name<>'' OR @Exam2Name IS NOT NULL)	    	    
	      SET @thHtml=@thHtml+'<th colspan="2">'+@Exam2Name+'</th>';  
	       if(@Exam3Name<>'' OR @Exam3Name IS NOT NULL)	    	  	    
	      SET @thHtml=@thHtml+'<th colspan="2">'+@Exam3Name+'</th>';   
	       if(@Exam4Name<>'' OR @Exam4Name IS NOT NULL)	  	    
	      SET @thHtml=@thHtml+'<th colspan="2">'+@Exam4Name+'</th>';  
	      if(@Exam5Name<>'' OR @Exam5Name IS NOT NULL)	  	    	    
	      SET @thHtml=@thHtml+'<th colspan="2">'+@Exam5Name+'</th>';  
	       if(@Exam6Name<>'' OR @Exam6Name IS NOT NULL)	  	  	    
	      SET @thHtml=@thHtml+'<th colspan="2">'+@Exam6Name+'</th>';  
	        if(@Exam7Name<>'' OR @Exam7Name IS NOT NULL)	  	  	    	    
	      SET @thHtml=@thHtml+'<th colspan="2">'+@Exam7Name+'</th>';  
	        if(@Exam8Name<>'' OR @Exam8Name IS NOT NULL)	  	  	    		    
	      SET @thHtml=@thHtml+'<th colspan="2">'+@Exam8Name+'</th>';  
	       if(@Exam9Name<>'' OR @Exam9Name IS NOT NULL)	  	  	    
	      SET @thHtml=@thHtml+'<th colspan="2">'+@Exam9Name+'</th>';  
	          if(@Exam10Name<>'' OR @Exam10Name IS NOT NULL)	  	  	    
	      SET @thHtml=@thHtml+'<th colspan="2">'+@Exam10Name+'</th>'; 
	       if(@Exam11Name<>'' OR @Exam11Name IS NOT NULL)	  		    
	      SET @thHtml=@thHtml+'<th colspan="2">'+@Exam11Name+'</th>';  
	      if(@Exam12Name<>'' OR @Exam12Name IS NOT NULL)	  		    
	      SET @thHtml=@thHtml+'<th colspan="2">'+@Exam12Name+'</th>';  

		  if(@Exam1Name<>'' OR @Exam1Name IS NOT NULL OR @Exam2Name<>'' OR @Exam2Name IS NOT NULL OR @Exam3Name<>'' OR @Exam3Name IS NOT NULL OR
		     @Exam4Name<>'' OR @Exam4Name IS NOT NULL OR @Exam5Name<>'' OR @Exam5Name IS NOT NULL OR @Exam6Name<>'' OR @Exam6Name IS NOT NULL OR
			 @Exam7Name<>'' OR @Exam7Name IS NOT NULL OR @Exam8Name<>'' OR @Exam8Name IS NOT NULL OR @Exam9Name<>'' OR @Exam9Name IS NOT NULL OR
			 @Exam10Name<>'' OR @Exam10Name IS NOT NULL OR @Exam11Name<>'' OR @Exam11Name IS NOT NULL OR @Exam12Name<>'' OR @Exam12Name IS NOT NULL)
			 BEGIN
			 SET @thHtml=@thHtml+'<tr><td></td>';
				  if(@Exam1Name<>'' OR @Exam1Name IS NOT NULL)	    
					SET @thHtml=@thHtml+'<td>Max</td><td>Obt</td>';
				  if(@Exam2Name<>'' OR @Exam2Name IS NOT NULL)	    
					SET @thHtml=@thHtml+'<td>Max</td><td>Obt</td>';
				  if(@Exam3Name<>'' OR @Exam3Name IS NOT NULL)	    
					SET @thHtml=@thHtml+'<td>Max</td><td>Obt</td>';
				  if(@Exam4Name<>'' OR @Exam4Name IS NOT NULL)	    
					SET @thHtml=@thHtml+'<td>Max</td><td>Obt</td>';
				  if(@Exam5Name<>'' OR @Exam5Name IS NOT NULL)	    
					SET @thHtml=@thHtml+'<td>Max</td><td>Obt</td>';
				  if(@Exam6Name<>'' OR @Exam6Name IS NOT NULL)	    
					SET @thHtml=@thHtml+'<td>Max</td><td>Obt</td>';
				  if(@Exam7Name<>'' OR @Exam7Name IS NOT NULL)	    
					SET @thHtml=@thHtml+'<td>Max</td><td>Obt</td>';
				  if(@Exam8Name<>'' OR @Exam8Name IS NOT NULL)	    
					SET @thHtml=@thHtml+'<td>Max</td><td>Obt</td>';
				  if(@Exam9Name<>'' OR @Exam9Name IS NOT NULL)	    
					SET @thHtml=@thHtml+'<td>Max</td><td>Obt</td>';
				  if(@Exam10Name<>'' OR @Exam10Name IS NOT NULL)	    
					SET @thHtml=@thHtml+'<td>Max</td><td>Obt</td>';
				  if(@Exam11Name<>'' OR @Exam11Name IS NOT NULL)	    
					SET @thHtml=@thHtml+'<td>Max</td><td>Obt</td>';
				  if(@Exam12Name<>'' OR @Exam12Name IS NOT NULL)	    
					SET @thHtml=@thHtml+'<td>Max</td><td>Obt</td>';
				 
				 SET @thHtml=@thHtml+'</tr>';
			 END

	     END   
	     SET @HeaderCounter=@HeaderCounter+1;
	    
	     
	     SET @tdHtml='<td class=Sub width=200>'+@ClassSubject+'</td>';
	     
	     Declare @SetDecimalFunction1 nvarchar(max)
	    --print @IsMarksInDecimal
	     IF(@IsMarksInDecimal=1)
			 BEGIN
			  SET @SetDecimalFunction1='onblur="javascript:return fnValidateDecimal(this,10,2)" onKeypress="javascript:return MaskDecimal(event,10,2)"';
		
			  
		 if(@ResultDetailId1<>'' OR @ResultDetailId1 IS NOT NULL)	    
	      SET @tdHtml=@tdHtml
		  +'<td  IsTempSave=0 ResultDetailId='+@ResultDetailId1+' class=max_obtain_mark>
		  <div class=MaxMarks>'+CONVERT(varchar(20),@ExamMaximumMarks1)+'</div></td>
		  <td><div class=ObtainMarks>'+CONVERT(varchar(20),@Obtain1)+'</div></td>';
	      ELSE IF(@Exam1Name<>'' OR  @Exam1Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td><td></td>';
	      
	      if(@ResultDetailId2 <>'' OR @ResultDetailId2 IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td  IsTempSave=0 ResultDetailId='+@ResultDetailId2+' class=max_obtain_mark>
		  <div class=MaxMarks>'+CONVERT(varchar(20),@ExamMaximumMarks2)+'</div></td>
		  <td><div class=ObtainMarks>'+CONVERT(varchar(20),@Obtain2)+'</div></td>';
	       ELSE IF(@Exam2Name<>'' OR  @Exam2Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td><td></td>';
	      
	      if(@ResultDetailId3 <>'' OR @ResultDetailId3 IS NOT NULL)	    	
	      SET @tdHtml=@tdHtml+'<td  IsTempSave=0 ResultDetailId='+@ResultDetailId3+' class=max_obtain_mark>
		  <div class=MaxMarks>'+CONVERT(varchar(20),@ExamMaximumMarks3)+'</div></td>
		  <td><div class=ObtainMarks>'+CONVERT(varchar(20),@Obtain3)+'</div></td>';
	       ELSE IF(@Exam3Name<>'' OR  @Exam3Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td><td></td>';
	      
	      if(@ResultDetailId4 <>'' OR @ResultDetailId4 IS NOT NULL)	    		
	      SET @tdHtml=@tdHtml+'<td  IsTempSave=0 ResultDetailId='+@ResultDetailId4+' class=max_obtain_mark>
		  <div class=MaxMarks>'+CONVERT(varchar(20),@ExamMaximumMarks4)+'</div></td>
		  <td><div class=ObtainMarks>'+CONVERT(varchar(20),@Obtain4)+'</div></td>';
	       ELSE IF(@Exam4Name<>'' OR  @Exam4Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td><td></td>';
	      
	      if(@ResultDetailId5 <>'' OR @ResultDetailId5 IS NOT NULL)	    		
	      SET @tdHtml=@tdHtml+'<td  IsTempSave=0 ResultDetailId='+@ResultDetailId5+' class=max_obtain_mark>
		  <div class=MaxMarks>'+CONVERT(varchar(20),@ExamMaximumMarks5)+'</div></td>
		  <td><div class=ObtainMarks>'+CONVERT(varchar(20),@Obtain5)+'</div></td>';
	        ELSE IF(@Exam5Name<>'' OR  @Exam5Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td><td></td>';
	      
	       if(@ResultDetailId6 <>'' OR @ResultDetailId6 IS NOT NULL)	    			
	      SET @tdHtml=@tdHtml+'<td  IsTempSave=0 ResultDetailId='+@ResultDetailId6+' class=max_obtain_mark>
		  <div class=MaxMarks>'+CONVERT(varchar(20),@ExamMaximumMarks6)+'</div></td>
		  <td><div class=ObtainMarks>'+CONVERT(varchar(20),@Obtain6)+'</div></td>';
	     ELSE IF(@Exam6Name<>'' OR  @Exam6Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td><td></td>';
	      
	      if(@ResultDetailId7 <>'' OR @ResultDetailId7 IS NOT NULL)	    				
	      SET @tdHtml=@tdHtml+'<td  IsTempSave=0 ResultDetailId='+@ResultDetailId7+' class=max_obtain_mark>
		  <div class=MaxMarks>'+CONVERT(varchar(20),@ExamMaximumMarks7)+'</div></td>
		  <td><div class=ObtainMarks>'+CONVERT(varchar(20),@Obtain7)+'</div></td>';
	         ELSE IF(@Exam7Name<>'' OR  @Exam7Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td><td></td>';
	      
	      
	       if(@ResultDetailId8 <>'' OR @ResultDetailId8 IS NOT NULL)	
	      SET @tdHtml=@tdHtml+'<td  IsTempSave=0 ResultDetailId='+@ResultDetailId8+' class=max_obtain_mark>
		  <div class=MaxMarks>'+CONVERT(varchar(20),@ExamMaximumMarks8)+'</div></td>
		  <td><div class=ObtainMarks>'+CONVERT(varchar(20),@Obtain8)+'</div></td>';
	       ELSE IF(@Exam8Name<>'' OR  @Exam8Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td><td></td>';
	      
	        if(@ResultDetailId9 <>'' OR @ResultDetailId9 IS NOT NULL)		 
	      SET @tdHtml=@tdHtml+'<td  IsTempSave=0 ResultDetailId='+@ResultDetailId9+' class=max_obtain_mark>
		  <div class=MaxMarks>'+CONVERT(varchar(20),@ExamMaximumMarks9)+'</div></td>
		  <td><div class=ObtainMarks>'+CONVERT(varchar(20),@Obtain9)+'</div></td>';
	       ELSE IF(@Exam9Name<>'' OR  @Exam9Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td><td></td>';
	      
	       if(@ResultDetailId10 <>'' OR @ResultDetailId10 IS NOT NULL)			
	       SET @tdHtml=@tdHtml+'<td  IsTempSave=0 ResultDetailId='+@ResultDetailId10+' class=max_obtain_mark>
		  <div class=MaxMarks>'+CONVERT(varchar(20),@ExamMaximumMarks10)+'</div></td>
		  <td><div class=ObtainMarks>'+CONVERT(varchar(20),@Obtain10)+'</div></td>';
	       ELSE IF(@Exam10Name<>'' OR  @Exam10Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td><td></td>';
	      
	        if(@ResultDetailId11 <>'' OR @ResultDetailId11 IS NOT NULL)				
	      SET @tdHtml=@tdHtml+'<td  IsTempSave=0 ResultDetailId='+@ResultDetailId11+' class=max_obtain_mark>
		  <div class=MaxMarks>'+CONVERT(varchar(20),@ExamMaximumMarks11)+'</div></td>
		  <td><div class=ObtainMarks>'+CONVERT(varchar(20),@Obtain11)+'</div></td>';
	      ELSE IF(@Exam11Name<>'' OR  @Exam11Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td><td></td>';
	     
	      if(@ResultDetailId12 <>'' OR @ResultDetailId12 IS NOT NULL)			
	      SET @tdHtml=@tdHtml+'<td  IsTempSave=0 ResultDetailId='+@ResultDetailId12+' class=max_obtain_mark>
		  <div class=MaxMarks>'+CONVERT(varchar(20),@ExamMaximumMarks12)+'</div></td>
		  <td><div class=ObtainMarks>'+CONVERT(varchar(20),@Obtain12)+'</div></td>';
	      ELSE IF(@Exam12Name<>'' OR  @Exam12Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td><td></td>';
			  
			  
			  
			 END
	     ELSE
			 BEGIN
			   
			  SET @SetDecimalFunction1='onblur="javascript:return fnValidateDecimal(this,10,0)" onKeypress="javascript:return MaskDecimal(event,10,0)"';
			  
			  
		if(@ResultDetailId1<>'' OR @ResultDetailId1 IS NOT NULL)	    
	      SET @tdHtml=@tdHtml
		  +'<td  IsTempSave=0 ResultDetailId='+@ResultDetailId1+' class=max_obtain_mark>
		  <div class=MaxMarks>'+CONVERT(varchar(20),@ExamMaximumMarks1)+'</div></td>
		  <td><div class=ObtainMarks>'+CONVERT(varchar(20),@Obtain1)+'</div></td>';
	      ELSE IF(@Exam1Name<>'' OR  @Exam1Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td><td></td>';
	      
	      if(@ResultDetailId2 <>'' OR @ResultDetailId2 IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td  IsTempSave=0 ResultDetailId='+@ResultDetailId2+' class=max_obtain_mark>
		  <div class=MaxMarks>'+CONVERT(varchar(20),@ExamMaximumMarks2)+'</div></td>
		  <td><div class=ObtainMarks>'+CONVERT(varchar(20),@Obtain2)+'</div></td>';
	       ELSE IF(@Exam2Name<>'' OR  @Exam2Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td><td></td>';
	      
	      if(@ResultDetailId3 <>'' OR @ResultDetailId3 IS NOT NULL)	    	
	      SET @tdHtml=@tdHtml+'<td  IsTempSave=0 ResultDetailId='+@ResultDetailId3+' class=max_obtain_mark>
		  <div class=MaxMarks>'+CONVERT(varchar(20),@ExamMaximumMarks3)+'</div></td>
		  <td><div class=ObtainMarks>'+CONVERT(varchar(20),@Obtain3)+'</div></td>';
	       ELSE IF(@Exam3Name<>'' OR  @Exam3Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td><td></td>';
	      
	      if(@ResultDetailId4 <>'' OR @ResultDetailId4 IS NOT NULL)	    		
	      SET @tdHtml=@tdHtml+'<td  IsTempSave=0 ResultDetailId='+@ResultDetailId4+' class=max_obtain_mark>
		  <div class=MaxMarks>'+CONVERT(varchar(20),@ExamMaximumMarks4)+'</div></td>
		  <td><div class=ObtainMarks>'+CONVERT(varchar(20),@Obtain4)+'</div></td>';
	       ELSE IF(@Exam4Name<>'' OR  @Exam4Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td><td></td>';
	      
	      if(@ResultDetailId5 <>'' OR @ResultDetailId5 IS NOT NULL)	    		
	      SET @tdHtml=@tdHtml+'<td  IsTempSave=0 ResultDetailId='+@ResultDetailId5+' class=max_obtain_mark>
		  <div class=MaxMarks>'+CONVERT(varchar(20),@ExamMaximumMarks5)+'</div></td>
		  <td><div class=ObtainMarks>'+CONVERT(varchar(20),@Obtain5)+'</div></td>';
	        ELSE IF(@Exam5Name<>'' OR  @Exam5Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td><td></td>';
	      
	       if(@ResultDetailId6 <>'' OR @ResultDetailId6 IS NOT NULL)	    			
	      SET @tdHtml=@tdHtml+'<td  IsTempSave=0 ResultDetailId='+@ResultDetailId6+' class=max_obtain_mark>
		  <div class=MaxMarks>'+CONVERT(varchar(20),@ExamMaximumMarks6)+'</div></td>
		  <td><div class=ObtainMarks>'+CONVERT(varchar(20),@Obtain6)+'</div></td>';
	     ELSE IF(@Exam6Name<>'' OR  @Exam6Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td><td></td>';
	      
	      if(@ResultDetailId7 <>'' OR @ResultDetailId7 IS NOT NULL)	    				
	      SET @tdHtml=@tdHtml+'<td  IsTempSave=0 ResultDetailId='+@ResultDetailId7+' class=max_obtain_mark>
		  <div class=MaxMarks>'+CONVERT(varchar(20),@ExamMaximumMarks7)+'</div></td>
		  <td><div class=ObtainMarks>'+CONVERT(varchar(20),@Obtain7)+'</div></td>';
	         ELSE IF(@Exam7Name<>'' OR  @Exam7Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td><td></td>';
	      
	      
	       if(@ResultDetailId8 <>'' OR @ResultDetailId8 IS NOT NULL)	
	      SET @tdHtml=@tdHtml+'<td  IsTempSave=0 ResultDetailId='+@ResultDetailId8+' class=max_obtain_mark>
		  <div class=MaxMarks>'+CONVERT(varchar(20),@ExamMaximumMarks8)+'</div></td>
		  <td><div class=ObtainMarks>'+CONVERT(varchar(20),@Obtain8)+'</div></td>';
	       ELSE IF(@Exam8Name<>'' OR  @Exam8Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td><td></td>';
	      
	        if(@ResultDetailId9 <>'' OR @ResultDetailId9 IS NOT NULL)		 
	      SET @tdHtml=@tdHtml+'<td  IsTempSave=0 ResultDetailId='+@ResultDetailId9+' class=max_obtain_mark>
		  <div class=MaxMarks>'+CONVERT(varchar(20),@ExamMaximumMarks9)+'</div></td>
		  <td><div class=ObtainMarks>'+CONVERT(varchar(20),@Obtain9)+'</div></td>';
	       ELSE IF(@Exam9Name<>'' OR  @Exam9Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td><td></td>';
	      
	       if(@ResultDetailId10 <>'' OR @ResultDetailId10 IS NOT NULL)			
	       SET @tdHtml=@tdHtml+'<td  IsTempSave=0 ResultDetailId='+@ResultDetailId10+' class=max_obtain_mark>
		  <div class=MaxMarks>'+CONVERT(varchar(20),@ExamMaximumMarks10)+'</div></td>
		  <td><div class=ObtainMarks>'+CONVERT(varchar(20),@Obtain10)+'</div></td>';
	       ELSE IF(@Exam10Name<>'' OR  @Exam10Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td><td></td>';
	      
	        if(@ResultDetailId11 <>'' OR @ResultDetailId11 IS NOT NULL)				
	      SET @tdHtml=@tdHtml+'<td  IsTempSave=0 ResultDetailId='+@ResultDetailId11+' class=max_obtain_mark>
		  <div class=MaxMarks>'+CONVERT(varchar(20),@ExamMaximumMarks11)+'</div></td>
		  <td><div class=ObtainMarks>'+CONVERT(varchar(20),@Obtain11)+'</div></td>';
	      ELSE IF(@Exam11Name<>'' OR  @Exam11Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td><td></td>';
	     
	      if(@ResultDetailId12 <>'' OR @ResultDetailId12 IS NOT NULL)			
	      SET @tdHtml=@tdHtml+'<td  IsTempSave=0 ResultDetailId='+@ResultDetailId12+' class=max_obtain_mark>
		  <div class=MaxMarks>'+CONVERT(varchar(20),@ExamMaximumMarks12)+'</div></td>
		  <td><div class=ObtainMarks>'+CONVERT(varchar(20),@Obtain12)+'</div></td>';
	      ELSE IF(@Exam12Name<>'' OR  @Exam12Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td><td></td>';
			  
			  
			 END
	     
	    SET @trHtml= '<tr>'+@tdHtml+'</tr>';
	    SET @FinalHtml=@FinalHtml+@trHtml;
	   END
	     SET @lCounter = @lCounter + 1
	END
	 --print @thHtml
	select '<table id="ExamDataTbl" class="table table-striped table-bordered table-hover" style=position:relative><tr>'+@thHtml+'</tr>'+@FinalHtml+'</table>' AS Html; 
	--if(@FinalHtml IS NOT NULL and @FinalHtml <> '')	    
 --   select '<table  id="ExamDataTbl" class="table table-striped table-bordered table-hover" ><tr>'+@thHtml+'</tr>'+@FinalHtml+'</table>' AS Html; 
 --   ELSE
 --   select '<table id="ExamDataTbl" class="table table-striped table-bordered table-hover"><tr>No record found.</tr></table>' AS Html; 
			
	drop table #tempcombineExam
	Drop table #TempAllExam
	END

--	SELECT @rBuilder1,@rBuilder2, T.* FROM sAssessment.tTempAllExam T
--end
GO
PRINT N'Altering [sAssessment].[pRptResultAnalysisBatchClassandSubjectWise]...';


GO
ALTER PROCEDURE [sAssessment].[pRptResultAnalysisBatchClassandSubjectWise]
	 
   	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rDepartmentId int=0,
	 @rExamSubGroupId int ,
	 @rBatchId1 int,
	 @rBatchId2 int,
	 --@rClassStatusId int=0 ,
	 @rIsDisplayAvgTotal bit=0,
	 @rIsDetail bit=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			
BEGIN 
 
	BEGIN

	SELECT 
			@rIsDisplayAvgTotal AS IsDisplayAvgTotal,
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			ESGM.Id AS ExamId,
			ESGM.Title AS Exam,
			BM.Id As BatchId,
			BM.Title As BatchName,
			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,
			ISNULL(SR.PresentDays,0)AS PresentDays,
			ISNULL(SR.TotalDays,0)AS TotalDays,
			(CASE WHEN @rIsDisplayAvgTotal=1 THEN ROUND(((RD.Obtain*100)/ED.Maximum),0) ELSE RD.Obtain END)As AvgTotal,
			@rIsDetail AS IsDetail
	
	FROM 	sAssessment.tResultDetail RD
			INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
			INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
			INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId	
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId		
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId					 
			INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId 
			INNER JOIN sSetup.tBatchMaster BM ON A.BatchId = BM.Id 
			LEFT JOIN sAssessment.tStudentRemark SR ON SR.AcademicId = A.Id AND SR.ExamId=EM.Id
			INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
			INNER JOIN sSetup.tOrganizationMaster OM ON StuM.OrgId = OM.Id
		
	WHERE 
			
		EM.BatchId = @rBatchId1
		AND ((CM.DepartmentId = @rDepartmentId) OR (@rDepartmentId=0))
		AND	A.BatchId = @rBatchId1
		AND ESGM.Id = @rExamSubGroupId
		AND StuM.StatusId = 1

UNION 
	
		SELECT 
			@rIsDisplayAvgTotal AS IsDisplayAvgTotal,
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			ESGM.Id AS ExamId,
			ESGM.Title AS Exam,
			BM.Id As BatchId,
			BM.Title As BatchName,
			StuM.Code,
			[sStudent].[fStudentNameGet](StuM.FirstName , StuM.MiddleName, StuM.LastName,OM.StudentNameFormatId ) AS Name,
			A.RollNo,
			--temp.tempAcademicId,
			A.Id AS AcademicId,
			RD.Obtain,
			R.ResultStatus,
			CM.DisplayTitle AS Class,
			Cm.Id AS ClassId,
			DM.DisplayTitle AS Division,
			DM.Id AS DivisionId,
			DM.OrderIndex AS DivisinOrderIndex,
			R.TotalMarks,
			R.TotalObtain,
			R.Percentage,
			R.RankNumber,
			R.ResultGrade,
			SM.Title AS ClassSubject,
			RD.Id AS ResultDetailId,
			R.Id AS ResultId,
			CS.Id AS SubjectId,
			ED.Maximum,
			RD.SubjectGrade, 
			
			EM.IsMarksInDecimal,
			--SM.OrderIndex AS SubjectCode,
			SM.Code AS SubjectCode,
			ED.DisplayOrder AS SubjectOrderIndex,
			CM.OrderIndex AS ClassOrderIndex,
			RD.IsPresent,
			EM.IsGrade,
			EM.IsPercentage,
			EM.IsResultStatus,
			EM.IsRankNo ,
			ED.Minimum,
			RD.GraceMark,
			EM.DecimalFormat,
			CS.IsOptional,
			ISNULL(SR.PresentDays,0)AS PresentDays,
			ISNULL(SR.TotalDays,0)AS TotalDays,
			(CASE WHEN @rIsDisplayAvgTotal=1 THEN ROUND(((RD.Obtain*100)/ED.Maximum),0) ELSE RD.Obtain END)As AvgTotal,
			@rIsDetail AS IsDetail

			--2 As ExamNo
	FROM 
				sAssessment.tResultDetail RD
			INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
			INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
			INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId	
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId		
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId					 
			INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId 
			INNER JOIN sSetup.tBatchMaster BM ON A.BatchId = BM.Id 
			LEFT JOIN sAssessment.tStudentRemark SR ON SR.AcademicId = A.Id AND SR.ExamId=EM.Id
			INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
			INNER JOIN sSetup.tOrganizationMaster OM ON StuM.OrgId = OM.Id
	WHERE 
		   EM.BatchId = @rBatchId2
		   AND ((CM.DepartmentId = @rDepartmentId) OR (@rDepartmentId=0))
		   AND	A.BatchId = @rBatchId2
		   AND ESGM.Id = @rExamSubGroupId
		   AND StuM.StatusId = 1
		order by A.RollNo,ClassOrderIndex
	--	SELECT * FROM #temp
	--RETURN 
		END
		--DROP Table #Temp_Academic
		--DROP Table #Temp_StudentId
		
			--SELECT 
			--0 AS IsDisplayAvgTotal,
			--'' AS Builder1,
			--'' AS Builder2,
			--0 AS ExamId,
			--'' AS Exam,
			--0 As BatchId,
			--'' As BatchName,
			--''  AS Code,
			--'' AS Name,
			--0 AS RollNo,
			----temp.tempAcademicId,
			--0 AS AcademicId,
			--0 AS Obtain,
			--'' AS ResultStatus,
			--'' AS Class,
			--0  AS ClassId,
			--'' AS Division,
			--0 AS DivisionId,
			--0 AS DivisinOrderIndex,
			--0 AS TotalMarks,
			--0 AS TotalObtain,
			--0 AS Percentage,
			--0 AS RankNumber,
			--'' AS ResultGrade,
			--'' AS ClassSubject,
			--0 AS ResultDetailId,
			--0 AS ResultId,
			--0 AS SubjectId,
			--0 AS Maximum,
			--'' AS SubjectGrade, 
			
			--0 AS IsMarksInDecimal,
			----SM.OrderIndex AS SubjectCode,
			--'' AS SubjectCode,
			--0 AS SubjectOrderIndex,
			--0 AS ClassOrderIndex,
			--0 AS IsPresent,
			-- 0 AS IsGrade,
			--0 AS IsPercentage,
			--0 AS IsResultStatus,
			--0 AS IsRankNo ,
			--0 AS  Minimum,
			--0 AS GraceMark,
			--'' AS DecimalFormat,
			--0 AS IsOptional,
			--0 AS PresentDays,
			--0 AS TotalDays,
			--0 As AvgTotal,
			--0 AS IsDetail
END
GO
PRINT N'Altering [sAssessment].[pRptResultAnalysisBatchStudentWise]...';


GO


ALTER PROCEDURE [sAssessment].[pRptResultAnalysisBatchStudentWise]
	 
   	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rClassId int,
	 @rDivisionId int,
	 @rCode nvarchar(20),
	 @rFromRollNo int =0,
	 @rToRollNo int =0,
	 @rStatusId int = 0,
	 @rResultStatus nvarchar(20)='',
	 @rDepartmentId int=0,
	 @rExamId1 int ,
	 @rExamId2 int ,
	 @rBatchId1 int,
	 @rBatchId2 int,
	 @rClassStatusId int=0 ,
	 @rIsDisplayAvgTotal bit=0,
	 @rIsDetail bit=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			
BEGIN 
 
	BEGIN
	
	CREATE TABLE #Temp_StudentId (StudentId bigint);
	INSERT INTO #Temp_StudentId
	SELECT A1.StudentId From sStudent.tAcademic A1 
	INNER JOIN
	sStudent.tAcademic A2 ON A1.StudentId = A2.StudentId 
	INNER JOIN sStudent.tStudentMaster SM ON SM.Id = A1.StudentId
	WHERE A1.BatchId =  @rBatchId1 AND A2.BatchId = @rBatchId2
	AND (A1.ClassId=@rClassId OR @rClassId=0) 
	AND (A1.DivisionId=@rDivisionId OR @rDivisionId=0)
	AND ((A1.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
	AND ((A1.RollNo <= @rToRollNo) OR (@rToRollNo=0))
	AND ((SM.Code=@rCode) OR (@rCode=''))
	AND SM.StatusId = 1
	AND ((A1.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))
	
	
CREATE TABLE #Temp_Academic (tempAcademicId bigint);
INSERT INTO #Temp_Academic 
SELECT  A.Id As tempAcademicId FROM sAssessment.tResult R 
		INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId 
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.batchId
		LEFT JOIN sStudent.tStudentMaster SM ON SM.Id = A.StudentId
		WHERE BM.Id = @rBatchId2 AND R.ExamId =@rExamId2
		AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))
		  
	--SELECT * FROM #temp
	--RETURN 	
		
	SELECT 
			@rIsDisplayAvgTotal AS IsDisplayAvgTotal,
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			EM.Id AS ExamId,
			ESGM.Title AS Exam,
			BM.Id As BatchId,
			BM.Title As BatchName,
			StuM.Code,
			[sStudent].[fStudentNameGet](StuM.FirstName , StuM.MiddleName, StuM.LastName,OM.StudentNameFormatId ) AS Name,
			A.RollNo,
			R.AcademicId,
			RD.Obtain,
			R.ResultStatus,
			CM.DisplayTitle AS Class,
			Cm.Id AS ClassId,
			DM.DisplayTitle AS Division,
			DM.Id AS DivisionId,
			DM.OrderIndex AS DivisinOrderIndex,
			R.TotalMarks,
			R.TotalObtain,
			R.Percentage,
			R.RankNumber,
			R.ResultGrade,
			SM.Title AS ClassSubject,
			RD.Id AS ResultDetailId,
			R.Id AS ResultId,
			CS.Id AS SubjectId,
			ED.Maximum,
			RD.SubjectGrade, 	
			EM.IsMarksInDecimal,
			--SM.OrderIndex AS SubjectCode,
			SM.Code AS SubjectCode,
			ED.DisplayOrder AS SubjectOrderIndex,
			CM.OrderIndex AS ClassOrderIndex,
			RD.IsPresent,
			EM.IsGrade,
			EM.IsPercentage,
			EM.IsResultStatus,
			EM.IsRankNo ,
			ED.Minimum,
			RD.GraceMark,
			EM.DecimalFormat,
			CS.IsOptional,
			ISNULL(SR.PresentDays,0)AS PresentDays,
			ISNULL(SR.TotalDays,0)AS TotalDays,
			(CASE WHEN @rIsDisplayAvgTotal=1 THEN ROUND(((RD.Obtain*100)/ED.Maximum),0) ELSE RD.Obtain END)As AvgTotal,
			@rIsDetail AS IsDetail
			
			--RD.SubjectGrade AS TermSubjectGrade,
			--RD.SubjectGrade AS SubjectGrade
			--1 As ExamNo
	FROM 
			sAssessment.tResultDetail RD
			INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
			INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
			INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId	
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId		
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId					 
			INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
			INNER JOIN #Temp_StudentId TEMP2 ON TEMP2.StudentId = A.StudentId
			INNER JOIN sSetup.tBatchMaster BM ON A.BatchId = BM.Id 
			LEFT JOIN sAssessment.tStudentRemark SR ON SR.AcademicId = A.Id AND SR.ExamId=EM.Id
			INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
			INNER JOIN sSetup.tOrganizationMaster OM ON StuM.OrgId = OM.Id
			
	WHERE 
			
		EM.BatchId = @rBatchId1
		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 ((EM.Id=@rExamId1 )	OR (@rExamId1 = 0))		
		AND ((StuM.Code=@rCode) OR (@rCode=''))
		AND ((StuM.StatusId=@rStatusId)OR(@rStatusId=0))	
		AND ((R.ResultStatus=@rResultStatus) OR (@rResultStatus=''))
		AND ((CM.DepartmentId = @rDepartmentId) OR (@rDepartmentId=0))
		AND	A.BatchId = @rBatchId1
		AND R.ExamId = @rExamId1
		 AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))

UNION 
	
		SELECT 
			@rIsDisplayAvgTotal AS IsDisplayAvgTotal,
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			EM.Id AS ExamId,
			ESGM.Title AS Exam,
			BM.Id As BatchId,
			BM.Title As BatchName,
			StuM.Code,
			[sStudent].[fStudentNameGet](StuM.FirstName , StuM.MiddleName, StuM.LastName,OM.StudentNameFormatId ) AS Name,
			A2.RollNo,
			--temp.tempAcademicId,
			A2.Id AS AcademicId,
			RD.Obtain,
			R.ResultStatus,
			CM2.DisplayTitle AS Class,
			Cm2.Id AS ClassId,
			DM2.DisplayTitle AS Division,
			DM2.Id AS DivisionId,
			DM2.OrderIndex AS DivisinOrderIndex,
			R.TotalMarks,
			R.TotalObtain,
			R.Percentage,
			R.RankNumber,
			R.ResultGrade,
			SM.Title AS ClassSubject,
			RD.Id AS ResultDetailId,
			R.Id AS ResultId,
			CS.Id AS SubjectId,
			ED.Maximum,
			RD.SubjectGrade, 
			
			EM.IsMarksInDecimal,
			--SM.OrderIndex AS SubjectCode,
			SM.Code AS SubjectCode,
			ED.DisplayOrder AS SubjectOrderIndex,
			CM2.OrderIndex AS ClassOrderIndex,
			RD.IsPresent,
			EM.IsGrade,
			EM.IsPercentage,
			EM.IsResultStatus,
			EM.IsRankNo ,
			ED.Minimum,
			RD.GraceMark,
			EM.DecimalFormat,
			CS.IsOptional,
			ISNULL(SR.PresentDays,0)AS PresentDays,
			ISNULL(SR.TotalDays,0)AS TotalDays,
			(CASE WHEN @rIsDisplayAvgTotal=1 THEN ROUND(((RD.Obtain*100)/ED.Maximum),0) ELSE RD.Obtain END)As AvgTotal,
			@rIsDetail AS IsDetail

			--2 As ExamNo
	FROM 
			sAssessment.tResultDetail RD
			INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
			INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
			INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId	
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId		
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId					 
			INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
			INNER JOIN #Temp_Academic temp ON temp.tempAcademicId= A.Id  
			INNER JOIN #Temp_StudentId TEMP2 ON TEMP2.StudentId = A.StudentId
			INNER JOIN sSetup.tBatchMaster BM ON A.BatchId = BM.Id 
			LEFT JOIN sAssessment.tStudentRemark SR ON SR.AcademicId = A.Id AND SR.ExamId=EM.Id
			INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
			INNER JOIN sSetup.tOrganizationMaster OM ON StuM.OrgId = OM.Id
			INNER JOIN sStudent.tAcademic A2 ON A2.StudentId = TEMP2.StudentId AND A2.BatchId = @rBatchId1
			INNER JOIN sSetup.tClassMaster CM2 ON CM2.Id=A2.ClassId
			INNER JOIN sSetup.tDivisionMaster DM2 ON DM2.Id=A2.DivisionId
	WHERE 
			
		EM.BatchId = @rBatchId2
		AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((EM.Id=@rExamId2 )	OR (@rExamId2 = 0))		
		AND ((StuM.Code=@rCode) OR (@rCode=''))
		AND ((StuM.StatusId=@rStatusId)OR(@rStatusId=0))	
		AND ((R.ResultStatus=@rResultStatus) OR (@rResultStatus=''))
		AND ((CM.DepartmentId = @rDepartmentId) OR (@rDepartmentId=0))
		AND	((A.BatchId = @rBatchId2 ))
		AND R.ExamId = @rExamId2
		AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))
		order by A.RollNo,ClassOrderIndex
	--	SELECT * FROM #temp
	--RETURN 
		END
		DROP Table #Temp_Academic
		DROP Table #Temp_StudentId
		
		----For Report Dataset
		--SELECT 
		--	@rBuilder1 AS Builder1,
		--	@rBuilder2 AS Builder2,
		--	EM.DisplayTitle AS Exam,
		--	EM.Id AS ExamId,
		--	StuM.Code,
		--	[sStudent].[fStudentNameGet](StuM.FirstName , StuM.MiddleName, StuM.LastName,OM.StudentNameFormatId ) AS Name,
		--	A.RollNo,
		--	--temp.tempAcademicId,
		--	R.AcademicId,
		--	RD.Obtain,
		--	R.ResultStatus,
		--	CM.DisplayTitle AS Class,
		--	Cm.Id AS ClassId,
		--	DM.DisplayTitle AS Division,
		--	DM.Id AS DivisionId,
		--	DM.OrderIndex AS DivisinOrderIndex,
		--	R.TotalMarks,
		--	R.TotalObtain,
		--	R.Percentage,
		--	R.RankNumber,
		--	R.ResultGrade,
		--	SM.Title AS ClassSubject,
		--	RD.Id AS ResultDetailId,
		--	R.Id AS ResultId,
		--	CS.Id AS SubjectId,
		--	ED.Maximum,
		--	RD.SubjectGrade, 
			
		--	EM.IsMarksInDecimal,
		--	--SM.OrderIndex AS SubjectCode,
		--	SM.Code AS SubjectCode,
		--	ED.DisplayOrder AS SubjectOrderIndex,
		--	CM.OrderIndex AS ClassOrderIndex,
		--	RD.IsPresent,
		--	EM.IsGrade,
		--	EM.IsPercentage,
		--	EM.IsResultStatus,
		--	EM.IsRankNo ,
		--	ED.Minimum,
		--	RD.GraceMark,
		--	EM.DecimalFormat,
		--	CS.IsOptional,
		--	SR.PresentDays,
		--	SR.TotalDays,
		--	BM.Id As BatchId,
		--	BM.Title As BatchName
		--	FROM
		--	sAssessment.tResultDetail RD
		--	INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
		--	INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
		--	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId	
		--	INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId		
		--	INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
		--	INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId					 
		--	INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
		--	INNER JOIN sSetup.tBatchMaster BM ON A.BatchId = BM.Id 
		--	LEFT JOIN sAssessment.tStudentRemark SR ON SR.AcademicId = A.Id
		--	INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
		--	INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
		--	INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
		--	INNER JOIN sSetup.tOrganizationMaster OM ON StuM.OrgId = OM.Id
			


			--SELECT 
			--0 AS IsDisplayAvgTotal,
			--'' AS Builder1,
			--'' AS Builder2,
			--0 AS ExamId,
			--'' AS Exam,
			--0 As BatchId,
			--'' As BatchName,
			--''  AS Code,
			--'' AS Name,
			--0 AS RollNo,
			----temp.tempAcademicId,
			--0 AS AcademicId,
			--0 AS Obtain,
			--'' AS ResultStatus,
			--'' AS Class,
			--0  AS ClassId,
			--'' AS Division,
			--0 AS DivisionId,
			--0 AS DivisinOrderIndex,
			--0 AS TotalMarks,
			--0 AS TotalObtain,
			--0 AS Percentage,
			--0 AS RankNumber,
			--'' AS ResultGrade,
			--'' AS ClassSubject,
			--0 AS ResultDetailId,
			--0 AS ResultId,
			--0 AS SubjectId,
			--0 AS Maximum,
			--'' AS SubjectGrade, 
			
			--0 AS IsMarksInDecimal,
			----SM.OrderIndex AS SubjectCode,
			--'' AS SubjectCode,
			--0 AS SubjectOrderIndex,
			--0 AS ClassOrderIndex,
			--0 AS IsPresent,
			-- 0 AS IsGrade,
			--0 AS IsPercentage,
			--0 AS IsResultStatus,
			--0 AS IsRankNo ,
			--0 AS  Minimum,
			--0 AS GraceMark,
			--'' AS DecimalFormat,
			--0 AS IsOptional,
			--0 AS PresentDays,
			--0 AS TotalDays,
			--0 As AvgTotal,
			--0 AS IsDetail
END
GO
PRINT N'Altering [sAssessment].[pRptResultListConsolidateFloating]...';


GO

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

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

CREATE TABLE #TempExam
(
	SubExamId int, 
	ExamOrderIndex int,
	TermExamId int,
	AnnualExamId int, 
	Exam nvarchar(50) 
)

INSERT INTO #TempExam
(
	 SubExamId,
	 ExamOrderIndex,
	 TermExamId,
	 AnnualExamId,
	 Exam 
	
)
Select  
	EC.SubExamId,
	EC.ExamOrder,
	EC.ExamId AS TermExamId,
	@rExamId AS AnnualExamId,
	ES.Title AS Exam	
	from  sAssessment.tExamCombine EC 
	INNER JOIN sAssessment.tExamMaster EM  ON EC.ExamId = EM.Id 
	 INNER JOIN sAssessment.tExamSubGroupMaster ES ON ES.Id = EM.ExamSubGroupId
	 INNER JOIN (select SubExamId from sAssessment.tExamCombine where examId = @rExamId) AS SE
	 ON EC.ExamId = SE.SubExamId  
	--WHere EC.ExamId  in  (select SubExamId from sAssessment.tExamCombine where examId = @rExamId  )
	--Select * from #TempExam
	
 
		Declare @lAnnualExamMaximum int,@lExamId int
		Select @lExamId= AnnualExamId FROM #TempExam 

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


GO

ALTER PROCEDURE [sAssessment].[pRptResultListConsolidateWithMarksGet]
	 
	 @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
	
	 --,@rcolumn_visible bit
	

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

--#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,		
		 
		 
		SubjectGradeTerm1 NVarchar(50),
		SubjectGradeTerm2 NVarchar(50),
		SubjectGradeTerm3 NVarchar(50),
		IsMarksInDecimal bit,
		column_visible bit,
		--Obtain decimal(5,2),
		Percentile decimal(5,2),
		--ClassSubject nvarchar(100),
		ResultDetailId bigint,
		ResultId bigint,	
		Remark1 nvarchar(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), 
		
		TermScopeId tinyint,		 
		StudentPhoto varbinary(max),
		GradeString nvarchar(1000),
		IsDisplayGradeString bit,		 
		IsDisplayInMarksheet bit,
		IsShowSubjectGrade bit,
		IsIncludeInTotal bit,
		ClassSubjectID int,
		SubjectId int,
		--Maximum decimal(5,2),
		SubjectOrderIndex smallint,
		SubjectGrade NVarchar(50),
		SubjectName NVarchar(150),
		SubjectCode Nvarchar(50),	
		SubjectMinimum decimal(8,2),		
		SubjectMaximum decimal(8,2),
		SubjectObtain  decimal(8,2),
		
		Exam1Name Nvarchar(150),		
		TotalMarks1 decimal(8,2),		
		TotalObtain1 decimal(8,2),
		Percentage1 decimal(8,2),
		RankNumber1 int,
		ResultGrade1 NVarchar(50),
		Percentile1 decimal(8,2),
		ResultStatus1 Nvarchar(20),
			
		Exam2Name nvarchar(150),	
		TotalMarks2 decimal(8,2),
		TotalObtain2 decimal(8,2),
		Percentage2 decimal(8,2),
		RankNumber2 int,
		ResultGrade2 NVarchar(50),
		Percentile2 decimal(8,2),
		ResultStatus2 Nvarchar(20),
		
		Exam3Name nvarchar(150),	
		TotalMarks3 decimal(8,2),
		TotalObtain3 decimal(8,2),
		Percentage3 decimal(8,2),
		RankNumber3 int,
		ResultGrade3 NVarchar(50),
		Percentile3 decimal(8,2),		
		ResultStatus3 Nvarchar(20),
		
		Exam4Name nvarchar(150),	
		TotalMarks4 decimal(8,2),
		TotalObtain4 decimal(8,2),
		Percentage4 decimal(8,2),
		RankNumber4 int,
		ResultGrade4 NVarchar(50),
		Percentile4 decimal(8,2),
		ResultStatus4 Nvarchar(20),
		
		Exam5Name nvarchar(150),		
		TotalMarks5 decimal(8,2),
		TotalObtain5 decimal(8,2),
		Percentage5 decimal(8,2),
		RankNumber5 int,
		ResultGrade5 NVarchar(50),
		Percentile5 decimal(8,2),
		ResultStatus5 Nvarchar(20),
		
		Exam6Name nvarchar(150),	
		TotalMarks6 decimal(8,2),
		TotalObtain6 decimal(8,2),
		Percentage6 decimal(8,2),
		RankNumber6 int,
		ResultGrade6 NVarchar(50),
		Percentile6 decimal(8,2),
		ResultStatus6 Nvarchar(20),
		
		Exam7Name nvarchar(150),		
		TotalMarks7 decimal(8,2),
		TotalObtain7 decimal(8,2),
		Percentage7 decimal(8,2),
		RankNumber7 int,
		ResultGrade7 NVarchar(50),
		Percentile7 decimal(8,2),
		ResultStatus7 Nvarchar(20),
		
		Exam8Name nvarchar(150),
		TotalMarks8 decimal(8,2),
		TotalObtain8 decimal(8,2),
		Percentage8 decimal(8,2),
		RankNumber8 int,
		ResultGrade8 NVarchar(50),
		Percentile8 decimal(8,2),
		ResultStatus8 Nvarchar(20),
		
		
		Exam9Name nvarchar(150),	
		TotalMarks9 decimal(8,2),
		TotalObtain9 decimal(8,2),
		Percentage9 decimal(8,2),
		RankNumber9 int,
		ResultGrade9 NVarchar(50),
		Percentile9 decimal(8,2),
		ResultStatus9 Nvarchar(20),
		
		Exam10Name nvarchar(150),	
		TotalMarks10 decimal(8,2),
		TotalObtain10 decimal(8,2),
		Percentage10 decimal(8,2),
		RankNumber10 int,
		ResultGrade10 NVarchar(50),
		Percentile10 decimal(8,2),
		ResultStatus10 Nvarchar(20),
		
		Exam11Name nvarchar(150),	
		TotalMarks11 decimal(8,2),
		TotalObtain11 decimal(8,2),
		Percentage11 decimal(8,2),
		RankNumber11 int,
		ResultGrade11 NVarchar(50),
		Percentile11 decimal(8,2),
		ResultStatus11 Nvarchar(20),
		
		Exam12Name nvarchar(150),	
		TotalMarks12 decimal(8,2),
		TotalObtain12 decimal(8,2),
		Percentage12 decimal(8,2),
		RankNumber12 int,
		ResultGrade12 NVarchar(50),
		Percentile12 decimal(8,2),
		ResultStatus12 Nvarchar(20),
		
		ResultRemark1 nvarchar(200),
		ResultRemark2 nvarchar(200),
		
		TotalDays 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(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),
		SubjectMaxTerm1 decimal(8,2),
		SubjectMaxTerm2 decimal(8,2),
		SubjectMaxTerm3 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),
		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),
		ComExam1Name nvarchar(max),
		ComExam1Grade nvarchar(10),
		ComExam1Mark nvarchar(10),
		ComExam2Name nvarchar(max),
		ComExam2Grade nvarchar(10),
		ComExam2Mark nvarchar(10),
		ComExam3Name nvarchar(max),
		ComExam3Grade nvarchar(10),
		ComExam3Mark nvarchar(10),
		ComExam4Name nvarchar(max),
		ComExam4Grade nvarchar(10),
		ComExam4Mark nvarchar(10),
		ComExam5Name nvarchar(max),
		ComExam5Grade nvarchar(10),
		ComExam5Mark nvarchar(10),
		ComExam6Name nvarchar(max),
		ComExam6Grade nvarchar(10),
		ComExam6Mark nvarchar(10),
		ComExam7Name nvarchar(max),
		ComExam7Grade nvarchar(10),
		ComExam7Mark nvarchar(10),
		ComExam8Name nvarchar(max),
		ComExam8Grade nvarchar(10),
		ComExam8Mark nvarchar(10),
		ComExam9Name nvarchar(max),
		ComExam9Grade nvarchar(10),
		ComExam9Mark nvarchar(10),
		ComExam10Name nvarchar(max),
		ComExam10Grade nvarchar(10),
		ComExam10Mark nvarchar(10),
		ComExam11Name nvarchar(max),
		ComExam11Grade nvarchar(10),
		ComExam11Mark nvarchar(10),
		ComExam12Name nvarchar(max),
		ComExam12Grade nvarchar(10),
		ComExam12Mark nvarchar(10)

	
	)	
	 --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 
	
	)
	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
	
		
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
	
	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 sAcademic.tTeacherSubjectDivision TSD ON TSD.SubjectId=SM.Id AND TSD.DivisionId = A.DivisionId
	--LEFT JOIN sHrm.tEmployeeMaster EMP ON TSD.EmployeeId = EMP.Id
	
	 WHERE
		R.ExamId = @rExamId 
		AND ((A.DivisionId =  @rDivisionId) OR (@rDivisionId=0))
		AND ((A.ClassId =  @rClassId) OR (@rClassId=0))		 
		AND ((A.BatchId =  @rBatchId) OR (@rBatchId=0))
		AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((R.RankNumber >= @rFromRank) OR (@rFromRank=0))
		AND ((R.RankNumber <= @rToRank) OR (@rToRank=0))
		AND ((R.ResultGrade = @rGrade) OR (@rGrade=''))
		AND ((StuM.Code=@rCode) OR (@rCode=''))	
		AND ((R.Id = @rResultId) OR (@rResultId = 0))	
		AND ((StuM.StatusId=@rStatusId)OR(@rStatusId=0))
		AND((A.Id=@rAcademicId)OR (@rAcademicId=0))
		AND ((CS.SubjectId=@rSubjectId) OR(@rSubjectId=0) ) 
		AND ((R.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  ISNULL(EMP.IsOtherUser,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 ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)) 
	    
	Order By ED.DisplayOrder

 --print 'temp insert'
  --SET @IsIncludeSubExam = 1
	create TABLE #tempcombineExam
	(	Id int IDENTITY,
		ExamID int )

	IF (@IsIncludeSubExam = 0)
	BEGIN	
	INSERT INTO #tempcombineExam (ExamID) 
	SELECT SUBEXAMID FROM sAssessment.tExamCombine WHERE ExamId  = @rExamId Order By ExamOrder ASC
 	END
 	ELSE
 	BEGIN
 	-- if we want to display result for both the term with all exam select this option
 	INSERT INTO #tempcombineExam (ExamID) 
	SELECT C.SUBEXAMID FROM sAssessment.tExamCombine C
	INNER JOIN (SELECT SUBEXAMID,ExamOrder FROM sAssessment.tExamCombine WHERE ExamId  = @rExamId) E
	ON C.ExamId = E.SubExamId
	ORDER BY E.ExamOrder,C.ExamOrder
	END
	--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,	
					 				
					 SubjectGrade' + convert(nvarchar(15),@lCount)+ '=RD.SubjectGrade,
					 TotalDays'+convert(nvarchar(15),@lCount)+'=SR.TotalDays,
					 PresentDays'+convert(nvarchar(15),@lCount)+'=SR.PresentDays										
					 From
						sAssessment.tResultDetail RD
						INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId	
						LEFT JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND T.AcademicId = SR.AcademicId 									
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
						
--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)
		
		
	set @lCount = @lCount -1
	end


	CREATE TABLE #CombineExam
	(
	Id int IDENTITY,
	ExamId int
	)

	INSERT INTO #CombineExam(ExamId)
	SELECT 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 Order By EC.ExamId ASC

		--Select * from #CombineExam
		DECLARE @lIdCount int,@query1  AS NVARCHAR(MAX),@lExamId int,@lTotalCount int,@query2  AS NVARCHAR(MAX),@query3  AS NVARCHAR(MAX)
  
	Select Top 1 @lIdCount = Id from #CombineExam
	Select @lTotalCount=Count(Id)From #CombineExam
	--Select @lIdCount
	DECLARE @ExamName nvarchar(150)
	--Select @lIdCount,@lTotalCount
	WHILE (@lIdCount <= @lTotalCount)
	
	BEGIN
	--DECLARE @ExamName nvarchar(150)
		select @lExamId = ExamID from #CombineExam Where Id = @lIdCount 
		Select @ExamName=DisplayTitle from [sAssessment].[tExamMaster] Where Id=@lExamId
		
			IF(@lIdCount=1)
				BEGIN
				
					set @query1 ='update #TempAllExam SET 					 
						ComExam1Name = ' +''''+  @ExamName  +''''
					

					set @query2 ='update T set					 
						ComExam1Grade=RD.SubjectGrade
								 
					 From
						sAssessment.tResultDetail RD
						INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						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), @lExamId) 
						
						set @query3 ='update T set					 
						ComExam1Mark=RD.Obtain
								 
					 From
						sAssessment.tResultDetail RD
						INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						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), @lExamId)  


				execute(@query1)
				execute(@query2)
				execute(@query3)
			END
			IF(@lIdCount=2)
				BEGIN
				
					set @query1 ='update #TempAllExam SET 					 
						ComExam2Name = ' +''''+  @ExamName  +''''
					set @query2 ='update T set					 
						ComExam2Grade=RD.SubjectGrade
								 
					 From
						sAssessment.tResultDetail RD
						INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						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), @lExamId)

						set @query3 ='update T set					 
						ComExam2Mark=RD.Obtain
								 
					 From
						sAssessment.tResultDetail RD
						INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						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), @lExamId)
				
				execute(@query1)
				execute(@query2)
				execute(@query3)
			END
			IF(@lIdCount=3)
				BEGIN
				
					set @query1 ='update #TempAllExam SET 					 
						ComExam3Name = ' +''''+  @ExamName  +''''
					set @query2 ='update T set					 
						ComExam3Grade=RD.SubjectGrade
								 
					 From
						sAssessment.tResultDetail RD
						INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						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), @lExamId)

						set @query3 ='update T set					 
						ComExam3Mark=RD.Obtain
								 
					 From
						sAssessment.tResultDetail RD
						INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						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), @lExamId)
				
				execute(@query1)
				execute(@query2)
				execute(@query3)
			END
			IF(@lIdCount=4)
				BEGIN
				
					set @query1 ='update #TempAllExam SET 					 
						ComExam4Name = ' +''''+  @ExamName  +''''
					set @query2 ='update T set					 
						ComExam4Grade=RD.SubjectGrade
								 
					 From
						sAssessment.tResultDetail RD
						INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						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), @lExamId)

						set @query3 ='update T set					 
						ComExam4Mark=RD.Obtain
								 
					 From
						sAssessment.tResultDetail RD
						INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						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), @lExamId)
				
				execute(@query1)
				execute(@query2)
				execute(@query3)
			END
			IF(@lIdCount=5)
				BEGIN
				
					set @query1 ='update #TempAllExam SET 					 
						ComExam5Name = ' +''''+  @ExamName  +''''
					set @query2 ='update T set					 
						ComExam5Grade=RD.SubjectGrade
								 
					 From
						sAssessment.tResultDetail RD
						INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						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), @lExamId)

						set @query3 ='update T set					 
						ComExam5Mark=RD.Obtain
								 
					 From
						sAssessment.tResultDetail RD
						INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						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), @lExamId)
				
				execute(@query1)
				execute(@query2)
				execute(@query3)
			END
			IF(@lIdCount=6)
				BEGIN
				
					set @query1 ='update #TempAllExam SET 					 
						ComExam6Name = ' +''''+  @ExamName  +''''
					set @query2 ='update T set					 
						ComExam6Grade=RD.SubjectGrade
								 
					 From
						sAssessment.tResultDetail RD
						INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						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), @lExamId)

					set @query3 ='update T set					 
						ComExam6Mark=RD.Obtain
								 
					 From
						sAssessment.tResultDetail RD
						INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						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), @lExamId)
				
				execute(@query1)
				execute(@query2)
				execute(@query3)
			END
			IF(@lIdCount=7)
				BEGIN
				
					set @query1 ='update #TempAllExam SET 					 
						ComExam7Name = ' +''''+  @ExamName  +''''
					set @query2 ='update T set					 
						ComExam7Grade=RD.SubjectGrade
								 
					 From
						sAssessment.tResultDetail RD
						INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						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), @lExamId)

					set @query3 ='update T set					 
						ComExam7Mark=RD.Obtain
								 
					 From
						sAssessment.tResultDetail RD
						INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						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), @lExamId)
				
				
				execute(@query1)
				execute(@query2)
				execute(@query3)
			END
			IF(@lIdCount=8)
				BEGIN
				
					set @query1 ='update #TempAllExam SET 					 
						ComExam8Name = ' +''''+  @ExamName  +''''
					set @query2 ='update T set					 
						ComExam8Grade=RD.SubjectGrade
								 
					 From
						sAssessment.tResultDetail RD
						INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						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), @lExamId)

					set @query3 ='update T set					 
						ComExam8Mark=RD.Obtain
								 
					 From
						sAssessment.tResultDetail RD
						INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						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), @lExamId)
				
				execute(@query1)
				execute(@query2)
				execute(@query3)
			END
			IF(@lIdCount=9)
				BEGIN
				
					set @query1 ='update #TempAllExam SET 					 
						ComExam9Name = ' +''''+  @ExamName  +''''

					set @query2 ='update T set					 
						ComExam9Grade=RD.SubjectGrade
								 
					 From
						sAssessment.tResultDetail RD
						INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						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), @lExamId)

					set @query3 ='update T set					 
						ComExam9Mark=RD.Obtain
								 
					 From
						sAssessment.tResultDetail RD
						INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						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), @lExamId)
				
				execute(@query1)
				execute(@query2)
				execute(@query3)
			END
			IF(@lIdCount=10)
				BEGIN
				
					set @query1 ='update #TempAllExam SET 					 
						ComExam10Name = ' +''''+  @ExamName  +''''
					set @query2 ='update T set					 
						ComExam10Grade=RD.SubjectGrade
								 
					 From
						sAssessment.tResultDetail RD
						INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						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), @lExamId)

					set @query3 ='update T set					 
						ComExam10Mark=RD.Obtain
								 
					 From
						sAssessment.tResultDetail RD
						INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						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), @lExamId)
				
				execute(@query1)
				execute(@query2)
				execute(@query3)
			END
			IF(@lIdCount=11)
				BEGIN
				
					set @query1 ='update #TempAllExam SET 					 
						ComExam11Name = ' +''''+  @ExamName  +''''
					set @query2 ='update T set					 
						ComExam11Grade=RD.SubjectGrade
								 
					 From
						sAssessment.tResultDetail RD
						INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						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), @lExamId)
						
					set @query3 ='update T set					 
						ComExam11Mark=RD.Obtain
								 
					 From
						sAssessment.tResultDetail RD
						INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						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), @lExamId)
				
				execute(@query1)
				execute(@query2)
				execute(@query3)
			END
			IF(@lIdCount=12)
				BEGIN
				
					set @query1 ='update #TempAllExam SET 					 
						ComExam12Name = ' +''''+  @ExamName  +''''
					set @query2 ='update T set					 
						ComExam12Grade=RD.SubjectGrade
								 
					 From
						sAssessment.tResultDetail RD
						INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						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), @lExamId)

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

		
	END
	--SELECT @rBuilder1 AS Builder1,@rBuilder2 AS Builder2, T.* FROM sAssessment.tTempAllExam T
	
--end
GO
PRINT N'Altering [sAssessment].[pRptResultListConsolidateWithSubExamGet]...';


GO
ALTER PROCEDURE [sAssessment].[pRptResultListConsolidateWithSubExamGet]
	 
	 @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.tTempAllExam
-- --drop table sAssessment.tTempAllExam
 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

--#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,		
		 
		 
		SubjectGradeTerm1 NVarchar(50),
		SubjectGradeTerm2 NVarchar(50),
		SubjectGradeTerm3 NVarchar(50),
		IsMarksInDecimal bit,
		column_visible bit,
		--Obtain decimal(5,2),
		Percentile decimal(5,2),
		--ClassSubject nvarchar(100),
		ResultDetailId bigint,
		ResultId bigint,	
		Remark1 nvarchar(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), 
		
		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),
		
		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(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),
		SubjectMaxTerm1 decimal(8,2),
		SubjectMaxTerm2 decimal(8,2),
		SubjectMaxTerm3 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),
		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(20),
		HighestDivisionMark decimal(5, 2),
		HighestDivisionGrade nvarchar(50),
		StreamTitle nvarchar(50),
		AdmissionNo int,
		AdmissionDate Date
		
	)	
	 --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
	)
	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.AdmissionFormNumber,0) AS AdmissionNo,
		ISNULL(StuA.AdmissionDate,'') AS AdmissionDate
				
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.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
	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  ISNULL(EMP.IsOtherUser,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 ((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,	
					 				
					 SubjectGrade' + convert(nvarchar(15),@lCount)+ '=RD.SubjectGrade,
					 TotalDays'+convert(nvarchar(15),@lCount)+'=SR.TotalDays,
					 PresentDays'+convert(nvarchar(15),@lCount)+'=SR.PresentDays										
					 From
						sAssessment.tResultDetail RD
						INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId	
						LEFT JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND T.AcademicId = SR.AcademicId 									
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
						
--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
						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
					
					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
						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			
					 From						 
					   sAssessment.tResult R  				 
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON  T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
		execute(@query)
		
		select @lSubExamId = SubExamId from sAssessment.tExamCombine  Where ExamId  = @rExamId AND ExamOrder = 3
		set @query ='update T set					 
					SubjectGradeTerm3=RD.SubjectGrade,
					SubjectObtainTerm3 = RD.Obtain,
					SubjectMaxTerm3= ED.Maximum				 
					 From
						sAssessment.tResultDetail RD
						INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
		execute(@query)
		set @query ='update T set
 
					TotalMarkTerm3 = R.TotalMarks,
					TotalObtainTerm3=R.TotalObtain,
					PercentageTerm3=R.Percentage,
					RankNumberTerm3=R.RankNumber,
					ResultGradeTerm3=R.ResultGrade,
					PercentileTerm3 = R.Percentile,
					ResultStatusTerm3 = R.ResultStatus,
					ExamNameTerm3 = ESGM.Code			
					 From						 
					   sAssessment.tResult R  				 
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON  T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
		execute(@query)
	END
	
	
	
	
	
	--WHILE (@lCount1 <= 6)
	--BEGIN
	--	set @query ='ALTER TABLE #TempAllExam DROP COLUMN MaximumMark' + convert(nvarchar(15),@lCount1)
	--	execute(@query)
	--	set @query ='ALTER TABLE #TempAllExam DROP COLUMN Exam' + convert(nvarchar(150),@lCount1)+ 'Name'
	--	execute(@query)
	--	set @query ='ALTER TABLE #TempAllExam DROP COLUMN SubjectGrade' + convert(nvarchar(150),@lCount1)
	--	execute(@query)		
	--	set @query ='ALTER TABLE #TempAllExam DROP COLUMN Obtain' + convert(nvarchar(15),@lCount1)
	--	execute(@query)
	--	set @query ='ALTER TABLE #TempAllExam DROP COLUMN ExamMaximum' + convert(nvarchar(15),@lCount1)
	--	execute(@query)
	--	SET @lCount1 = @lCount1 + 1
	--END
	
	SELECT @rBuilder1,@rBuilder2, T.*
	FROM #TempAllExam T
	
	--INNER JOIN SSETUP.TCLASSSUBJECT CS ON CS.ID = T.CLASSSUBJECTID
	--WHERE
	--	((T.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
	--	AND ((T.RollNo <= @rToRollNo) OR (@rToRollNo=0))
	--	AND ((T.RankNumber >= @rFromRank) OR (@rFromRank=0))
	--	AND ((T.RankNumber <= @rToRank) OR (@rToRank=0))
	--	AND ((T.ResultGrade = @rGrade) OR (@rGrade=''))
	--	AND ((T.StudCode=@rCode) OR (@rCode=''))		
		--order by T.RollNo,CS.ORDERINDEX
	--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			
-- SELECT  AS Builder1,@rBuilder2 AS Builder2, T.* FROM sAssessment.tTempAllExam T

 --SELECT @rBuilder1 AS Builder1,@rBuilder2 AS Builder2, T.* FROM sAssessment.tTempAllExam T

	END
	--SELECT @rBuilder1 AS Builder1,@rBuilder2 AS Builder2, T.* FROM sAssessment.tTempAllExam T
	
--end
GO
PRINT N'Altering [sAssessment].[pRptResultListFloatingCombineExam]...';


GO

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

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

CREATE TABLE #TempExam
(
	SubExamId int, 
	ExamOrderIndex int,
	TermExamId int,
	AnnualExamId int, 
	Exam nvarchar(50) 
)


INSERT INTO #TempExam
(
	 --SubExamId,
	 ExamOrderIndex,
	 TermExamId,
	 AnnualExamId,
	 Exam 
	
)
 
SELECT EC.ExamOrder,
EM.Id AS TermExamId,
@rExamId AS AnnualExamId,
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
	
	--Select * from #TempExam
	
 --Select * from #TempExam
		Declare @lAnnualExamMaximum int,@lExamId int
		Select @lExamId= AnnualExamId FROM #TempExam 

		Select @lAnnualExamMaximum=Maximum from sAssessment.tExamDetail Where ExamId=@lExamId
	
	SELECT 
			Convert(nvarchar(20),A.Id) AS AcademicIdText,
			Convert(nvarchar(20),@rExamId) AS ExamIdText,
			Convert(nvarchar(20),ISNULL(EM.IsDisplayMonthlyAttendance,0)) AS IsDisplayMonthlyAttendanceText,
			ESGM.Title AS Exam,
			 @rBuilder1 AS Builder1,
			StuM.Code,
			[sStudent].[fStudentNameGet](stum.FirstName , StuM.MiddleName, StuM.LastName,OM.StudentNameFormatId ) AS Name,
			A.RollNo,
			R.AcademicId,			
			R.ResultStatus,
			CM.DisplayTitle AS Class,
			DM.DisplayTitle AS Division,
			(Select R1.TotalObtain from 
			sAssessment.tResultDetail RD1
			INNER JOIN sAssessment.tResult R1 ON R1.Id = RD1.ResultId
			INNER JOIN sAssessment.tExamDetail ED1 ON ED1.Id=RD1.ExamDetailId
			Where ED1.ExamId=EC.AnnualExamId AND ED1.ClassSubjectId=CS.Id 
			AND R1.AcademicId=R.AcademicId
			)AS TotalMarks,
			--R.TotalMarks,
			(Select R1.Percentage from 
			sAssessment.tResultDetail RD1
			INNER JOIN sAssessment.tResult R1 ON R1.Id = RD1.ResultId
			INNER JOIN sAssessment.tExamDetail ED1 ON ED1.Id=RD1.ExamDetailId
			Where ED1.ExamId=EC.AnnualExamId AND ED1.ClassSubjectId=CS.Id 
			AND R1.AcademicId=R.AcademicId
			)AS Percentage,
			R.TotalObtain,
			R.RankNumber,
			(Select R1.ResultGrade from 
			sAssessment.tResultDetail RD1
			INNER JOIN sAssessment.tResult R1 ON R1.Id = RD1.ResultId
			INNER JOIN sAssessment.tExamDetail ED1 ON ED1.Id=RD1.ExamDetailId
			Where ED1.ExamId=EC.AnnualExamId AND ED1.ClassSubjectId=CS.Id 
			AND R1.AcademicId=R.AcademicId
			)AS ResultGrade,
			--R.ResultGrade,
			R.Percentile,			
			RD.Id AS ResultDetailId,		
			ED.IsDisplayInMarksheet,
			ED.IsShowSubjectGrade,
			ED.IsIncludeInTotal,
			RD.Obtain AS SubjectObtain,
			ED.Minimum AS SubjectMinimum,
			ED.Maximum AS SubjectMaximum,			
			SM.Code AS SubjectCode,
			SM.Title AS SubjectName,
			(CASE ISNULL(ED.DisplayOrder,0)
			WHEN 0 THEN CS.OrderIndex
			ELSE ED.DisplayOrder END) AS SubjectOrderIndex,
			R.Id AS ResultId,
			CS.Id AS SubjectId,			 	
			EM.IsMarksInDecimal,
			
			ISNULL(EM.Remark1,'') AS Remark1,
			ISNULL(EM.Remark2,'') AS Remark2,
			ISNULL(EM.Remark3,'') AS Remark3,
			EM.DisplayTitle,
			EM.IsRankNo, 
			EM.IsGrade,
			EM.IsPercentile,
			EM.IsPercentage,
			EM.IsSubjectPercentile,
			EM.IsProcessResult,
			 
			EM.IsNegativeMarks,
			EM.IsIncludeCoScholastic,
			EM.IsOnPrePrinted,
			EM.IsDisplayPhoto,
			EM.IsDisplayBirthDate,
			EM.IsLockForEdit,
			EM.IsDisplaySchoolName,			
			EM.IsDisplayAttendance,
			EM.IsDisplayHeightWeight,
			EM.IsResultStatus,
			REPLICATE(',',EM.FooterAdjustment) AS FooterAdjustmentText,
			REPLICATE(',',EM.DetailAdjustment) AS DetailAdjustmentText,
			EM.FooterAdjustment,
			EM.DetailAdjustment,
		 		 
			EM.TermScopeId,
		 
			RD.IsPresent,
			@GradeString AS GradeString,
			EM.IsDisplayGradeString,
			(CASE EM.IsDisplayHighestDivisionMark
			WHEN 1 THEN [sAssessment].[fGetHighestDivisionMark](A.DivisionId ,RD.ExamDetailId)
			ELSE 0 END) AS HighestDivisionMark,
			(CASE EM.IsDisplayHighestDivisionGrade
			WHEN 1 THEN [sAssessment].[fGetHighestDivisionGrade] (A.DivisionId ,RD.ExamDetailId)
			ELSE '' END) AS HighestDivisionGrade,			
			OM.SmallAddress1,
			EM.IsDisplayParentName,
			 
			ISNULL(ED.IsShowSubjectMark,1) AS IsShowSubjectMark,
			
			EM.IsDisplayTeacherSign,
			Em.IsDisplayPrincipalSign,
		 
			ISNULL(EM.IsDisplayMonthlyAttendance,0) AS IsDisplayMonthlyAttendance,
			 
			ISNULL(EM.IsDisplayImageHeader,0) AS IsImageHeader,
			 
			EC.SubExamId,
			EC.ExamOrderIndex,
			EC.AnnualExamId ,
			EM.DecimalFormat,
			EC.TermExamId,
			EC.Exam AS ExamNAme, 	
					 
			ARD.SubjectGrade AS AnnualSubjectGrade,
			--(Select RD1.SubjectGrade from 
			--sAssessment.tResultDetail RD1
			--INNER JOIN sAssessment.tResult R1 ON R1.Id = RD1.ResultId
			--INNER JOIN sAssessment.tExamDetail ED1 ON ED1.Id=RD1.ExamDetailId
			--Where ED1.ExamId=EC.AnnualExamId AND ED1.ClassSubjectId=CS.Id 
			--AND R1.AcademicId=R.AcademicId
			--)AS AnnualSubjectGrade,
			--(Select RD1.Obtain from 
			--sAssessment.tResultDetail RD1
			--INNER JOIN sAssessment.tResult R1 ON R1.Id = RD1.ResultId
			--INNER JOIN sAssessment.tExamDetail ED1 ON ED1.Id=RD1.ExamDetailId
			--Where ED1.ExamId=EC.AnnualExamId AND ED1.ClassSubjectId=CS.Id 
			--AND R1.AcademicId=R.AcademicId
			--)AS AnnualSubjectObtain,
			ARD.Obtain As AnnualSubjectObtain,
			--(Select RD1.SubjectGrade from 
			--sAssessment.tResultDetail RD1
			--INNER JOIN sAssessment.tResult R1 ON R1.Id = RD1.ResultId
			--INNER JOIN sAssessment.tExamDetail ED1 ON ED1.Id=RD1.ExamDetailId
			--Where ED1.ExamId=EC.TermExamId AND ED1.ClassSubjectId=CS.Id 
			--AND R1.AcademicId=R.AcademicId
			--)AS TermSubjectGrade,
			TRD.SubjectGrade AS TermSubjectGrade,
			--(Select RD1.Obtain from 
			--sAssessment.tResultDetail RD1
			--INNER JOIN sAssessment.tResult R1 ON R1.Id = RD1.ResultId
			--INNER JOIN sAssessment.tExamDetail ED1 ON ED1.Id=RD1.ExamDetailId
			--Where ED1.ExamId=EC.TermExamId AND ED1.ClassSubjectId=CS.Id 
			--AND R1.AcademicId=R.AcademicId
			--)AS TermSubjectObtain,
			TRD.Obtain AS TermSubjectObtain,
			EC.TermExamId,
			RD.Id,
			RD.SubjectGrade AS SubjectGrade,
			ISNULL(ARD.Remark,'')  AS Remark,
			SF.FatherName,
			SF.MotherName,
			ISNULL(SR.TotalDays,0)AS TotalDays,
			ISNULL(SR.PresentDays,0)AS PresentDays,
			--R.TotalMarks AS TotalMark,
			R.TotalObtain,
			(Select Exd.Maximum from sAssessment.tExamDetail Exd Where 
			Exd.ExamId=EC.TermExamId AND CS.Id=Exd.ClassSubjectId
			)AS TermMaximum,
			(Select Exd.Maximum from sAssessment.tExamDetail Exd Where 
			Exd.ExamId=EC.AnnualExamId AND CS.Id=Exd.ClassSubjectId
			)AS AnnualMaximum,
			(CASE WHEN SO.GenderId=1 THEN 'Male' ELSE 'Female' END)AS Gender,
			CS.Id
			--(Select R.TotalMarks From sAssessment.tResult)
			--@lAnnualExamMaximum AS AnnualMaximum,
			
			
			
			
	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.TermExamId = EM.Id 	
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.EXAMSUBGROUPID
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId					 
			INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId	
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId		
			INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId			
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId			
			INNER JOIN sSetup.tOrganizationMaster OM ON StuM.OrgId = OM.Id			
			INNER JOIN sAssessment.tResult AR ON AR.AcademicId = A.Id AND AR.ExamId = EC.AnnualExamId 
			INNER JOIN sAssessment.tResultDetail ARD ON AR.Id = ARD.ResultId 
			INNER JOIN sAssessment.tExamDetail AED ON ARD.EXamDetailId = AED.Id 
			INNER JOIN sSetup.tClassSubject ACS ON AED.ClassSubjectId = ACS.Id AND ACS.Id= CS.Id
			--AND ACS.SubjectId = @rSubjectId  
			INNER JOIN sAssessment.tResult TR ON TR.AcademicId = A.Id AND TR.ExamId = EC.TermExamId 
			INNER JOIN sAssessment.tResultDetail TRD ON TR.Id = TRD.ResultId 
			INNER JOIN sAssessment.tExamDetail TED ON TRD.EXamDetailId = TED.Id 
			INNER JOIN sSetup.tClassSubject TCS ON TED.ClassSubjectId = TCS.Id AND TCS.Id= CS.Id
			--AND TCS.SubjectId = @rSubjectId 
			
			
			LEFT JOIN sHostel.tAssignRoom ARO ON  ARO.SourceId=StuM.Id AND ARO.SourceTypeId=2003 AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((ARO.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0) AND (BM.OrgGroupBatchId = ARO.OrgGroupBatchId)) 
		    LEFT JOIN
			(SELECT AT.SourceId,B.OrgGroupBatchId FROM sTransport.tAssignRoute AT 
			INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId 
			INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT ON RT.SourceId = StuM.Id 
		
			LEFT JOIN sAssessment.tStudentRemark SR ON R.AcademicId = SR.AcademicId AND  SR.ExamId=EC.AnnualExamId
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = StuM.Id
			LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=StuM.Id
			
	WHERE 
			
		((EM.BatchId = @rBatchId) OR  (@rBatchId = 0))
		AND ((A.ClassId=@rClassId) OR (@rClassId=0)) 
		AND ((SM.Id=@rSubjectId) OR (@rSubjectId=0))
		AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((R.RankNumber >= @rFromRank) OR (@rFromRank=0))
		AND ((R.RankNumber <= @rToRank) OR (@rToRank=0))
		AND ((R.ResultGrade = @rGrade) OR (@rGrade=''))
		--AND ((R.Percentage>=@rFromPercentage) OR (@rFromPercentage=0))
		--AND ((R.Percentage<=@rToPercentage) OR (@rToPercentage=0))Total Marks
		AND ((StuM.Code=@rCode) OR (@rCode=''))
		AND ((R.Id = @rResultId) OR (@rResultId = 0))
		AND ((StuM.StatusId=@rStatusId)OR(@rStatusId=0))
		
		 AND (
	 (@rFilterId = 0) -- All
     OR (@rFilterId = 2 AND isnull(ARO.SourceId,0)!=0) -- Hostel
     OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport
     OR ((@rFilterId =1) AND ((isnull(ARO.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))
    ) 
	AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))
		--order by A.RollNo,CS.OrderIndex 
		
	 drop table #TempExam
		
END
GO
PRINT N'Altering [sAssessment].[pRptResultListGet]...';


GO
 
ALTER PROCEDURE [sAssessment].[pRptResultListGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 --@rOrgId smallint,
	 @rBatchId int,
	 @rClassId int,
	 @rDivisionId int,
	 @rExamId int=0,
	 @rExamSubGroupId int=0,
	 @rCode nvarchar(20)='',
	 @rFromRollNo int=0,
	 @rToRollNo int=0,
	 @rFromRank int=0,
	 @rToRank int=0,
	 @rGrade nvarchar(20)='',
	 @rAcademicId bigint=0,
	 @rFromPercentage decimal(5,2)=0,
	 @rToPercentage decimal(5,2)=0,
	 @rDepartmentid int=0,
	 @rStatus int =1,
	 @rGenderId int,
	 @rClassStatusId int=0,
	 @rResultStatus nvarchar(20)='',
	 @rMultiCode nvarchar(max)='',
	 @rOrderBy int = 0
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			Convert(nvarchar(20),A.Id) AS   AcademicIdText,	
	CONVERT (nvarchar(20),@rExamId) AS ExamIdText,
	CONVERT (nvarchar(20),EM.GradeSetId) AS GradeSetIdText,
	CONVERT (nvarchar(20),@rBatchId) AS BatchIdText,
			Convert(nvarchar(20),ISNULL(EM.IsDisplayMonthlyAttendance,0))AS IsDisplayMonthlyAttendanceText,
			ESGM.Title AS Exam,
			SM.Code,
			  [sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Name,
			A.RollNo,
			R.AcademicId,
			CM.DisplayTitle+'/'+DM.DisplayTitle AS Class,
			 DM.DisplayTitle AS Division,
			DM.Id AS DivisionId,
			DM.OrderIndex AS DivisinOrderIndex,
			R.TotalMarks,
			R.TotalObtain,
			R.Percentage,
			R.RankNumber,
			R.ResultGrade,
			EM.IsMarksInDecimal,
			SI.StudentPhoto,
			EM.DisplayTitle,
			OM.SmallAddress1,
			R.ResultRemark,
			R.OtherRemark1,
			EM.Remark1,
			EM.Remark2,
			EM.Remark3,
			SR.ResultRemark2,
			Em.GradeSetId,
			R.ResultStatus,
			SR.ResultRemark1,
			REPLICATE(',',EM.FooterAdjustment) AS FooterAdjustmentText,
			EI.EmployeeSign,
			EM.IsDisplayPrincipalSign,
			EM.IsDisplayTeacherSign,
			EM.IsOnPrePrinted,
			Em.IsDisplayPhoto,
			ISNULL(SR.PresentDays,0)AS PresentDays,			
			ISNULL(SR.TotalDays,0)AS TotalDays,
			EM.DecimalFormat,
			CM.Id AS ClassId,
			@rOrderBy AS OrderBy
      
	FROM 
			sAssessment.tExamMaster EM
			INNER JOIN sAssessment.tResult R ON EM.Id=R.ExamId			
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId 
			INNER JOIN sStudent.tAcademic A ON R.AcademicId=A.Id
			 
			INNER JOIN sStudent.tStudentMaster SM ON A.StudentId=SM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=EM.ClassId
			INNER JOIN sSetup.tDivisionMaster DM ON A.DivisionId=DM.Id
			LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = DM.InchargeEmployeeId
			LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=SM.Id
			LEFT JOIN sAssessment.tStudentRemark SR ON SR.AcademicId=A.Id AND SR.ExamId = EM.Id
			LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
			
			 
	WHERE 
			
		      EM.BatchId = @rBatchId 
		AND (EM.ClassId=@rClassId OR @rClassId=0) 
		AND (A.DivisionId=@rDivisionId OR @rDivisionId=0)
		AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((R.RankNumber >= @rFromRank) OR (@rFromRank=0))
		AND ((R.RankNumber <= @rToRank) OR (@rToRank=0))
		AND ((R.ResultGrade = @rGrade) OR (@rGrade=''))
		AND ((ESGM.Id=@rExamSubGroupId )	OR (@rExamSubGroupId = 0))
		AND ((EM.Id=@rExamId )	OR (@rExamId = 0))
		AND ((SM.Code=@rCode) OR (@rCode=''))
		AND ((A.Id =@rAcademicId) OR (@rAcademicId=0))
		
		AND ((R.Percentage >=@rFromPercentage) OR (@rFromPercentage=0))
		AND ((R.Percentage <=@rToPercentage) OR (@rToPercentage=0))
		AND ((CM.DepartmentId = @rDepartmentId) OR (@rDepartmentId=0))
		ANd ((SM.StatusId= @rStatus) OR (@rStatus = 0))
		AND ((SO.GenderId=@rGenderId) OR (@rGenderId=0))
		AND (A.ClassStatusId=@rClassStatusId OR @rClassStatusId=0)
		AND ((R.ResultStatus=@rResultStatus) OR (@rResultStatus=''))
		AND (ISNULL(SM.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rMultiCode,',')) OR @rMultiCode='')

		ORDER BY 
			CASE @rOrderBy WHEN 0 THEN SM.Code END , 
			CASE @rOrderBy WHEN 1 THEN R.RankNumber END , 
			CASE @rOrderBy WHEN 2 THEN A.RollNo END, 
			CASE @rOrderBy WHEN 3 THEN SM.FirstName END,
			CASE @rOrderBy WHEN 4 THEN R.TotalObtain END
			
END
GO
PRINT N'Altering [sAssessment].[pRptResultSheetCCEMultiExamGet]...';


GO


ALTER PROCEDURE [sAssessment].[pRptResultSheetCCEMultiExamGet]
	 
	 @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
	 --,@rcolumn_visible bit
	 
	

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
 begin
 

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

 
  
DECLARE @GradeString nvarchar(1000),
@GradeSetId int , @IsIncludeSubExam bit
SELECT @GradeSetId = GradesetId,
	   @IsIncludeSubExam = ISNULL(IsIncludeSubExam,0)  FROM sAssessment.tExamMaster WHERE Id = @rExamId
SELECT @GradeString = [sAssessment].[fGradeStringGet](@GradeSetId)
 
--#TempAllExam
	CREATE TABLE #TempAllExam
	(
		AcademicIdText nvarchar(20),
		ExamIdText nvarchar(20),
		CoScholasticScopeIdText nvarchar(20),
		
		AcademicId bigint,
		ExamName Nvarchar(150),
		StudCode NVarchar(20),
		StudentName Nvarchar(150),
		RollNo int,
		ResultStatus Nvarchar(20),	
		ClassName NVarchar(50),		
		Division NVarchar(50),
		TotalMark decimal(8,2),
		TotalObtain decimal(8,2),
		Percentage decimal(8,2),
		RankNumber int,
		ResultGrade NVarchar(50),
		
		MaximumMark1 decimal(8,2),		
		SubjectGrade1 NVarchar(50),
		Obtain1 decimal(8,2),
		ExamMaximum1 decimal(8,2),
		IsPresent1 bit,
						
		MaximumMark2 decimal(8,2),	
		SubjectGrade2 NVarchar(50),
		Obtain2 decimal(8,2),
		ExamMaximum2 decimal(8,2),
		IsPresent2 bit,
				
		MaximumMark3 decimal(8,2),
		SubjectGrade3 NVarchar(50),
		Obtain3 decimal(8,2),
		ExamMaximum3 decimal(8,2),
		IsPresent3 bit,		
		
		MaximumMark4 decimal(8,2),	
		SubjectGrade4 NVarchar(50),
		Obtain4 decimal(8,2),
		ExamMaximum4 decimal(8,2),
		IsPresent4 bit,	
				
		MaximumMark5 decimal(8,2),		
		SubjectGrade5 NVarchar(50),
		Obtain5 decimal(8,2),
		ExamMaximum5 decimal(8,2),
		IsPresent5 bit,	
				
		MaximumMark6 decimal(8,2),		
		SubjectGrade6 NVarchar(50),
		Obtain6 decimal(8,2),
		ExamMaximum6 decimal(8,2),
		IsPresent6 bit,	
		
		MaximumMark7 decimal(8,2),		
		SubjectGrade7 NVarchar(50),
		Obtain7 decimal(8,2),
		ExamMaximum7 decimal(8,2),
		IsPresent7 bit,	
		
		MaximumMark8 decimal(8,2),	
		SubjectGrade8 NVarchar(50),
		Obtain8 decimal(8,2),
		ExamMaximum8 decimal(8,2),
		IsPresent8 bit,	
		
		SubjectGradeTerm1 NVarchar(50),
		SubjectGradeTerm2 NVarchar(50),
		IsMarksInDecimal bit,
		column_visible bit,
		--Obtain decimal(5,2),
		Percentile decimal(5,2),
		--ClassSubject nvarchar(100),
		ResultDetailId bigint,
		ResultId bigint,	
		Remark1 nvarchar(150),
		Remark2 nvarchar(150),
		Remark3 nvarchar(150),
		DisplayTitle nvarchar(150),		
		IsRankNo bit, 
		IsGrade bit,
		IsPercentile bit,
		IsPercentage bit,
		IsSubjectPercentile bit,
		IsProcessResult bit,
		IsNegativeMarks bit,
		IsIncludeCoScholastic bit,
		IsOnPrePrinted bit,
		IsDisplayPhoto bit,
		IsDisplayBirthDate bit,
		IsLockForEdit bit,
		IsDisplaySchoolName bit,			
		IsDisplayAttendance bit,
		IsDisplayHeightWeight bit,
		IsResultStatus bit,
		FooterAdjustmentText nvarchar(max),
		DetailAdjustmentText nvarchar(max),
		FooterAdjustment smallint,
		DetailAdjustment smallint,
		ResultRemark nvarchar(200),
		DateOfBirth date,
		HeightTerm1 decimal(5,2),
		WeightTerm1 decimal(5,2),
		HeightTerm2 decimal(5,2),
		WeightTerm2 decimal(5,2),
		HeightAnnual decimal(5,2),
		WeightAnnual decimal(5,2),
		PresentDaysTerm1 smallint,
		PresentDaysTerm2 smallint,
		PresentDaysAnnual smallint,
		TotalDaysTerm1 smallint,
		TotalDaysTerm2 smallint,
		TotalDaysAnnual smallint,
		TotalMarkTerm1 decimal(8,2),
		TotalObtainTerm1 decimal(8,2),
		PercentageTerm1 decimal(8,2),
		RankNumberTerm1 int,
		ResultGradeTerm1 NVarchar(50),
		PercentileTerm1 decimal(8,2),
		ResultStatusTerm1 Nvarchar(20),		   
		TotalMarkTerm2 decimal(8,2),
		TotalObtainTerm2 decimal(8,2),
		PercentageTerm2 decimal(8,2),
		RankNumberTerm2 int,
		ResultGradeTerm2 NVarchar(50),
		PercentileTerm2 decimal(8,2),
		ResultStatusTerm2 Nvarchar(20), 
		TermScopeId tinyint,		 
		StudentPhoto varbinary(max),
		GradeString nvarchar(1000),
		IsDisplayGradeString bit,		 
		IsDisplayInMarksheet bit,
		IsShowSubjectGrade bit,
		IsIncludeInTotal bit,
		ClassSubjectID int,
		SubjectId int,
		--Maximum decimal(5,2),
		SubjectOrderIndex smallint,
		SubjectGrade NVarchar(50),
		SubjectName NVarchar(150),
		SubjectCode Nvarchar(50),	
		SubjectMinimum decimal(8,2),		
		SubjectMaximum decimal(8,2),
		SubjectObtain  decimal(8,2),
		
		Exam1Name Nvarchar(150),		
		TotalMarks1 decimal(8,2),		
		TotalObtain1 decimal(8,2),
		Percentage1 decimal(8,2),
		RankNumber1 int,
		ResultGrade1 NVarchar(50),
		Percentile1 decimal(8,2),
		ResultStatus1 Nvarchar(20),
		
		Exam2Name nvarchar(150),	
		TotalMarks2 decimal(8,2),
		TotalObtain2 decimal(8,2),
		Percentage2 decimal(8,2),
		RankNumber2 int,
		ResultGrade2 NVarchar(50),
		Percentile2 decimal(8,2),
		ResultStatus2 Nvarchar(20),
		
		Exam3Name nvarchar(150),	
		TotalMarks3 decimal(8,2),
		TotalObtain3 decimal(8,2),
		Percentage3 decimal(8,2),
		RankNumber3 int,
		ResultGrade3 NVarchar(50),
		Percentile3 decimal(8,2),		
		ResultStatus3 Nvarchar(20),
		
		Exam4Name nvarchar(150),	
		TotalMarks4 decimal(8,2),
		TotalObtain4 decimal(8,2),
		Percentage4 decimal(8,2),
		RankNumber4 int,
		ResultGrade4 NVarchar(50),
		Percentile4 decimal(8,2),
		ResultStatus4 Nvarchar(20),
		
		Exam5Name nvarchar(150),		
		TotalMarks5 decimal(8,2),
		TotalObtain5 decimal(8,2),
		Percentage5 decimal(8,2),
		RankNumber5 int,
		ResultGrade5 NVarchar(50),
		Percentile5 decimal(8,2),
		ResultStatus5 Nvarchar(20),
		
		Exam6Name nvarchar(150),	
		TotalMarks6 decimal(8,2),
		TotalObtain6 decimal(8,2),
		Percentage6 decimal(8,2),
		RankNumber6 int,
		ResultGrade6 NVarchar(50),
		Percentile6 decimal(8,2),
		ResultStatus6 Nvarchar(20),
		
		Exam7Name nvarchar(150),		
		TotalMarks7 decimal(8,2),
		TotalObtain7 decimal(8,2),
		Percentage7 decimal(8,2),
		RankNumber7 int,
		ResultGrade7 NVarchar(50),
		Percentile7 decimal(8,2),
		ResultStatus7 Nvarchar(20),
		
		Exam8Name nvarchar(150),
		TotalMarks8 decimal(8,2),
		TotalObtain8 decimal(8,2),
		Percentage8 decimal(8,2),
		RankNumber8 int,
		ResultGrade8 NVarchar(50),
		Percentile8 decimal(8,2),
		ResultStatus8 Nvarchar(20),
		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,
		IsDisplayParentName bit,
		FatherName nvarchar(30),
		MotherName nvarchar(30),
		IsShowSubjectMark bit, 
		IsOptionalSubject bit,
		CoScholasticScopeId tinyint,
		IsDisplayPrincipalSign bit,
		IsDisplayTeacherSign bit,
		EmployeeSign varbinary(max),
		Batch nvarchar(100),
		ExamNameTerm1 NVarchar(100),
		ExamNameTerm2 NVarchar(100) 
		 
		
	)	
	 --print 'temp created'    	
	INSERT INTO  #TempAllExam 
	(
	AcademicIdText,
	ExamIdText,
	CoScholasticScopeIdText,
	
	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,
	IsDisplayParentName,
	FatherName,
	MotherName,
	IsShowSubjectMark,
	IsOptionalSubject,
	CoScholasticScopeId,
	IsDisplayPrincipalSign,
	IsDisplayTeacherSign,
	EmployeeSign,
	Batch 
	
 
 
	 
	)
	SELECT 
		Convert(nvarchar(20),A.Id),
		Convert(nvarchar(20),@rExamId),
		Convert(nvarchar(20),EM.CoScholasticScopeId),
		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,
		R.ResultStatus,
		CM.DisplayTitle AS ClassName,
		DM.DisplayTitle AS Division,
		R.TotalMarks AS TotalMark,
		R.TotalObtain,
		R.Percentage,
		R.RankNumber,
		R.ResultGrade,


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

		ISNULL(EM.Remark1,'') AS Remark1,
		ISNULL(EM.Remark2,'') AS Remark2,
		ISNULL(EM.Remark3,'') AS Remark3,
		EM.DisplayTitle,
		EM.IsRankNo, 
		EM.IsGrade,
		EM.IsPercentile,
		EM.IsPercentage,
		EM.IsSubjectPercentile,
		EM.IsProcessResult,
		EM.IsNegativeMarks,
		EM.IsIncludeCoScholastic,
		EM.IsOnPrePrinted,
		EM.IsDisplayPhoto,
		EM.IsDisplayBirthDate,
		EM.IsLockForEdit,
		EM.IsDisplaySchoolName,			
		EM.IsDisplayAttendance,
		EM.IsDisplayHeightWeight,
		EM.IsResultStatus,
		REPLICATE(',',EM.FooterAdjustment) AS FooterAdjustmentText,
		REPLICATE(',',EM.DetailAdjustment) AS DetailAdjustmentText,
		EM.FooterAdjustment,
		EM.DetailAdjustment,
		ISNULL(R.ResultRemark,'') AS ResultRemark,
		SO.DateOfBirth,
		AD.HeightTerm1,
		AD.WeightTerm1,
		AD.HeightTerm2,
		AD.WeightTerm2,
		AD.HeightAnnual,
		AD.WeightAnnual,
		AD.PresentDaysTerm1,
		AD.PresentDaysTerm2,
		AD.PresentDaysAnnual,
		AD.TotalDaysTerm1,
		AD.TotalDaysTerm2,
		AD.TotalDaysAnnual,
		EM.TermScopeId,
		SI.StudentPhoto,
		@GradeString AS GradeString,
		EM.IsDisplayGradeString,
		ED.IsDisplayInMarksheet,
		ED.IsShowSubjectGrade,
		ED.IsIncludeInTotal,
	    ED.ClassSubjectId,
		CS.SubjectId AS SubjectId,
		--ED.Maximum,
		(CASE ISNULL(ED.DisplayOrder,0)
		WHEN 0 THEN CS.OrderIndex
		ELSE ED.DisplayOrder END) AS SubjectOrderIndex,
		
		--SM.OrderIndex AS SubjectOrderIndex,
		RD.SubjectGrade,
		SM.Title AS SubjectName,
		ISNULL(SM.Code,'') AS SubjectCode,
		ED.Minimum,
		ED.Maximum,
		RD.Obtain,
		SR.ResultRemark1,
		SR.ResultRemark2,
		ISNULL(SR.TotalDays,0)AS TotalDays,
		ISNULL(SR.PresentDays,0)AS PresentDays,
		SR.StudentHeight,
		SR.StudentWeight,
		SR.ExamSeatNo,
		@rExamId,
		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,
		EI.EmployeeSign,
		BM.Title AS Batch 
		
		
		 
			
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					 
	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
	LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = Dm.InchargeEmployeeId
	
	INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.EXAMSUBGROUPID
	LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=StuM.Id
	LEFT JOIN sStudent.tAcademicDetail AD ON AD.AcademicId=A.Id
	LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=StuM.Id
	LEFT JOIN sAssessment.tStudentRemark SR ON R.AcademicId = SR.AcademicId AND R.ExamId = SR.ExamId
	LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = StuM.Id
	LEFT JOIN sAssessment.tOptionalSubject OS ON OS.AcademicId = R.AcademicId AND OS.ClassSubjectId = ED.ClassSubjectId  AND ED.ExamId = R.ExamId
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId
	--LEFT JOIN sAcademic.tTeacherSubjectDivision TSD ON TSD.SubjectId=SM.Id AND TSD.DivisionId = A.DivisionId
	--LEFT JOIN sHrm.tEmployeeMaster EMP ON TSD.EmployeeId = EMP.Id
	
	 WHERE
		R.ExamId = @rExamId 
		AND ((A.DivisionId =  @rDivisionId) OR (@rDivisionId=0))
		AND ((A.ClassId =  @rClassId) OR (@rClassId=0))		 
		AND ((A.BatchId =  @rBatchId) OR (@rBatchId=0))
		AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((R.RankNumber >= @rFromRank) OR (@rFromRank=0))
		AND ((R.RankNumber <= @rToRank) OR (@rToRank=0))
		AND ((R.ResultGrade = @rGrade) OR (@rGrade=''))
		AND ((StuM.Code=@rCode) OR (@rCode=''))	
		AND ((R.Id = @rResultId) OR (@rResultId = 0))	
		AND ((StuM.StatusId=@rStatusId)OR(@rStatusId=0))
		AND((A.Id=@rAcademicId)OR (@rAcademicId=0))
		AND ((CS.SubjectId=@rSubjectId) OR(@rSubjectId=0) ) 
		AND ((R.Percentage>=@rFromPercentage) OR (@rFromPercentage=0))
		AND ((R.Percentage<=@rToPercentage) OR (@rToPercentage=0))
		 
	 
	Order By ED.DisplayOrder
 
 --print 'temp insert'
  --SET @IsIncludeSubExam = 1
	create TABLE #tempcombineExam
	(	Id int IDENTITY,
		ExamID int )

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

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

--end
GO
PRINT N'Altering [sAssessment].[pRptResultSheetFloating]...';


GO


ALTER PROCEDURE [sAssessment].[pRptResultSheetFloating]
	 
	 @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,
	 @rClassStatusId int=0 ,
	 @rMultiCode nvarchar(max)=''

	
	 
	
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
 --Select * from dbo.Float
DECLARE @GradeString nvarchar(1000),
@GradeSetId int 
 
SELECT @GradeSetId = GradesetId FROM sAssessment.tExamMaster WHERE Id = @rExamId
SELECT @GradeString = [sAssessment].[fGradeStringGet](@GradeSetId)  

CREATE TABLE #TempExam
(
	ExamId int, 
	ExamOrderIndex int 
)
INSERT INTO #TempExam
(
	ExamId,	 
	ExamOrderIndex
)
Select 
	--EC.ExamId,
	EC.SubExamId,
	EC.ExamOrder 	 
	from sAssessment.tExamMaster EM 
	INNER JOIN sAssessment.tExamCombine EC ON EC.ExamId = EM.Id 
	WHERE EM.Id=@rExamId 
	
INSERT INTO #TempExam
(
	ExamId,
	--SubExamId,
	ExamOrderIndex
)
Select 
	--EC.ExamId,
	@rExamId,
	999
	
	SELECT 
			Convert(nvarchar(20),A.Id) AS AcademicIdText,
			Convert(nvarchar(20),@rExamId) AS ExamIdText,
			Convert(nvarchar(20),ISNULL(EM.IsDisplayMonthlyAttendance,0)) AS IsDisplayMonthlyAttendanceText,
			ESGM.Title AS Exam,
			StuM.Code,
	[sStudent].[fStudentNameGet](stum.FirstName , StuM.MiddleName, StuM.LastName,OM.StudentNameFormatId ) AS Name,
			A.RollNo,
			R.AcademicId,			
			R.ResultStatus,
			CM.DisplayTitle AS Class,
			DM.DisplayTitle AS Division,
			R.TotalMarks,
			R.TotalObtain,
			R.Percentage,
			R.RankNumber,
			R.ResultGrade,
			R.Percentile,			
			RD.Id AS ResultDetailId,		
			ED.IsDisplayInMarksheet,
			ED.IsShowSubjectGrade,
			ED.IsIncludeInTotal,
			RD.Obtain AS SubjectObtain,
			ED.Minimum AS SubjectMinimum,
			ED.Maximum AS SubjectMaximum,
			RD.SubjectGrade,
			SM.Code AS SubjectCode,
			SM.Title AS SubjectName,
			(CASE ISNULL(ED.DisplayOrder,0)
			WHEN 0 THEN CS.OrderIndex
			ELSE ED.DisplayOrder END) AS SubjectOrderIndex,
			R.Id AS ResultId,
			CS.Id AS SubjectId,			 	
			EM.IsMarksInDecimal,
			--SM.OrderIndex AS SubjectCode,
			
			--CS.OrderIndex AS SubjectOrderIndex,
			ISNULL(EM.Remark1,'') AS Remark1,
			ISNULL(EM.Remark2,'') AS Remark2,
			ISNULL(EM.Remark3,'') AS Remark3,
			EM.DisplayTitle,
			EM.IsRankNo, 
			EM.IsGrade,
			EM.IsPercentile,
			EM.IsPercentage,
			EM.IsSubjectPercentile,
			EM.IsProcessResult,
			EM.IsMarksInDecimal,
			EM.IsNegativeMarks,
			EM.IsIncludeCoScholastic,
			EM.IsOnPrePrinted,
			EM.IsDisplayPhoto,
			EM.IsDisplayBirthDate,
			EM.IsLockForEdit,
			EM.IsDisplaySchoolName,			
			EM.IsDisplayAttendance,
			EM.IsDisplayHeightWeight,
			EM.IsResultStatus,
			REPLICATE(',',EM.FooterAdjustment) AS FooterAdjustmentText,
			REPLICATE(',',EM.DetailAdjustment) AS DetailAdjustmentText,
			EM.FooterAdjustment,
			EM.DetailAdjustment,
			--ISNULL(R.ResultRemark,'') AS ResultRemark,
			SO.DateOfBirth,
			SR.StudentHeight,
			SR.StudentWeight,		
			ISNULL(SR.PresentDays,0)AS PresentDays,			
			ISNULL(SR.TotalDays,0)AS TotalDays,
			SR.ResultRemark1,
			SR.ResultRemark2,						 
			EM.TermScopeId,
			(CASE EM.IsDisplayPhoto WHEN 1 THEN
				SI.StudentPhoto
			ELSE NULL END) AS StudentPhoto,
			RD.IsPresent,
			@GradeString AS GradeString,
			EM.IsDisplayGradeString,
			(CASE EM.IsDisplayHighestDivisionMark
			WHEN 1 THEN [sAssessment].[fGetHighestDivisionMark](A.DivisionId ,RD.ExamDetailId)
			ELSE 0 END) AS HighestDivisionMark,
			(CASE EM.IsDisplayHighestDivisionGrade
			WHEN 1 THEN [sAssessment].[fGetHighestDivisionGrade] (A.DivisionId ,RD.ExamDetailId)
			ELSE '' END) AS HighestDivisionGrade,			
			OM.SmallAddress1,
			EM.IsDisplayParentName,
			SF.FatherName,
			SF.MotherName,
			ISNULL(ED.IsShowSubjectMark,1) AS IsShowSubjectMark,
			
			EM.IsDisplayTeacherSign,
			Em.IsDisplayPrincipalSign,
			(CASE 	EM.IsDisplayTeacherSign WHEN 1 THEN
				EI.EmployeeSign
			ELSE NULL END)AS EmployeeSign,
			ISNULL(EM.IsDisplayMonthlyAttendance,0) AS IsDisplayMonthlyAttendance,
			(CASE EM.IsDisplayImageHeader WHEN 1 THEN 
				OI.CertificateHeaderA4 
			ELSE 
				NULL END) AS MarkSheetHeaderA4,
			ISNULL(EM.IsDisplayImageHeader,0) AS IsImageHeader,
			ISNULL(SR.MyGoal,'') AS MyGoal,
			ISNULL(SR.AreaOfInterest,'') AS AreaOfInterest,
			ISNULL(SR.Responsibility,'') AS Responsibility,
			ISNULL(SR.MyInterestHobby,'') AS MyInterestHobby,
			ISNULL(SR.MyStrength,'') AS MyStrength,
			ISNULL(SR.Achievements,'') AS Achievements,
			ISNULL(SR.DentalHygiene,'') AS DentalHygiene,
			ISNULL(SR.VisionLeft,'') AS VisionLeft,
			ISNULL(SR.VisionRight,'') AS VisionRight,
			 
			EC.ExamId,
			EC.ExamOrderIndex,
			EM.DecimalFormat,
			SM.Code
			
			--[sAssessment].[fGetHighestDivisionMark](A.DivisionId ,RD.ExamDetailId) AS HighestDivisionMark,
			--[sAssessment].[fGetHighestDivisionGrade] (A.DivisionId ,RD.ExamDetailId) AS HighestDivisionGrade
			
			
			
	FROM 
			sAssessment.tResultDetail RD
			INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
			INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
			INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId		
			INNER JOIN #TempExam EC ON EC.ExamId = EM.Id 	
			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.tOrganizationMaster OM ON OM.Id=A.OrgId
			LEFT JOIN sSetup.tOrgImages OI ON OI.Orgid = OM.Id
			LEFT JOIN sStudent.tAcademicDetail AD ON AD.AcademicId=A.Id
			INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
			LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
			LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=StuM.Id
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
			LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = Dm.InchargeEmployeeId
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.EXAMSUBGROUPID
			LEFT JOIN sAssessment.tStudentRemark SR ON R.AcademicId = SR.AcademicId AND R.ExamId = SR.ExamId
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = StuM.Id
	WHERE 
			
		((EM.BatchId = @rBatchId) OR  (@rBatchId = 0))
		AND ((A.ClassId=@rClassId) OR (@rClassId=0)) 
		AND ((SM.Id=@rSubjectId) OR (@rSubjectId=0))
		AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((R.RankNumber >= @rFromRank) OR (@rFromRank=0))
		AND ((R.RankNumber <= @rToRank) OR (@rToRank=0))
		AND ((R.ResultGrade = @rGrade) OR (@rGrade=''))
		--AND (R.ExamId = @rExamId)
	 
		AND ((StuM.Code=@rCode) OR (@rCode=''))
		AND ((R.Id = @rResultId) OR (@rResultId = 0))
		AND ((StuM.StatusId=@rStatusId)OR(@rStatusId=0))
		AND ((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 A.RollNo,CS.OrderIndex 
		 drop table #TempExam
END
GO
PRINT N'Altering [sAssessment].[pRptResultSheetGSEB10MultiExamGet]...';


GO

ALTER PROCEDURE [sAssessment].[pRptResultSheetGSEB10MultiExamGet]
	 
	 @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
	 --,@rcolumn_visible bit
	 
	

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
 begin
 

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

 
  
DECLARE @GradeString nvarchar(1000),
@GradeSetId int , @IsIncludeSubExam bit
SELECT @GradeSetId = GradesetId,
	   @IsIncludeSubExam = ISNULL(IsIncludeSubExam,0)  FROM sAssessment.tExamMaster WHERE Id = @rExamId
SELECT @GradeString = [sAssessment].[fGradeStringGet](@GradeSetId)
 
--#TempAllExam
	CREATE TABLE #TempAllExam
	(
		AcademicIdText nvarchar(20),
		ExamIdText nvarchar(20),
		AcademicId bigint,
		ExamName Nvarchar(150),
		StudCode NVarchar(20),
		StudentName Nvarchar(150),
		RollNo int,
		ResultStatus Nvarchar(20),	
		ClassName NVarchar(50),		
		Division NVarchar(50),
		TotalMark decimal(8,2),
		TotalObtain decimal(8,2),
		Percentage decimal(8,2),
		RankNumber int,
		ResultGrade NVarchar(50),
		
		MaximumMark1 decimal(8,2),		
		SubjectGrade1 NVarchar(50),
		Obtain1 decimal(8,2),
		ExamMaximum1 decimal(8,2),
		IsPresent1 bit,
						
		MaximumMark2 decimal(8,2),	
		SubjectGrade2 NVarchar(50),
		Obtain2 decimal(8,2),
		ExamMaximum2 decimal(8,2),
		IsPresent2 bit,
				
		MaximumMark3 decimal(8,2),
		SubjectGrade3 NVarchar(50),
		Obtain3 decimal(8,2),
		ExamMaximum3 decimal(8,2),
		IsPresent3 bit,		
		
		MaximumMark4 decimal(8,2),	
		SubjectGrade4 NVarchar(50),
		Obtain4 decimal(8,2),
		ExamMaximum4 decimal(8,2),
		IsPresent4 bit,	
				
		MaximumMark5 decimal(8,2),		
		SubjectGrade5 NVarchar(50),
		Obtain5 decimal(8,2),
		ExamMaximum5 decimal(8,2),
		IsPresent5 bit,	
				
		MaximumMark6 decimal(8,2),		
		SubjectGrade6 NVarchar(50),
		Obtain6 decimal(8,2),
		ExamMaximum6 decimal(8,2),
		IsPresent6 bit,	
		
		MaximumMark7 decimal(8,2),		
		SubjectGrade7 NVarchar(50),
		Obtain7 decimal(8,2),
		ExamMaximum7 decimal(8,2),
		IsPresent7 bit,	
		
		MaximumMark8 decimal(8,2),	
		SubjectGrade8 NVarchar(50),
		Obtain8 decimal(8,2),
		ExamMaximum8 decimal(8,2),
		IsPresent8 bit,	
		
		MaximumMark9 decimal(8,2),	
		SubjectGrade9 NVarchar(50),
		Obtain9 decimal(8,2),
		ExamMaximum9 decimal(8,2),
		IsPresent9 bit,	

		MaximumMark10 decimal(8,2),	
		SubjectGrade10 NVarchar(50),
		Obtain10 decimal(8,2),
		ExamMaximum10 decimal(8,2),
		IsPresent10 bit,	

		MaximumMark11 decimal(8,2),	
		SubjectGrade11 NVarchar(50),
		Obtain11 decimal(8,2),
		ExamMaximum11 decimal(8,2),
		IsPresent11 bit,
		
		SubjectGradeTerm1 NVarchar(50),
		SubjectGradeTerm2 NVarchar(50),
		IsMarksInDecimal bit,
		column_visible bit,
		--Obtain decimal(5,2),
		Percentile decimal(5,2),
		--ClassSubject nvarchar(100),
		ResultDetailId bigint,
		ResultId bigint,	
		Remark1 nvarchar(150),
		Remark2 nvarchar(150),
		Remark3 nvarchar(150),
		DisplayTitle nvarchar(150),		
		IsRankNo bit, 
		IsGrade bit,
		IsPercentile bit,
		IsPercentage bit,
		IsSubjectPercentile bit,
		IsProcessResult bit,
		IsNegativeMarks bit,
		IsIncludeCoScholastic bit,
		IsOnPrePrinted bit,
		IsDisplayPhoto bit,
		IsDisplayBirthDate bit,
		IsLockForEdit bit,
		IsDisplaySchoolName bit,			
		IsDisplayAttendance bit,
		IsDisplayHeightWeight bit,
		IsResultStatus bit,
		FooterAdjustmentText nvarchar(max),
		DetailAdjustmentText nvarchar(max),
		FooterAdjustment smallint,
		DetailAdjustment smallint,
		ResultRemark nvarchar(200),
		DateOfBirth date,
		HeightTerm1 decimal(5,2),
		WeightTerm1 decimal(5,2),
		HeightTerm2 decimal(5,2),
		WeightTerm2 decimal(5,2),
		HeightAnnual decimal(5,2),
		WeightAnnual decimal(5,2),
		PresentDaysTerm1 smallint,
		PresentDaysTerm2 smallint,
		PresentDaysAnnual smallint,
		TotalDaysTerm1 smallint,
		TotalDaysTerm2 smallint,
		TotalDaysAnnual smallint,
		TotalMarkTerm1 decimal(8,2),
		TotalObtainTerm1 decimal(8,2),
		PercentageTerm1 decimal(8,2),
		RankNumberTerm1 int,
		ResultGradeTerm1 NVarchar(50),
		PercentileTerm1 decimal(8,2),
		ResultStatusTerm1 Nvarchar(20),		   
		TotalMarkTerm2 decimal(8,2),
		TotalObtainTerm2 decimal(8,2),
		PercentageTerm2 decimal(8,2),
		RankNumberTerm2 int,
		ResultGradeTerm2 NVarchar(50),
		PercentileTerm2 decimal(8,2),
		ResultStatusTerm2 Nvarchar(20), 
		TermScopeId tinyint,		 
		StudentPhoto varbinary(max),
		GradeString nvarchar(1000),
		IsDisplayGradeString bit,		 
		IsDisplayInMarksheet bit,
		IsShowSubjectGrade bit,
		IsIncludeInTotal bit,
		ClassSubjectID int,
		SubjectId int,
		--Maximum decimal(5,2),
		SubjectOrderIndex smallint,
		SubjectGrade NVarchar(50),
		SubjectName NVarchar(150),
		SubjectCode Nvarchar(50),	
		SubjectMinimum decimal(8,2),		
		SubjectMaximum decimal(8,2),
		SubjectObtain  decimal(8,2),
		
		Exam1Name Nvarchar(150),		
		TotalMarks1 decimal(8,2),		
		TotalObtain1 decimal(8,2),
		Percentage1 decimal(8,2),
		RankNumber1 int,
		ResultGrade1 NVarchar(50),
		Percentile1 decimal(8,2),
		ResultStatus1 Nvarchar(20),
		
		Exam2Name nvarchar(150),	
		TotalMarks2 decimal(8,2),
		TotalObtain2 decimal(8,2),
		Percentage2 decimal(8,2),
		RankNumber2 int,
		ResultGrade2 NVarchar(50),
		Percentile2 decimal(8,2),
		ResultStatus2 Nvarchar(20),
		
		Exam3Name nvarchar(150),	
		TotalMarks3 decimal(8,2),
		TotalObtain3 decimal(8,2),
		Percentage3 decimal(8,2),
		RankNumber3 int,
		ResultGrade3 NVarchar(50),
		Percentile3 decimal(8,2),		
		ResultStatus3 Nvarchar(20),
		
		Exam4Name nvarchar(150),	
		TotalMarks4 decimal(8,2),
		TotalObtain4 decimal(8,2),
		Percentage4 decimal(8,2),
		RankNumber4 int,
		ResultGrade4 NVarchar(50),
		Percentile4 decimal(8,2),
		ResultStatus4 Nvarchar(20),
		
		Exam5Name nvarchar(150),		
		TotalMarks5 decimal(8,2),
		TotalObtain5 decimal(8,2),
		Percentage5 decimal(8,2),
		RankNumber5 int,
		ResultGrade5 NVarchar(50),
		Percentile5 decimal(8,2),
		ResultStatus5 Nvarchar(20),
		
		Exam6Name nvarchar(150),	
		TotalMarks6 decimal(8,2),
		TotalObtain6 decimal(8,2),
		Percentage6 decimal(8,2),
		RankNumber6 int,
		ResultGrade6 NVarchar(50),
		Percentile6 decimal(8,2),
		ResultStatus6 Nvarchar(20),
		
		Exam7Name nvarchar(150),		
		TotalMarks7 decimal(8,2),
		TotalObtain7 decimal(8,2),
		Percentage7 decimal(8,2),
		RankNumber7 int,
		ResultGrade7 NVarchar(50),
		Percentile7 decimal(8,2),
		ResultStatus7 Nvarchar(20),
		
		Exam8Name nvarchar(150),
		TotalMarks8 decimal(8,2),
		TotalObtain8 decimal(8,2),
		Percentage8 decimal(8,2),
		RankNumber8 int,
		ResultGrade8 NVarchar(50),
		Percentile8 decimal(8,2),
		ResultStatus8 Nvarchar(20),
		
		Exam9Name nvarchar(150),
		TotalMarks9 decimal(8,2),
		TotalObtain9 decimal(8,2),
		Percentage9 decimal(8,2),
		RankNumber9 int,
		ResultGrade9 NVarchar(50),
		Percentile9 decimal(8,2),
		ResultStatus9 Nvarchar(20),

		Exam10Name nvarchar(150),
		TotalMarks10 decimal(8,2),
		TotalObtain10 decimal(8,2),
		Percentage10 decimal(8,2),
		RankNumber10 int,
		ResultGrade10 NVarchar(50),
		Percentile10 decimal(8,2),
		ResultStatus10 Nvarchar(20),

		Exam11Name nvarchar(150),
		TotalMarks11 decimal(8,2),
		TotalObtain11 decimal(8,2),
		Percentage11 decimal(8,2),
		RankNumber11 int,
		ResultGrade11 NVarchar(50),
		Percentile11 decimal(8,2),
		ResultStatus11 Nvarchar(20),
		
		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,
		IsDisplayParentName bit,
		FatherName nvarchar(30),
		MotherName nvarchar(30),
		IsShowSubjectMark bit, 
		SubjectGroupTypeId smallint,
		IsDisplayPrincipalSign bit,
		IsDisplayTeacherSign bit,
		EmployeeSign varbinary(max),
		MarksheetHeaderA4 varbinary(max),
		IsImageHeader bit
		 
		
	)	
	 --print 'temp created'    	
	INSERT INTO  #TempAllExam
	(
	AcademicIdText,
	ExamIdText,
	
	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,
	IsDisplayParentName,
	FatherName,
	MotherName,
	IsShowSubjectMark ,
	SubjectGroupTypeId,
	IsDisplayPrincipalSign,
	IsDisplayTeacherSign,
	EmployeeSign,
	MarksheetHeaderA4,
	IsImageHeader
 
 
	 
	)
	SELECT 
		Convert(nvarchar(20),A.Id),
		Convert(nvarchar(20),@rExamId),
 
		A.Id,
		ISNULL(ESGM.Title,'') AS EXAMNAME,
		StuM.Code AS StudCode,
		StuM.FirstName+' '+StuM.MiddleName+' '+StuM.LastName AS Name,
		A.RollNo,
		R.ResultStatus,
		CM.DisplayTitle AS ClassName,
		DM.DisplayTitle AS Division,
		R.TotalMarks AS TotalMark,
		R.TotalObtain,
		R.Percentage,
		R.RankNumber,
		R.ResultGrade,


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

		ISNULL(EM.Remark1,'') AS Remark1,
		ISNULL(EM.Remark2,'') AS Remark2,
		ISNULL(EM.Remark3,'') AS Remark3,
		EM.DisplayTitle,
		EM.IsRankNo, 
		EM.IsGrade,
		EM.IsPercentile,
		EM.IsPercentage,
		EM.IsSubjectPercentile,
		EM.IsProcessResult,
		EM.IsNegativeMarks,
		EM.IsIncludeCoScholastic,
		EM.IsOnPrePrinted,
		EM.IsDisplayPhoto,
		EM.IsDisplayBirthDate,
		EM.IsLockForEdit,
		EM.IsDisplaySchoolName,			
		EM.IsDisplayAttendance,
		EM.IsDisplayHeightWeight,
		EM.IsResultStatus,
		REPLICATE(',',EM.FooterAdjustment) AS FooterAdjustmentText,
		REPLICATE(',',EM.DetailAdjustment) AS DetailAdjustmentText,
		EM.FooterAdjustment,
		EM.DetailAdjustment,
		ISNULL(R.ResultRemark,'') AS ResultRemark,
		SO.DateOfBirth,
		AD.HeightTerm1,
		AD.WeightTerm1,
		AD.HeightTerm2,
		AD.WeightTerm2,
		AD.HeightAnnual,
		AD.WeightAnnual,
		AD.PresentDaysTerm1,
		AD.PresentDaysTerm2,
		AD.PresentDaysAnnual,
		AD.TotalDaysTerm1,
		AD.TotalDaysTerm2,
		AD.TotalDaysAnnual,
		EM.TermScopeId,
		SI.StudentPhoto,
		@GradeString AS GradeString,
		EM.IsDisplayGradeString,
		ED.IsDisplayInMarksheet,
		ED.IsShowSubjectGrade,
		ED.IsIncludeInTotal,
	    ED.ClassSubjectId,
		CS.SubjectId AS SubjectId,
		--ED.Maximum,
		(CASE ISNULL(ED.DisplayOrder,0)
		WHEN 0 THEN CS.OrderIndex
		ELSE ED.DisplayOrder END) AS SubjectOrderIndex,
		
		--SM.OrderIndex AS SubjectOrderIndex,
		RD.SubjectGrade,
		SM.Title AS SubjectName,
		ISNULL(SM.Code,'') AS SubjectCode,
		ED.Minimum,
		ED.Maximum,
		RD.Obtain,
		SR.ResultRemark1,
		SR.ResultRemark2,
		ISNULL(SR.TotalDays,0)AS TotalDays,
		ISNULL(SR.PresentDays,0)AS PresentDays,
		SR.StudentHeight,
		SR.StudentWeight,
		SR.ExamSeatNo,
		@rExamId,
		EM.IsDisplayParentName,
		SF.FatherName,
		SF.MotherName,
		ED.IsShowSubjectMark,
		CASE WHEN CS.IsOptional =0 AND CS.IsPractical=0 THEN 1 
			WHEN CS.IsOptional = 1 AND CS.IsPractical = 0 THEN 2
			WHEN CS.IsPractical = 1 THEN 4
		            
         END as SubjectGroupTypeId  	,
         		EM.IsDisplayPrincipalSign,
		Em.IsDisplayTeacherSign,
		EI.EmployeeSign,
		(CASE EM.IsDisplayImageHeader WHEN 1 THEN
			OI.CertificateHeaderA4 
			ELSE NULL END)AS  MarksheetHeaderA4,
		ISNULL(EM.IsDisplayImageHeader,0) AS IsImageHeader			
		--EMP.FirstName
		
		 
			
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					 
	INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
	INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
	INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
	INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
	LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = Dm.InchargeEmployeeId
	INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.EXAMSUBGROUPID
	LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=StuM.Id
	LEFT JOIN sStudent.tAcademicDetail AD ON AD.AcademicId=A.Id
	LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=StuM.Id
	LEFT JOIN sAssessment.tStudentRemark SR ON R.AcademicId = SR.AcademicId AND R.ExamId = SR.ExamId
	LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = StuM.Id
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = StuM.OrgId
	LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = OM.Id
	
	--LEFT JOIN sAcademic.tTeacherSubjectDivision TSD ON TSD.SubjectId=SM.Id AND TSD.DivisionId = A.DivisionId
	--LEFT JOIN sHrm.tEmployeeMaster EMP ON TSD.EmployeeId = EMP.Id
	
	 WHERE
		R.ExamId = @rExamId 
		AND ((A.DivisionId =  @rDivisionId) OR (@rDivisionId=0))
		AND ((A.ClassId =  @rClassId) OR (@rClassId=0))		 
		AND ((A.BatchId =  @rBatchId) OR (@rBatchId=0))
		AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((R.RankNumber >= @rFromRank) OR (@rFromRank=0))
		AND ((R.RankNumber <= @rToRank) OR (@rToRank=0))
		AND ((R.ResultGrade = @rGrade) OR (@rGrade=''))
		AND ((StuM.Code=@rCode) OR (@rCode=''))	
		AND ((R.Id = @rResultId) OR (@rResultId = 0))	
		AND ((StuM.StatusId=@rStatusId)OR(@rStatusId=0))
		AND((A.Id=@rAcademicId)OR (@rAcademicId=0))
		AND ((CS.SubjectId=@rSubjectId) OR(@rSubjectId=0) ) 
		 
	 
	Order By ED.DisplayOrder
 
 --print 'temp insert'
  --SET @IsIncludeSubExam = 1
	create TABLE #tempcombineExam
	(	Id int IDENTITY,
		ExamID int )

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

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

--end
GO
PRINT N'Altering [sAssessment].[pRptResultSheetNCRTExamGet]...';


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

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
 begin
 

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

 Declare @lLinkExamId int
 Select @lLinkExamId = LinkExamId From sAssessment.tExamMaster Where ClassId=@rClassID AND Id=@rExamId ANd BatchId=@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 = @lLinkExamId
SELECT @GradeString = [sAssessment].[fGradeStringGet](@GradeSetId)

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

 

--#TempAllExam
	CREATE TABLE #TempAllExam
	(
		AcademicIdText nvarchar(20),
		ExamIdText nvarchar(20),
		CoScholasticScopeIdText nvarchar(20),
		IsDisplayMonthlyAttendanceText nvarchar(20),
		ClassIdText nvarchar(50),
		
		AcademicId bigint,
		ExamName Nvarchar(150),
		StudCode NVarchar(20),
		StudentName Nvarchar(150),
		RollNo int,
		ResultStatus Nvarchar(20),	
		ClassName NVarchar(50),		
		Division NVarchar(50),
		TotalMark decimal(8,2),
		TotalObtain decimal(8,2),
		Percentage decimal(8,2),
		RankNumber int,
		ResultGrade NVarchar(50),
		
		MaximumMark1 decimal(8,2),		
		SubjectGrade1 NVarchar(50),
		Obtain1 decimal(8,2),
		ExamMaximum1 decimal(8,2),
		IsPresent1 bit,
						
		MaximumMark2 decimal(8,2),	
		SubjectGrade2 NVarchar(50),
		Obtain2 decimal(8,2),
		ExamMaximum2 decimal(8,2),
		IsPresent2 bit,
				
		MaximumMark3 decimal(8,2),
		SubjectGrade3 NVarchar(50),
		Obtain3 decimal(8,2),
		ExamMaximum3 decimal(8,2),
		IsPresent3 bit,		
		
		MaximumMark4 decimal(8,2),	
		SubjectGrade4 NVarchar(50),
		Obtain4 decimal(8,2),
		ExamMaximum4 decimal(8,2),
		IsPresent4 bit,	
				
		MaximumMark5 decimal(8,2),		
		SubjectGrade5 NVarchar(50),
		Obtain5 decimal(8,2),
		ExamMaximum5 decimal(8,2),
		IsPresent5 bit,	
				
		MaximumMark6 decimal(8,2),		
		SubjectGrade6 NVarchar(50),
		Obtain6 decimal(8,2),
		ExamMaximum6 decimal(8,2),
		IsPresent6 bit,	
		
		MaximumMark7 decimal(8,2),		
		SubjectGrade7 NVarchar(50),
		Obtain7 decimal(8,2),
		ExamMaximum7 decimal(8,2),
		IsPresent7 bit,	
		
		MaximumMark8 decimal(8,2),	
		SubjectGrade8 NVarchar(50),
		Obtain8 decimal(8,2),
		ExamMaximum8 decimal(8,2),
		IsPresent8 bit,	
		
		MaximumMark9 decimal(8,2),		
		SubjectGrade9 NVarchar(50),
		Obtain9 decimal(8,2),
		ExamMaximum9 decimal(8,2),
		IsPresent9 bit,	
		
		
		MaximumMark10 decimal(8,2),		
		SubjectGrade10 NVarchar(50),
		Obtain10 decimal(8,2),
		ExamMaximum10 decimal(8,2),
		IsPresent10 bit,	
		
			MaximumMark11 decimal(8,2),		
		SubjectGrade11 NVarchar(50),
		Obtain11 decimal(8,2),
		ExamMaximum11 decimal(8,2),
		IsPresent11 bit,
		
		MaximumMark12 decimal(8,2),		
		SubjectGrade12 NVarchar(50),
		Obtain12 decimal(8,2),
		ExamMaximum12 decimal(8,2),
		IsPresent12 bit,		
		 
		 
		SubjectGradeTerm1 NVarchar(50),
		SubjectGradeTerm2 NVarchar(50),
		SubjectGradeTerm3 NVarchar(50),
		IsMarksInDecimal bit,
		column_visible bit,
		--Obtain decimal(5,2),
		Percentile decimal(5,2),
		--ClassSubject nvarchar(100),
		ResultDetailId bigint,
		ResultId bigint,	
		Remark1 nvarchar(500),
		Remark2 nvarchar(500),
		Remark3 nvarchar(500),
		DisplayTitle nvarchar(150),		
		IsRankNo bit, 
		IsGrade bit,
		IsPercentile bit,
		IsPercentage bit,
		IsSubjectPercentile bit,
		IsProcessResult bit,
		IsNegativeMarks bit,
		IsIncludeCoScholastic bit,
		IsOnPrePrinted bit,
		IsDisplayPhoto bit,
		IsDisplayBirthDate bit,
		IsLockForEdit bit,
		IsDisplaySchoolName bit,			
		IsDisplayAttendance bit,
		IsDisplayHeightWeight bit,
		IsResultStatus bit,
		FooterAdjustmentText nvarchar(max),
		DetailAdjustmentText nvarchar(max),
		FooterAdjustment smallint,
		DetailAdjustment smallint,
		ResultRemark nvarchar(200),
		DateOfBirth date,
		HeightTerm1 decimal(5,2),
		WeightTerm1 decimal(5,2),
		HeightTerm2 decimal(5,2),
		WeightTerm2 decimal(5,2),
		HeightAnnual decimal(5,2),
		WeightAnnual decimal(5,2),
		PresentDaysTerm1 smallint,
		PresentDaysTerm2 smallint,
		PresentDaysAnnual smallint,
		TotalDaysTerm1 smallint,
		TotalDaysTerm2 smallint,
		TotalDaysAnnual smallint,
		TotalMarkTerm1 decimal(8,2),
		TotalObtainTerm1 decimal(8,2),
		PercentageTerm1 decimal(8,2),
		RankNumberTerm1 int,
		ResultGradeTerm1 NVarchar(50),
		PercentileTerm1 decimal(8,2),
		ResultStatusTerm1 Nvarchar(20),		   
		TotalMarkTerm2 decimal(8,2),
		TotalObtainTerm2 decimal(8,2),
		PercentageTerm2 decimal(8,2),
		RankNumberTerm2 int,
		ResultGradeTerm2 NVarchar(50),
		PercentileTerm2 decimal(8,2),
		ResultStatusTerm2 Nvarchar(20), 
		TotalMarkTerm3 		decimal(8,2),
		TotalObtainTerm3 decimal(8,2),
		PercentageTerm3 decimal(8,2),
		RankNumberTerm3 int,
		ResultGradeTerm3 NVarchar(50),
		PercentileTerm3 decimal(8,2),
		ResultStatusTerm3 Nvarchar(20), 
		
		TermScopeId tinyint,		 
		StudentPhoto varbinary(max),
		GradeString nvarchar(1000),
		IsDisplayGradeString bit,		 
		IsDisplayInMarksheet bit,
		IsShowSubjectGrade bit,
		IsIncludeInTotal bit,
		ClassSubjectID int,
		SubjectId int,
		--Maximum decimal(5,2),
		SubjectOrderIndex smallint,
		SubjectGrade NVarchar(50),
		SubjectName NVarchar(150),
		SubjectCode Nvarchar(50),	
		SubjectMinimum decimal(8,2),		
		SubjectMaximum decimal(8,2),
		SubjectObtain  decimal(8,2),
		
		Exam1Name Nvarchar(150),		
		TotalMarks1 decimal(8,2),		
		TotalObtain1 decimal(8,2),
		Percentage1 decimal(8,2),
		RankNumber1 int,
		ResultGrade1 NVarchar(50),
		Percentile1 decimal(8,2),
		ResultStatus1 Nvarchar(20),
		
		Exam2Name nvarchar(150),	
		TotalMarks2 decimal(8,2),
		TotalObtain2 decimal(8,2),
		Percentage2 decimal(8,2),
		RankNumber2 int,
		ResultGrade2 NVarchar(50),
		Percentile2 decimal(8,2),
		ResultStatus2 Nvarchar(20),
		
		Exam3Name nvarchar(150),	
		TotalMarks3 decimal(8,2),
		TotalObtain3 decimal(8,2),
		Percentage3 decimal(8,2),
		RankNumber3 int,
		ResultGrade3 NVarchar(50),
		Percentile3 decimal(8,2),		
		ResultStatus3 Nvarchar(20),
		
		Exam4Name nvarchar(150),	
		TotalMarks4 decimal(8,2),
		TotalObtain4 decimal(8,2),
		Percentage4 decimal(8,2),
		RankNumber4 int,
		ResultGrade4 NVarchar(50),
		Percentile4 decimal(8,2),
		ResultStatus4 Nvarchar(20),
		
		Exam5Name nvarchar(150),		
		TotalMarks5 decimal(8,2),
		TotalObtain5 decimal(8,2),
		Percentage5 decimal(8,2),
		RankNumber5 int,
		ResultGrade5 NVarchar(50),
		Percentile5 decimal(8,2),
		ResultStatus5 Nvarchar(20),
		
		Exam6Name nvarchar(150),	
		TotalMarks6 decimal(8,2),
		TotalObtain6 decimal(8,2),
		Percentage6 decimal(8,2),
		RankNumber6 int,
		ResultGrade6 NVarchar(50),
		Percentile6 decimal(8,2),
		ResultStatus6 Nvarchar(20),
		
		Exam7Name nvarchar(150),		
		TotalMarks7 decimal(8,2),
		TotalObtain7 decimal(8,2),
		Percentage7 decimal(8,2),
		RankNumber7 int,
		ResultGrade7 NVarchar(50),
		Percentile7 decimal(8,2),
		ResultStatus7 Nvarchar(20),
		
		Exam8Name nvarchar(150),
		TotalMarks8 decimal(8,2),
		TotalObtain8 decimal(8,2),
		Percentage8 decimal(8,2),
		RankNumber8 int,
		ResultGrade8 NVarchar(50),
		Percentile8 decimal(8,2),
		ResultStatus8 Nvarchar(20),
		
		
		Exam9Name nvarchar(150),	
		TotalMarks9 decimal(8,2),
		TotalObtain9 decimal(8,2),
		Percentage9 decimal(8,2),
		RankNumber9 int,
		ResultGrade9 NVarchar(50),
		Percentile9 decimal(8,2),
		ResultStatus9 Nvarchar(20),
		
		Exam10Name nvarchar(150),	
		TotalMarks10 decimal(8,2),
		TotalObtain10 decimal(8,2),
		Percentage10 decimal(8,2),
		RankNumber10 int,
		ResultGrade10 NVarchar(50),
		Percentile10 decimal(8,2),
		ResultStatus10 Nvarchar(20),
		
		Exam11Name nvarchar(150),	
		TotalMarks11 decimal(8,2),
		TotalObtain11 decimal(8,2),
		Percentage11 decimal(8,2),
		RankNumber11 int,
		ResultGrade11 NVarchar(50),
		Percentile11 decimal(8,2),
		ResultStatus11 Nvarchar(20),
		
		
		Exam12Name nvarchar(150),	
		TotalMarks12 decimal(8,2),
		TotalObtain12 decimal(8,2),
		Percentage12 decimal(8,2),
		RankNumber12 int,
		ResultGrade12 NVarchar(50),
		Percentile12 decimal(8,2),
		ResultStatus12 Nvarchar(20),
		
		ResultRemark1 nvarchar(200),
		ResultRemark2 nvarchar(200),
		
		TotalDays 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)
	)	
	 --print 'temp created'    	
	INSERT INTO  #TempAllExam 
	(
	AcademicIdText,
	ExamIdText,
	CoScholasticScopeIdText,
	IsDisplayMonthlyAttendanceText,
	ClassIdText,
	AcademicId,
	ExamName,
	StudCode,
	StudentName,
	RollNo,
	ResultStatus,
	ClassName,
	Division,
	TotalMark,
	TotalObtain,
	Percentage,
	RankNumber,
	ResultGrade,
	IsMarksInDecimal,
	column_visible,
	--Obtain,
	Percentile,
	--ClassSubject,
	ResultDetailId,
	ResultId,

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

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

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

  --end
GO
PRINT N'Altering [sAssessment].[pRptResultSheetOnlyCoScholasticCombineGet]...';


GO


ALTER PROCEDURE [sAssessment].[pRptResultSheetOnlyCoScholasticCombineGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rSubjectId int,
	 @rBatchId int,
	 @rClassId int,
	 @rDivisionId int,
	 @rExamId int,
	 @rCode nvarchar(20),
	 @rFromRollNo int,
	 @rToRollNo int,
	 @rFromRank int=0,
	 @rToRank int=0,
	 @rGrade nvarchar(20),
	 @rStatusId int,
	 @rClassStatusId int=0,
	 @rMultiCode nvarchar(max)=''
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
 
 --select * from  dbo.tTempCoScholasticCombine
 
DECLARE @GradeString nvarchar(1000),
@GradeSetId int, 
@Exam1 int,
@Exam2 int

SELECT @Exam1 = SubExamId From sAssessment.tExamCombine WHERE ExamId = @rExamId AND ExamOrder = 1
SELECT @Exam2 = SubExamId From sAssessment.tExamCombine WHERE ExamId = @rExamId AND ExamOrder = 2
SELECT @GradeSetId = GradesetId FROM sAssessment.tExamMaster WHERE Id = @rExamId
SELECT @GradeString = [sAssessment].[fGradeStringGet](@GradeSetId)  	
 
 	CREATE TABLE #TempExam 
	(
		AcademicId bigint,
		ExamId int,
		CCECSId int,
		CCECSGroupId int,
		CoSubject nvarchar(150),
		CoSubjectGroup nvarchar(150),
		CoSubjectOrderIndex int,
		CoSubjectGroupOrderIndex int,
		Grade1 nvarchar(10) NULL,
		GradeIndicator1 nvarchar(50) NULL,
		DescriptiveIndicator1 nvarchar(200) NULL,
		Grade2 nvarchar(10) NULL,
		GradeIndicator2 nvarchar(50) NULL,
		DescriptiveIndicator2 nvarchar(200) NULL
	 )
	 
 

 INSERT INTO  #TempExam 
	(
	AcademicId,
	ExamId,
	CCECSId,
	CCECSGroupId,
	CoSubject,
	CoSubjectGroup,
	CoSubjectOrderIndex,
	CoSubjectGroupOrderIndex
	
	)
 SELECT A.Id,@rExamId,CS.Id,CS.CCECAGroupId,CS.Title,csg.Title,CS.OrderIndex,CSG.OrderIndex 
 FROM sStudent.tAcademic A INNER JOIN
 sAssessment.tCCECSClass C ON A.ClassId = C.ClassId  
 INNER JOIN sAssessment.tCCECSMaster CS ON C.CCECSGroupId = cs.CCECAGroupId
 INNER JOIN sAssessment.tCCECSGroupMaster CSG ON CS.CCECAGroupId = CSG.Id 
 WHERE DivisionId = @rDivisionId
 AND A.BatchId = @rBatchId
 
UPDATE
    TE
SET
    TE.Grade1 = ES.Grade,
    TE.GradeIndicator1 = ES.GradeIndicator,
    TE.DescriptiveIndicator1 = ES.DescriptiveIndicator
FROM
    #TempExam TE
    INNER JOIN sAssessment.tCCECSExamScore ES
    ON TE.AcademicId = ES.AcademicId AND   
    TE.CCECSId = ES.CCECSId
    AND ES.ExamId = @Exam1
    
  UPDATE
    TE
SET
    TE.Grade2 = ES.Grade,
    TE.GradeIndicator2 = ES.GradeIndicator,
    TE.DescriptiveIndicator2 = ES.DescriptiveIndicator
FROM
    #TempExam TE
    INNER JOIN sAssessment.tCCECSExamScore ES
    ON TE.AcademicId = ES.AcademicId AND   
    TE.CCECSId = ES.CCECSId
    AND ES.ExamId = @Exam2

	SELECT 
			ESGM.Title AS Exam,
			StuM.Code,
			StuM.FirstName+' '+StuM.MiddleName+' '+StuM.LastName AS Name,
			A.RollNo,
			TE.AcademicId,			 
			ISNULL(R.ResultStatus,'') AS ResultStatus,
			CM.DisplayTitle AS Class,
			DM.DisplayTitle AS Division,
			ISNULL(R.TotalMarks,0) AS TotalMarks ,
			ISNULL(R.TotalObtain,0) AS TotalObtain,
			ISNULL(R.Percentage,0) AS Percentage,
			ISNULL(R.RankNumber,0) AS RankNumber,
			ISNULL(R.ResultGrade,'') AS ResultGrade,
			ISNULL(R.Percentile,0) AS Percentile,		 
			ISNULL(R.Id ,0) AS ResultId, 
			EM.IsMarksInDecimal,
			--SM.OrderIndex AS SubjectCode,	 
			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,
			SI.StudentPhoto,
			@GradeString AS GradeString,
			EM.IsDisplayGradeString,
			TE.CoSubject,
			TE.CoSubjectGroup,
			TE.CoSubjectGroupOrderIndex,
			TE.CoSubjectOrderIndex,
			TE.Grade1,
			TE.GradeIndicator1,
			TE.DescriptiveIndicator1,
			TE.Grade2,
			TE.GradeIndicator2,
			TE.DescriptiveIndicator2,
			SF.FatherName,
			SF.MotherName,
			EM.IsDisplayPrincipalSign,
			Em.IsDisplayTeacherSign,
			EI.EmployeeSign ,
			SR.StudentHeight,
			ISNULL(SR.TotalDays,0)AS TotalDays,
			ISNULL(SR.PresentDays,0)AS PresentDays,
			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(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,
			SR.ResultRemark3,
			SR.ResultRemark1,
			Sr.ResultRemark2,
			(CASE EM.IsDisplayImageHeader WHEN 1 THEN
			OI.CertificateHeaderA4 
			ELSE NULL END)AS  MarksheetHeaderA4,
			ISNULL(EM.IsDisplayImageHeader,0) AS IsImageHeader
	FROM 
			#TempExam TE INNER JOIN 	 
			sAssessment.tExamMaster EM ON EM.Id=TE.ExamId 		 
			INNER JOIN sStudent.tAcademic A ON A.Id=TE.AcademicId
			LEFT JOIN sStudent.tAcademicDetail AD ON AD.AcademicId=A.Id
			INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
			LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
			LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=StuM.Id
			LEFT JOIN sAssessment.tStudentRemark SR ON A.Id = SR.AcademicId AND EM.Id = SR.ExamId
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = StuM.Id
			
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
			LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = Dm.InchargeEmployeeId
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.EXAMSUBGROUPID			 
			LEFT JOIN sAssessment.tResult R	ON TE.AcademicId = R.AcademicId AND TE.ExamId = R.ExamId
			LEFT JOIN 	sCommon.tBloodGroupMaster BGM ON BGM.Id=So.BloodGroupId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId
			LEFT JOIN sSetup.tOrgImages OI ON OI.Orgid = OM.Id
	WHERE 
			EM.BatchId = @rBatchId 
			AND (A.ClassId=@rClassId OR @rClassId=0) 
			--AND ((SM.Id=@rSubjectId) OR (@rSubjectId=0))
			AND (A.DivisionId=@rDivisionId OR @rDivisionId=0)
			AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
			AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
			AND ((R.RankNumber >= @rFromRank) OR (@rFromRank=0))
			AND ((R.RankNumber <= @rToRank) OR (@rToRank=0))
			AND ((R.ResultGrade = @rGrade) OR (@rGrade=''))		
			AND (TE.ExamId = @rExamId)
			AND ((StuM.Code=@rCode) OR (@rCode=''))		
			AND ((StuM.StatusId=@rStatusId)OR(@rStatusId=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 A.RollNo,TE.CoSubjectGroupOrderIndex,TE.CoSubjectOrderIndex 
			--AND A.id = 1005000000007
END
GO
PRINT N'Altering [sAssessment].[pRptResultSheetOnlyCoScholasticTermwiseGet]...';


GO
 


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

BEGIN 

DECLARE @GradeString nvarchar(1000),
@GradeSetId int
 
SELECT @GradeSetId = GradesetId FROM sAssessment.tExamMaster WHERE Id = @rExamId
SELECT @GradeString = [sAssessment].[fGradeStringGet](@GradeSetId)  
	SELECT 
			ESGM.Title AS Exam,
			StuM.Code,
			StuM.FirstName+' '+StuM.MiddleName+' '+StuM.LastName AS Name,
			A.RollNo,
			CCEEM.AcademicId,
			--RD.Obtain,
			ISNULL(R.ResultStatus,'') AS ResultStatus,
			CM.DisplayTitle AS Class,
			DM.DisplayTitle AS Division,
			ISNULL(R.TotalMarks,0) AS TotalMarks,
			ISNULL(R.TotalObtain,0) AS TotalObtain,
			ISNULL(R.Percentage,0) AS Percentage,
			ISNULL(R.RankNumber,0) AS RankNumber,
			ISNULL(R.ResultGrade,0) AS ResultGrade,
			ISNULL(R.Percentile,0) AS Percentile,
			--SM.Title AS ClassSubject,
			--RD.Id AS ResultDetailId,
			ISNULL(R.Id,0) AS ResultId,
			--CS.Id AS SubjectId,
			--ED.Maximum,
			--RD.SubjectGrade,
			EM.IsMarksInDecimal,
			--SM.OrderIndex AS SubjectCode,
			--SM.Code AS SubjectCode,
			--SM.OrderIndex AS SubjectOrderIndex,
			ISNULL(EM.Remark1,'') AS Remark1,
			ISNULL(EM.Remark2,'') AS Remark2,
			ISNULL(EM.Remark3,'') AS Remark3,
			EM.DisplayTitle,
			EM.IsRankNo, 
			EM.IsGrade,
			
			EM.IsPercentile,
			EM.IsPercentage,
			EM.IsSubjectPercentile,
			EM.IsProcessResult,
			EM.IsMarksInDecimal,
			EM.IsNegativeMarks,
			EM.IsIncludeCoScholastic,
			EM.IsOnPrePrinted,
			EM.IsDisplayPhoto,
			EM.IsDisplayBirthDate,
			EM.IsLockForEdit,
			EM.IsDisplaySchoolName,			
			EM.IsDisplayAttendance,
			EM.IsDisplayHeightWeight,
			EM.IsResultStatus,
			REPLICATE(',',EM.FooterAdjustment) AS FooterAdjustmentText,
			REPLICATE(',',EM.DetailAdjustment) AS DetailAdjustmentText,
			EM.FooterAdjustment,
			EM.DetailAdjustment,
			ISNULL(R.ResultRemark,'') AS ResultRemark,
			SO.DateOfBirth,
			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,
			SI.StudentPhoto,
			@GradeString AS GradeString,
			CCEEM.Grade,
			CCEEM.GradeIndicator,
			CCEEM.DescriptiveIndicator,
			CCEM.Title AS CoSubject,
			CCEM.OrderIndex AS CoOrderIndex,
			CCEGM.Title AS CoSubjectGroup,
			CCEGM.OrderIndex AS CoOrderIndexGroup,
			EM.IsDisplayPrincipalSign,
			Em.IsDisplayTeacherSign,
			EI.EmployeeSign ,
			SR.StudentHeight,
			ISNULL(SR.TotalDays,0)AS TotalDays,
			ISNULL(SR.PresentDays,0)AS PresentDays,
			SR.StudentWeight,
			EM.IsCoScholasticGrade,
			EM.IsCoScholasticGradeIndicator,
			EM.IsCoScholasticGradeDesIndicator,
				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,
		SR.ResultRemark3,
		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,
		SR.ResultRemark1,
		SR.ResultRemark2,
		EM.IsDisplayGradeString,
		(CASE EM.IsDisplayImageHeader WHEN 1 THEN
			OI.CertificateHeaderA4 
			ELSE NULL END)AS  MarksheetHeaderA4,
			ISNULL(EM.IsDisplayImageHeader,0) AS IsImageHeader,

		sAssessment.fGetGradepoint(CCEEM.Grade) AS GradePoint,
		SF.FatherName,
		SF.MotherName,
		EM.IsDisplayParentName
	FROM 
			 
			 
			sAssessment.tCCECSExamScore CCEEM INNER JOIN   
			--INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
			  sAssessment.tExamMaster EM ON EM.Id=CCEEM.ExamId AND CCEEM.ExamId=@rExamId
			--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=CCEEM.AcademicId
			LEFT JOIN sStudent.tAcademicDetail AD ON AD.AcademicId=A.Id
			INNER JOIN sAssessment.tCCECSMaster CCEM ON CCEM.Id=CCEEM.CCECSId
			INNER JOIN sAssessment.tCCECSGroupMaster CCEGM ON CCEGM.Id= CCEM.CCECAGroupId	
			INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
			
			LEFT JOIN sAssessment.tStudentRemark SR ON A.Id = SR.AcademicId AND EM.Id = SR.ExamId
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = StuM.Id
		   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId
			LEFT JOIN sSetup.tOrgImages OI ON OI.Orgid = OM.Id
			LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
			LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=StuM.Id
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
			LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = Dm.InchargeEmployeeId
			
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.EXAMSUBGROUPID
			LEFT JOIN sAssessment.tResult R ON R.AcademicId = CCEEM.AcademicId AND R.ExamId = CCEEM.ExamId
			LEFT JOIN 	sCommon.tBloodGroupMaster BGM ON BGM.Id=So.BloodGroupId
	WHERE 
			
		EM.BatchId = @rBatchId 
		AND (A.ClassId=@rClassId OR @rClassId=0) 
		--AND ((SM.Id=@rSubjectId) OR (@rSubjectId=0))
		AND (A.DivisionId=@rDivisionId OR @rDivisionId=0)
		AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((R.RankNumber >= @rFromRank) OR (@rFromRank=0))
		AND ((R.RankNumber <= @rToRank) OR (@rToRank=0))
		AND ((R.ResultGrade = @rGrade) OR (@rGrade=''))		
		AND (CCEEM.ExamId = @rExamId)
		AND ((StuM.Code=@rCode) OR (@rCode=''))		
		AND ((StuM.StatusId=@rStatusId)OR(@rStatusId=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 A.RollNo--,CS.OrderIndex 
		--AND A.id = 1005000000007
END
GO
PRINT N'Altering [sAssessment].[pRptResultSheetStandardGet]...';


GO

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

BEGIN 

DECLARE @GradeString nvarchar(1000),  @GradeStringRemark nvarchar(500),
@GradeSetId int,@lGradeStringText nvarchar(1000)
 
SELECT @GradeSetId = GradesetId FROM sAssessment.tExamMaster WHERE Id = @rExamId
 SELECT @GradeString = [sAssessment].[fGradeStringGet](@GradeSetId)
 Select @lGradeStringText = GradeStringText from sAssessment.tGradeSetMaster where Id=@Gradesetid
   
Select @GradeStringRemark = GradeStringText from sAssessment.tGradeSetMaster Where Id =@GradeSetId
 
	SELECT 
		Convert(nvarchar(20),A.Id) AS AcademicIdText,
		Convert(nvarchar(20),@rExamId) AS ExamIdText,
		Convert(nvarchar(20),EM.CoScholasticScopeId) AS CoScholasticScopeIdText,
		Convert(nvarchar(20),ISNULL(EM.IsDisplayMonthlyAttendance,0)) AS IsDisplayMonthlyAttendanceText,
		Convert(nvarchar(20),@rBatchId) AS BatchIdText,
		ESGM.Title AS Exam,
		StuM.Code,
		[sStudent].[fStudentNameGet](stum.FirstName , StuM.MiddleName, StuM.LastName,OM.StudentNameFormatId ) AS Name,
		A.RollNo,
		R.AcademicId,			
		R.ResultStatus,
		CM.DisplayTitle AS Class,
		DM.DisplayTitle AS Division,
		R.TotalMarks,
		R.TotalObtain,
		R.Percentage,
		R.RankNumber,
		R.ResultGrade,
		R.Percentile,			
		RD.Id AS ResultDetailId,		
		ED.IsDisplayInMarksheet,
		ED.IsShowSubjectGrade,
		ED.IsIncludeInTotal,
		RD.Obtain AS SubjectObtain,
		ED.Minimum AS SubjectMinimum,
		ED.Maximum AS SubjectMaximum,
		RD.SubjectGrade,
		SM.Code AS SubjectCode,
		SM.Title AS SubjectName,
		(CASE ISNULL(ED.DisplayOrder,0)
		WHEN 0 THEN CS.OrderIndex
		ELSE ED.DisplayOrder END) AS SubjectOrderIndex,
		R.Id AS ResultId,
		CS.Id AS SubjectId,			 	
		EM.IsMarksInDecimal,
		ISNULL(EM.Remark1,'') AS Remark1,
		ISNULL(EM.Remark2,'') AS Remark2,
		ISNULL(EM.Remark3,'') AS Remark3,
		EM.DisplayTitle,
		EM.IsRankNo, 
		EM.IsGrade,
		EM.IsPercentile,
		EM.IsPercentage,
		EM.IsSubjectPercentile,
		EM.IsProcessResult,
		EM.IsMarksInDecimal,
		EM.IsNegativeMarks,
		EM.IsIncludeCoScholastic,
		EM.IsOnPrePrinted,
		EM.IsDisplayPhoto,
		EM.IsDisplayBirthDate,
		EM.IsLockForEdit,
		EM.IsDisplaySchoolName,			
		EM.IsDisplayAttendance,
		EM.IsDisplayHeightWeight,
		EM.IsResultStatus,
		REPLICATE(',',EM.FooterAdjustment) AS FooterAdjustmentText,
		REPLICATE(',',EM.DetailAdjustment) AS DetailAdjustmentText,
		EM.FooterAdjustment,
		EM.DetailAdjustment,
		--ISNULL(R.ResultRemark,'') AS ResultRemark,
		SO.DateOfBirth,
		EM.TermScopeId,
		(CASE EM.IsDisplayPhoto WHEN 1 THEN
			SI.StudentPhoto
		ELSE NULL END) AS StudentPhoto,
		RD.IsPresent,
		CASE @GradeStringRemark WHEN '' THEN @GradeString  ELSE @GradeStringRemark END AS GradeString,
		EM.IsDisplayGradeString,
		(CASE EM.IsDisplayHighestDivisionMark
		WHEN 1 THEN [sAssessment].[fGetHighestDivisionMark](A.DivisionId ,RD.ExamDetailId)
		ELSE 0 END) AS HighestDivisionMark,
		(CASE EM.IsDisplayHighestDivisionGrade
		WHEN 1 THEN [sAssessment].[fGetHighestDivisionGrade] (A.DivisionId ,RD.ExamDetailId)
		ELSE '' END) AS HighestDivisionGrade,			
		OM.SmallAddress1,
		EM.IsDisplayParentName,
		SF.FatherName,
		SF.MotherName,
		ISNULL(ED.IsShowSubjectMark,1) AS IsShowSubjectMark,
		
		EM.IsDisplayTeacherSign,
		Em.IsDisplayPrincipalSign,
		(CASE 	EM.IsDisplayTeacherSign WHEN 1 THEN
			EI.EmployeeSign
		ELSE NULL END)AS EmployeeSign,
		ISNULL(EM.IsDisplayMonthlyAttendance,0) AS IsDisplayMonthlyAttendance,
		--(CASE EM.IsDisplayImageHeader WHEN 1 THEN 
		--	OI.CertificateHeaderA4 
		--ELSE 
		--	NULL END) AS MarksheetHeaderA4,
		(CASE EM.IsDisplayImageHeader WHEN 1 THEN 
			OI.MarksheetHeaderA4 
		ELSE 
			NULL END) AS MarksheetHeaderA4,
		ISNULL(EM.IsDisplayImageHeader,0) AS IsImageHeader,
		
		SR.StudentHeight,
		SR.StudentWeight,		
		SR.PresentDays,			
		SR.TotalDays,
		SR.ResultRemark1,
		SR.ResultRemark2,
		SR.Resultremark3,
		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.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(SR.ClassTeacherRemark,'') As ClassTeacherRemark,
		ISNULL(SR.HouseRemark,'') As HouseRemark,
		ISNULL(Emp.FirstName,'') +' ' + ISNULL(EMp.LastName,'') AS ClassTeacherName,
		BM.Title AS BatchName,
		Em.DecimalFormat,
		RD.GraceMark,
		ISNULL(SM.SubjectGroupId,0) AS SubjectGroupId,
		ISNULL(SG.Title,'')AS SubjectGroupTitle,
		ISNULL(SG.Code,'') AS SubjectGroupCode,
		@lGradeStringText AS GradeStringText,
		ISNULL(HM.Title,'') AS House,
		ISNULL(EM.TeacherSignCaption,'') As TeacherSignCaption,
		ISNULL(EM.PrincipalSignCaption,'') As PrincipalSignCaption,
		ISNULL(EM.ParentSignCaption,'') As ParentSignCaption,
		ISNULL(BGM.Title,'') AS BloodGroup,
		GS.GradeTitle,
		GS.GradePoint,
		RAD.SubjectHighestDivisionGrade,
		RAD.SubjectHighestDivisionMark,
		GM.Title AS Gender,
		RD.KrupaMark,
		RD.Remark AS OtherDetailRemark,
		ISNULL(SO.AdhaarNumber,'') AS AdharNumber,
		ISNULL(SO.UIDNumber,'') AS UIDNumber,
		ISNULL(SC.PresentStreetOne,'')+' '+ISNULL(SC.PresentStreetTwo,'')+' '+ISNULL(SC.PresentStreetThree,'')+' '+ISNULL(SC.PresentCity,'')+' '+ISNULL(SC.PresentState,'') AS PresentAddress,
		ISNULL(SC.ParentContactNo,'') AS ContactNo,
		(CASE  When EM.IsDisplayAbsentCount=1 then ([sAssessment].[fGetAbsentCount](@rExamId,R.AcademicId, CS.Id)) ELSE 0 END) AS AbsentCount,
		(CASE  When EM.CoordinatorEmployeeId IS NOT NULL AND EM.CoordinatorEmployeeId !=0 then EICoordinator.EmployeeSign ELSE NULL END) AS CoordinatorEmployeeSign,
		ISNULL((SELECT ISNULL(Template,'') FROM sCommon.tReportTemplate WHERE ReportId = 20438 AND OrgId=A.OrgId),0) AS ReportTemplate,
		StuM.SUId As SUID,
		ISNULL(SO.MotherTongue,'') as MotherTongue
	FROM 
		sAssessment.tResultDetail RD
		INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
		INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
		INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId			
		INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
		INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId	
		LEFT JOIN sSetup.tSubjectGroupMaster SG ON SG.Id = Sm.SubjectGroupId				 
		INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId
		LEFT JOIN sSetup.tOrgImages OI ON OI.Orgid = OM.Id
		LEFT JOIN sStudent.tAcademicDetail AD ON AD.AcademicId=A.Id
		INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
		LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
		LEFT JOIN sCommon.tGenderMaster GM ON GM.Id = SO.GenderId
		LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=StuM.Id
		INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
		INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
		LEFT JOIN sHrm.tEmployeeMaster Emp ON Emp.Id=DM.InchargeEmployeeId AND ISNULL(EMP.IsOtherUser,0) = 0
		LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = Dm.InchargeEmployeeId
		INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.EXAMSUBGROUPID
		LEFT JOIN sAssessment.tStudentRemark SR ON R.AcademicId = SR.AcademicId AND R.ExamId = SR.ExamId
		LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = StuM.Id
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.batchId
		LEFT JOIN sActivity.tHouseMaster HM ON HM.Id=SO.HouseId
		LEFT JOIN 	sCommon.tBloodGroupMaster BGM ON BGM.Id=So.BloodGroupId
		LEFT JOIN sAssessment.tGradeSetDetail GS ON GS.GradeSetId=ED.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 sStudent.tStudentCommunication SC ON SC.StudentId=A.StudentId
		LEFT JOIN sHrm.tEmployeeImages EICoordinator ON EICoordinator.EmployeeId = EM.CoordinatorEmployeeId
	WHERE 
			
		((EM.BatchId = @rBatchId) OR  (@rBatchId = 0))
		AND ((A.ClassId=@rClassId) OR (@rClassId=0)) 
		AND ((SM.Id=@rSubjectId) OR (@rSubjectId=0))
		AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((R.RankNumber >= @rFromRank) OR (@rFromRank=0))
		AND ((R.RankNumber <= @rToRank) OR (@rToRank=0))
		AND ((R.ResultGrade = @rGrade) OR (@rGrade=''))
		AND (R.ExamId = @rExamId)
		AND ((StuM.Code=@rCode) OR (@rCode=''))
		AND ((R.Id = @rResultId) OR (@rResultId = 0))
		AND ((StuM.StatusId=@rStatusId)OR(@rStatusId=0))
		AND ((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 A.RollNo,ED.DisplayOrder
END
GO
PRINT N'Altering [sAssessment].[pRptResultSheetStandardGet_AllCombine]...';


GO
ALTER PROCEDURE [sAssessment].[pRptResultSheetStandardGet_AllCombine]
	 
	 @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,
	 @rClassStatusId int=0,
	 @rMultiCode nvarchar(max)=''
	
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

DECLARE @GradeString nvarchar(1000),  @GradeStringRemark nvarchar(500),
@GradeSetId int,@lGradeStringText nvarchar(1000)
 
SELECT @GradeSetId = GradesetId FROM sAssessment.tExamMaster WHERE Id = @rExamId
 SELECT @GradeString = [sAssessment].[fGradeStringGet](@GradeSetId)
 Select @lGradeStringText = GradeStringText from sAssessment.tGradeSetMaster where Id=@Gradesetid
   
Select @GradeStringRemark = GradeStringText from sAssessment.tGradeSetMaster Where Id =@GradeSetId
 
	SELECT 
	@rBuilder1 AS Builder1,
	@rBuilder1 AS Builder2,
		Convert(nvarchar(20),A.Id) AS AcademicIdText,
		Convert(nvarchar(20),@rExamId) AS ExamIdText,
		Convert(nvarchar(20),EM.CoScholasticScopeId) AS CoScholasticScopeIdText,
		Convert(nvarchar(20),ISNULL(EM.IsDisplayMonthlyAttendance,0)) AS IsDisplayMonthlyAttendanceText,
		Convert(nvarchar(20),@rBatchId) AS BatchIdText,
		ESGM.Title AS Exam,
		StuM.Code,
		[sStudent].[fStudentNameGet](stum.FirstName , StuM.MiddleName, StuM.LastName,OM.StudentNameFormatId ) AS Name,
		A.RollNo,
		R.AcademicId,			
		R.ResultStatus,
		CM.Id AS ClassId,
		CM.DisplayTitle AS Class,
		DM.Id AS DivisionId,
		DM.DisplayTitle AS Division,
		R.TotalMarks,
		R.TotalObtain,
		R.Percentage,
		R.RankNumber,
		R.ResultGrade,
		R.Percentile,			
		RD.Id AS ResultDetailId,		
		ED.IsDisplayInMarksheet,
		ED.IsShowSubjectGrade,
		ED.IsIncludeInTotal,
		RD.Obtain AS SubjectObtain,
		ED.Minimum AS SubjectMinimum,
		ED.Maximum AS SubjectMaximum,
		RD.SubjectGrade,
		SM.Code AS SubjectCode,
		SM.Title AS SubjectName,
		(CASE ISNULL(ED.DisplayOrder,0)
		WHEN 0 THEN CS.OrderIndex
		ELSE ED.DisplayOrder END) AS SubjectOrderIndex,
		R.Id AS ResultId,
		CS.Id AS SubjectId,			 	
		EM.IsMarksInDecimal,
		ISNULL(EM.Remark1,'') AS Remark1,
		ISNULL(EM.Remark2,'') AS Remark2,
		ISNULL(EM.Remark3,'') AS Remark3,
		EM.DisplayTitle,
		EM.IsRankNo, 
		EM.IsGrade,
		EM.IsPercentile,
		EM.IsPercentage,
		EM.IsSubjectPercentile,
		EM.IsProcessResult,
		EM.IsMarksInDecimal,
		EM.IsNegativeMarks,
		EM.IsIncludeCoScholastic,
		EM.IsOnPrePrinted,
		EM.IsDisplayPhoto,
		EM.IsDisplayBirthDate,
		EM.IsLockForEdit,
		EM.IsDisplaySchoolName,			
		EM.IsDisplayAttendance,
		EM.IsDisplayHeightWeight,
		EM.IsResultStatus,
		REPLICATE(',',EM.FooterAdjustment) AS FooterAdjustmentText,
		REPLICATE(',',EM.DetailAdjustment) AS DetailAdjustmentText,
		EM.FooterAdjustment,
		EM.DetailAdjustment,
		--ISNULL(R.ResultRemark,'') AS ResultRemark,
		SO.DateOfBirth,
		EM.TermScopeId,
		(CASE EM.IsDisplayPhoto WHEN 1 THEN
			SI.StudentPhoto
		ELSE NULL END) AS StudentPhoto,
		RD.IsPresent,
		CASE @GradeStringRemark WHEN '' THEN @GradeString  ELSE @GradeStringRemark END AS GradeString,
		EM.IsDisplayGradeString,
		(CASE EM.IsDisplayHighestDivisionMark
		WHEN 1 THEN [sAssessment].[fGetHighestDivisionMark](A.DivisionId ,RD.ExamDetailId)
		ELSE 0 END) AS HighestDivisionMark,
		(CASE EM.IsDisplayHighestDivisionGrade
		WHEN 1 THEN [sAssessment].[fGetHighestDivisionGrade] (A.DivisionId ,RD.ExamDetailId)
		ELSE '' END) AS HighestDivisionGrade,			
		OM.SmallAddress1,
		EM.IsDisplayParentName,
		SF.FatherName,
		SF.MotherName,
		ISNULL(ED.IsShowSubjectMark,1) AS IsShowSubjectMark,
		
		EM.IsDisplayTeacherSign,
		Em.IsDisplayPrincipalSign,
		(CASE 	EM.IsDisplayTeacherSign WHEN 1 THEN
			EI.EmployeeSign
		ELSE NULL END)AS EmployeeSign,
		ISNULL(EM.IsDisplayMonthlyAttendance,0) AS IsDisplayMonthlyAttendance,
		--(CASE EM.IsDisplayImageHeader WHEN 1 THEN 
		--	OI.CertificateHeaderA4 
		--ELSE 
		--	NULL END) AS MarksheetHeaderA4,
			(CASE EM.IsDisplayImageHeader WHEN 1 THEN 
			OI.MarksheetHeaderA4 
		ELSE 
			NULL END) AS MarksheetHeaderA4,
		ISNULL(EM.IsDisplayImageHeader,0) AS IsImageHeader,
		
		SR.StudentHeight,
		SR.StudentWeight,		
		ISNULL(SR.PresentDays,0)AS PresentDays,			
		ISNULL(SR.TotalDays,0)AS TotalDays,
		SR.ResultRemark1,
		SR.ResultRemark2,
		SR.Resultremark3,
		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.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(SR.ClassTeacherRemark,'') As ClassTeacherRemark,
		ISNULL(SR.HouseRemark,'') As HouseRemark,
		ISNULL(Emp.FirstName,'') +' ' + ISNULL(EMp.LastName,'') AS ClassTeacherName,
		BM.Title AS BatchName,
		Em.DecimalFormat,
		RD.GraceMark,
		ISNULL(SM.SubjectGroupId,0) AS SubjectGroupId,
		ISNULL(SG.Title,'')AS SubjectGroupTitle,
		ISNULL(SG.Code,'') AS SubjectGroupCode,
		@lGradeStringText AS GradeStringText,
		ISNULL(HM.Title,'') AS House,
		ISNULL(EM.TeacherSignCaption,'') As TeacherSignCaption,
		ISNULL(EM.PrincipalSignCaption,'') As PrincipalSignCaption,
		ISNULL(EM.ParentSignCaption,'') As ParentSignCaption,
		ISNULL(BGM.Title,'') AS BloodGroup,
		GS.GradeTitle,
		--RAD.SubjectHighestDivisionGrade,
		--RAD.SubjectHighestDivisionMark,
		GM.Title AS Gender,
		RD.KrupaMark,
		RD.Remark AS OtherDetailRemark,
		ED2.ExamDate AS ExamDate2,
		SM.Title AS SubjectName2,
		RD2.Obtain AS SubjectObtain2,
		ED2.Minimum AS SubjectMinimum2,
		ED2.Maximum AS SubjectMaximum2,
		(CASE EM.IsDisplayHighestDivisionMark
		WHEN 1 THEN [sAssessment].[fGetHighestDivisionMark](A.DivisionId ,RD2.ExamDetailId)
		ELSE 0 END) AS HighestDivisionMark2,
		ED.Id AS ExamDetailId2,
		EM2.DisplayTitle As Exam2,
		EM2.Id As ExamId
		
	FROM 
		sAssessment.tResultDetail RD
		INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
		INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
		INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId			
		INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
		INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId	
		LEFT JOIN sSetup.tSubjectGroupMaster SG ON SG.Id = Sm.SubjectGroupId				 
		INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId
		LEFT JOIN sSetup.tOrgImages OI ON OI.Orgid = OM.Id
		LEFT JOIN sStudent.tAcademicDetail AD ON AD.AcademicId=A.Id
		INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
		LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
		LEFT JOIN sCommon.tGenderMaster GM ON GM.Id = SO.GenderId
		LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=StuM.Id
		INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
		INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
		LEFT JOIN sHrm.tEmployeeMaster Emp ON Emp.Id=DM.InchargeEmployeeId
		LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = Dm.InchargeEmployeeId
		INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.EXAMSUBGROUPID
		LEFT JOIN sAssessment.tStudentRemark SR ON R.AcademicId = SR.AcademicId AND R.ExamId = SR.ExamId
		LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = StuM.Id
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.batchId
		LEFT JOIN sActivity.tHouseMaster HM ON HM.Id=SO.HouseId
		LEFT JOIN 	sCommon.tBloodGroupMaster BGM ON BGM.Id=So.BloodGroupId
		LEFT JOIN sAssessment.tGradeSetDetail GS ON GS.GradeSetId=ED.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
		INNER JOIN sAssessment.tExamCombine EC2 ON EC2.ExamId = EM.Id
		INNER JOIN sAssessment.tExamMaster EM2 ON EM2.Id = EC2.SubExamId
		INNER JOIN sAssessment.tExamDetail ED2 ON EM2.Id = ED2.ExamId AND ED2.ClassSubjectId = ED.ClassSubjectId
		INNER JOIN sAssessment.tResult R2 ON R2.ExamId = EM2.Id AND R2.AcademicId = A.Id
		INNER JOIN sAssessment.tResultDetail RD2 ON ED2.Id = RD2.ExamDetailId AND RD2.ResultId = R2.Id

	WHERE 
			
		((EM.BatchId = @rBatchId) OR  (@rBatchId = 0))
		AND ((A.ClassId=@rClassId) OR (@rClassId=0)) 
		AND ((SM.Id=@rSubjectId) OR (@rSubjectId=0))
		AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((R.RankNumber >= @rFromRank) OR (@rFromRank=0))
		AND ((R.RankNumber <= @rToRank) OR (@rToRank=0))
		AND ((R.ResultGrade = @rGrade) OR (@rGrade=''))
		AND (R.ExamId = @rExamId)
		AND ((StuM.Code=@rCode) OR (@rCode=''))
		AND ((R.Id = @rResultId) OR (@rResultId = 0))
		AND ((StuM.StatusId=@rStatusId)OR(@rStatusId=0))
		AND (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 A.RollNo,ExamDate2
END
GO
PRINT N'Altering [sAssessment].[pRptResultSheetStandardGetwithResultDetailOther]...';


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

BEGIN 

DECLARE @GradeString nvarchar(1000),  @GradeStringRemark nvarchar(500),
@GradeSetId int,@lGradeStringText nvarchar(1000)
 
SELECT @GradeSetId = GradesetId FROM sAssessment.tExamMaster WHERE Id = @rExamId
 SELECT @GradeString = [sAssessment].[fGradeStringGet](@GradeSetId)
 Select @lGradeStringText = GradeStringText from sAssessment.tGradeSetMaster where Id=@Gradesetid
   
Select @GradeStringRemark = GradeStringText from sAssessment.tGradeSetMaster Where Id =@GradeSetId
 
	SELECT 
		Convert(nvarchar(20),A.Id) AS AcademicIdText,
		Convert(nvarchar(20),@rExamId) AS ExamIdText,
		Convert(nvarchar(20),EM.CoScholasticScopeId) AS CoScholasticScopeIdText,
		Convert(nvarchar(20),ISNULL(EM.IsDisplayMonthlyAttendance,0)) AS IsDisplayMonthlyAttendanceText,
		Convert(nvarchar(20),@rBatchId) AS BatchIdText,
		ESGM.Title AS Exam,
		StuM.Code,
		[sStudent].[fStudentNameGet](stum.FirstName , StuM.MiddleName, StuM.LastName,OM.StudentNameFormatId ) AS Name,
		A.RollNo,
		R.AcademicId,			
		R.ResultStatus,
		CM.DisplayTitle AS Class,
		DM.DisplayTitle AS Division,
		R.TotalMarks,
		R.TotalObtain,
		R.Percentage,
		R.RankNumber,
		R.ResultGrade,
		R.Percentile,			
		RD.Id AS ResultDetailId,		
		ED.IsDisplayInMarksheet,
		ED.IsShowSubjectGrade,
		ED.IsIncludeInTotal,
		RD.Obtain AS SubjectObtain,
		ED.Minimum AS SubjectMinimum,
		ED.Maximum AS SubjectMaximum,
		RD.SubjectGrade,
		SM.Code AS SubjectCode,
		SM.Title AS SubjectName,
		(CASE ISNULL(ED.DisplayOrder,0)
		WHEN 0 THEN CS.OrderIndex
		ELSE ED.DisplayOrder END) AS SubjectOrderIndex,
		R.Id AS ResultId,
		CS.Id AS SubjectId,			 	
		EM.IsMarksInDecimal,
		ISNULL(EM.Remark1,'') AS Remark1,
		ISNULL(EM.Remark2,'') AS Remark2,
		ISNULL(EM.Remark3,'') AS Remark3,
		EM.DisplayTitle,
		EM.IsRankNo, 
		EM.IsGrade,
		EM.IsPercentile,
		EM.IsPercentage,
		EM.IsSubjectPercentile,
		EM.IsProcessResult,
		EM.IsMarksInDecimal,
		EM.IsNegativeMarks,
		EM.IsIncludeCoScholastic,
		EM.IsOnPrePrinted,
		EM.IsDisplayPhoto,
		EM.IsDisplayBirthDate,
		EM.IsLockForEdit,
		EM.IsDisplaySchoolName,			
		EM.IsDisplayAttendance,
		EM.IsDisplayHeightWeight,
		EM.IsResultStatus,
		REPLICATE(',',EM.FooterAdjustment) AS FooterAdjustmentText,
		REPLICATE(',',EM.DetailAdjustment) AS DetailAdjustmentText,
		EM.FooterAdjustment,
		EM.DetailAdjustment,
		--ISNULL(R.ResultRemark,'') AS ResultRemark,
		SO.DateOfBirth,
		EM.TermScopeId,
		(CASE EM.IsDisplayPhoto WHEN 1 THEN
			SI.StudentPhoto
		ELSE NULL END) AS StudentPhoto,
		RD.IsPresent,
		CASE @GradeStringRemark WHEN '' THEN @GradeString  ELSE @GradeStringRemark END AS GradeString,
		EM.IsDisplayGradeString,
		(CASE EM.IsDisplayHighestDivisionMark
		WHEN 1 THEN [sAssessment].[fGetHighestDivisionMark](A.DivisionId ,RD.ExamDetailId)
		ELSE 0 END) AS HighestDivisionMark,
		(CASE EM.IsDisplayHighestDivisionGrade
		WHEN 1 THEN [sAssessment].[fGetHighestDivisionGrade] (A.DivisionId ,RD.ExamDetailId)
		ELSE '' END) AS HighestDivisionGrade,			
		OM.SmallAddress1,
		EM.IsDisplayParentName,
		SF.FatherName,
		SF.MotherName,
		ISNULL(ED.IsShowSubjectMark,1) AS IsShowSubjectMark,
		
		EM.IsDisplayTeacherSign,
		Em.IsDisplayPrincipalSign,
		(CASE 	EM.IsDisplayTeacherSign WHEN 1 THEN
			EI.EmployeeSign
		ELSE NULL END)AS EmployeeSign,
		ISNULL(EM.IsDisplayMonthlyAttendance,0) AS IsDisplayMonthlyAttendance,
		--(CASE EM.IsDisplayImageHeader WHEN 1 THEN 
		--	OI.CertificateHeaderA4 
		--ELSE 
		--	NULL END) AS MarksheetHeaderA4,
		(CASE EM.IsDisplayImageHeader WHEN 1 THEN 
		OI.MarksheetHeaderA4 
		ELSE 
			NULL END) AS MarksheetHeaderA4,
		ISNULL(EM.IsDisplayImageHeader,0) AS IsImageHeader,
		
		SR.StudentHeight,
		SR.StudentWeight,		
		ISNULL(SR.PresentDays,0)AS PresentDays,			
		ISNULL(SR.TotalDays,0)AS TotalDays,
		SR.ResultRemark1,
		SR.ResultRemark2,
		SR.Resultremark3,
		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.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(SR.ClassTeacherRemark,'') As ClassTeacherRemark,
		ISNULL(SR.HouseRemark,'') As HouseRemark,
		--ISNULL(Emp.FirstName,'') +' ' + ISNULL(EMp.LastName,'') AS ClassTeacherName,
		BM.Title AS BatchName,
		Em.DecimalFormat,
		RD.GraceMark,
		ISNULL(SM.SubjectGroupId,0) AS SubjectGroupId,
		ISNULL(SG.Title,'')AS SubjectGroupTitle,
		ISNULL(SG.Code,'') AS SubjectGroupCode,
		@lGradeStringText AS GradeStringText,
		ISNULL(HM.Title,'') AS House,
		ISNULL(EM.TeacherSignCaption,'') As TeacherSignCaption,
		ISNULL(EM.PrincipalSignCaption,'') As PrincipalSignCaption,
		ISNULL(EM.ParentSignCaption,'') As ParentSignCaption,
		ISNULL(BGM.Title,'') AS BloodGroup,
		GS.GradeTitle,
		RAD.SubjectHighestDivisionGrade,
		RAD.SubjectHighestDivisionMark,
		GM.Title AS Gender,
		RD.KrupaMark,
		RDO.TotalCount,
		RDO.PresentCount,
		RDO.Remark As Remark4,
		[sAssessment].[fSubjectEmployeeGet](DM.Id,SM.Id) As ClassTeacherName

	FROM 
		sAssessment.tResultDetail RD
		INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
		INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
		INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId			
		INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
		INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId	
		LEFT JOIN sSetup.tSubjectGroupMaster SG ON SG.Id = Sm.SubjectGroupId				 
		INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId
		LEFT JOIN sSetup.tOrgImages OI ON OI.Orgid = OM.Id
		LEFT JOIN sStudent.tAcademicDetail AD ON AD.AcademicId=A.Id
		INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
		LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
		LEFT JOIN sCommon.tGenderMaster GM ON GM.Id = SO.GenderId
		LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=StuM.Id
		INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
		INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
		LEFT JOIN sHrm.tEmployeeMaster Emp ON Emp.Id=DM.InchargeEmployeeId
		LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = Dm.InchargeEmployeeId
		INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.EXAMSUBGROUPID
		LEFT JOIN sAssessment.tStudentRemark SR ON R.AcademicId = SR.AcademicId AND R.ExamId = SR.ExamId
		LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = StuM.Id
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.batchId
		LEFT JOIN sActivity.tHouseMaster HM ON HM.Id=SO.HouseId
		LEFT JOIN 	sCommon.tBloodGroupMaster BGM ON BGM.Id=So.BloodGroupId
		LEFT JOIN sAssessment.tGradeSetDetail GS ON GS.GradeSetId=ED.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 sAssessment.tResultDetailOther RDO ON  RDO.ExamId = EM.Id AND R.Academicid =RDO.AcademicId AND ED.ClassSubjectId = RDO.ClassSubjectId
	WHERE 
			
		((EM.BatchId = @rBatchId) OR  (@rBatchId = 0))
		AND ((A.ClassId=@rClassId) OR (@rClassId=0)) 
		AND ((SM.Id=@rSubjectId) OR (@rSubjectId=0))
		AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((R.RankNumber >= @rFromRank) OR (@rFromRank=0))
		AND ((R.RankNumber <= @rToRank) OR (@rToRank=0))
		AND ((R.ResultGrade = @rGrade) OR (@rGrade=''))
		AND (R.ExamId = @rExamId)
		AND ((StuM.Code=@rCode) OR (@rCode=''))
		AND ((R.Id = @rResultId) OR (@rResultId = 0))
		AND ((StuM.StatusId=@rStatusId)OR(@rStatusId=0))
		order by A.RollNo,ED.DisplayOrder
END
GO
PRINT N'Altering [sAssessment].[pRptResultSheetStandardMultiExamGet]...';


GO

ALTER PROCEDURE [sAssessment].[pRptResultSheetStandardMultiExamGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rSubjectId int = 0,
	 @rBatchId int=0,
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rExamId int,
	 @rCode nvarchar(20)='',
	 @rFromRollNo int=0,
	 @rToRollNo int=0,
	 @rFromRank int=0,
	 @rToRank int=0,
	 @rGrade nvarchar(20)='',
	 @rResultId bigint=0,
	 @rStatusId int=0,
	 @rAcademicId bigint=0,
	 @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.tTempAllExam
-- --drop table sAssessment.tTempAllExam
 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

--#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,		
		 
		 
		SubjectGradeTerm1 NVarchar(50),
		SubjectGradeTerm2 NVarchar(50),
		SubjectGradeTerm3 NVarchar(50),
		IsMarksInDecimal bit,
		column_visible bit,
		--Obtain decimal(5,2),
		Percentile decimal(5,2),
		--ClassSubject nvarchar(100),
		ResultDetailId bigint,
		ResultId bigint,	
		Remark1 nvarchar(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), 
		
		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),
		
		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(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),
		SubjectMaxTerm1 decimal(8,2),
		SubjectMaxTerm2 decimal(8,2),
		SubjectMaxTerm3 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),
		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(20),
		HighestDivisionMark decimal(5, 2),
		HighestDivisionGrade nvarchar(50),
		StreamTitle nvarchar(50),
		AdmissionNo int,
		AdmissionDate Date,
		MiddleName nvarchar(50)
		
	)	
	 --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
	)
	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.AdmissionFormNumber,0) AS AdmissionNo,
		ISNULL(StuA.AdmissionDate,'') AS AdmissionDate,
		Stum.MiddleName				
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.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,	
					 				
					 SubjectGrade' + convert(nvarchar(15),@lCount)+ '=RD.SubjectGrade,
					 TotalDays'+convert(nvarchar(15),@lCount)+'=SR.TotalDays,
					 PresentDays'+convert(nvarchar(15),@lCount)+'=SR.PresentDays										
					 From
						sAssessment.tResultDetail RD
						INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId	
						LEFT JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND T.AcademicId = SR.AcademicId 									
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
						
--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
						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
					
					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
						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			
					 From						 
					   sAssessment.tResult R  				 
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON  T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
		execute(@query)
		
		select @lSubExamId = SubExamId from sAssessment.tExamCombine  Where ExamId  = @rExamId AND ExamOrder = 3
		set @query ='update T set					 
					SubjectGradeTerm3=RD.SubjectGrade,
					SubjectObtainTerm3 = RD.Obtain,
					SubjectMaxTerm3= ED.Maximum				 
					 From
						sAssessment.tResultDetail RD
						INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
		execute(@query)
		set @query ='update T set
 
					TotalMarkTerm3 = R.TotalMarks,
					TotalObtainTerm3=R.TotalObtain,
					PercentageTerm3=R.Percentage,
					RankNumberTerm3=R.RankNumber,
					ResultGradeTerm3=R.ResultGrade,
					PercentileTerm3 = R.Percentile,
					ResultStatusTerm3 = R.ResultStatus,
					ExamNameTerm3 = ESGM.Code			
					 From						 
					   sAssessment.tResult R  				 
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON  T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
		execute(@query)
	END
	
	
	
	
	
	--WHILE (@lCount1 <= 6)
	--BEGIN
	--	set @query ='ALTER TABLE #TempAllExam DROP COLUMN MaximumMark' + convert(nvarchar(15),@lCount1)
	--	execute(@query)
	--	set @query ='ALTER TABLE #TempAllExam DROP COLUMN Exam' + convert(nvarchar(150),@lCount1)+ 'Name'
	--	execute(@query)
	--	set @query ='ALTER TABLE #TempAllExam DROP COLUMN SubjectGrade' + convert(nvarchar(150),@lCount1)
	--	execute(@query)		
	--	set @query ='ALTER TABLE #TempAllExam DROP COLUMN Obtain' + convert(nvarchar(15),@lCount1)
	--	execute(@query)
	--	set @query ='ALTER TABLE #TempAllExam DROP COLUMN ExamMaximum' + convert(nvarchar(15),@lCount1)
	--	execute(@query)
	--	SET @lCount1 = @lCount1 + 1
	--END
	
	SELECT @rBuilder1,@rBuilder2, T.*
	FROM #TempAllExam T
	
	--INNER JOIN SSETUP.TCLASSSUBJECT CS ON CS.ID = T.CLASSSUBJECTID
	--WHERE
	--	((T.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
	--	AND ((T.RollNo <= @rToRollNo) OR (@rToRollNo=0))
	--	AND ((T.RankNumber >= @rFromRank) OR (@rFromRank=0))
	--	AND ((T.RankNumber <= @rToRank) OR (@rToRank=0))
	--	AND ((T.ResultGrade = @rGrade) OR (@rGrade=''))
	--	AND ((T.StudCode=@rCode) OR (@rCode=''))		
		--order by T.RollNo,CS.ORDERINDEX
	--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			
-- SELECT  AS Builder1,@rBuilder2 AS Builder2, T.* FROM sAssessment.tTempAllExam T
 
	END
	--SELECT @rBuilder1 AS Builder1,@rBuilder2 AS Builder2, T.* FROM sAssessment.tTempAllExam T
	
--end
GO
PRINT N'Altering [sAssessment].[pRptResultSheetStandardMultiExamGet_Backup]...';


GO
ALTER PROCEDURE [sAssessment].[pRptResultSheetStandardMultiExamGet_Backup]
	 
	 @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.tTempAllExam
 --drop table sAssessment.tTempAllExam
 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

--#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,		
		 
		 
		SubjectGradeTerm1 NVarchar(50),
		SubjectGradeTerm2 NVarchar(50),
		SubjectGradeTerm3 NVarchar(50),
		IsMarksInDecimal bit,
		column_visible bit,
		--Obtain decimal(5,2),
		Percentile decimal(5,2),
		--ClassSubject nvarchar(100),
		ResultDetailId bigint,
		ResultId bigint,	
		Remark1 nvarchar(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), 
		
		TermScopeId tinyint,		 
		StudentPhoto varbinary(max),
		GradeString nvarchar(1000),
		IsDisplayGradeString bit,		 
		IsDisplayInMarksheet bit,
		IsShowSubjectGrade bit,
		IsIncludeInTotal bit,
		ClassSubjectID int,
		SubjectId int,
		--Maximum decimal(5,2),
		SubjectOrderIndex smallint,
		SubjectGrade NVarchar(50),
		SubjectName NVarchar(150),
		SubjectCode Nvarchar(50),	
		SubjectMinimum decimal(8,2),		
		SubjectMaximum decimal(8,2),
		SubjectObtain  decimal(8,2),
		
		Exam1Name Nvarchar(150),		
		TotalMarks1 decimal(8,2),		
		TotalObtain1 decimal(8,2),
		Percentage1 decimal(8,2),
		RankNumber1 int,
		ResultGrade1 NVarchar(50),
		Percentile1 decimal(8,2),
		ResultStatus1 Nvarchar(20),
		
		Exam2Name nvarchar(150),	
		TotalMarks2 decimal(8,2),
		TotalObtain2 decimal(8,2),
		Percentage2 decimal(8,2),
		RankNumber2 int,
		ResultGrade2 NVarchar(50),
		Percentile2 decimal(8,2),
		ResultStatus2 Nvarchar(20),
		
		Exam3Name nvarchar(150),	
		TotalMarks3 decimal(8,2),
		TotalObtain3 decimal(8,2),
		Percentage3 decimal(8,2),
		RankNumber3 int,
		ResultGrade3 NVarchar(50),
		Percentile3 decimal(8,2),		
		ResultStatus3 Nvarchar(20),
		
		Exam4Name nvarchar(150),	
		TotalMarks4 decimal(8,2),
		TotalObtain4 decimal(8,2),
		Percentage4 decimal(8,2),
		RankNumber4 int,
		ResultGrade4 NVarchar(50),
		Percentile4 decimal(8,2),
		ResultStatus4 Nvarchar(20),
		
		Exam5Name nvarchar(150),		
		TotalMarks5 decimal(8,2),
		TotalObtain5 decimal(8,2),
		Percentage5 decimal(8,2),
		RankNumber5 int,
		ResultGrade5 NVarchar(50),
		Percentile5 decimal(8,2),
		ResultStatus5 Nvarchar(20),
		
		Exam6Name nvarchar(150),	
		TotalMarks6 decimal(8,2),
		TotalObtain6 decimal(8,2),
		Percentage6 decimal(8,2),
		RankNumber6 int,
		ResultGrade6 NVarchar(50),
		Percentile6 decimal(8,2),
		ResultStatus6 Nvarchar(20),
		
		Exam7Name nvarchar(150),		
		TotalMarks7 decimal(8,2),
		TotalObtain7 decimal(8,2),
		Percentage7 decimal(8,2),
		RankNumber7 int,
		ResultGrade7 NVarchar(50),
		Percentile7 decimal(8,2),
		ResultStatus7 Nvarchar(20),
		
		Exam8Name nvarchar(150),
		TotalMarks8 decimal(8,2),
		TotalObtain8 decimal(8,2),
		Percentage8 decimal(8,2),
		RankNumber8 int,
		ResultGrade8 NVarchar(50),
		Percentile8 decimal(8,2),
		ResultStatus8 Nvarchar(20),
		
		
		Exam9Name nvarchar(150),	
		TotalMarks9 decimal(8,2),
		TotalObtain9 decimal(8,2),
		Percentage9 decimal(8,2),
		RankNumber9 int,
		ResultGrade9 NVarchar(50),
		Percentile9 decimal(8,2),
		ResultStatus9 Nvarchar(20),
		
		Exam10Name nvarchar(150),	
		TotalMarks10 decimal(8,2),
		TotalObtain10 decimal(8,2),
		Percentage10 decimal(8,2),
		RankNumber10 int,
		ResultGrade10 NVarchar(50),
		Percentile10 decimal(8,2),
		ResultStatus10 Nvarchar(20),
		
		Exam11Name nvarchar(150),	
		TotalMarks11 decimal(8,2),
		TotalObtain11 decimal(8,2),
		Percentage11 decimal(8,2),
		RankNumber11 int,
		ResultGrade11 NVarchar(50),
		Percentile11 decimal(8,2),
		ResultStatus11 Nvarchar(20),
		
		Exam12Name nvarchar(150),	
		TotalMarks12 decimal(8,2),
		TotalObtain12 decimal(8,2),
		Percentage12 decimal(8,2),
		RankNumber12 int,
		ResultGrade12 NVarchar(50),
		Percentile12 decimal(8,2),
		ResultStatus12 Nvarchar(20),
		
		ResultRemark1 nvarchar(200),
		ResultRemark2 nvarchar(200),
		
		TotalDays 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(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),
		SubjectMaxTerm1 decimal(8,2),
		SubjectMaxTerm2 decimal(8,2),
		SubjectMaxTerm3 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),
		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(20),
		HighestDivisionMark decimal(5, 2),
		HighestDivisionGrade nvarchar(50),
		StreamTitle nvarchar(50),
		ResultSheetAdditionalTitle nvarchar(100),
		SchoolNameLabel nvarchar(200),
		MediumLabel nvarchar(100),
		NameLabel nvarchar(200),
		CodeLabel nvarchar(100),
		SUIDLabel nvarchar(100),
		ClassLabel nvarchar(100),
		BirthDateLabel nvarchar(100),
		RollNoLabel nvarchar(100),
		FatherNameLabel nvarchar(100),
		MotherNameLabel nvarchar(100),
		TotalWorkingDaysLabel nvarchar(100),
		TotalPresentDaysLabel nvarchar(100),
		HeightLabel nvarchar(100),
		WeightLabel nvarchar(100),
		SubjectLabel nvarchar(100),
		MaxMarksLabel nvarchar(100),
		TotalLabel nvarchar(100),
		GradeLabel nvarchar(100),
		GrandTotalLabel nvarchar(100),
		ResultStatusLabel nvarchar(100),
		RankNoLabel nvarchar(100),
		PercentileLabel nvarchar(100),
		PercentageLabel nvarchar(100),
		OverallGradeLabel nvarchar(100),
		DisplayAttendanceId int,
		ReportHeaderId int,
		StudentImage nvarchar(500)
		
	)	
	 --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,
	ResultSheetAdditionalTitle,
	SchoolNameLabel,
	MediumLabel,
	NameLabel,
	CodeLabel,
	SUIDLabel,
	ClassLabel,
	BirthDateLabel,
	RollNoLabel,
	FatherNameLabel,
	MotherNameLabel,
	TotalWorkingDaysLabel,
	TotalPresentDaysLabel,
	HeightLabel,
	WeightLabel,
	SubjectLabel,
	MaxMarksLabel,
	TotalLabel,
	GradeLabel,
	GrandTotalLabel,
	ResultStatusLabel,
	RankNoLabel,
	PercentileLabel,
	PercentageLabel,
	OverallGradeLabel,
	DisplayAttendanceId,
	ReportHeaderId,
	StudentImage
	)
	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(EM.ResultSheetAdditionalTitle,'') AS ResultSheetAdditionalTitle,
		ISNULL(ALS.SchoolNameLabel,'')AS SchoolNameLabel,
		ISNULL(ALS.MediumLabel,'') AS MediumLabel,
		ISNULL(ALS.NameLabel,'') AS NameLabel,
		ISNULL(ALS.CodeLabel,'') AS CodeLabel,
		ISNULL(ALS.SUIDLabel,'') AS SUIDLabel,
		ISNULL(ALS.ClassLabel,'') AS ClassLabel,
		ISNULL(ALS.BirthDateLabel,'') AS BirthDateLabel,
		ISNULL(ALS.RollNoLabel,'') AS RollNoLabel,
		ISNULL(ALS.FatherNameLabel,'') AS FatherNameLabel,
		ISNULL(ALS.MotherNameLabel,'') AS MotherNameLabel,
		ISNULL(ALS.TotalWorkingDaysLabel,'')AS TotalWorkingDaysLabel,
		ISNULL(ALS.TotalPresentDaysLabel,'') AS TotalPresentDaysLabel,
		ISNULL(ALS.HeightLabel,'') AS HeightLabel,
		ISNULL(ALS.WeightLabel,'') AS WeightLabel,
		ISNULL(ALS.SubjectLabel,'') AS SubjectLabel,
		ISNULL(ALS.MaxMarksLabel,'') AS MaxMarksLabel,
		ISNULL(ALS.TotalLabel,'') AS TotalLabel,
		ISNULL(ALS.GradeLabel,'') AS GradeLabel,
		ISNULl(ALS.GrandTotalLabel,'') AS GrandTotalLabel,
		ISNULl(ALS.ResultStatusLabel,'') AS ResultStatusLabel,
		ISNULL(ALS.RankNoLabel,'') AS RankNoLabel,
		ISNULL(ALS.PercentileLabel,'') AS PercentileLabel,
		ISNULl(ALS.PercentageLabel,'') AS PercentageLabel,
		ISNULL(ALS.OverallGradeLabel,'') AS OverallGradeLabel,
		ISNULL(EM.DisplayAttendanceId,'') AS DisplayAttendanceId,
		ISNULL(EM.ReportHeaderId,'') AS ReportHeaderId,
		--('~/Content/' + A.OrgId + A.StudentId + '.jpg')AS StudentImage
		'~/Content/9911/9911000000299.jpg' AS StudentImage
				
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.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
	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 sAssessment.tAssessmentLabelSetup ALS ON ALS.OrgId = OM.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.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  ISNULL(EMP.IsOtherUser,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 ((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,	
					 				
					 SubjectGrade' + convert(nvarchar(15),@lCount)+ '=RD.SubjectGrade,
					 TotalDays'+convert(nvarchar(15),@lCount)+'=SR.TotalDays,
					 PresentDays'+convert(nvarchar(15),@lCount)+'=SR.PresentDays										
					 From
						sAssessment.tResultDetail RD
						INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId	
						LEFT JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND T.AcademicId = SR.AcademicId 									
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
						
--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)
		
		
	set @lCount = @lCount -1
	end
	

	IF (@IsIncludeSubExam = 1)
	BEGIN	
		select @lSubExamId = SubExamId from sAssessment.tExamCombine  Where ExamId  = @rExamId AND ExamOrder = 1
		--select @ExamTitle = Title from sAssessment.tExamMaster Where Id = @lSubExamId	
		
		
			set @query ='update T set					 
					SubjectGradeTerm1=RD.SubjectGrade,
					SubjectObtainTerm1 = RD.Obtain,
					 SubjectMaxTerm1 = ED.Maximum
							 
					 From
						 sAssessment.tResultDetail RD
						INNER JOIN  sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
		
				execute(@query)
				
		set @query ='update T set					 
					 
					TotalMarkTerm1 = R.TotalMarks,
					TotalObtainTerm1=R.TotalObtain,
					PercentageTerm1=R.Percentage,
					RankNumberTerm1=R.RankNumber,
					ResultGradeTerm1=R.ResultGrade,
					PercentileTerm1 = R.Percentile,
					ResultStatusTerm1 = R.ResultStatus,
					ExamNameTerm1 = ESGM.Code,
					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
					
					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
						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			
					 From						 
					   sAssessment.tResult R  				 
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON  T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
		execute(@query)
		
		select @lSubExamId = SubExamId from sAssessment.tExamCombine  Where ExamId  = @rExamId AND ExamOrder = 3
		set @query ='update T set					 
					SubjectGradeTerm3=RD.SubjectGrade,
					SubjectObtainTerm3 = RD.Obtain,
					SubjectMaxTerm3= ED.Maximum				 
					 From
						sAssessment.tResultDetail RD
						INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
		execute(@query)
		set @query ='update T set
 
					TotalMarkTerm3 = R.TotalMarks,
					TotalObtainTerm3=R.TotalObtain,
					PercentageTerm3=R.Percentage,
					RankNumberTerm3=R.RankNumber,
					ResultGradeTerm3=R.ResultGrade,
					PercentileTerm3 = R.Percentile,
					ResultStatusTerm3 = R.ResultStatus,
					ExamNameTerm3 = ESGM.Code			
					 From						 
					   sAssessment.tResult R  				 
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON  T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
		execute(@query)
	END
	
	
	
	
	
	--WHILE (@lCount1 <= 6)
	--BEGIN
	--	set @query ='ALTER TABLE #TempAllExam DROP COLUMN MaximumMark' + convert(nvarchar(15),@lCount1)
	--	execute(@query)
	--	set @query ='ALTER TABLE #TempAllExam DROP COLUMN Exam' + convert(nvarchar(150),@lCount1)+ 'Name'
	--	execute(@query)
	--	set @query ='ALTER TABLE #TempAllExam DROP COLUMN SubjectGrade' + convert(nvarchar(150),@lCount1)
	--	execute(@query)		
	--	set @query ='ALTER TABLE #TempAllExam DROP COLUMN Obtain' + convert(nvarchar(15),@lCount1)
	--	execute(@query)
	--	set @query ='ALTER TABLE #TempAllExam DROP COLUMN ExamMaximum' + convert(nvarchar(15),@lCount1)
	--	execute(@query)
	--	SET @lCount1 = @lCount1 + 1
	--END
	
	SELECT @rBuilder1,@rBuilder2, T.*
	FROM #TempAllExam T
	
	--INNER JOIN SSETUP.TCLASSSUBJECT CS ON CS.ID = T.CLASSSUBJECTID
	--WHERE
	--	((T.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
	--	AND ((T.RollNo <= @rToRollNo) OR (@rToRollNo=0))
	--	AND ((T.RankNumber >= @rFromRank) OR (@rFromRank=0))
	--	AND ((T.RankNumber <= @rToRank) OR (@rToRank=0))
	--	AND ((T.ResultGrade = @rGrade) OR (@rGrade=''))
	--	AND ((T.StudCode=@rCode) OR (@rCode=''))		
		--order by T.RollNo,CS.ORDERINDEX
	--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			
--SELECT  '' AS Builder1,'' AS Builder2, T.* FROM sAssessment.tTempAllExam T
 
	END
	--SELECT @rBuilder1 AS Builder1,@rBuilder2 AS Builder2, T.* FROM sAssessment.tTempAllExam T
	
--end
GO
PRINT N'Altering [sAssessment].[pRptResultSheetStandardMultiExamGet_Old]...';


GO
--Date : 02/11/2022
ALTER PROCEDURE [sAssessment].[pRptResultSheetStandardMultiExamGet_Old]
	 
	 @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.tTempAllExam
-- --drop table sAssessment.tTempAllExam
 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

--#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,		
		 
		 
		SubjectGradeTerm1 NVarchar(50),
		SubjectGradeTerm2 NVarchar(50),
		SubjectGradeTerm3 NVarchar(50),
		IsMarksInDecimal bit,
		column_visible bit,
		--Obtain decimal(5,2),
		Percentile decimal(5,2),
		--ClassSubject nvarchar(100),
		ResultDetailId bigint,
		ResultId bigint,	
		Remark1 nvarchar(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), 
		
		TermScopeId tinyint,		 
		StudentPhoto varbinary(max),
		GradeString nvarchar(1000),
		IsDisplayGradeString bit,		 
		IsDisplayInMarksheet bit,
		IsShowSubjectGrade bit,
		IsIncludeInTotal bit,
		ClassSubjectID int,
		SubjectId int,
		--Maximum decimal(5,2),
		SubjectOrderIndex smallint,
		SubjectGrade NVarchar(50),
		SubjectName NVarchar(150),
		SubjectCode Nvarchar(50),	
		SubjectMinimum decimal(8,2),		
		SubjectMaximum decimal(8,2),
		SubjectObtain  decimal(8,2),
		
		Exam1Name Nvarchar(150),		
		TotalMarks1 decimal(8,2),		
		TotalObtain1 decimal(8,2),
		Percentage1 decimal(8,2),
		RankNumber1 int,
		ResultGrade1 NVarchar(50),
		Percentile1 decimal(8,2),
		ResultStatus1 Nvarchar(20),
		
		Exam2Name nvarchar(150),	
		TotalMarks2 decimal(8,2),
		TotalObtain2 decimal(8,2),
		Percentage2 decimal(8,2),
		RankNumber2 int,
		ResultGrade2 NVarchar(50),
		Percentile2 decimal(8,2),
		ResultStatus2 Nvarchar(20),
		
		Exam3Name nvarchar(150),	
		TotalMarks3 decimal(8,2),
		TotalObtain3 decimal(8,2),
		Percentage3 decimal(8,2),
		RankNumber3 int,
		ResultGrade3 NVarchar(50),
		Percentile3 decimal(8,2),		
		ResultStatus3 Nvarchar(20),
		
		Exam4Name nvarchar(150),	
		TotalMarks4 decimal(8,2),
		TotalObtain4 decimal(8,2),
		Percentage4 decimal(8,2),
		RankNumber4 int,
		ResultGrade4 NVarchar(50),
		Percentile4 decimal(8,2),
		ResultStatus4 Nvarchar(20),
		
		Exam5Name nvarchar(150),		
		TotalMarks5 decimal(8,2),
		TotalObtain5 decimal(8,2),
		Percentage5 decimal(8,2),
		RankNumber5 int,
		ResultGrade5 NVarchar(50),
		Percentile5 decimal(8,2),
		ResultStatus5 Nvarchar(20),
		
		Exam6Name nvarchar(150),	
		TotalMarks6 decimal(8,2),
		TotalObtain6 decimal(8,2),
		Percentage6 decimal(8,2),
		RankNumber6 int,
		ResultGrade6 NVarchar(50),
		Percentile6 decimal(8,2),
		ResultStatus6 Nvarchar(20),
		
		Exam7Name nvarchar(150),		
		TotalMarks7 decimal(8,2),
		TotalObtain7 decimal(8,2),
		Percentage7 decimal(8,2),
		RankNumber7 int,
		ResultGrade7 NVarchar(50),
		Percentile7 decimal(8,2),
		ResultStatus7 Nvarchar(20),
		
		Exam8Name nvarchar(150),
		TotalMarks8 decimal(8,2),
		TotalObtain8 decimal(8,2),
		Percentage8 decimal(8,2),
		RankNumber8 int,
		ResultGrade8 NVarchar(50),
		Percentile8 decimal(8,2),
		ResultStatus8 Nvarchar(20),
		
		
		Exam9Name nvarchar(150),	
		TotalMarks9 decimal(8,2),
		TotalObtain9 decimal(8,2),
		Percentage9 decimal(8,2),
		RankNumber9 int,
		ResultGrade9 NVarchar(50),
		Percentile9 decimal(8,2),
		ResultStatus9 Nvarchar(20),
		
		Exam10Name nvarchar(150),	
		TotalMarks10 decimal(8,2),
		TotalObtain10 decimal(8,2),
		Percentage10 decimal(8,2),
		RankNumber10 int,
		ResultGrade10 NVarchar(50),
		Percentile10 decimal(8,2),
		ResultStatus10 Nvarchar(20),
		
		Exam11Name nvarchar(150),	
		TotalMarks11 decimal(8,2),
		TotalObtain11 decimal(8,2),
		Percentage11 decimal(8,2),
		RankNumber11 int,
		ResultGrade11 NVarchar(50),
		Percentile11 decimal(8,2),
		ResultStatus11 Nvarchar(20),
		
		Exam12Name nvarchar(150),	
		TotalMarks12 decimal(8,2),
		TotalObtain12 decimal(8,2),
		Percentage12 decimal(8,2),
		RankNumber12 int,
		ResultGrade12 NVarchar(50),
		Percentile12 decimal(8,2),
		ResultStatus12 Nvarchar(20),
		
		ResultRemark1 nvarchar(200),
		ResultRemark2 nvarchar(200),
		
		TotalDays 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(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),
		SubjectMaxTerm1 decimal(8,2),
		SubjectMaxTerm2 decimal(8,2),
		SubjectMaxTerm3 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),
		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(20),
		HighestDivisionMark decimal(5, 2),
		HighestDivisionGrade nvarchar(50),
		StreamTitle nvarchar(50),
		AdmissionNo int,
		AdmissionDate Date
		
	)	
	 --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
	)
	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.AdmissionFormNumber,0) AS AdmissionNo,
		ISNULL(StuA.AdmissionDate,'') AS Admissio
				
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.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
	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  ISNULL(EMP.IsOtherUser,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 ((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,	
					 				
					 SubjectGrade' + convert(nvarchar(15),@lCount)+ '=RD.SubjectGrade,
					 TotalDays'+convert(nvarchar(15),@lCount)+'=SR.TotalDays,
					 PresentDays'+convert(nvarchar(15),@lCount)+'=SR.PresentDays										
					 From
						sAssessment.tResultDetail RD
						INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId	
						LEFT JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND T.AcademicId = SR.AcademicId 									
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
						
--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)
		
		
	set @lCount = @lCount -1
	end
	

	IF (@IsIncludeSubExam = 1)
	BEGIN	
		select @lSubExamId = SubExamId from sAssessment.tExamCombine  Where ExamId  = @rExamId AND ExamOrder = 1
		--select @ExamTitle = Title from sAssessment.tExamMaster Where Id = @lSubExamId	
		
		
			set @query ='update T set					 
					SubjectGradeTerm1=RD.SubjectGrade,
					SubjectObtainTerm1 = RD.Obtain,
					 SubjectMaxTerm1 = ED.Maximum
							 
					 From
						 sAssessment.tResultDetail RD
						INNER JOIN  sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
		
				execute(@query)
				
		set @query ='update T set					 
					 
					TotalMarkTerm1 = R.TotalMarks,
					TotalObtainTerm1=R.TotalObtain,
					PercentageTerm1=R.Percentage,
					RankNumberTerm1=R.RankNumber,
					ResultGradeTerm1=R.ResultGrade,
					PercentileTerm1 = R.Percentile,
					ResultStatusTerm1 = R.ResultStatus,
					ExamNameTerm1 = ESGM.Code,
					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
					
					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
						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			
					 From						 
					   sAssessment.tResult R  				 
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON  T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
		execute(@query)
		
		select @lSubExamId = SubExamId from sAssessment.tExamCombine  Where ExamId  = @rExamId AND ExamOrder = 3
		set @query ='update T set					 
					SubjectGradeTerm3=RD.SubjectGrade,
					SubjectObtainTerm3 = RD.Obtain,
					SubjectMaxTerm3= ED.Maximum				 
					 From
						sAssessment.tResultDetail RD
						INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
		execute(@query)
		set @query ='update T set
 
					TotalMarkTerm3 = R.TotalMarks,
					TotalObtainTerm3=R.TotalObtain,
					PercentageTerm3=R.Percentage,
					RankNumberTerm3=R.RankNumber,
					ResultGradeTerm3=R.ResultGrade,
					PercentileTerm3 = R.Percentile,
					ResultStatusTerm3 = R.ResultStatus,
					ExamNameTerm3 = ESGM.Code			
					 From						 
					   sAssessment.tResult R  				 
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON  T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
		execute(@query)
	END
	
	
	
	
	
	--WHILE (@lCount1 <= 6)
	--BEGIN
	--	set @query ='ALTER TABLE #TempAllExam DROP COLUMN MaximumMark' + convert(nvarchar(15),@lCount1)
	--	execute(@query)
	--	set @query ='ALTER TABLE #TempAllExam DROP COLUMN Exam' + convert(nvarchar(150),@lCount1)+ 'Name'
	--	execute(@query)
	--	set @query ='ALTER TABLE #TempAllExam DROP COLUMN SubjectGrade' + convert(nvarchar(150),@lCount1)
	--	execute(@query)		
	--	set @query ='ALTER TABLE #TempAllExam DROP COLUMN Obtain' + convert(nvarchar(15),@lCount1)
	--	execute(@query)
	--	set @query ='ALTER TABLE #TempAllExam DROP COLUMN ExamMaximum' + convert(nvarchar(15),@lCount1)
	--	execute(@query)
	--	SET @lCount1 = @lCount1 + 1
	--END
	
	SELECT @rBuilder1,@rBuilder2, T.*
	FROM #TempAllExam T
	
	--INNER JOIN SSETUP.TCLASSSUBJECT CS ON CS.ID = T.CLASSSUBJECTID
	--WHERE
	--	((T.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
	--	AND ((T.RollNo <= @rToRollNo) OR (@rToRollNo=0))
	--	AND ((T.RankNumber >= @rFromRank) OR (@rFromRank=0))
	--	AND ((T.RankNumber <= @rToRank) OR (@rToRank=0))
	--	AND ((T.ResultGrade = @rGrade) OR (@rGrade=''))
	--	AND ((T.StudCode=@rCode) OR (@rCode=''))		
		--order by T.RollNo,CS.ORDERINDEX
	--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			
-- SELECT  AS Builder1,@rBuilder2 AS Builder2, T.* FROM sAssessment.tTempAllExam T
 
	END
	--SELECT @rBuilder1 AS Builder1,@rBuilder2 AS Builder2, T.* FROM sAssessment.tTempAllExam T
	
--end
GO
PRINT N'Altering [sAssessment].[pRptResultSheetStandardMultiExamGetwithResultDetailOther]...';


GO

 ALTER PROCEDURE [sAssessment].[pRptResultSheetStandardMultiExamGetwithResultDetailOther]
	@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,
	 @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.tTempAllExam
-- --drop table sAssessment.tTempAllExam
 
  
DECLARE @GradeString nvarchar(1000)
DECLARE @GradeStringRemark nvarchar(500),
@GradeSetId int , @IsIncludeSubExam bit,@GradeStringHtml nvarchar(500)
SELECT @GradeSetId = GradesetId,
	   @IsIncludeSubExam = ISNULL(IsIncludeSubExam,0)  FROM sAssessment.tExamMaster WHERE Id = @rExamId
SELECT @GradeString = [sAssessment].[fGradeStringGet](@GradeSetId)

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

--#TempAllExam
	CREATE TABLE #TempAllExam
	(
		AcademicIdText nvarchar(20),
		ExamIdText nvarchar(20),
		DivisionIdText nvarchar(50),
		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,		
		 
		 
		SubjectGradeTerm1 NVarchar(50),
		SubjectGradeTerm2 NVarchar(50),
		SubjectGradeTerm3 NVarchar(50),
		IsMarksInDecimal bit,
		column_visible bit,
		--Obtain decimal(5,2),
		Percentile decimal(5,2),
		--ClassSubject nvarchar(100),
		ResultDetailId bigint,
		ResultId bigint,	
		Remark1 nvarchar(1000),
		Remark2 nvarchar(500),
		Remark3 nvarchar(500),
		DisplayTitle nvarchar(150),		
		IsRankNo bit, 
		IsGrade bit,
		IsPercentile bit,
		IsPercentage bit,
		IsSubjectPercentile bit,
		IsProcessResult bit,
		IsNegativeMarks bit,
		IsIncludeCoScholastic bit,
		IsOnPrePrinted bit,
		IsDisplayPhoto bit,
		IsDisplayBirthDate bit,
		IsLockForEdit bit,
		IsDisplaySchoolName bit,			
		IsDisplayAttendance bit,
		IsDisplayHeightWeight bit,
		IsResultStatus bit,
		FooterAdjustmentText nvarchar(max),
		DetailAdjustmentText nvarchar(max),
		FooterAdjustment smallint,
		DetailAdjustment smallint,
		ResultRemark nvarchar(200),
		DateOfBirth date,
		HeightTerm1 decimal(5,2),
		WeightTerm1 decimal(5,2),
		HeightTerm2 decimal(5,2),
		WeightTerm2 decimal(5,2),
		HeightAnnual decimal(5,2),
		WeightAnnual decimal(5,2),
		PresentDaysTerm1 smallint,
		PresentDaysTerm2 smallint,
		PresentDaysAnnual smallint,
		TotalDaysTerm1 smallint,
		TotalDaysTerm2 smallint,
		TotalDaysAnnual smallint,
		TotalMarkTerm1 decimal(8,2),
		TotalObtainTerm1 decimal(8,2),
		PercentageTerm1 decimal(8,2),
		RankNumberTerm1 int,
		ResultGradeTerm1 NVarchar(50),
		PercentileTerm1 decimal(8,2),
		ResultStatusTerm1 Nvarchar(20),		   
		TotalMarkTerm2 decimal(8,2),
		TotalObtainTerm2 decimal(8,2),
		PercentageTerm2 decimal(8,2),
		RankNumberTerm2 int,
		ResultGradeTerm2 NVarchar(50),
		PercentileTerm2 decimal(8,2),
		ResultStatusTerm2 Nvarchar(20), 
		TotalMarkTerm3 		decimal(8,2),
		TotalObtainTerm3 decimal(8,2),
		PercentageTerm3 decimal(8,2),
		RankNumberTerm3 int,
		ResultGradeTerm3 NVarchar(50),
		PercentileTerm3 decimal(8,2),
		ResultStatusTerm3 Nvarchar(20), 
		
		TermScopeId tinyint,		 
		StudentPhoto varbinary(max),
		GradeString nvarchar(1000),
		IsDisplayGradeString bit,		 
		IsDisplayInMarksheet bit,
		IsShowSubjectGrade bit,
		IsIncludeInTotal bit,
		ClassSubjectID int,
		SubjectId int,
		--Maximum decimal(5,2),
		SubjectOrderIndex smallint,
		SubjectGrade NVarchar(50),
		SubjectName NVarchar(150),
		SubjectCode Nvarchar(50),	
		SubjectMinimum decimal(8,2),		
		SubjectMaximum decimal(8,2),
		SubjectObtain  decimal(8,2),
		
		Exam1Name Nvarchar(150),		
		TotalMarks1 decimal(8,2),		
		TotalObtain1 decimal(8,2),
		Percentage1 decimal(8,2),
		RankNumber1 int,
		ResultGrade1 NVarchar(50),
		Percentile1 decimal(8,2),
		ResultStatus1 Nvarchar(20),
		
		Exam2Name nvarchar(150),	
		TotalMarks2 decimal(8,2),
		TotalObtain2 decimal(8,2),
		Percentage2 decimal(8,2),
		RankNumber2 int,
		ResultGrade2 NVarchar(50),
		Percentile2 decimal(8,2),
		ResultStatus2 Nvarchar(20),
		
		Exam3Name nvarchar(150),	
		TotalMarks3 decimal(8,2),
		TotalObtain3 decimal(8,2),
		Percentage3 decimal(8,2),
		RankNumber3 int,
		ResultGrade3 NVarchar(50),
		Percentile3 decimal(8,2),		
		ResultStatus3 Nvarchar(20),
		
		Exam4Name nvarchar(150),	
		TotalMarks4 decimal(8,2),
		TotalObtain4 decimal(8,2),
		Percentage4 decimal(8,2),
		RankNumber4 int,
		ResultGrade4 NVarchar(50),
		Percentile4 decimal(8,2),
		ResultStatus4 Nvarchar(20),
		
		Exam5Name nvarchar(150),		
		TotalMarks5 decimal(8,2),
		TotalObtain5 decimal(8,2),
		Percentage5 decimal(8,2),
		RankNumber5 int,
		ResultGrade5 NVarchar(50),
		Percentile5 decimal(8,2),
		ResultStatus5 Nvarchar(20),
		
		Exam6Name nvarchar(150),	
		TotalMarks6 decimal(8,2),
		TotalObtain6 decimal(8,2),
		Percentage6 decimal(8,2),
		RankNumber6 int,
		ResultGrade6 NVarchar(50),
		Percentile6 decimal(8,2),
		ResultStatus6 Nvarchar(20),
		
		Exam7Name nvarchar(150),		
		TotalMarks7 decimal(8,2),
		TotalObtain7 decimal(8,2),
		Percentage7 decimal(8,2),
		RankNumber7 int,
		ResultGrade7 NVarchar(50),
		Percentile7 decimal(8,2),
		ResultStatus7 Nvarchar(20),
		
		Exam8Name nvarchar(150),
		TotalMarks8 decimal(8,2),
		TotalObtain8 decimal(8,2),
		Percentage8 decimal(8,2),
		RankNumber8 int,
		ResultGrade8 NVarchar(50),
		Percentile8 decimal(8,2),
		ResultStatus8 Nvarchar(20),
		
		
		Exam9Name nvarchar(150),	
		TotalMarks9 decimal(8,2),
		TotalObtain9 decimal(8,2),
		Percentage9 decimal(8,2),
		RankNumber9 int,
		ResultGrade9 NVarchar(50),
		Percentile9 decimal(8,2),
		ResultStatus9 Nvarchar(20),
		
		Exam10Name nvarchar(150),	
		TotalMarks10 decimal(8,2),
		TotalObtain10 decimal(8,2),
		Percentage10 decimal(8,2),
		RankNumber10 int,
		ResultGrade10 NVarchar(50),
		Percentile10 decimal(8,2),
		ResultStatus10 Nvarchar(20),
		
		Exam11Name nvarchar(150),	
		TotalMarks11 decimal(8,2),
		TotalObtain11 decimal(8,2),
		Percentage11 decimal(8,2),
		RankNumber11 int,
		ResultGrade11 NVarchar(50),
		Percentile11 decimal(8,2),
		ResultStatus11 Nvarchar(20),
		
		Exam12Name nvarchar(150),	
		TotalMarks12 decimal(8,2),
		TotalObtain12 decimal(8,2),
		Percentage12 decimal(8,2),
		RankNumber12 int,
		ResultGrade12 NVarchar(50),
		Percentile12 decimal(8,2),
		ResultStatus12 Nvarchar(20),
		
		ResultRemark1 nvarchar(200),
		ResultRemark2 nvarchar(200),
		
		TotalDays 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(max),
		InchargeEmployeeName Nvarchar(max),
		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),
		KrupaMark 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(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 smallint,
		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),
		
		AchievementsTerm1 nvarchar(200),
		AchievementsTerm2 nvarchar(200),
		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),
		TotalCount smallint,
		PresentCount smallint,
		Remark4 nvarchar(1000)
	
		
	)	
	 --print 'temp created'    	
	INSERT INTO  #TempAllExam 
	(
	AcademicIdText,
	ExamIdText,
	DivisionIdText,
	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,
	InchargeEmployeeName,
	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,
	TotalCount,
	PresentCount,
	Remark4
	
	)
	SELECT 
		Convert(nvarchar(20),A.Id),
		Convert(nvarchar(20),@rExamId),
		Convert(nvarchar(50),@rDivisionId),
		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,
		--ISNULL(Emp.FirstName,'') +' ' + ISNULL(EMp.LastName,'') AS ClassTeacherName,
		[sAssessment].[fSubjectEmployeeGet](DM.Id,SM.Id) As ClassTeacherName,
		ISNULL(Emp.FirstName,'') +' ' + ISNULL(EMp.LastName,'') AS InchargeEmployeeName,
		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,
	    ISNULL(RDO.TotalCount,0) As TotalCount,
	    ISNULL(RDO.PresentCount,0) As PresentCount,
	    Isnull(RDO.Remark,'') As Remark4
	    ---[sAssessment].[fSubjectEmployeeGet](DM.Id,SM.Id) As ClassTeacherName
	   		
FROM 
	sAssessment.tResultDetail RD
	INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
	INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId		
	INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
	INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId	
	LEFT JOIN sSetup.tSubjectGroupMaster SG ON SG.Id = Sm.SubjectGroupId				 
	INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId
	LEFT JOIN sSetup.tOrgImages OI ON OI.Orgid = OM.Id
	INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
	INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
	INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
	INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
	LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = Dm.InchargeEmployeeId
	LEFT JOIN sHrm.tEmployeeMaster EMP ON EMP.Id = DM.InchargeEmployeeId
	INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.EXAMSUBGROUPID
	LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=StuM.Id
	LEFT JOIN sStudent.tAcademicDetail AD ON AD.AcademicId=A.Id
	LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=StuM.Id
	LEFT JOIN sAssessment.tStudentRemark SR ON R.AcademicId = SR.AcademicId AND R.ExamId = SR.ExamId
	LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = StuM.Id
	LEFT JOIN sAssessment.tOptionalSubject OS ON OS.AcademicId = R.AcademicId AND OS.ClassSubjectId = ED.ClassSubjectId  AND ED.ExamId = R.ExamId
	LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=A.StudentId
	LEFT JOIN 	sCommon.tBloodGroupMaster BGM ON BGM.Id=So.BloodGroupId
	LEFT JOIN sAssessment.tGradeSetDetail GS ON GS.GradeSetId=ED.GradeSetId AND ED.GradeSetId = @GradeSetId and RD.SubjectGrade = GS.GradeCode
	LEFT JOIN sAssessment.tResultAnalysisDivisionDetail RAD ON RAD.ClassSubjectId = CS.Id AND RAD.DivisionId = A.DivisionId AND RAD.ExamId = Em.Id
	LEFT JOIN sAssessment.tResultDetailOther RDO ON  RDO.ExamId = EM.Id AND R.Academicid =RDO.AcademicId AND ED.ClassSubjectId = RDO.ClassSubjectId
	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 sAcademic.tTeacherSubjectDivision TSD ON TSD.SubjectId=SM.Id AND TSD.DivisionId = A.DivisionId
	--LEFT JOIN sHrm.tEmployeeMaster EMP ON TSD.EmployeeId = EMP.Id
	
	 WHERE
		R.ExamId = @rExamId 
		AND ((A.DivisionId =  @rDivisionId) OR (@rDivisionId=0))
		AND ((A.ClassId =  @rClassId) OR (@rClassId=0))		 
		AND ((A.BatchId =  @rBatchId) OR (@rBatchId=0))
		AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((R.RankNumber >= @rFromRank) OR (@rFromRank=0))
		AND ((R.RankNumber <= @rToRank) OR (@rToRank=0))
		AND ((R.ResultGrade = @rGrade) OR (@rGrade=''))
		AND ((StuM.Code=@rCode) OR (@rCode=''))	
		AND ((R.Id = @rResultId) OR (@rResultId = 0))	
		AND ((StuM.StatusId=@rStatusId)OR(@rStatusId=0))
		AND((A.Id=@rAcademicId)OR (@rAcademicId=0))
		AND ((CS.SubjectId=@rSubjectId) OR(@rSubjectId=0) ) 
		AND ((R.Percentage>=@rFromPercentage) OR (@rFromPercentage=0))
		AND ((R.Percentage<=@rToPercentage) OR (@rToPercentage=0))
		 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
	--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,	
					 				
					 SubjectGrade' + convert(nvarchar(15),@lCount)+ '=RD.SubjectGrade,
					 TotalDays'+convert(nvarchar(15),@lCount)+'=SR.TotalDays,
					 PresentDays'+convert(nvarchar(15),@lCount)+'=SR.PresentDays										
					 From
						sAssessment.tResultDetail RD
						INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId	
						LEFT JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND T.AcademicId = SR.AcademicId 									
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
						
	
	 execute(@query)
	
						
			set @query ='update T set 
				    TotalMarks' + convert(nvarchar(15),@lCount)+ '=R.TotalMarks,
					TotalObtain' + convert(nvarchar(15),@lCount)+ '=R.TotalObtain,
					Percentage' + convert(nvarchar(15),@lCount)+ '=R.Percentage,
					RankNumber' + convert(nvarchar(15),@lCount)+'=R.RankNumber,
					ResultGrade' + convert(nvarchar(15),@lCount)+'=R.ResultGrade,
					Percentile' + convert(nvarchar(15),@lCount)+'=R.Percentile,
					ResultStatus' + convert(nvarchar(15),@lCount)+'=R.ResultStatus,
					Exam' + convert(nvarchar(15),@lCount)+ 'Name=ESGM.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)
		
		
	set @lCount = @lCount -1
	end
	

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

--SELECT @rBuilder1,@rBuilder2, T.* FROM sAssessment.tTempAllExam T
--end
GO
PRINT N'Altering [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

--#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(500),
		Remark2 nvarchar(500),
		Remark3 nvarchar(500),
		DisplayTitle nvarchar(150),		
		IsRankNo bit, 
		IsGrade bit,
		IsPercentile bit,
		IsPercentage bit,
		IsSubjectPercentile bit,
		IsProcessResult bit,
		IsNegativeMarks bit,
		IsIncludeCoScholastic bit,
		IsOnPrePrinted bit,
		IsDisplayPhoto bit,
		IsDisplayBirthDate bit,
		IsLockForEdit bit,
		IsDisplaySchoolName bit,			
		IsDisplayAttendance bit,
		IsDisplayHeightWeight bit,
		IsResultStatus bit,
		FooterAdjustmentText nvarchar(max),
		DetailAdjustmentText nvarchar(max),
		FooterAdjustment smallint,
		DetailAdjustment smallint,
		ResultRemark nvarchar(200),
		DateOfBirth date,
		HeightTerm1 decimal(5,2),
		WeightTerm1 decimal(5,2),
		HeightTerm2 decimal(5,2),
		WeightTerm2 decimal(5,2),
		HeightAnnual decimal(5,2),
		WeightAnnual decimal(5,2),
		PresentDaysTerm1 smallint,
		PresentDaysTerm2 smallint,
		PresentDaysAnnual smallint,
		TotalDaysTerm1 smallint,
		TotalDaysTerm2 smallint,
		TotalDaysAnnual smallint,
		TotalMarkTerm1 decimal(8,2),
		TotalObtainTerm1 decimal(8,2),
		PercentageTerm1 decimal(8,2),
		RankNumberTerm1 int,
		ResultGradeTerm1 NVarchar(50),
		PercentileTerm1 decimal(8,2),
		ResultStatusTerm1 Nvarchar(20),		   
		TotalMarkTerm2 decimal(8,2),
		TotalObtainTerm2 decimal(8,2),
		PercentageTerm2 decimal(8,2),
		RankNumberTerm2 int,
		ResultGradeTerm2 NVarchar(50),
		PercentileTerm2 decimal(8,2),
		ResultStatusTerm2 Nvarchar(20), 
		TotalMarkTerm3 		decimal(8,2),
		TotalObtainTerm3 decimal(8,2),
		PercentageTerm3 decimal(8,2),
		RankNumberTerm3 int,
		ResultGradeTerm3 NVarchar(50),
		PercentileTerm3 decimal(8,2),
		ResultStatusTerm3 Nvarchar(20), 
		
		TermScopeId tinyint,		 
		StudentPhoto varbinary(max),
		GradeString nvarchar(1000),
		IsDisplayGradeString bit,		 
		IsDisplayInMarksheet bit,
		IsShowSubjectGrade bit,
		IsIncludeInTotal bit,
		ClassSubjectID int,
		SubjectId int,
		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)
	)	
	 
	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
	)
	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
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 [sAssessment].[pRptResultSheetStandardWithAnalysisGet]...';


GO

ALTER  PROCEDURE [sAssessment].[pRptResultSheetStandardWithAnalysisGet]
	 
	 @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,
	 @rClassStatusId int=0,
	 @rMultiCode nvarchar(max)=''
		 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 

DECLARE @GradeString nvarchar(1000),
@GradeSetId int 
 
SELECT @GradeSetId = GradesetId FROM sAssessment.tExamMaster WHERE Id = @rExamId
SELECT @GradeString = [sAssessment].[fGradeStringGet](@GradeSetId)  
	SELECT 
			--Convert(nvarchar(20),A.Id) AS AcademicIdText,
			--Convert(nvarchar(20),@rExamId) AS ExamIdText,
			RAD.SubjectHighestClassMark,
			RAD.SubjectHighestDivisionMark,
			RAD.SubjectAverageClassMark,
			RAD.SubjectAverageDivisionMark,
			RAD.SubjectHighestClassGrade,
			RAD.SubjectHighestDivisionGrade,
			RAD.ClassSubjectId,
			ESGM.Title AS Exam,
			StuM.Code,
			[sStudent].[fStudentNameGet](stum.FirstName , StuM.MiddleName, StuM.LastName,OM.StudentNameFormatId ) AS Name,
			A.RollNo,
			R.AcademicId,			
			R.ResultStatus,
			CM.DisplayTitle AS Class,
			DM.DisplayTitle AS Division,
			R.TotalMarks,
			R.TotalObtain,
			R.Percentage,
			R.RankNumber,
			R.ResultGrade,
			R.Percentile,			
			RD.Id AS ResultDetailId,		
			ED.IsDisplayInMarksheet,
			ED.IsShowSubjectGrade,
			ED.IsIncludeInTotal,
			RD.Obtain AS SubjectObtain,
			ED.Minimum AS SubjectMinimum,
			ED.Maximum AS SubjectMaximum,
			RD.SubjectGrade,
			SM.Code AS SubjectCode,
			SM.Title AS SubjectName,
			(CASE ISNULL(ED.DisplayOrder,0)
			WHEN 0 THEN CS.OrderIndex
			ELSE ED.DisplayOrder END) AS SubjectOrderIndex,
			R.Id AS ResultId,
			CS.Id AS SubjectId,			 	
			EM.IsMarksInDecimal,
			--SM.OrderIndex AS SubjectCode,
			
			--CS.OrderIndex AS SubjectOrderIndex,
			ISNULL(EM.Remark1,'') AS Remark1,
			ISNULL(EM.Remark2,'') AS Remark2,
			ISNULL(EM.Remark3,'') AS Remark3,
			EM.DisplayTitle,
			EM.IsRankNo, 
			EM.IsGrade,
			EM.IsPercentile,
			EM.IsPercentage,
			EM.IsSubjectPercentile,
			EM.IsProcessResult,
			EM.IsMarksInDecimal,
			EM.IsNegativeMarks,
			EM.IsIncludeCoScholastic,
			EM.IsOnPrePrinted,
			EM.IsDisplayPhoto,
			EM.IsDisplayBirthDate,
			EM.IsLockForEdit,
			EM.IsDisplaySchoolName,			
			EM.IsDisplayAttendance,
			EM.IsDisplayHeightWeight,
			EM.IsResultStatus,
			REPLICATE(',',EM.FooterAdjustment) AS FooterAdjustmentText,
			REPLICATE(',',EM.DetailAdjustment) AS DetailAdjustmentText,
			EM.FooterAdjustment,
			EM.DetailAdjustment,
			--ISNULL(R.ResultRemark,'') AS ResultRemark,
			SO.DateOfBirth,
			SR.StudentHeight,
			SR.StudentWeight,		
			ISNULL(SR.PresentDays,0)AS PresentDays,			
			ISNULL(SR.TotalDays,0)AS TotalDays,
			SR.ResultRemark1,
			SR.ResultRemark2,						 
			EM.TermScopeId,
			SI.StudentPhoto,
			RD.IsPresent,
			@GradeString AS GradeString,
			EM.IsDisplayGradeString,
			(CASE EM.IsDisplayHighestDivisionMark
			WHEN 1 THEN [sAssessment].[fGetHighestDivisionMark](A.DivisionId ,RD.ExamDetailId)
			ELSE 0 END) AS HighestDivisionMark,
			(CASE EM.IsDisplayHighestDivisionGrade
			WHEN 1 THEN [sAssessment].[fGetHighestDivisionGrade] (A.DivisionId ,RD.ExamDetailId)
			ELSE '' END) AS HighestDivisionGrade,			
			OM.SmallAddress1,
			EM.IsDisplayParentName,
			SF.FatherName,
			SF.MotherName,
			ISNULL(ED.IsShowSubjectMark,1) AS IsShowSubjectMark,
			RAN.HighestClassMark,
			RAN.HighestDivisionMark AS DivisionHighestMark,
			RAn.HighestClassGrade,
			RAN.HighestDivisionGrade AS DivisionHighestGrade,
			RAN.AverageClassMark,
			RAn.AverageDivisionMark,
			RAN.DivisionPercentile,
			RAN.ClassPercentile 
			,RAN.TotalStudentClass,
			RAN.TotalStudentDivision,
		 
			RA.ClassRank,
			RA.DivisionRank,
			RD.Remark,
			RA.PassedSubject,
			RA.FailedSubject,
			EMP.Id AS EmployeeId,
			--TSD.EmployeeId,
			EMP.FirstName + ' ' +EMP.MiddleName +' ' +Emp.LastName AS EmployeeName,
			EI.EmployeeSign,
			EM.IsDisplayPrincipalSign,
			EM.IsDisplayTeacherSign,
			EM.DecimalFormat,
			SR.ResultRemark3,
			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,
			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(EM.IsDisplayImageHeader,0) AS IsImageHeader,
			--(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
	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 sStudent.tAcademic A ON A.Id=R.AcademicId
			 INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
			 LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = DM .InchargeEmployeeId
			 INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId		
			 --Left Join sAcademic.tTeacherSubjectDivision TSD ON TSD.SubjectId = SM.Id AND Tsd.DivisionId=A.DivisionId
			 --AND TSD.EmployeeId = EI.EmployeeId
			 LEFT JOIN sHrm.tEmployeeMaster EMP ON EMP.Id=EI.EmployeeId 
			
			  
			  LEFT JOin sAssessment.tResultAnalysis RA ON RA.AcademicId = A.Id AND RA.ExamId = EM.Id
			  LEFT JOIN sAssessment.tResultAnalysisDivisionDetail RAD ON RAD.ClassSubjectId = CS.Id AND RAD.DivisionId = A.DivisionId AND RAD.ExamId = Em.Id
			  LEFT JOIN sAssessment.tResultAnalysisDivision RAN ON RAN.DivisionId = A.DivisionId AND RAN.ExamId = EM.Id
			   
			  
		      INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId
			  LEFT JOIN sSetup.tOrgImages OI ON OI.Orgid = OM.Id
			  LEFT JOIN sStudent.tAcademicDetail AD ON AD.AcademicId=A.Id
			  INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
			  LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
			  LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=StuM.Id
			  INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			
			  INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.EXAMSUBGROUPID
			  LEFT JOIN sAssessment.tStudentRemark SR ON R.AcademicId = SR.AcademicId AND R.ExamId = SR.ExamId
			  LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = StuM.Id
			  LEFT JOIN 	sCommon.tBloodGroupMaster BGM ON BGM.Id=So.BloodGroupId
				 
	WHERE 
			
			((EM.BatchId = @rBatchId) OR  (@rBatchId = 0))
			AND ((A.ClassId=@rClassId) OR (@rClassId=0)) 
			--AND ((SM.Id=@rSubjectId) OR (@rSubjectId=0))
			AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
			AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
			AND ((R.RankNumber >= @rFromRank) OR (@rFromRank=0))
			AND ((R.RankNumber <= @rToRank) OR (@rToRank=0))
			AND ((R.ResultGrade = @rGrade) OR (@rGrade=''))
			AND (R.ExamId = @rExamId)
			AND ((StuM.Code=@rCode) OR (@rCode=''))
			AND ((R.Id = @rResultId) OR (@rResultId = 0))
			AND ((StuM.StatusId=@rStatusId)OR(@rStatusId=0))
			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 A.RollNo,CS.OrderIndex 
			--AND A.id = 1005000000007
END
GO
PRINT N'Altering [sAssessment].[pRptResultSheetStandardWithGradeGet]...';


GO

ALTER PROCEDURE [sAssessment].[pRptResultSheetStandardWithGradeGet]
	 
	 @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,
	 @rClassStatusId int=0,
	 @rMultiCode nvarchar(max)=''
	
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

DECLARE @GradeString nvarchar(1000),  @GradeStringRemark nvarchar(500),
@GradeSetId int,@lGradeStringText nvarchar(1000)
 
SELECT @GradeSetId = GradesetId FROM sAssessment.tExamMaster WHERE Id = @rExamId
 SELECT @GradeString = [sAssessment].[fGradeStringGet](@GradeSetId)
 Select @lGradeStringText = GradeStringText from sAssessment.tGradeSetMaster where Id=@Gradesetid
   
Select @GradeStringRemark = GradeStringText from sAssessment.tGradeSetMaster Where Id =@GradeSetId
 
	SELECT 
			Convert(nvarchar(20),A.Id) AS AcademicIdText,
			Convert(nvarchar(20),@rExamId) AS ExamIdText,
			Convert(nvarchar(20),EM.CoScholasticScopeId) AS CoScholasticScopeIdText,
			Convert(nvarchar(20),ISNULL(EM.IsDisplayMonthlyAttendance,0)) AS IsDisplayMonthlyAttendanceText,
				Convert(nvarchar(20),@rBatchId) AS BatchIdText,
			ESGM.Title AS Exam,
			StuM.Code,
			[sStudent].[fStudentNameGet](stum.FirstName , StuM.MiddleName, StuM.LastName,OM.StudentNameFormatId ) AS Name,
			A.RollNo,
			R.AcademicId,			
			R.ResultStatus,
			CM.DisplayTitle AS Class,
			DM.DisplayTitle AS Division,
			R.TotalMarks,
			R.TotalObtain,
			R.Percentage,
			R.RankNumber,
			R.ResultGrade,
			R.Percentile,			
			RD.Id AS ResultDetailId,		
			ED.IsDisplayInMarksheet,
			ED.IsShowSubjectGrade,
			ED.IsIncludeInTotal,
			RD.Obtain AS SubjectObtain,
			ED.Minimum AS SubjectMinimum,
			ED.Maximum AS SubjectMaximum,
			RD.SubjectGrade,
			SM.Code AS SubjectCode,
			SM.Title AS SubjectName,
			(CASE ISNULL(ED.DisplayOrder,0)
			WHEN 0 THEN CS.OrderIndex
			ELSE ED.DisplayOrder END) AS SubjectOrderIndex,
			R.Id AS ResultId,
			CS.Id AS SubjectId,			 	
			EM.IsMarksInDecimal,
			--SM.OrderIndex AS SubjectCode,
			
			--CS.OrderIndex AS SubjectOrderIndex,
			ISNULL(EM.Remark1,'') AS Remark1,
			ISNULL(EM.Remark2,'') AS Remark2,
			ISNULL(EM.Remark3,'') AS Remark3,
			EM.DisplayTitle,
			EM.IsRankNo, 
			EM.IsGrade,
			EM.IsPercentile,
			EM.IsPercentage,
			EM.IsSubjectPercentile,
			EM.IsProcessResult,
			EM.IsMarksInDecimal,
			EM.IsNegativeMarks,
			EM.IsIncludeCoScholastic,
			EM.IsOnPrePrinted,
			EM.IsDisplayPhoto,
			EM.IsDisplayBirthDate,
			EM.IsLockForEdit,
			EM.IsDisplaySchoolName,			
			EM.IsDisplayAttendance,
			EM.IsDisplayHeightWeight,
			EM.IsResultStatus,
			REPLICATE(',',EM.FooterAdjustment) AS FooterAdjustmentText,
			REPLICATE(',',EM.DetailAdjustment) AS DetailAdjustmentText,
			EM.FooterAdjustment,
			EM.DetailAdjustment,
			--ISNULL(R.ResultRemark,'') AS ResultRemark,
			SO.DateOfBirth,
			SR.StudentHeight,
			SR.StudentWeight,		
			ISNULL(SR.PresentDays,0)AS PresentDays,			
			ISNULL(SR.TotalDays,0)AS TotalDays,
			SR.ResultRemark1,
			SR.ResultRemark2,						 
			EM.TermScopeId,
			(CASE EM.IsDisplayPhoto WHEN 1 THEN
				SI.StudentPhoto
			ELSE NULL END) AS StudentPhoto,
			RD.IsPresent,
			CASE @GradeStringRemark WHEN '' THEN @GradeString  ELSE @GradeStringRemark END AS GradeString,
			EM.IsDisplayGradeString,
			(CASE EM.IsDisplayHighestDivisionMark
			WHEN 1 THEN [sAssessment].[fGetHighestDivisionMark](A.DivisionId ,RD.ExamDetailId)
			ELSE 0 END) AS HighestDivisionMark,
			(CASE EM.IsDisplayHighestDivisionGrade
			WHEN 1 THEN [sAssessment].[fGetHighestDivisionGrade] (A.DivisionId ,RD.ExamDetailId)
			ELSE '' END) AS HighestDivisionGrade,			
			OM.SmallAddress1,
			EM.IsDisplayParentName,
			SF.FatherName,
			SF.MotherName,
			ISNULL(ED.IsShowSubjectMark,1) AS IsShowSubjectMark,
			
			EM.IsDisplayTeacherSign,
			Em.IsDisplayPrincipalSign,
			(CASE 	EM.IsDisplayTeacherSign WHEN 1 THEN
				EI.EmployeeSign
			ELSE NULL END)AS EmployeeSign,
			ISNULL(EM.IsDisplayMonthlyAttendance,0) AS IsDisplayMonthlyAttendance,
			--(CASE EM.IsDisplayImageHeader WHEN 1 THEN 
			--	OI.CertificateHeaderA4 
			--ELSE 
			--	NULL END) AS MarksheetHeaderA4,
			(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,
			ISNULL(Emp.FirstName,'') +' ' + ISNULL(EMp.LastName,'') AS ClassTeacherName,
			BM.Title AS BatchName,
			Em.DecimalFormat,
			SR.Resultremark3,
			RD.GraceMark,
			ISNULL(SM.SubjectGroupId,0) AS SubjectGroupId,
		ISNULL(SG.Title,'')AS SubjectGroupTitle,
		ISNULL(SG.Code,'') AS SubjectGroupCode,
		@lGradeStringText AS GradeStringText,
		ISNULL(HM.Title,'') AS House,
		ISNULL(EM.TeacherSignCaption,'') As TeacherSignCaption,
		ISNULL(EM.PrincipalSignCaption,'') As PrincipalSignCaption,
		ISNULL(EM.ParentSignCaption,'') As ParentSignCaption,
		ISNULL(SR.ImprovementArea,'') As ImprovementArea,
		ISNULL(SR.ProgressArea,'') AS ProgressArea,
		ISNULL(SR.GeneralRemark,'') As GeneralRemark,
		ISNULL(SR.MyActivity,'') AS MyActivity,
		ISNULL(SR.ClassTeacherRemark,'') As ClassTeacherRemark,
		ISNULL(Sr.HouseRemark,'') As HouseRemark,
		ISNULL(BGM.Title,'') AS BloodGroup,
		GS.GradeTitle,
		RAD.SubjectHighestDivisionGrade,
		RAD.SubjectHighestDivisionMark,
		GM.Title AS Gender,
		GSCSD.GradeRemark
			--[sAssessment].[fGetHighestDivisionMark](A.DivisionId ,RD.ExamDetailId) AS HighestDivisionMark,
			--[sAssessment].[fGetHighestDivisionGrade] (A.DivisionId ,RD.ExamDetailId) AS HighestDivisionGrade
			
	FROM 
			sAssessment.tResultDetail RD
			INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
			INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
			INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId			
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId	
			LEFT JOIN sSetup.tSubjectGroupMaster SG ON SG.Id = Sm.SubjectGroupId				 
			INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId
			LEFT JOIN sSetup.tOrgImages OI ON OI.Orgid = OM.Id
			LEFT JOIN sStudent.tAcademicDetail AD ON AD.AcademicId=A.Id
			INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
			LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
			LEFT JOIN sCommon.tGenderMaster GM ON GM.Id = SO.GenderId
			LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=StuM.Id
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
			LEFT JOIN sHrm.tEmployeeMaster Emp ON Emp.Id=DM.InchargeEmployeeId
			LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = Dm.InchargeEmployeeId
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.EXAMSUBGROUPID
			LEFT JOIN sAssessment.tStudentRemark SR ON R.AcademicId = SR.AcademicId AND R.ExamId = SR.ExamId
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = StuM.Id
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.batchId
			LEFT JOIN sActivity.tHouseMaster HM ON HM.Id=SO.HouseId
			LEFT JOIN 	sCommon.tBloodGroupMaster BGM ON BGM.Id=So.BloodGroupId
			LEFT JOIN sAssessment.tGradeSetDetail GS ON GS.GradeSetId=ED.GradeSetId  and RD.SubjectGrade = GS.GradeCode
			
			LEFT JOIN sAssessment.tGradeSetClassSubjectMaster GSCSM ON GSCSM.ClassId = CM.Id AND GSCSM.SubjectId = SM.Id AND GSCSM.GradeSetId = GS.GradeSetId
			LEFT JOIN sAssessment.tGradeSetClassSubjectDetail GSCSD ON GSCSD.GradeSetDetailId = GS.Id AND GSCSD.GradeSetClassSubjectId = GSCSM.Id
			
			LEFT JOIN sAssessment.tResultAnalysisDivisionDetail RAD ON RAD.ClassSubjectId = CS.Id AND RAD.DivisionId = A.DivisionId AND RAD.ExamId = Em.Id
	WHERE 
			
		((EM.BatchId = @rBatchId) OR  (@rBatchId = 0))
		AND ((A.ClassId=@rClassId) OR (@rClassId=0)) 
		AND ((SM.Id=@rSubjectId) OR (@rSubjectId=0))
		AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((R.RankNumber >= @rFromRank) OR (@rFromRank=0))
		AND ((R.RankNumber <= @rToRank) OR (@rToRank=0))
		AND ((R.ResultGrade = @rGrade) OR (@rGrade=''))
		AND (R.ExamId = @rExamId)
		AND ((StuM.Code=@rCode) OR (@rCode=''))
		AND ((R.Id = @rResultId) OR (@rResultId = 0))
		AND ((StuM.StatusId=@rStatusId)OR(@rStatusId=0))
		AND ((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 A.RollNo,ED.DisplayOrder
		--AND A.id = 1005000000007
END
GO
PRINT N'Altering [sAssessment].[pRptResultSheetSubjectAcivityMultiExamGet]...';


GO
 
 
ALTER PROCEDURE [sAssessment].[pRptResultSheetSubjectAcivityMultiExamGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rSubjectId int = 0,
	 @rBatchId int=0,
	 @rClass 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,
	 @rOrgId int=0,
	 @rMultiCode nvarchar(max)=''

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
 begin
 
-- --drop table sAssessment.tTempAllExam	

 --Select * from   sAssessment.tTempAllExamSubjectActivity
DECLARE @GradeString nvarchar(1000)
DECLARE @GradeStringRemark nvarchar(1000),
@GradeSetId int , @IsIncludeSubExam bit
SELECT @GradeSetId = GradesetId,
	   @IsIncludeSubExam = ISNULL(IsIncludeSubExam,0)  FROM sAssessment.tExamMaster WHERE Id = @rExamId
SELECT @GradeString = [sAssessment].[fGradeStringGet](@GradeSetId)
SELECT @GradeStringRemark = GradeStringText from sAssessment.tGradeSetMaster Where Id =@GradeSetId
 
--#TempAllExam
	CREATE TABLE #TempAllExam
	(
		AcademicIdText nvarchar(20),
		ExamIdText nvarchar(20),
		CoScholasticScopeIdText nvarchar(20),
		
		AcademicId bigint,
		ExamName Nvarchar(150),
		StudCode NVarchar(20),
		StudentName Nvarchar(150),
		RollNo int,
		ResultStatus Nvarchar(20),	
		ClassName NVarchar(50),		
		Division NVarchar(50),
		TotalMark decimal(8,2),
		TotalObtain decimal(8,2),
		Percentage decimal(8,2),
		RankNumber int,
		ResultGrade NVarchar(50),
		
		--MaximumMark1 decimal(8,2),		
		SubjectGrade1 NVarchar(50),
		--Obtain1 decimal(8,2),
		--ExamMaximum1 decimal(8,2),
		IsPresent1 bit,
						
		MaximumMark2 decimal(8,2),	
		SubjectGrade2 NVarchar(50),
		Obtain2 decimal(8,2),
		ExamMaximum2 decimal(8,2),
		IsPresent2 bit,
				
		MaximumMark3 decimal(8,2),
		SubjectGrade3 NVarchar(50),
		Obtain3 decimal(8,2),
		ExamMaximum3 decimal(8,2),
		IsPresent3 bit,		
		
		MaximumMark4 decimal(8,2),	
		SubjectGrade4 NVarchar(50),
		Obtain4 decimal(8,2),
		ExamMaximum4 decimal(8,2),
		IsPresent4 bit,	
				
		MaximumMark5 decimal(8,2),		
		SubjectGrade5 NVarchar(50),
		Obtain5 decimal(8,2),
		ExamMaximum5 decimal(8,2),
		IsPresent5 bit,	
				
		MaximumMark6 decimal(8,2),		
		SubjectGrade6 NVarchar(50),
		Obtain6 decimal(8,2),
		ExamMaximum6 decimal(8,2),
		IsPresent6 bit,	
		
		MaximumMark7 decimal(8,2),		
		SubjectGrade7 NVarchar(50),
		Obtain7 decimal(8,2),
		ExamMaximum7 decimal(8,2),
		IsPresent7 bit,	
		
		MaximumMark8 decimal(8,2),	
		SubjectGrade8 NVarchar(50),
		Obtain8 decimal(8,2),
		ExamMaximum8 decimal(8,2),
		IsPresent8 bit,	
		
		SubjectGradeTerm1 NVarchar(50),
		SubjectGradeTerm2 NVarchar(50),
		IsMarksInDecimal bit,
		column_visible bit,
		--Obtain decimal(5,2),
		Percentile decimal(5,2),
		--ClassSubject nvarchar(100),
		ResultDetailId bigint,
		ResultId bigint,	
		Remark1 nvarchar(1000),
		Remark2 nvarchar(150),
		Remark3 nvarchar(150),
		DisplayTitle nvarchar(150),		
		IsRankNo bit, 
		IsGrade bit,
		IsPercentile bit,
		IsPercentage bit,
		IsSubjectPercentile bit,
		IsProcessResult bit,
		IsNegativeMarks bit,
		IsIncludeCoScholastic bit,
		IsOnPrePrinted bit,
		IsDisplayPhoto bit,
		IsDisplayBirthDate bit,
		IsLockForEdit bit,
		IsDisplaySchoolName bit,			
		IsDisplayAttendance bit,
		IsDisplayHeightWeight bit,
		IsResultStatus bit,
		FooterAdjustmentText nvarchar(max),
		DetailAdjustmentText nvarchar(max),
		FooterAdjustment smallint,
		DetailAdjustment smallint,
		ResultRemark nvarchar(200),
		DateOfBirth date,
		HeightTerm1 decimal(5,2),
		WeightTerm1 decimal(5,2),
		HeightTerm2 decimal(5,2),
		WeightTerm2 decimal(5,2),
		HeightAnnual decimal(5,2),
		WeightAnnual decimal(5,2),
		PresentDaysTerm1 smallint,
		PresentDaysTerm2 smallint,
		PresentDaysAnnual smallint,
		TotalDaysTerm1 smallint,
		TotalDaysTerm2 smallint,
		TotalDaysAnnual smallint,
		TotalMarkTerm1 decimal(8,2),
		TotalObtainTerm1 decimal(8,2),
		PercentageTerm1 decimal(8,2),
		RankNumberTerm1 int,
		ResultGradeTerm1 NVarchar(50),
		PercentileTerm1 decimal(8,2),
		ResultStatusTerm1 Nvarchar(20),		   
		TotalMarkTerm2 decimal(8,2),
		TotalObtainTerm2 decimal(8,2),
		PercentageTerm2 decimal(8,2),
		RankNumberTerm2 int,
		ResultGradeTerm2 NVarchar(50),
		PercentileTerm2 decimal(8,2),
		ResultStatusTerm2 Nvarchar(20), 
		TermScopeId tinyint,		 
		StudentPhoto varbinary(max),
		GradeString nvarchar(1000),
		IsDisplayGradeString bit,		 
		IsDisplayInMarksheet bit,
		IsShowSubjectGrade bit,
		IsIncludeInTotal bit,
		ClassSubjectID int,
		SubjectId int,
		--Maximum decimal(5,2),
		SubjectOrderIndex smallint,
		SubjectGrade NVarchar(50),
		SubjectName NVarchar(150),
		SubjectCode Nvarchar(50),	
		SubjectMinimum decimal(8,2),		
		SubjectMaximum decimal(8,2),
		SubjectObtain  decimal(8,2),
		
		Exam1Name Nvarchar(150),		
		TotalMarks1 decimal(8,2),		
		TotalObtain1 decimal(8,2),
		Percentage1 decimal(8,2),
		RankNumber1 int,
		ResultGrade1 NVarchar(50),
		Percentile1 decimal(8,2),
		ResultStatus1 Nvarchar(20),
		
		SubActivityGrade1 nvarchar(50),
		ActivityGrade1 nvarchar(50),
		
		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),
		
		SubActivityGrade2 nvarchar(50),
		ActivityGrade2 nvarchar(50),
		
		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),
		
		SubActivityGrade3 nvarchar(50),
		ActivityGrade3 nvarchar(50),
		
		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),
		
		SubActivityGrade4 nvarchar(50),
		ActivityGrade4 nvarchar(50),
		
		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),
		
		SubActivityGrade5 nvarchar(50),
		ActivityGrade5 nvarchar(50),
		
		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),
		
		SubActivityGrade6 nvarchar(50),
		ActivityGrade6 nvarchar(50),
		
		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),
		
		--SubActivityGrade7 nvarchar(10),
		
		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),
		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,
		IsDisplayParentName bit,
		FatherName nvarchar(30),
		MotherName nvarchar(30),
		IsShowSubjectMark bit, 
		IsOptionalSubject bit,
		CoScholasticScopeId tinyint,
		IsDisplayPrincipalSign bit,
		IsDisplayTeacherSign bit,
		EmployeeSign varbinary(max),
		
		ActivityName nvarchar(200),
		SubActivityName nvarchar(200),
		SubActivityId int,
		ActivityId Int,
		 SubActivityGrade nvarchar(50),
		 ActivityGrade nvarchar(50),
		SubActivityGradeIndicator nvarchar(50),
		SubActivityDescriptiveIndicator nvarchar(200),
		SubjectActivityOrderIndex Smallint,
		SubActivityOrderIndex smallint,
		ColumnSubjectCount SmallInt,
		MarksheetHeaderA4 varbinary(max),
		IsImageHeader bit,
		Height1 decimal(6,2),
		Height2 decimal(6,2),
		Height3 decimal(6,2),
		Height4 decimal(6,2),
		Height5 decimal(6,2),
		Height6 decimal(6,2),
		Weight1 decimal(6,2),
		Weight2 decimal(6,2),
		Weight3 decimal(6,2),
		Weight4 decimal(6,2),
		Weight5 decimal(6,2),
		Weight6 decimal(6,2),
		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),
		MyActivity1 nvarchar(200),
		MyActivity2 nvarchar(200),
		MyActivity3 nvarchar(200),
		MyActivity4 nvarchar(200),
		MyActivity5 nvarchar(200),
		MyActivity6 nvarchar(200),
		GeneralRemark1 nvarchar(200),
		GeneralRemark2 nvarchar(200),
		GeneralRemark3 nvarchar(200),
		GeneralRemark4 nvarchar(200),
		GeneralRemark5 nvarchar(200),
		GeneralRemark6 nvarchar(200),
		PresentAddress nvarchar(500) ,
		MobileNo nvarchar(50),
		House nvarchar(20),
		 
		AttendanceTerm1 decimal(6, 2) ,
		AttendanceTerm2 decimal(6, 2),
		WorkingDaysTerm1 decimal(6, 2),
		WorkingDaysTerm2 decimal(6, 2),
		BloodGroup nvarchar(10),
		GradeSetIdText nvarchar(50),
		IsDisplayMonthlyAttendanceText nvarchar(20),
		DentalHygiene nvarchar(200),
		VisionLeft nvarchar(50),
		VisionRight nvarchar(50),
		TeacherSignCaption nvarchar(100),
		PrincipalSignCaption nvarchar(100),
		ParentSignCaption nvarchar(100),
		ParentEmail nvarchar(500),
		MyGoal nvarchar(200),
		MyStrength nvarchar(200),
		MyInterestHobby nvarchar(200),
		AreaOfInterest nvarchar(200),
		Responsibility nvarchar(200),
		Achievements nvarchar(200),
		ImprovementArea nvarchar(200),
		ProgressArea nvarchar(200),
		MyActivity nvarchar(200),
		ClassTeacherRemark nvarchar(1000),
		ClassTeacherName Nvarchar(100),
		HouseRemark nvarchar(1000),
		GeneralRemark nvarchar(1000),
		FatherContactNo nvarchar(20),
		MotherContactNo nvarchar(20),
		FatherMail nvarchar(max),
		MotherMail nvarchar(max)
	)	
	
	 --print 'temp created'    	
	INSERT INTO  #TempAllExam 
	(
	AcademicIdText,
	ExamIdText,
	CoScholasticScopeIdText,
	
	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,
	IsDisplayParentName,
	FatherName,
	MotherName,
	IsShowSubjectMark,
	IsOptionalSubject,
	CoScholasticScopeId,
	IsDisplayPrincipalSign,
	IsDisplayTeacherSign,
	EmployeeSign,
	SubActivityGrade,
	ActivityGrade,
	ActivityName,
	SubActivityName,
	SubActivityId,
	ActivityId,
	SubActivityGradeIndicator,
	SubActivityDescriptiveIndicator,
	SubjectActivityOrderIndex,
	SubActivityOrderIndex,
	ColumnSubjectCount,
	MarksheetHeaderA4,
	IsImageHeader,
	PresentAddress,
 	MobileNo,
	House,
	AttendanceTerm1   ,
	AttendanceTerm2  ,
	WorkingDaysTerm1  ,
	WorkingDaysTerm2  ,
	BloodGroup,
	GradeSetIdText,
	IsDisplayMonthlyAttendanceText,
	DentalHygiene,
	VisionLeft,
	VisionRight,
	TeacherSignCaption,
	PrincipalSignCaption,ParentSignCaption,
	ParentEmail,
	MyGoal ,
	MyStrength ,
	MyInterestHobby ,
	AreaOfInterest ,
	Responsibility ,
	Achievements ,
	ImprovementArea ,
	ProgressArea ,
	MyActivity ,
	ClassTeacherRemark ,
	ClassTeacherName ,
	HouseRemark ,
	GeneralRemark ,
	FatherContactNo ,
	MotherContactNo ,
	FatherMail,
	MotherMail 
	)
	
	SELECT 
		Convert(nvarchar(20),A.Id),
		Convert(nvarchar(20),@rExamId),
		Convert(nvarchar(20),EM.CoScholasticScopeId),
		A.Id,
		ISNULL(ESGM.Title,'') AS EXAMNAME,
		StuM.Code AS StudCode,
		StuM.FirstName+' '+StuM.MiddleName+' '+StuM.LastName AS Name,
		A.RollNo,
		R.ResultStatus,
		CM.DisplayTitle AS ClassName,
		DM.DisplayTitle AS Division,
		R.TotalMarks AS TotalMark,
		R.TotalObtain,
		R.Percentage,
		R.RankNumber,
		R.ResultGrade,


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

		ISNULL(EM.Remark1,'') AS Remark1,
		ISNULL(EM.Remark2,'') AS Remark2,
		ISNULL(EM.Remark3,'') AS Remark3,
		EM.DisplayTitle,
		EM.IsRankNo, 
		EM.IsGrade,
		EM.IsPercentile,
		EM.IsPercentage,
		EM.IsSubjectPercentile,
		EM.IsProcessResult,
		EM.IsNegativeMarks,
		EM.IsIncludeCoScholastic,
		EM.IsOnPrePrinted,
		EM.IsDisplayPhoto,
		EM.IsDisplayBirthDate,
		EM.IsLockForEdit,
		EM.IsDisplaySchoolName,			
		EM.IsDisplayAttendance,
		EM.IsDisplayHeightWeight,
		EM.IsResultStatus,
		REPLICATE(',',EM.FooterAdjustment) AS FooterAdjustmentText,
		REPLICATE(',',EM.DetailAdjustment) AS DetailAdjustmentText,
		EM.FooterAdjustment,
		EM.DetailAdjustment,
		ISNULL(R.ResultRemark,'') AS ResultRemark,
		SO.DateOfBirth,
		AD.HeightTerm1,
		AD.WeightTerm1,
		AD.HeightTerm2,
		AD.WeightTerm2,
		AD.HeightAnnual,
		AD.WeightAnnual,
		AD.PresentDaysTerm1,
		AD.PresentDaysTerm2,
		AD.PresentDaysAnnual,
		AD.TotalDaysTerm1,
		AD.TotalDaysTerm2,
		AD.TotalDaysAnnual,
		EM.TermScopeId,
		CASE WHEN EM.IsDisplayPhoto = 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,
	    SAM.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,
		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,
		EI.EmployeeSign,
		SSA.Grade AS SubActivityGrade,
		ISNULL(SAS.Grade,'') AS ActivityGrade,
		SAM.Title AS ActivityName,
		SSAM.Title AS SubActivityName,
		SSA.SubjectSubActivityId AS SubActivityId,
		SAM.Id AS ActivityId,
		SSA.GradeIndicator AS SubActivityGradeIndicator,
		SSA.DescriptiveIndicator AS SubActivityDescriptiveIndicator,
		SAM.OrderIndex AS SubjectActivityOrderIndex,
		SSAM.OrderIndex AS SubActivityOrderIndex,
		CASE WHEN CS.OrderIndex % 2 = 0 THEN 2 
				ELSE 1 END   AS   ColumnSubjectCount,
		(CASE EM.IsDisplayImageHeader WHEN 1 THEN
			OI.CertificateHeaderA4 
			ELSE NULL END)AS  MarksheetHeaderA4,
		ISNULL(EM.IsDisplayImageHeader,0) AS IsImageHeader	,
		ISNULL(SC.PresentStreetONe,'')+' '+ISNULL(SC.PresentStreetTwo,'')+' '+ISNULL(SC.PresentStreetThree,'')+' '+ISNULL(SC.PresentCity,'')+' '+ISNULL(SC.PresentState,'') AS PresentAddress,
		 SC.ParentContactNo,
		ISNULL(HM.Title,'') AS House,
		ISNULL(CCER.AttendanceTerm1,0) AS AttendanceTerm1,
		ISNULL(CCER.AttendanceTerm2,0) AS AttendanceTerm2,
		ISNULL(CCER.WorkingDaysTerm1,0) AS WorkingDaysTerm1,
		ISNULL(CCER.WorkingDaysTerm2,0) AS WorkingDaysTerm2,
		ISNULL(BGM.Title,'') AS BloodGroup,
		CONVERT (nvarchar(50),EM.GradeSetId) AS GradeSetIdText,
		Convert(nvarchar(20),ISNULL(EM.IsDisplayMonthlyAttendance,0)),
		ISNULL(SR.DentalHygiene,'') AS DentalHygiene,
		ISNULL(SR.VisionLeft,'') AS VisionLeft,
		ISNULL(SR.VisionRight,'') AS VisionRight,
		--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,
		ISNULL(EM.TeacherSignCaption,'') AS TeacherSignCaption,
		ISNULL(EM.PrincipalSignCaption,'') AS PrincipalSignCaption,
		ISNULL(ParentSignCaption,'') AS ParentSignCaption,
		SC.ParentEmail As ParentEmail,
		ISNULL(SR.MyGoal,'') AS MyGoal,
		ISNULL(SR.MyStrength,'') AS MyStrength,
		ISNULL(SR.MyInterestHobby,'') AS MyInterestHobby,
		ISNULL(SR.AreaOfInterest,'') AS AreaOfInterest,
		ISNULL(SR.Responsibility,'') AS Responsibility,
		ISNULL(SR.Achievements,'') AS Achievements,
		ISNULL(SR.ImprovementArea,'') As ImprovementArea,
		ISNULL(SR.ProgressArea,'') AS ProgressArea,
		ISNULL(SR.MyActivity,'') AS MyActivity,
		ISNULL(SR.ClassTeacherRemark,'') As ClassTeacherRemark,
		EMP.FirstName + ' ' + EMP.LastName AS ClassTeacherName,
		ISNULL(SR.HouseRemark,'') As HouseRemark,
		ISNULL(SR.GeneralRemark,'') As GeneralRemark,
		SF.FatherContactNo,
		SF.MotherContactNo,
		SF.FatherMail,
		SF.MotherMail
	FROM 
		sAssessment.tCCESubjectSubActivityExamScore SSA
		INNER JOIN sAssessment.tCCESubjectSubActivityMaster SSAM ON SSAM.Id = SSA.SubjectSubActivityId
		INNER JOIN sAssessment.tCCESubjectActivityMaster SAM ON SAM.Id = SSAM.SubjectActivityId
		LEFT JOIN sAssessment.tCCESubjectActivityExamScore SAS ON SAS.SubjectActivityId= SAM.Id AND SSA.AcademicId = SAS.AcademicId AND SSA.ExamId = SAS.ExamId
		INNER JOIN sSetup.tClassSubject CS ON CS.Id=SAM.ClassSubjectId	
		INNER JOIN sAssessment.tExamMaster EM ON EM.Id=SSA.ExamId
		INNER JOIN sAssessment.tExamDetail ED ON EM.Id=ED.ExamId AND ED.ClassSubjectId = SAM.ClassSubjectId
		--INNER JOIN sSetup.tClassSubject CS ON CS.Id=SAM.ClassSubjectId
		INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId					 
    	INNER JOIN sStudent.tAcademic  A ON   SSA.AcademicId = A.Id
		LEFT JOIN sAssessment.tCCEResult CCER    ON  CCER.AcademicId=A.Id
		INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
		INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
		INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
		LEFT JOIN sHrm.tEmployeeMaster EMP ON EMP.Id = DM.InchargeEmployeeId
		LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = Dm.InchargeEmployeeId
		INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.EXAMSUBGROUPID
		LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=StuM.Id
		LEFT JOIN sCommon.tBloodGroupMaster BGM ON BGM.Id=SO.BloodGroupId
		LEFT JOIN sStudent.tAcademicDetail AD ON AD.AcademicId=A.Id
		LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=StuM.Id
		LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = StuM.Id
		LEFT JOIN sAssessment.tOptionalSubject OS ON OS.AcademicId = A.Id AND OS.ClassSubjectId = ED.ClassSubjectId  
		LEFT JOIN sAssessment.tResult R ON R.AcademicId = SSA.AcademicId AND R.ExamId = SSA.ExamId
		LEFT JOIN sAssessment.tResultDetail RD  ON R.Id = RD.ResultId AND ED.ID = RD.ExamDetailId 
		LEFT JOIN sAssessment.tStudentRemark SR ON A.Id = SR.AcademicId AND EM.Id = SR.ExamId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = StuM.OrgId
		LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = OM.Id
		LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId =Stum.ID
		LEFT JOIN sActivity.tHouseMaster HM ON HM.Id=SO.HouseId
		--LEFT JOIN sAcademic.tTeacherSubjectDivision TSD ON TSD.SubjectId=SM.Id AND TSD.DivisionId = A.DivisionId
		--LEFT JOIN sHrm.tEmployeeMaster EMP ON TSD.EmployeeId = EMP.Id
	
	 WHERE
		SSA.ExamId = @rExamId 
		AND ((A.DivisionId =  @rDivisionId) OR (@rDivisionId=0))
		AND ((A.ClassId =  @rClass) OR (@rClass=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 (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.SubExamId = E.SubExamId
	ORDER BY E.ExamOrder,C.ExamOrder
	END
	 
	--ON 
	
	-- Order By ExamOrder ASC
	--WHERE ExamId in (SELECT SUBEXAMID FROM sAssessment.tExamCombine WHERE ExamId  = @rExamId Order By ExamOrder ASC)
	
	DECLARE @lCount int,@query  AS NVARCHAR(MAX),@lSubExamId int,@lCount1 int  
	Select @lCount = MAX(Id) from #tempcombineExam	
	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
					
					 IsPresent' + convert(nvarchar(15),@lCount)+'=RD.IsPresent,					
					 SubjectGrade' + convert(nvarchar(15),@lCount)+ '=RD.SubjectGrade,
					 Exam' + convert(nvarchar(15),@lCount)+ 'Name=ESGM.Title,
					 Height' + convert(nvarchar(15),@lCount)+ '=SR.StudentHeight,
					 Weight' + convert(nvarchar(15),@lCount)+ '=SR.StudentWeight,				
					 TotalDays'+convert(nvarchar(15),@lCount)+'=SR.TotalDays,
					 PresentDays'+convert(nvarchar(15),@lCount)+'=SR.PresentDays,
					 MyActivity'+convert(nvarchar(15),@lCount)+'=SR.MyActivity,
					 GeneralRemark'+convert(nvarchar(15),@lCount)+'=SR.GeneralRemark 
					 									
					 From
						 
						 sAssessment.tResult R 
						INNER JOIN  sAssessment.tResultDetail RD ON RD.ResultId = R.Id						
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId	
						LEFT JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND T.AcademicId = SR.AcademicId 							
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
						
	
	 execute(@query)
 
	 set @query ='update T SET
					
					 
					 SubActivityGrade' + convert(nvarchar(15),@lCount)+ '=SSA.Grade	
					 						
					 From
						sAssessment.tCCESubjectSubActivityExamScore SSA				
						inner JOIN 	#TempAllExam  T ON T.SubActivityId = SSA.SubjectSubActivityId And T.AcademicId = SSA.AcademicId	 					
						WHERE SSA.ExamId =' + convert(nvarchar(15), @lSubExamId)  
						
	
 --PRINT(@QUERY)	
   EXECUTE(@query)
 
  set @query ='update T SET
					
					  ActivityGrade' + convert(nvarchar(15),@lCount)+ '=SAS.Grade	
					 						
					 From
						sAssessment.tCCESubjectActivityExamScore SAS				
						inner JOIN 	#TempAllExam  T ON T.ActivityId = SAS.SubjectActivityId And T.AcademicId = SAS.AcademicId	 					
						WHERE SAS.ExamId =' + convert(nvarchar(15), @lSubExamId)  
						
	
 --PRINT(@QUERY)	
   EXECUTE(@query)
	-- set @query ='update T SET
					
	--				 Height' + convert(nvarchar(15),@lCount)+ '=SR.StudentHeight,
	--				 Weight' + convert(nvarchar(15),@lCount)+ '=SR.StudentWeight,				
	--				 TotalDays'+convert(nvarchar(15),@lCount)+'=SR.TotalDays,
	--				 PresentDays'+convert(nvarchar(15),@lCount)+'=SR.PresentDays,
	--				 MyActivity'+convert(nvarchar(15),@lCount)+'=SR.MyActivity,
	--				 GeneralRemark'+convert(nvarchar(15),@lCount)+'=SR.GeneralRemark
	--				 From
	--					sAssessment.tCCESubjectSubActivityExamScore SSA
						
	--					inner JOIN sAssessment.tCCESubjectSubActivityMaster SSAM ON SSAM.Id = SSA.SubjectSubActivityId
	--					inner JOIN sAssessment.tCCESubjectActivityMaster SAM ON SAM.Id = SSAM.SubjectActivityId
	--					INNER JOIN sAssessment.tExamMaster EM ON EM.Id=SSA.ExamId
	--					inner JOIN 	#TempAllExam  T ON T.SubActivityId = SSA.SubjectSubActivityId And T.AcademicId = SSA.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.Title,
					ExamMaximum' + convert(nvarchar(15),@lCount)+'=EM.ExamMaximum
					 From						
						sAssessment.tResult R						
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON  T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
						
	execute(@query)*/
		
		
	set @lCount = @lCount -1
	end
	SELECT @rBuilder1 , T.*
	FROM #TempAllExam T
	
	
		
	drop table #tempcombineExam
	Drop table #TempAllExam
	--Select 
	-- '' As AcademicIdText,
	--	'' As ExamIdText,
	--	'' As CoScholasticScopeIdText ,
		
	--	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 ,
		
	--	--MaximumMark1 decimal(8,2),		
	--	'' As SubjectGrade1 ,
	--	--Obtain1 decimal(8,2),
	--	--ExamMaximum1 decimal(8,2),
	--	0 As IsPresent1,
						
	--	0 As MaximumMark2 ,	
	--	'' As SubjectGrade2 ,
	--	0 As Obtain2 ,
	--	0 As ExamMaximum2 ,
	--	0 As IsPresent2,
				
	--	0 As MaximumMark3 ,
	--	'' As SubjectGrade3 ,
	--	0 As Obtain3 ,
	--	0 As ExamMaximum3 ,
	--	0 As IsPresent3 ,		
		
	--	0 As MaximumMark4 ,	
	--	'' As SubjectGrade4 ,
	--	0 As Obtain4 ,
	--	0 As ExamMaximum4 ,
	--	0 As IsPresent4 ,	
				
	--	0 As MaximumMark5 ,		
	--	'' As SubjectGrade5 ,
	--	0 As Obtain5 ,
	--	0 As ExamMaximum5 ,
	--	0 As IsPresent5 ,	
				
	--	0 As MaximumMark6 ,		
	--	'' As SubjectGrade6,
	--	0 As Obtain6 ,
	--	0 As ExamMaximum6 ,
	--	0 As IsPresent6 ,	
		
	--	0 As MaximumMark7 ,		
	--	'' As SubjectGrade7,
	--	0 As Obtain7 ,
	--	0 As ExamMaximum7 ,
	--	0 As IsPresent7 ,	
	
	--	0 As MaximumMark8 ,	
	--	'' As SubjectGrade8,
	--	0 As Obtain8 ,
	--	0 As ExamMaximum8 ,
	--	0 As IsPresent8 ,	
		
	--	'' As SubjectGradeTerm1,
	--	'' As SubjectGradeTerm2 ,
	--	0 As IsMarksInDecimal ,
	--	0 As column_visible ,
	--	--Obtain decimal(5,2),
	--	0 As Percentile,
	--	--ClassSubject nvarchar(100),
	--	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 TotalMarkTerm1 ,
	--	 0 As TotalObtainTerm1 ,
	--	0 As PercentageTerm1,
	--	0 As RankNumberTerm1 ,
	--	'' As ResultGradeTerm1,
	--	0 As PercentileTerm1 ,
	--	'' As ResultStatusTerm1,		   
	--	0 As TotalMarkTerm2 ,
	--	0 As TotalObtainTerm2 ,
	--	0 As PercentageTerm2 ,
	--	0 As RankNumberTerm2 ,
	--	'' As ResultGradeTerm2 ,
	--	0 As PercentileTerm2 ,
	--	'' As ResultStatusTerm2 , 
	--	0 As TermScopeId ,		 
	--	'' 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 Exam1Name ,		
	--	0 As TotalMarks1 ,		
	--	0 As TotalObtain1 ,
	--	0 As Percentage1 ,
	--	0 As RankNumber1 ,
	--	'' As ResultGrade1,
	--	0 As Percentile1 ,
	--	'' As ResultStatus1 ,
		
	--	'' As SubActivityGrade1,
	--	'' As ActivityGrade1,
		
	--	'' As Exam2Name ,	
	--	0 As TotalMarks2 ,
	--	0 As TotalObtain2 ,
	--	0 As Percentage2 ,
	--	0 As RankNumber2 ,
	--	'' As ResultGrade2 ,
	--	0 As Percentile2 ,
	--	'' As ResultStatus2 ,
		
	--	'' As SubActivityGrade2,
	--	'' As ActivityGrade2 ,
		
	--	'' As Exam3Name ,	
	--	0 As TotalMarks3 ,
	--	0 As TotalObtain3 ,
	--	0 As Percentage3 ,
	--	0 As RankNumber3 ,
	--	'' As ResultGrade3 ,
	--	0 As Percentile3 ,		
	--	'' As ResultStatus3,
		
	--	'' As SubActivityGrade3 ,
	--	'' As ActivityGrade3 ,
		
	--	'' As Exam4Name ,	
	--	0 As TotalMarks4 ,
	--	0 As TotalObtain4,
	--	0 As Percentage4 ,
	--	0 As RankNumber4 ,
	--	'' As ResultGrade4 ,
	--	0 As Percentile4 ,
	--	'' As ResultStatus4 ,
		
	--	'' As SubActivityGrade4,
	--	'' As ActivityGrade4 ,
		
	--	'' As Exam5Name ,		
	--	0 As TotalMarks5 ,
	--	0 As TotalObtain5 ,
	--	0 As Percentage5 ,
	--	0 As RankNumber5 ,
	--	'' As ResultGrade5 ,
	--	0 As Percentile5 ,
	--	'' As ResultStatus5 ,
		
	--	'' As SubActivityGrade5 ,
	--	'' As ActivityGrade5 ,
		
	--	'' As Exam6Name ,	
	--	0 As TotalMarks6 ,
	--	0 As TotalObtain6,
	--	0 As Percentage6 ,
	--	0 As RankNumber6 ,
	--	'' As ResultGrade6 ,
	--	0 As Percentile6 ,
	--	'' As ResultStatus6 ,
		
	--	'' As SubActivityGrade6 ,
	--	'' As ActivityGrade6 ,
		
	--	'' As Exam7Name ,		
	--	0 As TotalMarks7 ,
	--	0 As TotalObtain7,
	--	0 As Percentage7 ,
	--	0 As RankNumber7 ,
	--	'' As ResultGrade7,
	--	0 As Percentile7 ,
	--	'' As ResultStatus7 ,
		
	--	--SubActivityGrade7 nvarchar(10),
		
	--	'' As Exam8Name,
	--	0 As TotalMarks8 ,
	--	0 As TotalObtain8 ,
	--	0 As Percentage8,
	--	0 As RankNumber8 ,
	--	'' As ResultGrade8 ,
	--	0 As Percentile8,
	--	'' As ResultStatus8,
	--	'' As ResultRemark1 ,
	--	'' As ResultRemark2,
	--	0 As TotalDays ,
	--	0 As PresentDays ,
	--	0 As StudentHeight,
	--	0 As StudentWeight ,
	--	'' As ExamSeatNo ,
	--0 As ExamId ,
	--	0 As IsDisplayParentName ,
	--	'' As FatherName ,
	--	'' As MotherName ,
	--	0 As IsShowSubjectMark , 
	--	0 As IsOptionalSubject ,
	--	0 As CoScholasticScopeId ,
	--	0 As IsDisplayPrincipalSign ,
	--	0 As IsDisplayTeacherSign ,
	--	'' As EmployeeSign,
		
	--	'' As ActivityName ,
	--	'' As SubActivityName ,
	--	0 As SubActivityId ,
	--	0 As ActivityId ,
	--	 '' As SubActivityGrade,
	--	 '' As ActivityGrade ,
	--	'' As SubActivityGradeIndicator ,
	--	'' As SubActivityDescriptiveIndicator,
	--	0 As SubjectActivityOrderIndex ,
	--	0 As SubActivityOrderIndex ,
	--	0 As ColumnSubjectCount ,
	--	'' As MarksheetHeaderA4 ,
	--	0 As IsImageHeader ,
	--	0 As Height1 ,
	--	0 As Height2 ,
	--	0 As Height3,
	--	0 As Height4 ,
	--	0 As Height5,
	--	0 As Height6 ,
	--	0 As Weight1 ,
	--	0 As Weight2 ,
	--	0 As Weight3 ,
	--	0 As Weight4,
	--	0 As Weight5 ,
	--	0 As Weight6 ,
	--	0 As TotalDays1 ,
	--	0 As PresentDays1 ,
	--	0 As TotalDays2 ,
	--	0 As PresentDays2 ,
	--	0 As TotalDays3 ,
	--	0 As PresentDays3 ,
	--	0 As TotalDays4 ,
	--	0 As PresentDays4 ,
	--	0 As TotalDays5 ,
	--	0 As PresentDays5 ,
	--	0 As TotalDays6 ,
	--	0 As PresentDays6 ,
	--	'' As MyActivity1,
	--	'' As MyActivity2 ,
	--	'' As MyActivity3,
	--	'' As MyActivity4 ,
	--	'' As MyActivity5,
	--	'' As MyActivity6,
	--	'' As GeneralRemark1,
	--	'' As GeneralRemark2 ,
	--	'' As GeneralRemark3 ,
	--	'' As GeneralRemark4,
	--	'' As GeneralRemark5,
	--	'' As GeneralRemark6,
	--	'' As PresentAddress ,
	--	'' As  MobileNo,
	--	'' As House ,
		 
	--	0 As AttendanceTerm1  ,
	--	0 As AttendanceTerm2 ,
	--	0 As WorkingDaysTerm1 ,
	--	0 As WorkingDaysTerm2 ,
	--	  '' As BloodGroup ,
	--	  '' As GradeSetIdText ,
	--	  '' As IsDisplayMonthlyAttendanceText ,
	--	  '' As DentalHygiene ,
	--	'' As VisionLeft ,
	--	'' As VisionRight ,
	--	'' As TeacherSignCaption ,
	--	'' As PrincipalSignCaption ,
	--	'' As ParentSignCaption ,
	--	'' As ParentEmail

	END

--end
/*
 MaximumMark' + convert(nvarchar(15),@lCount)+ '=ED.Maximum,
Obtain' + convert(nvarchar(15),@lCount)+'=RD.Obtain,
					
					--sAssessment.tCCESubjectActivityMaster SAM 	
	--		INNER JOIN sAssessment.tCCESubjectSubActivityMaster SSAM ON SSAM.SubjectActivityId=SAM.Id  
	--		INNER JOIN sAssessment.vCCEExamClassSubject CS ON CS.ClassSubjectId=SAM.ClassSubjectId
	--		INNER JOIN sSetup.tClassMaster CMM ON CMM.Id=CS.ClassId 
	--		 INNER JOIN sStudent.vStudentAcademic  A ON   A.ClassId = CS.ClassId AND  A.StatusId = 1
	--		 LEFT JOIN sAssessment.tCCESubjectSubActivityExamScore SSA ON SSA.AcademicId = A.AcademicId AND SSA.SubjectSubActivityId= SSAM.Id  	
			  */
GO
PRINT N'Altering [sAssessment].[pRptResultSheetUniqFormat]...';


GO

ALTER PROCEDURE [sAssessment].[pRptResultSheetUniqFormat]
	 
	 @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.tTempAllExam
 --drop table sAssessment.tTempAllExam
 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

--#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,		
		 
		 
		SubjectGradeTerm1 NVarchar(50),
		SubjectGradeTerm2 NVarchar(50),
		SubjectGradeTerm3 NVarchar(50),
		IsMarksInDecimal bit,
		column_visible bit,
		--Obtain decimal(5,2),
		Percentile decimal(5,2),
		--ClassSubject nvarchar(100),
		ResultDetailId bigint,
		ResultId bigint,	
		Remark1 nvarchar(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), 
		
		TermScopeId tinyint,		 
		StudentPhoto varbinary(max),
		GradeString nvarchar(1000),
		IsDisplayGradeString bit,		 
		IsDisplayInMarksheet bit,
		IsShowSubjectGrade bit,
		IsIncludeInTotal bit,
		ClassSubjectID int,
		SubjectId int,
		--Maximum decimal(5,2),
		SubjectOrderIndex smallint,
		SubjectGrade NVarchar(50),
		SubjectName NVarchar(150),
		SubjectCode Nvarchar(50),	
		SubjectMinimum decimal(8,2),		
		SubjectMaximum decimal(8,2),
		SubjectObtain  decimal(8,2),
		
		Exam1Name Nvarchar(150),		
		TotalMarks1 decimal(8,2),		
		TotalObtain1 decimal(8,2),
		Percentage1 decimal(8,2),
		RankNumber1 int,
		ResultGrade1 NVarchar(50),
		Percentile1 decimal(8,2),
		ResultStatus1 Nvarchar(20),
		
		Exam2Name nvarchar(150),	
		TotalMarks2 decimal(8,2),
		TotalObtain2 decimal(8,2),
		Percentage2 decimal(8,2),
		RankNumber2 int,
		ResultGrade2 NVarchar(50),
		Percentile2 decimal(8,2),
		ResultStatus2 Nvarchar(20),
		
		Exam3Name nvarchar(150),	
		TotalMarks3 decimal(8,2),
		TotalObtain3 decimal(8,2),
		Percentage3 decimal(8,2),
		RankNumber3 int,
		ResultGrade3 NVarchar(50),
		Percentile3 decimal(8,2),		
		ResultStatus3 Nvarchar(20),
		
		Exam4Name nvarchar(150),	
		TotalMarks4 decimal(8,2),
		TotalObtain4 decimal(8,2),
		Percentage4 decimal(8,2),
		RankNumber4 int,
		ResultGrade4 NVarchar(50),
		Percentile4 decimal(8,2),
		ResultStatus4 Nvarchar(20),
		
		Exam5Name nvarchar(150),		
		TotalMarks5 decimal(8,2),
		TotalObtain5 decimal(8,2),
		Percentage5 decimal(8,2),
		RankNumber5 int,
		ResultGrade5 NVarchar(50),
		Percentile5 decimal(8,2),
		ResultStatus5 Nvarchar(20),
		
		Exam6Name nvarchar(150),	
		TotalMarks6 decimal(8,2),
		TotalObtain6 decimal(8,2),
		Percentage6 decimal(8,2),
		RankNumber6 int,
		ResultGrade6 NVarchar(50),
		Percentile6 decimal(8,2),
		ResultStatus6 Nvarchar(20),
		
		Exam7Name nvarchar(150),		
		TotalMarks7 decimal(8,2),
		TotalObtain7 decimal(8,2),
		Percentage7 decimal(8,2),
		RankNumber7 int,
		ResultGrade7 NVarchar(50),
		Percentile7 decimal(8,2),
		ResultStatus7 Nvarchar(20),
		
		Exam8Name nvarchar(150),
		TotalMarks8 decimal(8,2),
		TotalObtain8 decimal(8,2),
		Percentage8 decimal(8,2),
		RankNumber8 int,
		ResultGrade8 NVarchar(50),
		Percentile8 decimal(8,2),
		ResultStatus8 Nvarchar(20),
		
		
		Exam9Name nvarchar(150),	
		TotalMarks9 decimal(8,2),
		TotalObtain9 decimal(8,2),
		Percentage9 decimal(8,2),
		RankNumber9 int,
		ResultGrade9 NVarchar(50),
		Percentile9 decimal(8,2),
		ResultStatus9 Nvarchar(20),
		
		Exam10Name nvarchar(150),	
		TotalMarks10 decimal(8,2),
		TotalObtain10 decimal(8,2),
		Percentage10 decimal(8,2),
		RankNumber10 int,
		ResultGrade10 NVarchar(50),
		Percentile10 decimal(8,2),
		ResultStatus10 Nvarchar(20),
		
		Exam11Name nvarchar(150),	
		TotalMarks11 decimal(8,2),
		TotalObtain11 decimal(8,2),
		Percentage11 decimal(8,2),
		RankNumber11 int,
		ResultGrade11 NVarchar(50),
		Percentile11 decimal(8,2),
		ResultStatus11 Nvarchar(20),
		
		Exam12Name nvarchar(150),	
		TotalMarks12 decimal(8,2),
		TotalObtain12 decimal(8,2),
		Percentage12 decimal(8,2),
		RankNumber12 int,
		ResultGrade12 NVarchar(50),
		Percentile12 decimal(8,2),
		ResultStatus12 Nvarchar(20),
		
		ResultRemark1 nvarchar(200),
		ResultRemark2 nvarchar(200),
		
		TotalDays 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(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),
		SubjectMaxTerm1 decimal(8,2),
		SubjectMaxTerm2 decimal(8,2),
		SubjectMaxTerm3 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),
		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(20),
		HighestDivisionMark decimal(5, 2),
		HighestDivisionGrade nvarchar(50),
		StreamTitle nvarchar(50),
		ResultSheetAdditionalTitle nvarchar(100),
		SchoolNameLabel nvarchar(200),
		MediumLabel nvarchar(100),
		NameLabel nvarchar(200),
		CodeLabel nvarchar(100),
		SUIDLabel nvarchar(100),
		ClassLabel nvarchar(100),
		BirthDateLabel nvarchar(100),
		RollNoLabel nvarchar(100),
		FatherNameLabel nvarchar(100),
		MotherNameLabel nvarchar(100),
		TotalWorkingDaysLabel nvarchar(100),
		TotalPresentDaysLabel nvarchar(100),
		HeightLabel nvarchar(100),
		WeightLabel nvarchar(100),
		SubjectLabel nvarchar(100),
		MaxMarksLabel nvarchar(100),
		TotalLabel nvarchar(100),
		GradeLabel nvarchar(100),
		GrandTotalLabel nvarchar(100),
		ResultStatusLabel nvarchar(100),
		RankNoLabel nvarchar(100),
		PercentileLabel nvarchar(100),
		PercentageLabel nvarchar(100),
		OverallGradeLabel nvarchar(100),
		DisplayAttendanceId int,
		ReportHeaderId int,
		StudentImage varbinary(max)
		
	)	
	 --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,
	ResultSheetAdditionalTitle,
	SchoolNameLabel,
	MediumLabel,
	NameLabel,
	CodeLabel,
	SUIDLabel,
	ClassLabel,
	BirthDateLabel,
	RollNoLabel,
	FatherNameLabel,
	MotherNameLabel,
	TotalWorkingDaysLabel,
	TotalPresentDaysLabel,
	HeightLabel,
	WeightLabel,
	SubjectLabel,
	MaxMarksLabel,
	TotalLabel,
	GradeLabel,
	GrandTotalLabel,
	ResultStatusLabel,
	RankNoLabel,
	PercentileLabel,
	PercentageLabel,
	OverallGradeLabel,
	DisplayAttendanceId,
	ReportHeaderId,
	StudentImage
	)
	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(EM.ResultSheetAdditionalTitle,'') AS ResultSheetAdditionalTitle,
		ISNULL(ALS.SchoolNameLabel,'')AS SchoolNameLabel,
		ISNULL(ALS.MediumLabel,'') AS MediumLabel,
		ISNULL(ALS.NameLabel,'') AS NameLabel,
		ISNULL(ALS.CodeLabel,'') AS CodeLabel,
		ISNULL(ALS.SUIDLabel,'') AS SUIDLabel,
		ISNULL(ALS.ClassLabel,'') AS ClassLabel,
		ISNULL(ALS.BirthDateLabel,'') AS BirthDateLabel,
		ISNULL(ALS.RollNoLabel,'') AS RollNoLabel,
		ISNULL(ALS.FatherNameLabel,'') AS FatherNameLabel,
		ISNULL(ALS.MotherNameLabel,'') AS MotherNameLabel,
		ISNULL(ALS.TotalWorkingDaysLabel,'')AS TotalWorkingDaysLabel,
		ISNULL(ALS.TotalPresentDaysLabel,'') AS TotalPresentDaysLabel,
		ISNULL(ALS.HeightLabel,'') AS HeightLabel,
		ISNULL(ALS.WeightLabel,'') AS WeightLabel,
		ISNULL(ALS.SubjectLabel,'') AS SubjectLabel,
		ISNULL(ALS.MaxMarksLabel,'') AS MaxMarksLabel,
		ISNULL(ALS.TotalLabel,'') AS TotalLabel,
		ISNULL(ALS.GradeLabel,'') AS GradeLabel,
		ISNULl(ALS.GrandTotalLabel,'') AS GrandTotalLabel,
		ISNULl(ALS.ResultStatusLabel,'') AS ResultStatusLabel,
		ISNULL(ALS.RankNoLabel,'') AS RankNoLabel,
		ISNULL(ALS.PercentileLabel,'') AS PercentileLabel,
		ISNULl(ALS.PercentageLabel,'') AS PercentageLabel,
		ISNULL(ALS.OverallGradeLabel,'') AS OverallGradeLabel,
		ISNULL(EM.DisplayAttendanceId,0) AS DisplayAttendanceId,
		ISNULL(EM.ReportHeaderId,0) AS ReportHeaderId,
		(CASE EM.IsDisplayPhoto WHEN 1 THEN
		SI.StudentPhoto
		ELSE NULL END)AS StudentImage
		--('~/Content/' + A.OrgId + A.StudentId + '.jpg')AS StudentImage
		--'~/Content/9911/9911000000299.jpg' AS StudentImage
				
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.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
	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 sAssessment.tAssessmentLabelSetup ALS ON ALS.OrgId = OM.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.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  ISNULL(EMP.IsOtherUser,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 ((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,	
					 				
					 SubjectGrade' + convert(nvarchar(15),@lCount)+ '=RD.SubjectGrade,
					 TotalDays'+convert(nvarchar(15),@lCount)+'=SR.TotalDays,
					 PresentDays'+convert(nvarchar(15),@lCount)+'=SR.PresentDays										
					 From
						sAssessment.tResultDetail RD
						INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId	
						LEFT JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND T.AcademicId = SR.AcademicId 									
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
						
--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)
		
		
	set @lCount = @lCount -1
	end
	

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

 
	END
	--SELECT @rBuilder1 AS Builder1,@rBuilder2 AS Builder2, T.* FROM sAssessment.tTempAllExam T
	
--end
GO
PRINT N'Altering [sAssessment].[pRptResultWithSubjectAnalysisBatchwise]...';


GO


ALTER PROCEDURE [sAssessment].[pRptResultWithSubjectAnalysisBatchwise]
	 
   	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rSubjectId int=0,
	 --@rBatchId int,
	 @rClassId int,
	 @rDivisionId int,
	 --@rExamId int,
     --@rExamSubGroupId1 int=0,
     --@rExamSubGroupId2 int=0,
	 @rCode nvarchar(20),
	 @rFromRollNo int =0,
	 @rToRollNo int =0,
	 @rFromRank int=0,
	 @rToRank int=0,
	 @rGrade nvarchar(20)='',
	 @rStatusId int = 0,
	 @rFromPercentage decimal(5,2)=0,
	 @rToPercentage decimal(5,2)=0,
	 @rResultStatus nvarchar(20)='',
	 @rDepartmentId int=0,
	 @rExamId1 int ,
	 @rExamId2 int ,
	 @rBatchId1 int,
	 @rBatchId2 int,
	 @rClassStatusId int=0 ,
	 @rIsDisplayAvgTotal bit=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			
BEGIN 
 
	BEGIN
	
	CREATE TABLE #Temp_StudentId (StudentId bigint);
	INSERT INTO #Temp_StudentId
	SELECT A1.StudentId From sStudent.tAcademic A1 
	INNER JOIN
	sStudent.tAcademic A2 ON A1.StudentId = A2.StudentId 
	INNER JOIN sStudent.tStudentMaster SM ON SM.Id = A1.StudentId
	WHERE A1.BatchId =  @rBatchId1 AND A2.BatchId = @rBatchId2
	AND (A1.ClassId=@rClassId OR @rClassId=0) 
	AND (A1.DivisionId=@rDivisionId OR @rDivisionId=0)
	AND ((A1.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
	AND ((A1.RollNo <= @rToRollNo) OR (@rToRollNo=0))
	AND ((SM.Code=@rCode) OR (@rCode=''))
	AND SM.StatusId = 1
	AND ((A1.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))
	
	
CREATE TABLE #Temp_Academic (tempAcademicId bigint);
INSERT INTO #Temp_Academic 
SELECT  A.Id As tempAcademicId FROM sAssessment.tResult R 
		INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId 
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.batchId
		LEFT JOIN sStudent.tStudentMaster SM ON SM.Id = A.StudentId
		WHERE BM.Id = @rBatchId2 AND R.ExamId =@rExamId2
		AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))
		  
	--SELECT * FROM #temp
	--RETURN 	
		
	SELECT 
			@rIsDisplayAvgTotal AS IsDisplayAvgTotal,
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			EM.Id AS ExamId,
			ESGM.Title AS Exam,
			BM.Id As BatchId,
			BM.Title As BatchName,
			StuM.Code,
			[sStudent].[fStudentNameGet](StuM.FirstName , StuM.MiddleName, StuM.LastName,OM.StudentNameFormatId ) AS Name,
			A.RollNo,
			R.AcademicId,
			RD.Obtain,
			R.ResultStatus,
			CM.DisplayTitle AS Class,
			Cm.Id AS ClassId,
			DM.DisplayTitle AS Division,
			DM.Id AS DivisionId,
			DM.OrderIndex AS DivisinOrderIndex,
			R.TotalMarks,
			R.TotalObtain,
			R.Percentage,
			R.RankNumber,
			R.ResultGrade,
			SM.Title AS ClassSubject,
			RD.Id AS ResultDetailId,
			R.Id AS ResultId,
			CS.Id AS SubjectId,
			ED.Maximum,
			RD.SubjectGrade, 	
			EM.IsMarksInDecimal,
			--SM.OrderIndex AS SubjectCode,
			SM.Code AS SubjectCode,
			ED.DisplayOrder AS SubjectOrderIndex,
			CM.OrderIndex AS ClassOrderIndex,
			RD.IsPresent,
			EM.IsGrade,
			EM.IsPercentage,
			EM.IsResultStatus,
			EM.IsRankNo ,
			ED.Minimum,
			RD.GraceMark,
			EM.DecimalFormat,
			CS.IsOptional,
			ISNULL(SR.PresentDays,0)AS PresentDays,
			ISNULL(SR.TotalDays,0)AS TotalDays,
			(CASE WHEN @rIsDisplayAvgTotal=1 THEN ROUND(((RD.Obtain*100)/ED.Maximum),0) ELSE RD.Obtain END)As AvgTotal
			
			--RD.SubjectGrade AS TermSubjectGrade,
			--RD.SubjectGrade AS SubjectGrade
			--1 As ExamNo
	FROM 
			sAssessment.tResultDetail RD
			INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
			INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
			INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId	
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId		
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId					 
			INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
			INNER JOIN #Temp_StudentId TEMP2 ON TEMP2.StudentId = A.StudentId
			INNER JOIN sSetup.tBatchMaster BM ON A.BatchId = BM.Id 
			LEFT JOIN sAssessment.tStudentRemark SR ON SR.AcademicId = A.Id AND SR.ExamId=EM.Id
			INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
			INNER JOIN sSetup.tOrganizationMaster OM ON StuM.OrgId = OM.Id
			
	WHERE 
			
		EM.BatchId = @rBatchId1
		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 (@rExamSubGroupId1 = 0))		
		AND ((EM.Id=@rExamId1 )	OR (@rExamId1 = 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 = @rBatchId1
		--AND BM.Id = @rBatchId1
		AND R.ExamId = @rExamId1
		 AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))

UNION 
	
		SELECT 
			@rIsDisplayAvgTotal AS IsDisplayAvgTotal,
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			EM.Id AS ExamId,
			ESGM.Title AS Exam,
			BM.Id As BatchId,
			BM.Title As BatchName,
			StuM.Code,
			[sStudent].[fStudentNameGet](StuM.FirstName , StuM.MiddleName, StuM.LastName,OM.StudentNameFormatId ) AS Name,
			A2.RollNo,
			--temp.tempAcademicId,
			A2.Id AS AcademicId,
			RD.Obtain,
			R.ResultStatus,
			CM2.DisplayTitle AS Class,
			Cm2.Id AS ClassId,
			DM2.DisplayTitle AS Division,
			DM2.Id AS DivisionId,
			DM2.OrderIndex AS DivisinOrderIndex,
			R.TotalMarks,
			R.TotalObtain,
			R.Percentage,
			R.RankNumber,
			R.ResultGrade,
			SM.Title AS ClassSubject,
			RD.Id AS ResultDetailId,
			R.Id AS ResultId,
			CS.Id AS SubjectId,
			ED.Maximum,
			RD.SubjectGrade, 
			
			EM.IsMarksInDecimal,
			--SM.OrderIndex AS SubjectCode,
			SM.Code AS SubjectCode,
			ED.DisplayOrder AS SubjectOrderIndex,
			CM2.OrderIndex AS ClassOrderIndex,
			RD.IsPresent,
			EM.IsGrade,
			EM.IsPercentage,
			EM.IsResultStatus,
			EM.IsRankNo ,
			ED.Minimum,
			RD.GraceMark,
			EM.DecimalFormat,
			CS.IsOptional,
			ISNULL(SR.PresentDays,0)AS PresentDays,
			ISNULL(SR.TotalDays,0)AS TotalDays,
			(CASE WHEN @rIsDisplayAvgTotal=1 THEN ROUND(((RD.Obtain*100)/ED.Maximum),0) ELSE RD.Obtain END)As AvgTotal

			--2 As ExamNo
	FROM 
			sAssessment.tResultDetail RD
			INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
			INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
			INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId	
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId		
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId					 
			INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
			INNER JOIN #Temp_Academic temp ON temp.tempAcademicId= A.Id  
			INNER JOIN #Temp_StudentId TEMP2 ON TEMP2.StudentId = A.StudentId
			INNER JOIN sSetup.tBatchMaster BM ON A.BatchId = BM.Id 
			LEFT JOIN sAssessment.tStudentRemark SR ON SR.AcademicId = A.Id AND SR.ExamId=EM.Id
			INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
			INNER JOIN sSetup.tOrganizationMaster OM ON StuM.OrgId = OM.Id
			INNER JOIN sStudent.tAcademic A2 ON A2.StudentId = TEMP2.StudentId AND A2.BatchId = @rBatchId1
			INNER JOIN sSetup.tClassMaster CM2 ON CM2.Id=A2.ClassId
			INNER JOIN sSetup.tDivisionMaster DM2 ON DM2.Id=A2.DivisionId
	WHERE 
			
		EM.BatchId = @rBatchId2
		--AND (A.ClassId=@rClassId OR @rClassId=0)  
		--AND (A.ClassId=temp.tempClassId )
		AND ((SM.Id=@rSubjectId) OR (RD.ExamDetailId=@rSubjectId) OR (@rSubjectId=0))
		--AND (A.DivisionId=@rDivisionId OR @rDivisionId=0)
		--AND (A.DivisionId=temp.tempDivisionId )
		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 = @rExamSubGroupId2) OR (@rExamSubGroupId2 = 0))		
		AND ((EM.Id=@rExamId2 )	OR (@rExamId2 = 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 = @rBatchId2 ))
		--AND ((BM.Id = @rBatchId2))
		AND R.ExamId = @rExamId2
		AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))
		order by A.RollNo,ClassOrderIndex
	--	SELECT * FROM #temp
	--RETURN 
		END
		DROP Table #Temp_Academic
		DROP Table #Temp_StudentId
		
		----For Report Dataset
		--SELECT 
		--	@rBuilder1 AS Builder1,
		--	@rBuilder2 AS Builder2,
		--	EM.DisplayTitle AS Exam,
		--	EM.Id AS ExamId,
		--	StuM.Code,
		--	[sStudent].[fStudentNameGet](StuM.FirstName , StuM.MiddleName, StuM.LastName,OM.StudentNameFormatId ) AS Name,
		--	A.RollNo,
		--	--temp.tempAcademicId,
		--	R.AcademicId,
		--	RD.Obtain,
		--	R.ResultStatus,
		--	CM.DisplayTitle AS Class,
		--	Cm.Id AS ClassId,
		--	DM.DisplayTitle AS Division,
		--	DM.Id AS DivisionId,
		--	DM.OrderIndex AS DivisinOrderIndex,
		--	R.TotalMarks,
		--	R.TotalObtain,
		--	R.Percentage,
		--	R.RankNumber,
		--	R.ResultGrade,
		--	SM.Title AS ClassSubject,
		--	RD.Id AS ResultDetailId,
		--	R.Id AS ResultId,
		--	CS.Id AS SubjectId,
		--	ED.Maximum,
		--	RD.SubjectGrade, 
			
		--	EM.IsMarksInDecimal,
		--	--SM.OrderIndex AS SubjectCode,
		--	SM.Code AS SubjectCode,
		--	ED.DisplayOrder AS SubjectOrderIndex,
		--	CM.OrderIndex AS ClassOrderIndex,
		--	RD.IsPresent,
		--	EM.IsGrade,
		--	EM.IsPercentage,
		--	EM.IsResultStatus,
		--	EM.IsRankNo ,
		--	ED.Minimum,
		--	RD.GraceMark,
		--	EM.DecimalFormat,
		--	CS.IsOptional,
		--	SR.PresentDays,
		--	SR.TotalDays,
		--	BM.Id As BatchId,
		--	BM.Title As BatchName
		--	FROM
		--	sAssessment.tResultDetail RD
		--	INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
		--	INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
		--	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId	
		--	INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId		
		--	INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
		--	INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId					 
		--	INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
		--	INNER JOIN sSetup.tBatchMaster BM ON A.BatchId = BM.Id 
		--	LEFT JOIN sAssessment.tStudentRemark SR ON SR.AcademicId = A.Id
		--	INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
		--	INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
		--	INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
		--	INNER JOIN sSetup.tOrganizationMaster OM ON StuM.OrgId = OM.Id
			


			--SELECT 
			--0 AS IsDisplayAvgTotal,
			--'' AS Builder1,
			--'' AS Builder2,
			--0 AS ExamId,
			--'' AS Exam,
			--0 As BatchId,
			--'' As BatchName,
			--''  AS Code,
			--'' AS Name,
			--0 AS RollNo,
			----temp.tempAcademicId,
			--0 AS AcademicId,
			--0 AS Obtain,
			--'' AS ResultStatus,
			--'' AS Class,
			--0  AS ClassId,
			--'' AS Division,
			--0 AS DivisionId,
			--0 AS DivisinOrderIndex,
			--0 AS TotalMarks,
			--0 AS TotalObtain,
			--0 AS Percentage,
			--0 AS RankNumber,
			--'' AS ResultGrade,
			--'' AS ClassSubject,
			--0 AS ResultDetailId,
			--0 AS ResultId,
			--0 AS SubjectId,
			--0 AS Maximum,
			--'' AS SubjectGrade, 
			
			--0 AS IsMarksInDecimal,
			----SM.OrderIndex AS SubjectCode,
			--'' AS SubjectCode,
			--0 AS SubjectOrderIndex,
			--0 AS ClassOrderIndex,
			--0 AS IsPresent,
			-- 0 AS IsGrade,
			--0 AS IsPercentage,
			--0 AS IsResultStatus,
			--0 AS IsRankNo ,
			--0 AS  Minimum,
			--0 AS GraceMark,
			--'' AS DecimalFormat,
			--0 AS IsOptional,
			--0 AS PresentDays,
			--0 AS TotalDays,
			--0 As AvgTotal
END
GO
PRINT N'Altering [sAssessment].[pRptResultWithSubjectListGet]...';


GO

ALTER PROCEDURE [sAssessment].[pRptResultWithSubjectListGet]
	 
   	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rSubjectId int=0,
	 @rBatchId int,
	 @rClassId int,
	 @rDivisionId int,
	 @rExamId int=0,
     @rExamSubGroupId int=0,
	 @rCode nvarchar(20),
	 @rFromRollNo int,
	 @rToRollNo int,
	 @rFromRank int,
	 @rToRank int,
	 @rGrade nvarchar(20),
	 @rStatusId int = 0,
	 @rFromPercentage decimal(5,2)=0,
	 @rToPercentage decimal(5,2)=0,
	 @rResultStatus nvarchar(20)='',
	 @rDepartmentId int=0,
	 @rClassStatusId int=0,
	 @rGenderId int = 0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			
BEGIN 
	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			SO.GenderId,
			ESGM.Title AS Exam,
			StuM.Code,
			[sStudent].[fStudentNameGet](StuM.FirstName , StuM.MiddleName, StuM.LastName,OM.StudentNameFormatId ) AS Name,
			A.RollNo,
			R.AcademicId,
			RD.Obtain,
			R.ResultStatus,
			CM.DisplayTitle AS Class,
			Cm.Id AS ClassId,
			DM.DisplayTitle AS Division,
			DM.Id AS DivisionId,
			DM.OrderIndex AS DivisinOrderIndex,
			R.TotalMarks,
			R.TotalObtain,
			R.Percentage,
			R.RankNumber,
			R.ResultGrade,
			SM.Title AS ClassSubject,
			RD.Id AS ResultDetailId,
			R.Id AS ResultId,
			CS.Id AS SubjectId,
			ED.Maximum,
			RD.SubjectGrade, 
			
			EM.IsMarksInDecimal,
			--SM.OrderIndex AS SubjectCode,
			SM.Code AS SubjectCode,
			ED.DisplayOrder AS SubjectOrderIndex,
			CM.OrderIndex AS ClassOrderIndex,
			RD.IsPresent,
			EM.IsGrade,
			EM.IsPercentage,
			EM.IsResultStatus,
			EM.IsRankNo ,
			ED.Minimum,
			RD.GraceMark,
			EM.DecimalFormat,
			CS.IsOptional,
			ISNULL(SR.PresentDays,0)AS PresentDays,
			ISNULL(SR.TotalDays,0)AS TotalDays,
			ED.IsShowSubjectGrade,
			ED.IsShowSubjectMark,
			(EmpM.FirstName + ' ' +EmpM.LastName ) AS InchargeEmployeeName

	FROM 
			sAssessment.tResultDetail RD
			INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
			INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
			INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId	
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId		
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId					 
			INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
			LEFT JOIN sAssessment.tStudentRemark SR ON SR.AcademicId = A.Id AND SR.ExamId =  EM.Id
			INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
			INNER JOIN sSetup.tOrganizationMaster OM ON StuM.OrgId = OM.Id
			LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
			LEFT JOIN sHrm.tEmployeeMaster EmpM ON EmpM.Id = DM.InchargeEmployeeId AND EmpM.StatusId = 7
			
	WHERE 
			
		EM.BatchId = @rBatchId 
		AND (A.ClassId=@rClassId OR @rClassId=0) 
		AND ((SM.Id=@rSubjectId) OR (RD.ExamDetailId=@rSubjectId) OR (@rSubjectId=0))
		AND (A.DivisionId=@rDivisionId OR @rDivisionId=0)
		AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((R.RankNumber >= @rFromRank) OR (@rFromRank=0))
		AND ((R.RankNumber <= @rToRank) OR (@rToRank=0))
		AND ((R.ResultGrade = @rGrade) OR (@rGrade=''))
		AND ((ESGM.Id = @rExamSubGroupId) OR (@rExamSubGroupId = 0))		
		AND ((EM.Id=@rExamId )	OR (@rExamId = 0))		
		AND ((StuM.Code=@rCode) OR (@rCode=''))
		AND ((StuM.StatusId=@rStatusId)OR(@rStatusId=0))	
		AND ((R.Percentage>=@rFromPercentage) OR (@rFromPercentage=0))
		AND ((R.Percentage<=@rToPercentage) OR(@rToPercentage=0))	
		AND ((R.ResultStatus=@rResultStatus) OR (@rResultStatus=''))
		AND ((CM.DepartmentId = @rDepartmentId) OR (@rDepartmentId=0))
		AND	A.BatchId = @rBatchId 
		AND (A.ClassStatusId=@rClassStatusId OR @rClassStatusId=0) 
		AND ((SO.GenderId=@rGenderId) OR (@rGenderId=0))
		--AND RD.IsPresent = 0
		order by A.RollNo,CS.OrderIndex 

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


GO


ALTER PROCEDURE [sAssessment].[pRptStudentAnalysisDetailsGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rBatchId int=0,
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rExamId int,
	 @rCode nvarchar(20)='',
	 @rSubjectId int = 0,
	 @rFromRollNo int=0,
	 @rToRollNo int=0,
	 @rStatusId int=0,
	 @rClassStatusId int=0,
	 @rOrgGroupBatchId int=0,
	 @rIsPercentageDisplay bit=0
	
	 --@rFromRank int=0,
	 --@rToRank int=0,
	 --@rGrade nvarchar(20)='',
	 --@rResultId bigint=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,
	 --@rMultiCode nvarchar(max)=''
	
	 --,@rcolumn_visible bit
	

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
begin
 
  
  --select * from sAssessment.tTempAllExam
-- --drop table sAssessment.tTempAllExam
 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

--#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) Default 0,		
		SubjectGrade1 NVarchar(50),
		Obtain1 decimal(8,2) Default 0,
		ExamMaximum1 decimal(8,2),
		IsPresent1 bit,
						
		MaximumMark2 decimal(8,2) Default 0,	
		SubjectGrade2 NVarchar(50),
		Obtain2 decimal(8,2) Default 0,
		ExamMaximum2 decimal(8,2),
		IsPresent2 bit,
				
		MaximumMark3 decimal(8,2) Default 0,
		SubjectGrade3 NVarchar(50),
		Obtain3 decimal(8,2) Default 0,
		ExamMaximum3 decimal(8,2),
		IsPresent3 bit,		
		
		MaximumMark4 decimal(8,2) Default 0,	
		SubjectGrade4 NVarchar(50),
		Obtain4 decimal(8,2) Default 0,
		ExamMaximum4 decimal(8,2),
		IsPresent4 bit,	
				
		MaximumMark5 decimal(8,2) Default 0,		
		SubjectGrade5 NVarchar(50),
		Obtain5 decimal(8,2) Default 0,
		ExamMaximum5 decimal(8,2),
		IsPresent5 bit,	
				
		MaximumMark6 decimal(8,2) Default 0,		
		SubjectGrade6 NVarchar(50),
		Obtain6 decimal(8,2) Default 0,
		ExamMaximum6 decimal(8,2),
		IsPresent6 bit,	
		
		MaximumMark7 decimal(8,2) Default 0,		
		SubjectGrade7 NVarchar(50),
		Obtain7 decimal(8,2) Default 0,
		ExamMaximum7 decimal(8,2),
		IsPresent7 bit,	
		
		MaximumMark8 decimal(8,2) Default 0,	
		SubjectGrade8 NVarchar(50),
		Obtain8 decimal(8,2) Default 0,
		ExamMaximum8 decimal(8,2),
		IsPresent8 bit,	
		
		MaximumMark9 decimal(8,2) Default 0,		
		SubjectGrade9 NVarchar(50),
		Obtain9 decimal(8,2) Default 0,
		ExamMaximum9 decimal(8,2),
		IsPresent9 bit,	
		
		
		MaximumMark10 decimal(8,2) Default 0,		
		SubjectGrade10 NVarchar(50),
		Obtain10 decimal(8,2) Default 0,
		ExamMaximum10 decimal(8,2),
		IsPresent10 bit,	
		
		MaximumMark11 decimal(8,2) Default 0,		
		SubjectGrade11 NVarchar(50),
		Obtain11 decimal(8,2) Default 0,
		ExamMaximum11 decimal(8,2),
		IsPresent11 bit,
		
		MaximumMark12 decimal(8,2) Default 0,		
		SubjectGrade12 NVarchar(50),
		Obtain12 decimal(8,2) Default 0,
		ExamMaximum12 decimal(8,2),
		IsPresent12 bit,		
		 
		 
		SubjectGradeTerm1 NVarchar(50),
		SubjectGradeTerm2 NVarchar(50),
		SubjectGradeTerm3 NVarchar(50),
		IsMarksInDecimal bit,
		column_visible bit,
		--Obtain decimal(5,2),
		Percentile decimal(5,2),
		--ClassSubject nvarchar(100),
		ResultDetailId bigint,
		ResultId bigint,	
		Remark1 nvarchar(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), 
		
		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) default '',		
		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) default '',	
		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) default '',	
		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) default '',	
		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) default '',		
		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) default '',	
		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) default '',		
		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) default '',
		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) default '',	
		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) default '',	
		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) default '',	
		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) default '',	
		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(1000),
		
		DentalHygiene nvarchar(200),
		VisionLeft nvarchar(50),
		VisionRight nvarchar(50), 
		--IsDetail bit,
		IsPercentageDisplay 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),
		SubjectMaxTerm1 decimal(8,2),
		SubjectMaxTerm2 decimal(8,2),
		SubjectMaxTerm3 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),
		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(20),
		HighestDivisionMark decimal(5, 2),
		HighestDivisionGrade nvarchar(50),
		StreamTitle nvarchar(50),
		AdmissionNo int,
		AdmissionDate Date
		
	)	
	 --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,
	IsPercentageDisplay,
	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
	)
	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,
		@rIsPercentageDisplay AS IsPercentageDisplay,
		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.AdmissionFormNumber,0) AS AdmissionNo,
		ISNULL(StuA.AdmissionDate,'') AS Admissio
				
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.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
	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  ISNULL(EMP.IsOtherUser,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 ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)) 
	--AND (ISNULL(StuM.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rMultiCode,',')) OR @rMultiCode='')
	AND StuM.StatusId = 1
	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,	
					 				
					 SubjectGrade' + convert(nvarchar(15),@lCount)+ '=RD.SubjectGrade,
					 TotalDays'+convert(nvarchar(15),@lCount)+'=SR.TotalDays,
					 PresentDays'+convert(nvarchar(15),@lCount)+'=SR.PresentDays										
					 From
						sAssessment.tResultDetail RD
						INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId	
						LEFT JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND T.AcademicId = SR.AcademicId 									
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
						
--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)
		
		
	set @lCount = @lCount -1
	end
	

	IF (@IsIncludeSubExam = 1)
	BEGIN	
		select @lSubExamId = SubExamId from sAssessment.tExamCombine  Where ExamId  = @rExamId AND ExamOrder = 1
		--select @ExamTitle = Title from sAssessment.tExamMaster Where Id = @lSubExamId	
		
		
			set @query ='update T set					 
					SubjectGradeTerm1=RD.SubjectGrade,
					SubjectObtainTerm1 = RD.Obtain,
					 SubjectMaxTerm1 = ED.Maximum
							 
					 From
						 sAssessment.tResultDetail RD
						INNER JOIN  sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
		
				execute(@query)
				
		set @query ='update T set					 
					 
					TotalMarkTerm1 = R.TotalMarks,
					TotalObtainTerm1=R.TotalObtain,
					PercentageTerm1=R.Percentage,
					RankNumberTerm1=R.RankNumber,
					ResultGradeTerm1=R.ResultGrade,
					PercentileTerm1 = R.Percentile,
					ResultStatusTerm1 = R.ResultStatus,
					ExamNameTerm1 = ESGM.Code,
					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
					
					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
						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			
					 From						 
					   sAssessment.tResult R  				 
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON  T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
		execute(@query)
		
		select @lSubExamId = SubExamId from sAssessment.tExamCombine  Where ExamId  = @rExamId AND ExamOrder = 3
		set @query ='update T set					 
					SubjectGradeTerm3=RD.SubjectGrade,
					SubjectObtainTerm3 = RD.Obtain,
					SubjectMaxTerm3= ED.Maximum				 
					 From
						sAssessment.tResultDetail RD
						INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
		execute(@query)
		set @query ='update T set
 
					TotalMarkTerm3 = R.TotalMarks,
					TotalObtainTerm3=R.TotalObtain,
					PercentageTerm3=R.Percentage,
					RankNumberTerm3=R.RankNumber,
					ResultGradeTerm3=R.ResultGrade,
					PercentileTerm3 = R.Percentile,
					ResultStatusTerm3 = R.ResultStatus,
					ExamNameTerm3 = ESGM.Code			
					 From						 
					   sAssessment.tResult R  				 
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON  T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
		execute(@query)
	END
	
	
	
	
	
	--WHILE (@lCount1 <= 6)
	--BEGIN
	--	set @query ='ALTER TABLE #TempAllExam DROP COLUMN MaximumMark' + convert(nvarchar(15),@lCount1)
	--	execute(@query)
	--	set @query ='ALTER TABLE #TempAllExam DROP COLUMN Exam' + convert(nvarchar(150),@lCount1)+ 'Name'
	--	execute(@query)
	--	set @query ='ALTER TABLE #TempAllExam DROP COLUMN SubjectGrade' + convert(nvarchar(150),@lCount1)
	--	execute(@query)		
	--	set @query ='ALTER TABLE #TempAllExam DROP COLUMN Obtain' + convert(nvarchar(15),@lCount1)
	--	execute(@query)
	--	set @query ='ALTER TABLE #TempAllExam DROP COLUMN ExamMaximum' + convert(nvarchar(15),@lCount1)
	--	execute(@query)
	--	SET @lCount1 = @lCount1 + 1
	--END
	
	SELECT @rBuilder1,@rBuilder2, T.*
	FROM #TempAllExam T
	
	--INNER JOIN SSETUP.TCLASSSUBJECT CS ON CS.ID = T.CLASSSUBJECTID
	--WHERE
	--	((T.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
	--	AND ((T.RollNo <= @rToRollNo) OR (@rToRollNo=0))
	--	AND ((T.RankNumber >= @rFromRank) OR (@rFromRank=0))
	--	AND ((T.RankNumber <= @rToRank) OR (@rToRank=0))
	--	AND ((T.ResultGrade = @rGrade) OR (@rGrade=''))
	--	AND ((T.StudCode=@rCode) OR (@rCode=''))		
		--order by T.RollNo,CS.ORDERINDEX
	--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			
-- SELECT  AS Builder1,@rBuilder2 AS Builder2, T.* FROM sAssessment.tTempAllExam T
 
	END
	--SELECT @rBuilder1 AS Builder1,@rBuilder2 AS Builder2, T.* FROM sAssessment.tTempAllExam T
	
--end
GO
PRINT N'Altering [sAssessment].[pRptStudentProfileGet]...';


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

BEGIN 
	SELECT 
		    Convert(nvarchar(20),A.Id) AS   AcademicIdText,	
			CONVERT (nvarchar(20),@rExamId) AS ExamIdText,
			A.Id AS AcademicId,
			SM.Code,
			[sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Name,			 
			ISNULL(SF.FatherName,'') AS FatherName,
			ISNULL(SF.MotherName,'')AS MotherName,
			CONVERT(VARCHAR(10),SO.DateOfBirth,103) AS DateOfBirth,
			A.RollNo,
			CM.DisplayTitle AS Class,
			--DM.DisplayTitle AS Division,
			ISNULL(SC.ParentContactNo,'') AS ContactNo,
			HM.Title AS House,
			SI.StudentPhoto,
			EM.FirstName + ' ' + EM.LastName AS ClassTeacherName,
			DM.DisplayTitle AS Division,
			BM.Title AS Batch,
			SA.AdmissionDate,
			OM.OrgLogo,
			OM.DisplayTitle AS Organization,
			ISNULL(SR.PresentDays,0)AS PresentDays,
			ISNULL(SR.TotalDays,0)AS TotalDays,
			SR.StudentHeight,
			SR.StudentWeight
			 
			--CASE WHEN ED.ClassSubjectId=CS.Id THEN 'Yes' ELSE 'false' END AS Selected
      
	FROM 
			sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId
			INNER JOIN sStudent.tStudentAdmission SA ON SA.StudentId = SM.Id
			left Join sStudent.tStudentFamily SF ON SF.StudentId =SM.Id
			LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=A.StudentId
			LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=SM.Id
			LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
			Inner Join sSetup.tBatchMaster BM ON BM.Id=A.BatchId
			LEFT JOIN sActivity.tHouseMaster HM ON HM.Id=SO.HouseId
			LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id =DM.InchargeEmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
			INNER JOIN sSetup.tOrganizationMaster OM ON SM.OrgId = OM.Id
			LEFT JOIN sAssessment.tStudentRemark SR ON A.Id = SR.AcademicId AND SR.ExamId=@rExamId
			
	WHERE 
		((A.Id=@rAcademicId) OR (@rAcademicId=0))
		
END
GO
PRINT N'Altering [sAssessment].[pRptSubjectActivityExamDetailGet]...';


GO
ALTER PROCEDURE [sAssessment].[pRptSubjectActivityExamDetailGet]
	 
		@rOrgId int=0,
		@rExamId int=0,
		@rClass int=0,
		@rDivisionId int=0,
		@rBatchId int=0,
		@rBuilder1 nvarchar(max)='',
		@rAcademicId bigint=0,
		@rCode nvarchar(20)='',
		@rFromRollNo int=0,
		@rToRollNo int=0,
		@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

	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

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


GO
 


ALTER PROCEDURE [sAssessment].[pRptSubjectActivityExamDetailWithTermGradeGet]
	 
		@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 @GradeString nvarchar(500),@GradeSetId int
SELECT @GradeSetId = GradesetId FROM sAssessment.tExamMaster WHERE Id = @rExamId
SELECT @GradeString = [sAssessment].[fGradeStringGet](@GradeSetId)


--Declare @rIsDisplayStudentPhoto bit, @rIsDisplayTeacherSign bit, @rIsDisplayPrincipalSign bit, @rIsDisplayImageHeader bit
--SELECT @rIsDisplayStudentPhoto = ISNULL(IsDisplayPhoto,0), @rIsDisplayTeacherSign = ISNULL(IsDisplayTeacherSign,0),
--	   @rIsDisplayPrincipalSign = ISNULL(IsDisplayPrincipalSign,0),@rIsDisplayImageHeader = ISNULL(IsDisplayImageHeader,0)
--	   From sAssessment.tExamMaster Where Id = @rExamId
	   
		--DECLARE @lAcademicId TABLE (AcademicId bigint, ClassSubjectId int, Term1Grade nvarchar(20), Term2Grade nvarchar(20), AnnualGrade nvarchar(20),
		--Term1PresentDays Int, Term1TotalDays Int, Term2PresentDays Int, Term2TotalDays Int)
		
		--INSERT INTO @lAcademicId (AcademicId, ClassSubjectId)
		--(
		--	SELECT 			 
		--		SA.AcademicId,
		--		CS.ClassSubjectId
		--	FROM 
		--		sStudent.vStudentAcademic SA
		--		INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = SA.ClassId
		--		INNER JOIN sAssessment.tExamDetail ED ON EM.Id = ED.ExamId
		--		INNER JOIN sAssessment.vCCEExamClassSubject CS ON CS.ClassSubjectId = ED.ClassSubjectId 
		--		--INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = CS.SubjectId
		--	WHERE
		--		((SA.AcademicId=@rAcademicId) OR(@rAcademicId=0))
		--		AND ((CS.ClassId=@rClass) OR (@rClass=0))
		--		And ((SA.DivisionId =@rDivisionId) or(@rDivisionId=0))	
		--		And ((SA.BatchId =@rBatchId) OR (@rBatchId=0))
		--		And ((EM.Id = @rExamId) OR (@rExamId = 0))
		--		and ((SA.OrgId=@rOrgId) OR (@rOrgId=0))
		--		AND ((SA.Code = @rCode) OR(@rCode=''))
		--		AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		--		AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		--		AND SA.StatusId = 1
		--)
		
		--Declare @FirstTermExamId AS INT,@SecondTermExamId AS INT, @Term1PresentDays AS INT, @Term1TotalDays AS INT,
		--@Term2PresentDays AS INT, @Term2TotalDays AS INT
		
		--Select @FirstTermExamId=SubExamId  from sAssessment.tExamCombine Where ExamId = @rExamId AND ExamOrder = 1
		
		--Select @SecondTermExamId=SubExamId from sAssessment.tExamCombine Where ExamId = @rExamId AND ExamOrder = 2
		
		
	
		--UPDATE @lAcademicId 
		--SET Term1Grade = ARD.SubjectGrade
		--FROM @lAcademicId A
		--INNER JOIN sAssessment.tResult AR ON AR.ExamId = @FirstTermExamId AND AR.AcademicId = A.AcademicId
		--INNER JOIN sAssessment.tResultDetail ARD ON ARD.ResultId = AR.Id 
		--INNER JOIN sAssessment.tExamDetail ED ON ED.Id = ARD.ExamDetailId AND ED.ClassSubjectId = A.ClassSubjectId
	    
		--UPDATE @lAcademicId 
		--SET Term2Grade = ARD.SubjectGrade
		--FROM @lAcademicId A
		--INNER JOIN sAssessment.tResult AR ON AR.ExamId = @SecondTermExamId AND AR.AcademicId = A.AcademicId
		--INNER JOIN sAssessment.tResultDetail ARD ON ARD.ResultId = AR.Id 
		--INNER JOIN sAssessment.tExamDetail ED ON ED.Id = ARD.ExamDetailId AND ED.ClassSubjectId = A.ClassSubjectId
		
		--UPDATE @lAcademicId 
		--SET AnnualGrade = ARD.SubjectGrade
		--FROM @lAcademicId A
		--INNER JOIN sAssessment.tResult AR ON AR.ExamId = @rExamId AND AR.AcademicId = A.AcademicId
		--INNER JOIN sAssessment.tResultDetail ARD ON ARD.ResultId = AR.Id 
		--INNER JOIN sAssessment.tExamDetail ED ON ED.Id = ARD.ExamDetailId AND ED.ClassSubjectId = A.ClassSubjectId
		
		--UPDATE @lAcademicId 
		--SET Term1PresentDays = SR.PresentDays
		--FROM @lAcademicId A
		--INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = @FirstTermExamId AND SR.AcademicId = A.AcademicId
		
		--UPDATE @lAcademicId 
		--SET Term1TotalDays = SR.TotalDays
		--FROM @lAcademicId A
		--INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = @FirstTermExamId AND SR.AcademicId = A.AcademicId
		
	 --   UPDATE @lAcademicId 
		--SET Term2PresentDays = SR.PresentDays
		--FROM @lAcademicId A
		--INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = @SecondTermExamId AND SR.AcademicId = A.AcademicId
		
		--UPDATE @lAcademicId 
		--SET Term2TotalDays = SR.TotalDays
		--FROM @lAcademicId A
		--INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = @SecondTermExamId AND SR.AcademicId = A.AcademicId
	    
	    --Select * from @lAcademicId
	    
	    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,
			StuM.FirstName + ' ' +StuM.MiddleName +' ' +StuM.LastName AS Name,
			SO.DateOfBirth,
			CMM.Title AS ClassName,
			StuM.code,
			ISNULL(SR.PresentDays,0)AS PresentDays,			
			ISNULL(SR.TotalDays,0)AS TotalDays,
			SR.StudentHeight,
			SR.StudentWeight,
			SF.FatherName,
			SF.MotherName,
			SAM.ClassSubjectId ,
			SM.Title AS SubjectName,
			SM.OrderIndex AS SubjectOrderIndex,
			CMM.DisplayTitle AS Class,
			DM.DisplayTitle AS Division,
			SR.ResultRemark1,
			SR.ResultRemark2,						 
			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 Em.IsDisplayTeacherSign WHEN 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.CertificateHeaderA4 
			ELSE NULL END)AS MarksheetHeaderA4,
			ISNULL(EM.IsDisplayImageHeader,0) AS IsImageHeader,
			RD.Remark,
			SR.ClassTeacherRemark,
			SR.HouseRemark,
			HM.Title AS House,
			BM.Title AS BAtch ,
			[sAttendance].[fSubjectTeacherGet](SA.DivisionId,SM.ID) AS TEacherName,
			ED.IsShowSubjectGrade,
			@GradeString AS GradeString,
			Convert(nvarchar(20),ISNULL(Em.IsDisplayMonthlyAttendance,0)) As IsDisplayMonthlyAttendanceText,
			--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,
			ISNULL(EM.TeacherSignCaption,'') AS TeacherSignCaption,
		    ISNULL(EM.PrincipalSignCaption,'') AS PrincipalSignCaption,
			ParentSignCaption,
			SR.ResultRemark3,
			ARD.SubjectGrade,
			ISNULL(SR.GeneralRemark,'') As GeneralRemark,
			(CASE  When EM.CoordinatorEmployeeId IS NOT NULL AND EM.CoordinatorEmployeeId !=0 then EICoordinator.EmployeeSign ELSE NULL END) AS CoordinatorEmployeeSign,
			ISNULL(C.ParentContactNo,'') AS ParentContactNo,
			ISNULL(C.StudentContactNo,'') AS StudentContactNo,
			(C.PresentStreetOne+' '+C.PresentStreetTwo+' '+C.PresentStreetThree+' '+C.PresentCountry+' '+C.PresentState+' '+C.PresentCity+' '+C.PresentZipCode) AS Address1  

			
			--A.Term1Grade,
			--A.Term2Grade,
			--A.AnnualGrade,
			--A.Term1PresentDays,
			--A.Term1TotalDays,
			--A.Term2PresentDays,
			--A.Term2TotalDays			
			
		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.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 sHrm.tEmployeeImages EICoordinator ON EICoordinator.EmployeeId = EM.CoordinatorEmployeeId	
			--LEFT JOIN @lAcademicId A ON A.AcademicId = SA.AcademicId AND A.ClassSubjectId = ED.ClassSubjectId
			LEFT JOIN sStudent.tStudentCommunication C ON C.StudentId = SA.StudentId
			
		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='')
		--ORDER BY 
		--	SA.RollNo ASC,
		--	SAM.OrderIndex ASC,
		--	SSA.OrderIndex ASC;
			
END
GO
PRINT N'Altering [sAssessment].[pRptSubjectActivityExamMarkGet]...';


GO

ALTER PROCEDURE [sAssessment].[pRptSubjectActivityExamMarkGet]
	  
	   @rOrgId int
	  ,@rExamId int,
	  @rClass int,
	  @rDivisionId int,
	  @rBatchId int,
	  @rActivityId int,
	  @rSubjectSubActivityId int,
	  @rBuilder1 nvarchar(max)
	  
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 	
 
			SELECT 		
				 
				 @rBuilder1 AS Builder1,
				 SA.AcademicId,
				 SA.RollNo,
				 SA.Number,
				 SA.Name,
				  
				 ISNULL(AIS.Marks,0) AS Marks,
				 
				 SAM.Title AS SubjectActivityTitle,
				 SSA.Title AS SubjectSubActivityTitle,
				 SAM.Id AS ActivityId,
				 SSA.Id AS SubjectSubActivityId,
				 SAM.OrderIndex AS ActivityOrderIndex,
				 SSA.OrderIndex AS SubjectSubActivityOrderIndex,
				 SM.Title AS SubjectName,
				 SAM.ClassSubjectId,
				 ISNULL(AIS.Grade,'') AS Grade,
				 ISNULL(AIS.GradeIndicator,'') AS GradeIndicator,
				 ISNULL(AIS.DescriptiveIndicator,'') AS DescriptiveIndicator,
				 (SELECT EM.FirstName + ' ' + EM.LastName  From sHrm.tEmployeeMaster EM 
				  INNER JOIN sSetup.tDivisionMaster DM ON EM.Id = DM.InchargeEmployeeId Where DM.Id = @rDivisionId) AS ClassTeacher
					 
			FROM 
			  sAssessment.tCCESubjectActivityMaster SAM 	
			INNER JOIN sAssessment.tCCESubjectSubActivityMaster SSA ON SAM.Id=SSA.SubjectActivityId  
			INNER JOIN sAssessment.vCCEExamClassSubject CS ON CS.ClassSubjectId=SAM.ClassSubjectId		
			INNER JOIN sSetup.tClassMaster CMM ON CMM.Id=CS.ClassId 
			INNER JOIN sStudent.vStudentAcademic SA ON   SA.ClassId = CMM.Id 
			LEFT JOIN sAssessment.tCCESubjectSubActivityExamScore AIS ON AIS.AcademicId =SA.AcademicId AND AIS.SubjectSubActivityId= SSA.Id And AIS.ExamId=@rExamId
			 INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId

	    	 WHERE
				 ((SAM.ClassSubjectId=@rClass) OR (@rClass=0))
				And SA.DivisionId =@rDivisionID	
				And SA.BatchId =@rBatchId
				--AND AIS.ExamId=@rExamId
				and ((SSA.SubjectActivityId=@rActivityId) OR (@rActivityId=0))
				AND((SSA.Id=@rSubjectSubActivityId) OR (@rSubjectSubActivityId=0))	
				and SSA.OrgId=@rOrgId
				AND  SA.StatusId = 1		
		 
			 ORDER BY SA.RollNo
			
END
GO
PRINT N'Altering [sAssessment].[pRptTeacherEvaluationExamWise]...';


GO
 
 
ALTER PROCEDURE [sAssessment].[pRptTeacherEvaluationExamWise]
   	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='',
	 @rDepartmentId int=0,
	 @rClassId int,
	 @rDivisionId int,
	 @rCode nvarchar(20),
	 @rFromRollNo int,
	 @rToRollNo int,
	 @rStatusId int = 0,
	 @rFromPercentage decimal(5,2)=0,
	 @rToPercentage decimal(5,2)=0,
	 @rOrgGroupId int,
	 @rTop int=0,
	 @rTeacherClass NVARCHAR(MAX)='',
	 @rEmployeeId bigint,
	 @rClassExam NVARCHAR(MAX)='',
	 @rBatchId int,
	 @rClassStatusId int=0

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

DECLARE @lMarkEntryBasedOn nvarchar(50)
SELECT @lMarkEntryBasedOn=CS.ItemValue FROM sConfig.tConfigurationMaster CM LEFT JOIN sConfig.tConfigurationSetup CS ON CM.Id=CS.Configurationid AND CS.SourceId=@rOrgGroupId WHERE CM.Id = 188


IF(@lMarkEntryBasedOn='Class Teacher')
BEGIN

SELECT 
			@rTop RowNum,
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			ESGM.Title AS Exam,
			StuM.Code,
			[sStudent].[fStudentNameGet](StuM.FirstName , StuM.MiddleName, StuM.LastName,OM.StudentNameFormatId ) AS Name,
			A.RollNo,
			R.AcademicId,
			RD.Obtain,
			R.ResultStatus,
			CM.DisplayTitle AS Class,
			Cm.Id AS ClassId,
			DM.DisplayTitle AS Division,
			DM.Id AS DivisionId,
			DM.OrderIndex AS DivisinOrderIndex,
			R.TotalMarks,
			R.TotalObtain,
			R.Percentage,
			R.RankNumber,
			R.ResultGrade,
			SM.Title AS ClassSubject,
			RD.Id AS ResultDetailId,
			R.Id AS ResultId,
			CS.Id AS SubjectId,
			ED.Maximum,
			RD.SubjectGrade, 
			
			EM.IsMarksInDecimal,
			--SM.OrderIndex AS SubjectCode,
			SM.Code AS SubjectCode,
			ED.DisplayOrder AS SubjectOrderIndex,
			CM.OrderIndex AS ClassOrderIndex,
			RD.IsPresent,
			EM.IsGrade,
			EM.IsPercentage,
			EM.IsResultStatus,
			EM.IsRankNo ,
			ED.Minimum,
			RD.GraceMark,
			EM.DecimalFormat,
			CS.IsOptional,
			ISNULL(SR.PresentDays,0)AS PresentDays,
			ISNULL(SR.TotalDays,0)AS TotalDays,
			EM.Id AS ExamId
	FROM 
			sAssessment.tResultDetail RD
			INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
			INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
			INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId	
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId		
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId					 
			INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
			LEFT JOIN sAssessment.tStudentRemark SR ON SR.AcademicId = A.Id
			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 sAcademic.tTeacherSubjectDivision TS ON TS.SubjectId=CS.SubjectId  AND TS.DivisionId=DM.ID
			
	WHERE 
			
		EM.BatchId = @rBatchId 
		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 ((R.Percentage>=@rFromPercentage) OR (@rFromPercentage=0))
		AND ((R.Percentage<=@rToPercentage) OR(@rToPercentage=0))	
		AND ((CM.DepartmentId = @rDepartmentId) OR (@rDepartmentId=0))
		AND (A.ClassId=@rClassId OR @rClassId=0)
		--AND TS.EmployeeId=@rEmployeeId
		AND (ISNULL(A.DivisionId,0) IN( SELECT item FROM  sCommon.fnsplit(@rTeacherClass,','))OR @rTeacherClass='')
		AND (ISNULL(ESGM.Id,0) IN( SELECT item FROM  sCommon.fnsplit(@rClassExam,','))OR @rClassExam='')
		AND	A.BatchId = @rBatchId
		AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))
		order by A.RollNo,CS.OrderIndex 
	
END 
IF(@lMarkEntryBasedOn='Class Teacher Batch')
BEGIN
SELECT 
			@rTop AS RowNum,
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			ESGM.Title AS Exam,
			StuM.Code,
			[sStudent].[fStudentNameGet](StuM.FirstName , StuM.MiddleName, StuM.LastName,OM.StudentNameFormatId ) AS Name,
			A.RollNo,
			R.AcademicId,
			RD.Obtain,
			R.ResultStatus,
			CM.DisplayTitle AS Class,
			Cm.Id AS ClassId,
			DM.DisplayTitle AS Division,
			DM.Id AS DivisionId,
			DM.OrderIndex AS DivisinOrderIndex,
			R.TotalMarks,
			R.TotalObtain,
			R.Percentage,
			R.RankNumber,
			R.ResultGrade,
			SM.Title AS ClassSubject,
			RD.Id AS ResultDetailId,
			R.Id AS ResultId,
			CS.Id AS SubjectId,
			ED.Maximum,
			RD.SubjectGrade, 
			
			EM.IsMarksInDecimal,
			--SM.OrderIndex AS SubjectCode,
			SM.Code AS SubjectCode,
			ED.DisplayOrder AS SubjectOrderIndex,
			CM.OrderIndex AS ClassOrderIndex,
			RD.IsPresent,
			EM.IsGrade,
			EM.IsPercentage,
			EM.IsResultStatus,
			EM.IsRankNo ,
			ED.Minimum,
			RD.GraceMark,
			EM.DecimalFormat,
			CS.IsOptional,
			ISNULL(SR.PresentDays,0)AS PresentDays,
			ISNULL(SR.TotalDays,0)AS TotalDays,
			EM.Id AS ExamId
	FROM 
			sAssessment.tResultDetail RD
			INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
			INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
			INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId	
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId		
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId					 
			INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
			LEFT JOIN sAssessment.tStudentRemark SR ON SR.AcademicId = A.Id
			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 sAcademic.tTeacherSubjectDivision TS ON TS.SubjectId=CS.SubjectId  AND TS.DivisionId=DM.ID
			INNER JOIN sSetup.tDivisionInchargeEmployee DIE ON DIE.DivisionId = DM.Id
			
	WHERE 
		EM.BatchId = @rBatchId 
		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 ((R.Percentage>=@rFromPercentage) OR (@rFromPercentage=0))
		AND ((R.Percentage<=@rToPercentage) OR(@rToPercentage=0))	
		AND ((CM.DepartmentId = @rDepartmentId) OR (@rDepartmentId=0))
		AND (A.ClassId=@rClassId OR @rClassId=0)
		AND TS.EmployeeId=@rEmployeeId
		AND (ISNULL(A.DivisionId,0) IN( SELECT item FROM  sCommon.fnsplit(@rTeacherClass,','))OR @rTeacherClass='')
		AND (ISNULL(ESGM.Id,0) IN( SELECT item FROM  sCommon.fnsplit(@rClassExam,','))OR @rClassExam='')
		AND	A.BatchId = @rBatchId
		AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))
		AND DIE.Number = (SELECT MIN(Number) FROM sSetup.tDivisionInchargeEmployee WHERE  DIE.DivisionId = DM.Id AND DIE.BatchId = @rBatchId)
		order by A.RollNo,CS.OrderIndex 
END 

IF(@lMarkEntryBasedOn='Academic Setup')
BEGIN
SELECT 
			@rTop AS RowNum,
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			ESGM.Title AS Exam,
			StuM.Code,
			[sStudent].[fStudentNameGet](StuM.FirstName , StuM.MiddleName, StuM.LastName,OM.StudentNameFormatId ) AS Name,
			A.RollNo,
			R.AcademicId,
			RD.Obtain,
			R.ResultStatus,
			CM.DisplayTitle AS Class,
			Cm.Id AS ClassId,
			DM.DisplayTitle AS Division,
			DM.Id AS DivisionId,
			DM.OrderIndex AS DivisinOrderIndex,
			R.TotalMarks,
			R.TotalObtain,
			R.Percentage,
			R.RankNumber,
			R.ResultGrade,
			SM.Title AS ClassSubject,
			RD.Id AS ResultDetailId,
			R.Id AS ResultId,
			CS.Id AS SubjectId,
			ED.Maximum,
			RD.SubjectGrade, 
			
			EM.IsMarksInDecimal,
			--SM.OrderIndex AS SubjectCode,
			SM.Code AS SubjectCode,
			ED.DisplayOrder AS SubjectOrderIndex,
			CM.OrderIndex AS ClassOrderIndex,
			RD.IsPresent,
			EM.IsGrade,
			EM.IsPercentage,
			EM.IsResultStatus,
			EM.IsRankNo ,
			ED.Minimum,
			RD.GraceMark,
			EM.DecimalFormat,
			CS.IsOptional,
			ISNULL(SR.PresentDays,0)AS PresentDays,
			ISNULL(SR.TotalDays,0)AS TotalDays,
			EM.Id AS ExamId
			
	FROM 
			sAssessment.tResultDetail RD
			INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
			INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
			INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId	
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId		
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId					 
			INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
			LEFT JOIN sAssessment.tStudentRemark SR ON SR.AcademicId = A.Id
			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 sAcademic.tTeacherSubjectDivision TS ON TS.SubjectId=CS.SubjectId  AND TS.DivisionId=DM.ID
			
	WHERE 
		EM.BatchId = @rBatchId 
		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 ((R.Percentage>=@rFromPercentage) OR (@rFromPercentage=0))
		AND ((R.Percentage<=@rToPercentage) OR(@rToPercentage=0))	
		AND ((CM.DepartmentId = @rDepartmentId) OR (@rDepartmentId=0))
		AND (A.ClassId=@rClassId OR @rClassId=0)
		AND TS.EmployeeId=@rEmployeeId
		AND (ISNULL(A.DivisionId,0) IN( SELECT item FROM  sCommon.fnsplit(@rTeacherClass,','))OR @rTeacherClass='')
		AND (ISNULL(ESGM.Id,0) IN( SELECT item FROM  sCommon.fnsplit(@rClassExam,','))OR @rClassExam='')
		AND	A.BatchId = @rBatchId
		AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))
		order by A.RollNo,CS.OrderIndex 
END 

IF(@lMarkEntryBasedOn='User Access')
BEGIN
SELECT 
			@rTop AS RowNum,
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			ESGM.Title AS Exam,
			StuM.Code,
			[sStudent].[fStudentNameGet](StuM.FirstName , StuM.MiddleName, StuM.LastName,OM.StudentNameFormatId ) AS Name,
			A.RollNo,
			R.AcademicId,
			RD.Obtain,
			R.ResultStatus,
			CM.DisplayTitle AS Class,
			Cm.Id AS ClassId,
			DM.DisplayTitle AS Division,
			DM.Id AS DivisionId,
			DM.OrderIndex AS DivisinOrderIndex,
			R.TotalMarks,
			R.TotalObtain,
			R.Percentage,
			R.RankNumber,
			R.ResultGrade,
			SM.Title AS ClassSubject,
			RD.Id AS ResultDetailId,
			R.Id AS ResultId,
			CS.Id AS SubjectId,
			ED.Maximum,
			RD.SubjectGrade, 
			
			EM.IsMarksInDecimal,
			--SM.OrderIndex AS SubjectCode,
			SM.Code AS SubjectCode,
			ED.DisplayOrder AS SubjectOrderIndex,
			CM.OrderIndex AS ClassOrderIndex,
			RD.IsPresent,
			EM.IsGrade,
			EM.IsPercentage,
			EM.IsResultStatus,
			EM.IsRankNo ,
			ED.Minimum,
			RD.GraceMark,
			EM.DecimalFormat,
			CS.IsOptional,
			ISNULL(SR.PresentDays,0)AS PresentDays,
			ISNULL(SR.TotalDays,0)AS TotalDays,
			EM.Id AS ExamId
	FROM 
			sAssessment.tResultDetail RD
			INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
			INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
			INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId	
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId		
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId					 
			INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
			LEFT JOIN sAssessment.tStudentRemark SR ON SR.AcademicId = A.Id
			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 sAcademic.tTeacherSubjectDivision TS ON TS.SubjectId=CS.SubjectId  AND TS.DivisionId=DM.ID
			INNER JOIN sSecurity.tUserAccess U ON U.SourceId = DM.Id AND U.SourceTypeId= 2005
			
	WHERE 
		EM.BatchId = @rBatchId 
		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 ((R.Percentage>=@rFromPercentage) OR (@rFromPercentage=0))
		AND ((R.Percentage<=@rToPercentage) OR(@rToPercentage=0))	
		AND ((CM.DepartmentId = @rDepartmentId) OR (@rDepartmentId=0))
		AND (A.ClassId=@rClassId OR @rClassId=0)
		--AND TS.EmployeeId=@rEmployeeId
		AND (ISNULL(A.DivisionId,0) IN( SELECT item FROM  sCommon.fnsplit(@rTeacherClass,','))OR @rTeacherClass='')
		AND (ISNULL(ESGM.Id,0) IN( SELECT item FROM  sCommon.fnsplit(@rClassExam,','))OR @rClassExam='')
		AND	A.BatchId = @rBatchId
		AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))
		order by A.RollNo,CS.OrderIndex 
END 

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


GO


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

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


GO
ALTER PROCEDURE [sAttendance].[pMonthlyAttenanceRegisterGet]
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rAttendanceTypeId smallint=0,
	 @rOrgId int,
	 @rForMonth smallint,
	 @rForYear smallint,
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rBatchId int = 0  
	 WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	DECLARE @lFirstDate Date,@lLastDate date
	
	DECLARE @lResult nvarchar(max)
	DECLARE @li int 
	SET @li=1
	SET @lFirstDate = CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'/'+CONVERT(NVARCHAR(2),@rForMonth)+'/01'))	
	SET @lLastDate = sCommon.fGetLastDateofMonth(@lFirstDate)
	Declare @Days int 
	select @Days=sCommon.fGetDaysInMonth(@rForMonth,@rForYear)
	--DECLARE @lAdmissionDate date 
	-- select @lAdmissionDate=Stud.AdmissionDate from    sStudent.tStudentAdmission Stud  inner join sStudent.vStudentAcademic A ON A.StudentId = Stud.StudentId
	--						Where AdmissionStandardId=@rClassId AND Stud.BatchId =@rBatchId  
	 
BEGIN 
 
CREATE Table #AttendanceRegistertempTable
(
	 
	ClassDivisionTitle Nvarchar(50),
	Code nvarchar(50),
	RollNo int,
	AcademicId bigint,
	Name nvarchar(100),
	AttendanceTypeId int,
	ForYear int,
	ForMonth int,
	ForMonthInWord nvarchar(100),
	ClassId int,
	DivisionId int,
	ClassName nvarchar(50),
	DivisionName nvarchar(50),
	IsPresent bit,
	DayPart int,
	LeftDate date,
	ClassOrderIndex int,
	DivisionOrderIndex int,
	FooterSignature nvarchar(500),
	StatusId int,
	AttendanceDate date,
	AttendanceTagId int ,
	AdmissionDate date
 
)
Insert INTO #AttendanceRegistertempTable
(	
	ClassDivisionTitle,
	Code ,
	RollNo,
	AcademicId,
	Name,
	AttendanceTypeId,
	ForYear,
	ForMonth,
	ForMonthInWord,
	ClassId,
	DivisionId,
	ClassName,
	DivisionName,
	IsPresent,
	DayPart,
	LeftDate,
	ClassOrderIndex,
	DivisionOrderIndex,
	FooterSignature,
	StatusId,
	AttendanceDate,
	AttendanceTagId,
	AdmissionDate
  
)
Select	    
	ISNULL(SA.ClassName + '-' + SA.DivisionName,'') AS ClassDivisionTitle,
	SA.Code,
	SA.RollNo,
	SA.AcademicId,
	SA.Name,
	SR.AttendanceTypeId ,
	YEAR(SR.AttendanceDate) AS ForYear,
	MONTH(SR.AttendanceDate) AS ForMonth,
	DATENAME(month, SR.AttendanceDate) AS ForMonthInWord,
	SA.ClassId,
	SA.DivisionId,
	SA.ClassName,Sa.DivisionName,
  
	--(CASE SR.IsPresent WHEN 1 THEN 'P' 
	--	WHEN 0 THEN 'A'
	--ELSE  ' ' END )AS  IsPresent,		
	SR.IsPresent,
	 day(SR.AttendanceDate) AS DayPart,
	 
	 A.LeftDate,
	 CM.OrderIndex AS ClassOrderIndex,
	 DM.OrderIndex As DivisionOrderIndex,
	 OM.FooterSignature AS FooterSignature,
	 SA.StatusId,
	 SR.AttendanceDate As AttendanceDate,
	 SR.AttendanceTagId,
	 A.AdmissionDate
	 
	 --,
	 --SR.IsPresent
	 
	 
    from
            sStudent.vStudentAcademic SA 
            LEFT JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.AcademicId AND (YEAR(SR.AttendanceDate)=@rForYear) AND (MONTH(SR.AttendanceDate)=@rForMonth) AND (SR.AttendanceTypeId=@rAttendanceTypeId)
            INNER JOIN sStudent.tStudentAdmission A ON SA.StudentId = A.StudentId
            INNER JOIN sSetup.tClassMaster CM ON CM.Id = SA.ClassId
            INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = CM.OrgId
            INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=SA.DivisionId
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId AND ISNULL(EM.IsOtherUser,0) = 0
             
             WHERE  
	        
			  SA.OrgId=@rOrgId  
	          AND  (SA.BatchId=@rBatchId) AND  (SA.ClassId=@rClassId) 
	          AND  (SA.DivisionId=@rDivisionId)
	          AND  A.AdmissionDate <=  @lLastDate
	          AND ((A.LeftDate >= @lFirstDate) OR ISNULL(A.LeftDate,'') = '')
			  
				
CREATE TABLE #TempDaysTempTable
(
 DayPart int,
 Value nvarchar(20)
 )
WHILE @li<=@Days
BEGIN
INSERT INTO #TempDaysTempTable
(
	DayPart ,
   Value
)

SELECT 
@li AS DayPart,
 [sAttendance].[fWeekHOffGet](@rForYear,@rForMonth,@li,@rBatchId,@rClassId, @rDivisionId,'',@rOrgId) 
SET @li = @li + 1
END
 
SELECT  
			@lFirstDate AS LastDate,
			LeftDate,
            @rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			PivotTable.AcademicId,
			ClassDivisionTitle,isnull(Code,'') as Code,isnull(RollNo,0) as RollNo,
			isnull(Name,'') as Name,isnull(AttendanceTypeId,0) as AttendanceTypeId,isnull(ForYear,'') AS ForYear,
			isnull(ForMonth,'') AS ForMonth,ClassId,ClassName,DivisionId,
			DivisionName, 
			ForMonthInWord,
			(ISNULL(TC.TCount,0) - ISNULL(AC.ACount,0)) AS PresentCount,
			 ISNULL(TC.TCount,0) AS AttendanceCount,
				
		      ISNULL(AC.ACount,0) As  AbsentCount,
		       ISNULL(PC.PCount,0) As  PresentUpto,
		       ClassOrderIndex,
		       DivisionOrderIndex,
		       FooterSignature,				 
			0 AS TotalPresent ,
			 
	 		   sAttendance.fAttendanceAdmissionDateGet(AdmissionDate,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-01')),LeftDate,[1]) AS P1,
	 	 
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-02')),LeftDate,[2]) AS P2,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-03')),LeftDate,[3]) AS P3,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-04')),LeftDate,[4]) AS P4,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-05')),LeftDate,[5]) AS P5,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-06')),LeftDate,[6]) AS P6,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-07')),LeftDate,[7]) AS P7,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-08')),LeftDate,[8]) AS P8,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-09')),LeftDate,[9]) AS P9,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-10')),LeftDate,[10]) AS P10,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-11')),LeftDate,[11]) AS P11,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-12')),LeftDate,[12]) AS P12,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-13')),LeftDate,[13]) AS P13,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-14')),LeftDate,[14]) AS P14,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-15')),LeftDate,[15]) AS P15,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-16')),LeftDate,[16]) AS P16,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-17')),LeftDate,[17]) AS P17,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-18')),LeftDate,[18]) AS P18,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-19')),LeftDate,[19]) AS P19,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-20')),LeftDate,[20]) AS P20,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-21')),LeftDate,[21]) AS P21,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-22')),LeftDate,[22]) AS P22,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-23')),LeftDate,[23]) AS P23,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-24')),LeftDate,[24]) AS P24,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-25')),LeftDate,[25]) AS P25,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-26')),LeftDate,[26]) AS P26,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-27')),LeftDate,[27]) AS P27,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-28')),LeftDate,[28]) AS P28,
			CASE WHEN @Days>=29 THEN sAttendance.fAttendanceAdmissionDateGet(AdmissionDate,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-29')),LeftDate,[29]) end AS P29,
			CASE WHEN @Days>=30 THEN sAttendance.fAttendanceAdmissionDateGet(AdmissionDate,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-30')),LeftDate,[30])end AS P30,
		    
			CASE WHEN @Days>=31 THEN sAttendance.fAttendanceAdmissionDateGet(AdmissionDate,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-31')),LeftDate,[31])end AS P31,
		 
sCommon.fGetDaysInMonth ( @rForMonth,@rForYear) AS DaysInMonth
,0 Ispresent,
0 AS AttendanceTagId,
AdmissionDate  
FROM
(
	Select  
		ISNULL(ClassName + '-' + DivisionName,'') AS ClassDivisionTitle,
		Code,
		RollNo,
		AcademicId,
		Name,
		AttendanceTypeId ,
		YEAR(ST.AttendanceDate) AS ForYear,
		MONTH(ST.AttendanceDate) AS ForMonth,
		DATENAME(month, ST.AttendanceDate) AS ForMonthInWord,
		ClassId,
		DivisionId,
		ClassName,
		DivisionName,
		(
			CASE 
			 WHEN IsPresent = 1 AND ST.AttendanceTagId = 1 THEN 'LA' 
				  WHEN IsPresent = 1 AND ST.AttendanceTagId = 2 THEN 'ED' 
			      WHEN IsPresent = 1  THEN 'P' 
				  WHEN IsPresent = 0 THEN 'A'
				  ELSE  DT.Value END 
		)AS  IsPresent,		
		day(ST.AttendanceDate) AS DayPart,
		LeftDate,		 
		ClassOrderIndex,
		DivisionOrderIndex,
		FooterSignature,
		AdmissionDate

		 
		
	 FROM 
		#AttendanceRegistertempTable ST 
		LEFT JOIN #TempDaysTempTable DT ON DT.DayPart = ST.DayPart
	 WHERE
		((LeftDate >= @lFirstDate) OR ISNULL(LeftDate,'') = '')
) AS SourceTable 
	           
	        
PIVOT
(	
MIN(IsPresent)
FOR DayPart IN ([0], [1], [2], [3], [4],[5],[6],[7],[8],[9],[10],[11],[12],[13],[14],[15],[16],[17],[18],[19],[20],[21],[22],[23],[24],[25],[26],[27],[28],[29],[30],[31])
) AS PivotTable
	LEFT JOIN
	(
		Select  AcademicId AS AcademicId, COUNT(1) AS TCount 
		   FROM  
				#AttendanceRegistertempTable
		     GROUP BY  AcademicId  
    ) TC ON TC.AcademicId = PivotTable.AcademicId 
	LEFT JOIN
	(
		Select AcademicId AS AcademicId, COUNT(1) AS ACount 
		   FROM  #AttendanceRegistertempTable
		    WHERE   IsPresent = 0	 	 
			GROUP BY  AcademicId
    ) AC ON AC.AcademicId = PivotTable.AcademicId
	LEFT JOIN
	(
		SELECT A.Id AS AcademicId, COUNT(1) AS PCount  FROM sStudent.tAcademic A 
			LEFT JOIN  sAttendance.tStudentRegister SR ON SR.AcademicId = A.Id 
		   INNER JOIN sStudent.tStudentMaster SA ON A.StudentId = SA.Id
		   INNER JOIN sSetup.tClassMaster CM ON A.ClassId = CM.Id
			WHERE   
			 SR.AttendanceDate < (convert(date,CONVERT(nvarchar(10), @rForYear)+ '/' +  CONVERT(nvarchar(10), @rForMonth) + '/' + '01' ))
			    		
            --AND (SA.StatusId = 1)
	        --AND ((SR.AttendanceTypeId=@rAttendanceTypeId) OR (@rAttendanceTypeId= 0))
	        AND  ((SA.OrgId=@rOrgId) OR (@rOrgId= 0))
	        AND ((A.BatchId=@rBatchId) OR (@rBatchId= 0))	          
	        AND ((A.ClassId=@rClassId) OR (@rClassId= 0))
	        --AND ((SA.Code=@rStudentCode) OR (@rStudentCode=''))
	  --      AND ((A.Id=@rAcademicId) OR (@rAcademicId=0))	           
			--AND ((CM.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))				
	        AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId= 0))
			GROUP BY A.Id
    ) PC ON PC.AcademicId = PivotTable.AcademicId
    ORDER BY RollNo; 
    
--select * from #TempDaysTempTable 
drop table #AttendanceRegistertempTable	  
drop table #TempDaysTempTable
END
GO
PRINT N'Altering [sAttendance].[pUpdateResultAttendance]...';


GO

ALTER PROCEDURE [sAttendance].[pUpdateResultAttendance]
	 	 
		 @rClassId int=0,
		 @rDivisionId int=0,
		 @rStudentCode nvarchar(20)='',	
	 	 @rAttendanceTypeId tinyint=1,	 	 
		 @rFromAttendanceDate date='',
		 @rToAttendanceDate date='',
	 	 @rBatchId int,
	 	 @rOrgId int,
	 	 @rExamId int,
	 	 @rExamSubGroupId int=0
	  
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
 
 

BEGIN 
 
		
	CREATE TABLE #tResultAttendance
	 (
	 ExamId int,  
	 AcademicId  bigint,	 
	 PresentCount int,
	 AbsentCount int 
	 )

   INSERT INTO #tResultAttendance
   (ExamId,AcademicId,PresentCount,AbsentCount)
   	SELECT
   	EM.Id, 
   	SA.Id,
	   ISNULL((SELECT count(AcademicId) FROM sAttendance.tStudentRegister SR	 
		WHERE		 
		 SR.AttendanceDate >= @rFromAttendanceDate
		AND SR.AttendanceDate <= @rToAttendanceDate
		AND 
		SR.AcademicId = SA.Id
		AND SR.IsPresent = 1
		AND SR.AttendanceTypeId = @rAttendanceTypeId				
		) ,0)
		 AS PresentCount
		 , 
	   ISNULL((SELECT count(AcademicId) FROM sAttendance.tStudentRegister SR	 
		WHERE		 
		 SR.AttendanceDate >= @rFromAttendanceDate
		AND SR.AttendanceDate <= @rToAttendanceDate		
		AND 
		SR.IsPresent = 0
		AND SR.AttendanceTypeId = @rAttendanceTypeId
		AND SR.AcademicId = SA.Id		
		),0)
		 AS AbsentCount 		
  FROM 
		 sStudent.tAcademic SA 
		 INNER JOIN sStudent.tStudentMaster SM ON SM.Id=SA.StudentId
		 INNER JOIN sAssessment.tExamMaster EM ON SA.BatchId = EM.BatchId 
		 AND SA.ClassId = EM.ClassId
		 AND EM.ExamSubGroupId = 	@rExamSubGroupId
		 AND EM.BatchId = @rBatchId	 
		 INNER JOIN sAssessment.tExamStatus ES ON ES.ExamId = EM.Id AND ES.DivisionId = SA.DivisionId 
         WHERE
   --       ((SM.Code=@rStudentCode) OR (@rStudentCode=''))         
		 --AND 
		 ((SA.ClassId=@rClassId) OR (@rClassId=0))
	     AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0)) 
         AND (SA.OrgId = @rOrgId)
         AND (SA.BatchId = @rBatchId)
		 AND ES.StatusId <> 504
        
  
 -- Select * from #tResultAttendance
    INSERT INTO sAssessment.tStudentRemark
    (ExamId,AcademicId,PresentDays,TotalDays)
    SELECT RA.ExamId,RA.AcademicId,CONVERT(decimal(6, 2),PresentCount),CONVERT(decimal(6, 2),AbsentCount) + CONVERT(decimal(6, 2),PresentCount)
    --,SR.AcademicId,SR.ExamId
    FROM #tResultAttendance RA LEFT JOIN sAssessment.tStudentRemark SR
    ON RA.AcademicId = SR.AcademicId AND RA.ExamId = SR.ExamId
    WHERE SR.AcademicId IS NULL   AND SR.ExamId IS NULL
    
   
    
    UPDATE SR
    SET PresentDays = CONVERT(decimal(6, 2),RA.PresentCount),
         TotalDays = CONVERT(decimal(6, 2),RA.PresentCount) + CONVERT(decimal(6, 2),RA.AbsentCount)
    FROM sAssessment.tStudentRemark SR INNER JOIN
    #tResultAttendance RA 
    ON  SR.ExamId = RA.ExamId AND SR.AcademicId = RA.AcademicId
    --INNER JOIN sAssessment.tExamMaster EM ON EM.Id = SR.ExamId
    --WHERE EM.ExamSubGroupId = @rExamSubGroupId
 
 --Select * from sAssessment.tStudentRemark Order by UpdatedDateTime desc
 SELECT 1 AS RESULT
END
GO
PRINT N'Altering [sBiometric].[pMonthlyStatus]...';


GO
 
ALTER PROCEDURE [sBiometric].[pMonthlyStatus]  
    
 @rOrgId smallint,
     @rBatchId int,     
     @rYear smallint,
     @rMonth smallint,
	 @rDayOfMonth smallint,
	 @rAttendanceTypeId int = 1

WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  
BEGIN   
  
 CREATE Table #temptable  
 ( 
 ClassId bigint , DivisionId bigint,ClassDivisionName nvarchar(50) , ClassTeacherName nvarchar(100) ,
  P1 nvarchar(5),P2 nvarchar(5),P3 nvarchar(5),P4 nvarchar(5),P5 nvarchar(5),P6 nvarchar(5),P7 nvarchar(5),P8 nvarchar(5),P9 nvarchar(5),  
  P10 nvarchar(5),P11 nvarchar(5),P12 nvarchar(5),P13 nvarchar(5),P14 nvarchar(5),P15 nvarchar(5),P16 nvarchar(5),P17 nvarchar(5),  
  P18 nvarchar(5),P19 nvarchar(5),P20 nvarchar(5),P21 nvarchar(5),P22 nvarchar(5),P23 nvarchar(5),P24 nvarchar(5),P25 nvarchar(5),  
  P26 nvarchar(5),P27 nvarchar(5),P28 nvarchar(5),P29 nvarchar(5),P30 nvarchar(5),P31 nvarchar(5)  
 )  

 Insert into #temptable  
 (  
  ClassId,DivisionId,ClassDivisionName,  ClassTeacherName,P1
 ) 
 
( SELECT 	A.ClassId ,A.DivisionId,	
			vCD.ClassDivisionName,
			ISNULL(EM.FirstName+' '+ EM.LastName,'') AS ClassTeacherName,
		    CASE WHEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,01,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) !='' THEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,01,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) ELSE CASE WHEN COUNT(SR.AcademicId)=0 THEN CASE WHEN (Select [sCommon].[fCountAbsentStudent](A.DivisionId,  @rBatchId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-01')),@rAttendanceTypeId,0)) =0 THEN 'P' ELSE 'C' END ELSE 'C' END END  AS P1
			   
    FROM 
			sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId AND SM.StatusId=1 
			INNER JOIN sSetup.vClassDivision vCD ON vCD.ClassId=A.ClassId AND vCD.OrgId=@rOrgId
            AND vCD.DivisionId=A.DivisionId AND A.OrgId=vCD.OrgId AND A.OrgId=@rOrgId AND A.BatchId=@rBatchId AND vCD.IsObsolete=0 
            INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vCD.DivisionId  AND  DM.OrgId=@rOrgId
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId AND ISNULL(EM.IsOtherUser,0) = 0
            LEFT JOIN sAttendance.tStudentRegister SR ON A.Id = SR.AcademicId 		
			AND SR.AttendanceDate=CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-01'))		
            AND SR.AttendanceTypeId = @rAttendanceTypeId
			AND SR.IsPresent=1 		 	
            GROUP BY A.DivisionId,A.BatchId,vCD.ClassDivisionName,vCD.OrderIndex,EM.FirstName,EM.LastName,SM.StatusId,A.ClassId )
          
 DECLARE @intFlag INT
 DECLARE @DAY INT
SET @intFlag = 2
 DECLARE @COLFlag NVARCHAR(5)

WHILE (@intFlag <=@rDayOfMonth)
BEGIN
--    PRINT @intFlag; 
	
--	--SET @DAY=CASE WHEN LEN(@intFlag)=1 THEN CONCAT('0',@intFlag)  ELSE @intFlag END

	SET @COLFlag=   'P' + CAST(@intFlag AS varchar(12)); 

--	--update #temptable set @COLFlag= 
	
--UPDATE #temptable set P2= 

 --Insert into #temptable  
 --(  
 -- ClassDivisionName,  ClassTeacherName,P2
 --) 
UPDATE  T1 set @COLFlag= ( 
SELECT 				
			
		    CASE WHEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,@intFlag,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) !='' THEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,@intFlag,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) ELSE CASE WHEN COUNT(SR.AcademicId)=0 THEN CASE WHEN (Select [sCommon].[fCountAbsentStudent](A.DivisionId,  @rBatchId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-'+CONVERT(NVARCHAR(2),@intFlag))),@rAttendanceTypeId)) =0 THEN 'P' ELSE 'C' END ELSE 'C' END END 
			   
    FROM 


			sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId AND SM.StatusId=1 
			INNER JOIN sSetup.vClassDivision vCD ON vCD.ClassId=A.ClassId AND vCD.OrgId=@rOrgId
            AND vCD.DivisionId=A.DivisionId AND A.OrgId=vCD.OrgId AND A.OrgId=@rOrgId AND A.BatchId=@rBatchId AND vCD.IsObsolete=0 
            INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vCD.DivisionId  AND  DM.OrgId=@rOrgId
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId AND ISNULL(EM.IsOtherUser,0) = 0
            LEFT JOIN sAttendance.tStudentRegister SR ON A.Id = SR.AcademicId 		
			AND SR.AttendanceDate=CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-'+CONVERT(NVARCHAR(2),@intFlag)))		
            AND SR.AttendanceTypeId =@rAttendanceTypeId
			AND SR.IsPresent=1	 		
            GROUP BY A.DivisionId,A.BatchId,vCD.ClassDivisionName,vCD.OrderIndex,EM.FirstName,EM.LastName,SM.StatusId,A.ClassId ) FROM #temptable T1
			INNER JOIN #temptable T2  ON T2.ClassId =T1.ClassId AND T2.DivisionId=T1.DivisionId 
   

    SET @intFlag = @intFlag + 1;
END 
 
 SELECT * FROM #temptable
 
END
GO
PRINT N'Altering [sBiometric].[pTimeSheetListGet]...';


GO

ALTER PROCEDURE [sBiometric].[pTimeSheetListGet]
  @rEmployeeId bigint=0,  
  @rFromDate DateTime,  
  @rToDate DateTime,  
  @rStatus nvarchar(10) = '0',  
  @rOrgId int = 0  ,
  @rEmployeeName nvarchar(50) = '',
  @rStatusId int = 0,
  @rOrganizationDepartmentId int=0,
  @rOrgGroupDepartmentId int = 0
  
 WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  BEGIN   
  
 CREATE TABLE #TempMonthTrans  
 (  
 Id int Identity,  
 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)

		SELECT @lBatchID = Id FROM sSetup.tBatchMaster WHERE OrgId = @rOrgId AND IsActive = 1
   
 INSERT INTO #TempMonthTrans  
   
 	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 01) as datetime),D01,D01_IN,D01_OUT,D01_O,D01_L,D01_T,D01_E,D01_S FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	IF  Month(@rFromDate) <> 2 or (((YEAR(@rFromDate) % 4 = 0 AND YEAR(@rFromDate) % 100 <> 0) OR YEAR(@rFromDate) % 400 = 0 And Month(@rFromDate)  =2)) 
	BEGIN
		INSERT INTO #TempMonthTrans
		SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 29) as datetime),D29,D29_IN,D29_OUT,D29_O,D29_L,D29_T,D29_E,D29_S FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
		AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)
	END
	
	IF Month(@rFromDate) <> 2
	BEGIN
	INSERT INTO #TempMonthTrans
	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 30) as datetime),D30,D30_IN,D30_OUT,D30_O,D30_L,D30_T,D30_E,D30_S FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)
	END
	
	IF Month(@rFromDate) NOT IN (2,4,6,9,11)
	BEGIN
	INSERT INTO #TempMonthTrans
	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 31) as datetime),D31,D31_IN,D31_OUT,D31_O,D31_L,D31_T,D31_E,D31_S FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)
	END
	
	


 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 01) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),1,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),1,0,0,@rOrgId) else D01 end as D01,  
 --D01_IN,D01_OUT,D01_O,D01_L,D01_T,D01_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 02) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),2,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),2,0,0,@rOrgId) else D02 end as D02,  
 --D02_IN,D02_OUT,D02_O,D02_L,D02_T,D02_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 03) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),3,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),3,0,0,@rOrgId) else D03 end as D03,  
 --D03_IN,D03_OUT,D03_O,D03_L,D03_T,D03_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 04) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),4,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),4,0,0,@rOrgId) else D04 end as D04,  
 --D04_IN,D04_OUT,D04_O,D04_L,D04_T,D04_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 05) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),5,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),5,0,0,@rOrgId) else D05 end as D05,  
 --D05_IN,D05_OUT,D05_O,D05_L,D05_T,D05_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 06) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),6,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),6,0,0,@rOrgId) else D06 end as D06,  
 --D06_IN,D06_OUT,D06_O,D06_L,D06_T,D06_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 07) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),7,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),7,0,0,@rOrgId) else D07 end as D07,  
 --D07_IN,D07_OUT,D07_O,D07_L,D07_T,D07_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 08) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),8,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),8,0,0,@rOrgId) else D08 end as D08,  
 --D08_IN,D08_OUT,D08_O,D08_L,D08_T,D08_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 09) as datetime), case When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),9,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),9,0,0,@rOrgId) else D09 end as D09,  
 --D09_IN,D09_OUT,D09_O,D09_L,D09_T,D09_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 10) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),10,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),10,0,0,@rOrgId) else D10 end as D10,  
 --D10_IN,D10_OUT,D10_O,D10_L,D10_T,D10_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 11) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),11,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),11,0,0,@rOrgId) else D11 end as D11,  
 --D11_IN,D11_OUT,D11_O,D11_L,D11_T,D11_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 12) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),12,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),12,0,0,@rOrgId) else D12 end as D12,  
 --D12_IN,D12_OUT,D12_O,D12_L,D12_T,D12_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 13) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),13,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),13,0,0,@rOrgId) else D13 end as D13,  
 --D13_IN,D13_OUT,D13_O,D13_L,D13_T,D13_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 14) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),14,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),14,0,0,@rOrgId) else D14 end as D14,  
 --D14_IN,D14_OUT,D14_O,D14_L,D14_T,D14_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 15) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),15,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),15,0,0,@rOrgId) else D15 end as D15,  
 --D15_IN,D15_OUT,D15_O,D15_L,D15_T,D15_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 16) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),16,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),16,0,0,@rOrgId) else D16 end as D16,  
 --D16_IN,D16_OUT,D16_O,D16_L,D16_T,D16_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 17) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),17,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),17,0,0,@rOrgId) else D17 end as D17,  
 --D17_IN,D17_OUT,D17_O,D17_L,D17_T,D17_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 18) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),18,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),18,0,0,@rOrgId) else D18 end as D18,  
 --D18_IN,D18_OUT,D18_O,D18_L,D18_T,D18_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 19) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),19,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),19,0,0,@rOrgId) else D19 end as D19,  
 --D19_IN,D19_OUT,D19_O,D19_L,D19_T,D19_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 20) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),20,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),20,0,0,@rOrgId) else D20 end as D20,  
 --D20_IN,D20_OUT,D20_O,D20_L,D20_T,D20_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 21) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),21,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),21,0,0,@rOrgId) else D21 end as D21,  
 --D21_IN,D21_OUT,D21_O,D21_L,D21_T,D21_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 22) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),22,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),22,0,0,@rOrgId) else D22 end as D22,  
 --D22_IN,D22_OUT,D22_O,D22_L,D22_T,D22_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 23) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),23,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),23,0,0,@rOrgId) else D23 end as D23,  
 --D23_IN,D23_OUT,D23_O,D23_L,D23_T,D23_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 24) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),24,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),24,0,0,@rOrgId) else D24 end as D24,  
 --D24_IN,D24_OUT,D24_O,D24_L,D24_T,D24_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 25) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),25,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),25,0,0,@rOrgId) else D25 end as D25,  
 --D25_IN,D25_OUT,D25_O,D25_L,D25_T,D25_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 26) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),26,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),26,0,0,@rOrgId) else D26 end as D26,  
 --D26_IN,D26_OUT,D26_O,D26_L,D26_T,D26_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 27) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),27,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),27,0,0,@rOrgId) else D27 end as D27,  
 --D27_IN,D27_OUT,D27_O,D27_L,D27_T,D27_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 28) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),28,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),28,0,0,@rOrgId) else D28 end as D28,  
 --D28_IN,D28_OUT,D28_O,D28_L,D28_T,D28_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --IF  Month(@rFromDate) <> 2 or (((YEAR(@rFromDate) % 4 = 0 AND YEAR(@rFromDate) % 100 <> 0) OR YEAR(@rFromDate) % 400 = 0 And Month(@rFromDate)  =2))   
 --BEGIN  
 -- INSERT INTO #TempMonthTrans  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 29) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),29,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),29,0,0,@rOrgId) else D29 end as D29,D29_IN,D29_OUT,D29_O,D29_L,D29_T,D29_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
 --END  
   
 --IF Month(@rFromDate) <> 2  
 --BEGIN  
 --INSERT INTO #TempMonthTrans  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 30) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),30,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),30,0,0,@rOrgId) else D30 end as D30,  
 --D30_IN,D30_OUT,D30_O,D30_L,D30_T,D30_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
 --END  
   
 --IF Month(@rFromDate) NOT IN (2,4,6,9,11)  
 --BEGIN  
 --INSERT INTO #TempMonthTrans  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 31) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),31,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),31,0,0,@rOrgId) else D31 end as D31,  
 --D31_IN,D31_OUT,D31_O,D31_L,D31_T,D31_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
 --END  

 --SELECT * FROM #TempMonthTrans
 --SELECT TM.*,
 
       
		
 SELECT TM.Id,TM.EmployeeId,TM.Attn_Date,TM.PresentStatus AS OldPresentStatus,OGD.Title AS [Organization Group Department],
 
 CASE When (([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,@lBatchID ,ODM.Id ,@rOrgId )='H') AND (TM.FirstIn !='00:00'))  then 'PH'
 When (([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,@lBatchID ,ODM.Id ,@rOrgId )='H') AND (TM.FirstIn='00:00')) THEN 'H'  
 When (([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,@lBatchID ,ODM.Id ,@rOrgId )='W') AND (TM.FirstIn !='00:00'))  then 'PW'
 When (([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,@lBatchID ,ODM.Id ,@rOrgId )='W') AND (TM.FirstIn ='00:00'))  then 'W'
 When ((TM.PresentStatus='W')AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,@lBatchID ,ODM.Id ,@rOrgId )!='W') AND (TM.FirstIn !='00:00'))  then 'P'
 When ((TM.PresentStatus='PW')AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,@lBatchID ,ODM.Id ,@rOrgId )!='W') AND (TM.FirstIn !='00:00'))  then 'P'
 When ((TM.PresentStatus='W')AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,@lBatchID ,ODM.Id ,@rOrgId )!='W') AND (TM.FirstIn ='00:00'))  then 'A'
 WHEN ((TM.PresentStatus='W') AND (TM.FirstIn !='00:00')) THEN 'PW'

 ELSE
 TM.PresentStatus END as PresentStatus,
 TM.FirstIn,TM.LastOut,TM.OverTime,TM.LateBy,TM.Duration,TM.EarlyBy,TM.ShiftName, MT.Tot_Attn,
 MT.Tot_Attn + Tot_WeekOff + Tot_Holiday  AS TotalPresent,Tot_Abs AS TotalAbsent,Tot_WeekOff AS TotalWeekOff,  
 Tot_Holiday AS Totalholiday,Tot_Leave AS TotalLeave,EM.FirstName + ' ' + EM.LastName As ShortName,EM.Code as EmpCode ,   
 [sBiometric].[fEmployeeLeaveTypeGet] (TM.ATTN_DATE,TM.EmployeeId) AS LeaveStatus ,   
 [sBiometric].[fEmployeeLeaveTypePendingGet](TM.ATTN_DATE,TM.EmployeeId) AS LeavePendingStatus,   
 [sBiometric].[fEmployeeTravelGet](TM.ATTN_DATE,TM.EmployeeId) AS EmployeeTravel,  
 ISNULL(ELS.Id,0) AS EmployeeLateStatusId, 
 ISNULL(SM.Id,0) AS StatusId,  
 ISNULL(SM.Title,'') AS Status  
 FROM #TempMonthTrans TM   
 INNER JOIN sBiometric.tMonthTrans MT ON MT.EmployeeId=TM.EmployeeId 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(EJD.DateOfJoining,'1900/01/01'))
 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
 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 (( @rStatus = '1' AND (TM.Duration < '09:30')) OR ( @rStatus != '1' AND ((PresentStatus = @rStatus OR @rStatus='0'))))
 AND EM.OrgId = @rOrgId 
 AND ((EM.StatusId = @rStatusId) OR (@rStatusId = 0))
 AND((EJD.OrganizationDepartmentId=@rOrganizationDepartmentId) OR (@rOrganizationDepartmentId=0))
 AND ((EJD.OrgGroupDepartmentId = @rOrgGroupDepartmentId) OR (@rOrgGroupDepartmentId=0)) 
 AND (EM.FirstName + ' ' + EM.LastName like '%' + @rEmployeeName + '%' or @rEmployeeName = '')
 AND  ISNULL(EM.IsOtherUser,0) = 0
 AND (EJD.DateOfJoining<= @Lastdate OR ISNULL(EJD.DateOfJoining,'')='')
 AND (EJD.DateOfleaving>= @Firstdate OR ISNULL(EJD.DateOfleaving,'')='')
 --AND (TM.Duration < '09:30')
 Order By TM.EmployeeId,TM.Attn_Date
END
GO
PRINT N'Altering [sCanteen].[pRegisterForBreakGet]...';


GO
ALTER PROCEDURE [sCanteen].[pRegisterForBreakGet]

@rSourceTypeId int=0,
@rOrgId int,
@rDepartmentId int,
@rClassId int,
@rDivisionId int,
@rBreakTypeId int,
 @rCanteenId int
	 
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 
	IF(@rSourceTypeId=2003)
	BEGIN 		
		SELECT 		
		SA.Code,
		SA.Name,
		SA.OrganizationName,
		SA.DepartmentName,
		SA.ClassName+'-'+ SA.DivisionName As Div ,
		BTM.Title AS BreakType,
		SA.StudentId AS SourceId,
		'2003' AS SourceTypeId,
		CASE WHEN RB.SourceId is null THEN 'false' ELSE 'true' END AS Selected			      
    FROM 
    
	   sStudent.vStudentLastAcademic SA 
	   LEFT JOIN sCanteen.tRegisterForBreak RB ON SA.StudentId = RB.SourceId AND RB.SourceTypeId = 2003  AND   RB.BreakTypeId = @rBreakTypeId   
	   LEFT JOIN sCanteen.tBreakTypeMaster BTM	ON BTM.Id=  RB.BreakTypeId    AND BTM.CanteenId=@rCanteenId	
	  LEFT JOIN sCanteen.tCanteenMaster  CM ON CM.Id=BTM.CanteenId             
  WHERE 
		 ((SA.OrgId = @rOrgId) OR (@rOrgId = 0))
		 AND ((SA.DepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))
		 AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
		 AND ((SA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))	
		  -- AND BTM.CanteenId=@rCanteenId
       END
       
    ELSE 
	BEGIN 
       
		SELECT 
		EM.Code,
		EM.FirstName +' '+ EM.MiddleName +' '+ EM.LastName AS Name,
		OM.Title AS OrganizationName,
		DM.Title As DepartmentName,
		'' As Div ,
		BTM.Title AS BreakType,
		EM.Id AS SourceId,
		'95' AS SourceTypeId,
	
		CASE WHEN RB.SourceId is null THEN 'false' ELSE 'true' END AS Selected
			
      
    FROM 
    --sCanteen.tCanteenIssue CI   LEFT JOIN
	 [sHrm].[tEmployeeMaster] EM 
	 INNER JOIN [sHrm].[tEmployeeJobDetail] EJD ON EJD.EmployeeId = EM.Id
	 INNER JOIN [sSetup].[tDepartmentMaster] DM ON DM.Id = EJD.OrganizationDepartmentId
	 LEFT JOIN sCanteen.tRegisterForBreak RB ON EM.Id = RB.SourceId AND RB.SourceTypeId = 95 AND   RB.BreakTypeId = @rBreakTypeId 
	 LEFT JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgId
	  LEFT JOIN sCanteen.tBreakTypeMaster BTM	ON BTM.Id=  RB.BreakTypeId 	 AND BTM.CanteenId=@rCanteenId  
      LEFT JOIN sCanteen.tCanteenMaster  CM ON CM.Id=BTM.CanteenId  	 
            
  WHERE   
  
   ((EM.OrgId = @rOrgId) OR (@rOrgId = 0))
		 AND ((EJD.OrganizationDepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))
		--AND((RB.BreakTypeId = 11010006) OR (0 = 0))
		 
       END   
END
GO
PRINT N'Altering [sCertificate].[pRptBonafiedCertificateGet]...';


GO

 

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

DECLARE @lIsShowPhoto bit = 0
DECLARE @lIsOnPrePrinted bit = 0
DECLARE @lIsDisplayReligion bit=0
DECLARE @lIsDisplayImageHeader bit=0

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


	SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 124 AND SourceTypeId = 1016 AND SourceId = @rOrgId
	
	IF (@lConfigValue IS NULL) OR (@lConfigValue = 'False')
	SET @lIsShowPhoto = 0
	ELSE
	SET @lIsShowPhoto = 1
	
	SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 177 AND SourceTypeId = 1016 AND SourceId = @rOrgId
	
	IF (@lConfigValue IS NULL) OR (@lConfigValue = 'Default')
	BEGIN
	SET @lIsOnPrePrinted = 0
	SET @lIsDisplayImageHeader = 0
	END
	ELSE IF (@lConfigValue = 'Blank')
	BEGIN
	SET @lIsOnPrePrinted = 1
	SET @lIsDisplayImageHeader = 0
	END
	ELSE IF (@lConfigValue = 'Image')
	BEGIN
	SET @lIsOnPrePrinted = 0
	SET @lIsDisplayImageHeader = 1
	END
	
	
	SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 157 AND SourceTypeId = 1016 AND SourceId = @rOrgId
	
	IF (@lConfigValue IS NULL) OR (@lConfigValue = 'False')
	SET @lIsDisplayReligion = 0
	ELSE
	SET @lIsDisplayReligion = 1
	
	Select @lOrgGroupId = OrgGroupId From  sSetup.tOrganizationMaster Where Id = @rOrgId
	SELECT @lIDConfigValue =ItemValue From sConfig.tConfigurationSetup
	WHERE ConfigurationId = 236 AND SourceId = @lOrgGroupId
	--SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 158 AND SourceTypeId = 1016 AND SourceId = @rOrgId
	
	--IF (@lConfigValue IS NULL) OR (@lConfigValue = 'False')
	--SET @lIsDisplayImageHeader = 0
	--ELSE
	--SET @lIsDisplayImageHeader = 1	
	
	
	
	SELECT 	
			@rBuilder1 AS Builder1,
		    @rBuilder2 AS Builder2,
			B.Id,
			B.Number,
			B.AcademicId,
			SM.Code,
			--SM.FirstName+' '+SM.MiddleName+' '+SM.LastName AS Name,
			   [sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Name,
			CM.DisplayTitle+' - '+DM.DisplayTitle AS Class,
			BM.Title AS Batch,
			SM.FirstName,
			SM.MiddleName,
			SM.LastName,
			SO.DateOfBirth,
			ISNULL(SO.BirthDateInWord,'') AS DOBInWords,
			ISNULL(SO.BirthPlace,'') AS BirthPlace,
			ISNULL(SO.BirthTaluka,'') AS Taluka,
			ISNULL(SO.BirthDistrict,'')	AS District,		
			B.BonafideDate,
			ISNULL(SO.FamilyCast,'') AS Caste,
			ISNULL(SO.FamilySubCast,'') AS SubCaste,
			ISNULL(OM.CityName,'') AS City,
			ISNULL(OM.StateName,'') AS CityState,
			SO.GenderId,
			SI.StudentPhoto,
			OM.OrgLogo,
			OM.Title AS OrgTitle,
			--OM.StreetOne+' '+OM.StreetTwo+' '+OM.StreetThree AS OrgAddress,
			--OM.PhoneNo,
			SM.StatusId,
			A.RollNo,
			DM.OrderIndex AS DivisionOrder,
			ATM.Title AS AffiliationType,
			OM.ReportOrgTitle,
			OM.SmallAddress1,
			OM.SmallAddress2,
			OM.RegistrationDetail,
			ISNULL(RM.Title,'') AS ReligionName,
			@lIsShowPhoto AS IsShowPhoto,
			@lIsOnPrePrinted AS IsOnPrePrinted,
			@lIsDisplayReligion AS IsDisplayReligion,
			B.Remark AS ReceiptNo,
			SF.FatherName,
			SA.AdmissionDate,
			DP.Title AS DepartmentName,
			ISNULL(OM.DegreeAwarded,'') AS DegreeAwarded,
			@lIsDisplayImageHeader AS IsDisplayImageHeader,
			--OI.CertificateHeaderA4,
			REPLICATE(',',OM.LetterHeadMargin)    AS LetterHeadMargin,
			ISNULL(B.BonafiedReason,'') AS BonafiedReason,
			CT.Title AS Category,
			SF.MotherName,
			C.PermanentStreetOne,
			C.PermanentStreetTwo,
			C.PermanentStreetThree,
			C.PermanentCountry,
			C.PermanentState,
			C.PermanentCity,
			C.PermanentZipCode,
			C.PermanentContactNo,
			C.PresentStreetOne,
			C.PresentStreetTwo,
			C.PresentStreetThree,
			C.PresentCountry,
			C.PresentState,
			C.PresentCity,
			C.PresentContactNo,
			C.PresentZipCode,
			SM.SUId,
			SO.AdhaarNumber,
			CM.DisplayTitle AS ClassName,
			ISNULL(CTM.Nationality,'') AS Nationality,
			OM.PrincipalSignature,
			ISnull(AR.SourceId,0) AS StudentidForhostel,
			DM.DisplayTitle AS Divisionname,
			@lIDConfigValue AS ItemValue ,
			SM.RecordStatusId,
			SO.BirthState AS BirthState,
			CM1.Title AS AdmissionStandard,
			RRG.SchoolRemark1,
			RRG.SchoolRemark2,
			RRG.SchoolRemark3,
			SF.FatherAdhaarNumber AS FatherAadharNo,
			SF.MotherAdhaarNumber AS MotherAadharNo,
			ISNULL(OM.ReportOrgGroupTitle,'') AS ReportOrgGroupTitle,
			OM.ReportOrgTitle,
			--OI.CertificateHeaderA4,
			OI.CertificateHeaderA4Portrait AS CertificateHeaderA4,
			SM.Id AS StudentId,
			(CASE WHEN RRG.SchoolRequiredSignature IS NULL THEN NULL ELSE RRG.SchoolRequiredSignature END) AS SchoolRequiredSignature ,
			SO.UIDNumber,
			ISNULL(EI.EmployeeSign,0x) AS EmployeeSign,
			ISNULL(SA.AdmissionNumber,'') AS AdmissionNumber,
			BM.FromDate AS BatchFromDate,
			BM.ToDate AS BatchToDate ,

			ISNULL(U.DisplayTitle,'') AS UserName ,
		
		    ISNULL(EM.FirstName,'') +' '+ISNULL(EM.LastName,'') AS PrincipalName
	FROM 
			sCertificate.tBonafide B
			
			INNER JOIN sStudent.tAcademic A ON B.AcademicId=A.Id
			LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=A.StudentId
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId
			LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
			INNER JOIN sSetup.tDivisionMaster DM ON A.DivisionId = DM.Id  
			INNER JOIN sSetup.tClassMaster CM ON CM.Id= DM.ClassId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id=A.BatchId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId
			left JOIN sSetup.tOrgImages OI ON OI.OrgId = OM.Id
			INNER JOIN sSetup.tAffiliationMaster AM ON OM.AffiliationId = AM.Id
			INNER JOIN sSetup.tAffiliationTypeMaster ATM ON AM.AffiliationTypeId = ATM.Id
			LEFT JOIN sCommon.tReligionMaster RM ON SO.ReligionId=RM.Id
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SM.Id
			INNER JOIN sStudent.tStudentAdmission SA ON SA.StudentId = SM.Id
			LEFT JOIN sSetup.tClassMaster CM1 ON CM1.Id = SA.AdmissionStandardId
			INNER JOIN sSetup.tDepartmentMaster DP ON CM.DepartmentId = DP.Id
			LEFT JOIN sCommon.tCastCategoryMaster CT ON CT.Id = SO.CastCategoryId
			LEFT JOIN sStudent.tStudentCommunication C ON C.StudentId = A.StudentId
			LEFT JOIN sCommon.tCountryMaster CTM ON CTM.Id=SO.NationalityId
			LEFT JOIN SHostel.tAssignRoom Ar On Ar.SourceId=A.StudentId AND Ar.OrgGroupBatchId=@rOrgGroupBatchId 
			LEFT JOIN sCommon.tReportRemarkGroupOrg RRG ON RRG.OrgId = OM.Id AND ReportRemarkGroupId=6
			LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = DM.InchargeEmployeeId 
			LEFT JOIN sSecurity.tUser U	ON U.Id=B.CreatedUserId

			Left join sHrm.tEmployeeMaster EM on EM.Id = OM.EmployeeId
			--INNER JOIN sSetup.tTermMaster TM ON  TM.ID=
	WHERE 
			A.OrgId=@rOrgId
			AND	A.BatchId = @rBatchId 
			AND ((A.ClassId=@rClassId) OR (@rClassId=0))
			AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			AND ((SM.Code = @rCode) OR (ISNULL(@rCode,'') = ''))
			AND ((SM.FirstName = @rName) OR (ISNULL(@rName,'') = ''))
			--AND ((B.BonafideDate=@rBonafiedDate) OR (ISNULL(@rBonafiedDate,'')=''))
			AND ((B.Number=@rNumber) OR (@rNumber=''))
			AND ((B.Number >= @rFromNo) OR (@rFromNo=''))
			AND ((B.Number <= @rToNo) OR (@rToNo=''))
			AND ((B.BonafideDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((B.BonafideDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			--Group By B.AcademicId,SM.Code,SM.FirstName,SM.LastName,SM.MiddleName,CM.DisplayTitle,BM.Title,SO.DateOfBirth,SO.BirthDateInWord,
			--SO.BirthPlace,SO.BirthTaluka,SO.BirthDistrict,B.BonafideDate,OM.CityName,OM.StateName,SO.FamilyCast,SO.FamilySubCast,SO.GenderId,SI.StudentPhoto,SM.StatusId,
			--OM.OrgLogo,OM.PhoneNo,OM.Title,OM.StreetOne,OM.StreetTwo,OM.StreetThree
	END
GO
PRINT N'Altering [sCommunication].[pResultSheetUploadResultAdd]...';


GO

ALTER PROCEDURE [sCommunication].[pResultSheetUploadResultAdd]
	 
        @rId int,
        @rTitle nvarchar(100),
        @rExamDate date,
		@rDivisionId int,
		@rIsObsolete bit,
		@rBatchId int,
		@rOrgId int,
		@rCreatedUserId bigint,
		@rExamId int=null,
		@rUploadTypeId int = 1
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	 
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

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

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE sCommunication.tUploadResult
	    SET
			Title=@rTitle,
			ExamDate=@rExamDate,
			DivisionId=@rDivisionId,
			IsObsolete=@rIsObsolete,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate(),
			ExamId= @rExamId,
			UploadTypeId = @rUploadTypeId
	      WHERE Id = @rId
	 END  	
	SELECT @lNextNumber AS Result
	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sCommunication].[pStudentResultGet]...';


GO
 
ALTER PROCEDURE [sCommunication].[pStudentResultGet]
	 
	 --@rSourceTypeId smallint,
	 @rSourceId bigint,
	 @rDivisionId int,
	 @rBatchId int,
	 @rSyncedUploadResultId int=0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	IF (@rSourceId!=0)
	BEGIN
		SELECT @rDivisionId=DivisionId FROM sStudent.tAcademic		
		 WHERE StudentId=@rSourceId AND BatchId = @rBatchId
	END
		SELECT 
			@rSourceId AS SourceId,
			UR.Id,
			UR.Title,
			UR.ExamDate,
			S.Code ,
			BM.OrgId
			 
		FROM 
			sCommunication.tUploadResult UR  
			INNER JOIN sStudent.vStudentAcademic S ON S.DivisionId = UR.DivisionId AND UR.BatchId = S.BatchId 
			AND S.StudentId = @rSourceId AND S.BatchId = @rBatchId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = S.BatchId
		WHERE 
			UR.DivisionId=@rDivisionId
			AND UR.BatchId=@rBatchId
			AND UR.IsObsolete=0
			AND ( UR.Id > @rSyncedUploadResultId OR @rSyncedUploadResultId = 0)
			and UR.ExamDate <= replace(convert(varchar, sCommon.fGetDate(), 111), '/','-') 
			AND ISNULL(UR.UploadTypeId,1) = 1
				order by UR.ExamDate,S.RollNo,S.Code DESC
END
GO
PRINT N'Altering [sCommunication].[pUploadResultAdd]...';


GO
 

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

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

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE sCommunication.tUploadResult
	    SET
			Title=@rTitle,
			ExamDate=@rExamDate,
			DivisionId=@rDivisionId,
			IsObsolete=@rIsObsolete,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate(),
			UploadTypeId = @rUploadTypeId
			--ExamId= @rExamId
	      WHERE Id = @rId
	 END  	
	SELECT @lNextNumber AS Result
	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sCommunication].[pUploadResultGet]...';


GO
ALTER PROCEDURE [sCommunication].[pUploadResultGet]
	 @rId int,
	 @rTitle nvarchar(100),
	 @rFromDate date,
	 @rToDate date,
	 @rDivisionId int,
	 @rBatchId int,
	 @rIsSearch bit = 1
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	 IF @rIsSearch = 1
		BEGIN
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		END
	
	SELECT 
			UR.Id,
			UR.Title,
			UR.ExamDate,
			UR.DivisionId,
			BCD.ClassDivisionName AS Division,
			UR.IsObsolete,
			ISNULL(UR.UploadTypeId,1) AS UploadTypeId
  FROM 
            sCommunication.tUploadResult UR
        INNER JOIN sSetup.vBatchClassDivision BCD ON BCD.DivisionId=UR.DivisionId AND BCD.BatchId=@rBatchId
  WHERE 
		((UR.Id = @rId) OR (@rId = 0))
	AND ((UR.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
	AND ((UR.ExamDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	AND ((UR.ExamDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
	AND ((UR.DivisionId=@rDivisionId) OR (@rDivisionId=0))
	AND ((UR.BatchId=@rBatchId) OR (@rBatchId=0))
	order by UR.ExamDate DESC
END
GO
PRINT N'Altering [sFee].[pAutoAssignOptinalFee]...';


GO
ALTER PROCEDURE [sFee].[pAutoAssignOptinalFee]
	@rAcademicId bigint,	
	@rClassId int, 
	--@rFeeHeadId int,
	@rCreatedUserId bigint,
	@rOrgId int,
	@rOrgGroupId int,
	@rBatchId int,
	@rRoomId int=0,
	@rPickupPointId int=0,	 
	@rAdmissionCategoryId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	BEGIN TRANSACTION
	
	DECLARE @lItemValue nvarchar(20) = ''
	
	SELECT @lItemValue = CASE WHEN CS.Id IS NOT NULL THEN ISNULL(CS.ItemValue,'') ELSE ISNULL(CM.ItemValue,'') END
	FROM sConfig.tConfigurationMaster CM
	LEFT JOIN sConfig.tConfigurationSetup CS ON CM.Id = CS.ConfigurationId
	AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId WHERE CM.Id = 222

	DECLARE @lRoomCharge   decimal(10,2),@lBusCharge   decimal(10,2)
	DECLARE @lIsTranportOptional bit,@lIsTransportVariable  bit,@lIsHostelOptional  bit,@lIsHostelVariable  bit
	DECLARE @lTransportHeadId int, @lHostelHeadId int
	
IF(@lItemValue='Fee Head')
BEGIN
	IF (@rPickupPointId > 0)
	BEGIN
		SELECT @lBusCharge = RDM.Amount FROM sTransport.tBusRouteMaster RM INNER JOIN sTransport.tBusRouteDestinationMaster RDM
		ON RM.Id = RDM.BusRouteId WHERE RDM.Id = @rPickupPointId

		SELECT @lTransportHeadId = FeeHeadId FROM sFee.tFeeMainGroupOrgGroupwise WHERE OrgGroupId = @rOrgGroupId AND FeeMainGroupId = 4
		SELECT  @lIsTranportOptional =  FS.IsOptional ,@lIsTransportVariable = FS.IsVariable 
		FROM sFee.tFeeSetup FS INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
		WHERE FM.FeeHeadId = @lTransportHeadId
		AND FS.BatchId = @rBatchId AND FS.ClassId = @rClassId AND FS.AdmissionCategoryId = @rAdmissionCategoryId
		
		IF (@lIsTranportOptional = 1)
		BEGIN
			IF NOT EXISTS (SELECT 1  
			FROM sFee.tFeeOptional FO INNER JOIN sFee.tFeeSetup FS  ON FO.FeeSetupId = FS.Id  
			INNER JOIN  sFee.tFeeMaster FM ON FS.FeeId = FM.Id
			WHERE FM.FeeHeadId = @lTransportHeadId
			AND FS.BatchId = @rBatchId AND ClassId = @rClassId 
			AND FS.AdmissionCategoryId = @rAdmissionCategoryId
			--AND FS.IsOptional = 1 
			AND FO.SourceTypeId = 2001 AND FO.SourceId = @rAcademicId )
			BEGIN
				INSERT INTO sFee.tFeeOptional (FeeSetupId,SourceTypeId,SourceId,BatchId)
				SELECT FS.Id AS FeeSetupId,2001 AS SourceTypeId,@rAcademicId AS SourceId,@rBatchId AS BatchId 
				FROM sFee.tFeeSetup FS INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
				WHERE FM.FeeHeadId = @lTransportHeadId
				AND FS.BatchId = @rBatchId AND ClassId = @rClassId 
				AND AdmissionCategoryId = @rAdmissionCategoryId
				AND FS.IsOptional = 1
			END		
		END
		IF (@lIsTransportVariable = 1)
		BEGIN	
			IF NOT EXISTS (SELECT 1  
			FROM sFee.tFeeAllocation FO INNER JOIN sFee.tFeeSetup FS  ON FO.FeeSetupId = FS.Id  
			INNER JOIN  sFee.tFeeMaster FM ON FS.FeeId = FM.Id
			WHERE FM.FeeHeadId = @lTransportHeadId
			AND FS.BatchId = @rBatchId AND ClassId = @rClassId 
			AND FS.AdmissionCategoryId = @rAdmissionCategoryId
			--AND FS.IsOptional = 1 
			AND FO.SourceTypeId = 2001 AND FO.SourceId = @rAcademicId )
			BEGIN
				INSERT INTO sFee.tFeeAllocation
				SELECT  2001,@rAcademicId,FS.Id,@lBusCharge,0,0,0,'',NULL,NULL,@rCreatedUserId,sCommon.fGetDate(),NULL,NULL,'','',''
				FROM sFee.tFeeSetup FS INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
				WHERE FM.FeeHeadId = @lTransportHeadId
				AND FS.BatchId = @rBatchId AND ClassId = @rClassId 
				AND AdmissionCategoryId = @rAdmissionCategoryId
				AND FS.IsVariable = 1
			END
		END
	END

	IF (@rRoomId > 0)
	BEGIN
		SELECT @lRoomCharge = RCM.RoomCharge FROM sHostel.tRoomMaster RM INNER JOIN sHostel.tRoomCategoryMaster RCM
		ON RM.RoomCategoryId = RCM.Id WHERE RM.Id = @rRoomId

		SELECT @lHostelHeadId = FeeHeadId FROM sFee.tFeeMainGroupOrgGroupwise WHERE OrgGroupId = @rOrgGroupId AND FeeMainGroupId = 5
		SELECT  @lIsHostelOptional = FS.IsOptional,@lIsHostelVariable = FS.IsVariable  
		FROM sFee.tFeeSetup FS INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
		WHERE FM.FeeHeadId = @lHostelHeadId
		AND FS.BatchId = @rBatchId AND ClassId = @rClassId AND AdmissionCategoryId = @rAdmissionCategoryId
	IF (@lIsHostelOptional = 1)
	BEGIN
		IF NOT EXISTS (SELECT 1  
		FROM sFee.tFeeOptional FO INNER JOIN sFee.tFeeSetup FS  ON FO.FeeSetupId = FS.Id  
		INNER JOIN  sFee.tFeeMaster FM ON FS.FeeId = FM.Id
		WHERE FM.FeeHeadId = @lHostelHeadId
		AND FS.BatchId = @rBatchId AND ClassId = @rClassId 
		AND FS.AdmissionCategoryId = @rAdmissionCategoryId
		--AND FS.IsOptional = 1 
		AND FO.SourceTypeId = 2001 AND FO.SourceId = @rAcademicId )
		BEGIN
			INSERT INTO sFee.tFeeOptional (FeeSetupId,SourceTypeId,SourceId,BatchId)
			SELECT FS.Id AS FeeSetupId,2001 AS SourceTypeId,@rAcademicId AS SourceId,@rBatchId AS BatchId 
			FROM sFee.tFeeSetup FS INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
			WHERE FM.FeeHeadId = @lHostelHeadId
			AND FS.BatchId = @rBatchId AND ClassId = @rClassId 
			AND AdmissionCategoryId = @rAdmissionCategoryId
			AND FS.IsOptional = 1
		END
	END
	IF (@lIsHostelVariable = 1)
	BEGIN
		IF NOT EXISTS (SELECT 1  
		FROM sFee.tFeeAllocation FA INNER JOIN sFee.tFeeSetup FS  ON FA.FeeSetupId = FS.Id  
		INNER JOIN  sFee.tFeeMaster FM ON FS.FeeId = FM.Id
		WHERE FM.FeeHeadId = @lHostelHeadId
		AND FS.BatchId = @rBatchId AND ClassId = @rClassId 
		AND FS.AdmissionCategoryId = @rAdmissionCategoryId
		--AND FS.IsVariable = 1 
		AND FA.SourceTypeId = 2001 AND FA.SourceId = @rAcademicId )
		BEGIN
			INSERT INTO sFee.tFeeAllocation
			SELECT  2001,@rAcademicId,FS.Id,@lRoomCharge,0,0,0,'',NULL,NULL,@rCreatedUserId,sCommon.fGetDate(),NULL,NULL,'','',''
			FROM sFee.tFeeSetup FS INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
			WHERE FM.FeeHeadId = @lHostelHeadId
			AND FS.BatchId = @rBatchId AND ClassId = @rClassId 
			AND AdmissionCategoryId = @rAdmissionCategoryId
			AND FS.IsVariable = 1
		END
	END
END
END

ELSE IF(@lItemValue='Fee')
BEGIN
	DECLARE @lCount int=0
	DECLARE @lIsOptionalTranportFee bit=0
	DECLARE @lIsVariableTransportFee bit=0
	
	CREATE TABLE #TempFeeMainGroupOptionalFee
	(
		[AutoId] int identity,
		[OrgId] [int] NOT NULL,
		[FeeMainGroupId] [int] NOT NULL,
		[FeeId] [int] NOT NULL
	)
	
	INSERT INTO #TempFeeMainGroupOptionalFee SELECT * FROM sFee.tFeeMainGroupOptionalFee WHERE OrgId = @rOrgId AND FeeMainGroupId = 4
		
	SELECT @lCount = COUNT(AutoId) From #TempFeeMainGroupOptionalFee
	
	IF (@rPickupPointId > 0)
	BEGIN
		SELECT @lBusCharge = RDM.Amount FROM sTransport.tBusRouteMaster RM INNER JOIN sTransport.tBusRouteDestinationMaster RDM
		ON RM.Id = RDM.BusRouteId WHERE RDM.Id = @rPickupPointId
		WHILE (@lCount > 0)
		BEGIN
			DECLARE @lTransportFeeId int=0
			SELECT @lTransportFeeId=FeeId FROM #TempFeeMainGroupOptionalFee WHERE AutoId = @lCount
			
			SELECT  @lIsOptionalTranportFee =  FS.IsOptional ,@lIsVariableTransportFee = FS.IsVariable 
			FROM sFee.tFeeSetup FS WHERE FS.FeeId = @lTransportFeeId
			AND FS.BatchId = @rBatchId AND FS.ClassId = @rClassId AND FS.AdmissionCategoryId = @rAdmissionCategoryId
			
			IF(@lTransportFeeId > 0)
			BEGIN 
				IF (@lIsOptionalTranportFee = 1)
				BEGIN
					IF NOT EXISTS (SELECT 1  
					FROM sFee.tFeeOptional FO INNER JOIN sFee.tFeeSetup FS  ON FO.FeeSetupId = FS.Id  
					WHERE FS.FeeId = @lTransportFeeId
					AND FS.BatchId = @rBatchId AND ClassId = @rClassId 
					AND FS.AdmissionCategoryId = @rAdmissionCategoryId
					AND FO.SourceTypeId = 2001 AND FO.SourceId = @rAcademicId )
					BEGIN
						INSERT INTO sFee.tFeeOptional (FeeSetupId,SourceTypeId,SourceId,BatchId)
						SELECT FS.Id AS FeeSetupId,2001 AS SourceTypeId,@rAcademicId AS SourceId,@rBatchId AS BatchId 
						FROM sFee.tFeeSetup FS WHERE FS.FeeId = @lTransportFeeId
						AND FS.BatchId = @rBatchId AND ClassId = @rClassId 
						AND AdmissionCategoryId = @rAdmissionCategoryId
						AND FS.IsOptional = 1
					END		
				END
				IF (@lIsVariableTransportFee = 1)
				BEGIN	
					IF NOT EXISTS (SELECT 1  
					FROM sFee.tFeeAllocation FO INNER JOIN sFee.tFeeSetup FS  ON FO.FeeSetupId = FS.Id  
					WHERE FS.FeeId = @lTransportFeeId
					AND FS.BatchId = @rBatchId AND ClassId = @rClassId 
					AND FS.AdmissionCategoryId = @rAdmissionCategoryId
					AND FO.SourceTypeId = 2001 AND FO.SourceId = @rAcademicId )
					BEGIN
						INSERT INTO sFee.tFeeAllocation
						SELECT  2001,@rAcademicId,FS.Id,@lBusCharge,0,0,0,'',NULL,NULL,@rCreatedUserId,sCommon.fGetDate(),NULL,NULL,'','',''
						FROM sFee.tFeeSetup FS WHERE FS.FeeId = @lTransportFeeId
						AND FS.BatchId = @rBatchId AND ClassId = @rClassId 
						AND AdmissionCategoryId = @rAdmissionCategoryId
						AND FS.IsVariable = 1
					END
				END
			END
			SET @lCount = @lCount -1
		END
	END
	
	TRUNCATE TABLE #TempFeeMainGroupOptionalFee 
	INSERT INTO #TempFeeMainGroupOptionalFee SELECT * FROM sFee.tFeeMainGroupOptionalFee WHERE OrgId = @rOrgId AND FeeMainGroupId = 5
	
	SET @lCount = 0
	DECLARE @lIsOptionalHostelFee bit=0
	DECLARE @lIsVariableHostelFee bit=0
	SELECT @lCount = COUNT(AutoId) From #TempFeeMainGroupOptionalFee
	
	IF (@rRoomId > 0)
	BEGIN
		
		SELECT @lRoomCharge = RCM.RoomCharge FROM sHostel.tRoomMaster RM INNER JOIN sHostel.tRoomCategoryMaster RCM
		ON RM.RoomCategoryId = RCM.Id WHERE RM.Id = @rRoomId
		WHILE (@lCount > 0)
		BEGIN
			DECLARE @lHostelFeeId int=0
			SELECT @lHostelFeeId=FeeId FROM #TempFeeMainGroupOptionalFee WHERE AutoId = @lCount
			
			SELECT  @lIsOptionalHostelFee = FS.IsOptional,@lIsVariableHostelFee = FS.IsVariable  
			FROM sFee.tFeeSetup FS WHERE FS.FeeId = @lHostelFeeId
			AND FS.BatchId = @rBatchId AND ClassId = @rClassId AND AdmissionCategoryId = @rAdmissionCategoryId
			
			IF(@lHostelFeeId > 0)
			BEGIN
				 
				IF (@lIsOptionalHostelFee = 1)
				BEGIN
					
					IF NOT EXISTS (SELECT 1  
					FROM sFee.tFeeOptional FO INNER JOIN sFee.tFeeSetup FS  ON FO.FeeSetupId = FS.Id  
					WHERE FS.FeeId = @lHostelFeeId
					AND FS.BatchId = @rBatchId AND ClassId = @rClassId 
					AND FS.AdmissionCategoryId = @rAdmissionCategoryId
					AND FO.SourceTypeId = 2001 AND FO.SourceId = @rAcademicId )
					BEGIN
						INSERT INTO sFee.tFeeOptional (FeeSetupId,SourceTypeId,SourceId,BatchId)
						SELECT FS.Id AS FeeSetupId,2001 AS SourceTypeId,@rAcademicId AS SourceId,@rBatchId AS BatchId 
						FROM sFee.tFeeSetup FS
						WHERE FS.FeeId = @lHostelFeeId
						AND FS.BatchId = @rBatchId AND ClassId = @rClassId 
						AND AdmissionCategoryId = @rAdmissionCategoryId
						AND FS.IsOptional = 1
					END
				END
				IF (@lIsVariableHostelFee = 1)
				BEGIN
				
					IF NOT EXISTS (SELECT 1  
					FROM sFee.tFeeAllocation FA INNER JOIN sFee.tFeeSetup FS  ON FA.FeeSetupId = FS.Id  
					WHERE FS.FeeId = @lHostelFeeId
					AND FS.BatchId = @rBatchId AND ClassId = @rClassId 
					AND FS.AdmissionCategoryId = @rAdmissionCategoryId
					AND FA.SourceTypeId = 2001 AND FA.SourceId = @rAcademicId )
					BEGIN
						INSERT INTO sFee.tFeeAllocation
						SELECT  2001,@rAcademicId,FS.Id,@lRoomCharge,0,0,0,'',NULL,NULL,@rCreatedUserId,sCommon.fGetDate(),NULL,NULL,'','',''
						FROM sFee.tFeeSetup FS
						WHERE FS.FeeId = @lHostelFeeId
						AND FS.BatchId = @rBatchId AND ClassId = @rClassId 
						AND AdmissionCategoryId = @rAdmissionCategoryId
						AND FS.IsVariable = 1
					END
				END
			END
			SET @lCount = @lCount -1
		END	
	END		
END	
SELECT 1 AS Result    
COMMIT TRANSACTION
IF OBJECT_ID('#TempFeeMainGroupOptionalFee') IS NOT NULL
DROP TABLE #TempFeeMainGroupOptionalFee
	END TRY
	BEGIN CATCH
		IF OBJECT_ID('#TempFeeMainGroupOptionalFee') IS NOT NULL
		DROP TABLE #TempFeeMainGroupOptionalFee 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
END
GO
PRINT N'Altering [sFee].[pFeeCustomSearchGet]...';


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

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


GO
ALTER PROCEDURE [sFrontOffice].[pVisitorLogGet]
          
           @rVisitorId int=0,
           --@rOutTimeFrom datetime,
           --@rOutTimeTo datetime,
           @rFromVisitDate datetime,
           @rToVisitDate datetime,
           @rOrgId int=0,
           @rWhomToMeetName nvarchar(100)='',
           @rIsPrintView bit=0,
           @rOrgGroupId int =0,
           @rTypeId int=0 ,
		   @rStatusId int=0 
           --@rIsWildCardSearch bit
          
AS
SET NOCOUNT ON

		--IF @rIsWildCardSearch = 1
		--BEGIN
			SET @rWhomToMeetName = sCommon.fSearchStringGet(@rWhomToMeetName)
		--END
		Declare @GatePassConfig nvarchar(20)=''
		SELECT @GatePassConfig =ItemValue From sConfig.tConfigurationSetup WHERE ConfigurationId = 241 AND SourceId = @rOrgGroupId


BEGIN
SELECT  
	   VL.Id As VisitorId,
       VL.VisitorName,
       VL.NoOfVisitor,
       VL.PurposeOfVisit,
       VL.WhomToMeet AS WhomToMeetId,
	   (isnull(case when isnull(VL.WhomToMeet,0)!=0 then isnull(EM.EmployeeName,'') else ISNULL(VL.WhomToMeetName,'') end,'' )+ (case when isnull(VL.StudentId,0)!=0 AND isnull(VL.WhomToMeet,0)!=0 then ',' else '' end)+
	   isnull(case when  isnull(VL.StudentId,0)!=0 Then sStudent.fStudentNameGet(STM.FirstName, STM.MiddleName,STM.LastName, OM1.StudentNameFormatId) end,'')) AS WhomToMeetName,
	   ISNULL(VL.InTime,'00:00') AS InTime,
       ISNULL(VL.OutTime,'00:00') AS OutTime,
       ISNULL(VL.VisitDate,'1900-01-01 00:00:00') AS VisitDate,
       --VL.CreatedDateTime ,
       (CASE  WHEN @rIsPrintView=1 THEN 
				VL.VisitorPhoto		
			ELSE ISNULL(VL.VisitorPhoto, CONVERT(VARBINARY(MAX), 0)) END) AS VisitorPhoto,
       --ISNULL(VL.VisitorPhoto, CONVERT(VARBINARY(MAX), 0)) AS VisitorPhoto,
       VL.OrgId,
       ISNULL(OM.DisplayTitle,'') AS Organization,
       ISNULL(Remark,'') AS Remark,
       @GatePassConfig AS ConfigValue,
	   ISNUll(VisitorContactNumber,'') AS VisitorContactNumber,
	   ISNULL(StudentId,0) AS StudentId,
	   (CASE WHEN ISNULL(VL.TypeId,'')!='' then case when VL.TypeId=1 then 'Visitor' else 'Parents' end
			 when ISNULL(VL.StudentId,0)=0 THEN 'Visitor'
			 ELSE 'Parents' END) AS VisitorType,
	   (CASE WHEN ISNULL(VL.OutTime,'00:00:00')='00:00:00' THEN 0
			 ELSE 1 END) AS InOutStatus,
		OM.OrgGroupId AS OrgGroupId,
		SM.Title as Status,
		ISNULL(VL.StatusId,0) as StatusId,
		(CASE WHEN ISNULL(VL.TypeId,'')!='' then case when VL.TypeId=1 then 1 else 2 end
			 when ISNULL(VL.StudentId,0)=0 THEN 1
			 ELSE 2 END) AS VisitorTypeId
		
  FROM  sFrontOffice.tVisitorLog VL 
  INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=VL.OrgId
  LEFT JOIN sCommon.tStatusMaster SM ON SM.Id = VL.StatusId
  Left Join  sHrm.vExtEmployeeMaster EM on EM.EmployeeId=VL.WhomToMeet
  left Join sStudent.tStudentMaster STM On STM.Id=VL.StudentId  
  left JOIN sSetup.tOrganizationMaster AS OM1 ON STM.OrgId = OM1.Id 
 
  WHERE 
	(VL.OrgId=@rOrgId OR @rOrgId=0) AND OM.OrgGroupId=@rOrgGroupId
	AND (VL.Id=@rVisitorId OR @rVisitorId=0)
	AND (((VL.WhomToMeetName LIKE @rWhomToMeetName) OR  (isnull(EM.EmployeeId,0)>0 AND EM.EmployeeName Like  @rWhomToMeetName) OR (isnull(STM.Id,0)>0 AND sStudent.fStudentNameGet(STM.FirstName, STM.MiddleName,STM.LastName, OM1.StudentNameFormatId) like  @rWhomToMeetName)) OR (ISNULL(@rWhomToMeetName,'')=''))
	AND (VL.VisitDate>=@rFromVisitDate OR ISNULL(@rFromVisitDate,'')='')
	AND (VL.VisitDate<=@rToVisitDate OR ISNULL(@rToVisitDate,'')='')
	AND ((ISNULL(VL.TypeId,0)=0 AND (ISNULL(VL.StudentId,1) = @rTypeId) OR  (@rTypeId=0) OR (((VL.StudentId > 0 AND @rTypeId=2) OR  @rTypeId=0)))  OR (ISNULL(VL.TypeId,0)!=0 AND ((VL.TypeId=@rTypeId) or (@rTypeId=0)))) -- Visitor 
	AND ((VL.StatusId = @rStatusId) OR (ISNULL(@rStatusId,0) = 0)) 
	 -- Parents
  ORDER BY VL.VisitDate DESC,VL.InTime DESC
END
GO
PRINT N'Altering [sHostel].[pHostelWardenGet]...';


GO
ALTER PROCEDURE [sHostel].[pHostelWardenGet]
	 @rHostelId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 		
		
	SELECT 
			HM.Id,
			HM.Title,
		    HM.Remark,
		    HM.HostelTypeId,
		    HM.NoOfRooms,	
			HM.IsObsolete,
			HW.EmployeeId,
			EM.FirstName+' '+EM.LastName as EmployeeName,
			HM.ReportOrgTitle,
			HM.SmallAddress1,
			HM.SmallAddress2
  FROM 
			sHostel.tHostelMaster HM
			LEFT JOIN [sHostel].[tHostelWarden] HW ON HW.HostelId=HM.Id
			LEFT JOIN sHRM.tEmployeeMaster EM ON EM.Id=HW.EmployeeId AND ISNULL(EM.IsOtherUser,0) = 0
WHERE 
			(HM.Id=@rHostelId OR @rHostelId=0) 

			 order by EmployeeName
		
END
GO
PRINT N'Altering [sHrm].[pLeaveHierarchyListingGet]...';


GO


ALTER PROCEDURE [sHrm].[pLeaveHierarchyListingGet]  
(  
	@rOrgId int,  
	@rLeaveHierarchyLevelId bigint = 0,
    --@rId bigint = 0,  
    @rEmployeeId  bigint,     
    @rFromDate date,  
    @rLeaveTypeId int,  
    @rTodate date,  
    @rOrgGroupBatchId int,  
    @rEmployeeCode nvarchar(100)='',  
    @rEmployeeName nvarchar(100)='',  
    @rStatusId int = 0,  
    --@rOrgGroupId int,  
    --@rIsSearchLeaveHierarchyWise int = 0,  
    @rDepartmentId int
	
	--@rUserId bigint = 0
 )  
AS  
SET NOCOUNT ON  
  
BEGIN  
      
   SELECT   
      L.[Id] AS LeaveId,  
	  LHL.AutoId AS LeaveHierarchyLevelId,
      L.[EmployeeId],  
      L.[ReportDate],  
      L.[FromDate],  
      L.[ToDate],  
      L.[LeavePeriodId],  
      L.[LeaveTypeId],  
      L.[LeaveReason],  
      LPM.Title AS LeavePeriod,  
      LTM.Title AS LeaveType,  
      --EM.EmployeeName,  
	  [sHrm].[fEmployeeNameGet](EM.FirstName , EM.MiddleName, EM.LastName,ISNULL(OM.EmployeeNameFormatId,1)) AS EmployeeName,
      EM.Code AS EmployeeCode,  
      L.NoOfLeave,  
      ISNULL(LHL.StatusId,0) AS StatusId,  
      ISNULL(SM.Title,'Pending') AS StatusName,  
      ISNULL(L.LeaveRemark,'') AS  LeaveRemark,  
      OM.DisplayTitle AS OrganizationName,  
      --L.ActionByEmployeeId,  
      --CASE WHEN ISNULL(L.ActionByEmployeeId,0) = 0 AND L.StatusId = 549 THEN NULL  
      --WHEN L.ActionByEmployeeId = 0 AND L.StatusId != 549 THEN US.DisplayTitle  
      --ELSE EMP.FirstName + ' ' + EMP.LastName END AS ActionByEmployee,  
      OM.Id AS OrgId,  
      L.BatchId AS BatchId,  
      EM.DepartmentId AS DepartmentId,  
      EM.DepartmentName As DepartmentName
  FROM   
	  sHrm.tLeaveHierarchyLevel LHL
	  INNER JOIN sHrm.tLeave L  ON L.Id = LHL.LeaveId
      INNER JOIN sSetup.tBatchMaster BM ON BM.Id = L.BatchId    
      INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId  
	  --INNER JOIN sSecurity.tUserOrganization UO ON UO.OrgId = OM.Id AND UO.UserId = @rUserId
      INNER JOIN sHrm.tLeavePeriodMaster LPM ON LPM.Id = L.LeavePeriodId  
      INNER JOIN sHrm.tLeaveTypeMaster LTM ON LTM.Id = L.LeaveTypeId  
      INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = L.EmployeeId  
      --INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = L.EmployeeId  
      INNER JOIN sCommon.tStatusMaster SM ON SM.Id = LHL.StatusId  
      --LEFT JOIN sHrm.tEmployeeMaster EMP ON EMP.Id = L.ActionByEmployeeId AND ISNULL(EMP.IsOtherUser,0)=0 
      --LEFT JOIN sSecurity.tUser US ON US.Id = L.UpdatedUserId 
	  --INNER JOIN sSecurity.tUserAccess U ON U.SourceId = EM.DepartmentId AND U.SourceTypeId=2017     
  WHERE   
      (LHL.AutoId = @rLeaveHierarchyLevelId OR @rLeaveHierarchyLevelId = 0)     
      AND ((L.FromDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))  
      AND ((L.FromDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))  
      AND (L.LeaveTypeId = @rLeaveTypeId OR @rLeaveTypeId = 0)        
      AND BM.OrgGroupBatchId = @rOrgGroupBatchId  
      AND ((L.OrgId = @rOrgId) OR (@rOrgId = 0))  
      AND (EM.Code = @rEmployeeCode OR ISNULL(@rEmployeeCode,'') = '')  
      AND (EM.EmployeeName like @rEmployeeName+'%' OR ISNULL(@rEmployeeName,'') = '')  
      AND (LHL.StatusId = @rStatusId OR @rStatusId = 0) 
      AND ((EM.DepartmentId = @rDepartmentId ) OR (@rDepartmentId = 0)) 
	  AND ISNULL(EM.IsOtherUser,0)=0 
	  AND (LHL.ActionByEmployeeId = @rEmployeeId) 
END
GO
PRINT N'Altering [sHrm].[pRptEmployeeProfileGet]...';


GO
 
 
 
 
ALTER PROCEDURE [sHrm].[pRptEmployeeProfileGet]
(

		@rBuilder1 nvarchar(max)='',
		@rBuilder2 nvarchar(max)='',
		@rPayrollId int,
		@rPayrollGroupId int,
		@rPayrollYearId int,
    	@rEmployeeId bigint,
		@rEmployeeCode nvarchar(200),
		@rEmployeeName nvarchar(200),
	    @rOrderByField nvarchar(20)='',
		@rOrgId int = 0,
		@rDepartmentId int = 0,
		@rStatusId int = 0,
	 @rEmployeeGroupId int = 0
)
AS
SET NOCOUNT ON

BEGIN

	--DECLARE @lConfigValue nvarchar(50) = ''
	--DECLARE @lIsOnPrePrinted bit = 0
	--DECLARE @lIsDisplayImageHeader bit=0

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

		SELECT 
				@rOrderByField AS OrderByField,
				@rBuilder1 AS Builder1,
				@rBuilder2 AS Builder2,
				EM.EmployeeId AS EmployeeId,
				tEM.FirstName +' '+tEM.MiddleName+' '+ tEM.LastName AS Name,
				DM.Id AS DepartmentId,
				DM.Title AS DepartmentName,
				CONVERT(date,EJD.DateOfJoining) AS DateOfJoining,
				EM.Code AS Code,
				CONVERT(date,EJD.DateOfleaving) AS DateOfleaving,
				EDM.Title AS Designation,
				EPD.Qualification,
				EM.GenderTitle,
				CONVERT(date,EPD.DateOfBirth) AS DateOfBirth,
				EPD.UIDNumber,
				EC.PersonalEmail AS Email,
				ESO.BankName,
				ESO.AccountNumber,
				ESO.EPFNumber,
				ESO.PanNumber,
				EC.MobileNumber,
				ISNULL(DATEDIFF(YY,EJD.DateOfJoining,EJD.DateOfleaving),'')AS EXPYEAR,
				ISNULL(DATEDIFF(MM,EJD.DateOfJoining,EJD.DateOfleaving),'') AS EXPMONTH,
				EM.FirstName,
				EM.LastName,
				tEM.Number,
				--@lIsOnPrePrinted AS IsOnPrePrinted,
				--@lIsDisplayImageHeader AS IsDisplayImageHeader,
				--ISNULL(OI.PayrollHeaderA4,0x) AS PayrollHeader
				(CASE WHEN ISNULL(PM.HeaderDisplayId,1) = 3 THEN ISNULL(PM.PayrollHeader,0x) ELSE NULL END) AS PayrollHeader,
				--ISNULL(PM.PayrollHeader,0x) AS PayrollHeader,
				ISNULL(PM.HeaderDisplayId,1)AS HeaderDisplayId
		FROM 
			sPayroll.tPayProcess PP
			INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId = PP.ID 
			INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = PPE.EmployeeId 
			INNER JOIN sHrm.tEmployeeMaster tEM ON tEM.Id=PPE.EmployeeId
			INNER JOIN sPayroll.tPayrollYearMaster PY ON PP.PayrollYearId = PY.Id
			INNER JOIN  sHrm.tEmployeeCommunications EC ON EC.EmployeeId=EM.EmployeeId
			INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId=EM.EmployeeId
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.EmployeeId
			INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EJD.OrganizationDepartmentId
			INNER JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id=EJD.EmployeeDesignationId
			INNER JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.EmployeeId=PPE.EmployeeId	
			--LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = tEM.OrgID
			INNER JOIN sPayroll.tPayrollMaster PM ON PY.PayrollId = PM.Id
		WHERE 
				(EM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
			AND((PY.PayrollId=@rPayrollId) OR (@rPayrollId=0))
			 AND (PPE.PayrollGroupId = @rPayrollGroupId OR @rPayrollGroupId = 0) 
			 AND ((EM.Code Like '%' +  @rEmployeeCode + '%' ) OR (@rEmployeeCode = ''))
			 AND ((EM.EmployeeName Like '%' + @rEmployeeName  + '%') OR (@rEmployeeName = ''))
			 AND (PP.PayrollYearId = @rPayrollYearId OR @rPayrollYearId = 0) 
			 AND ((tEM.OrgID = @rOrgId) OR (@rOrgId = 0))
			 AND (EM.DepartmentId = @rDepartmentId OR @rDepartmentId = 0)
			 AND ((tEM.StatusId = @rStatusId) OR (@rStatusId = 0))
			 AND ((EM.EmployeeGroupId = @rEmployeeGroupId) OR (@rEmployeeGroupId = 0))
		END
GO
PRINT N'Altering [sMis].[pRptResultAnalysisExamWiseWithAttendanceGet]...';


GO


ALTER PROCEDURE [sMis].[pRptResultAnalysisExamWiseWithAttendanceGet]
	 
		@rBuilder1 nvarchar(max)='',
		@rBuilder2 nvarchar(max)='', 
		
		@rOrgGroupBatchId int,
		@rExamId int,
		@rStrOrgMainGroupId nvarchar(max),
		@rStrOrgSubGroupId nvarchar(max),
		@rStrOrgId nvarchar(max),
		@rStrDepartmentId nvarchar(max),
		@rStrClassId nvarchar(max)

	 
	
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
--Select 
--		0 AS OrgMainGroupId,
--	    '' AS OrgMainGroupName,
--		0 AS OrgSubGroupId,
--		'' AS SubGroupName,
--		'' AS OrgName,
--		0 AS DepartmentId,
--		0 AS OrgId,
--		'' AS Code,
--		'' AS Name,
--		0 AS RollNo,
--		0 AS AcademicId,			
--		'' AS Class,
--		0 As ClassId,
--		'' AS Division,
--		0 AS DivisionId,
--		'' AS Exam,
--		0 AS SubjectId,	
--		'' AS SubjectCode,
--		'' AS SubjectName,
--		--RD.SubjectGrade,
--		--R.ResultGrade,
--		--BM.OrgGroupBatchId,
--		--RD.Obtain,
--		'' AS SubjectGrade,
--		--R.Percentage,
--		'' AS ResultGrade,
--		@rExamId AS ExamId,
--		0 AS Attendance


			
 
 
 
		Select Distinct
		OMGM.Id AS OrgMainGroupId,
		OMGM.Code AS OrgMainGroupName,
		OSGM.Id AS OrgSubGroupId,
		OSGM.Code AS SubGroupName,
		OM.Title AS OrgName,
		DM.Id AS DepartmentId,
		--CM.Id,
		stum.OrgId,
		Stum.Code,
		[sStudent].[fStudentNameGet](stum.FirstName , StuM.MiddleName, StuM.LastName,OM.StudentNameFormatId ) AS Name,
		A.RollNo,
		A.Id AS AcademicId,			
		CM.DisplayTitle AS Class,
		CM.Id As ClassId,
		DM.DisplayTitle AS Division,
		DM.Id AS DivisionId,
		ETM.Code AS Exam,
		--CS.Id AS SubjectId,	
		--SM.Code AS SubjectCode,
		--SM.Title AS SubjectName,
		--RD.SubjectGrade,
		--R.ResultGrade,
		--BM.OrgGroupBatchId,
		--RD.Obtain,
		--[sAssessment].[fGetConfigGrade](stum.OrgId,RD.Obtain) AS SubjectGrade,
		--R.Percentage,
		[sAssessment].[fGetConfigGrade](stum.OrgId,R.Percentage)AS ResultGrade,
		@rExamId AS ExamId,
		(CASE WHEN (SR.PresentDays<>0 AND SR.TotalDays<>0) THEN ROUND(((CAST(SR.PresentDays AS FLOAT)/CAST(SR.TotalDays AS FLOAT))*100),2) ELSE 0 END)AS Attendance,
		--((CAST(SR.PresentDays AS FLOAT)/CAST(SR.TotalDays AS FLOAT))*100)AS Attendance
		ISNULL(SR.PresentDays,0)AS PresentDays,
		ISNULL(SR.TotalDays,0)AS TotalDays
		
		
		 from sStudent.tStudentMaster Stum 
		INNER JOIN  sStudent.tAcademic A ON Stum.Id=A.StudentId
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
		INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
		INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
		INNER JOIN sSetup.tOrganizationMaster OM ON Stum.OrgId = OM.Id
		INNER JOIN sAssessment.tResult R ON A.Id=R.AcademicId
		--INNER JOIN sAssessment.tResultDetail RD ON R.Id = RD.ResultId
		--INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
		INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
		INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.EXAMSUBGROUPID
		INNER JOIN sAssessment.tExamTypeMaster ETM ON ETM.Id=ESGM.ExamTypeId
		--INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
		--INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId
		INNER JOIN sSetup.tOrgSubGroupMaster OSGM ON OSGM.Id = OM.OrgSubGroupId
		INNER JOIN sSetup.tOrgMainGroupMaster OMGM ON OMGM.Id = OSGM.OrgMainGroupId	
		INNER JOIN sSetup.tDepartmentMaster DeptM ON DeptM.Id=CM.DepartmentId
		LEFT JOIN sAssessment.tStudentRemark SR ON R.AcademicId = SR.AcademicId AND R.ExamId = SR.ExamId

		WHERE		
			ETM.Id=@rExamId
			AND (OMGM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit(@rStrOrgMainGroupId,','))OR @rStrOrgMainGroupId='')
			AND (OSGM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit(@rStrOrgSubGroupId,','))OR @rStrOrgSubGroupId='')
			AND (OM.Id IN (SELECT cast (item as int) FROM  sCommon.fnsplit (@rStrOrgId,','))OR @rStrOrgId='')
			AND (DM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit  (@rStrDepartmentId,','))OR @rStrDepartmentId='')
			AND (CM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit  (@rStrClassId,','))OR @rStrClassId='')
			AND BM.OrgGroupBatchId = @rOrgGroupBatchId


END
GO
PRINT N'Altering [sPayroll].[pPayrollMasterAdd]...';


GO




ALTER PROCEDURE [sPayroll].[pPayrollMasterAdd]
	 
	        @rId int,
			@rCode nvarchar(100),
			@rTitle nvarchar(100),
			@rCreatedUserId bigint,       
			@rOrgGroupId smallint,
			@rIsActive bit,
			@rIsFormulawise bit =0,
			@rHeaderDisplayId tinyint=0
			--@rPayrollHeader varbinary(max)=NULL
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	 
	IF(@rId = 0)	
	BEGIN
		If Exists(select Id from sPayroll.tPayrollMaster where Code=@rCode AND OrgGroupId=@rOrgGroupId)
			BEGIN
			select -101 as Result
			RETURN
		END 
		If Exists(select Id from sPayroll.tPayrollMaster where Title=@rTitle AND OrgGroupId=@rOrgGroupId)
			BEGIN
			select -102 as Result
			RETURN
		END 
	END
	ELSE
	BEGIN
		If Exists(select Id from sPayroll.tPayrollMaster where Code=@rCode AND OrgGroupId=@rOrgGroupId AND Id<>@rId)
		Begin
			select -101 as Result
			RETURN
		End 
		If  Exists(select Id from sPayroll.tPayrollMaster where Title=@rTitle AND OrgGroupId=@rOrgGroupId AND Id<>@rId)
		Begin
			select -102 as Result
			RETURN
		End
	END
	 
	 BEGIN TRANSACTION	
 IF(@rId = 0)	
BEGIN
    
	DECLARE @lNextNumber INT     

EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sPayroll.tPayrollMaster',@lNextNumber = @lNextNumber output
 
INSERT INTO [sPayroll].[tPayrollMaster]
           (
			[Id],
           [Code],
           [Title],
           [CreatedUserId],
           [CreatedDateTime],
           --[UpdatedUserId],
           --[UpdatedDateTime],
           [OrgGroupId],
           [IsActive],
           IsFormulawise,
		   HeaderDisplayId
           )
     VALUES
           (
            @lNextNumber,
           @rCode ,
           @rTitle ,
           @rCreatedUserId, 
           sCommon.fGetDate(),
           --@rCreatedUserId,
           --sCommon.fGetDate(), 
           @rOrgGroupId, 
           @rIsActive,
           @rIsFormulawise,
		   @rHeaderDisplayId
		  -- @rPayrollHeader
           ) 
           
           	INSERT INTO sSecurity.tUserAccess
           (
           SourceTypeId
           ,SourceId
           ,[UserId]
           
           
           )
		   SELECT 
		   2019
		   ,@lNextNumber
		   ,@rCreatedUserId	
           
           SELECT @lNextNumber AS Result
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE [sPayroll].[tPayrollMaster]
	    SET
			code = @rCode,
			Title = @rTitle,
			UpdatedUserId= @rCreatedUserId,
			UpdatedDateTime =sCommon.fGetDate(),	
			IsActive = @rIsActive,
			IsFormulawise = @rIsFormulawise,
			HeaderDisplayId = @rHeaderDisplayId
			--PayrollHeader = @rPayrollHeader
	      
	      WHERE Id = @rId 	 
	       SELECT @lNextNumber AS Result  
	 END  
		 
	
		  COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sPayroll].[pPayrollMasterGet]...';


GO

ALTER PROCEDURE [sPayroll].[pPayrollMasterGet]
	 
	 @rId int = 0,
	 @rTitle nvarchar(100),
	 @rCode nvarchar(100),
	 @rOrgGroupId smallint
		
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	  BEGIN 
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
			SET @rCode = sCommon.fSearchStringGet(@rCode)
	  END	 
	SELECT 
		PM.Id,
		PM.Code,
		PM.Title,
		PM.IsActive,
		ISNULL(PM.IsFormulawise,0 ) As IsFormulawise,
		PM.PayrollHeader,
		ISNULL(PM.HeaderDisplayId,1) AS HeaderDisplayId   
  FROM 
      sPayroll.tPayrollMaster PM
  WHERE  
        ((PM.Id = @rId) OR (@rId = 0))
        AND  ((PM.Title LIKE @rTitle) OR (ISNULL(@rTitle,'') = '')) 
        AND  ((PM.Code LIKE @rCode) OR (ISNULL(@rCode,'') = ''))
		AND PM.OrgGroupId = @rOrgGroupId
		order by PM.CreatedDateTime desc
END
GO
PRINT N'Altering [sPayroll].[pRptEmployeePaybillDetail]...';


GO
 
 

ALTER PROCEDURE [sPayroll].[pRptEmployeePaybillDetail]
	
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rEmployeeId bigint,
	 @rEmployeeCode nvarchar(200),
	 @rEmployeeName nvarchar(200),
	 @rDepartmentId int,
	 @rForMonth int,
	 @rForYear int,
	 @rPayrollId int,
	 @rPayrollGroupId int,
	 @rPayrollYearId int,
	 @rOrderByField nvarchar(20)='',
	 @rOrgId int = 0,
	 @rStatusId int = 0,
	 @rEmployeeGroupId int = 0
	  
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN  
	
	DECLARE @lFirstDate Date
	DECLARE @lLasteDate Date
	
	IF(@rForMonth!=0 and @rForYear!=0)
	BEGIN
		SET @lFirstDate = CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'/'+CONVERT(NVARCHAR(2),@rForMonth)+'/01'))
		SET @lLasteDate=DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,@lFirstDate)+1,0))
	END
	 
	DECLARE @lBasicPayElementId int
	SELECT @lBasicPayElementId = Id FROM sPayroll.tPayElement WHERE PayrollId = @rPayrollId AND PayElementDefaultId = 1

	SET @rEmployeeCode = sCommon.fSearchStringGet(@rEmployeeCode)
    SET @rEmployeeName = sCommon.fSearchStringGet(@rEmployeeName)


	--DECLARE @lConfigValue nvarchar(50) = ''
	--DECLARE @lIsOnPrePrinted bit = 0
	--DECLARE @lIsDisplayImageHeader bit=0

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

	SELECT 
		@rOrderByField AS OrderByField,
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		EM.EmployeeId, 
		PP.ID As PayProcessId,
		PPE.ID AS PayProcessEmployeeId,
		PP.SalaryMonth,
		PP.SalaryYear,
		tEM.FirstName +' '+tEM.MiddleName+' '+tEm.LastName AS EmployeeName,
		EM.Code AS EmployeeCode,
		PPE.TotalEarning,
		PPE.TotalDeduction,
		PPE.NetAmount,
		(CASE WHEN PayElementId = @lBasicPayElementId then PPE.TotalEarning else 0 END) AS TotalEarningTotal,
		(CASE WHEN PayElementId = @lBasicPayElementId then PPE.TotalDeduction else 0 END) AS TotalDeductionTotal,
		(CASE WHEN PayElementId = @lBasicPayElementId then PPE.NetAmount else 0 END) AS NetAmountTotal,
		ISNULL(ESO.BankName,'') AS BankName,
		ISNULL(ESO.AccountNumber,'') AS AccountNumber,
		MM.Title AS MonthName,
		ISNULL(PPE.WorkingDays,0) AS WorkingDays,
		(ISNULL(PPE.WorkingDays,0) - ISNULL(PPE.Lwp,0)) AS PresentDays,
		--ISNULL(PPE.Lwp,0) AS AbsentDays,
		ISNULL(PPE.GrossBasic,0) AS GrossBasic,
		PY.Title AS PayrollYearName,
		PGM.Id AS PayrollGroupId,
		PGM.Title AS PayrollGroupName,
		ISNULL(ESO.IFSCNumber,'') AS IFSCNumber,
		tEM.FirstName,
		tEm.LastName,
		ISNULL(ESO.AccountHolderName,'')AS AccountHolderName,
		tEM.Number,
		EM.EmployeeDesignation,
		--@lIsOnPrePrinted AS IsOnPrePrinted,
		--@lIsDisplayImageHeader AS IsDisplayImageHeader,
		--ISNULL(OI.PayrollHeaderA4,0x) AS PayrollHeader
		(CASE WHEN ISNULL(PM.HeaderDisplayId,1) = 3 THEN ISNULL(PM.PayrollHeader,0x) ELSE NULL END) AS PayrollHeader,
		--ISNULL(PM.PayrollHeader,0x) AS PayrollHeader,
		ISNULL(PM.HeaderDisplayId,1)AS HeaderDisplayId

		
	FROM sPayroll.tPayProcess PP 
	INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId=PP.ID
	INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = PPE.EmployeeId 
	INNER JOIN sHrm.tEmployeeMaster tEM ON tEM.Id = PPE.EmployeeId 
	INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
	INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID 
	LEFT JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.EmployeeId=PPE.EmployeeId	
	INNER JOIN sCommon.tMonthMaster MM ON MM.Id=PP.SalaryMonth	
	INNER JOIN sPayroll.tPayrollYearMaster PY ON PP.PayrollYearId = PY.Id 
	INNER JOIN sPayroll.tPayrollGroupMaster PGM ON PGM.Id = PPE.PayrollGroupId
	--LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = tEM.OrgID
	INNER JOIN sPayroll.tPayrollMaster PM ON PY.PayrollId = PM.Id
where 
      (PPE.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
      AND ((EM.Code Like '%' +  @rEmployeeCode + '%' ) OR (@rEmployeeCode = ''))
	  AND ((EM.EmployeeName Like '%' + @rEmployeeName  + '%') OR (@rEmployeeName = ''))
	  AND (EM.DepartmentId = @rDepartmentId OR @rDepartmentId = 0)
	  AND (PP.SalaryMonth = @rForMonth OR @rForMonth = 0)
	  AND (PP.SalaryYear = @rForYear OR @rForYear = 0) 
	  AND ((PY.PayrollId=@rPayrollId) OR (@rPayrollId=0))
	  AND (PPE.PayrollGroupId = @rPayrollGroupId OR @rPayrollGroupId = 0) 
	  AND (PP.PayrollYearId = @rPayrollYearId OR @rPayrollYearId = 0) 
	  --AND ((EM.DateOfleaving >= @lFirstDate) OR ISNULL(EM.DateOfleaving,'') = '')
   --   AND ((EM.DateOfJoining <= @lLasteDate) OR ISNULL(EM.DateOfJoining,'') = '')
	  AND ((tEM.OrgID = @rOrgId) OR (@rOrgId = 0))
	  AND ((tEM.StatusId = @rStatusId) OR (@rStatusId = 0))
	  AND ((EM.EmployeeGroupId = @rEmployeeGroupId) OR (@rEmployeeGroupId = 0))
END
GO
PRINT N'Altering [sPayroll].[pRptEmployeePFDetail]...';


GO
 
 
 
ALTER PROCEDURE [sPayroll].[pRptEmployeePFDetail]
	
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rEmployeeId bigint,
	 @rEmployeeCode nvarchar(200),
	 @rEmployeeName nvarchar(200),
	 @rForMonth int,
	 @rForYear int,
	 @rPayrollId int,
	 @rPayrollGroupId int,
	 @rPayrollYearId int,
	 @rOrderByField nvarchar(20)='',
	 @rOrgId int = 0,
	 @rDepartmentId int = 0,
	 @rStatusId int = 0,
	 @rEmployeeGroupId int = 0
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 


	SET @rEmployeeCode = sCommon.fSearchStringGet(@rEmployeeCode)
	SET @rEmployeeName = sCommon.fSearchStringGet(@rEmployeeName)

	--DECLARE @lConfigValue nvarchar(50) = ''
	--DECLARE @lIsOnPrePrinted bit = 0
	--DECLARE @lIsDisplayImageHeader bit=0

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

	SELECT 
		@rOrderByField AS OrderByField,
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,	
		ISNULL(ESO.EPFNumber,'') AS PFNumber,
		EM.EmployeeId,
		tEM.FirstName +' '+tEM.MiddleName+' '+ tEM.LastName AS EmployeeName,
		EM.Code AS EmployeeCode,
		ISNULL(PPE.GrossBasic,0) AS GrossBasic,
		PFS.PfSalaryLimit,
		PFS.FpsSalaryLimit,
		PFS.EmployeePfPercent,
		PFS.EmployerPfPercent,
		PFS.EmployerFpsPercent,
		PFS.AdminChargesPercent,
		PFS.EdliPercent,
		PFS.InspectionChargesPercent,
		PFPro.PayProcessElementId,
		PFPro.EmployeePfAmount,
		PFPro.EmployerPfAmount,
		PFPro.EmployerFpsAmount,
		PFPro.AdminChargesAmount,
		PFPro.EdliChargesAmount,
		PFPro.InspectionChargesAmount,
		PY.Title AS PayrollYearName,
		PP.SalaryMonth,
		
		PP.SalaryYear,
	    MM.Title AS MonthName,
	    (ISNULL(AT.TotalWorkingDays,0) - ISNULL(AT.LWP,0)) AS WorkingDays,
	   (SELECT ISNULL(SUM(PPE.Amount),0) FROM sPayroll.tPayProcessElement PPE INNER JOIN sPayroll.tPayElement P  
	    ON PPE.PayElementId =  P.ID  WHERE PPE.PayProcessEmployeeId = PE.PayProcessEmployeeId AND PayElementId IN 
		(SELECT DependentPayElementId FROM sPayroll.tPaySetupDependent PD INNER JOIN sPayroll.tPaySetup PS ON  PD.PaySetupId = PS.ID
		INNER JOIN sPayroll.tPayElement PE ON PS.PayElementId = PE.ID 
		--WHERE PS.PayrollId = @rPayrollId 
		--AND PS.PayrollYearId = @rPayrollYearId 
		AND PE.PayElementDefaultId = 56 AND ((PS.SourceTypeId=2020 AND ESO.PayrollGroupId=PS.SourceId) OR (PS.SourceTypeId=95 AND tEM.Id=PS.SourceId)))
		) 
		AS Salary,
	    ISNULL(ESO.UAN,'') AS UAN,
	    PPE.TotalEarning,
	    EM.FirstName,
		EM.LastName,
		tEM.Number,
		--@lIsOnPrePrinted AS IsOnPrePrinted,
		--@lIsDisplayImageHeader AS IsDisplayImageHeader,
		--ISNULL(OI.PayrollHeaderA4,0x) AS PayrollHeader
		(CASE WHEN ISNULL(PM.HeaderDisplayId,1) = 3 THEN ISNULL(PM.PayrollHeader,0x) ELSE NULL END) AS PayrollHeader,
		--ISNULL(PM.PayrollHeader,0x) AS PayrollHeader,
		ISNULL(PM.HeaderDisplayId,1)AS HeaderDisplayId
	FROM 
		sPayroll.tPayProcess PP 
		INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId=PP.ID
		INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = PPE.EmployeeId
		INNER JOIN sHrm.tEmployeeMaster tEM ON tEM.Id=PPE.EmployeeId
		LEFT JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.EmployeeId=EM.EmployeeId
		INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
		INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID 
		INNER JOIN sPayroll.tPfProcess PFPro ON PFPro.PayProcessElementId=PE.ID
		INNER JOIN sPayroll.tPayrollYearMaster PY ON PP.PayrollYearId = PY.Id
		INNER JOIN sPayroll.tPfSetup PFS ON PFS.PayrollYearId = PY.Id 
		INNER JOIN sCommon.tMonthMaster MM ON MM.Id=PP.SalaryMonth
		INNER JOIN sHrm.tEmployeeAttendance AT ON AT.EmployeeId=EM.EmployeeId 
		--AND AT.ForMonth =PP.SalaryMonth AND AT.ForYear =PP.SalaryYear
		AND AT.ForMonth=PP.SalaryMonth AND AT.ForYear =PP.SalaryYear
		INNER JOIN sPayroll.tPayrollMaster PM ON PY.PayrollId = PM.Id
		LEFT JOIN 
		(
		SELECT PE.Amount,PPE.WorkingDays,PPE.PayProcessId,PPE.EmployeeId, PPE.PayrollGroupId
		FROM sPayroll.tPayProcess PP 
		INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId=PP.ID
		INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = PPE.EmployeeId
		INNER JOIN sHrm.tEmployeeMaster tEM ON tEM.Id=PPE.EmployeeId
		LEFT JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.EmployeeId=EM.EmployeeId
		INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
		INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID AND P.PayElementDefaultId = 1
		INNER JOIN sPayroll.tPayrollYearMaster PY ON PP.PayrollYearId = PY.Id		
		WHERE 
		(PPE.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
		AND ((EM.Code Like @rEmployeeCode) OR (@rEmployeeCode = ''))
		AND ((EM.EmployeeName Like @rEmployeeName) OR (@rEmployeeName = ''))		
		--AND ((PY.PayrollId=@rPayrollId) OR (@rPayrollId=0))
		AND (PPE.PayrollGroupId = @rPayrollGroupId OR @rPayrollGroupId = 0) 
		AND ((tEM.OrgID = @rOrgId) OR (@rOrgId = 0))
		AND (EM.DepartmentId = @rDepartmentId OR @rDepartmentId = 0)	
		AND ((tEM.StatusId = @rStatusId) OR (@rStatusId = 0))
		AND ((EM.EmployeeGroupId = @rEmployeeGroupId) OR (@rEmployeeGroupId = 0))	
		) A ON A.PayProcessId = PPE.PayProcessId AND A.EmployeeId = PPE.EmployeeId  AND A.PayrollGroupId =  PPE.PayrollGroupId
		--LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = tEM.OrgID
		
WHERE 
		(PPE.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
		AND ((EM.Code Like @rEmployeeCode) OR (@rEmployeeCode = ''))
		AND ((EM.EmployeeName Like @rEmployeeName) OR (@rEmployeeName = ''))
		AND ((PY.PayrollId=@rPayrollId) OR (@rPayrollId=0))
		AND (PPE.PayrollGroupId = @rPayrollGroupId OR @rPayrollGroupId = 0) 
		AND ((tEM.OrgID = @rOrgId) OR (@rOrgId = 0))		
		AND (EM.DepartmentId = @rDepartmentId OR @rDepartmentId = 0)
		AND ((tEM.StatusId = @rStatusId) OR (@rStatusId = 0))
		AND ((EM.EmployeeGroupId = @rEmployeeGroupId) OR (@rEmployeeGroupId = 0))
END
GO
PRINT N'Altering [sPayroll].[pRptEmployeeSalaryDetail]...';


GO
 


ALTER PROCEDURE [sPayroll].[pRptEmployeeSalaryDetail]
	
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rEmployeeId bigint,
	 @rEmployeeCode nvarchar(200),
	 @rEmployeeName nvarchar(200),
	 @rDepartmentId int,
	 @rForMonth int,
	 @rForYear int,
	 @rPayrollId int,
	 @rPayrollGroupId int,
	 @rPayrollYearId int,
	 @rReportId smallint=0,
	 @rOrderByField nvarchar(20)='',
	 @rMonths nvarchar(50)='',
	 @rOrgId int = 0,
	 @rStatusId int = 0,
	 @rEmployeeGroupId int = 0
	 
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN  
	
	DECLARE @lMonthDay int=0
	SELECT @lMonthDay=[sCommon].[fGetDaysInMonth] (@rForMonth,@rForYear)
	
	--DECLARE @lConfigValue nvarchar(50) = ''
	--DECLARE @lIsOnPrePrinted bit = 0
	--DECLARE @lIsDisplayImageHeader bit=0

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


	DECLARE @lFirstDate Date
	DECLARE @lLasteDate Date
	IF(@rForMonth!=0 and @rForYear!=0)
	BEGIN
		SET @lFirstDate = CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'/'+CONVERT(NVARCHAR(2),@rForMonth)+'/01'))
		SET @lLasteDate=DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,@lFirstDate)+1,0))
	END
	
	DECLARE @lBasicPayElementId int
	SELECT @lBasicPayElementId = Id FROM sPayroll.tPayElement WHERE PayrollId = @rPayrollId AND PayElementDefaultId = 1
	
	SET @rEmployeeCode = sCommon.fSearchStringGet(@rEmployeeCode)
    SET @rEmployeeName = sCommon.fSearchStringGet(@rEmployeeName)

	SELECT
		@rOrderByField AS OrderByField,
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2, 
		EM.EmployeeId, 
		PP.ID As PayProcessId,
		PPE.ID AS PayProcessEmployeeId,
		PP.SalaryMonth,
		PP.SalaryYear,
		tEM.FirstName +' '+tEM.MiddleName+' '+tEm.LastName AS EmployeeName,
		EM.Code AS EmployeeCode,
		EM.EmployeeDesignation,
		EM.EmployeeGrade,
		ESO.EPFNumber,
		ESO.PanNumber,
		PPE.TotalEarning,		
		PPE.TotalDeduction,
		PPE.NetAmount,
		(CASE WHEN PayElementId = @lBasicPayElementId then PPE.TotalEarning else 0 END) AS TotalEarningTotal,
		(CASE WHEN PayElementId = @lBasicPayElementId then PPE.TotalDeduction else 0 END) AS TotalDeductionTotal,
		(CASE WHEN PayElementId = @lBasicPayElementId then PPE.NetAmount else 0 END) AS NetAmountTotal,
		PE.Amount As PPEAmount,
		P.Title AS PayElementTitle,
		P.ID AS PayElementId,
		P.PayElementTypeId,
		ISNULL(ESO.BankName,'') AS BankName,
		ISNULL(ESO.AccountNumber,'') AS AccountNumber, 
		MM.Title AS MonthName,
		P.Title AS PayElementName,
		P.Code AS PayElementCode,
		(CASE WHEN PayElementId = @lBasicPayElementId then ISNULL(PPE.WorkingDays,@lMonthDay) else 0 END) AS WorkingDays,
		--ISNULL(EWD.WorkingDays,@lMonthDay) AS WorkingDays,
		(CASE WHEN PayElementId = @lBasicPayElementId then PPE.Lwp else 0 END) AS Lwp,
		(CASE WHEN PayElementId = @lBasicPayElementId then ISNULL(PPE.PaidLeave,0) else 0 END) AS PaidLeave,
		P.SortOrder,
		PY.Title AS PayrollYearName,
		PGM.Id AS PayrollGroupId,
		PGM.Title AS PayrollGroupName,
		PPE.GrossBasic,
		P.PayElementDefaultId,
		ISNULL(EPD.Qualification,'') AS Qualification,
		EJD.DateOfJoining AS DateOfAppointment,
		ISNULL(ESO.PayScale,'') AS PayScale,
		EPD.DateOfBirth,
		ISNULL(ROG.SelectableField,'') AS SelectableField,
		RGO.SchoolRequiredSignature ,
		RGO.SchoolRemark1,
		ISNULL(ESO.BasicPay,0) AS BasicPay,
		DAY(DATEADD(DD,-1,DATEADD(mm, DATEDIFF(mm, 0, CONVERT(DATE,CONVERT(nvarchar,PP.SalaryMonth) +'/01/'+CONVERT(nvarchar,PP.SalaryYear)) ) + 1, 0))) AS MonthDay,
		ESO.UAN,
		EPD.GenderId,
		ISNULL(PPR.Remark,'') AS PayProcessEmployeeRemark,
		tEM.FirstName,
		tEm.LastName,
		EM.DateOfJoining,
		OI.CertificateHeaderA4Portrait AS CertificateHeaderA4,
		ISNULL(REPLACE(REPLACE(
		(SELECT STUFF(
		(
		  SELECT  ' ' + Leave FROM -- create comma separated values
			(
					Select '<br>'+('<b>'+ LTM.Code +'</b>' +' - '+ CAST(SUM(CAST(L.NoOfLeave AS FLOAT)) AS varchar(50)) ) + '</br>'AS Leave 
					from 
					sHrm.tLeaveTypeMaster LTM  
					INNER JOIN sHrm.tLeave L ON  EM.EmployeeId = L.EmployeeId 
					INNER JOIN sCommon.tStatusMaster SM ON SM.Id=L.StatusId
					Where EM.EmployeeId=EM.EmployeeId AND LTM.OrgId=EM.OrgId AND LTM.IsObsolete = 0 
					AND LTM.Id = L.LeaveTypeId AND SM.Id=550
					AND (YEAR(L.FromDate) = @rForYear OR @rForYear=0) 
					AND (MONTH(L.FromDate) = @rForMonth OR @rForMonth=0) 
					GROUP BY LTM.Code
					)AS T FOR XML PATH('')
		)
		,1,1,'')),'&lt;','<'),'&gt;','>')
		,'') AS LeaveCount,
		tEM.Number,
		--@lIsOnPrePrinted AS IsOnPrePrinted,
		--@lIsDisplayImageHeader AS IsDisplayImageHeader,
		--ISNULL(OI.PayrollHeaderA4,0x) AS PayrollHeader
		(CASE WHEN ISNULL(PM.HeaderDisplayId,1) = 3 THEN ISNULL(PM.PayrollHeader,0x) ELSE NULL END) AS PayrollHeader,
		--ISNULL(PM.PayrollHeader,0x) AS PayrollHeader,
		ISNULL(PM.HeaderDisplayId,1)AS HeaderDisplayId
		
	FROM 
	sPayroll.tPayProcess PP 
	INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId = PP.ID 
	INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = PPE.EmployeeId 
	INNER JOIN sHrm.tEmployeeMaster tEM ON tEM.Id = PPE.EmployeeId 
	INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
	INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID AND P.IsIncludeInPaySlip = 1
	LEFT JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.EmployeeId=PPE.EmployeeId	
	LEFT JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId=PPE.EmployeeId	
	LEFT JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=PPE.EmployeeId	
	INNER JOIN sCommon.tMonthMaster MM ON MM.Id=PP.SalaryMonth
	INNER JOIN sPayroll.tPayrollYearMaster PY ON PP.PayrollYearId = PY.Id 
	INNER JOIN sPayroll.tPayrollGroupMaster PGM ON PGM.Id = PPE.PayrollGroupId
	LEFT JOIN sCommon.tReportOrgGroup ROG ON ROG.OrgGroupId=PY.OrgGroupId AND (ROG.ReportId = @rReportId OR @rReportId = 0) 
	LEFT JOIN sCommon.tReportRemarkGroupOrg RGO ON RGO.OrgId = tEM.OrgID AND RGO.ReportRemarkGroupId =  4
	LEFT JOIN sPayroll.tPayProcessEmployeeRemark PPR ON PPR.SalaryMonth = PP.SalaryMonth
	AND PPR.SalaryYear = PP.SalaryYear AND PPR.PayrollYearId = PP.PayrollYearId AND  PPR.EmployeeId = PPE.EmployeeId
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=tEM.OrgId
	LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = OM.Id
	INNER JOIN sPayroll.tPayrollMaster PM ON PY.PayrollId = PM.Id
	
	--LEFT JOIN sHrm.tEmployeeWorkingDays EWD ON tEM.Id = EWD.EmployeeId AND PP.SalaryMonth=EWD.ForMonth AND PP.SalaryYear=EWD.ForYear
where 
      (EM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
      AND (P.IsObsolete=0)
      AND ((EM.Code Like '%' +  @rEmployeeCode + '%' ) OR (@rEmployeeCode = ''))
	  AND ((EM.EmployeeName Like '%' + @rEmployeeName  + '%') OR (@rEmployeeName = ''))
	  AND (EM.DepartmentId = @rDepartmentId OR @rDepartmentId = 0)
	  AND (PP.SalaryMonth = @rForMonth OR @rForMonth = 0)
	  AND (PP.SalaryYear = @rForYear OR @rForYear = 0)
	  AND ((PY.PayrollId=@rPayrollId) OR (@rPayrollId=0))
	  AND (PPE.PayrollGroupId = @rPayrollGroupId OR @rPayrollGroupId = 0) 
	  AND (PP.PayrollYearId = @rPayrollYearId OR @rPayrollYearId = 0) 
	  AND (PP.SalaryMonth IN(SELECT cast(item as int) FROM  sCommon.fnsplit(@rMonths,',')) OR @rMonths='')
	  --AND ((EM.DateOfleaving >= @lFirstDate) OR ISNULL(EM.DateOfleaving,'') = '')
   --   AND ((EM.DateOfJoining <= @lLasteDate) OR ISNULL(EM.DateOfJoining,'') = '')
	  AND ((tEM.OrgID = @rOrgId) OR (@rOrgId = 0))
	  AND ((tEM.StatusId = @rStatusId) OR (@rStatusId = 0))
	  AND ((EJD.EmployeeGroupId = @rEmployeeGroupId) OR (@rEmployeeGroupId = 0))
END
GO
PRINT N'Altering [sPayroll].[pRptMonthlyPFStatement]...';


GO
 

ALTER PROCEDURE [sPayroll].[pRptMonthlyPFStatement]
	
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rEmployeeId bigint,
	 @rEmployeeCode nvarchar(200),
	 @rEmployeeName nvarchar(200),
	 @rForMonth int,
	 @rForYear int,
	 @rPayrollId int,
	 @rPayrollGroupId int,
	 @rPayrollYearId int,
	 @rOrderByField nvarchar(20)='',
	 @rOrgId int = 0,
	 @rDepartmentId int = 0,
	 @rStatusId int = 0,
	 @rEmployeeGroupId int = 0
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	
	DECLARE @lFirstDate Date
	DECLARE @lLasteDate Date
	
	
	SET @lFirstDate = CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'/'+CONVERT(NVARCHAR(2),@rForMonth)+'/01'))
	SET @lLasteDate=DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,@lFirstDate)+1,0))
	 

	SET @rEmployeeCode = sCommon.fSearchStringGet(@rEmployeeCode)
	SET @rEmployeeName = sCommon.fSearchStringGet(@rEmployeeName)

	--DECLARE @lConfigValue nvarchar(50) = ''
	--DECLARE @lIsOnPrePrinted bit = 0
	--DECLARE @lIsDisplayImageHeader bit=0

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

	SELECT
		@rOrderByField AS OrderByField, 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,	
		ISNULL(ESO.EPFNumber,'') AS PFNumber,
		EM.EmployeeId,
		tEM.FirstName +' '+tEM.MiddleName+' '+ tEM.LastName AS EmployeeName,
		EM.Code AS EmployeeCode,
		ISNULL(PPE.GrossBasic,0) AS GrossBasic,
		ISNULL(PPE.TotalEarning,0) AS TotalEarning,
		PFS.PfSalaryLimit,
		PFS.FpsSalaryLimit,
		PFS.EmployeePfPercent,
		PFS.EmployerPfPercent,
		PFS.EmployerFpsPercent,
		PFS.AdminChargesPercent,
		PFS.EdliPercent,
		PFS.InspectionChargesPercent,
		PFPro.PayProcessElementId,
		PFPro.EmployeePfAmount,
		PFPro.EmployerPfAmount,
		PFPro.EmployerFpsAmount,
		PFPro.AdminChargesAmount,
		PFPro.EdliChargesAmount,
		PFPro.InspectionChargesAmount,
		PY.Title AS PayrollYearName,
		PP.SalaryMonth,
		PP.SalaryYear,
	    MM.Title AS MonthName,
	    (ISNULL(AT.TotalWorkingDays,0) - ISNULL(AT.LWP,0)) AS WorkingDays,
	    (SELECT ISNULL(SUM(PPE.Amount),0) FROM sPayroll.tPayProcessElement PPE INNER JOIN sPayroll.tPayElement P  
	    ON PPE.PayElementId =  P.ID  WHERE PPE.PayProcessEmployeeId = PE.PayProcessEmployeeId AND PayElementId IN 
		(SELECT DependentPayElementId FROM sPayroll.tPaySetupDependent PD INNER JOIN sPayroll.tPaySetup PS ON  PD.PaySetupId = PS.ID
		INNER JOIN sPayroll.tPayElement PE ON PS.PayElementId = PE.ID WHERE PS.PayrollId = @rPayrollId AND PS.PayrollYearId = @rPayrollYearId 
		AND PE.PayElementDefaultId = 56 AND ((PS.SourceTypeId=2020 AND PGM.Id=PS.SourceId) OR (PS.SourceTypeId=95 AND tEM.Id=PS.SourceId)))
		) 
		AS Salary,
		PGM.Id AS PayrollGroupId,
		PGM.Title AS PayrollGroup,
		EM.FirstName,
		EM.LastName,
		tEM.Number,
		--@lIsOnPrePrinted AS IsOnPrePrinted,
		--@lIsDisplayImageHeader AS IsDisplayImageHeader,
		--ISNULL(OI.PayrollHeaderA4,0x) AS PayrollHeader
		(CASE WHEN ISNULL(PM.HeaderDisplayId,1) = 3 THEN ISNULL(PM.PayrollHeader,0x) ELSE NULL END) AS PayrollHeader,
		--ISNULL(PM.PayrollHeader,0x) AS PayrollHeader,
		ISNULL(PM.HeaderDisplayId,1)AS HeaderDisplayId
	FROM 
		sPayroll.tPayProcess PP 
		INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId=PP.ID
		INNER JOIN sPayroll.tPayrollGroupMaster PGM ON PGM.Id = PPE.PayrollGroupId
		INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = PPE.EmployeeId
		INNER JOIN sHrm.tEmployeeMaster tEM ON tEM.Id=PPE.EmployeeId
		LEFT JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.EmployeeId=EM.EmployeeId
		INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
		INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID 
		INNER JOIN sPayroll.tPfProcess PFPro ON PFPro.PayProcessElementId=PE.ID
		INNER JOIN sPayroll.tPayrollYearMaster PY ON PP.PayrollYearId = PY.Id
		INNER JOIN sPayroll.tPfSetup PFS ON PFS.PayrollYearId = PY.Id 
		INNER JOIN sCommon.tMonthMaster MM ON MM.Id=PP.SalaryMonth
		INNER JOIN sHrm.tEmployeeAttendance AT ON AT.EmployeeId=EM.EmployeeId AND AT.ForMonth=@rForMonth AND AT.ForYear =@rForYear
		--LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = tEM.OrgID
		INNER JOIN sPayroll.tPayrollMaster PM ON PY.PayrollId = PM.Id
		--LEFT JOIN 
		--(
		--SELECT PE.Amount,PPE.WorkingDays,PPE.PayProcessId,PPE.EmployeeId, PPE.PayrollGroupId
		--FROM sPayroll.tPayProcess PP 
		--INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId=PP.ID
		--INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = PPE.EmployeeId
		--INNER JOIN sHrm.tEmployeeMaster tEM ON tEM.Id=PPE.EmployeeId
		--LEFT JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.EmployeeId=EM.EmployeeId
		--INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
		--INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID AND P.PayElementDefaultId = 1
		--INNER JOIN sPayroll.tPayrollYearMaster PY ON PP.PayrollYearId = PY.Id
		--WHERE 
		--(PPE.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
		--AND ((EM.Code Like @rEmployeeCode) OR (@rEmployeeCode = ''))
		--AND ((EM.EmployeeName Like @rEmployeeName) OR (@rEmployeeName = ''))
		--AND ((PP.SalaryMonth = @rForMonth) OR (@rForMonth = 0))
	 --   AND ((PP.SalaryYear = @rForYear) OR (@rForYear = 0))
		--AND ((PY.PayrollId=@rPayrollId) OR (@rPayrollId=0))
		--AND (PPE.PayrollGroupId = @rPayrollGroupId OR @rPayrollGroupId = 0) 
		--AND (PP.PayrollYearId = @rPayrollYearId OR @rPayrollYearId = 0) 
		--) A ON A.PayProcessId = PPE.PayProcessId AND A.EmployeeId = PPE.EmployeeId  AND A.PayrollGroupId =  PPE.PayrollGroupId
		
WHERE 
		(PPE.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
		AND ((EM.Code Like @rEmployeeCode) OR (@rEmployeeCode = ''))
		AND ((EM.EmployeeName Like @rEmployeeName) OR (@rEmployeeName = ''))
		AND ((PP.SalaryMonth = @rForMonth) OR (@rForMonth = 0))
	    AND ((PP.SalaryYear = @rForYear) OR (@rForYear = 0))
		AND ((PY.PayrollId=@rPayrollId) OR (@rPayrollId=0))
		AND (PPE.PayrollGroupId = @rPayrollGroupId OR @rPayrollGroupId = 0) 
		AND (PP.PayrollYearId = @rPayrollYearId OR @rPayrollYearId = 0) 
		AND PFPro.EmployeePfAmount!=0
		AND ((EM.DateOfleaving >= @lFirstDate) OR ISNULL(EM.DateOfleaving,'') = '')
		AND ((EM.DateOfJoining <= @lLasteDate) OR ISNULL(EM.DateOfJoining,'') = '')
		AND ((tEM.OrgID = @rOrgId) OR (@rOrgId = 0))
		AND (EM.DepartmentId = @rDepartmentId OR @rDepartmentId = 0)
		AND ((tEM.StatusId = @rStatusId) OR (@rStatusId = 0))
		AND ((EM.EmployeeGroupId = @rEmployeeGroupId) OR (@rEmployeeGroupId = 0))
END
GO
PRINT N'Altering [sPayroll].[pRptMonthlyProfessoionTaxSummary]...';


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

BEGIN   
		
		DECLARE @lFirstDate Date
		DECLARE @lLasteDate Date
	
	
		SET @lFirstDate = CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'/'+CONVERT(NVARCHAR(2),@rForMonth)+'/01'))
		SET @lLasteDate=DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,@lFirstDate)+1,0))
		
 
		SET @rEmployeeCode = sCommon.fSearchStringGet(@rEmployeeCode)
		SET @rEmployeeName = sCommon.fSearchStringGet(@rEmployeeName)

	--DECLARE @lConfigValue nvarchar(50) = ''
	--DECLARE @lIsOnPrePrinted bit = 0
	--DECLARE @lIsDisplayImageHeader bit=0

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

		SELECT
			@rBuilder1 AS Builder1,
		    @rBuilder2 AS Builder2, 
			PTR.Id,
			PTR.Tax,
			ISNULL(A.NomberOfEmployee,0) AS NumberOfEmployee,
			--@lIsOnPrePrinted AS IsOnPrePrinted,
			--@lIsDisplayImageHeader AS IsDisplayImageHeader,
			PayrollHeader,
			HeaderDisplayId
		FROM 
			sPayroll.tProfessionalTaxRange PTR
		LEFT JOIN 
		(	
		SELECT 
			PTR.Id, COUNT(EM.EmployeeId) AS NomberOfEmployee ,PE.Amount,(CASE WHEN ISNULL(PM.HeaderDisplayId,1) = 3 THEN ISNULL(PM.PayrollHeader,0x) ELSE NULL END) AS PayrollHeader,ISNULL(PM.HeaderDisplayId,1)AS HeaderDisplayId
		FROM 
			sPayroll.tProfessionalTaxRange PTR
			INNER JOIN sPayroll.tPayProcess PP ON PP.PayrollYearId = PTR.PayrollYearId
			INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId = PP.ID 
			INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = PPE.EmployeeId 
			INNER JOIN sHrm.tEmployeeMaster tEM ON tEM.Id = PPE.EmployeeId 
			INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
			INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID  AND PayElementDefaultId = 57 
			LEFT JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.EmployeeId=PPE.EmployeeId	
			LEFT JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId=PPE.EmployeeId	
			LEFT JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=PPE.EmployeeId	
			INNER JOIN sCommon.tMonthMaster MM ON MM.Id=PP.SalaryMonth
			INNER JOIN sPayroll.tPayrollYearMaster PY ON PP.PayrollYearId = PY.Id 
			INNER JOIN sPayroll.tPayrollGroupMaster PGM ON PGM.Id = PPE.PayrollGroupId	
			--LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = tEM.OrgID
			INNER JOIN sPayroll.tPayrollMaster PM ON PY.PayrollId = PM.Id
		WHERE 
			(EM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
			AND (P.IsObsolete=0)
			AND ((EM.Code Like '%' +  @rEmployeeCode + '%' ) OR (@rEmployeeCode = ''))
			AND ((EM.EmployeeName Like '%' + @rEmployeeName  + '%') OR (@rEmployeeName = ''))
			AND (EM.DepartmentId = @rDepartmentId OR @rDepartmentId = 0)
			AND (PP.SalaryMonth = @rForMonth OR @rForMonth = 0)
			AND (PP.SalaryYear = @rForYear OR @rForYear = 0)
			AND ((PY.PayrollId=@rPayrollId) OR (@rPayrollId=0))
			AND (PPE.PayrollGroupId = @rPayrollGroupId OR @rPayrollGroupId = 0) 
			AND (PP.PayrollYearId = @rPayrollYearId OR @rPayrollYearId = 0) 
			AND ((EM.DateOfleaving >= @lFirstDate) OR ISNULL(EM.DateOfleaving,'') = '')
			AND ((EM.DateOfJoining <= @lLasteDate) OR ISNULL(EM.DateOfJoining,'') = '')
			AND ((tEM.OrgID = @rOrgId) OR (@rOrgId = 0))
			AND ((tEM.StatusId = @rStatusId) OR (@rStatusId = 0))
			AND ((EM.EmployeeGroupId = @rEmployeeGroupId) OR (@rEmployeeGroupId = 0))
		GROUP BY 
			PTR.Id,EM.EmployeeId,PE.Amount,PM.PayrollHeader,PM.HeaderDisplayId
		) A ON A.Id = PTR.Id AND PTR.Tax = A.Amount
		WHERE PTR.PayrollYearId = @rPayrollYearId
		GROUP BY PTR.Id,PTR.Tax,A.NomberOfEmployee,PayrollHeader,HeaderDisplayId
		ORDER BY PTR.Tax
END
GO
PRINT N'Altering [sPayroll].[pRptPayElementwiseSummaryDetail]...';


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

BEGIN  
	
	DECLARE @lFirstDate Date
	DECLARE @lLasteDate Date
	IF(@rForMonth!=0 and @rForYear!=0)
	BEGIN
		SET @lFirstDate = CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'/'+CONVERT(NVARCHAR(2),@rForMonth)+'/01'))
		SET @lLasteDate=DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,@lFirstDate)+1,0))
	END
	
	DECLARE @lBasicPayElementId int
	DECLARE @lProfessionalTaxPayElementId int
	
	SELECT @lBasicPayElementId = Id FROM sPayroll.tPayElement WHERE PayrollId = @rPayrollId AND PayElementDefaultId = 1
	SELECT @lProfessionalTaxPayElementId = Id FROM sPayroll.tPayElement WHERE PayrollId = @rPayrollId AND PayElementDefaultId = 57
	
	SET @rEmployeeCode = sCommon.fSearchStringGet(@rEmployeeCode)
    SET @rEmployeeName = sCommon.fSearchStringGet(@rEmployeeName)

	--DECLARE @lConfigValue nvarchar(50) = ''
	--DECLARE @lIsOnPrePrinted bit = 0
	--DECLARE @lIsDisplayImageHeader bit=0

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

	SELECT 
	@rOrderByField AS OrderByField,
	@rBuilder1 AS Builder1,
	@rBuilder2 AS Builder2,	
	PE.Amount,
	P.Id AS PayElementId, 
	P.Title AS PayElementName,
	P.Code AS PayElementCode,
	EM.EmployeeId,
	tEM.FirstName +' '+tEM.MiddleName+' '+ tEM.LastName AS EmployeeName,
	EM.Code,
	EM.EmployeeDesignation,
	PP.SalaryMonth,
	PP.SalaryYear,
	MM.Title AS MonthName,
	PY.Title AS PayrollYearName,
	P.SortOrder,
	P.PayElementTypeId,
	@rPayElementTypeId AS IsPayElementTypeIdZero,
	@rPayElementId AS IsPayElementIdZero, 
	PPE.TotalEarning,		
	PPE.TotalDeduction,
	PPE.NetAmount,
	(CASE WHEN PayElementId = @lBasicPayElementId then PPE.TotalEarning else 0 END) AS TotalEarningTotal,
	(CASE WHEN (PayElementId = @lBasicPayElementId And @rPayElementTypeId <> 2) 
	 THEN PPE.TotalDeduction WHEN PayElementId = @lProfessionalTaxPayElementId And @rPayElementTypeId = 2 
	 THEN PPE.TotalDeduction ELSE 0 END) AS TotalDeductionTotal,	 
	(CASE WHEN PayElementId = @lBasicPayElementId then PPE.NetAmount else 0 END) AS NetAmountTotal,
	PGM.Id AS PayrollGroupId,
	PGM.Title AS PayrollGroupName,
	PPE.GrossBasic ,
	P.PayElementDefaultId,
	ISNULL(PPE.WorkingDays,0) AS WorkingDays,
	ISNULL(PPE.Lwp,0) AS Lwp,
	EM.FirstName,
	EM.LastName,
	tEM.Number,
	OM.Id AS OrganizationId,
	OM.Title AS OrganizationTitle,
	OM.Code AS OrganizationCode,
	OM.OrderIndex AS OrganizationOrderIndex,
	@rIsDetail AS IsDetail,
	EM.DateOfBirth,
	EM.DateOfJoining,
	--@lIsOnPrePrinted AS IsOnPrePrinted,
	--@lIsDisplayImageHeader AS IsDisplayImageHeader,
	--ISNULL(OI.PayrollHeaderA4,0x) AS PayrollHeader
	(CASE WHEN ISNULL(PM.HeaderDisplayId,1) = 3 THEN ISNULL(PM.PayrollHeader,0x) ELSE NULL END) AS PayrollHeader,
	--ISNULL(PM.PayrollHeader,0x) AS PayrollHeader,
	ISNULL(PM.HeaderDisplayId,1)AS HeaderDisplayId
		
	FROM sPayroll.tPayProcessEmployee PPE
		INNER JOIN sPayroll.tPayProcess PP ON PPE.PayProcessId=PP.ID
		INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
		INNER JOIN sPayroll.tPayElement P ON P.ID=PE.PayElementId AND P.IsObsolete = 0
		INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId=PPE.EmployeeId
		INNER JOIN sHrm.tEmployeeMaster tEM ON tEM.Id=PPE.EmployeeId
		LEFT JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.EmployeeId=PPE.EmployeeId	
		INNER JOIN sCommon.tMonthMaster MM ON MM.Id=PP.SalaryMonth
		INNER JOIN sPayroll.tPayrollYearMaster PY ON PP.PayrollYearId = PY.Id 
		INNER JOIN sPayroll.tPayrollGroupMaster PGM ON PGM.Id = PPE.PayrollGroupId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = tEM.OrgId
		--LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = tEM.OrgID
		INNER JOIN sPayroll.tPayrollMaster PM ON PY.PayrollId = PM.Id
WHERE 
      (PPE.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
      AND ((P.ID=@rPayElementId) OR (@rPayElementId=0))
      AND ((EM.Code Like  @rEmployeeCode) OR (@rEmployeeCode = ''))
	  AND ((EM.EmployeeName Like @rEmployeeName ) OR (@rEmployeeName = ''))
	  AND (EM.DepartmentId = @rDepartmentId OR @rDepartmentId = 0)
	  AND (PP.SalaryMonth = @rForMonth OR @rForMonth = 0)
	  AND (PP.SalaryYear = @rForYear OR @rForYear = 0)
	  AND ((PY.PayrollId=@rPayrollId) OR (@rPayrollId=0))
	  AND (PPE.PayrollGroupId = @rPayrollGroupId OR @rPayrollGroupId = 0) 
	  AND (PP.PayrollYearId = @rPayrollYearId OR @rPayrollYearId = 0) 
	  AND (P.PayElementTypeId = @rPayElementTypeId OR @rPayElementTypeId = 0) 
	  AND (PP.SalaryMonth IN(SELECT cast(item as int) FROM  sCommon.fnsplit(@rMonths,',')) OR @rMonths='')
	  AND ((tEM.OrgID = @rOrgId) OR (@rOrgId = 0))
	  AND ((tEM.StatusId = @rStatusId) OR (@rStatusId = 0))
	  --AND ((EM.DateOfleaving >= @lFirstDate) OR ISNULL(EM.DateOfleaving,'') = '')
   --   AND ((EM.DateOfJoining <= @lLasteDate) OR ISNULL(EM.DateOfJoining,'') = '')
	  AND ((EM.EmployeeGroupId = @rEmployeeGroupId) OR (@rEmployeeGroupId = 0))
END
GO
PRINT N'Altering [sPayroll].[pRptPayrollReconcilationGet]...';


GO
 
ALTER PROCEDURE [sPayroll].[pRptPayrollReconcilationGet]
	
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rPayElementId int,
	 @rEmployeeId bigint,
	 @rEmployeeCode nvarchar(200),
	 @rEmployeeName nvarchar(200),
	 @rDepartmentId int,
	 @rForMonth int,
	 @rForYear int,
	 @rPayrollId int,
	 @rPayrollGroupId int,
	 @rPayrollYearId int,	
	 @rPayElementTypeId int=0,
	 @rMonths nvarchar(50)='',
	 @rOrderByField nvarchar(20)='',
	 @rOrgId int = 0,
	 @rIsDetail bit = 0,
	 @rStatusId int = 0,
	 @rEmployeeGroupId int = 0,
	 @rCompareWithMonth int = 0,
	 @rCompareWithYear int = 0
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN  
	
	DECLARE @lFirstDate Date
	DECLARE @lLasteDate Date
	IF(@rForMonth!=0 and @rForYear!=0)
	BEGIN
		SET @lFirstDate = CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'/'+CONVERT(NVARCHAR(2),@rForMonth)+'/01'))
		SET @lLasteDate=DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,@lFirstDate)+1,0))
	END
	
	DECLARE @lBasicPayElementId int
	DECLARE @lProfessionalTaxPayElementId int
	
	SELECT @lBasicPayElementId = Id FROM sPayroll.tPayElement WHERE PayrollId = @rPayrollId AND PayElementDefaultId = 1
	SELECT @lProfessionalTaxPayElementId = Id FROM sPayroll.tPayElement WHERE PayrollId = @rPayrollId AND PayElementDefaultId = 57
	
	SET @rEmployeeCode = sCommon.fSearchStringGet(@rEmployeeCode)
    SET @rEmployeeName = sCommon.fSearchStringGet(@rEmployeeName)

	--DECLARE @lConfigValue nvarchar(50) = ''
	--DECLARE @lIsOnPrePrinted bit = 0
	--DECLARE @lIsDisplayImageHeader bit=0

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

	DECLARE @lFromMonth nvarchar(20) = (SELECT Title FROM sCommon.tMonthMaster WHERE Id = @rForMonth)
	DECLARE @lToMonth nvarchar(20) = (SELECT Title FROM sCommon.tMonthMaster WHERE Id = @rCompareWithMonth)

	SELECT 
	@rOrderByField AS OrderByField,
	@lFromMonth + ' ' + CAST(@rForYear AS nvarchar) + ' compare with ' + @lToMonth + ' ' + CAST(@rCompareWithYear AS nvarchar) AS Builder1,
	@rBuilder2 AS Builder2,	
	Fr.Amount,
	ISNULL(Comp.Amount,0) AS CompAmount,
	Fr.PayElementId, 
	Fr.PayElementName,
	Fr.PayElementCode,
	Fr.EmployeeId,
	Fr.EmployeeName,
	Fr.Code,
	Fr.EmployeeDesignation,
	Fr.SalaryMonth + '-' + Fr.SalaryYear AS SalaryMonthYear,
	ISNULL(Comp.SalaryMonth + '-' + Comp.SalaryYear,0) AS CompSalaryMonthYear,
	Fr.[MonthName],
	ISNULL(Comp.[MonthName],'') AS CompMonthName,
	Fr.PayrollYearName,
	Fr.SortOrder,
	Fr.PayElementTypeId,
	@rPayElementTypeId AS IsPayElementTypeIdZero,
	@rPayElementId AS IsPayElementIdZero, 
	Fr.TotalEarning,
	ISNULL(Comp.TotalEarning,0) AS CompTotalEarning,
	Fr.TotalDeduction,
	ISNULL(Comp.TotalDeduction,0) AS CompTotalDeduction,
	Fr.NetAmount,
	ISNULL(Comp.NetAmount,0) AS CompNetAmount,
	Fr.TotalEarningTotal,
	ISNULL(Comp.TotalEarningTotal,0) AS CompTotalEarningTotal,
	Fr.TotalDeductionTotal,
	ISNULL(Comp.TotalDeductionTotal,0) AS CompTotalDeductionTotal,
	Fr.NetAmountTotal,	
	ISNULL(Comp.NetAmountTotal,0) AS CompNetAmountTotal,
	Fr.PayrollGroupId,
	Fr.PayrollGroupName,
	Fr.GrossBasic,
	ISNULL(Comp.GrossBasic,0) AS CompGrossBasic,
	Fr.PayElementDefaultId,
	Fr.WorkingDays,
	ISNULL(Comp.WorkingDays,0) AS CompWorkingDays,
	Fr.Lwp,
	ISNULL(Comp.Lwp,0) AS CompLwp,
	Fr.FirstName,
	Fr.LastName,
	Fr.Number,
	Fr.OrganizationId,
	Fr.OrganizationTitle,
	Fr.OrganizationCode,
	Fr.OrganizationOrderIndex,
	@rIsDetail AS IsDetail,
	--@lIsOnPrePrinted AS IsOnPrePrinted,
	--@lIsDisplayImageHeader AS IsDisplayImageHeader,	
	PayrollHeader,
	HeaderDisplayId
	FROM 


	(SELECT 
	@rOrderByField AS OrderByField,
	@rBuilder1 AS Builder1,
	@rBuilder2 AS Builder2,	
	PE.Amount,
	P.Id AS PayElementId, 
	P.Title AS PayElementName,
	P.Code AS PayElementCode,
	EM.EmployeeId,
	tEM.FirstName +' '+tEM.MiddleName+' '+ tEM.LastName AS EmployeeName,
	EM.Code,
	EM.EmployeeDesignation,
	PP.SalaryMonth,
	PP.SalaryYear,
	MM.Title AS MonthName,
	PY.Title AS PayrollYearName,
	P.SortOrder,
	P.PayElementTypeId,
	@rPayElementTypeId AS IsPayElementTypeIdZero,
	@rPayElementId AS IsPayElementIdZero, 
	PPE.TotalEarning,		
	PPE.TotalDeduction,
	PPE.NetAmount,
	(CASE WHEN PayElementId = @lBasicPayElementId then PPE.TotalEarning else 0 END) AS TotalEarningTotal,
	(CASE WHEN (PayElementId = @lBasicPayElementId And @rPayElementTypeId <> 2) 
	 THEN PPE.TotalDeduction WHEN PayElementId = @lProfessionalTaxPayElementId And @rPayElementTypeId = 2 
	 THEN PPE.TotalDeduction ELSE 0 END) AS TotalDeductionTotal,	 
	(CASE WHEN PayElementId = @lBasicPayElementId then PPE.NetAmount else 0 END) AS NetAmountTotal,
	PGM.Id AS PayrollGroupId,
	PGM.Title AS PayrollGroupName,
	PPE.GrossBasic ,
	P.PayElementDefaultId,
	ISNULL(PPE.WorkingDays,0) AS WorkingDays,
	ISNULL(PPE.Lwp,0) AS Lwp,
	EM.FirstName,
	EM.LastName,
	tEM.Number,
	OM.Id AS OrganizationId,
	OM.Title AS OrganizationTitle,
	OM.Code AS OrganizationCode,
	OM.OrderIndex AS OrganizationOrderIndex,
	@rIsDetail AS IsDetail,
	--ISNULL(OI.PayrollHeaderA4,0x) AS PayrollHeader
	(CASE WHEN ISNULL(PM.HeaderDisplayId,1) = 3 THEN ISNULL(PM.PayrollHeader,0x) ELSE NULL END) AS PayrollHeader,
	--ISNULL(PM.PayrollHeader,0x) AS PayrollHeader,
	ISNULL(PM.HeaderDisplayId,1)AS HeaderDisplayId

	FROM sPayroll.tPayProcessEmployee PPE
		INNER JOIN sPayroll.tPayProcess PP ON PPE.PayProcessId=PP.ID
		INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
		INNER JOIN sPayroll.tPayElement P ON P.ID=PE.PayElementId AND P.IsObsolete = 0
		INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId=PPE.EmployeeId
		INNER JOIN sHrm.tEmployeeMaster tEM ON tEM.Id=PPE.EmployeeId
		LEFT JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.EmployeeId=PPE.EmployeeId	
		INNER JOIN sCommon.tMonthMaster MM ON MM.Id=PP.SalaryMonth
		INNER JOIN sPayroll.tPayrollYearMaster PY ON PP.PayrollYearId = PY.Id 
		INNER JOIN sPayroll.tPayrollGroupMaster PGM ON PGM.Id = PPE.PayrollGroupId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = tEM.OrgId
		--LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = tEM.OrgID
		INNER JOIN sPayroll.tPayrollMaster PM ON PY.PayrollId = PM.Id
WHERE 
      (PPE.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
      AND ((P.ID=@rPayElementId) OR (@rPayElementId=0))
      AND ((EM.Code Like  @rEmployeeCode) OR (@rEmployeeCode = ''))
	  AND ((EM.EmployeeName Like @rEmployeeName ) OR (@rEmployeeName = ''))
	  AND (EM.DepartmentId = @rDepartmentId OR @rDepartmentId = 0)
	  AND (PP.SalaryMonth = @rForMonth OR @rForMonth = 0)
	  AND (PP.SalaryYear = @rForYear OR @rForYear = 0)
	  AND ((PY.PayrollId=@rPayrollId) OR (@rPayrollId=0))
	  AND (PPE.PayrollGroupId = @rPayrollGroupId OR @rPayrollGroupId = 0) 
	  AND (PP.PayrollYearId = @rPayrollYearId OR @rPayrollYearId = 0) 
	  AND (P.PayElementTypeId = @rPayElementTypeId OR @rPayElementTypeId = 0) 
	  AND (PP.SalaryMonth IN(SELECT cast(item as int) FROM  sCommon.fnsplit(@rMonths,',')) OR @rMonths='')
	  AND ((tEM.OrgID = @rOrgId) OR (@rOrgId = 0))
	  AND ((tEM.StatusId = @rStatusId) OR (@rStatusId = 0))	
	  AND ((EM.EmployeeGroupId = @rEmployeeGroupId) OR (@rEmployeeGroupId = 0))
	  ) Fr 


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

	FROM sPayroll.tPayProcessEmployee PPE
		INNER JOIN sPayroll.tPayProcess PP ON PPE.PayProcessId=PP.ID
		INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
		INNER JOIN sPayroll.tPayElement P ON P.ID=PE.PayElementId AND P.IsObsolete = 0
		INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId=PPE.EmployeeId
		INNER JOIN sHrm.tEmployeeMaster tEM ON tEM.Id=PPE.EmployeeId
		LEFT JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.EmployeeId=PPE.EmployeeId	
		INNER JOIN sCommon.tMonthMaster MM ON MM.Id=PP.SalaryMonth
		INNER JOIN sPayroll.tPayrollYearMaster PY ON PP.PayrollYearId = PY.Id 
		INNER JOIN sPayroll.tPayrollGroupMaster PGM ON PGM.Id = PPE.PayrollGroupId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = tEM.OrgId
WHERE 
      (PPE.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
      AND ((P.ID=@rPayElementId) OR (@rPayElementId=0))
      AND ((EM.Code Like  @rEmployeeCode) OR (@rEmployeeCode = ''))
	  AND ((EM.EmployeeName Like @rEmployeeName ) OR (@rEmployeeName = ''))
	  AND (EM.DepartmentId = @rDepartmentId OR @rDepartmentId = 0)
	  AND (PP.SalaryMonth = @rCompareWithMonth OR @rCompareWithMonth = 0)
	  AND (PP.SalaryYear = @rCompareWithYear OR @rCompareWithYear = 0)
	  AND ((PY.PayrollId=@rPayrollId) OR (@rPayrollId=0))
	  AND (PPE.PayrollGroupId = @rPayrollGroupId OR @rPayrollGroupId = 0) 
	  AND (PP.PayrollYearId = @rPayrollYearId OR @rPayrollYearId = 0) 
	  AND (P.PayElementTypeId = @rPayElementTypeId OR @rPayElementTypeId = 0) 
	  AND (PP.SalaryMonth IN(SELECT cast(item as int) FROM  sCommon.fnsplit(@rMonths,',')) OR @rMonths='')
	  AND ((tEM.OrgID = @rOrgId) OR (@rOrgId = 0))
	  AND ((tEM.StatusId = @rStatusId) OR (@rStatusId = 0))	
	  AND ((EM.EmployeeGroupId = @rEmployeeGroupId) OR (@rEmployeeGroupId = 0))
	  ) Comp ON Comp.PayElementId = Fr.PayElementId AND Comp.EmployeeId = Fr.EmployeeId


END
GO
PRINT N'Altering [sPayroll].[pRptPaysheetDetail]...';


GO
 
 

ALTER PROCEDURE [sPayroll].[pRptPaysheetDetail]
	
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rEmployeeId bigint,
	 @rEmployeeCode nvarchar(200),
	 @rEmployeeName nvarchar(200),
	 @rDepartmentId int,
	 @rForMonth int,
	 @rForYear int,
	 @rPayrollId int,
	 @rPayrollGroupId int,
	 @rPayrollYearId int,
	 @rReportId smallint=0,
	 @rOrgId int,
	 @rOrderByField nvarchar(20)='',
	 @rStatusId int = 0,
	 @rEmployeeGroupId int = 0
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN  
DECLARE @lOrgGroupId int = 0
DECLARE @lCurrencyCode nvarchar(20) = ''
    SELECT  @lCurrencyCode = [sFinanceCommon].[fDefaultCurrencyCodeGet](@lOrgGroupId) 

	--DECLARE @lConfigValue nvarchar(50) = ''
	--DECLARE @lIsOnPrePrinted bit = 0
	--DECLARE @lIsDisplayImageHeader bit=0

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

	SELECT
		@rOrderByField AS OrderByField,
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		@lCurrencyCode AS CurrencyCode,
		@rForYear AS Foryear,
		(Select DateName( month , DateAdd( month ,@rForMonth, 0 ) - 1 )) AS ForMonth,
		(SELECT Title FROM sSetup.tOrganizationMaster  WHERE Id= EM.OrgId ) AS OrgName,
		(SELECT OG.Title FROM sSetup.tOrgGroupMaster OG INNER JOIN sSetup.tOrganizationMaster OM  ON OG.Id=OM.OrgGroupId WHERE OM.Id=EM.OrgId) AS TrustName,
		(SELECT SmallAddress1 FROM sSetup.tOrganizationMaster WHERE Id= EM.OrgId ) AS ReportAddress1,
		(SELECT SmallAddress2 FROM sSetup.tOrganizationMaster WHERE Id= EM.OrgId ) AS ReportAddress2,
	  --  (SELECT EM1.FirstName+' '+EM1.MiddleName+' ' +EM1.LastName From  sHrm.tEmployeeMaster EM1
			--INNER JOIN sHrm.tEmployeeJobDetail EJ ON EM1.Id=EJ.EmployeeId
			--INNER JOIN sHrm.tEmployeeDesignationMaster ED ON ED.Id=EJ.EmployeeDesignationId
			--Where EJ.OrgId=EM.OrgID AND ED.Code='PRINCIPAL' AND  ISNULL(EM.IsOtherUser,0) = 0)AS HeadMasterName,
		(Select STUFF((SELECT ','+ (EM1.FirstName+' '+EM1.MiddleName+' ' +EM1.LastName) From  sHrm.tEmployeeMaster EM1
		INNER JOIN sHrm.tEmployeeJobDetail EJ ON EM1.Id=EJ.EmployeeId
		INNER JOIN sHrm.tEmployeeDesignationMaster ED ON ED.Id=EJ.EmployeeDesignationId
		Where EJ.OrgId=EM.OrgID AND ED.Code='PRINCIPAL' AND  ISNULL(EM.IsOtherUser,0) = 0
		FOR XML Path('')),1,1,''))AS HeadMasterName,
		
		10000 AS SalaryGrant,
		10000 AS RecoveryAdj,
		10000 AS GrossAmount,
		10000 AS TutionFees	,						
		(SELECT sum(PE.Amount) FROM sPayroll.tPayProcess PP 
			INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId = PP.ID 
			INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
			INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID 
			WHERE P.PayElementDefaultId=1 and PayrollId=@rPayrollId
			GROUP BY PE.PayElementId,P.code) AS BasicPay,
			
		(SELECT sum(PE.Amount) FROM sPayroll.tPayProcess PP 
			INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId = PP.ID 
			INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
			INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID 
			WHERE P.PayElementDefaultId=8 and PayrollId=@rPayrollId
			GROUP BY PE.PayElementId,P.code) AS GradePay,
			
		(SELECT sum(PE.Amount) FROM sPayroll.tPayProcess PP 
			INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId = PP.ID 
			INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
			INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID 
			WHERE P.PayElementDefaultId=2 and PayrollId=@rPayrollId
			GROUP BY PE.PayElementId,P.code) AS DA,
			
		(SELECT sum(PE.Amount) FROM sPayroll.tPayProcess PP 
			INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId = PP.ID 
			INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
			INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID 
			WHERE P.PayElementDefaultId=4 and PayrollId=@rPayrollId
			GROUP BY PE.PayElementId,P.code) AS HRA,
			
		(SELECT sum(PE.Amount) FROM sPayroll.tPayProcess PP 
			INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId = PP.ID 
			INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
			INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID 
			WHERE P.PayElementDefaultId=3 and PayrollId=@rPayrollId
			GROUP BY PE.PayElementId,P.code) AS CLA,
			
		(SELECT sum(PE.Amount) FROM sPayroll.tPayProcess PP 
			INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId = PP.ID 
			INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
			INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID 
			WHERE P.PayElementDefaultId=18 and PayrollId=@rPayrollId
			GROUP BY PE.PayElementId,P.code) AS TA,
			
		(SELECT sum(PE.Amount) FROM sPayroll.tPayProcess PP 
			INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId = PP.ID 
			INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
			INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID 
			WHERE P.PayElementDefaultId=17 and PayrollId=@rPayrollId
			GROUP BY PE.PayElementId,P.code) AS Differenc,
			
		(SELECT sum(PE.Amount) FROM sPayroll.tPayProcess PP 
			INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId = PP.ID 
			INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
			INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID 
			WHERE P.PayElementDefaultId=56 and PayrollId=@rPayrollId
			GROUP BY PE.PayElementId,P.code) AS PF,
			
		(SELECT sum(PE.Amount) FROM sPayroll.tPayProcess PP
			INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId = PP.ID 
			INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
			INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID 
			WHERE P.PayElementDefaultId=57 and PayrollId=@rPayrollId
			GROUP BY PE.PayElementId,P.code) AS PT,
			
		(SELECT sum(PE.Amount) FROM sPayroll.tPayProcess PP
			INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId = PP.ID 
			INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
			INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID 
			WHERE P.PayElementDefaultId=57 and PayrollId=@rPayrollId
			GROUP BY PE.PayElementId,P.code) AS TrSoc,
			
		(SELECT sum(PE.Amount) FROM sPayroll.tPayProcess PP
			INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId = PP.ID 
			INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
			INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID 
			WHERE P.PayElementDefaultId=57 and PayrollId=@rPayrollId
			GROUP BY PE.PayElementId,P.code) AS NtrSoc,
			
		(SELECT sum(PE.Amount) FROM sPayroll.tPayProcess PP
			INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId = PP.ID 
			INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
			INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID 
			WHERE P.PayElementDefaultId=54 and PayrollId=@rPayrollId
			GROUP BY PE.PayElementId,P.code) AS LIC,
			
		(SELECT sum(PE.Amount) FROM sPayroll.tPayProcess PP
			INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId = PP.ID 
			INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
			INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID 
			WHERE P.PayElementDefaultId=57 and PayrollId=@rPayrollId
			GROUP BY PE.PayElementId,P.code) AS RD,
			
		(SELECT sum(PE.Amount) FROM sPayroll.tPayProcess PP
			INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId = PP.ID 
			INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
			INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID 
			WHERE P.PayElementDefaultId=52 and PayrollId=@rPayrollId
			GROUP BY PE.PayElementId,P.code) AS IncomeTax,
			
		(SELECT sum(PE.Amount) FROM sPayroll.tPayProcess PP
			INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId = PP.ID 
			INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
			INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID 
			WHERE P.PayElementDefaultId=52 and PayrollId=@rPayrollId
			GROUP BY PE.PayElementId,P.code) AS Other,
			1 AS HM,
			1 AS AHM,
			1 AS Sup,
			1 AS TG,
			1 AS TUG,
			1 AS SplTr,
			1 AS OS,
			1 AS HC,
			1 AS SrCl,
			1 AS JrCl,
			1 AS Libr,
			1 AS LAs,
			1 AS LAt,
			1 AS Naik,
			1 AS Peon,
			1 AS SS,
			EM.FirstName,
		    EM.LastName,
			EM.OrgID,
			--@lIsOnPrePrinted AS IsOnPrePrinted,
			--@lIsDisplayImageHeader AS IsDisplayImageHeader,
			--ISNULL(OI.PayrollHeaderA4,0x) AS PayrollHeader
			(CASE WHEN ISNULL(PM.HeaderDisplayId,1) = 3 THEN ISNULL(PM.PayrollHeader,0x) ELSE NULL END) AS PayrollHeader,
			--ISNULL(PM.PayrollHeader,0x) AS PayrollHeader,
			ISNULL(PM.HeaderDisplayId,1)AS HeaderDisplayId
			
			
	FROM 
	sHrm.tEmployeeMaster EM
    INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.EmployeeId = EM.Id AND  ISNULL(EM.IsOtherUser,0) = 0
	INNER JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id = EJD.EmployeeId AND EM.IsObsolete = 0 
	INNER JOIN sSetup.tDepartmentMaster ODM ON EJD.OrganizationDepartmentId = ODM.Id AND ODM.IsObsolete = 0
	--LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = EM.OrgID
	INNER JOIN sPayroll.tPayrollMaster PM ON  PM.Id = @rPayrollId
	WHERE ((EM.OrgID = @rOrgId) OR (@rOrgId = 0))
	AND (ODM.Id = @rDepartmentId OR @rDepartmentId = 0)
	AND ((EM.StatusId = @rStatusId) OR (@rStatusId = 0))
	AND ((EJD.EmployeeGroupId = @rEmployeeGroupId) OR (@rEmployeeGroupId = 0))
END
GO
PRINT N'Altering [sPayroll].[pRptPFChallanDetailGet]...';


GO
 
 
 
ALTER PROCEDURE [sPayroll].[pRptPFChallanDetailGet]
	
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rEmployeeId bigint,
	 @rEmployeeCode nvarchar(200),
	 @rEmployeeName nvarchar(200),
	 @rForMonth int,
	 @rForYear int,
	 @rPayrollId int,
	 @rPayrollGroupId int,
	 @rPayrollYearId int,
	 @rOrderByField nvarchar(20)='',
	 @rOrgId int = 0,
	 @rDepartmentId int = 0,
	 @rStatusId int = 0,
	 @rEmployeeGroupId int = 0
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	
	DECLARE @lFirstDate Date
	DECLARE @lLasteDate Date
	IF(@rForMonth!=0 and @rForYear!=0)
	BEGIN
		SET @lFirstDate = CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'/'+CONVERT(NVARCHAR(2),@rForMonth)+'/01'))
		SET @lLasteDate=DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,@lFirstDate)+1,0))
	END

	SET @rEmployeeCode = sCommon.fSearchStringGet(@rEmployeeCode)
	SET @rEmployeeName = sCommon.fSearchStringGet(@rEmployeeName)

	--DECLARE @lConfigValue nvarchar(50) = ''
	--DECLARE @lIsOnPrePrinted bit = 0
	--DECLARE @lIsDisplayImageHeader bit=0

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

	SELECT 
		@rOrderByField AS OrderByField,
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,	
		--ISNULL(ESO.EPFNumber,'') AS PFNumber,
		EM.EmployeeId,
		--tEM.FirstName +' '+tEM.MiddleName+' '+ tEM.LastName AS EmployeeName,
		--EM.Code AS EmployeeCode,
		--ISNULL(PPE.GrossBasic,0) AS GrossBasic,
		PFS.PfSalaryLimit,
		PFS.FpsSalaryLimit,
		PFS.EmployeePfPercent,
		PFS.EmployerPfPercent,
		PFS.EmployerFpsPercent,
		PFS.AdminChargesPercent,
		PFS.EdliPercent,
		PFS.InspectionChargesPercent,
		PFPro.PayProcessElementId,
		PFPro.EmployeePfAmount,
		PFPro.EmployerPfAmount,
		PFPro.EmployerFpsAmount,
		PFPro.AdminChargesAmount,
		PFPro.EdliChargesAmount,
		PFPro.InspectionChargesAmount,
		PY.Title AS PayrollYearName,
		PP.SalaryMonth,
		PP.SalaryYear,
	    MM.Title AS MonthName,
		(ISNULL(AT.TotalWorkingDays,0) - ISNULL(AT.LWP,0)) AS WorkingDays,
		(SELECT ISNULL(SUM(PPE.Amount),0) FROM sPayroll.tPayProcessElement PPE INNER JOIN sPayroll.tPayElement P  
	    ON PPE.PayElementId =  P.ID  WHERE PPE.PayProcessEmployeeId = PE.PayProcessEmployeeId AND PayElementId IN 
		(SELECT DependentPayElementId FROM sPayroll.tPaySetupDependent PD INNER JOIN sPayroll.tPaySetup PS ON  PD.PaySetupId = PS.ID
		INNER JOIN sPayroll.tPayElement PE ON PS.PayElementId = PE.ID WHERE PS.PayrollId = @rPayrollId AND PS.PayrollYearId = @rPayrollYearId 
		AND PE.PayElementDefaultId = 56 AND ((PS.SourceTypeId=2020 AND ESO.PayrollGroupId=PS.SourceId) OR (PS.SourceTypeId=95 AND tEM.Id=PS.SourceId)))
		) 
		AS Salary,
	    --ISNULL(ESO.UAN,'') AS UAN,
	   -- PPE.TotalEarning,
	    OOD.PFEstablishmentCode,
	    OM.DisplayTitle AS OrganizationName,
	    OM.StreetOne + ' ' + OM.StreetTwo + ' ' + OM.StreetThree AS OrgAddress,
		OM.CityName AS OrgCity,
		OM.StateName AS OrgState,
		OM.CountryName AS OrgCountry,
		OM.ZipCode AS OrgZipCode,
		OM.HomePage AS OrgHomePage,
		OM.PhoneNo AS OrgPhoneNo,
		OM.RegistrationDetail AS OrgRegistrationDetail,
	    EM.FirstName,
		EM.LastName,
		--@lIsOnPrePrinted AS IsOnPrePrinted,
		--@lIsDisplayImageHeader AS IsDisplayImageHeader,
		--ISNULL(OI.PayrollHeaderA4,0x) AS PayrollHeader
		(CASE WHEN ISNULL(PM.HeaderDisplayId,1) = 3 THEN ISNULL(PM.PayrollHeader,0x) ELSE NULL END) AS PayrollHeader,
		--ISNULL(PM.PayrollHeader,0x) AS PayrollHeader,
		ISNULL(PM.HeaderDisplayId,1)AS HeaderDisplayId
	FROM 
		sPayroll.tPayProcess PP 
		INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId=PP.ID
		INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = PPE.EmployeeId
		INNER JOIN sHrm.tEmployeeMaster tEM ON tEM.Id=PPE.EmployeeId
		LEFT JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.EmployeeId=EM.EmployeeId
		INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
		--INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID 
		INNER JOIN sPayroll.tPfProcess PFPro ON PFPro.PayProcessElementId=PE.ID
		INNER JOIN sPayroll.tPayrollYearMaster PY ON PP.PayrollYearId = PY.Id
		INNER JOIN sPayroll.tPfSetup PFS ON PFS.PayrollYearId = PY.Id 
		INNER JOIN sCommon.tMonthMaster MM ON MM.Id=PP.SalaryMonth
		INNER JOIN sHrm.tEmployeeAttendance AT ON AT.EmployeeId=EM.EmployeeId AND AT.ForMonth=@rForMonth AND AT.ForYear =@rForYear
		INNER JOIN sSetup.tOrganizationOtherDetail OOD ON OOD.OrgId = EM.OrgID 
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = OOD.OrgId
		--LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = tEM.OrgID
		INNER JOIN sPayroll.tPayrollMaster PM ON PY.PayrollId = PM.Id
		--LEFT JOIN 
		--(
		--SELECT PE.Amount,PPE.WorkingDays,PPE.PayProcessId,PPE.EmployeeId, PPE.PayrollGroupId
		--FROM sPayroll.tPayProcess PP 
		--INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId=PP.ID
		--INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = PPE.EmployeeId
		--INNER JOIN sHrm.tEmployeeMaster tEM ON tEM.Id=PPE.EmployeeId
		--LEFT JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.EmployeeId=EM.EmployeeId
		--INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
		--INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID AND P.PayElementDefaultId = 1
		--INNER JOIN sPayroll.tPayrollYearMaster PY ON PP.PayrollYearId = PY.Id
		--WHERE 
		--(PPE.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
		--AND ((EM.Code Like @rEmployeeCode) OR (@rEmployeeCode = ''))
		--AND ((EM.EmployeeName Like @rEmployeeName) OR (@rEmployeeName = ''))
		--AND ((PP.SalaryMonth = @rForMonth) OR (@rForMonth = 0))
	 --   AND ((PP.SalaryYear = @rForYear) OR (@rForYear = 0))
		--AND ((PY.PayrollId=@rPayrollId) OR (@rPayrollId=0))
		--AND (PPE.PayrollGroupId = @rPayrollGroupId OR @rPayrollGroupId = 0) 
		--AND (PP.PayrollYearId = @rPayrollYearId OR @rPayrollYearId = 0) 
		--AND ((EM.DateOfleaving >= @lFirstDate) OR ISNULL(EM.DateOfleaving,'') = '')
  --      AND ((EM.DateOfJoining <= @lLasteDate) OR ISNULL(EM.DateOfJoining,'') = '')
		--) A ON A.PayProcessId = PPE.PayProcessId AND A.EmployeeId = PPE.EmployeeId  AND A.PayrollGroupId =  PPE.PayrollGroupId
WHERE 
		(PPE.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
		AND ((EM.Code Like @rEmployeeCode) OR (@rEmployeeCode = ''))
		AND ((EM.EmployeeName Like @rEmployeeName) OR (@rEmployeeName = ''))
		AND ((PP.SalaryMonth = @rForMonth) OR (@rForMonth = 0))
	    AND ((PP.SalaryYear = @rForYear) OR (@rForYear = 0))
		AND ((PY.PayrollId=@rPayrollId) OR (@rPayrollId=0))
		AND (PPE.PayrollGroupId = @rPayrollGroupId OR @rPayrollGroupId = 0) 
		AND (PP.PayrollYearId = @rPayrollYearId OR @rPayrollYearId = 0) 
		AND ((EM.DateOfleaving >= @lFirstDate) OR ISNULL(EM.DateOfleaving,'') = '')
        AND ((EM.DateOfJoining <= @lLasteDate) OR ISNULL(EM.DateOfJoining,'') = '')
		AND ((tEM.OrgID = @rOrgId) OR (@rOrgId = 0))
		AND (EM.DepartmentId = @rDepartmentId OR @rDepartmentId = 0)
		AND ((tEM.StatusId = @rStatusId) OR (@rStatusId = 0))
		AND ((EM.EmployeeGroupId = @rEmployeeGroupId) OR (@rEmployeeGroupId = 0))
END
GO
PRINT N'Altering [sPayroll].[pRptPFDetail]...';


GO
 
 
 
ALTER PROCEDURE [sPayroll].[pRptPFDetail]
	
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rEmployeeId bigint,
	 @rEmployeeCode nvarchar(200),
	 @rEmployeeName nvarchar(200),
	 @rForMonth int,
	 @rForYear int,
	 @rPayrollId int,
	 @rPayrollGroupId int,
	 @rPayrollYearId int,
	 @rOrderByField nvarchar(20)='',
	 @rOrgId int = 0,
	 @rDepartmentId int = 0,
	 @rStatusId int = 0,
	 @rEmployeeGroupId int = 0
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	
	DECLARE @lFirstDate Date
	DECLARE @lLasteDate Date
	IF(@rForMonth!=0 and @rForYear!=0)
	BEGIN
		SET @lFirstDate = CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'/'+CONVERT(NVARCHAR(2),@rForMonth)+'/01'))
		SET @lLasteDate=DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,@lFirstDate)+1,0))
	END

	SET @rEmployeeCode = sCommon.fSearchStringGet(@rEmployeeCode)
	SET @rEmployeeName = sCommon.fSearchStringGet(@rEmployeeName)

	--DECLARE @lConfigValue nvarchar(50) = ''
	--DECLARE @lIsOnPrePrinted bit = 0
	--DECLARE @lIsDisplayImageHeader bit=0

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

	SELECT 
		@rOrderByField AS OrderByField,
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,	
		ISNULL(ESO.EPFNumber,'') AS PFNumber,
		EM.EmployeeId,
		tEM.FirstName +' '+tEM.MiddleName+' '+ tEM.LastName AS EmployeeName,
		EM.Code AS EmployeeCode,
		ISNULL(PPE.GrossBasic,0) AS GrossBasic,
		PFS.PfSalaryLimit,
		PFS.FpsSalaryLimit,
		PFS.EmployeePfPercent,
		PFS.EmployerPfPercent,
		PFS.EmployerFpsPercent,
		PFS.AdminChargesPercent,
		PFS.EdliPercent,
		PFS.InspectionChargesPercent,
		PFPro.PayProcessElementId,
		PFPro.EmployeePfAmount,
		PFPro.EmployerPfAmount,
		PFPro.EmployerFpsAmount,
		PFPro.AdminChargesAmount,
		PFPro.EdliChargesAmount,
		PFPro.InspectionChargesAmount,
		PY.Title AS PayrollYearName,
		PP.SalaryMonth,
		PP.SalaryYear,
	    MM.Title AS MonthName,
	    (ISNULL(AT.TotalWorkingDays,0) - ISNULL(AT.LWP,0)) AS WorkingDays,
	   (SELECT ISNULL(SUM(PPE.Amount),0) FROM sPayroll.tPayProcessElement PPE INNER JOIN sPayroll.tPayElement P  
	    ON PPE.PayElementId =  P.ID  WHERE PPE.PayProcessEmployeeId = PE.PayProcessEmployeeId AND PayElementId IN 
		(SELECT DependentPayElementId FROM sPayroll.tPaySetupDependent PD INNER JOIN sPayroll.tPaySetup PS ON  PD.PaySetupId = PS.ID
		INNER JOIN sPayroll.tPayElement PE ON PS.PayElementId = PE.ID WHERE PS.PayrollId = @rPayrollId AND PS.PayrollYearId = @rPayrollYearId 
		AND PE.PayElementDefaultId = 56 AND ((PS.SourceTypeId=2020 AND ESO.PayrollGroupId=PS.SourceId) OR (PS.SourceTypeId=95 AND tEM.Id=PS.SourceId)))
		) 
		AS Salary,
	    ISNULL(ESO.UAN,'') AS UAN,
	    PPE.TotalEarning,
	    EM.FirstName,
		EM.LastName,
		tEM.Number,
		--@lIsOnPrePrinted AS IsOnPrePrinted,
		--@lIsDisplayImageHeader AS IsDisplayImageHeader,
		--ISNULL(OI.PayrollHeaderA4,0x) AS PayrollHeader
		(CASE WHEN ISNULL(PM.HeaderDisplayId,1) = 3 THEN ISNULL(PM.PayrollHeader,0x) ELSE NULL END) AS PayrollHeader,
		--ISNULL(PM.PayrollHeader,0x) AS PayrollHeader,
		ISNULL(PM.HeaderDisplayId,1)AS HeaderDisplayId

	FROM 
		sPayroll.tPayProcess PP 
		INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId=PP.ID
		INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = PPE.EmployeeId
		INNER JOIN sHrm.tEmployeeMaster tEM ON tEM.Id=PPE.EmployeeId
		LEFT JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.EmployeeId=EM.EmployeeId
		INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
		INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID 
		INNER JOIN sPayroll.tPfProcess PFPro ON PFPro.PayProcessElementId=PE.ID
		INNER JOIN sPayroll.tPayrollYearMaster PY ON PP.PayrollYearId = PY.Id
		INNER JOIN sPayroll.tPfSetup PFS ON PFS.PayrollYearId = PY.Id 
		INNER JOIN sCommon.tMonthMaster MM ON MM.Id=PP.SalaryMonth
		--INNER JOIN sHrm.tEmployeeAttendance AT ON AT.EmployeeId=EM.EmployeeId AND AT.ForMonth=@rForMonth AND AT.ForYear =@rForYear
		--INNER JOIN sHrm.tEmployeeAttendance AT ON AT.EmployeeId=EM.EmployeeId AND ((AT.ForMonth = 0) OR (0 = 0))  AND ((AT.ForYear = 0) OR (0 = 0)) 
		INNER JOIN sHrm.tEmployeeAttendance AT ON AT.EmployeeId=EM.EmployeeId AND ((AT.ForMonth = @rForMonth) OR (@rForMonth = 0))  AND ((AT.ForYear = @rForYear) OR (@rForYear = 0)) 
		LEFT JOIN 
		(
		SELECT PE.Amount,PPE.WorkingDays,PPE.PayProcessId,PPE.EmployeeId, PPE.PayrollGroupId
		FROM sPayroll.tPayProcess PP 
		INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId=PP.ID
		INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = PPE.EmployeeId
		INNER JOIN sHrm.tEmployeeMaster tEM ON tEM.Id=PPE.EmployeeId
		LEFT JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.EmployeeId=EM.EmployeeId
		INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
		INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID AND P.PayElementDefaultId = 1
		INNER JOIN sPayroll.tPayrollYearMaster PY ON PP.PayrollYearId = PY.Id
		WHERE 
		(PPE.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
		AND ((EM.Code Like @rEmployeeCode) OR (@rEmployeeCode = ''))
		AND ((EM.EmployeeName Like @rEmployeeName) OR (@rEmployeeName = ''))
		AND ((PP.SalaryMonth = @rForMonth) OR (@rForMonth = 0))
	    AND ((PP.SalaryYear = @rForYear) OR (@rForYear = 0))
		AND ((PY.PayrollId=@rPayrollId) OR (@rPayrollId=0))
		AND (PPE.PayrollGroupId = @rPayrollGroupId OR @rPayrollGroupId = 0) 
		AND (PP.PayrollYearId = @rPayrollYearId OR @rPayrollYearId = 0) 
		AND ((EM.DateOfleaving >= @lFirstDate) OR ISNULL(EM.DateOfleaving,'') = '')
        AND ((EM.DateOfJoining <= @lLasteDate) OR ISNULL(EM.DateOfJoining,'') = '')
		AND ((tEM.OrgID = @rOrgId) OR (@rOrgId = 0))
		AND (EM.DepartmentId = @rDepartmentId OR @rDepartmentId = 0)
		AND ((tEM.StatusId = @rStatusId) OR (@rStatusId = 0))
		) A ON A.PayProcessId = PPE.PayProcessId AND A.EmployeeId = PPE.EmployeeId  AND A.PayrollGroupId =  PPE.PayrollGroupId
		--LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = tEM.OrgID
		INNER JOIN sPayroll.tPayrollMaster PM ON PY.PayrollId = PM.Id
		
WHERE 
		(PPE.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
		AND ((EM.Code Like @rEmployeeCode) OR (@rEmployeeCode = ''))
		AND ((EM.EmployeeName Like @rEmployeeName) OR (@rEmployeeName = ''))
		AND ((PP.SalaryMonth = @rForMonth) OR (@rForMonth = 0))
	    AND ((PP.SalaryYear = @rForYear) OR (@rForYear = 0))
		AND ((PY.PayrollId=@rPayrollId) OR (@rPayrollId=0))
		AND (PPE.PayrollGroupId = @rPayrollGroupId OR @rPayrollGroupId = 0) 
		AND (PP.PayrollYearId = @rPayrollYearId OR @rPayrollYearId = 0) 
		AND ((EM.DateOfleaving >= @lFirstDate) OR ISNULL(EM.DateOfleaving,'') = '')
        AND ((EM.DateOfJoining <= @lLasteDate) OR ISNULL(EM.DateOfJoining,'') = '')
		AND ((tEM.OrgID = @rOrgId) OR (@rOrgId = 0))
		AND (EM.DepartmentId = @rDepartmentId OR @rDepartmentId = 0)
		AND ((tEM.StatusId = @rStatusId) OR (@rStatusId = 0))
		AND ((EM.EmployeeGroupId = @rEmployeeGroupId) OR (@rEmployeeGroupId = 0))
END
GO
PRINT N'Altering [sPayroll].[pRptPFECRFormat]...';


GO
 
ALTER PROCEDURE [sPayroll].[pRptPFECRFormat]
	
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rEmployeeId bigint,
	 @rEmployeeCode nvarchar(200),
	 @rEmployeeName nvarchar(200),
	 @rForMonth int,
	 @rForYear int,
	 @rPayrollId int,
	 @rPayrollGroupId int,
	 @rPayrollYearId int,
	 @rOrgGroupId int,
	 @rOrderByField nvarchar(20)='',
	 @rOrgId int = 0,
	 @rDepartmentId int = 0,
	 @rStatusId int = 0,
	 @rEmployeeGroupId int = 0
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

DECLARE @lFirstDate Date
DECLARE @lLasteDate Date


SET @lFirstDate = CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'/'+CONVERT(NVARCHAR(2),@rForMonth)+'/01'))
SET @lLasteDate=DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,@lFirstDate)+1,0))	

DECLARE @lIsActivateUniqueId bit = 0
DECLARE @lIsECRIsLWP nvarchar(10)

SELECT @lIsECRIsLWP = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 259 AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId

IF (@lIsECRIsLWP = '') OR (@lIsECRIsLWP = 'False')
	SET @lIsActivateUniqueId = 0
ELSE
	SET @lIsActivateUniqueId = 1

BEGIN  

	SET @rEmployeeCode = sCommon.fSearchStringGet(@rEmployeeCode)
	SET @rEmployeeName = sCommon.fSearchStringGet(@rEmployeeName)

	--DECLARE @lConfigValue nvarchar(50) = ''
	--DECLARE @lIsOnPrePrinted bit = 0
	--DECLARE @lIsDisplayImageHeader bit=0

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

-- For report
	SELECT 
		@rOrderByField AS OrderByField,
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,	
		ISNULL(ESO.EPFNumber,'') AS PFNumber,
		EM.EmployeeId,
		tEM.FirstName +' '+tEM.MiddleName+' '+ tEM.LastName AS EmployeeName,
		EM.Code AS EmployeeCode,
		ISNULL(PPE.GrossBasic,0) AS GrossBasic,
		PFS.PfSalaryLimit,
		PFS.FpsSalaryLimit,
		PFS.EmployeePfPercent,
		PFS.EmployerPfPercent,
		PFS.EmployerFpsPercent,
		PFS.AdminChargesPercent,
		PFS.EdliPercent,
		PFS.InspectionChargesPercent,
		PFPro.PayProcessElementId,
		PFPro.EmployeePfAmount,
		PFPro.EmployerPfAmount,
		PFPro.EmployerFpsAmount,
		PFPro.AdminChargesAmount,
		PFPro.EdliChargesAmount,
		PFPro.InspectionChargesAmount,
		PY.Title AS PayrollYearName,
		PP.SalaryMonth,
		PP.SalaryYear,
	    MM.Title AS MonthName,
	    ISNULL(A.WorkingDays,0) AS WorkingDays,
	    (SELECT ISNULL(SUM(PPE.Amount),0) FROM sPayroll.tPayProcessElement PPE INNER JOIN sPayroll.tPayElement P  
	    ON PPE.PayElementId =  P.ID  WHERE PPE.PayProcessEmployeeId = PE.PayProcessEmployeeId AND PayElementId IN 
		(SELECT DependentPayElementId FROM sPayroll.tPaySetupDependent PD INNER JOIN sPayroll.tPaySetup PS ON  PD.PaySetupId = PS.ID
		INNER JOIN sPayroll.tPayElement PE ON PS.PayElementId = PE.ID WHERE PS.PayrollId = @rPayrollId AND PS.PayrollYearId = @rPayrollYearId 
		AND PE.PayElementDefaultId = 56 AND ((PS.SourceTypeId=2020 AND ESO.PayrollGroupId=PS.SourceId) OR (PS.SourceTypeId=95 AND tEM.Id=PS.SourceId)))
		) 
		AS Salary,
	    ISNULL(ESO.UAN,'') AS UAN,
	    CASE WHEN @lIsActivateUniqueId = 1 THEN ROUND(1+PPE.Lwp,0)-1 ELSE 0 END AS NCPDays,
	    ISNULL(A.TotalEarning,0) AS TotalEarning,
	    EM.FirstName,
		EM.LastName,
		tEM.Number,
		--@lIsOnPrePrinted AS IsOnPrePrinted,
		--@lIsDisplayImageHeader AS IsDisplayImageHeader,
		--ISNULL(OI.PayrollHeaderA4,0x) AS PayrollHeader
		(CASE WHEN ISNULL(PM.HeaderDisplayId,1) = 3 THEN ISNULL(PM.PayrollHeader,0x) ELSE NULL END) AS PayrollHeader,
		--ISNULL(PM.PayrollHeader,0x) AS PayrollHeader,
		ISNULL(PM.HeaderDisplayId,1)AS HeaderDisplayId
	FROM 
		sPayroll.tPayProcess PP 
		INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId=PP.ID
		INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = PPE.EmployeeId
		INNER JOIN sHrm.tEmployeeMaster tEM ON tEM.Id=PPE.EmployeeId
		LEFT JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.EmployeeId=EM.EmployeeId
		INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
		INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID 
		INNER JOIN sPayroll.tPfProcess PFPro ON PFPro.PayProcessElementId=PE.ID
		INNER JOIN sPayroll.tPayrollYearMaster PY ON PP.PayrollYearId = PY.Id
		INNER JOIN sPayroll.tPfSetup PFS ON PFS.PayrollYearId = PY.Id 
		INNER JOIN sCommon.tMonthMaster MM ON MM.Id=PP.SalaryMonth
		INNER JOIN sPayroll.tPayrollMaster PM ON PY.PayrollId = PM.Id
		LEFT JOIN 
		(
		SELECT PE.Amount,PPE.WorkingDays,PPE.PayProcessId,PPE.EmployeeId, PPE.PayrollGroupId,PPE.TotalEarning
		FROM sPayroll.tPayProcess PP 
		INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId=PP.ID
		INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = PPE.EmployeeId
		INNER JOIN sHrm.tEmployeeMaster tEM ON tEM.Id=PPE.EmployeeId
		LEFT JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.EmployeeId=EM.EmployeeId
		INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
		INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID AND P.PayElementDefaultId = 1
		INNER JOIN sPayroll.tPayrollYearMaster PY ON PP.PayrollYearId = PY.Id
		WHERE 
		(PPE.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
		AND ((EM.Code Like @rEmployeeCode) OR (@rEmployeeCode = ''))
		AND ((EM.EmployeeName Like @rEmployeeName) OR (@rEmployeeName = ''))
		AND ((PP.SalaryMonth = @rForMonth) OR (@rForMonth = 0))
	    AND ((PP.SalaryYear = @rForYear) OR (@rForYear = 0))
		AND ((PY.PayrollId=@rPayrollId) OR (@rPayrollId=0))
		AND (PPE.PayrollGroupId = @rPayrollGroupId OR @rPayrollGroupId = 0) 
		AND (PP.PayrollYearId = @rPayrollYearId OR @rPayrollYearId = 0) 
		AND ((EM.DateOfleaving >= @lFirstDate) OR ISNULL(EM.DateOfleaving,'') = '')
        AND ((EM.DateOfJoining <= @lLasteDate) OR ISNULL(EM.DateOfJoining,'') = '')
		AND ((tEM.OrgID = @rOrgId) OR (@rOrgId = 0))
		AND (EM.DepartmentId = @rDepartmentId OR @rDepartmentId = 0)
		AND ((tEM.StatusId = @rStatusId) OR (@rStatusId = 0))
		AND ((EM.EmployeeGroupId = @rEmployeeGroupId) OR (@rEmployeeGroupId = 0))
		) A ON A.PayProcessId = PPE.PayProcessId AND A.EmployeeId = PPE.EmployeeId  AND A.PayrollGroupId =  PPE.PayrollGroupId
		--LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = tEM.OrgID
WHERE 
		(PPE.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
		AND ((EM.Code Like @rEmployeeCode) OR (@rEmployeeCode = ''))
		AND ((EM.EmployeeName Like @rEmployeeName) OR (@rEmployeeName = ''))
		AND ((PP.SalaryMonth = @rForMonth) OR (@rForMonth = 0))
	    AND ((PP.SalaryYear = @rForYear) OR (@rForYear = 0))
		AND ((PY.PayrollId=@rPayrollId) OR (@rPayrollId=0))
		AND (PPE.PayrollGroupId = @rPayrollGroupId OR @rPayrollGroupId = 0) 
		AND (PP.PayrollYearId = @rPayrollYearId OR @rPayrollYearId = 0) 
		AND ((tEM.OrgID = @rOrgId) OR (@rOrgId = 0))
		AND (EM.DepartmentId = @rDepartmentId OR @rDepartmentId = 0)
		AND ((tEM.StatusId = @rStatusId) OR (@rStatusId = 0))
		AND ((EM.EmployeeGroupId = @rEmployeeGroupId) OR (@rEmployeeGroupId = 0))
--	For Notepad report
	
	SELECT 
		ISNULL(ESO.UAN,'') AS UAN,
		tEM.FirstName +' '+tEM.MiddleName+' '+ tEM.LastName AS EmployeeName,
		--ISNULL(cast(replace(A.TotalEarning, '.','') as integer),0) AS TotalEarning,
		ISNULL(CONVERT(DECIMAL(12,0),A.TotalEarning),0) AS TotalEarning,
		CASE WHEN ISNULL(PFS.PfSalaryLimit,0) > (SELECT ISNULL(SUM(PPE.Amount),0) FROM sPayroll.tPayProcessElement PPE INNER JOIN sPayroll.tPayElement P  
	    ON PPE.PayElementId =  P.ID  WHERE PPE.PayProcessEmployeeId = PE.PayProcessEmployeeId AND PayElementId IN 
		(SELECT DependentPayElementId FROM sPayroll.tPaySetupDependent PD INNER JOIN sPayroll.tPaySetup PS ON  PD.PaySetupId = PS.ID
		INNER JOIN sPayroll.tPayElement PE ON PS.PayElementId = PE.ID WHERE PS.PayrollId = @rPayrollId AND PS.PayrollYearId = @rPayrollYearId 
		AND PE.PayElementDefaultId = 56 AND ((PS.SourceTypeId=2020 AND ESO.PayrollGroupId=PS.SourceId) OR (PS.SourceTypeId=95 AND tEM.Id=PS.SourceId)))
		)  
		THEN 
		--(SELECT ISNULL(SUM(cast(replace(PPE.Amount, '.','') as integer)),0) FROM sPayroll.tPayProcessElement PPE 
		(SELECT ISNULL(SUM(CONVERT(DECIMAL(12,0),PPE.Amount)),0) FROM sPayroll.tPayProcessElement PPE
		INNER JOIN sPayroll.tPayElement P ON PPE.PayElementId =  P.ID  WHERE PPE.PayProcessEmployeeId = PE.PayProcessEmployeeId AND PayElementId 
		IN 
		(SELECT DependentPayElementId FROM sPayroll.tPaySetupDependent PD INNER JOIN sPayroll.tPaySetup PS ON  PD.PaySetupId = PS.ID
		INNER JOIN sPayroll.tPayElement PE ON PS.PayElementId = PE.ID WHERE PS.PayrollId = @rPayrollId AND PS.PayrollYearId = @rPayrollYearId 
		AND PE.PayElementDefaultId = 56 AND ((PS.SourceTypeId=2020 AND ESO.PayrollGroupId=PS.SourceId) OR (PS.SourceTypeId=95 AND tEM.Id=PS.SourceId)))
		)  
		--ELSE ISNULL(cast(replace(PFS.PfSalaryLimit, '.','') as integer),0)  END AS PfSalaryLimit1,
		ELSE ISNULL(CONVERT(DECIMAL(12,0),PFS.PfSalaryLimit),0)  END AS PfSalaryLimit1,
		CASE WHEN ISNULL(PFS.PfSalaryLimit,0) > (SELECT ISNULL(SUM(PPE.Amount),0) FROM sPayroll.tPayProcessElement PPE INNER JOIN sPayroll.tPayElement P  
	    ON PPE.PayElementId =  P.ID  WHERE PPE.PayProcessEmployeeId = PE.PayProcessEmployeeId AND PayElementId IN 
		(SELECT DependentPayElementId FROM sPayroll.tPaySetupDependent PD INNER JOIN sPayroll.tPaySetup PS ON  PD.PaySetupId = PS.ID
		INNER JOIN sPayroll.tPayElement PE ON PS.PayElementId = PE.ID WHERE PS.PayrollId = @rPayrollId AND PS.PayrollYearId = @rPayrollYearId 
		AND PE.PayElementDefaultId = 56 AND ((PS.SourceTypeId=2020 AND ESO.PayrollGroupId=PS.SourceId) OR (PS.SourceTypeId=95 AND tEM.Id=PS.SourceId)))
		)  THEN 
		--(SELECT ISNULL(SUM(cast(replace(PPE.Amount, '.','') as integer)),0) FROM sPayroll.tPayProcessElement PPE INNER JOIN sPayroll.tPayElement P  
		(SELECT ISNULL(SUM(CONVERT(DECIMAL(12,0),PPE.Amount)),0) FROM sPayroll.tPayProcessElement PPE INNER JOIN sPayroll.tPayElement P
	    ON PPE.PayElementId =  P.ID  WHERE PPE.PayProcessEmployeeId = PE.PayProcessEmployeeId AND PayElementId IN 
		(SELECT DependentPayElementId FROM sPayroll.tPaySetupDependent PD INNER JOIN sPayroll.tPaySetup PS ON  PD.PaySetupId = PS.ID
		INNER JOIN sPayroll.tPayElement PE ON PS.PayElementId = PE.ID WHERE PS.PayrollId = @rPayrollId AND PS.PayrollYearId = @rPayrollYearId 
		AND PE.PayElementDefaultId = 56 AND ((PS.SourceTypeId=2020 AND ESO.PayrollGroupId=PS.SourceId) OR (PS.SourceTypeId=95 AND tEM.Id=PS.SourceId)))
		)  
		--ELSE ISNULL(cast(replace(PFS.PfSalaryLimit, '.','') as integer),0)  END AS PfSalaryLimit2,
		ELSE ISNULL(CONVERT(DECIMAL(12,0),PFS.PfSalaryLimit),0)  END AS PfSalaryLimit2,
		CASE WHEN ISNULL(PFS.PfSalaryLimit,0) > (SELECT ISNULL(SUM(PPE.Amount),0) FROM sPayroll.tPayProcessElement PPE INNER JOIN sPayroll.tPayElement P  
	    ON PPE.PayElementId =  P.ID  WHERE PPE.PayProcessEmployeeId = PE.PayProcessEmployeeId AND PayElementId IN 
		(SELECT DependentPayElementId FROM sPayroll.tPaySetupDependent PD INNER JOIN sPayroll.tPaySetup PS ON  PD.PaySetupId = PS.ID
		INNER JOIN sPayroll.tPayElement PE ON PS.PayElementId = PE.ID WHERE PS.PayrollId = @rPayrollId AND PS.PayrollYearId = @rPayrollYearId 
		AND PE.PayElementDefaultId = 56 AND ((PS.SourceTypeId=2020 AND ESO.PayrollGroupId=PS.SourceId) OR (PS.SourceTypeId=95 AND tEM.Id=PS.SourceId)))
		)  
		--THEN (SELECT ISNULL(SUM(cast(replace(PPE.Amount, '.','') as integer)),0) FROM sPayroll.tPayProcessElement PPE INNER JOIN sPayroll.tPayElement P
		THEN (SELECT ISNULL(SUM(CONVERT(DECIMAL(12,0),PPE.Amount)),0) FROM sPayroll.tPayProcessElement PPE INNER JOIN sPayroll.tPayElement P  
	    ON PPE.PayElementId =  P.ID  WHERE PPE.PayProcessEmployeeId = PE.PayProcessEmployeeId AND PayElementId IN 
		(SELECT DependentPayElementId FROM sPayroll.tPaySetupDependent PD INNER JOIN sPayroll.tPaySetup PS ON  PD.PaySetupId = PS.ID
		INNER JOIN sPayroll.tPayElement PE ON PS.PayElementId = PE.ID WHERE PS.PayrollId = @rPayrollId AND PS.PayrollYearId = @rPayrollYearId 
		AND PE.PayElementDefaultId = 56 AND ((PS.SourceTypeId=2020 AND ESO.PayrollGroupId=PS.SourceId) OR (PS.SourceTypeId=95 AND tEM.Id=PS.SourceId)))
		--)  ELSE ISNULL(cast(replace(PFS.PfSalaryLimit, '.','') as integer),0)  END AS PfSalaryLimit3,
		)  ELSE ISNULL(CONVERT(DECIMAL(12,0),PFS.PfSalaryLimit),0)  END AS PfSalaryLimit3,
		--ISNULL(PFS.PfSalaryLimit,0) AS PfSalaryLimit1,
		--ISNULL(PFS.PfSalaryLimit,0) AS PfSalaryLimit2,
		--ISNULL(PFS.PfSalaryLimit,0) AS PfSalaryLimit3,
		--ISNULL(cast(replace(PFPro.EmployeePfAmount, '.','') as integer),0) AS EmployeePfAmount,
		ISNULL(CONVERT(DECIMAL(12,0),PFPro.EmployeePfAmount),0) AS EmployeePfAmount,
		--ISNULL(cast(replace(PFPro.EmployerFpsAmount, '.','') as integer),0) AS EmployerFpsAmount,
		ISNULL(CONVERT(DECIMAL(12,0),PFPro.EmployerFpsAmount),0) AS EmployerFpsAmount,
		--ISNULL(cast(replace(PFPro.EmployeePfAmount, '.','') as integer),0) - ISNULL(cast(replace(PFPro.EmployerFpsAmount, '.','') as integer),0) AS EPFEPS,
		ISNULL(CONVERT(DECIMAL(12,0),PFPro.EmployeePfAmount),0) - ISNULL(CONVERT(DECIMAL(12,0),PFPro.EmployerFpsAmount),0) AS EPFEPS,
		--CASE WHEN @lIsActivateUniqueId = 1 THEN cast(replace(ROUND(1+PPE.Lwp,0)-1, '.','') as integer) ELSE 0 END AS NCPDays,
		CASE WHEN @lIsActivateUniqueId = 1 THEN Convert(DECIMAL(12,0),(1+PPE.Lwp)-1,0) ELSE 0 END AS NCPDays,
		0 AS RefundAdv
	FROM 
		sPayroll.tPayProcess PP 
		INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId=PP.ID
		INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = PPE.EmployeeId
		INNER JOIN sHrm.tEmployeeMaster tEM ON tEM.Id=PPE.EmployeeId
		LEFT JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.EmployeeId=EM.EmployeeId
		INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
		INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID 
		INNER JOIN sPayroll.tPfProcess PFPro ON PFPro.PayProcessElementId=PE.ID
		INNER JOIN sPayroll.tPayrollYearMaster PY ON PP.PayrollYearId = PY.Id
		INNER JOIN sPayroll.tPfSetup PFS ON PFS.PayrollYearId = PY.Id 
		INNER JOIN sCommon.tMonthMaster MM ON MM.Id=PP.SalaryMonth
		LEFT JOIN 
		(
		SELECT PE.Amount,PPE.WorkingDays,PPE.PayProcessId,PPE.EmployeeId, PPE.PayrollGroupId,PPE.TotalEarning
		FROM sPayroll.tPayProcess PP 
		INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId=PP.ID
		INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = PPE.EmployeeId
		INNER JOIN sHrm.tEmployeeMaster tEM ON tEM.Id=PPE.EmployeeId
		LEFT JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.EmployeeId=EM.EmployeeId
		INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
		INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID AND P.PayElementDefaultId = 1
		INNER JOIN sPayroll.tPayrollYearMaster PY ON PP.PayrollYearId = PY.Id
		WHERE 
		(PPE.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
		AND ((EM.Code Like @rEmployeeCode) OR (@rEmployeeCode = ''))
		AND ((EM.EmployeeName Like @rEmployeeName) OR (@rEmployeeName = ''))
		AND ((PP.SalaryMonth = @rForMonth) OR (@rForMonth = 0))
	    AND ((PP.SalaryYear = @rForYear) OR (@rForYear = 0))
		AND ((PY.PayrollId=@rPayrollId) OR (@rPayrollId=0))
		AND (PPE.PayrollGroupId = @rPayrollGroupId OR @rPayrollGroupId = 0) 
		AND (PP.PayrollYearId = @rPayrollYearId OR @rPayrollYearId = 0) 
		AND ((EM.DateOfleaving >= @lFirstDate) OR ISNULL(EM.DateOfleaving,'') = '')
        AND ((EM.DateOfJoining <= @lLasteDate) OR ISNULL(EM.DateOfJoining,'') = '')
		AND ((tEM.OrgID = @rOrgId) OR (@rOrgId = 0))
		AND (EM.DepartmentId = @rDepartmentId OR @rDepartmentId = 0)
		AND ((tEM.StatusId = @rStatusId) OR (@rStatusId = 0))
		AND ((EM.EmployeeGroupId = @rEmployeeGroupId) OR (@rEmployeeGroupId = 0))
		) A ON A.PayProcessId = PPE.PayProcessId AND A.EmployeeId = PPE.EmployeeId  AND A.PayrollGroupId =  PPE.PayrollGroupId
		
WHERE 
		(PPE.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
		AND ((EM.Code Like @rEmployeeCode) OR (@rEmployeeCode = ''))
		AND ((EM.EmployeeName Like @rEmployeeName) OR (@rEmployeeName = ''))
		AND ((PP.SalaryMonth = @rForMonth) OR (@rForMonth = 0))
	    AND ((PP.SalaryYear = @rForYear) OR (@rForYear = 0))
		AND ((PY.PayrollId=@rPayrollId) OR (@rPayrollId=0))
		AND (PPE.PayrollGroupId = @rPayrollGroupId OR @rPayrollGroupId = 0) 
		AND (PP.PayrollYearId = @rPayrollYearId OR @rPayrollYearId = 0) 		
		AND ((tEM.OrgID = @rOrgId) OR (@rOrgId = 0))
		AND (EM.DepartmentId = @rDepartmentId OR @rDepartmentId = 0)
		AND ((tEM.StatusId = @rStatusId) OR (@rStatusId = 0))
		AND ((EM.EmployeeGroupId = @rEmployeeGroupId) OR (@rEmployeeGroupId = 0))
END
GO
PRINT N'Altering [sProcurement].[pStockIssGet]...';


GO
 
 
ALTER PROCEDURE [sProcurement].[pStockIssGet]
	@rOrgGroupId int,
	@rNumber [nvarchar](20) = '',
	@rFromDate date='',
	@rToDate date='',
	@rStoreLocationId int=0,
	@rItemCode nvarchar(100)='',
	@rItemName nvarchar(200)='',
	@rSearchType nvarchar(5)= '1',
	@rIssueToSourceId BIGINT = null,
	@rToDept int = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN	  
SET @rNumber = sCommon.fSearchStringGet(@rNumber)

	if(@rSearchType='1')
		begin
				SELECT		
				SI.Id,SI.Number,isnull(SI.StockIssueRequestId,0) as StockIssueRequestId,
				SI.IssuedByName,
				case when SI.TransactionDate is not null  then SI.TransactionDate else  SI.CreatedDateTime End AS IssuedDate,
				 SI.CreatedDateTime as TranjactionDate,
				 '' StockItemCode,
				 '' StockItemName,
				 ISNULL(SI.IssueToSourceId,'') as IssueToSourceId,
				 ISNULL(EM.ShortName,'') as ToEmployeeName,
				 ISNULL(DM.DisplayTitle,'') as ToDepartment,
				 ISNULL(SI.IssueToName,'') as IssueToName
				FROM sProcurement.tStockIssue SI 
				LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = SI.IssueToSourceId AND  ISNULL(EM.IsOtherUser,0) = 0
				LEFT JOIN sSetup.tDepartmentMaster DM ON DM.Id = SI.ToOrganizationDepartmentId
				WHERE
				SI.OrgGroupId = @rOrgGroupId 
				AND  ((SI.Number like @rNumber) OR (@rNumber = ''))
				AND (( Convert(Date,SI.CreatedDateTime)>= @rFromDate ) OR (ISNULL(@rFromDate,'')=''))
				AND (( Convert(Date,SI.CreatedDateTime)<= @rToDate ) OR (ISNULL(@rToDate,'')=''))
				AND SI.FromStoreLocationId=@rStoreLocationId 
				AND ((SI.IssueToSourceId = @rIssueToSourceId) OR (ISNULL(@rIssueToSourceId,'')=''))
				AND ((DM.Id = @rToDept) OR (@rToDept = 0))
				Order by SI.CreatedDateTime desc
		end
	else
		begin
				SELECT		
					SI.Id,SI.Number,isnull(SI.StockIssueRequestId,0) as StockIssueRequestId,
					SI.IssuedByName,
					case when SI.TransactionDate is not null  then SI.TransactionDate else  SI.CreatedDateTime End	AS IssuedDate,
					 SI.CreatedDateTime as TranjactionDate,
					 SIM.Code AS StockItemCode,
					SIM.TItle As StockItemName,
					isnull(SI.IssueToSourceId,'') as IssueToSourceId,
					ISNULL(EM.ShortName,'') as ToEmployeeName,
				    ISNULL(DM.DisplayTitle,'') as ToDepartment,
				    ISNULL(SI.IssueToName,'') as IssueToName
				FROM sProcurement.tStockIssue SI 
				Inner join sProcurement.tStockIssueDetail SIDE on SI.ID= SIDE.StockIssueId
				INNER JOIN sIp.tStockItemMaster SIM ON SIM.Id = SIDE.StockItemID
				LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = SI.IssueToSourceId AND  ISNULL(EM.IsOtherUser,0) = 0
				LEFT JOIN sSetup.tDepartmentMaster DM ON DM.Id = SI.ToOrganizationDepartmentId
				WHERE ((SI.Number like @rNumber) OR (@rNumber = ''))
				AND  SI.OrgGroupId = @rOrgGroupId 
				AND (( Convert(Date,SI.CreatedDateTime)>= @rFromDate ) OR (ISNULL(@rFromDate,'')=''))
				AND (( Convert(Date,SI.CreatedDateTime)<= @rToDate ) OR (ISNULL(@rToDate,'')=''))
				AND SI.FromStoreLocationId=@rStoreLocationId 
				AND (SIM.Id = @rItemCode or @rItemCode='')
				AND (SIM.Title = @rItemName or @rItemName='')
				AND ((SI.IssueToSourceId = @rIssueToSourceId) or (ISNULL(@rIssueToSourceId,'')=''))
				AND ((DM.Id = @rToDept) OR (@rToDept = 0))
				Order by SI.CreatedDateTime desc
		end
END
GO
PRINT N'Altering [sStudent].[pAcademicAdd]...';


GO
 
 
ALTER PROCEDURE [sStudent].[pAcademicAdd]
	 
	@rAcademicId bigint=0,
	@rStudentId bigint=0,
	@rClassId int=0,
	@rDivisionId int=0,
	@rRollNo int=0,
	@rOrgId int=0,
	@rBatchId int=0,
	@rCreatedUserId bigint=0,
	@rUpdatedUserId bigint=0,
	@rAdmissionCategoryId int = 0,
	@rClassStatusId int=0,
	@rFeesRemark nvarchar(500)=''
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	SET @rRollNo = ISNULL(@rRollNo,0)
	
	 BEGIN TRANSACTION	
 IF NOT EXISTS(Select Id from sStudent.tAcademic where StudentId=@rStudentId AND BatchId=@rBatchId)
BEGIN
	
	DECLARE @lNextNumber BIGINT     
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sStudent.tAcademic', 0, 1, 1,@outNextNumber = @lNextNumber output



--IF ISNULL(@rRollNo,0) <> 0
--BEGIN
--IF EXISTS(Select Id from sStudent.tAcademic where RollNo = @rRollNo AND DivisionId = @rDivisionId )
--BEGIN
--SET @rRollNo = 0
--END
--END
--ELSE
--BEGIN
--  SELECT @rRollNo =  (ISNULL(max(RollNo),0) + 1) FROM  sStudent.tAcademic where DivisionId=@rDivisionId AND BatchId=@rBatchId
--END
 
	INSERT INTO sStudent.tAcademic
		(
			Id,
			StudentId,
			ClassId,
			DivisionId,
			RollNo,
			OrgId,
			BatchId,
			CreatedUserId,
			CreatedDateTime,
			IsCurrent,
			BatchStatusId,
			AdmissionCategoryId,
			ClassStatusId,
			FeesRemark
		)
	VALUES
		(
			@lNextNumber,
			@rStudentId,
			@rClassId,
			@rDivisionId,
			@rRollNo,
			@rOrgId,
			@rBatchId,
			@rCreatedUserId,
			sCommon.fGetDate()
			,1
			,1
			,@rAdmissionCategoryId,
			@rClassStatusId,
			@rFeesRemark
		)	
		
	   INSERT INTO sStudent.tAcademicDetail
		(
		AcademicId,
		RepeatCount
		)
		VALUES
		(
		@lNextNumber,
		1
		)
			
        UPDATE sStudent.tAcademic SET IsCurrent = 0 WHERE StudentId = @rStudentId AND OrgId = @rOrgId AND BatchId <>  @rBatchId        
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rAcademicId
	 
	 
--if ISNULL(@rRollNo,0) <> 0
--BEGIN
--IF EXISTS(Select Id from sStudent.tAcademic where RollNo = @rRollNo AND DivisionId = @rDivisionId AND Id <> @rAcademicId )
--BEGIN
--SET @rRollNo = 0
--END
--END
	 
	    UPDATE sStudent.tAcademic
	    SET
			ClassId=@rClassId,
			DivisionId=@rDivisionId,
			RollNo=@rRollNo,
			OrgId=@rOrgId,
			BatchId=@rBatchId,
			UpdatedUserId=@rUpdatedUserId,
			UpdatedDateTime=sCommon.fGetDate() ,
			AdmissionCategoryId = @rAdmissionCategoryId,
			ClassStatusId=@rClassStatusId,
			FeesRemark=@rFeesRemark
	      WHERE 
	       --Id = @rAcademicId  AND 
	       StudentId=@rStudentId  AND 
	       BatchId = @rBatchId
	      
	 END  			
		COMMIT TRANSACTION
		SELECT @lNextNumber AS Result
		
	--UPDATE sStudent.tAcademic SET BatchStatusId = 1 WHERE BatchStatusId is null
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sStudent].[pStudentFullProfileGet]...';


GO
 
 
ALTER PROCEDURE [sStudent].[pStudentFullProfileGet]
	 
	 @rBatchId int,
	 @rStudentId bigint,
	 @rReportId int=0,
	 @rOrgId int,
	 @rStrCode nvarchar(max)='',
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rFromRollNo int=0,
	 @rToRollNo int=0,
	 @rStatusId int=0,
	 @rClassStatusId int=0,
	 @rDateOfBirth int=0,
	 @rDepartmentId int=0,
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='',
	 @rOrgGroupBatchId int,
	 @rFromAdmissionDate date = '',
	 @rToAdmissionDate date = ''
	 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	
	DECLARE @lAcademicId bigint
	SELECT @lAcademicId = Id from sStudent.tAcademic Where StudentId = @rStudentId AND BatchId = @rBatchId
	
	SELECT 
			--Academic
			@rBuilder1 As Builder1,
			SA.StudentId AS Id,
			--SA.FirstName + ' ' + ISNULL(SA.MiddleName,'') + ' ' + 	SA.LastName AS StudentName,
			SA.Name AS StudentName,
			SA.FirstName as FirstName,
			SA.MiddleName as MiddleName,
			SA.LastName as LastName,
			SA.Batch AS AcademicYear,
			ISNULL(SA.Code,' - ') AS Code,
			SA.ClassDivision AS ClassDiv,			
			SA.RollNo,
			ISNULL(SM.Title,'-') AS House,
			--Other
			CASE WHEN @rReportId=0 THEN ISNULL(SA.DateOfBirth,'0001/01/01')  
			WHEN @rReportId=1 THEN  SA.DateOfBirth END  AS DateOfBirth,
			ISNULL(SA.BirthTaluka,'') AS BirthTaluka,
			ISNULL(SA.BirthPlace,'') AS BirthPlace,	
			ISNULL(SA.BirthDistrict,'') AS BirthDistrict,
			ISNULL(SA.BirthDateInWord,'') AS BirthDateInWord,                           
			ISNULL(SA.Gender,'') AS Gender,
			ISNULL(SA.Religion,'') AS Religion,
			--Admission			
			ISNULL(SA.AdmissionStandard,'') AS AdmissionStandard,
			--ISNULL(SA.AdmissionDate,'0001/01/01') AS AdmissionDate,
			CASE WHEN @rReportId=0 THEN ISNULL(SA.AdmissionDate,'0001/01/01')
			WHEN @rReportId=1 THEN  SA.AdmissionDate END AS AdmissionDate,
	
			ISNULL(SA.PreviousSchool,'') AS PreviousSchool,
			ISNULL(SA.AdmissionCategory,'') AS StudentAdmissionCategory,
			CASE WHEN @rReportId=0 THEN ISNULL(SA.LeftDate,'0001/01/01')
			WHEN @rReportId=1 THEN  SA.LeftDate END AS LeftDate,
						 
			ISNULL(SA.LeftStandard,'') AS LeftStandard,
			--ISNULL(SA.InactiveDate,'0001/01/01') AS InactiveDate,
			CASE WHEN @rReportId=0 THEN ISNULL(SA.InactiveDate,'0001/01/01')
			WHEN @rReportId=1 THEN  SA.InactiveDate END AS InactiveDate,		
			ISNULL(SA.LCNumber,'') AS LCNumber,
			--ISNULL(SA.LCDate,'0001/01/01') AS LCDate,
			 CASE WHEN @rReportId=0 THEN ISNULL(SA.LCDate,'0001/01/01')
			WHEN @rReportId=1 THEN  SA.LCDate END AS LCDate,
			--Communication
			ISNULL(SA.PresentStreetone,'') + ' ' + ISNULL(SA.PresentStreetTwo,'') + ' ' + ISNULL(SA.PresentStreetThree,'') AS PresentAddress,
			ISNULL(SA.PresentCity,'') AS PresentCity,
			ISNULL(SA.PresentState,'') AS PresentState,
			ISNULL(SA.PresentCountry,'') AS PresentCountry,
			ISNULL(SA.PresentZipCode,'') AS PresentZipCode,
			ISNULL(SA.PresentContactNo,'') AS PresentContactNo,
			
			ISNULL(SA.EmergencyStreetOne,'') + ' ' + ISNULL(SA.EmergencyStreetTwo,'') + ' ' + ISNULL(SA.EmergencyStreetThree,'') AS EmergencyAddress,
			ISNULL(SA.EmergencyCity,'') AS EmergencyCity,
			ISNULL(SA.EmergencyState,'') AS EmergencyState,
			ISNULL(SA.EmergencyCountry,'') AS EmergencyCountry,
			ISNULL(SA.EmergencyZipCode,'') AS EmergencyZipCode,
			ISNULL(SA.EmergencyContactNo,'') AS EmergencyContactNo,
			
			ISNULL(SA.PermanentStreetOne,'') + ' ' + ISNULL(SA.PermanentStreetTwo,'') + ' ' + ISNULL(SA.PermanentStreetThree,'') AS PermanentAddress,
			ISNULL(SA.PermanentCity,'') AS PermanentCity,
			ISNULL(SA.PermanentState,'') AS PermanentState,
			ISNULL(SA.PermanentCountry,'') AS PermanentCountry,
			ISNULL(SA.PermanentZipCode,'') AS PermanentZipCode,
			ISNULL(SA.PermanentContactNo,'') AS PermanentContactNo,
			
			--Parent Information
			ISNULL(SF.FatherName,'') AS FatherName,
			ISNULL(SF.FatherOccupation,'') AS FatherOccupation,
			ISNULL(SF.FatherQualification,'') AS FatherQualification,
			ISNULL(SF.FatherContactNo,'') AS FatherContactNo,
			ISNULL(SF.FatherMail,'') AS FatherMail,
			ISNULL(SF.FatherOfficeAddress,'') AS FatherOfficeAddress,
			ISNULL(SF.FatherDesignation,'') AS FatherDesignation,
			ISNULL(SF.FatherOrganization,'') AS FatherOrganization,
			ISNULL(SF.FatherIncome,'') AS FatherIncome,

			ISNULL(SF.MotherName,'') AS MotherName,
			ISNULL(SF.MotherOccupation,'') AS MotherOccupation,
			ISNULL(SF.MotherQualification,'') AS MotherQualification,
			ISNULL(SF.MotherContactNo,'') AS MotherContactNo,
			ISNULL(SF.MotherMail,'') AS MotherMail,
			ISNULL(SF.MotherOfficeAddress,'') AS MotherOfficeAddress,
			ISNULL(SF.MotherDesignation,'') AS MotherDesignation,
			ISNULL(SF.MotherOrganization,'') AS MotherOrganization,
			ISNULL(SF.MotherIncome,'') AS MotherIncome,

			ISNULL(SF.RelationshipName,'') AS RelationShip,
			ISNULL(SF.RelativeName,'') AS RelativeName,
			ISNULL(SF.RelativeOccupation,'') AS RelativeOccupation,
			ISNULL(SF.RelativeQualification,'') AS RelativeQualification,
			ISNULL(SF.RelativeContactNo,'') AS RelativeContactNo,
			ISNULL(SF.RelativeMail,'') AS RelativeMail,
			ISNULL(SF.RelativeOfficeAddress,'') AS RelativeOfficeAddress,
			ISNULL(SF.RelativeDesignation,'') AS RelativeDesignation,
			ISNULL(SF.RelativeOrganization,'') AS RelativeOrganization,
			ISNULL(SF.RelativeIncome,'') AS RelativeIncome,
			
			--Health Information
			ISNULL(SA.BloodGroup,'') AS BloodGroup,
			ISNULL(SH.IdentificationMark1,'')+' '+ISNULL(SH.IdentificationMark2,'') as IdentificationMark,
			
			ISNULL(SH.FamilyDoctorName,'') AS FamilyDoctorName,
			ISNULL(SH.FamilyDoctorContactNo,'') AS FamilyDoctorContactNo,
			
			ISNULL(SH.IsPysicalDeformity,0) AS IsPysicalDeformity,
			ISNULL(SH.PysicalDeformityRemark,'') AS PysicalDeformityRemark,
			ISNULL(SH.IsMajorIllness,0) AS IsMajorIllness,
			ISNULL(SH.MajorIllnessRemark,'') As MajorIllnessRemark,
			ISNULL(SH.IsAllergy,0) AS IsAllergy,
			ISNULL(SH.AllergyRemark,'') As AllergyRemark,
			ISNULL(SH.IsPastHistory,0) As IsPastHistory ,
			ISNULL(SH.PastHistoryRemark,'') As PastHistoryRemark,
			--Hostel
			ISNULL(RM.Title,'') AS RoomNo,			
			ISNULL(HM.Title,'') AS Hostel,
			ISNULL(EMW.FirstName,'')+' '+ISNULL(EMW.LastName,'') AS WardenName,
			ISNULL(ECW.PhoneNoCompany,'') As WardenPhoneNo,
			ISNULL(ECW.ExtensionNo,'') AS WardenExtNo,
			ISNULL(ECW.MobileNumber,'') AS WardenMobileNo,
			ISNULL(EMA.FirstName,'')+' '+ISNULL(EMA.LastName,'') AS AssignedRoomBy,	
			ISNULL(ECA.PhoneNoCompany,'') AS AssignedRoomByPhoneNo,
			ISNULL(ECA.ExtensionNo,'') AS AssignedRoomByExtNo,
			ISNULL(ECA.MobileNumber,'') AS AssignedRoomByMobileNo,
			--Notification Details
			ISNULL(SA.ParentEmail,'') AS ParentEmail,
			ISNULL(SA.ParentContactNo,'') As ParentContactNo,
			ISNULL(SA.StudentEmail,'') AS StudentEmail,
			ISNULL(SA.StudentContactNo,'') AS StudentContactNo,
					
	   	    --ISNULL(SA.StudentPhoto, CONVERT(VARBINARY(MAX), 0))AS StudentPhoto,
	   	   -- ISNULL(SA.FatherPhoto, CONVERT(VARBINARY(MAX), 0)) AS FatherPhoto,
	   	   -- ISNULL(SA.MotherPhoto, CONVERT(VARBINARY(MAX), 0)) AS MotherPhoto,
	   	    --ISNULL(SA.RelativePhoto, CONVERT(VARBINARY(MAX), 0)) AS RelativePhoto,
	   	   CASE WHEN @rReportId=0
			THEN ISNULL(SA.StudentPhoto, CONVERT(VARBINARY(MAX), 0))
			WHEN @rReportId=1
			THEN ISNULL(SA.StudentPhoto, CONVERT(VARBINARY(MAX), ''))
			END AS StudentPhoto,
			
			CASE WHEN @rReportId=0
			THEN ISNULL(SA.MotherPhoto, CONVERT(VARBINARY(MAX), 0))
			WHEN @rReportId=1
			THEN ISNULL(SA.MotherPhoto, CONVERT(VARBINARY(MAX), ''))
			END AS MotherPhoto,
			
			CASE WHEN @rReportId=0
			THEN ISNULL(SA.FatherPhoto, CONVERT(VARBINARY(MAX), 0))
			WHEN @rReportId=1
			THEN ISNULL(SA.FatherPhoto, CONVERT(VARBINARY(MAX), ''))
			END AS FatherPhoto,
			
			CASE WHEN @rReportId=0
			THEN ISNULL(SA.RelativePhoto, CONVERT(VARBINARY(MAX), 0))
			WHEN @rReportId=1
			THEN ISNULL(SA.RelativePhoto, CONVERT(VARBINARY(MAX), ''))
			END AS RelativePhoto,
		   -- Transport Details
		    A.VehicleName AS VehicleName,
		    A.VehicleRegistrationNumber AS VehicleRegistrationNumber,
		    A.TypeOfVehicle AS TypeOfVehicle,
		    ISNULL(A.BusRoute,'') AS BusRoute,
		    A.DriverName,
		    A.DriverMobileNo,
		    A.ConductorName,
		    A.ConductorMobileNo,
		    ISNULL(A.BusRouteDestination,'') AS BusRouteDestination,
		    
		    A.DropVehicleName AS DropVehicleName,
		    A.DropVehicleRegistrationNumber AS DropVehicleRegistrationNumber,
		    A.DropTypeOfVehicle AS DropTypeOfVehicle,
		    ISNULL(A.DropRoute,'') AS DropRoute,
		    A.DropRouteDriverName AS DropRouteDriverName,
		    A.DropRouteDriverMobileNo AS DropRouteDriverMobileNo,
		    A.DropRouteConductorName AS DropRouteConductorName,
		    A.DropRouteConductorMobileNo AS DropRouteConductorMobileNo,
		    ISNULL(A.DropDestination,'') AS DropDestination,
		    
		    --ClassTeacher Details
		    ISNULL(EMT.Id,0) AS TeacherId,
		    EMT.FirstName+' '+EMT.MiddleName+' '+EMT.LastName AS TeacherFullName,
		    EDM.Title AS TeacherDesignation,
		    EPD.Qualification AS TeacherQualification,
		    ISNULL(EI.EmployeePhoto, CONVERT(VARBINARY(MAX), 0)) AS TeacherPhoto,
		    ISNULL(DF.IsDisplayFamilyDetail,0) AS IsDisplayFamilyDetail,
		    ISNULL(DF.IsDisplaySiblingDetail,0) AS IsDisplaySiblingDetail,
		    ISNULL(DF.IsDisplayPassportDetail,0) AS IsDisplayPassportDetail,
		    ISNULL(DF.IsDisplayBankDetail,0) AS IsDisplayBankDetail,
		    ISNULL(DF.IsDisplayCBSEREGDetail,0) AS IsDisplayCBSEREGDetail,
		    ISNULL(DF.IsDisplayCollegeDetail,0) AS IsDisplayCollegeDetail,
		    ISNULL(DF.IsDisplayGOVREGNoDetail,0) AS IsDisplayGOVREGNoDetail,
		    ISNULL(DF.IsDisplayHealthDetail,0) AS IsDisplayHealthDetail,
		    ISNULL(DF.IsDisplayTransportDetail,0) AS IsDisplayTransportDetail,
		    ISNULL(DF.IsDisplayHostelDetail,0) AS IsDisplayHostelDetail,
		    ISNULL(DF.IsDisplayClubDetail,0) AS IsDisplayClubDetail,
		    
		    ISNULL(DF.IsDisplaySSCResultDDetail,0) AS IsDisplaySSCResultDDetail,
		    ISNULL(DF.IsDisplayHSCResultDetail,0) AS IsDisplayHSCResultDetail,
		    ISNULL(DF.IsDisplayJeeDetail,0) AS IsDisplayJeeDetail,
		    ISNULL(DF.IsDisplayDiplomaDetail,0) AS IsDisplayDiplomaDetail,
			ISNULL(DF.IsDisplayClassTeacherDetail,0) AS IsDisplayClassTeacherDetail,
		    --Sibling Detail
		    isnull(SS.SiblingName1,'') AS SiblingName1,
	        ISNULL (SS.SiblingInstitue1,'') AS SiblingInstitue1,
	        ISNULL(SS.SiblingClass1,'')AS SiblingClass1,
	        ISNULL(SS.SiblingAge1,'')AS SiblingAge1,
	        ISNULL(SS.SiblingRelation1,'')AS SiblingRelation1,
	        isnull(SS.SiblingName2,'') AS SiblingName2,
	        ISNULL(SS.SiblingInstitue2,'')AS SiblingInstitue2,
	        ISNULL(SS.SiblingClass2,'')AS SiblingClass2,
	        ISNULL(SS.SiblingAge2,'') AS SiblingAge2,
	        ISNULL(SS.SiblingRelation2,'')AS SiblingRelation2,
	        isnull(SS.SiblingName3,'') AS SiblingName3,
	        ISNULL( SS.SiblingInstitue3,'')AS SiblingInstitue3,
	        ISNULL(SS.SiblingClass3,'')AS SiblingClass3,
	        ISNULL(SS.SiblingAge3,'')AS SiblingAge3,
	        ISNULL(SS.SiblingRelation3,'')AS SiblingRelation3,
	        ISNULL(SAD.BankAccountNumber,'')AS BankAccountNumber,
	        ISNULL(SAD.BankName,'')AS BankName,
	        ISNULL(SAD.BankBranch,'') AS BankBranch,
	        ISNULL(SAD.BankIFSCCode,'')AS BankIFSCCode,
	        ISNULL(SAD.Class9BoardRegistrationNumber,'') AS Class9BoardRegistrationNumber,
	        ISNULL(SAD.Class11BoardRegistrationNumber,'')AS Class11BoardRegistrationNumber,
	        ISNULL(SAD.PassportNumber,'')AS PassportNumber, 
	        ISNULL(SAD.PassportType,'') AS PassportType,
	       ISNULL( SAD.PassportCountryCode,'') AS PassportCountryCode,
	        CASE WHEN @rReportId=0 THEN ISNULL(SAD.PassportIssueDate,'0001/01/01')
			WHEN @rReportId=1 THEN  SAD.PassportIssueDate END AS PassportIssueDate,
			CASE WHEN @rReportId=0 THEN ISNULL(SAD.PassportExpiryDate,'0001/01/01')
			WHEN @rReportId=1 THEN  SAD.PassportExpiryDate END AS PassportExpiryDate,
	        ISNULL(SA.UIDNumber,'')AS UIDNumber,
	        ISNULL(SA.AdhaarNumber,'') AS AdhaarNumber,
	       ISNull(SA.StatusId,0) AS StatusId,
	       ISNUll(SA.IsTransfer,0)AS IsTransfer,
	       ISNULL(SA.TransferFrom,'') AS TransferFrom,
	       ISNULL(SA.CertificateName,'') AS CertificateName,
	       ISNUll(SA.IsTFWS,0)AS IsTFWS,
	       ISNUll(SA.IsCertificateHolder,0)AS IsCertificateHolder,
	       ISNULL(CD.SSCBoard,'') AS SSCBoard,
	       ISNULL(CD.SSCSchool,'') AS SSCSchool,
	       ISNULL(CD.SSCPassingYear,'') AS SSCPassingYear,
	       ISNULL(CD.SSCObtainMarks,0) AS SSCObtainMarks,
	       ISNULL(CD.SSCOutOfMarks,0) AS SSCOutOfMarks,
	       ISNULL(CD.SSCPercentage,0) AS SSCPercentage,
	       ISNULL(CD.SSCMathMarks,0) AS SSCMathMarks,
	       ISNULL(CD.SSCMathOutOfMarks,0) AS SSCMathOutOfMarks,
	       ISNULL(CD.SSCPercentile,0) AS SSCPercentile,
	       ISNULL(CD.SSCGrade,0) AS SSCGrade,
	       ISNULL(CD.HSCBoard,'') AS HSCBoard,
	       ISNULL(CD.HSCSchool,'') AS HSCSchool,
	       ISNULL(CD.HSCPassingYear,0) AS HSCPassingYear,
	       ISNULL(CD.HSCObtainMarks,0) AS HSCObtainMarks,
	       ISNULL(CD.HSCOutOfMarks,0) AS HSCOutOfMarks,
	       ISNULL(CD.HSCPercentage,0) AS HSCPercentage,
	       ISNULL(CD.HSCPhysicsMarks,0) AS HSCPhysicsMarks,
	       ISNULL(CD.HSCPhysicsOutOfMarks,0) AS HSCPhysicsOutOfMarks,
	       ISNULL(CD.HSCChemistryMarks,0) AS HSCChemistryMarks,
	       ISNULL(CD.HSCChemistryOutOfMarks,0) AS HSCChemistryOutOfMarks,
	       ISNULL(CD.HSCMathMarks,0) AS HSCMathMarks,
	       ISNULL(CD.HSCMathOutOfMarks,0) AS HSCMathOutOfMarks,
	       ISNULL(CD.HSCBiologyMarks,0) AS HSCBiologyMarks,
	       ISNULL(CD.HSCBiologyOutOfMarks,0) AS HSCBiologyOutOfMarks,
	       ISNULL(CD.PCMMarks,0) AS PCMMarks,
	       ISNULL(CD.PCBMarks,0) AS PCBMarks,
	       ISNULL(CD.JEERollNo,'') AS JEERollNo,
	       ISNULL(CD.JEEMeritNo,'') AS JEEMeritNo,
	       ISNULL(CD.JEEMeritMarks,0) AS JEEMeritMarks,
	       ISNULL(CD.JEEOutOfMarks,0) AS JEEOutOfMarks,
	       ISNULL(CD.DiplomaBoard,'') AS DiplomaBoard,
	       ISNULL(CD.DiplomaCollege,'') AS DiplomaCollege,
	       ISNULL(CD.DiplomaPassingYear,'') AS DiplomaPassingYear,
	       ISNULL(CD.DiplomaObtainMarks,0) AS DiplomaObtainMarks,
	       ISNULL(CD.DiplomaOutOfMarks,0) AS DiplomaOutOfMarks,
	       ISNULL(CD.DiplomaPercentage,0) AS DiplomaPercentage,
	       ISNULL(CD.ApplicationNo,'') AS ApplicationNo,
	       ISNULL(CD.AdmissionRound,0) AS AdmissionRound,
	       ISNULL(CD.MaritalStatusId,0) AS MaritalStatusId,
	       ISNULL(MS.Title,'') AS MaritalStatus,
	       ISNULL(ACD.RepeatCount,1)AS RepeatCount,
	       ISNULL(SA.MotherTongue,'') As MotherTongue,
	       ISNULL(SA.FamilyCast,'') AS FamilyCast,
	      ISNULL(CM.Nationality,'') AS Nationality,
	       ISNULL(CT.Title,'') AS CasteCategory,
	       ISnull(SA.ClassName,'') AS ClassName ,
	       ISnull( SA.DivisionName,'') AS DivisionName,
	      ISNULL( SF.IsFatherExStudent,0) AS IsFatherExStudent,
	       ISnull(SF.FatherPassOutYear,'') AS FatherPassOutYear,
	       Isnull(SF.IsMotherExStudent,0) AS IsMotherExStudent,
	       Isnull(SF.MotherPassOutYear,'') AS MotherPassOutYear,
	       ISNULL(SF.IsRelativeExStudent,0) AS IsRelativeExStudent,
	       ISNULL(SF.RelativePassOutYear,'') AS RelativePassOutYear,
	       ISNULL(Sa.PresentDistanceFromSchool,0) AS PresentDistanceFromSchool,
	        SA.StudentId,
	        SA.ClassId,
	        SA.DivisionId,
	        SA.BirthState,
	        SA.BirthCountry,
	         ISNULL(SA.PreviousStandard,'')AS PreviousStandard
	        ,ISNULL(CGG.Title,'') AS CustomGroup
			,ISNULL(SGM.Title,'') As StudentGroup
			,ISNULL(SOGM.Title,'') As StudentOtherGroup
			,ISNULL([sStudent].[fAssignedClubGet](@lAcademicId),'') AS ClubName
			,ISNULL([sStudent].[fAssignedCustomTagGet](@lAcademicId),'') AS CustomTag 
	        ,SA.ClassStatusId
	        ,SA.ClassStatusName
	        ,PDCM.Title As PhysicalDisabilityCategory
			,ISNULL(SAM.PreviousLCNumber,'') AS PreviousLCNumber
			,ISNULL(SAM.PreviousLCDate,'') AS PreviousLCDate,
			ISNULL(SAM.AdmissionNumber,'') AS  AdmissionNumber,
			ISNULL(SAM.AdmissionFormNumber,'') AS  AdmissionFormNumber,
			SA.SUId
	       --[sHostel].[fHostelWardenGet](HM.Id) As WardenName

  FROM 
           sStudent.vStudentAllDetail SA
          -- LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
           LEFT JOIN sStudent.tStudentHealth SH ON SA.StudentId=SH.StudentId
           LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SA.StudentId 
          -- LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId = SA.StudentId
           LEFT JOIN sActivity.tHouseMaster SM ON SM.ID = SA.HouseId
           LEFT JOIN sHostel.tAssignRoom AR ON AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003  AND ((AR.OrgGroupBatchId=@rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
           LEFT JOIN sHostel.tRoomMaster RM ON RM.Id=AR.RoomId
           LEFT JOIN sCommon.tPhysicalDisabilityCategoryMaster PDCM ON PDCM.Id = SH.PhysicalDisabilityCategoryId
           LEFT JOIN sHostel.tHostelMaster HM ON HM.Id=RM.HostelId   
            LEFT JOIN
            (
		   SELECT 
		   employeeId, 
		   HostelId,   
		   ROW_NUMBER() OVER (PARTITION BY HostelId ORDER By HostelId ) as ROWNo 		   
		 
		   FROM sHostel.tHostelwarden 
            )  HW ON HW.HostelId=HM.Id AND RowNo = 1       
           --LEFT JOIN sHostel.tHostelWarden HW ON HW.HostelId=HM.Id
           LEFT JOIN sHrm.tEmployeeMaster EMW ON HW.EmployeeId=EMW.Id AND  ISNULL(EMW.IsOtherUser,0) = 0
           LEFT JOIN sHrm.tEmployeeMaster EMA ON RM.AssignedEmployeeId=EMA.Id AND  ISNULL(EMA.IsOtherUser,0) = 0
           LEFT JOIN sHrm.tEmployeeCommunications ECW ON EMW.Id=ECW.EmployeeId 
           LEFT JOIN sHrm.tEmployeeCommunications ECA ON  EMA.Id=ECA.EmployeeId
           LEFT JOIN 
           ( SElect AR1.SourceId,
           VM.Title AS VehicleName,
		    VM.RegistrationNumber AS VehicleRegistrationNumber,
		    TV.Title AS TypeOfVehicle,
		    ISNULL(BRM.Title,'') AS BusRoute,
		    BRM.DriverName,
		    BRM.DriverMobileNo,
		    BRM.ConductorName,
		    BRM.ConductorMobileNo,
		    ISNULL(BRDM.Title,'') AS BusRouteDestination,
		    VM.Title AS DropVehicleName,
		    VM.RegistrationNumber AS DropVehicleRegistrationNumber,
		    TV1.Title AS DropTypeOfVehicle,
		    ISNULL(BRM1.Title,'') AS DropRoute,
		    BRM1.DriverName AS DropRouteDriverName,
		    BRM1.DriverMobileNo AS DropRouteDriverMobileNo,
		    BRM1.ConductorName AS DropRouteConductorName,
		    BRM1.ConductorMobileNo AS DropRouteConductorMobileNo,
		    ISNULL(BRDM1.Title,'') AS DropDestination
		      FROM
             sTransport.tAssignRoute AR1   
           INNER JOIN sTransport.tBusRouteDestinationMaster BRDM ON BRDM.Id=AR1.PickupDestinationId AND AR1.SourceTypeId=2003
           INNER JOIN sTransport.tBusRouteMaster BRM ON BRM.Id=BRDM.BusRouteId AND ((BRM.OrgGroupBatchId=@rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
           LEFT JOIN sTransport.tVehicleMaster VM ON VM.Id=BRM.VehicleId
           LEFT JOIN sTransport.tVehicleTypeMaster TV ON TV.Id = VM.VehicleTypeId
           LEFT JOIN sTransport.tBusRouteDestinationMaster BRDM1 ON BRDM1.Id=AR1.DropDestinationId
           LEFT JOIN sTransport.tBusRouteMaster BRM1 ON BRM1.Id=BRDM1.BusRouteId AND ((BRM1.OrgGroupBatchId=@rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
           LEFT JOIN sTransport.tVehicleMaster VM1 ON VM1.Id=BRM1.VehicleId
           LEFT JOIN sTransport.tVehicleTypeMaster TV1 ON TV1.Id = VM1.VehicleTypeId) A ON A.SourceId=SA.StudentId
           LEFT JOIN sSetup.tDivisionMaster DM ON  DM.Id=SA.DivisionId
           LEFT JOIN sHrm.tEmployeeMaster EMT ON EMT.Id=DM.InchargeEmployeeId AND  ISNULL(EMT.IsOtherUser,0) = 0
           LEFT JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EMT.Id
           LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id=EJD.EmployeeDesignationId
           LEFT JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId=EMT.Id
           LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId=EMT.Id
           LEFT JOIN sStudent.tStudentSibling  SS ON SS.StudentId=SA.StudentId 
           LEFT JOIN sStudent.tStudentAdditional  SAD ON SAD.StudentId=SA.StudentId 
           LEFT JOIN sStudent.tCollegeDetail  CD ON CD.StudentId=SA.StudentId 
           LEFT JOIN sStudent.tAcademicDetail  ACD ON ACD.AcademicId=SA.AcademicId 
           LEFT JOIN sCommon.tMaritalStatusMaster  MS ON MS.Id=CD.MaritalStatusId
           LEFT JOIN sConfig.fDisplayFieldGet(@rOrgId) AS DF ON DF.OrgId=SA.OrgId
           LEFT JOIN sCommon.tCastCategoryMaster CT ON CT.Id = SA.CastCategoryId
           LEFT JOIN sCommon.tCountryMaster CM ON CM.Id=SA.NationalityId
           INNER JOIN sSetup.tBatchClass BC ON BC.ClassID =  SA.ClassID and BC.BatchId= @rBatchId
           LEFT JOIN sCommunication.tCustomGroupMember CGM ON CGM.SourceId = SA.StudentId AND CGM.SourceTypeId = 2003
           LEFT JOIN sCommunication.tCustomGroup CGG ON CGG.Id = CGM.CustomGroupId
           LEFT JOIN sStudent.tStudentMaster SMM ON SMM.Id = SA.StudentId
           LEFT JOIN sStudent.tStudentGroupMaster SGM ON SGM.Id = SMM.StudentGroupId
           LEFT JOIN sStudent.tStudentOtherGroupMaster SOGM ON SOGM.Id = SMM.StudentOtherGroupId
		   LEFT JOIN sStudent.tStudentAdmission SAM ON SAM.StudentId = SA.StudentId
  WHERE 
			((SA.StudentId=@rStudentId)OR(@rStudentId=0))
			AND((SA.BatchId=@rBatchId) OR(@rBatchId=0))
			AND (ISNULL(SA.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rStrCode,',')) OR @rStrCode='') 
			AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
			AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			AND ((SA.StudentId=@rStudentId) OR (@rStudentId=0))
			AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
			AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
			AND ((SA.StatusId=@rStatusId)OR(@rStatusId=0))
			AND ((SA.ClassStatusId=@rClassStatusId)OR(@rClassStatusId=0))
			AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
			AND ((SA.OrgGroupBatchId=@rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
			AND ((SA.AdmissionDate >= @rFromAdmissionDate) OR (ISNULL(@rFromAdmissionDate,'') = ''))
			AND ((SA.AdmissionDate <= @rToAdmissionDate) OR (ISNULL(@rToAdmissionDate,'') = ''))
			--AND(SA.OrgId=@rOrgId)
			
END
GO
PRINT N'Altering [sStudent].[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
			
  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 [sStudent].[pStudentSearchWithPhotoGet]...';


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

BEGIN 
	 
		BEGIN
			SET @rCode= sCommon.fSearchStringGet(@rCode)
			SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
			SET @rLastName = sCommon.fSearchStringGet(@rLastName)
		END
	IF(@rRollNo IS NULL)
	BEGIN
	SELECT 
			SA.AcademicId,
			SA.StudentId,
			SA.FirstName,
			SA.LastName,
			SA.Name,
			SA.Code,
			SA.ClassId,
			SA.ClassName,
			SA.DivisionId,
			SA.DivisionName,
			ISNULL(SA.Number,0) AS Number,
			SA.RollNo,
			SA.StatusId,
			SA.StatusName,
			SA.OrgId,
			ISNULL(SA.SUId,'') AS SUId,
			ISNULL(SI.StudentPhoto, CONVERT(VARBINARY(MAX), 0)) AS StudentPhoto,
			SA.ClassStatusId,
			SA.ClassStatusName
			
  FROM 
          sStudent.vStudentAcademic SA
       LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=SA.StudentId
       INNER JOIN sSecurity.tUserAccess U ON U.SourceId = SA.DivisionId AND U.SourceTypeId=2005
	   LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
	   LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SA.StudentId
             
  WHERE 
 
		((SA.ClassId=@rClassId)OR(@rClassId=0))
		AND((SA.DivisionId=@rDivisionId)OR(@rDivisionId=0))
		AND((SA.Code like @rCode) OR (ISNULL(@rCode,'') = '')) 
		AND((SA.FirstName like @rFirstName) OR (ISNULL(@rFirstName,'') = '')) 
		AND((SA.LastName like @rLastName) OR (ISNULL(@rLastName,'') = '')) 
		AND((SA.StatusId=@rStatusId)OR(@rStatusId=0))	
		AND(SA.OrgId=@rOrgId)
		AND(SA.BatchId=@rBatchId)
		AND((SA.SUID = @rSUId) OR (ISNULL(@rSUId,'') = '')) 
		--AND((SA.Number=@rNumber)OR(@rNumber=0))	
		AND U.UserId = @rUserId
		AND((SA.ClassStatusId=@rClassStatusId)OR(@rClassStatusId=0))
		--AND (ISNULL(SA.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rMultiCode,',')) OR @rMultiCode='')
		AND ((SC.PresentContactNo=@rContactNo) OR (SC.PermanentContactNo=@rContactNo) OR (SC.EmergencyContactNo=@rContactNo) OR (SC.ParentContactNo=@rContactNo) OR (SC.StudentContactNo=@rContactNo) OR (SF.FatherContactNo=@rContactNo) OR (SF.MotherContactNo=@rContactNo) OR (@rContactNo=''))
ORDER BY SA.ClassId,SA.DivisionId,SA.RollNo
END
ELSE
BEGIN
	SELECT 
			SA.AcademicId,
			SA.StudentId,
			SA.FirstName,
			SA.LastName,
			SA.Name,
			SA.Code,
			SA.ClassId,
			SA.ClassName,
			SA.DivisionId,
			SA.DivisionName,
			SA.Number,
			SA.RollNo,
			SA.StatusId,
			SA.StatusName,
			SA.OrgId,
			ISNULL(SI.StudentPhoto, CONVERT(VARBINARY(MAX), 0)) AS StudentPhoto,
			SA.ClassStatusId,
			SA.ClassStatusName
			
  FROM 
          sStudent.vStudentAcademic SA
       LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=SA.StudentId
       INNER JOIN sSecurity.tUserAccess U ON U.SourceId = SA.DivisionId AND U.SourceTypeId=2005
	   LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
	   LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SA.StudentId
  WHERE 
 
		((SA.ClassId=@rClassId)OR(@rClassId=0))
		AND((SA.DivisionId=@rDivisionId)OR(@rDivisionId=0))
		AND((SA.Code like @rCode) OR (ISNULL(@rCode,'') = '')) 
		AND((SA.FirstName like @rFirstName) OR (ISNULL(@rFirstName,'') = '')) 
		AND((SA.LastName like @rLastName) OR (ISNULL(@rLastName,'') = '')) 
		AND(SA.RollNo=@rRollNo)	
		AND((SA.StatusId=@rStatusId)OR(@rStatusId=0))	
		AND(SA.OrgId=@rOrgId)
		AND(SA.BatchId=@rBatchId)
		AND((SA.SUID = @rSUId) OR (ISNULL(@rSUId,'') = '')) 
		AND U.UserId = @rUserId
		AND((SA.ClassStatusId=@rClassStatusId)OR(@rClassStatusId=0))
		--AND (ISNULL(SA.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rMultiCode,',')) OR @rMultiCode='')
		--AND((SA.Number=@rNumber)OR(@rNumber=0))	
		AND ((SC.PresentContactNo=@rContactNo) OR (SC.PermanentContactNo=@rContactNo) OR (SC.EmergencyContactNo=@rContactNo) OR (SC.ParentContactno=@rContactNo) OR (SC.StudentContactNo=@rContactNo) OR (SF.FatherContactNo=@rContactNo) OR (SF.MotherContactNo=@rContactNo) OR (@rContactNo=''))

ORDER BY SA.ClassId,SA.DivisionId,SA.RollNo
END
  
		
END
GO
PRINT N'Altering [sStudent].[pStudentViewProfileGet]...';


GO
ALTER PROCEDURE [sStudent].[pStudentViewProfileGet]
	 
	 @rBatchId int,
	 @rAcademicId bigint,
	 @rReportId int=0,
	 @rOrgId int,
	 @rOrgGroupBatchId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	
	SELECT 
			SA.StudentId AS Id,
			SA.SUId,
			SA.FirstName + ' ' + ISNULL(SA.MiddleName,'') + ' ' + 	SA.LastName AS StudentName,
			ISnull(SA.Batch,'') AS AcademicYear,
			ISNULL(SA.Code,' ') AS Code,
			SA.ClassDivision AS ClassDiv,			
			Isnull(SA.RollNo,'') AS RollNo,
			convert(varchar,ISNULL(SA.DateOfBirth,'0001/01/01'),103) AS DateOfBirth,
			ISNULL(SM.Title,'-') AS House,
			ISNULL(SA.BirthTaluka,'') AS BirthTaluka,
			ISNULL(SA.BirthPlace,'') AS BirthPlace,	
			ISNULL(SA.BirthDistrict,'') AS BirthDistrict,
			ISNULL(SA.BirthDateInWord,'') AS BirthDateInWord,                           
			ISNULL(SA.Gender,'') AS Gender,
			ISNULL(SA.Religion,'') AS Religion,
			ISNULL(SA.AdmissionStandard,'') AS AdmissionStandard,
			convert(varchar,ISNULL(SA.AdmissionDate,'0001/01/01'),103) AS AdmissionDate,
			ISNULL(SA.PreviousSchool,'') AS PreviousSchool,
			ISNULL(SA.AdmissionCategory,'') AS StudentAdmissionCategory,
            convert(varchar,ISNULL(SA.LeftDate,'0001/01/01'),103) AS LeftDate,
			ISNULL(SA.LeftStandard,'') AS LeftStandard,
			convert(varchar,ISNULL(SA.InactiveDate,'01/01/0001'),103) AS InactiveDate,
			ISNULL(SA.LCNumber,'') AS LCNumber,
			convert(varchar,ISNULL(SA.LCDate,'01/01/0001'),103) AS LCDate,
			ISNULL(SA.PresentStreetone,'') + ' ' + ISNULL(SA.PresentStreetTwo,'') + ' ' + ISNULL(SA.PresentStreetThree,'') AS PresentAddress,
			ISNULL(SA.PresentCity,'') AS PresentCity,
			ISNULL(SA.PresentState,'') AS PresentState,
			ISNULL(SA.PresentCountry,'') AS PresentCountry,
			ISNULL(SA.PresentZipCode,'') AS PresentZipCode,
			ISNULL(SA.PresentContactNo,'') AS PresentContactNo,
			ISNULL(SA.EmergencyStreetOne,'') + ' ' + ISNULL(SA.EmergencyStreetTwo,'') + ' ' + ISNULL(SA.EmergencyStreetThree,'') AS EmergencyAddress,
			ISNULL(SA.EmergencyCity,'') AS EmergencyCity,
			ISNULL(SA.EmergencyState,'') AS EmergencyState,
			ISNULL(SA.EmergencyCountry,'') AS EmergencyCountry,
			ISNULL(SA.EmergencyZipCode,'') AS EmergencyZipCode,
			ISNULL(SA.EmergencyContactNo,'') AS EmergencyContactNo,
			ISNULL(SA.PermanentStreetOne,'') + ' ' + ISNULL(SA.PermanentStreetTwo,'') + ' ' + ISNULL(SA.PermanentStreetThree,'') AS PermanentAddress,
			ISNULL(SA.PermanentCity,'') AS PermanentCity,
			ISNULL(SA.PermanentState,'') AS PermanentState,
			ISNULL(SA.PermanentCountry,'') AS PermanentCountry,
			ISNULL(SA.PermanentZipCode,'') AS PermanentZipCode,
			ISNULL(SA.PermanentContactNo,'') AS PermanentContactNo,
			ISNULL(SF.FatherName,'') AS FatherName,
			ISNULL(SF.FatherOccupation,'') AS FatherOccupation,
			ISNULL(SF.FatherQualification,'') AS FatherQualification,
			ISNULL(SF.FatherContactNo,'') AS FatherContactNo,
			ISNULL(SF.FatherMail,'') AS FatherMail,
			ISNULL(SF.FatherOfficeAddress,'') AS FatherOfficeAddress,
			ISNULL(SF.FatherDesignation,'') AS FatherDesignation,
			ISNULL(SF.FatherOrganization,'') AS FatherOrganization,
			ISNULL(SF.MotherName,'') AS MotherName,
			ISNULL(SF.MotherOccupation,'') AS MotherOccupation,
			ISNULL(SF.MotherQualification,'') AS MotherQualification,
			ISNULL(SF.MotherContactNo,'') AS MotherContactNo,
			ISNULL(SF.MotherMail,'') AS MotherMail,
			ISNULL(SF.MotherOfficeAddress,'') AS MotherOfficeAddress,
			ISNULL(SF.MotherDesignation,'') AS MotherDesignation,
			ISNULL(SF.MotherOrganization,'') AS MotherOrganization,
			ISNULL(SF.RelationshipName,'') AS RelationShip,
			ISNULL(SF.RelativeName,'') AS RelativeName,
			ISNULL(SF.RelativeOccupation,'') AS RelativeOccupation,
			ISNULL(SF.RelativeQualification,'') AS RelativeQualification,
			ISNULL(SF.RelativeContactNo,'') AS RelativeContactNo,
			ISNULL(SF.RelativeMail,'') AS RelativeMail,
			ISNULL(SF.RelativeOfficeAddress,'') AS RelativeOfficeAddress,
			ISNULL(SF.RelativeDesignation,'') AS RelativeDesignation,
			ISNULL(SF.RelativeOrganization,'') AS RelativeOrganization,
			ISNULL(SA.BloodGroup,'') AS BloodGroup,
			ISNULL(SH.IdentificationMark1,'')+' '+ISNULL(SH.IdentificationMark2,'') as IdentificationMark,
			ISNULL(SH.FamilyDoctorName,'') AS FamilyDoctorName,
			ISNULL(SH.FamilyDoctorContactNo,'') AS FamilyDoctorContactNo,
			case When isnull(SH.IsPysicalDeformity,0)=0 then 'NO' Else 'Yes' End As IsPysicalDeformity,
			SH.PysicalDeformityRemark ,
			case When isnull(SH.IsMajorIllness,0)=0 then 'NO' Else 'Yes' End As IsMajorIllness,
			ISNULL(SH.MajorIllnessRemark,'') As MajorIllnessRemark,
			 case When isnull(SH.IsAllergy,0)=0 then 'NO' Else 'Yes' End As IsAllergy,
			ISNULL(SH.AllergyRemark,'') As AllergyRemark,
			 case When isnull(SH.IsPastHistory,0)=0 then 'NO' Else 'Yes' End As IsPastHistory,
			ISNULL(SH.PastHistoryRemark,'') As PastHistoryRemark,
			ISNULL(RM.Title,'') AS RoomNo,			
			ISNULL(HM.Title,'') AS Hostel,
			ISNULL(EMW.FirstName,'')+' '+ISNULL(EMW.LastName,'') AS WardenName,
			ISNULL(ECW.PhoneNoCompany,'') As WardenPhoneNo,
			ISNULL(ECW.ExtensionNo,'') AS WardenExtNo,
			ISNULL(ECW.MobileNumber,'') AS WardenMobileNo,
			ISNULL(EMA.FirstName,'')+' '+ISNULL(EMA.LastName,'') AS AssignedRoomBy,	
			ISNULL(ECA.PhoneNoCompany,'') AS AssignedRoomByPhoneNo,
			ISNULL(ECA.ExtensionNo,'') AS AssignedRoomByExtNo,
			ISNULL(ECA.MobileNumber,'') AS AssignedRoomByMobileNo,
			--Notification Details
			ISNULL(SA.ParentEmail,'') AS ParentEmail,
			ISNULL(SA.ParentContactNo,'') As ParentContactNo,
			ISNULL(SA.StudentEmail,'') AS StudentEmail,
			ISNULL(SA.StudentContactNo,'') AS StudentContactNo,
		    ISnull( A.VehicleName,'') AS VehicleName,
		    ISNULL( A.VehicleRegistrationNumber,'') AS VehicleRegistrationNumber,
		    ISNULL(A.TypeOfVehicle ,'') AS TypeOfVehicle ,
		    ISNULL(A.BusRoute,'') AS BusRoute,
		    ISNULL( A.DriverName,'') AS DriverName,
		    ISNULL(A.DriverMobileNo,'') AS DriverMobileNo,
		    ISNULL( A.ConductorName,'') AS ConductorName,
		    ISNULL( A.ConductorMobileNo,'') AS ConductorMobileNo ,
		    ISNULL(A.BusRouteDestination,'') AS BusRouteDestination,
		    isnull(A.DropVehicleName,'') AS DropVehicleName,
		    isnull(A.DropVehicleRegistrationNumber,'') AS DropVehicleRegistrationNumber,
		    isnull(A.DropTypeOfVehicle,'') AS DropTypeOfVehicle,
		    ISNULL(A.DropRoute,'') AS DropRoute,
		    isnull( A.DriverName,'') AS DropRouteDriverName,
		    isnull(A.DriverMobileNo,'') AS DropRouteDriverMobileNo,
		    isnull(A.ConductorName,'') AS DropRouteConductorName,
		    isnull(A.ConductorMobileNo,'') AS DropRouteConductorMobileNo,
		    ISNULL(A.DropDestination,'') AS DropDestination,
		    ISNULL( EMT.FirstName+' '+EMT.MiddleName+' '+EMT.LastName,'') AS TeacherFullName,
		    isnull( EDM.Title,'') AS TeacherDesignation,
		    ISNULL( EPD.Qualification,'') AS TeacherQualification,
		    ISNULL(DF.IsDisplayFamilyDetail,0) AS IsDisplayFamilyDetail,
		    ISNULL(DF.IsDisplaySiblingDetail,0) AS IsDisplaySiblingDetail,
		    ISNULL(DF.IsDisplayPassportDetail,0) AS IsDisplayPassportDetail,
		    ISNULL(DF.IsDisplayBankDetail,0) AS IsDisplayBankDetail,
		    ISNULL(DF.IsDisplayCBSEREGDetail,0) AS IsDisplayCBSEREGDetail,
		    ISNULL(DF.IsDisplayCollegeDetail,0) AS IsDisplayCollegeDetail,
		    ISNULL(DF.IsDisplayGOVREGNoDetail,0) AS IsDisplayGOVREGNoDetail,
		    ISNULL(DF.IsDisplayHealthDetail,0) AS IsDisplayHealthDetail,
		    ISNULL(DF.IsDisplayTransportDetail,0) AS IsDisplayTransportDetail,
		    ISNULL(DF.IsDisplayHostelDetail,0) AS IsDisplayHostelDetail,
		    ISNULL(DF.IsDisplayClubDetail,0) AS IsDisplayClubDetail,
		    
		    ISNULL(DF.IsDisplaySSCResultDDetail,0) AS IsDisplaySSCResultDDetail,
		    ISNULL(DF.IsDisplayHSCResultDetail,0) AS IsDisplayHSCResultDetail,
		    ISNULL(DF.IsDisplayJeeDetail,0) AS IsDisplayJeeDetail,
		    ISNULL(DF.IsDisplayDiplomaDetail,0) AS IsDisplayDiplomaDetail,
		
		    isnull(SS.SiblingName1,'') AS SiblingName1,
	        ISNULL (SS.SiblingInstitue1,'') AS SiblingInstitue1,
	        ISNULL(SS.SiblingClass1,'')AS SiblingClass1,
	        ISNULL(SS.SiblingAge1,'')AS SiblingAge1,
	        ISNULL(SS.SiblingRelation1,'')AS SiblingRelation1,
	        isnull(SS.SiblingName2,'') AS SiblingName2,
	        ISNULL(SS.SiblingInstitue2,'')AS SiblingInstitue2,
	        ISNULL(SS.SiblingClass2,'')AS SiblingClass2,
	        ISNULL(SS.SiblingAge2,'') AS SiblingAge2,
	        ISNULL(SS.SiblingRelation2,'')AS SiblingRelation2,
	        isnull(SS.SiblingName3,'') AS SiblingName3,
	        ISNULL( SS.SiblingInstitue3,'')AS SiblingInstitue3,
	        ISNULL(SS.SiblingClass3,'')AS SiblingClass3,
	        ISNULL(SS.SiblingAge3,'')AS SiblingAge3,
	        ISNULL(SS.SiblingRelation3,'')AS SiblingRelation3,
	        ISNULL(SAD.BankAccountNumber,'')AS BankAccountNumber,
	        ISNULL(SAD.BankName,'')AS BankName,
	        ISNULL(SAD.BankBranch,'') AS BankBranch,
	        ISNULL(SAD.BankIFSCCode,'')AS BankIFSCCode,
	        ISNULL(SAD.Class9BoardRegistrationNumber,'') AS Class9BoardRegistrationNumber,
	        ISNULL(SAD.Class11BoardRegistrationNumber,'')AS Class11BoardRegistrationNumber,
	        ISNULL(SAD.PassportNumber,'')AS PassportNumber, 
	        ISNULL(SAD.PassportType,'') AS PassportType,
	        ISNULL( SAD.PassportCountryCode,'') AS PassportCountryCode,
	       	convert(varchar,ISNULL(SAD.PassportExpiryDate,'01/01/0001'),103) AS PassportExpiryDate,
	       	convert(varchar,ISNULL(SAD.PassportIssueDate,'01/01/0001'),103) AS PassportIssueDate,
	        ISNULL(SA.UIDNumber,'')AS UIDNumber,
	        ISNULL(SA.AdhaarNumber,'') AS AdhaarNumber,
	        case When isnull(SA.IsTransfer,0)=0 then 'No' Else 'Yes' End As IsTransfer,
	        ISNULL(SA.TransferFrom,'') AS TransferFrom,
	        ISNULL(SA.CertificateName,'') AS CertificateName,
	        case When isnull(SA.IsTFWS,0)=0 then 'No' Else 'Yes 'End As IsTFWS,
	        case When isnull(SA.IsCertificateHolder,0)=0 then 'No' Else 'Yes' End As IsCertificateHolder,
	        ISNULL(CD.SSCBoard,'') AS SSCBoard,
	        ISNULL(CD.SSCSchool,'') AS SSCSchool,
	        ISNULL(CD.SSCPassingYear,'') AS SSCPassingYear,
	        ISNULL(CD.SSCObtainMarks,0) AS SSCObtainMarks,
	        ISNULL(CD.SSCOutOfMarks,0) AS SSCOutOfMarks,
	        ISNULL(CD.SSCMathMarks,0) AS SSCMathMarks,
	        ISNULL(CD.SSCMathOutOfMarks,0) AS SSCMathOutOfMarks,
	        ISNULL(CD.SSCPercentage,0) AS SSCPercentage,
	        ISNULL(CD.HSCBoard,'') AS HSCBoard,
	        ISNULL(CD.HSCSchool,'') AS HSCSchool,
	        ISNULL(CD.HSCPassingYear,0) AS HSCPassingYear,
	        ISNULL(CD.HSCObtainMarks,0) AS HSCObtainMarks,
	        ISNULL(CD.HSCOutOfMarks,0) AS HSCOutOfMarks,
	        ISNULL(CD.HSCPercentage,0) AS HSCPercentage,
	        ISNULL(CD.HSCPhysicsMarks,0) AS HSCPhysicsMarks,
	        ISNULL(CD.HSCPhysicsOutOfMarks,0) AS HSCPhysicsOutOfMarks,
	        ISNULL(CD.HSCChemistryMarks,0) AS HSCChemistryMarks,
	        ISNULL(CD.HSCChemistryOutOfMarks,0) AS HSCChemistryOutOfMarks,
	        ISNULL(CD.HSCMathMarks,0) AS HSCMathMarks,
	        ISNULL(CD.HSCMathOutOfMarks,0) AS HSCMathOutOfMarks,
	        ISNULL(CD.HSCBiologyMarks,0) AS HSCBiologyMarks,
	        ISNULL(CD.HSCBiologyOutOfMarks,0) AS HSCBiologyOutOfMarks,
	        ISNULL(CD.PCMMarks,0) AS PCMMarks,
	        ISNULL(CD.PCBMarks,0) AS PCBMarks,
	        ISNULL(CD.JEERollNo,'') AS JEERollNo,
	        ISNULL(CD.JEEMeritNo,'') AS JEEMeritNo,
	        ISNULL(CD.JEEMeritMarks,0) AS JEEMeritMarks,
	        ISNULL(CD.JEEOutOfMarks,0) AS JEEOutOfMarks,
	        ISNULL(CD.DiplomaBoard,'') AS DiplomaBoard,
	        ISNULL(CD.DiplomaCollege,'') AS DiplomaCollege,
	        ISNULL(CD.DiplomaPassingYear,'') AS DiplomaPassingYear,
	        ISNULL(CD.DiplomaObtainMarks,0) AS DiplomaObtainMarks,
	        ISNULL(CD.DiplomaOutOfMarks,0) AS DiplomaOutOfMarks,
	        ISNULL(CD.DiplomaPercentage,0) AS DiplomaPercentage,
	        ISNULL(CD.ApplicationNo,'') AS ApplicationNo,
	        ISNULL(CD.AdmissionRound,0) AS AdmissionRound,
            ISNULL(MS.Title,'') AS MaritalStatus,
	        ISNULL(ACD.RepeatCount,1)AS RepeatCount,
	        ISNULL(SA.MotherTongue,'') As MotherTongue,
	        ISNULL(SA.FamilyCast,'') AS FamilyCast,
			ISNULL(SA.FamilySubCast,'') AS FamilySubCast,
	        ISNULL(CM.Nationality,'') AS Nationality,
            ISNULL(CT.Title,'') AS CasteCategory,
            --StudentPhoto = case when SA.StudentPhoto is null then '' else SA.StudentPhoto end,
	        StudentPhoto=(SELECT CAST(SA.StudentPhoto as varbinary(max)) FOR XML PATH(''), BINARY BASE64) ,
			TeacherPhoto=(SELECT CAST(EI.EmployeePhoto as varbinary(max)) FOR XML PATH(''), BINARY BASE64) ,
			FatherPhoto=(SELECT CAST(SA.FatherPhoto as varbinary(max)) FOR XML PATH(''), BINARY BASE64) ,
			MotherPhoto=(SELECT CAST(SA.MotherPhoto as varbinary(max)) FOR XML PATH(''), BINARY BASE64) ,
			RelativePhoto=(SELECT CAST(SA.RelativePhoto as varbinary(max)) FOR XML PATH(''), BINARY BASE64) ,
			ISNULL(SA.PreviousStandard,'')AS PreviousStandard
			,CGG.Title AS CustomGroup
			,SGM.Title As StudentGroup
			,SOGM.Title As StudentOtherGroup
			,ISNULL([sStudent].[fAssignedClubGet](@rAcademicId),'') AS ClubName
			,ISNULL([sStudent].[fAssignedCustomTagGet](@rAcademicId),'') AS CustomTag,
			ISNULL(SA.StudentPhoto, CONVERT(VARBINARY(MAX), 0))AS StudentImage
  FROM 
           sStudent.vStudentAllDetail SA
           --LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
           LEFT JOIN sStudent.tStudentHealth SH ON SA.StudentId=SH.StudentId
           LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SA.StudentId 
           --LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId = SA.StudentId
           LEFT JOIN sActivity.tHouseMaster SM ON SM.ID = SA.HouseId
           LEFT JOIN sHostel.tAssignRoom AR ON AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003  AND ((AR.OrgGroupBatchId=@rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
           LEFT JOIN sHostel.tRoomMaster RM ON RM.Id=AR.RoomId
           LEFT JOIN sHostel.tHostelMaster HM ON HM.Id=RM.HostelId 
           LEFT JOIN
           (
		   SELECT 
		   employeeId, 
		   HostelId,   
		   ROW_NUMBER() OVER (PARTITION BY HostelId ORDER By HostelId ) as ROWNo 
		   FROM sHostel.tHostelwarden 
            )  HW ON HW.HostelId=HM.Id AND RowNo = 1       
           --LEFT JOIN sHostel.tHostelWarden HW ON HW.HostelId=HM.Id
           LEFT JOIN sHrm.tEmployeeMaster EMW ON HW.EmployeeId=EMW.Id AND  ISNULL(EMW.IsOtherUser,0) = 0
           LEFT JOIN sHrm.tEmployeeMaster EMA ON RM.AssignedEmployeeId=EMA.Id AND  ISNULL(EMA.IsOtherUser,0) = 0
           LEFT JOIN sHrm.tEmployeeCommunications ECW ON EMW.Id=ECW.EmployeeId 
           LEFT JOIN sHrm.tEmployeeCommunications ECA ON  EMA.Id=ECA.EmployeeId
           LEFT JOIN 
           (SELECT AR1.SourceId ,
           ISnull( VM.Title,'') AS VehicleName,
		   ISNULL( VM.RegistrationNumber,'') AS VehicleRegistrationNumber,
		   ISNULL(TV.Title ,'') AS TypeOfVehicle ,
		   ISNULL(BRM.Title,'') AS BusRoute,
		   ISNULL( BRM.DriverName,'') AS DriverName,
		   ISNULL(BRM.DriverMobileNo,'') AS DriverMobileNo,
		   ISNULL( BRM.ConductorName,'') AS ConductorName,
		   ISNULL( BRM.ConductorMobileNo,'') AS ConductorMobileNo ,
		   ISNULL(BRDM.Title,'') AS BusRouteDestination,
		   isnull(VM.Title,'') AS DropVehicleName,
		   isnull(VM.RegistrationNumber,'') AS DropVehicleRegistrationNumber,
		   isnull(TV1.Title,'') AS DropTypeOfVehicle,
		   ISNULL(BRM1.Title,'') AS DropRoute,
		   isnull( BRM1.DriverName,'') AS DropRouteDriverName,
		   isnull(BRM1.DriverMobileNo,'') AS DropRouteDriverMobileNo,
		   isnull(BRM1.ConductorName,'') AS DropRouteConductorName,
		   isnull(BRM1.ConductorMobileNo,'') AS DropRouteConductorMobileNo,
		   ISNULL(BRDM1.Title,'') AS DropDestination
		   FROM sTransport.tAssignRoute AR1 
           INNER JOIN sTransport.tBusRouteDestinationMaster BRDM ON BRDM.Id=AR1.PickupDestinationId AND AR1.SourceTypeId=2003
           INNER JOIN sTransport.tBusRouteMaster BRM ON BRM.Id=BRDM.BusRouteId  AND ((BRM.OrgGroupBatchId=@rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
           LEFT JOIN sTransport.tVehicleMaster VM ON VM.Id=BRM.VehicleId
           LEFT JOIN sTransport.tVehicleTypeMaster TV ON TV.Id = VM.VehicleTypeId
           LEFT JOIN sTransport.tBusRouteDestinationMaster BRDM1 ON BRDM1.Id=AR1.DropDestinationId
           LEFT JOIN sTransport.tBusRouteMaster BRM1 ON BRM1.Id=BRDM1.BusRouteId AND ((BRM1.OrgGroupBatchId=@rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
           LEFT JOIN sTransport.tVehicleMaster VM1 ON VM1.Id=BRM1.VehicleId
           LEFT JOIN sTransport.tVehicleTypeMaster TV1 ON TV1.Id = VM1.VehicleTypeId)A ON A.SourceId=SA.StudentId
           LEFT JOIN sSetup.tDivisionMaster DM ON  DM.Id=SA.DivisionId
           LEFT JOIN sHrm.tEmployeeMaster EMT ON EMT.Id=DM.InchargeEmployeeId AND  ISNULL(EMT.IsOtherUser,0) = 0
           LEFT JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EMT.Id
           LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id=EJD.EmployeeDesignationId
           LEFT JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId=EMT.Id
           LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId=EMT.Id
           LEFT JOIN sStudent.tStudentSibling  SS ON SS.StudentId=SA.StudentId 
           LEFT JOIN sStudent.tStudentAdditional  SAD ON SAD.StudentId=SA.StudentId 
           LEFT JOIN sStudent.tCollegeDetail  CD ON CD.StudentId=SA.StudentId 
           LEFT JOIN sStudent.tAcademicDetail  ACD ON ACD.AcademicId=SA.AcademicId 
           LEFT JOIN sCommon.tMaritalStatusMaster  MS ON MS.Id=CD.MaritalStatusId
           LEFT JOIN sConfig.fDisplayFieldGet(@rOrgId) AS DF ON DF.OrgId=SA.OrgId
           LEFT JOIN sCommon.tCastCategoryMaster CT ON CT.Id = SA.CastCategoryId
           LEFT JOIN sCommon.tCountryMaster CM ON CM.Id=SA.NationalityId
           LEFT JOIN sCommunication.tCustomGroupMember CGM ON CGM.SourceId = SA.AcademicId AND CGM.SourceTypeId = 2001
           LEFT JOIN sCommunication.tCustomGroup CGG ON CGG.Id = CGM.CustomGroupId
           LEFT JOIN sStudent.tStudentMaster SMM ON SMM.Id = SA.StudentId
           LEFT JOIN sStudent.tStudentGroupMaster SGM ON SGM.Id = SMM.StudentGroupId
           LEFT JOIN sStudent.tStudentOtherGroupMaster SOGM ON SOGM.Id = SMM.StudentOtherGroupId
  WHERE 
		   ((SA.AcademicId=@rAcademicId)OR(@rAcademicId=0))
		   AND(SA.BatchId=@rBatchId)
		
END
GO
PRINT N'Altering [sTally].[pFeeLedgerMappingAdd]...';


GO
ALTER PROCEDURE [sTally].[pFeeLedgerMappingAdd]	 
      @rXmlDoc nvarchar(MAX)     
	
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

		DELETE FROM sTally.tFeeLedgerMapping WHERE FeeId IN (
		SELECT FeeId FROM OPENXML (@intDoc, '/Table/FeeLedgerMapping', 1)
		WITH ( FeeId int '@FeeId'))
	
	INSERT INTO sTally.tFeeLedgerMapping
		(
		FeeId,
		LedgerName,
		LedgerGroup
		)
	SELECT
		FeeId,
		[sSetup].[fPortalXMLTagsReplaceReverse](LedgerName) AS LedgerName,
		[sSetup].[fPortalXMLTagsReplaceReverse](LedgerGroup) AS LedgerGroup
		
	FROM OPENXML (@intDoc, '/Table/FeeLedgerMapping', 1)
	WITH
	(
		FeeId int '@FeeId',
		LedgerName nvarchar(150) '@LedgerName',
		LedgerGroup nvarchar(150) '@LedgerGroup'
	)
	
	SELECT 101 AS RESULT
	
	COMMIT TRANSACTION		
	END TRY

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


GO
 
ALTER PROCEDURE [sTimetable].[pDivisionTimeTableGet]
	
	 @rDivisionId int,
	 @rTimeTableSchemaId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

	DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX),@query1  AS NVARCHAR(MAX),@query2  AS NVARCHAR(MAX),@query3 AS NVARCHAR(MAX)

select @cols = STUFF((SELECT ',' + QUOTENAME(Title) 
                    from sCommon.tDayMaster
                    group by Title,Id 
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')
        
     
 IF EXISTS(SELECT 1 FROM sTimetable.tTimeTableSchema TS INNER JOIN sTimetable.tTimeTable TT ON TT.TimeTableSchemaId = TS.Id WHERE TS.IsDisplayPeriodTime = 1 AND TS.Id = @rTimeTableSchemaId)
 BEGIN
set @query = 'SELECT LectureNumber , ' + @cols + ' from 
             (
            Select T.LectureNumber, 
			ISNULL(
			--EM.ShortName + '+ ''' - ''' +'+ SM.Code + '
			+'
			[sCommon].[fXMLTagsReplaceReverse](STUFF((
				SELECT '' '' +  ISNULL(ISNULL(Em1.ShortName,'''') +'' - ''+SM1.Code+''<br>'','''')
				FROM sTimetable.tTimeTable T1 
				inner join sHrm.tEmployeeMaster EM1 on EM1.Id=T1.EmployeeId
				INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=T1.SubjectId
				where T1.DivisionId=T.DivisionId 
				AND T1.LectureNumber=T.LectureNumber 
				AND T1.DayId=T.DayId and T1.TimeTableSchemaId=T.TimeTableSchemaId  
				--AND timetableid in ()
				FOR XML PATH('''')
				), 1, 1, ''''))'
			+ '+''|''' +' +ISNULL(TTM.FromTime,0) +'+ '''-''' +'+ ISNULL(TTM.ToTime,0) ,'''') 
			+ [sTimetable].[fTimeTableDetailGet](T.Id,1) AS EmployeeName ,
			DM.Title AS DayNames 
            from
            sTimetable.tTimeTable T 
            INNER JOIN sCommon.tDayMaster DM ON DM.Id = T.DayId
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id=T.EmployeeId
	        INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=T.SubjectId
			LEFT JOIN sTimetable.tTimeTableTime TTM ON TTM.TimeTableSchemaId=T.TimeTableSchemaId AND TTM.DayId = DM.Id AND TTM.DivisionId = T.DivisionId AND TTM.LectureNumber = T.LectureNumber AND TTM.IsBreak = 0
	         WHERE    
	        ((T.DivisionId=' + CAST(@rDivisionId AS NVARCHAR(30))+') OR ('+CAST(@rDivisionId AS NVARCHAR(30))+'= 0) )
	         AND ((T.TimeTableSchemaId=' + CAST(@rTimeTableSchemaId AS NVARCHAR(30))+') OR ('+CAST(@rTimeTableSchemaId AS NVARCHAR(30))+'= 0))
			 
	       
            ) x
            pivot 
            (
                max(EmployeeName)
                for DayNames in (' + @cols + ')
            ) p '
   END
   ELSE
   BEGIN
   set @query = 'SELECT LectureNumber , ' + @cols + ' from 
             (
            Select T.LectureNumber, 
			--ISNULL(EM.ShortName + '+ ''' - ''' +' + SM.Code,'''') 
			[sCommon].[fXMLTagsReplaceReverse](STUFF((
				SELECT '' '' +  ISNULL(ISNULL(Em1.ShortName,'''') +'' - ''+SM1.Code+''<br>'','''')
				FROM sTimetable.tTimeTable T1 
				inner join sHrm.tEmployeeMaster EM1 on EM1.Id=T1.EmployeeId
				INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=T1.SubjectId
				where T1.DivisionId=T.DivisionId 
				AND T1.LectureNumber=T.LectureNumber 
				AND T1.DayId=T.DayId and T1.TimeTableSchemaId=T.TimeTableSchemaId  
				--AND timetableid in ()
				FOR XML PATH('''')
				), 1, 1, ''''))
			+ [sTimetable].[fTimeTableDetailGet](T.Id,1) AS EmployeeName ,DM.Title AS DayNames 
            from
            sTimetable.tTimeTable T 
            INNER JOIN sCommon.tDayMaster DM ON DM.Id = T.DayId
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id=T.EmployeeId
	        INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=T.SubjectId
	         WHERE    
	        ((T.DivisionId=' + CAST(@rDivisionId AS NVARCHAR(30))+') OR ('+CAST(@rDivisionId AS NVARCHAR(30))+'= 0) )
	         AND ((T.TimeTableSchemaId=' + CAST(@rTimeTableSchemaId AS NVARCHAR(30))+') OR ('+CAST(@rTimeTableSchemaId AS NVARCHAR(30))+'= 0))
	       
            ) x
            pivot 
            (
                max(EmployeeName)
                for DayNames in (' + @cols + ')
            ) p '
   END         
print @query
execute(@query)
END
GO
PRINT N'Altering [sTimetable].[pEmployeeTimeTableAdd]...';


GO

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

	 
 
BEGIN 

	 BEGIN TRY	
	 BEGIN TRANSACTION 
	   
	--IF NOT EXISTS(Select 1 FROM sTimetable.tTimeTable Where EmployeeId = @rEmployeeId AND LectureNumber = @rLectureNumber AND DayId = @rDayId and TimeTableSchemaId=@rTimeTableSchemaId)
	
	BEGIN
	DECLARE @lNextNumber BIGINT

	if(@rId=0)
	BEGIN
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sTimetable.tTimeTable', 0, 1, 1,@outNextNumber = @lNextNumber output	
	
	  BEGIN	
	    DELETE FROM sTimetable.tTimeTable Where EmployeeId = @rEmployeeId AND LectureNumber = @rLectureNumber AND DayId = @rDayId and TimeTableSchemaId=@rTimeTableSchemaId     
	    IF(@rDivisionId<>0 and @rSubjectId<>0)
	     BEGIN	  
		   INSERT INTO sTimetable.tTimeTable		 
		   (
				[Id]
			   ,[TimeTableSchemaId]
			   ,[EmployeeId]
			   ,[DivisionId]
			   ,[SubjectId]
			   ,[DayId]
			   ,[LectureNumber]
			   ,[LockNo]
			   ,[LockColour]
            )		 
			VALUES
			(	
				@lNextNumber,
				@rTimeTableSchemaID,
				@rEmployeeId,
				@rDivisionId,
				@rSubjectId,
				@rDayId,
				@rLectureNumber,
				@rLockNo,
				@rLockColour
			)		
			SELECT @lNextNumber AS Result
		 END	
    	END
      END
	  ELSE IF(@rId<>0)
	  BEGIN
		if(@rDivisionId=0 AND @rSubjectId=0)
		BEGIN
			DELETE FROM sTimetable.tTimeTable Where Id = @rId 
		END
		ELSE
		BEGIN
			UPDATE [sTimetable].[tTimeTable]
			   SET 
				  [DivisionId] = @rDivisionId
				  ,[SubjectId] = @rSubjectId
			 WHERE Id=@rId
		END
		 SELECT @rId AS Result
	  END
    --ELSE
    --BEGIN       
    --  SELECT -101 AS Result
    --END
	END
	
	COMMIT TRANSACTION
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
	
	
END 	             
	
		
END
GO
PRINT N'Altering [sTimetable].[pEmployeeTimeTableGet]...';


GO
 
ALTER PROCEDURE [sTimetable].[pEmployeeTimeTableGet]
	
	@rEmployeeId bigint,
	 @rBatchId int=0,
	 @rTimeTableSchemaId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

	DECLARE @lTableList TABLE
(
   
    LectureNumber int,   
	Sunday varchar(100) NULL,
    Monday varchar(100) NULL,
    Tuesday varchar(100) NULL,
    Wednesday varchar(100) NULL,
    Thursday varchar(100) NULL,
    Friday varchar(100) NULL,
    Saturday varchar(100) NULL,	
	SundayClassSubjectId varchar(100) NULL,
    MondayClassSubjectId varchar(100) NULL,
    TuesdayClassSubjectId varchar(100) NULL,
    WednesdayClassSubjectId varchar(100) NULL,
    ThursdayClassSubjectId varchar(100) NULL,
    FridayClassSubjectId varchar(100) NULL,
    SaturdayClassSubjectId varchar(100) NULL    
)


DECLARE @HeaderCounterStart INT=1
DECLARE @HeaderMaxCounter INT=0

SET @HeaderMaxCounter  = (select max(NoOfPeriod) as MaxLectures  From [sTimetable].[tTimeSetup] where TimeTableSchemaId=@rTimeTableSchemaId and BatchId=@rBatchId)

  WHILE (@HeaderCounterStart <= @HeaderMaxCounter)
    BEGIN
        --DECLARE @HeaderTitle varchar(100)='';
        --SET @HeaderTitle=(SELECT FieldName from @lFieldList where Id=@HeaderCounterStart)  
        --IF(SUBSTRING(@HeaderTitle, len(@HeaderTitle) - 1, 2)='Id')
        --BEGIN
        --  SET @HeaderTitle=REPLACE(@HeaderTitle, SUBSTRING(@HeaderTitle, len(@HeaderTitle) - 1, 2), '') 
        --END     
        --SET @HeaderHtml=@HeaderHtml + ('<th>'+@HeaderTitle+'</th>') 
      
			--Declare @AssignSundayClassDivisionName varchar(100)
   --         SET @AssignSundayClassDivisionName=(SELECT VBCD.ClassDivisionName From  sTimetable.tTimeTable T INNER JOIN sSetup.vClassDivision VBCD ON VBCD.DivisionId=T.DivisionId  where EmployeeId=@rEmployeeId and TimeTableSchemaId=@rTimeTableSchemaId and DayId=1 and LectureNumber=@HeaderCounterStart)
            
   --         IF(@AssignSundayClassDivisionName is NULL)
   --          BEGIN
   --           SET @AssignSundayClassDivisionName='-1'
   --          END 
             
            
            --Declare @AssignSundaySubjectName varchar(100)
   --         SET @AssignSundaySubjectName=(SELECT SM.Code From  sTimetable.tTimeTable T INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=T.SubjectId  where EmployeeId=@rEmployeeId and TimeTableSchemaId=@rTimeTableSchemaId and DayId=1 and LectureNumber=@HeaderCounterStart)
            
   --          IF(@AssignSundaySubjectName is NULL)
   --          BEGIN
   --           SET @AssignSundaySubjectName='-1'
   --          END

			Declare @AssignSundayDivisionSubjectName varchar(100)=null
			Declare @AssignSundayDivisionSubject varchar(100)=null
			SELECT @AssignSundayDivisionSubjectName=COALESCE(@AssignSundayDivisionSubjectName+','+VBCD.ClassDivisionName+'/'+SM.Code ,VBCD.ClassDivisionName+'/'+SM.Code),
					@AssignSundayDivisionSubject=COALESCE(@AssignSundayDivisionSubject+','+Cast(VBCD.DivisionId AS Nvarchar)+'/'+cast(SM.Id AS Nvarchar)+'/'+cast(T.Id AS Nvarchar),Cast(VBCD.DivisionId AS Nvarchar)+'/'+cast(SM.Id AS Nvarchar)+'/'+cast(T.Id AS Nvarchar))
			From  sTimetable.tTimeTable T 
			INNER JOIN sSetup.vClassDivision VBCD ON VBCD.DivisionId=T.DivisionId 
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=T.SubjectId 
				where EmployeeId=@rEmployeeId and TimeTableSchemaId=@rTimeTableSchemaId and DayId=1 and LectureNumber=@HeaderCounterStart
			IF(@AssignSundayDivisionSubjectName is NULL)
				BEGIN
					SET @AssignSundayDivisionSubjectName='-1/-1'
				END 
			IF(@AssignSundayDivisionSubject is NULL)
				BEGIN
					SET @AssignSundayDivisionSubject='-1/-1'
				END 


            --Declare @AssignMondayClassDivisionName varchar(100)
            --SET @AssignMondayClassDivisionName=(SELECT VBCD.ClassDivisionName From  sTimetable.tTimeTable T INNER JOIN sSetup.vClassDivision VBCD ON VBCD.DivisionId=T.DivisionId  where EmployeeId=@rEmployeeId and TimeTableSchemaId=@rTimeTableSchemaId and DayId=2 and LectureNumber=@HeaderCounterStart)
            
            --IF(@AssignMondayClassDivisionName is NULL)
            -- BEGIN
            --  SET @AssignMondayClassDivisionName='-1'
            -- END 
             
            
            --Declare @AssignMondaySubjectName varchar(100)
            --SET @AssignMondaySubjectName=(SELECT SM.Code From  sTimetable.tTimeTable T INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=T.SubjectId  where EmployeeId=@rEmployeeId and TimeTableSchemaId=@rTimeTableSchemaId and DayId=2 and LectureNumber=@HeaderCounterStart)
            
            -- IF(@AssignMondaySubjectName is NULL)
            -- BEGIN
            --  SET @AssignMondaySubjectName='-1'
            -- END 

            Declare @AssignMondayDivisionSubjectName varchar(100)=null
			Declare @AssignMondayDivisionSubject varchar(100)=null
			SELECT @AssignMondayDivisionSubjectName=COALESCE(@AssignMondayDivisionSubjectName+','+VBCD.ClassDivisionName+'/'+SM.Code,VBCD.ClassDivisionName+'/'+SM.Code),
					@AssignMondayDivisionSubject=COALESCE(@AssignMondayDivisionSubject+','+Cast(VBCD.DivisionId AS Nvarchar)+'/'+cast(SM.Id AS Nvarchar)+'/'+cast(T.Id AS Nvarchar),Cast(VBCD.DivisionId AS Nvarchar)+'/'+cast(SM.Id AS Nvarchar)+'/'+cast(T.Id AS Nvarchar))
				From  sTimetable.tTimeTable T 
				INNER JOIN sSetup.vClassDivision VBCD ON VBCD.DivisionId=T.DivisionId 
				INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=T.SubjectId 
				where EmployeeId=@rEmployeeId and TimeTableSchemaId=@rTimeTableSchemaId and DayId=2 and LectureNumber=@HeaderCounterStart
			IF(@AssignMondayDivisionSubjectName is NULL)
				BEGIN
					SET @AssignMondayDivisionSubjectName='-1/-1'
				END 
			IF(@AssignMondayDivisionSubject is NULL)
				BEGIN
					SET @AssignMondayDivisionSubject='-1/-1'
				END 

            --Declare @AssignTuesdayClassDivisionName varchar(100)
            --SET @AssignTuesdayClassDivisionName=(SELECT VBCD.ClassDivisionName From  sTimetable.tTimeTable T INNER JOIN sSetup.vClassDivision VBCD ON VBCD.DivisionId=T.DivisionId  where EmployeeId=@rEmployeeId and TimeTableSchemaId=@rTimeTableSchemaId and DayId=3 and LectureNumber=@HeaderCounterStart)
            
            -- IF(@AssignTuesdayClassDivisionName is NULL)
            -- BEGIN
            --  SET @AssignTuesdayClassDivisionName='-1'
            -- END 
            
            --Declare @AssignTuesdaySubjectName varchar(100)
            --SET @AssignTuesdaySubjectName=(SELECT SM.Code From  sTimetable.tTimeTable T INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=T.SubjectId  where EmployeeId=@rEmployeeId and TimeTableSchemaId=@rTimeTableSchemaId and DayId=3 and LectureNumber=@HeaderCounterStart)
           
            -- IF(@AssignTuesdaySubjectName is NULL)
            -- BEGIN
            --  SET @AssignTuesdaySubjectName='-1'
            -- END 

            Declare @AssignTuesdayDivisionSubjectName varchar(100)=null
			Declare @AssignTuesdayDivisionSubject varchar(100)=null
			SELECT @AssignTuesdayDivisionSubjectName=COALESCE(@AssignTuesdayDivisionSubjectName+','+VBCD.ClassDivisionName+'/'+SM.Code,VBCD.ClassDivisionName+'/'+SM.Code),
					@AssignTuesdayDivisionSubject=COALESCE(@AssignTuesdayDivisionSubject+','+Cast(VBCD.DivisionId AS Nvarchar)+'/'+cast(SM.Id AS Nvarchar) +'/'+cast(T.Id AS Nvarchar),Cast(VBCD.DivisionId AS Nvarchar)+'/'+cast(SM.Id AS Nvarchar)+'/'+cast(T.Id AS Nvarchar))
				From  sTimetable.tTimeTable T 
				INNER JOIN sSetup.vClassDivision VBCD ON VBCD.DivisionId=T.DivisionId 
				INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=T.SubjectId 
				where EmployeeId=@rEmployeeId and TimeTableSchemaId=@rTimeTableSchemaId and DayId=3 and LectureNumber=@HeaderCounterStart
			IF(@AssignTuesdayDivisionSubjectName is NULL)
				BEGIN
					SET @AssignTuesdayDivisionSubjectName='-1/-1'
				END 
			IF(@AssignTuesdayDivisionSubject is NULL)
				BEGIN
					SET @AssignTuesdayDivisionSubject='-1/-1'
				END 
            
            --Declare @AssignWedenadayClassDivisionName varchar(100)
            --SET @AssignWedenadayClassDivisionName=(SELECT VBCD.ClassDivisionName From  sTimetable.tTimeTable T INNER JOIN sSetup.vClassDivision VBCD ON VBCD.DivisionId=T.DivisionId  where EmployeeId=@rEmployeeId and TimeTableSchemaId=@rTimeTableSchemaId and DayId=4 and LectureNumber=@HeaderCounterStart)
            
            -- IF(@AssignWedenadayClassDivisionName is NULL)
            -- BEGIN
            --  SET @AssignWedenadayClassDivisionName='-1'
            -- END 
            
            --   Declare @AssignWedenadaySubjectName varchar(100)
            --SET @AssignWedenadaySubjectName=(SELECT SM.Code From  sTimetable.tTimeTable T INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=T.SubjectId  where EmployeeId=@rEmployeeId and TimeTableSchemaId=@rTimeTableSchemaId and DayId=4 and LectureNumber=@HeaderCounterStart)
           
            
            -- IF(@AssignWedenadaySubjectName is NULL)
            -- BEGIN
            --  SET @AssignWedenadaySubjectName='-1'
            -- END 

            Declare @AssignWednesdayDivisionSubjectName varchar(100)=null
			Declare @AssignWednesdayDivisionSubject varchar(100)=null
			SELECT @AssignWednesdayDivisionSubjectName=COALESCE(@AssignWednesdayDivisionSubjectName+','+VBCD.ClassDivisionName+'/'+SM.Code,VBCD.ClassDivisionName+'/'+SM.Code),
					@AssignWednesdayDivisionSubject=COALESCE(@AssignWednesdayDivisionSubject+','+Cast(VBCD.DivisionId AS Nvarchar)+'/'+cast(SM.Id AS Nvarchar)+'/'+cast(T.Id AS Nvarchar),Cast(VBCD.DivisionId AS Nvarchar)+'/'+cast(SM.Id AS Nvarchar)+'/'+cast(T.Id AS Nvarchar))
				From  sTimetable.tTimeTable T 
				INNER JOIN sSetup.vClassDivision VBCD ON VBCD.DivisionId=T.DivisionId 
				INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=T.SubjectId 
				where EmployeeId=@rEmployeeId and TimeTableSchemaId=@rTimeTableSchemaId and DayId=4 and LectureNumber=@HeaderCounterStart
			IF(@AssignWednesdayDivisionSubjectName is NULL)
				BEGIN
					SET @AssignWednesdayDivisionSubjectName='-1/-1'
				END 
			IF(@AssignWednesdayDivisionSubject is NULL)
				BEGIN
					SET @AssignWednesdayDivisionSubject='-1/-1'
				END 
            
            --Declare @AssignThrusdayClassDivisionName nvarchar(100)
            --SET @AssignThrusdayClassDivisionName=(SELECT VBCD.ClassDivisionName From  sTimetable.tTimeTable T INNER JOIN sSetup.vClassDivision VBCD ON VBCD.DivisionId=T.DivisionId  where EmployeeId=@rEmployeeId and TimeTableSchemaId=@rTimeTableSchemaId and DayId=5 and LectureNumber=@HeaderCounterStart)
            
            
            -- IF(@AssignThrusdayClassDivisionName is NULL)
            -- BEGIN
            --  SET @AssignThrusdayClassDivisionName='-1'
            -- END 
            
            
            --Declare @AssignThrusdaySubjectName nvarchar(100)
            --SET @AssignThrusdaySubjectName=(SELECT SM.Code From  sTimetable.tTimeTable T INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=T.SubjectId  where EmployeeId=@rEmployeeId and TimeTableSchemaId=@rTimeTableSchemaId and DayId=5 and LectureNumber=@HeaderCounterStart)
           
            --IF(@AssignThrusdaySubjectName is NULL)
            -- BEGIN
            --  SET @AssignThrusdaySubjectName='-1'
            -- END 

            Declare @AssignThrusdayDivisionSubjectName varchar(100)=null
			Declare @AssignThursdayDivisionSubject varchar(100)=null
			SELECT @AssignThrusdayDivisionSubjectName=COALESCE(@AssignThrusdayDivisionSubjectName+','+VBCD.ClassDivisionName+'/'+SM.Code,VBCD.ClassDivisionName+'/'+SM.Code),
				@AssignThursdayDivisionSubject=COALESCE(@AssignThursdayDivisionSubject+','+Cast(VBCD.DivisionId AS Nvarchar)+'/'+cast(SM.Id AS Nvarchar)+'/'+cast(T.Id AS Nvarchar),Cast(VBCD.DivisionId AS Nvarchar)+'/'+cast(SM.Id AS Nvarchar)+'/'+cast(T.Id AS Nvarchar))
				From  sTimetable.tTimeTable T 
				INNER JOIN sSetup.vClassDivision VBCD ON VBCD.DivisionId=T.DivisionId 
				INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=T.SubjectId 
				where EmployeeId=@rEmployeeId and TimeTableSchemaId=@rTimeTableSchemaId and DayId=5 and LectureNumber=@HeaderCounterStart
			IF(@AssignThrusdayDivisionSubjectName is NULL)
				BEGIN
					SET @AssignThrusdayDivisionSubjectName='-1/-1'
				END 
			IF(@AssignThursdayDivisionSubject is NULL)
				BEGIN
					SET @AssignThursdayDivisionSubject='-1/-1'
				END 
            
            --Declare @AssignFridayClassDivisionName varchar(100)
            --SET @AssignFridayClassDivisionName=(SELECT VBCD.ClassDivisionName From  sTimetable.tTimeTable T INNER JOIN sSetup.vClassDivision VBCD ON VBCD.DivisionId=T.DivisionId  where EmployeeId=@rEmployeeId and TimeTableSchemaId=@rTimeTableSchemaId and DayId=6 and LectureNumber=@HeaderCounterStart)
       
            -- IF(@AssignFridayClassDivisionName is NULL)
            -- BEGIN
            --  SET @AssignFridayClassDivisionName='-1'
            -- END 
            
       
            --Declare @AssignFridaySubjectName varchar(100)
            --SET @AssignFridaySubjectName=(SELECT SM.Code From  sTimetable.tTimeTable T INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=T.SubjectId  where EmployeeId=@rEmployeeId and TimeTableSchemaId=@rTimeTableSchemaId and DayId=6 and LectureNumber=@HeaderCounterStart)
           
            -- IF(@AssignFridaySubjectName is NULL)
            -- BEGIN
            --  SET @AssignFridaySubjectName='-1'
            -- END 
             
            Declare @AssignFridayDivisionSubjectName varchar(100)=null
			Declare @AssignFridayDivisionSubject varchar(100)=null
			SELECT @AssignFridayDivisionSubjectName=COALESCE(@AssignFridayDivisionSubjectName+','+VBCD.ClassDivisionName+'/'+SM.Code,VBCD.ClassDivisionName+'/'+SM.Code),
					@AssignFridayDivisionSubject=COALESCE(@AssignFridayDivisionSubject+','+Cast(VBCD.DivisionId AS Nvarchar)+'/'+cast(SM.Id AS Nvarchar)+'/'+cast(T.Id AS Nvarchar),Cast(VBCD.DivisionId AS Nvarchar)+'/'+cast(SM.Id AS Nvarchar)+'/'+cast(T.Id AS Nvarchar))
				From  sTimetable.tTimeTable T 
				INNER JOIN sSetup.vClassDivision VBCD ON VBCD.DivisionId=T.DivisionId 
				INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=T.SubjectId 
				where EmployeeId=@rEmployeeId and TimeTableSchemaId=@rTimeTableSchemaId and DayId=6 and LectureNumber=@HeaderCounterStart
			IF(@AssignFridayDivisionSubjectName is NULL)
				BEGIN
					SET @AssignFridayDivisionSubjectName='-1/-1'
				END 
			IF(@AssignFridayDivisionSubject is NULL)
				BEGIN
					SET @AssignFridayDivisionSubject='-1/-1'
				END 
      
           -- Declare @AssignSaturdayClassDivisionName varchar(100)
           -- SET @AssignSaturdayClassDivisionName=(SELECT VBCD.ClassDivisionName From  sTimetable.tTimeTable T INNER JOIN sSetup.vClassDivision VBCD ON VBCD.DivisionId=T.DivisionId  where EmployeeId=@rEmployeeId and TimeTableSchemaId=@rTimeTableSchemaId and DayId=7 and LectureNumber=@HeaderCounterStart)
      
           -- IF(@AssignSaturdayClassDivisionName is NULL)
           --  BEGIN
           --   SET @AssignSaturdayClassDivisionName='-1'
           --  END 
          
           -- Declare @AssignSaturdaySubjectName varchar(100)
           -- SET @AssignSaturdaySubjectName=(SELECT SM.Code From  sTimetable.tTimeTable T INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=T.SubjectId  where EmployeeId=@rEmployeeId and TimeTableSchemaId=@rTimeTableSchemaId and DayId=7 and LectureNumber=@HeaderCounterStart)
           
           --IF(@AssignSaturdaySubjectName is NULL)
           --  BEGIN
           --   SET @AssignSaturdaySubjectName='-1'
           --  END 
           
		   Declare @AssignSaturdayDivisionSubjectName varchar(100)=null
		   Declare @AssignSaturdayDivisionSubject varchar(100)=null
			SELECT @AssignSaturdayDivisionSubjectName=COALESCE(@AssignSaturdayDivisionSubjectName+','+VBCD.ClassDivisionName+'/'+SM.Code,VBCD.ClassDivisionName+'/'+SM.Code),
					@AssignSaturdayDivisionSubject=COALESCE(@AssignSaturdayDivisionSubject+','+Cast(VBCD.DivisionId AS Nvarchar)+'/'+cast(SM.Id AS Nvarchar)+'/'+cast(T.Id AS Nvarchar),Cast(VBCD.DivisionId AS Nvarchar)+'/'+cast(SM.Id AS Nvarchar)+'/'+cast(T.Id AS Nvarchar))
				From  sTimetable.tTimeTable T 
				INNER JOIN sSetup.vClassDivision VBCD ON VBCD.DivisionId=T.DivisionId 
				INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=T.SubjectId 
				where EmployeeId=@rEmployeeId and TimeTableSchemaId=@rTimeTableSchemaId and DayId=7 and LectureNumber=@HeaderCounterStart
			IF(@AssignSaturdayDivisionSubjectName is NULL)
				BEGIN
					SET @AssignSaturdayDivisionSubjectName='-1/-1'
				END 
			IF(@AssignSaturdayDivisionSubject is NULL)
				BEGIN
					SET @AssignSaturdayDivisionSubject='-1/-1'
				END 


			--Declare @AssignSundayDivisionSubject varchar(100)
   --          Declare @AssignSundayClassDivisionId varchar(100)
   --          Declare @AssignSundaySubjectId varchar(100)
             
   --          SET @AssignSundayClassDivisionId=(SELECT VBCD.DivisionId From  sTimetable.tTimeTable T INNER JOIN sSetup.vClassDivision VBCD ON VBCD.DivisionId=T.DivisionId  where EmployeeId=@rEmployeeId and TimeTableSchemaId=@rTimeTableSchemaId and DayId=1 and LectureNumber=@HeaderCounterStart)
   --          SET @AssignSundaySubjectId=(SELECT SM.Id From  sTimetable.tTimeTable T INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=T.SubjectId  where EmployeeId=@rEmployeeId and TimeTableSchemaId=@rTimeTableSchemaId and DayId=1 and LectureNumber=@HeaderCounterStart)
             
   --          IF(@AssignSundayClassDivisionId is NULL)
   --          BEGIN
   --           SET @AssignSundayClassDivisionId='-1'
   --          END 
   --           IF(@AssignSundaySubjectId is NULL)
   --          BEGIN
   --           SET @AssignSundaySubjectId='-1'
   --          END 
           
             
             --SET @AssignSundayDivisionSubject=@AssignSundayClassDivisionId +'/' + @AssignSundaySubjectId

           
            -- Declare @AssignMondayDivisionSubject varchar(100)
            -- Declare @AssignMondayClassDivisionId varchar(100)
            -- Declare @AssignMondaySubjectId varchar(100)
             
            -- SET @AssignMondayClassDivisionId=(SELECT VBCD.DivisionId From  sTimetable.tTimeTable T INNER JOIN sSetup.vClassDivision VBCD ON VBCD.DivisionId=T.DivisionId  where EmployeeId=@rEmployeeId and TimeTableSchemaId=@rTimeTableSchemaId and DayId=2 and LectureNumber=@HeaderCounterStart)
            -- SET @AssignMondaySubjectId=(SELECT SM.Id From  sTimetable.tTimeTable T INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=T.SubjectId  where EmployeeId=@rEmployeeId and TimeTableSchemaId=@rTimeTableSchemaId and DayId=2 and LectureNumber=@HeaderCounterStart)
             
            -- IF(@AssignMondayClassDivisionId is NULL)
            -- BEGIN
            --  SET @AssignMondayClassDivisionId='-1'
            -- END 
            --  IF(@AssignMondaySubjectId is NULL)
            -- BEGIN
            --  SET @AssignMondaySubjectId='-1'
            -- END 
           
             
            -- SET @AssignMondayDivisionSubject=@AssignMondayClassDivisionId +'/' + @AssignMondaySubjectId
             
            -- Declare @AssignTuesdayDivisionSubject varchar(100)
            -- Declare @AssignTuesdayClassDivisionId varchar(100)
            -- Declare @AssignTuesdaySubjectId varchar(100)
             
            -- SET @AssignTuesdayClassDivisionId=(SELECT VBCD.DivisionId From  sTimetable.tTimeTable T INNER JOIN sSetup.vClassDivision VBCD ON VBCD.DivisionId=T.DivisionId  where EmployeeId=@rEmployeeId and TimeTableSchemaId=@rTimeTableSchemaId and DayId=3 and LectureNumber=@HeaderCounterStart)
            -- SET @AssignTuesdaySubjectId=(SELECT SM.Id From  sTimetable.tTimeTable T INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=T.SubjectId  where EmployeeId=@rEmployeeId and TimeTableSchemaId=@rTimeTableSchemaId and DayId=3 and LectureNumber=@HeaderCounterStart)
             
            --IF(@AssignTuesdayClassDivisionId is NULL)
            -- BEGIN
            --  SET @AssignTuesdayClassDivisionId='-1'
            -- END 
            --  IF(@AssignTuesdaySubjectId is NULL)
            -- BEGIN
            --  SET @AssignTuesdaySubjectId='-1'
            -- END 
             
            -- SET @AssignTuesdayDivisionSubject=@AssignTuesdayClassDivisionId +'/' + @AssignTuesdaySubjectId
             
             
            -- Declare @AssignWednesdayDivisionSubject varchar(100)
            -- Declare @AssignWednesdayClassDivisionId varchar(100)
            -- Declare @AssignWednesdaySubjectId varchar(100)
             
            -- SET @AssignWednesdayClassDivisionId=(SELECT VBCD.DivisionId From  sTimetable.tTimeTable T INNER JOIN sSetup.vClassDivision VBCD ON VBCD.DivisionId=T.DivisionId  where EmployeeId=@rEmployeeId and TimeTableSchemaId=@rTimeTableSchemaId and DayId=4 and LectureNumber=@HeaderCounterStart)
            -- SET @AssignWednesdaySubjectId=(SELECT SM.Id From  sTimetable.tTimeTable T INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=T.SubjectId  where EmployeeId=@rEmployeeId and TimeTableSchemaId=@rTimeTableSchemaId and DayId=4 and LectureNumber=@HeaderCounterStart)
             
            --  IF(@AssignWednesdayClassDivisionId is NULL)
            -- BEGIN
            --  SET @AssignWednesdayClassDivisionId='-1'
            -- END 
            --  IF(@AssignWednesdaySubjectId is NULL)
            -- BEGIN
            --  SET @AssignWednesdaySubjectId='-1'
            -- END 
             
             
            -- SET @AssignWednesdayDivisionSubject=@AssignWednesdayClassDivisionId +'/' + @AssignWednesdaySubjectId
             
            -- Declare @AssignThursdayDivisionSubject varchar(100)
            -- Declare @AssignThursdayClassDivisionId varchar(100)
            -- Declare @AssignThursdaySubjectId varchar(100)
             
            -- SET @AssignThursdayClassDivisionId=(SELECT VBCD.DivisionId From  sTimetable.tTimeTable T INNER JOIN sSetup.vClassDivision VBCD ON VBCD.DivisionId=T.DivisionId  where EmployeeId=@rEmployeeId and TimeTableSchemaId=@rTimeTableSchemaId and DayId=5 and LectureNumber=@HeaderCounterStart)
            -- SET @AssignThursdaySubjectId=(SELECT SM.Id From  sTimetable.tTimeTable T INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=T.SubjectId  where EmployeeId=@rEmployeeId and TimeTableSchemaId=@rTimeTableSchemaId and DayId=5 and LectureNumber=@HeaderCounterStart)
             
            -- IF(@AssignThursdayClassDivisionId is NULL)
            -- BEGIN
            --  SET @AssignThursdayClassDivisionId='-1'
            -- END 
            --  IF(@AssignThursdaySubjectId is NULL)
            -- BEGIN
            --  SET @AssignThursdaySubjectId='-1'
            -- END 
             
             
            -- SET @AssignThursdayDivisionSubject=@AssignThursdayClassDivisionId +'/' + @AssignThursdaySubjectId
             
             
            -- Declare @AssignFridayDivisionSubject varchar(100)
            -- Declare @AssignFridayClassDivisionId varchar(100)
            -- Declare @AssignFridaySubjectId varchar(100)
             
            -- SET @AssignFridayClassDivisionId=(SELECT VBCD.DivisionId From  sTimetable.tTimeTable T INNER JOIN sSetup.vClassDivision VBCD ON VBCD.DivisionId=T.DivisionId  where EmployeeId=@rEmployeeId and TimeTableSchemaId=@rTimeTableSchemaId and DayId=6 and LectureNumber=@HeaderCounterStart)
            -- SET @AssignFridaySubjectId=(SELECT SM.Id From  sTimetable.tTimeTable T INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=T.SubjectId  where EmployeeId=@rEmployeeId and TimeTableSchemaId=@rTimeTableSchemaId and DayId=6 and LectureNumber=@HeaderCounterStart)
             
            -- IF(@AssignFridayClassDivisionId is NULL)
            -- BEGIN
            --  SET @AssignFridayClassDivisionId='-1'
            -- END 
            --  IF(@AssignFridaySubjectId is NULL)
            -- BEGIN
            --  SET @AssignFridaySubjectId='-1'
            -- END 
             
             
            -- SET @AssignFridayDivisionSubject=@AssignFridayClassDivisionId +'/' + @AssignFridaySubjectId
             
            -- Declare @AssignSaturdayDivisionSubject varchar(100)
            -- Declare @AssignSaturdayClassDivisionId varchar(100)
            -- Declare @AssignSaturdaySubjectId varchar(100)
             
            -- SET @AssignSaturdayClassDivisionId=(SELECT VBCD.DivisionId From  sTimetable.tTimeTable T INNER JOIN sSetup.vClassDivision VBCD ON VBCD.DivisionId=T.DivisionId  where EmployeeId=@rEmployeeId and TimeTableSchemaId=@rTimeTableSchemaId and DayId=7 and LectureNumber=@HeaderCounterStart)
            -- SET @AssignSaturdaySubjectId=(SELECT SM.Id From  sTimetable.tTimeTable T INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=T.SubjectId  where EmployeeId=@rEmployeeId and TimeTableSchemaId=@rTimeTableSchemaId and DayId=7 and LectureNumber=@HeaderCounterStart)
             
            -- IF(@AssignSaturdayClassDivisionId is NULL)
            -- BEGIN
            --  SET @AssignSaturdayClassDivisionId='-1'
            -- END 
            --  IF(@AssignSaturdaySubjectId is NULL)
            -- BEGIN
            --  SET @AssignSaturdaySubjectId='-1'
            -- END 
             
             
            -- SET @AssignSaturdayDivisionSubject=@AssignSaturdayClassDivisionId +'/' + @AssignSaturdaySubjectId
             
           print @HeaderCounterStart
      -- print @AssignThrusdayClassDivisionName
       --print @AssignThrusdaySubjectName
			--INSERT INTO @lTableList(LectureNumber,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday,MondayClassSubjectId,TuesdayClassSubjectId,WednesdayClassSubjectId,ThursdayClassSubjectId,FridayClassSubjectId,SaturdayClassSubjectId)
			--values(@HeaderCounterStart,@AssignMondayClassDivisionName +'/' + @AssignMondaySubjectName,@AssignTuesdayClassDivisionName+'/' + @AssignTuesdaySubjectName,@AssignWedenadayClassDivisionName+'/' + @AssignWedenadaySubjectName,@AssignThrusdayClassDivisionName+'/' + @AssignThrusdaySubjectName,@AssignFridayClassDivisionName+'/' + @AssignFridaySubjectName,@AssignSaturdayClassDivisionName+'/' + @AssignSaturdaySubjectName,@AssignMondayDivisionSubject,@AssignTuesdayDivisionSubject,@AssignWednesdayDivisionSubject,@AssignThursdayDivisionSubject,@AssignFridayDivisionSubject,@AssignSaturdayDivisionSubject)
        
   --    INSERT INTO @lTableList(LectureNumber,Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday,SundayClassSubjectId,MondayClassSubjectId,TuesdayClassSubjectId,WednesdayClassSubjectId,ThursdayClassSubjectId,FridayClassSubjectId,SaturdayClassSubjectId)
			--values(@HeaderCounterStart,@AssignSundayClassDivisionName +'/' + @AssignSundaySubjectName,@AssignMondayClassDivisionName +'/' + @AssignMondaySubjectName,@AssignTuesdayClassDivisionName+'/' + @AssignTuesdaySubjectName,@AssignWedenadayClassDivisionName+'/' + @AssignWedenadaySubjectName,@AssignThrusdayClassDivisionName +'/' + @AssignThrusdaySubjectName,@AssignFridayClassDivisionName+'/' + @AssignFridaySubjectName,@AssignSaturdayClassDivisionName+'/' + @AssignSaturdaySubjectName,@AssignSundayDivisionSubject,@AssignMondayDivisionSubject,@AssignTuesdayDivisionSubject,@AssignWednesdayDivisionSubject,@AssignThursdayDivisionSubject,@AssignFridayDivisionSubject,@AssignSaturdayDivisionSubject)
        
        INSERT INTO @lTableList(LectureNumber,Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday,SundayClassSubjectId,MondayClassSubjectId,TuesdayClassSubjectId,WednesdayClassSubjectId,ThursdayClassSubjectId,FridayClassSubjectId,SaturdayClassSubjectId)
			values(@HeaderCounterStart,@AssignSundayDivisionSubjectName,@AssignMondayDivisionSubjectName,@AssignTuesdayDivisionSubjectName,@AssignWednesdayDivisionSubjectName,@AssignThrusdayDivisionSubjectName,@AssignFridayDivisionSubjectName,@AssignSaturdayDivisionSubjectName,@AssignSundayDivisionSubject,@AssignMondayDivisionSubject,@AssignTuesdayDivisionSubject,@AssignWednesdayDivisionSubject,@AssignThursdayDivisionSubject,@AssignFridayDivisionSubject,@AssignSaturdayDivisionSubject)
        
            
        SET @HeaderCounterStart=@HeaderCounterStart+1;
    END



     select *From @lTableList
END
GO
PRINT N'Altering [sTimetable].[pImportTimeTableData]...';


GO
ALTER PROCEDURE [sTimetable].[pImportTimeTableData]
				
		@rTimeTableSchemaID int,
		@rCreatedUserId bigint
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

BEGIN 
 	   
	 IF EXISTS(SELECT 1 FROM sTimetable.tDivisionWorkLoad WHERE TimeTableSchemaID=@rTimeTableSchemaID AND NoOfLecture<>0) 	
	 BEGIN   	    
	    SELECT -101 AS Result
	    RETURN;
	 END
	  
	 IF EXISTS(SELECT 1 FROM sTimetable.tTeacherWorkLoad WHERE TimeTableSchemaID=@rTimeTableSchemaID) 	   
	 BEGIN
	    SELECT -102 AS Result
	    RETURN;
	 END
	
	 IF EXISTS(SELECT 1 FROM sTimetable.tAssignOrg WHERE TimeTableSchemaID=@rTimeTableSchemaID) 
	 BEGIN	   
	    SELECT -103 AS Result
	    RETURN;
	 END
	  
	 IF EXISTS(SELECT 1 FROM sTimetable.tAssignTeacher WHERE TimeTableSchemaID=@rTimeTableSchemaID) 	
	 BEGIN   
	    SELECT -104 AS Result
	    RETURN;
	 END
	  BEGIN TRY	
	 BEGIN TRANSACTION 
	  
	   INSERT INTO sTimetable.tDivisionWorkLoad(BatchId, DivisionId, SubjectId , NoOfLecture , CreatedUserId , CreatedDateTime ,TimeTableSchemaId)
	       SELECT ISNULL(([sTimeTable].[fBatchGet] (@rTimeTableSchemaID,TT.DivisionId)),0) AS BatchId , DivisionId , SubjectId , COUNT(LectureNumber) AS NoOfLecture , @rCreatedUserId , GETDATE() , @rTimeTableSchemaID 
	           FROM sTimetable.tTimeTable TT 
	       WHERE TT.TimeTableSchemaID=@rTimeTableSchemaID
	       GROUP BY TT.DivisionId , TT.SubjectId , TT.TimeTableSchemaId
	      
	   	   
	   INSERT INTO sTimetable.tTeacherWorkLoad(BatchId, EmployeeId, DivisionId , SubjectId , NoOfLecture , CreatedUserId , CreatedDateTime ,TimeTableSchemaId , LectureLength)
	       SELECT ISNULL(([sTimeTable].[fBatchGet] (@rTimeTableSchemaID,TT.DivisionId)),0) AS BatchId , EmployeeId , DivisionId , SubjectId , COUNT(LectureNumber) AS NoOfLecture , @rCreatedUserId , GETDATE() , @rTimeTableSchemaID , 0 
	           FROM sTimetable.tTimeTable TT 
	       WHERE TT.TimeTableSchemaID=@rTimeTableSchemaID AND (TT.EmployeeId<>0 AND TT.EmployeeId IS NOT NULL)   
	       GROUP BY TT.EmployeeId , TT.DivisionId ,TT.SubjectId  ,TT.TimeTableSchemaId
	       
	       
	       
	   INSERT INTO sTimetable.tAssignTeacher  
	       SELECT DISTINCT TimeTableSchemaId,EmployeeId
	           FROM sTimetable.tTimeTable 
	       WHERE  TimeTableSchemaId=@rTimeTableSchemaID AND (EmployeeId<>0 AND EmployeeId IS NOT NULL)
          
       INSERT INTO sTimetable.tAssignOrg
           SELECT DISTINCT TT.TimeTableSchemaId,EM.OrgID   
			  FROM sTimetable.tTimeTable TT
			    LEFT JOIN sHrm.tEmployeeMaster EM ON TT.EmployeeId=EM.Id  AND ISNULL(EM.IsOtherUser,0) = 0			 
		   WHERE  TT.TimeTableSchemaId=@rTimeTableSchemaID AND (TT.EmployeeId<>0 AND TT.EmployeeId IS NOT NULL)
		 
	   SELECT 1 AS Result   
	        
	 COMMIT TRANSACTION
	 END TRY
	
	 BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	 END CATCH	
	
	
END 	             
	
		
END
GO
PRINT N'Altering [sTimetable].[pRptDivisionTimeTableGet]...';


GO

 
ALTER PROCEDURE [sTimetable].[pRptDivisionTimeTableGet]

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

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

	A.TimeTableID,
	A.DivisionName,
	
	A.EmployeeId,
	A.SubjectId,
	
	CASE WHEN A.EmployeeId=-1 THEN '###' WHEN A.EmployeeId=-2 THEN '***' ELSE A.EmployeeName END  AS EmployeeName,
	CASE WHEN A.SubjectId=-1 THEN '###' WHEN A.SubjectId=-2 THEN '***' ELSE A.Subject END  AS Subject,
	--A.Subject,
	A.DivisionId,
	ISNULL(L.Title,'') AS DayName,
	ISNULL(L.DayId,0) AS DayId,
	ISNULL(L.LectureNumber,'') AS LactureNumber,
	--ISNULL(A.DayName,'') AS DayName,
	--ISNULL(A.DayId,0) AS DayId,
	--ISNULL(A.LactureNumber,'') AS LactureNumber,
	A.DayLacture,
	A.ClassId,
	A.ClassDivisionName,
	A.DivisionOrderIndex,
	A.Code,
	A.TimeTableDetail,
	0 As IsPresent,
	'' As WeekOffs,
	CASE WHEN EXISTS (SELECT 1 FROM sTimetable.tTimeTableSchema TS INNER JOIN sTimetable.tTimeTable TT ON TT.TimeTableSchemaId = TS.Id WHERE TS.IsDisplayPeriodTime = 1 AND TS.Id = @rTimeTableSchemaId) THEN A.FromTime ELSE '' END As FromTime,
	CASE WHEN EXISTS (SELECT 1 FROM sTimetable.tTimeTableSchema TS INNER JOIN sTimetable.tTimeTable TT ON TT.TimeTableSchemaId = TS.Id WHERE TS.IsDisplayPeriodTime = 1 AND TS.Id = @rTimeTableSchemaId) THEN A.ToTime ELSE '' END As ToTime,
	ISNULL(IsDiplayPeriodTime,0) As IsDiplayPeriodTime,
	'' as DivisionIncharge,
	IsBreak,
	IsBreakBefore,
	EmployeeSubject,
	 ClassSubject

  FROM
(
	SELECT 
	--@rBuilder1 AS Builder1,
	--@rBuilder2 AS Builder2,	 
	TT.Id AS TimeTableID,
	ISNULL(DV.Title,'') AS DivisionName,
	ISNULL(EmployeeId,0) AS EmployeeId,
	ISNULL(SubjectId,0) AS SubjectId,

	ISNULL(Em.FirstName +'  '+Em.LastName,'')  AS EmployeeName,
	--ISNULL(Em.FirstName,'')  AS EmployeeName,  
	ISNULL(SM.Title,'') AS Subject,
	ISNULL(TT.DivisionId,0) AS DivisionId,
	ISNULL(DM.Title,'') AS DayName,
	ISNULL(TT.DayId,0) AS DayId,
	ISNULL(TT.LectureNumber,'') AS LactureNumber,
	ISNULL(DM.Title,'') +'-'+ISNULL(convert(nvarchar(4),TT.LectureNumber),'') AS DayLacture,
	ISNULL(DV.ClassId,0) AS ClassId,
	ISNULL(CM.DisplayTitle,'')+'-'+ISNULL(DV.Title,'') as ClassDivisionName,
	ISNULL(DV.OrderIndex,0) As DivisionOrderIndex,
	ISNULL(SM.Code,'') AS Code,
	--'' AS TimeTableDetail,
	--(ISNULL(CM.DisplayTitle,'')+'-'+ISNULL(DV.Title,'') + ISNULL(SM.Title,'')) AS TimeTableDetail
	ISNULL([sTimetable].[fTimeTableDivisionGet](TT.TimeTableSchemaId,TT.Id,TT.EmployeeId,TT.DayId,TT.LectureNumber,0),'') AS TimeTableDetail,
	ISNULL(TTM.FromTime,0) As FromTime,
	ISNULL(TTM.ToTime,0) As ToTime,
	ISNULL(TS.IsDisplayPeriodTime,0) As IsDiplayPeriodTime,

	--GetBreak
	CASE WHEN 
	(SELECT ISNULL(IsBreak,0) FROM sTimetable.tTimeTableTime WHERE TimeTableSchemaId = TT.TimeTableSchemaId 
	AND DayId = TT.DayId AND DivisionId = TT.DivisionId AND LectureNumber = TT.LectureNumber AND IsBreak = 1) = 1 
	THEN (SELECT ISNULL(IsBreak,0) FROM sTimetable.tTimeTableTime WHERE TimeTableSchemaId = TT.TimeTableSchemaId 
	AND DayId = TT.DayId AND DivisionId = TT.DivisionId AND LectureNumber = TT.LectureNumber AND IsBreak = 1)
	ELSE ISNULL(TT.IsBreak,0) END AS IsBreak,

	--GetBreakBefore
	CASE WHEN 
	(SELECT ISNULL(IsBreakBefore,0) FROM sTimetable.tTimeTableTime WHERE TimeTableSchemaId = TT.TimeTableSchemaId 
	AND DayId = TT.DayId AND DivisionId = TT.DivisionId AND LectureNumber = TT.LectureNumber AND IsBreakBefore = 1) = 1 
	THEN (SELECT ISNULL(IsBreakBefore,0) FROM sTimetable.tTimeTableTime WHERE TimeTableSchemaId = TT.TimeTableSchemaId 
	AND DayId = TT.DayId AND DivisionId = TT.DivisionId AND LectureNumber = TT.LectureNumber AND IsBreakBefore = 1)
	ELSE ISNULL(TT.IsBreakBefore,0) END AS IsBreakBefore,
	
	STUFF((
			SELECT ', ' +  ISNULL(ISNULL(Em1.FirstName +'  '+Em1.LastName,'') +' - '+SM1.Title,'')
			FROM sTimetable.tTimeTable T1 
			inner join sHrm.tEmployeeMaster EM1 on EM1.Id=T1.EmployeeId
			INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=T1.SubjectId
			where T1.DivisionId=TT.DivisionId 
			AND TT.LectureNumber=T1.LectureNumber 
			AND TT.DayId=T1.DayId and TT.TimeTableSchemaId=T1.TimeTableSchemaId  
			--AND timetableid in ()
			FOR XML PATH('')
			), 1, 1, '') EmployeeSubject,
	[sCommon].[fXMLTagsReplaceReverse](STUFF((
		SELECT ',<br>' +  ISNULL(VBCD1.ClassDivisionName +' - '+SM1.Title,'')
				FROM sTimetable.tTimeTable T1 
				INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=T1.SubjectId
					INNER JOIN sSetup.vClassDivision VBCD1 ON VBCD1.DivisionId=T1.DivisionId
				where T1.EmployeeId=TT.EmployeeId 
				AND TT.LectureNumber=T1.LectureNumber 
				AND TT.DayId=T1.DayId and TT.TimeTableSchemaId=T1.TimeTableSchemaId  
				--AND timetableid in ()
				FOR XML PATH('')
				), 1, 11, ''))  ClassSubject 

	FROM 
	sTimetable.tTimeTable TT	
	INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = TT.SubjectId 
	LEFT JOIN sHrm.tEmployeeMaster Em ON Em.Id = TT.EmployeeId
	LEFT JOIN sCommon.tDayMaster DM ON DM.Id = TT.DayId
	LEFT JOIN sSetup.tDivisionMaster DV ON DV.Id = TT.DivisionId
	LEFT JOIN sSetup.tClassMaster CM ON CM.Id = DV.ClassId
	LEFT JOIN sTimetable.tTimeTableTime TTM ON TTM.TimeTableSchemaId=TT.TimeTableSchemaId AND TTM.DayId = DM.Id AND TTM.DivisionId = TT.DivisionId AND TTM.LectureNumber = TT.LectureNumber
	INNER JOIN sTimetable.tTimeTableSchema TS ON TS.Id = TT.TimeTableSchemaId
	WHERE (ClassId = @rClassId OR @rClassId=0)
	  AND (TT.DivisionId = @rDivisionId OR @rDivisionId=0)	
	  AND (TT.EmployeeId=@rEmployeeId OR @rEmployeeId=0)
	  AND TT.TimeTableSchemaId=@rTimeTableSchemaId
	  AND TT.EmployeeId <> 0
	  
	  UNION ALL
	  
	  
	  
	  	SELECT 
	--@rBuilder1 AS Builder1,
	--@rBuilder2 AS Builder2,	 
	TT.Id AS TimeTableID,
	ISNULL(DV.Title,'') AS DivisionName,
	ISNULL(TTD.EmployeeId,0) AS EmployeeId,
	ISNULL(TTD.SubjectId,0) AS SubjectId,

	ISNULL(Em.FirstName +'  '+Em.LastName,'')  AS EmployeeName,
	--ISNULL(Em.FirstName,'')  AS EmployeeName,  
	ISNULL(SM.Title,'') AS Subject,
	ISNULL(TT.DivisionId,0) AS DivisionId,
	ISNULL(DM.Title,'') AS DayName,
	ISNULL(TT.DayId,0) AS DayId,
	ISNULL(TT.LectureNumber,'') AS LactureNumber,
	ISNULL(DM.Title,'') +'-'+ISNULL(convert(nvarchar(4),TT.LectureNumber),'') AS DayLacture,
	ISNULL(DV.ClassId,0) AS ClassId,
	ISNULL(CM.DisplayTitle,'')+'-'+ISNULL(DV.Title,'') as ClassDivisionName,
	ISNULL(DV.OrderIndex,0) As DivisionOrderIndex,
	ISNULL(SM.Code,'') AS Code,
	--(ISNULL(CM.DisplayTitle,'')+'-'+ISNULL(DV.Title,'') + ISNULL(SM.Title,'')) AS TimeTableDetail
	'' AS TimeTableDetail,
	ISNULL(TTM.FromTime,0) As FromTime,
	ISNULL(TTM.ToTime,0) As ToTime,
	ISNULL(TS.IsDisplayPeriodTime,0) As IsDiplayPeriodTime,
	0 AS IsBreak,
	0 AS IsBreakBefore,
	STUFF((
			SELECT ', ' +  ISNULL(ISNULL(Em1.FirstName +'  '+Em1.LastName,'') +' - '+SM1.Title,'')
			FROM sTimetable.tTimeTable T1 
			inner join sHrm.tEmployeeMaster EM1 on EM1.Id=T1.EmployeeId
			INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=T1.SubjectId
			where T1.DivisionId=TT.DivisionId 
			AND TT.LectureNumber=T1.LectureNumber 
			AND TT.DayId=T1.DayId and TT.TimeTableSchemaId=T1.TimeTableSchemaId  
			--AND timetableid in ()
			FOR XML PATH('')
			), 1, 1, '') EmployeeSubject ,
	[sCommon].[fXMLTagsReplaceReverse](STUFF((
		SELECT ',<br>' +  ISNULL(VBCD1.ClassDivisionName +' - '+SM1.Title,'')
				FROM sTimetable.tTimeTable T1 
				INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=T1.SubjectId
					INNER JOIN sSetup.vClassDivision VBCD1 ON VBCD1.DivisionId=T1.DivisionId
				where T1.EmployeeId=TT.EmployeeId 
				AND TT.LectureNumber=T1.LectureNumber 
				AND TT.DayId=T1.DayId and TT.TimeTableSchemaId=T1.TimeTableSchemaId  
				--AND timetableid in ()
				FOR XML PATH('')
				), 1, 11, ''))  ClassSubject 

	FROM 
	sTimetable.tTimeTable TT
	INNER JOIN 	sTimetable.tTimeTableDetail TTD ON TTD.TimetableId = TT.Id
	INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = TTD.SubjectId 
	INNER JOIN sHrm.tEmployeeMaster Em ON Em.Id = TTD.EmployeeId
	LEFT JOIN sCommon.tDayMaster DM ON DM.Id = TT.DayId
	LEFT JOIN sSetup.tDivisionMaster DV ON DV.Id = TT.DivisionId
	LEFT JOIN sSetup.tClassMaster CM ON CM.Id = DV.ClassId
	LEFT JOIN sTimetable.tTimeTableTime TTM ON TTM.TimeTableSchemaId=TT.TimeTableSchemaId AND TTM.DayId = DM.Id AND TTM.DivisionId = TT.DivisionId AND TTM.LectureNumber = TT.LectureNumber
	INNER JOIN sTimetable.tTimeTableSchema TS ON TS.Id = TT.TimeTableSchemaId 

	WHERE (ClassId = @rClassId OR @rClassId=0)
	  AND (TT.DivisionId = @rDivisionId OR @rDivisionId=0)	
	  AND (TTD.EmployeeId=@rEmployeeId OR @rEmployeeId=0)
	  AND TT.TimeTableSchemaId=@rTimeTableSchemaId
	 
	  
	  --ORDER BY DV.OrderIndex
	  )
	  A
			INNER JOIN (SELECT DISTINCT DayId,LectureNumber,DM.title  FROM sTimetable.tTimeTable
			INNER JOIN sCommon.tDayMaster DM ON DM.Id = DayId
			WHERE TimeTableSchemaId=@rTimeTableSchemaId  ) L
			ON A.LactureNumber = L.LectureNumber AND A.DayId = L.DayId

	END
ELSE IF(@rReportId = 30661) --- Absent Teacher Divisionwise
  BEGIN
	  SELECT

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

	[sHrm].[fEmployeeNameGet](ISNULL(Em.FirstName,'') , ISNULL(Em.MiddleName,''), ISNULL(Em.LastName,''),ISNULL(OM.EmployeeNameFormatId,1)) AS EmployeeName,
	--ISNULL(Em.FirstName +'  '+Em.LastName,'')  AS EmployeeName,
	--ISNULL(Em.FirstName,'')  AS EmployeeName,  
	ISNULL(SM.Title,'') AS Subject,
	ISNULL(TT.DivisionId,0) AS DivisionId,
	ISNULL(DM.Title,'') AS DayName,
	ISNULL(TT.DayId,0) AS DayId,
	ISNULL(TT.LectureNumber,'') AS LactureNumber,
	ISNULL(DM.Title,'') +'-'+ISNULL(convert(nvarchar(4),TT.LectureNumber),'') AS DayLacture,
	ISNULL(DV.ClassId,0) AS ClassId,
	ISNULL(CM.DisplayTitle,'')+'-'+ISNULL(DV.Title,'') as ClassDivisionName,
	ISNULL(DV.OrderIndex,0) As DivisionOrderIndex,
	ISNULL(SM.Code,'') AS Code,
	'' AS TimeTableDetail,
	ISNULL(EAR.IsPresent,0) AS IsPresent,
	[sCommon].[fXMLTagsReplaceReverse](STUFF((
			SELECT ',<br>' + case when ISNULL(EAR1.IsPresent,0)=0 then   ISNULL(ISNULL([sHrm].[fEmployeeNameGet](ISNULL(Em1.FirstName,'') , ISNULL(Em1.MiddleName,''), ISNULL(Em1.LastName,''),ISNULL(OM1.EmployeeNameFormatId,1)),'') +' <br><b> '+SM1.Title+'</b>','') else '' end
			FROM sTimetable.tTimeTable T1 
			Left join sHrm.tEmployeeMaster EM1 on EM1.Id=T1.EmployeeId
			left JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=T1.SubjectId
			LEFT JOIN sSetup.tOrganizationMaster OM1 ON OM1.Id = Em1.OrgID
			RIGHT JOIN sHrm.tEmployeeAttendanceRegister EAR1 ON EAR1.EmployeeId = Em1.Id
			where T1.DivisionId=TT.DivisionId 
			AND T1.LectureNumber=TT.LectureNumber 
			AND T1.DayId=TT.DayId and T1.TimeTableSchemaId=TT.TimeTableSchemaId  
			AND (EAR1.AttendanceDate = @rDate OR @rDate = '')
			AND (T1.DayId = (DATEPART(weekday,@rDate)) OR @rDate = '') 
			--AND timetableid in ()
			FOR XML PATH('')
			), 1, 11, '')) EmployeeSubject
	--(ISNULL(CM.DisplayTitle,'')+'-'+ISNULL(DV.Title,'') + ISNULL(SM.Title,'')) AS TimeTableDetail
	--ISNULL([sTimetable].[fTimeTableDivisionGet](TT.TimeTableSchemaId,TT.Id,TT.EmployeeId,TT.DayId,TT.LectureNumber),'') AS TimeTableDetail
	FROM 
	sTimetable.tTimeTable TT	 
	LEFT JOIN sSetup.tSubjectMaster SM ON SM.Id = TT.SubjectId 
	LEFT JOIN sHrm.tEmployeeMaster Em ON Em.Id = TT.EmployeeId
	LEFT JOIN sCommon.tDayMaster DM ON DM.Id = TT.DayId
	LEFT JOIN sSetup.tDivisionMaster DV ON DV.Id = TT.DivisionId
	LEFT JOIN sSetup.tClassMaster CM ON CM.Id = DV.ClassId
	LEFT JOIN sSetup.tOrganizationMaster OM ON OM.Id = Em.OrgID
	RIGHT JOIN sHrm.tEmployeeAttendanceRegister EAR ON EAR.EmployeeId = Em.Id

	WHERE (ClassId = @rClassId OR @rClassId=0)
	  AND (TT.DivisionId = @rDivisionId OR @rDivisionId=0)	
	  AND (TT.EmployeeId=@rEmployeeId OR @rEmployeeId=0)
	  AND TT.TimeTableSchemaId=@rTimeTableSchemaId
	  AND (EAR.AttendanceDate = @rDate OR @rDate = '')
	  AND (TT.DayId = (DATEPART(weekday,@rDate)) OR @rDate = '')

	  UNION ALL
	  
	  
	  
	  	SELECT 
	--@rBuilder1 AS Builder1,
	--@rBuilder2 AS Builder2,	 
	TT.Id AS TimeTableID,
	ISNULL(DV.Title,'') AS DivisionName,
	ISNULL(TTD.EmployeeId,0) AS EmployeeId,
	ISNULL(TTD.SubjectId,0) AS SubjectId,

	[sHrm].[fEmployeeNameGet](ISNULL(Em.FirstName,'') , ISNULL(Em.MiddleName,''), ISNULL(Em.LastName,''),ISNULL(OM.EmployeeNameFormatId,1)) AS EmployeeName,
	--ISNULL(Em.FirstName +'  '+Em.LastName,'')  AS EmployeeName,
	--ISNULL(Em.FirstName,'')  AS EmployeeName,  
	ISNULL(SM.Title,'') AS Subject,
	ISNULL(TT.DivisionId,0) AS DivisionId,
	ISNULL(DM.Title,'') AS DayName,
	ISNULL(TT.DayId,0) AS DayId,
	ISNULL(TT.LectureNumber,'') AS LactureNumber,
	ISNULL(DM.Title,'') +'-'+ISNULL(convert(nvarchar(4),TT.LectureNumber),'') AS DayLacture,
	ISNULL(DV.ClassId,0) AS ClassId,
	ISNULL(CM.DisplayTitle,'')+'-'+ISNULL(DV.Title,'') as ClassDivisionName,
	ISNULL(DV.OrderIndex,0) As DivisionOrderIndex,
	ISNULL(SM.Code,'') AS Code,
	--(ISNULL(CM.DisplayTitle,'')+'-'+ISNULL(DV.Title,'') + ISNULL(SM.Title,'')) AS TimeTableDetail
	ISNULL([sTimetable].[fTimeTableDivisionGet](TT.TimeTableSchemaId,TT.Id,TTD.EmployeeId,TT.DayId,TT.LectureNumber,0),'') AS TimeTableDetail,
	ISNULL(EAR.IsPresent,'') As IsPresent,
	[sCommon].[fXMLTagsReplaceReverse](STUFF((
			SELECT   ',<br>' +case when ISNULL(EAR1.IsPresent,0)=0 then ISNULL(ISNULL([sHrm].[fEmployeeNameGet](ISNULL(Em1.FirstName,'') , ISNULL(Em1.MiddleName,''), ISNULL(Em1.LastName,''),ISNULL(OM1.EmployeeNameFormatId,1)),'') +' <br><b> '+SM1.Title+'</b>','') else '' end
			FROM sTimetable.tTimeTable T1 
			inner join sHrm.tEmployeeMaster EM1 on EM1.Id=T1.EmployeeId
			INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=T1.SubjectId
			LEFT JOIN sSetup.tOrganizationMaster OM1 ON OM1.Id = Em1.OrgID
			LEFT JOIN sHrm.tEmployeeAttendanceRegister EAR1 ON EAR1.EmployeeId = Em1.Id
			where T1.DivisionId=TT.DivisionId 
			AND T1.LectureNumber=TT.LectureNumber 
			AND T1.DayId=TT.DayId and T1.TimeTableSchemaId=TT.TimeTableSchemaId  
			AND (EAR1.AttendanceDate = @rDate OR @rDate = '')
			AND (T1.DayId = (DATEPART(weekday,@rDate)) OR @rDate = '') 
			--AND timetableid in ()
			FOR XML PATH('')
			), 1, 11, '')) EmployeeSubject
	FROM 
	sTimetable.tTimeTable TT
	INNER JOIN 	sTimetable.tTimeTableDetail TTD ON TTD.TimetableId = TT.Id
	INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = TTD.SubjectId 
	INNER JOIN sHrm.tEmployeeMaster Em ON Em.Id = TTD.EmployeeId
	LEFT JOIN sCommon.tDayMaster DM ON DM.Id = TT.DayId
	LEFT JOIN sSetup.tDivisionMaster DV ON DV.Id = TT.DivisionId
	LEFT JOIN sSetup.tClassMaster CM ON CM.Id = DV.ClassId
	LEFT JOIN sSetup.tOrganizationMaster OM ON OM.Id = Em.OrgID
	LEFT JOIN sHrm.tEmployeeAttendanceRegister EAR ON EAR.EmployeeId = Em.Id

	WHERE (ClassId = @rClassId OR @rClassId=0)
	  AND (TT.DivisionId = @rDivisionId OR @rDivisionId=0)	
	  AND (TTD.EmployeeId=@rEmployeeId OR @rEmployeeId=0)
	  AND TT.TimeTableSchemaId=@rTimeTableSchemaId
	  AND (EAR.AttendanceDate = @rDate OR @rDate = '')
	  AND (TT.DayId = (DATEPART(weekday,@rDate)) OR @rDate = '') 
	  
	  --ORDER BY DV.OrderIndex
	  )
	  A
			INNER JOIN (SELECT DISTINCT DayId,LectureNumber,DM.title  FROM sTimetable.tTimeTable
			INNER JOIN sCommon.tDayMaster DM ON DM.Id = DayId
			
			WHERE TimeTableSchemaId=@rTimeTableSchemaId ) L
			ON A.LactureNumber = L.LectureNumber AND A.DayId = L.DayId

	END
ELSE IF(@rReportId = 30925) --TeacherTimeTable_2
   BEGIN
   SELECT

	A.TimeTableID,
	A.DivisionName,
	A.EmployeeId,
	A.SubjectId,
	CASE WHEN A.EmployeeId=-1 THEN '###' WHEN A.EmployeeId=-2 THEN '***' ELSE A.EmployeeName END As EmployeeName,
	CASE WHEN A.SubjectId=-1 THEN '###' WHEN A.SubjectId=-2 THEN '***' ELSE A.Subject END  AS Subject,
	--A.Subject,
	A.DivisionId,
	--ISNULL(L.Title,'') AS DayName,
	--ISNULL(L.DayId,0) AS DayId,
	--ISNULL(L.LectureNumber,'') AS LactureNumber,
	ISNULL(A.DayName,'') AS DayName,
	ISNULL(A.DayId,0) AS DayId,
	ISNULL(A.LactureNumber,'') AS LactureNumber,
	A.DayLacture,
	A.ClassId,
	A.ClassDivisionName,
	A.DivisionOrderIndex,
	A.Code,
	[sTimetable].[fTimeTableDetailGet](A.TimeTableID,1) AS TimeTableDetail,
	0 AS IsPresent,
	A.WeekOffs,
	CASE WHEN EXISTS (SELECT 1 FROM sTimetable.tTimeTableSchema TS INNER JOIN sTimetable.tTimeTable TT ON TT.TimeTableSchemaId = TS.Id WHERE TS.IsDisplayPeriodTime = 1 AND TS.Id = @rTimeTableSchemaId) THEN A.FromTime ELSE '' END As FromTime,
	CASE WHEN EXISTS (SELECT 1 FROM sTimetable.tTimeTableSchema TS INNER JOIN sTimetable.tTimeTable TT ON TT.TimeTableSchemaId = TS.Id WHERE TS.IsDisplayPeriodTime = 1 AND TS.Id = @rTimeTableSchemaId) THEN A.ToTime ELSE '' END As ToTime,
	ISNULL(IsDiplayPeriodTime,0) As IsDiplayPeriodTime,
	DivisionIncharge,
	'' AS EmployeeSubject,
	ClassSubject
FROM
(
	SELECT 
	--@rBuilder1 AS Builder1,
	--@rBuilder2 AS Builder2,	 
	TT.Id AS TimeTableID,
	ISNULL(DV.Title,'') AS DivisionName,
	ISNULL(TT.EmployeeId,0) AS EmployeeId,
	ISNULL(SubjectId,0) AS SubjectId,
	[sHrm].[fEmployeeNameGet](ISNULL(EM.FirstName,'') , ISNULL(EM.MiddleName,''), ISNULL(EM.LastName,''),ISNULL(OM.EmployeeNameFormatId,1)) AS EmployeeName,
	--ISNULL(EM.LastName+' '+EM.FirstName,'')  AS EmployeeName,
	ISNULL(SM.Title,'') AS Subject,
	ISNULL(TT.DivisionId,0) AS DivisionId,
	ISNULL(DM.Title,'') AS DayName,
	ISNULL(TT.DayId,0) AS DayId,
	ISNULL(TT.LectureNumber,'') AS LactureNumber,
	ISNULL(DM.Title,'') +'-'+ISNULL(convert(nvarchar(4),TT.LectureNumber),'') AS DayLacture,
	ISNULL(DV.ClassId,0) AS ClassId,
	ISNULL(CM.DisplayTitle,'')+'-'+ISNULL(DV.Title,'') as ClassDivisionName,
	ISNULL(DV.OrderIndex,0) As DivisionOrderIndex,
	ISNULL(SM.Code,'') AS Code,
	ISNULL(TTS.WeekOffs,'') As WeekOffs,
	ISNULL(TTM.FromTime,'') As FromTime,
	ISNULL(TTM.ToTime,'') As ToTime,
	ISNULL(TS.IsDisplayPeriodTime,0) As IsDiplayPeriodTime,
	(SELECT ISNULL(EM.FirstName+' '+EM.LastName,'') FROM sHrm.tEmployeeMaster EM INNER JOIN sSetup.tDivisionMaster DIE ON DIE.InchargeEmployeeId = EM.Id  WHERE DIE.Id = DV.Id) as DivisionIncharge,
	[sCommon].[fXMLTagsReplaceReverse](STUFF((
		SELECT ',<br>' +  ISNULL(VBCD1.ClassDivisionName +'<br><b>'+SM1.Title+'</b>','')
				FROM sTimetable.tTimeTable T1 
				INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=T1.SubjectId
					INNER JOIN sSetup.vClassDivision VBCD1 ON VBCD1.DivisionId=T1.DivisionId
				where T1.EmployeeId=TT.EmployeeId 
				AND TT.LectureNumber=T1.LectureNumber 
				AND TT.DayId=T1.DayId and TT.TimeTableSchemaId=T1.TimeTableSchemaId  
				--AND timetableid in ()
				FOR XML PATH('')
				), 1, 11, ''))  ClassSubject
	FROM 
	sTimetable.tTimeTable TT  
	LEFT JOIN sSetup.tSubjectMaster SM ON SM.Id = TT.SubjectId 
	INNER JOIN sHrm.tEmployeeMaster Em ON Em.Id = TT.EmployeeId
	LEFT JOIN sCommon.tDayMaster DM ON DM.Id = TT.DayId
	LEFT JOIN sSetup.tDivisionMaster DV ON DV.Id = TT.DivisionId
	LEFT JOIN sSetup.tClassMaster CM ON CM.Id = DV.ClassId
	LEFT JOIN sTimetable.tTimeTableSchema TTS ON TTS.Id = TT.TimeTableSchemaId
	LEFT JOIN sTimetable.tTimeTableTime TTM ON TTM.TimeTableSchemaId=TT.TimeTableSchemaId AND TTM.DayId = DM.Id AND TTM.DivisionId = TT.DivisionId AND TTM.LectureNumber = TT.LectureNumber AND TTM.IsBreak = 0
	INNER JOIN sTimetable.tTimeTableSchema TS ON TS.Id = TT.TimeTableSchemaId 
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = DV.OrgId
	WHERE (ClassId = @rClassId OR @rClassId=0)
	  AND (TT.DivisionId = @rDivisionId OR @rDivisionId=0)	
	  AND (TT.EmployeeId=@rEmployeeId OR @rEmployeeId=0)
	  AND TT.TimeTableSchemaId=@rTimeTableSchemaId
	  AND (TT.DayId = (DATEPART(weekday,@rDate)) OR @rDate = '')
	  AND (OM.Id = @rOrgId OR @rOrgId = 0)
	  --AND (Em.OrgId = @rOrgId OR @rOrgId = 0)
	  )
	  A  ORDER BY A.EmployeeName, A.DivisionOrderIndex,A.DayId, A.LactureNumber
   END
 ELSE
 BEGIN
	SELECT

	A.TimeTableID,
	A.DivisionName,
	A.EmployeeId,
	A.SubjectId,
	CASE WHEN A.EmployeeId=-1 THEN '###' WHEN A.EmployeeId=-2 THEN '***' ELSE A.EmployeeName END As EmployeeName,
	CASE WHEN A.SubjectId=-1 THEN '###' WHEN A.SubjectId=-2 THEN '***' ELSE A.Subject END  AS Subject,
	--A.Subject,
	A.DivisionId,
	--ISNULL(L.Title,'') AS DayName,
	--ISNULL(L.DayId,0) AS DayId,
	--ISNULL(L.LectureNumber,'') AS LactureNumber,
	ISNULL(A.DayName,'') AS DayName,
	ISNULL(A.DayId,0) AS DayId,
	ISNULL(A.LactureNumber,'') AS LactureNumber,
	A.DayLacture,
	A.ClassId,
	A.ClassDivisionName,
	A.DivisionOrderIndex,
	A.Code,
	[sTimetable].[fTimeTableDetailGet](A.TimeTableID,1) AS TimeTableDetail,
	0 AS IsPresent,
	A.WeekOffs,
	CASE WHEN EXISTS (SELECT 1 FROM sTimetable.tTimeTableSchema TS INNER JOIN sTimetable.tTimeTable TT ON TT.TimeTableSchemaId = TS.Id WHERE TS.IsDisplayPeriodTime = 1 AND TS.Id = @rTimeTableSchemaId) THEN A.FromTime ELSE '' END As FromTime,
	CASE WHEN EXISTS (SELECT 1 FROM sTimetable.tTimeTableSchema TS INNER JOIN sTimetable.tTimeTable TT ON TT.TimeTableSchemaId = TS.Id WHERE TS.IsDisplayPeriodTime = 1 AND TS.Id = @rTimeTableSchemaId) THEN A.ToTime ELSE '' END As ToTime,
	ISNULL(IsDiplayPeriodTime,0) As IsDiplayPeriodTime,
	DivisionIncharge,
	IsBreak,
	IsBreakBefore,
	EmployeeSubject,
	ClassSubject
FROM
(
	SELECT 
	--@rBuilder1 AS Builder1,
	--@rBuilder2 AS Builder2,	 
	TT.Id AS TimeTableID,
	ISNULL(DV.Title,'') AS DivisionName,
	ISNULL(TT.EmployeeId,0) AS EmployeeId,
	ISNULL(SubjectId,0) AS SubjectId,
	[sHrm].[fEmployeeNameGet](ISNULL(Em.FirstName,'') , ISNULL(Em.MiddleName,''), ISNULL(Em.LastName,''),ISNULL(OM.EmployeeNameFormatId,1)) AS EmployeeName,
	--ISNULL(EM.LastName+' '+EM.FirstName,'')  AS EmployeeName,
	ISNULL(SM.Title,'') AS Subject,
	ISNULL(TT.DivisionId,0) AS DivisionId,
	ISNULL(DM.Title,'') AS DayName,
	ISNULL(TT.DayId,0) AS DayId,
	ISNULL(TT.LectureNumber,'') AS LactureNumber,
	ISNULL(DM.Title,'') +'-'+ISNULL(convert(nvarchar(4),TT.LectureNumber),'') AS DayLacture,
	ISNULL(DV.ClassId,0) AS ClassId,
	ISNULL(CM.DisplayTitle,'')+'-'+ISNULL(DV.Title,'') as ClassDivisionName,
	ISNULL(DV.OrderIndex,0) As DivisionOrderIndex,
	ISNULL(SM.Code,'') AS Code,
	ISNULL(TTS.WeekOffs,'') As WeekOffs,
	ISNULL(TTM.FromTime,'') As FromTime,
	ISNULL(TTM.ToTime,'') As ToTime,
	ISNULL(TS.IsDisplayPeriodTime,0) As IsDiplayPeriodTime,
	(SELECT ISNULL(EM.FirstName+' '+EM.LastName,'') FROM sHrm.tEmployeeMaster EM INNER JOIN sSetup.tDivisionMaster DIE ON DIE.InchargeEmployeeId = EM.Id  WHERE DIE.Id = DV.Id) as DivisionIncharge,

	--GetBreak
	CASE WHEN 
	(SELECT ISNULL(IsBreak,0) FROM sTimetable.tTimeTableTime WHERE TimeTableSchemaId = TT.TimeTableSchemaId 
	AND DayId = TT.DayId AND DivisionId = TT.DivisionId AND LectureNumber = TT.LectureNumber AND IsBreak = 1) = 1 
	THEN (SELECT ISNULL(IsBreak,0) FROM sTimetable.tTimeTableTime WHERE TimeTableSchemaId = TT.TimeTableSchemaId 
	AND DayId = TT.DayId AND DivisionId = TT.DivisionId AND LectureNumber = TT.LectureNumber AND IsBreak = 1)
	ELSE ISNULL(TT.IsBreak,0) END AS IsBreak,

	--GetBreakBefore
	CASE WHEN 
	(SELECT ISNULL(IsBreakBefore,0) FROM sTimetable.tTimeTableTime WHERE TimeTableSchemaId = TT.TimeTableSchemaId 
	AND DayId = TT.DayId AND DivisionId = TT.DivisionId AND LectureNumber = TT.LectureNumber AND IsBreakBefore = 1) = 1 
	THEN (SELECT ISNULL(IsBreakBefore,0) FROM sTimetable.tTimeTableTime WHERE TimeTableSchemaId = TT.TimeTableSchemaId 
	AND DayId = TT.DayId AND DivisionId = TT.DivisionId AND LectureNumber = TT.LectureNumber AND IsBreakBefore = 1)
	ELSE ISNULL(TT.IsBreakBefore,0) END AS IsBreakBefore,
	[sCommon].[fXMLTagsReplaceReverse](STUFF((
			SELECT ',<br>' +  ISNULL(ISNULL([sHrm].[fEmployeeNameGet](ISNULL(Em1.FirstName,'') , ISNULL(Em1.MiddleName,''), ISNULL(Em1.LastName,''),ISNULL(OM1.EmployeeNameFormatId,1)) ,'') +' - '+SM1.Title,'')
			FROM sTimetable.tTimeTable T1 
			inner join sHrm.tEmployeeMaster EM1 on EM1.Id=T1.EmployeeId
			INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=T1.SubjectId
			LEFT JOIN sSetup.tOrganizationMaster OM1 ON OM1.Id = Em1.OrgID
			where T1.DivisionId=TT.DivisionId 
			AND T1.LectureNumber=TT.LectureNumber 
			AND T1.DayId=TT.DayId and T1.TimeTableSchemaId=TT.TimeTableSchemaId  
			--AND timetableid in ()
			FOR XML PATH('')
			), 1, 11, ''))  EmployeeSubject,
	[sCommon].[fXMLTagsReplaceReverse](STUFF((
		SELECT ',<br>' +  ISNULL(VBCD1.ClassDivisionName+'<br><b>' +SM1.Code+'</b>','')
				FROM sTimetable.tTimeTable T1 
				INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=T1.SubjectId
					INNER JOIN sSetup.vClassDivision VBCD1 ON VBCD1.DivisionId=T1.DivisionId
				where T1.EmployeeId=TT.EmployeeId 
				AND TT.LectureNumber=T1.LectureNumber 
				AND TT.DayId=T1.DayId and TT.TimeTableSchemaId=T1.TimeTableSchemaId  
				--AND timetableid in ()
				FOR XML PATH('')
				), 1, 11, '')) ClassSubject

	FROM 
	sTimetable.tTimeTable TT  
	LEFT JOIN sSetup.tSubjectMaster SM ON SM.Id = TT.SubjectId 
	LEFT JOIN sHrm.tEmployeeMaster Em ON Em.Id = TT.EmployeeId
	LEFT JOIN sCommon.tDayMaster DM ON DM.Id = TT.DayId
	LEFT JOIN sSetup.tDivisionMaster DV ON DV.Id = TT.DivisionId
	LEFT JOIN sSetup.tClassMaster CM ON CM.Id = DV.ClassId
	LEFT JOIN sTimetable.tTimeTableSchema TTS ON TTS.Id = TT.TimeTableSchemaId
	LEFT JOIN sTimetable.tTimeTableTime TTM ON TTM.TimeTableSchemaId=TT.TimeTableSchemaId AND TTM.DayId = DM.Id AND TTM.DivisionId = TT.DivisionId AND TTM.LectureNumber = TT.LectureNumber AND TTM.IsBreak = 0	
	INNER JOIN sTimetable.tTimeTableSchema TS ON TS.Id = TT.TimeTableSchemaId 
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = DV.OrgId
	WHERE (ClassId = @rClassId OR @rClassId=0)
	  AND (TT.DivisionId = @rDivisionId OR @rDivisionId=0)	
	  AND (TT.EmployeeId=@rEmployeeId OR @rEmployeeId=0)
	  AND TT.TimeTableSchemaId=@rTimeTableSchemaId
	  AND (TT.DayId = (DATEPART(weekday,@rDate)) OR @rDate = '')
	  AND (OM.Id = @rOrgId OR @rOrgId = 0)
	  AND TT.EmployeeId <> 0
	  )
	  A  ORDER BY A.EmployeeName, A.DivisionOrderIndex,A.DayId, A.LactureNumber
		END
END
GO
PRINT N'Altering [sTimetable].[pRptFreeLectureListGet]...';


GO
 
 

ALTER PROCEDURE [sTimetable].[pRptFreeLectureListGet]
	  @rBatchId int,
	  @rClassID int,
	  @rDivisionId int,
	  @rEmployeeId bigint,
	  @rTimeTableSchemaId int,	
	  @rReportId int,
	  @rOrgId int = 0	  
	  
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON 

BEGIN   
	

CREATE TABLE #Temp (Id int identity, LectureNumber int,TimeTableSchemaId int)
DECLARE @lMaxLecture int = (SELECT MAX(NoOfPeriod) FROM sTimeTable.tTimeSetup WHERE TimeTableSchemaId = @rTimeTableSchemaId)
DECLARE @lCount int = 1

WHILE @lCount <= @lMaxLecture
BEGIN
INSERT INTO #Temp VALUES (@lCount, @rTimeTableSchemaId)

SET @lCount = @lCount + 1
END

--SELECT * FROM #Temp


	SELECT	DISTINCT
		TS.DayId, 
		ISNULL(DM.Title,'') AS DayNames,
		EMP.Code,
		EMP.ID AS EmployeeId,
		[sHrm].[fEmployeeNameGet](ISNULL(EMP.FirstName,'') , ISNULL(EMP.MiddleName,''), ISNULL(EMP.LastName,''),ISNULL(OM.EmployeeNameFormatId,1)) AS EmployeeName,
		EMP.FirstName + ' '  + EMP.LastName AS Employee,
		CASE WHEN ISNULL(TT.LectureNumber,0) = TEM.LectureNumber AND ISNULL(TT.DayId,0) =  TS.DayId THEN ISNULL(TT.Id,0) ELSE 0 END AS TimeTableId,
		CASE WHEN ISNULL(TT.LectureNumber,0) = TEM.LectureNumber AND ISNULL(TT.DayId,0) =  TS.DayId THEN ISNULL(TT.LectureNumber,0) ELSE 0 END AS LectureNumber,
		--ISNULL(TT.LectureNumber,0) AS LectureNumber,
		CASE WHEN ISNULL(TT.LectureNumber,0) = TEM.LectureNumber AND ISNULL(TT.DayId,0) =  TS.DayId THEN ISNULL(TT.DayId,0) ELSE 0 END AS TimeTableDayId,
		--ISNULL(TT.DayId,0) AS TimeTableDayId,		
		TEM.LectureNumber AS Lecture,
		SM.Id AS SubjectId,
		SM.Title AS SubjectName,
		TTT.FromTime + ' - ' + TTT.ToTime AS LectureTime,
		DIM.Id AS DivisionId,
		DIM.Title AS DivisionTitle,
		CM.Id AS ClassId,
		CM.Title AS ClassTitle,
		CM.Title + ' ' + DIM.Title AS ClassDivisionName,
		TTS.IsDisplayPeriodTime,
		OM.Title AS OrganizationName,
		[sCommon].[fXMLTagsReplaceReverse](STUFF((
			SELECT ',<br>' +  ISNULL(VBCD1.ClassDivisionName +'-'+SM1.Title,'')
				FROM sTimetable.tTimeTable T1 
				INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=T1.SubjectId
				INNER JOIN sSetup.vClassDivision VBCD1 ON VBCD1.DivisionId=T1.DivisionId
				where T1.EmployeeId=TT.EmployeeId 
				AND TT.LectureNumber=T1.LectureNumber 
				AND TT.DayId=T1.DayId and TT.TimeTableSchemaId=T1.TimeTableSchemaId  
				--AND timetableid in ()
				FOR XML PATH('')
				), 1, 11, ''))  ClassSubject
	FROM
		sTimetable.tTimeSetup TS
		INNER JOIN sTimeTable.tTimeTableSchema TTS ON TTS.Id = TS.TimeTableSchemaId
		INNER JOIN sTimetable.tAssignTeacher ASS ON ASS.TimeTableSchemaId = TS.TimeTableSchemaId
		INNER JOIN  sHrm.tEmployeeMaster EMP ON EMP.Id = ASS.EmployeeId 
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EMP.OrgID		
		LEFT JOIN #Temp TEM ON TEM.TimeTableSchemaId = TS.TimeTableSchemaId
		LEFT JOIN sTimetable.tTimeTable TT ON TT.EmployeeId = EMP.Id AND TS.TimeTableSchemaId = TT.TimeTableSchemaId AND TS.DayId =TT.DayId AND TT.LectureNumber = TEM.LectureNumber
		LEFT JOIN sSetup.tSubjectMaster SM ON SM.Id = TT.SubjectId
		LEFT JOIN sSetup.tDivisionMaster DIM ON DIM.Id = TT.DivisionId
		LEFT JOIN sSetup.tClassMaster CM ON CM.Id = DIM.ClassId
		LEFT JOIN sTimeTable.tTimeTableTime TTT ON TTT.TimeTableSchemaId = TT.TimeTableSchemaId AND TTT.DivisionId = TT.DivisionId AND TTT.DayId = TS.DayId AND TTT.LectureNumber = TEM.LectureNumber
		INNER JOIN sCommon.tDayMaster DM ON DM.Id = TS.DayId AND NoOfPeriod > 0
	WHERE 
		TS.TimeTableSchemaId = @rTimeTableSchemaId
		AND TS.BatchID =@rBatchId 
		AND (EMP.OrgID = @rOrgId OR @rOrgId = 0) 
		AND  ISNULL(EMP.IsOtherUser,0) = 0 
		AND (EMP.Id = @rEmployeeId OR @rEmployeeId = 0)
		--AND (CM.Id = @rClassID OR @rClassID = 0)
		--AND (DIM.Id = @rDivisionId OR @rDivisionId = 0)
	--ORDER BY TT.Id,EMP.Id
    
DROP TABLE #Temp


--SELECT 
--		0 AS DayId, 
--		'' AS DayNames,
--		'' AS Code,
--		0 AS EmployeeId,
--		'' AS EmployeeName,
--		'' AS Employee,
--		0 AS TimeTableId,
--		0 AS LectureNumber,
--		--ISNULL(TT.LectureNumber,0) AS LectureNumber,
--		0 AS TimeTableDayId,
--		--ISNULL(TT.DayId,0) AS TimeTableDayId,		
--		0 AS Lecture,
--		0 AS SubjectId,
--		'' AS SubjectName,
--		'' AS LectureTime,
--		0 AS DivisionId,
--		'' AS DivisionTitle,
--		0 AS ClassId,
--		'' AS ClassTitle,
--		'' AS ClassDivisionName,
--		0 AS IsDisplayPeriodTime,
--		'' AS OrganizationName,
--		'' AS  ClassSubject

END
GO
PRINT N'Altering [sTimetable].[pRptFreeTeacherTimetableGet]...';


GO
 
ALTER PROCEDURE [sTimetable].[pRptFreeTeacherTimetableGet]

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

BEGIN   
 
	SELECT

	A.TimeTableID,
	A.DivisionName,
	A.EmployeeId,
	A.SubjectId,
	 
	CASE WHEN A.TimeTableID is not null THEN ISNULL(A.Subject,'FREE') ELSE '' END AS Subject,
	--CASE WHEN A.EmployeeId=-1 THEN 'FREE' WHEN A.EmployeeId=-2 THEN '***' ELSE A.EmployeeName END  AS EmployeeName,
	--CASE WHEN A.SubjectId=-1 THEN 'FREE' WHEN A.SubjectId=-2 THEN '***' ELSE A.Subject END  AS Subject,
	--ELSE
	 A.EmployeeName AS EmployeeName,
	--CASE WHEN A.EmployeeId=0 THEN 'Free' ELSE '' END AS Subject,
	 
	A.DivisionId,
	--ISNULL(L.Title,'') AS DayName,
	--ISNULL(L.DayId,0) AS DayId,
	--ISNULL(L.LectureNumber,'') AS LactureNumber,
	ISNULL(A.DayName,'') AS DayName,
	ISNULL(A.DayId,0) AS DayId,
	ISNULL(A.LactureNumber,'') AS LactureNumber,
	A.DayLacture,
	A.ClassId,
	'' AS ClassDivisionName,
	A.DivisionOrderIndex,
	A.Code ,
	 case WHEN A.TimeTableID is not null THEN ISNULL(A.ClassSubject,'FREE') ELSE '' END  AS ClassSubject
  FROM
(
	SELECT 
	--@rBuilder1 AS Builder1,
	--@rBuilder2 AS Builder2,	 
	TT.Id AS TimeTableID,
	ISNULL(DV.Title,'') AS DivisionName,
	ISNULL(TT.EmployeeId,0) AS EmployeeId,
	ISNULL(SubjectId,0) AS SubjectId,
	[sHrm].[fEmployeeNameGet](ISNULL(Em.FirstName,'') , ISNULL(Em.MiddleName,''), ISNULL(Em.LastName,''),ISNULL(OM.EmployeeNameFormatId,1)) AS EmployeeName,
	--ISNULL(Em.FirstName,'')  AS EmployeeName,  
	ISNULL(SM.Title,'') AS Subject,
	ISNULL(TT.DivisionId,0) AS DivisionId,
	ISNULL(DM.Title,'') AS DayName,
	ISNULL(TT.DayId,0) AS DayId,
	ISNULL(TT.LectureNumber,'') AS LactureNumber,
	ISNULL(DM.Title,'') +'-'+ISNULL(convert(nvarchar(4),TT.LectureNumber),'') AS DayLacture,
	ISNULL(DV.ClassId,0) AS ClassId,
	ISNULL(CM.DisplayTitle,'')+'-'+ISNULL(DV.Title,'') as ClassDivisionName,
	ISNULL(DV.OrderIndex,0) As DivisionOrderIndex,
	ISNULL(SM.Code,'') AS Code,
	STUFF((
		SELECT '/ ' +  ISNULL(SM1.Title,'')
				FROM sTimetable.tTimeTable T1 
				INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=T1.SubjectId
				where T1.EmployeeId=TT.EmployeeId 
				AND TT.LectureNumber=T1.LectureNumber 
				AND TT.DayId=T1.DayId and TT.TimeTableSchemaId=T1.TimeTableSchemaId  
				--AND timetableid in ()
				FOR XML PATH('')
				), 1, 1, '') ClassSubject
	
	FROM 
	sTimetable.tTimeTable TT  
	LEFT JOIN sSetup.tSubjectMaster SM ON SM.Id = TT.SubjectId 
	LEFT JOIN sHrm.tEmployeeMaster Em ON Em.Id = TT.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
	LEFT JOIN sCommon.tDayMaster DM ON DM.Id = TT.DayId
	LEFT JOIN sSetup.tDivisionMaster DV ON DV.Id = TT.DivisionId
	LEFT JOIN sSetup.tClassMaster CM ON CM.Id = DV.ClassId
	LEFT JOIN sSetup.tOrganizationMaster OM ON OM.Id = Em.OrgID
	WHERE  1=1
	AND (ClassId = @rClassId OR @rClassId=0)
	AND (TT.DivisionId = @rDivisionId OR @rDivisionId=0)	
	  AND (TT.EmployeeId=@rEmployeeId OR @rEmployeeId=0)
	  AND TT.TimeTableSchemaId=@rTimeTableSchemaId
	  AND (DV.OrgId = @rOrgId OR @rOrgId = 0)
	  --ORDER BY DV.OrderIndex
	  )
	  A
			--RIGHT JOIN (SELECT DISTINCT DayId,LectureNumber,DM.title  FROM sTimetable.tTimeTable
			--INNER JOIN sCommon.tDayMaster DM ON DM.Id = DayId
			--WHERE TimeTableSchemaId=@rTimeTableSchemaId ) L
			--ON A.LactureNumber = L.LectureNumber AND A.DayId = L.DayId
		 
END
GO
PRINT N'Altering [sTimetable].[pRptSubejctTimeTableGet]...';


GO
ALTER PROCEDURE [sTimetable].[pRptSubejctTimeTableGet]

	  @rSubjectId int,
	  @rTimeTableSchemaId int
	  
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON 

BEGIN   
   
--	SELECT

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


SELECT   A.LectureNumber,
		[sCommon].[fReplaceFirstWordOfLine]([sTimetable].[fTimeTableSubjectGet](@rTimeTableSchemaId,@rSubjectId,LectureNumber,1,0) + [sTimetable].[fTimeTableSubjectGet](@rTimeTableSchemaId,@rSubjectId,LectureNumber,1,1))  AS Sunday,
		[sCommon].[fReplaceFirstWordOfLine]([sTimetable].[fTimeTableSubjectGet](@rTimeTableSchemaId,@rSubjectId,LectureNumber,2,0) + [sTimetable].[fTimeTableSubjectGet](@rTimeTableSchemaId,@rSubjectId,LectureNumber,2,1)) AS Monday,
		[sCommon].[fReplaceFirstWordOfLine]([sTimetable].[fTimeTableSubjectGet](@rTimeTableSchemaId,@rSubjectId,LectureNumber,3,0) + [sTimetable].[fTimeTableSubjectGet](@rTimeTableSchemaId,@rSubjectId,LectureNumber,3,1)) AS Tuesday,
		[sCommon].[fReplaceFirstWordOfLine]([sTimetable].[fTimeTableSubjectGet](@rTimeTableSchemaId,@rSubjectId,LectureNumber,4,0) + [sTimetable].[fTimeTableSubjectGet](@rTimeTableSchemaId,@rSubjectId,LectureNumber,4,1)) AS Wednesday,
		[sCommon].[fReplaceFirstWordOfLine]([sTimetable].[fTimeTableSubjectGet](@rTimeTableSchemaId,@rSubjectId,LectureNumber,5,0) + [sTimetable].[fTimeTableSubjectGet](@rTimeTableSchemaId,@rSubjectId,LectureNumber,5,1)) AS Thursday,
		[sCommon].[fReplaceFirstWordOfLine]([sTimetable].[fTimeTableSubjectGet](@rTimeTableSchemaId,@rSubjectId,LectureNumber,6,0) + [sTimetable].[fTimeTableSubjectGet](@rTimeTableSchemaId,@rSubjectId,LectureNumber,6,1)) AS Friday,
		[sCommon].[fReplaceFirstWordOfLine]([sTimetable].[fTimeTableSubjectGet](@rTimeTableSchemaId,@rSubjectId,LectureNumber,7,0) + [sTimetable].[fTimeTableSubjectGet](@rTimeTableSchemaId,@rSubjectId,LectureNumber,7,1)) AS Saturday,
		WeekOffs
	FROM 
		(SELECT DISTINCT LectureNumber,TTS.WeekOffs As WeekOffs FROM sTimetable.tTimeTable TT LEFT JOIN sTimetable.tTimeTableSchema TTS ON TTS.Id = TT.TimeTableSchemaId  WHERE TimeTableSchemaId=@rTimeTableSchemaId ) A
END
GO
PRINT N'Altering [sTimetable].[pStudentTimeTableGet]...';


GO
 
 
ALTER PROCEDURE [sTimetable].[pStudentTimeTableGet]
	
	 @rStudentId bigint,
	 @rTimeTableSchemaId int,
	 @rDivisionId int,
	 @rFromDate Date='',
	 @rToDate Date=''
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 

	DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX),@query1  AS NVARCHAR(MAX),@query2  AS NVARCHAR(MAX),@query3 AS NVARCHAR(MAX)
	if(@rFromDate is null)
	BEGIN
	print @rFromDate
		set @rFromDate=''
	END
	if(@rToDate is null)
	BEGIN
		set @rToDate=''
	END

select @cols = STUFF((SELECT ',' + QUOTENAME(Title) 
                    from sCommon.tDayMaster
                    group by Title,Id 
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')
        
     
 IF EXISTS(SELECT 1 FROM sTimetable.tTimeTableSchema TS INNER JOIN sTimetable.tTimeTable TT ON TT.TimeTableSchemaId = TS.Id WHERE TS.IsDisplayPeriodTime = 1 AND TS.Id = @rTimeTableSchemaId)
  BEGIN 
		set @query = 'SELECT LectureNumber , ' + @cols + ',WeekOffs from 
					 (
					Select T.LectureNumber, 
					ISNULL((select top 1  CASE WHEN TTM.IsBreakBefore=1 then ''Break Before''+ ''(''+ISNULL(TTM.FromTime,0)+''-''+ISNULL(TTM.ToTime,0)+''); | ''  ELSE '''' end  from sTimetable.tTimeTableTime TTM where TTM.TimeTableSchemaId=T.TimeTableSchemaId AND TTM.DayId = DM.Id AND TTM.DivisionId = T.DivisionId AND TTM.LectureNumber = T.LectureNumber AND IsBreakBefore=1),'''') 
					--+ ISNULL(EM.ShortName +'+ ''' - ''' +'+SM.Code ,'''')
					+STUFF((
							 SELECT ''/'' + case When PS.Id IS NOT NULL THEN ISNULL(EM1.ShortName +'' - ''+SM1.Code+'' (Proxy Lecture) '','''') ELSE ISNULL(EM.ShortName +'' - ''+SM.Code,'''') END
								FROM sTimetable.tTimeTable T1 
								inner join sHrm.tEmployeeMaster EM on EM.Id=T1.EmployeeId
								INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=T1.SubjectId
								left join sTimetable.tProxySetting PS on PS.TimeTableId=t1.Id AND PS.TimeTableSchemaId=T1.TimeTableSchemaId And PS.ProxyDate<='''+ CAST(@rToDate AS NVARCHAR(30) )+''' AND PS.ProxyDate>='''+ CAST(@rFromDate AS NVARCHAR(30) )+'''
								Left join sHrm.tEmployeeMaster EM1 on EM1.Id=PS.EmployeeId
								Left JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=PS.SubjectId
								where T1.DivisionId=T.DivisionId 
								AND T.LectureNumber=T1.LectureNumber 
								AND T.DayId=T1.DayId and T.TimeTableSchemaId=T1.TimeTableSchemaId  
								--AND timetableid in ()
								FOR XML PATH('''')
							 ), 1, 1, '''')
					+ [sTimetable].[fTimeTableDetailGet](T.Id,1) + '' | ''
					+isnull((select top 1 ISNULL(TTM.FromTime,0)+''-''+ ISNULL(TTM.ToTime,0) from sTimetable.tTimeTableTime TTM where TTM.TimeTableSchemaId=T.TimeTableSchemaId AND TTM.DayId = DM.Id AND TTM.DivisionId = T.DivisionId AND TTM.LectureNumber = T.LectureNumber AND isnull(IsBreakBefore,0)=0 AND isnull(IsBreak,0)=0),''0-0'')+'' | ''
					+ISNULL((select top 1  Case WHEN TTM.IsBreak=1 Then ''Break''+''(''+ISNULL(TTM.FromTime,0)+''-''+ISNULL(TTM.ToTime,0)+'')''  ELSE '''' END from sTimetable.tTimeTableTime TTM where TTM.TimeTableSchemaId=T.TimeTableSchemaId AND TTM.DayId = DM.Id AND TTM.DivisionId = T.DivisionId AND TTM.LectureNumber = T.LectureNumber AND IsBreak=1),'''')  
					AS EmployeeName ,
					DM.Title AS DayNames
					,TTS.WeekOffs
					from
					sTimetable.tTimeTable T 
					INNER JOIN sTimetable.tTimeTableSchema TTS ON TTS.Id = T.TimeTableSchemaId AND TTS.IsPublish = 1
					INNER JOIN sCommon.tDayMaster DM ON DM.Id = T.DayId
					INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id=T.EmployeeId
					INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=T.SubjectId
					INNER JOIN sStudent.tAcademic A ON A.DivisionId=T.DivisionId
					 WHERE    
					((A.StudentId=' + CAST(@rStudentId AS NVARCHAR(30))+') OR('+ CAST(@rStudentId AS NVARCHAR(30))+'=0))
					AND  ((T.DivisionId=' + CAST(@rDivisionId AS NVARCHAR(30))+') OR ('+CAST(@rDivisionId AS NVARCHAR(30))+'= 0) )
					 AND ((T.TimeTableSchemaId=' + CAST(@rTimeTableSchemaId AS NVARCHAR(30))+') OR ('+CAST(@rTimeTableSchemaId AS NVARCHAR(30))+'= 0))
					) x
					pivot 
					(
						max(EmployeeName)
						for DayNames in (' + @cols + ')
					) p '
    END
 ELSE
	BEGIN
		set @query = 'SELECT LectureNumber , ' + @cols + ',WeekOffs from 
					 (
					Select T.LectureNumber, 
					Case WHEN ISNULL((select top 1 TTM.IsBreakBefore from sTimetable.tTimeTableTime TTM where TTM.TimeTableSchemaId=T.TimeTableSchemaId AND TTM.DayId = DM.Id AND TTM.DivisionId = T.DivisionId AND TTM.LectureNumber = T.LectureNumber AND IsBreakBefore=1),0) = 1 THEN ''Break Before | '' ELSE '''' END 
					--+ISNULL(EM.ShortName +'+ ''' - ''' +'+SM.Code ,'''') 
					+STUFF((
							SELECT ''/'' + case When PS.Id IS NOT NULL THEN ISNULL(EM1.ShortName +'' - ''+SM1.Code+''(Proxy Lecture)'','''') ELSE ISNULL(EM.ShortName +'' - ''+SM.Code,'''') END
								FROM sTimetable.tTimeTable T1 
								inner join sHrm.tEmployeeMaster EM on EM.Id=T1.EmployeeId
								INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=T1.SubjectId
								left join sTimetable.tProxySetting PS on PS.TimeTableId=t1.Id AND PS.TimeTableSchemaId=T1.TimeTableSchemaId And PS.ProxyDate<='''+ CAST(@rToDate AS NVARCHAR(30) )+''' AND PS.ProxyDate>='''+ CAST(@rFromDate AS NVARCHAR(30) )+'''
								Left join sHrm.tEmployeeMaster EM1 on EM1.Id=PS.EmployeeId
								Left JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=PS.SubjectId
								where T1.DivisionId=T.DivisionId 
								AND T.LectureNumber=T1.LectureNumber 
								AND T.DayId=T1.DayId and T.TimeTableSchemaId=T1.TimeTableSchemaId    
								--AND timetableid in ()
								FOR XML PATH('''')
							 ), 1, 1, '''')
					+ [sTimetable].[fTimeTableDetailGet](T.Id,1) + '' | ''
					+ Case WHEN ISNULL((select top 1 TTM.IsBreak from sTimetable.tTimeTableTime TTM where TTM.TimeTableSchemaId=T.TimeTableSchemaId AND TTM.DayId = DM.Id AND TTM.DivisionId = T.DivisionId AND TTM.LectureNumber = T.LectureNumber AND IsBreak=1),0) = 1 THEN ''Break'' ELSE '''' END 
					AS EmployeeName ,
					DM.Title AS DayNames
					,TTS.WeekOffs
					from
					sTimetable.tTimeTable T 
					INNER JOIN sTimetable.tTimeTableSchema TTS ON TTS.Id = T.TimeTableSchemaId AND TTS.IsPublish = 1
					INNER JOIN sCommon.tDayMaster DM ON DM.Id = T.DayId
					INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id=T.EmployeeId
					INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=T.SubjectId
					INNER JOIN sStudent.tAcademic A ON A.DivisionId=T.DivisionId
					LEFT JOIN sTimetable.tTimeTableTime TTM ON TTM.TimeTableSchemaId=T.TimeTableSchemaId AND TTM.DayId = DM.Id AND TTM.DivisionId = T.DivisionId AND TTM.LectureNumber = T.LectureNumber
					 WHERE    
					((A.StudentId=' + CAST(@rStudentId AS NVARCHAR(30))+') OR('+ CAST(@rStudentId AS NVARCHAR(30))+'=0))
					AND  ((T.DivisionId=' + CAST(@rDivisionId AS NVARCHAR(30))+') OR ('+CAST(@rDivisionId AS NVARCHAR(30))+'= 0) )
					 AND ((T.TimeTableSchemaId=' + CAST(@rTimeTableSchemaId AS NVARCHAR(30))+') OR ('+CAST(@rTimeTableSchemaId AS NVARCHAR(30))+'= 0))
	       
					) x
					pivot 
					(
						max(EmployeeName)
						for DayNames in (' + @cols + ')
					) p '
	END
		--print @query
		execute(@query)
END
GO
PRINT N'Altering [sTimetable].[pTeacherTimeTableGet]...';


GO

 
 
ALTER PROCEDURE [sTimetable].[pTeacherTimeTableGet]
	
	 @rEmployeeId bigint,
	 @rBatchId int=0,
	 @rTimeTableSchemaId int,
	 @rFromDate Date='',
	 @rToDate Date=''
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

	DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX),@query1  AS NVARCHAR(MAX),@query2  AS NVARCHAR(MAX),@query3 AS NVARCHAR(MAX)
	if(@rFromDate is null)
	BEGIN
		set @rFromDate=''
	END
	if(@rToDate is null)
	BEGIN
		set @rToDate=''
	END

select @cols = STUFF((SELECT ',' + QUOTENAME(Title) 
                    from sCommon.tDayMaster
                    order by Id,Title 
                    
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')
        
IF EXISTS(SELECT 1 FROM sTimetable.tTimeTableSchema TS INNER JOIN sTimetable.tTimeTable TT ON TT.TimeTableSchemaId = TS.Id WHERE TS.IsDisplayPeriodTime = 1 AND TS.Id = @rTimeTableSchemaId)
 BEGIN 
set @query = 'SELECT  LectureNumber,' + @cols + ',WeekOffs from 
             (
                Select T.LectureNumber, 
				ISNULL((select top 1  CASE WHEN TTM.IsBreakBefore=1 then ''Break Before''+ ''(''+ISNULL(TTM.FromTime,0)+''-''+ISNULL(TTM.ToTime,0)+''); | ''  ELSE '''' end  from sTimetable.tTimeTableTime TTM where TTM.TimeTableSchemaId=T.TimeTableSchemaId AND TTM.DayId = DM.Id AND TTM.DivisionId = T.DivisionId AND TTM.LectureNumber = T.LectureNumber AND IsBreakBefore=1),'''') 
				--+CASE WHEN ISNULL(TTM.IsBreakBefore,0) = 1 THEN ''Break Before | '' ELSE '''' END 
				--+ ISNULL(VBCD.ClassDivisionName + '' - ''+  SM.Code  + 
				+ Isnull(STUFF((
						SELECT ''/'' +  ISNULL(VBCD.ClassDivisionName +'' - ''+SM.Code,'''') 
								FROM sTimetable.tTimeTable T1 
								INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=T1.SubjectId
								 INNER JOIN sSetup.vClassDivision VBCD ON VBCD.DivisionId=T1.DivisionId
								where T1.EmployeeId=' + CAST(@rEmployeeId AS NVARCHAR(30))+'
								AND T.LectureNumber=T1.LectureNumber 
								AND T.DayId=T1.DayId and T.TimeTableSchemaId=T1.TimeTableSchemaId  
								--AND timetableid in ()
								FOR XML PATH('''')
							 ), 1, 1, ''''),'''')
				+Isnull(STUFF((
						SELECT ''/'' + ISNULL(VBCD.ClassDivisionName +'' - ''+SM.Code+'' (Proxy Lecture) '','''')
								FROM sTimetable.tProxySetting PS1
								Inner join sSetup.vClassDivision VBCD  ON VBCD.DivisionId=PS1.DivisionId
								Inner JOIN sSetup.tSubjectMaster SM ON SM.Id=PS1.SubjectId
								where Ps.Id=PS1.Id
								AND PS1.EmployeeId=' + CAST(@rEmployeeId AS NVARCHAR(30))+'
								FOR XML PATH('''')
							 ), 1, 1, ''''),'''')
							 
				+ [sTimetable].[fTimeTableDivisionGet](T.TimeTableSchemaId, T.Id,T.EmployeeId,T.DayId,T.LectureNumber,1) + '' | '' 
				--+''|''+ ISNULL(TTM.FromTime,0) + ''-''+ ISNULL(TTM.ToTime,0) ,'''') 
				+isnull((select top 1 ISNULL(TTM.FromTime,0)+''-''+ ISNULL(TTM.ToTime,0) from sTimetable.tTimeTableTime TTM where TTM.TimeTableSchemaId=T.TimeTableSchemaId AND TTM.DayId = DM.Id AND TTM.DivisionId = T.DivisionId AND TTM.LectureNumber = T.LectureNumber AND isnull(IsBreakBefore,0)=0 AND isnull(IsBreak,0)=0),''0-0'')+'' | ''
				+ISNULL((select top 1  Case WHEN TTM.IsBreak=1 Then ''Break''+''(''+ISNULL(TTM.FromTime,0)+''-''+ISNULL(TTM.ToTime,0)+'')''  ELSE '''' END from sTimetable.tTimeTableTime TTM where TTM.TimeTableSchemaId=T.TimeTableSchemaId AND TTM.DayId = DM.Id AND TTM.DivisionId = T.DivisionId AND TTM.LectureNumber = T.LectureNumber AND IsBreak=1),'''')  
				AS DivisionTitle,
				DM.Title AS DayNames
				,TTS.WeekOffs
            from
            sTimetable.tTimeTable T 
            LEFT JOIN sTimetable.tTimeTableDetail TD ON T.Id = TD.TimeTableId 
            INNER JOIN sTimetable.tTimeTableSchema TTS ON TTS.Id = T.TimeTableSchemaId
            INNER JOIN sCommon.tDayMaster DM ON DM.Id = T.DayId
            --INNER JOIN sSetup.vClassDivision VBCD ON VBCD.DivisionId=T.DivisionId
	        --INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=T.SubjectId
	        LEFT JOIN sSetup.tSubjectMaster TDSM ON TDSM.Id=TD.SubjectId
			left join sTimetable.tProxySetting PS on PS.TimeTableId=T.Id AND PS.TimeTableSchemaId=T.TimeTableSchemaId And PS.ProxyDate<='''+ CAST(@rToDate AS NVARCHAR(30) )+''' AND PS.ProxyDate>='''+ CAST(@rFromDate AS NVARCHAR(30) )+'''
			--LEFT JOIN sTimetable.tTimeTableTime TTM ON TTM.TimeTableSchemaId=T.TimeTableSchemaId AND TTM.DayId = DM.Id AND TTM.DivisionId = VBCD.DivisionId AND TTM.LectureNumber = T.LectureNumber
	         WHERE 
	        ((T.EmployeeId=' + CAST(@rEmployeeId AS NVARCHAR(30))+') OR (TD.EmployeeId=' + CAST(@rEmployeeId AS NVARCHAR(30))+') OR ('+CAST(@rEmployeeId AS NVARCHAR(30))+'= 0) OR  (PS.EmployeeId=' + CAST(@rEmployeeId AS NVARCHAR(30))+'))
	         
	         AND ((T.TimeTableSchemaId=' + CAST(@rTimeTableSchemaId AS NVARCHAR(30))+') )
            ) x
            pivot 
            (
                max(DivisionTitle)
                for DayNames in (' + @cols + ')
            ) p order by LectureNumber'
	END 
	ELSE
	BEGIN
set @query = 'SELECT  LectureNumber,' + @cols + ',WeekOffs from 
             (
                Select T.LectureNumber, 
				Case WHEN ISNULL((select top 1 TTM.IsBreakBefore from sTimetable.tTimeTableTime TTM where TTM.TimeTableSchemaId=T.TimeTableSchemaId AND TTM.DayId = DM.Id AND TTM.DivisionId = T.DivisionId AND TTM.LectureNumber = T.LectureNumber AND IsBreakBefore=1),0) = 1 THEN ''Break Before | '' ELSE '''' END 
				--+ISNULL(VBCD.ClassDivisionName + '' - ''+ SM.Code ,'''') 
				+ISNULL(STUFF((
						SELECT ''/'' +  ISNULL(VBCD.ClassDivisionName +'' - ''+SM.Code,'''') 
								FROM sTimetable.tTimeTable T1 
								INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=T1.SubjectId
								 INNER JOIN sSetup.vClassDivision VBCD ON VBCD.DivisionId=T1.DivisionId
								where T1.EmployeeId=' + CAST(@rEmployeeId AS NVARCHAR(30))+' 
								AND T.LectureNumber=T1.LectureNumber 
								AND T.DayId=T1.DayId and T.TimeTableSchemaId=T1.TimeTableSchemaId  
								--AND timetableid in ()
								FOR XML PATH('''')
							 ), 1, 1, ''''),'''')
				+Isnull(STUFF((
						SELECT ''/'' + ISNULL(VBCD.ClassDivisionName +'' - ''+SM.Code+'' (Proxy Lecture) '','''')
								FROM sTimetable.tProxySetting PS1
								Inner join sSetup.vClassDivision VBCD  ON VBCD.DivisionId=PS1.DivisionId
								Inner JOIN sSetup.tSubjectMaster SM ON SM.Id=PS1.SubjectId
								where Ps.Id=PS1.Id
								FOR XML PATH('''')
							 ), 1, 1, ''''),'''')
				+ [sTimetable].[fTimeTableDivisionGet](T.TimeTableSchemaId, T.Id,T.EmployeeId,T.DayId,T.LectureNumber,1) + '' | '' 
				--+ CASE WHEN ISNULL(TTM.IsBreak,0) = 1 THEN ''Break'' ELSE '''' END 
				+ Case WHEN ISNULL((select top 1 TTM.IsBreak from sTimetable.tTimeTableTime TTM where TTM.TimeTableSchemaId=T.TimeTableSchemaId AND TTM.DayId = DM.Id AND TTM.DivisionId = T.DivisionId AND TTM.LectureNumber = T.LectureNumber AND IsBreak=1),0) = 1 THEN ''Break'' ELSE '''' END 
					AS DivisionTitle
				,DM.Title AS DayNames
				,TTS.WeekOffs
			from
            sTimetable.tTimeTable T 
            LEFT JOIN sTimetable.tTimeTableDetail TD ON T.Id = TD.TimeTableId 
            INNER JOIN sTimetable.tTimeTableSchema TTS ON TTS.Id = T.TimeTableSchemaId AND TTS.IsPublish = 1
            INNER JOIN sCommon.tDayMaster DM ON DM.Id = T.DayId
            --INNER JOIN sSetup.vClassDivision VBCD ON VBCD.DivisionId=T.DivisionId
	        --INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=T.SubjectId
	        LEFT JOIN sSetup.tSubjectMaster TDSM ON TDSM.Id=TD.SubjectId
			left join sTimetable.tProxySetting PS on PS.TimeTableId=T.Id AND PS.TimeTableSchemaId=T.TimeTableSchemaId And PS.ProxyDate<='''+ CAST(@rToDate AS NVARCHAR(30) )+''' AND PS.ProxyDate>='''+ CAST(@rFromDate AS NVARCHAR(30) )+'''
			--LEFT JOIN sTimetable.tTimeTableTime TTM ON TTM.TimeTableSchemaId=T.TimeTableSchemaId AND TTM.DayId = DM.Id AND TTM.DivisionId = VBCD.DivisionId AND TTM.LectureNumber = T.LectureNumber
	         WHERE 
	        ((T.EmployeeId=' + CAST(@rEmployeeId AS NVARCHAR(30))+') OR (TD.EmployeeId=' + CAST(@rEmployeeId AS NVARCHAR(30))+') OR ('+CAST(@rEmployeeId AS NVARCHAR(30))+'= 0) OR  (PS.EmployeeId=' + CAST(@rEmployeeId AS NVARCHAR(30))+'))
	         
	         AND ((T.TimeTableSchemaId=' + CAST(@rTimeTableSchemaId AS NVARCHAR(30))+') )
            ) x
            pivot 
            (
                max(DivisionTitle)
                for DayNames in (' + @cols + ')
            ) p order by LectureNumber'
	END
--print @query
 execute(@query)
END
GO
PRINT N'Altering [sTimetable].[pTimeTableAdd]...';


GO

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

	 
 
BEGIN 

	 BEGIN TRY	
	 BEGIN TRANSACTION 
	   print 'a'
	IF NOT EXISTS(Select 1 FROM sTimetable.tTimeTable Where EmployeeId = @rEmployeeId  AND LectureNumber = @rLectureNumber AND DayId = @rDayId and TimeTableSchemaId=@rTimeTableSchemaId AND DivisionId=@rDivisionId)
	 
	BEGIN
	IF NOT EXISTS(Select 1 FROM sTimetable.tTimeTable Where  SubjectId=@rSubjectId  AND LectureNumber = @rLectureNumber AND DayId = @rDayId and TimeTableSchemaId=@rTimeTableSchemaId AND DivisionId=@rDivisionId)
	BEGIN
	DECLARE @lNextNumber BIGINT
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sTimetable.tTimeTable', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	 
	  BEGIN
		   INSERT INTO sTimetable.tTimeTable		 
		   (
				[Id]
			   ,[TimeTableSchemaId]
			   ,[EmployeeId]
			   ,[DivisionId]
			   ,[SubjectId]
			   ,[DayId]
			   ,[LectureNumber]
			   ,[LockNo]
			   ,[LockColour]
            )		 
			VALUES
			(	
				@lNextNumber,
				@rTimeTableSchemaID,
				@rEmployeeId,
				@rDivisionId,
				@rSubjectId,
				@rDayId,
				@rLectureNumber,
				@rLockNo,
				@rLockColour
			)		
			SELECT @lNextNumber AS Result
    	END
      END
	  ELSE
	  BEGIN       
		  SELECT -102 AS Result
		END
	  END
    ELSE
    BEGIN       
      SELECT -101 AS Result
    END
	
	COMMIT TRANSACTION
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
	
	
END 	             
	
		
END
GO
PRINT N'Altering [sTimetable].[pTimeTableDataRemove]...';


GO
 
ALTER PROCEDURE [sTimetable].[pTimeTableDataRemove]
	   
	  @rSubjectId int,
	  @rEmployeeId bigint,
	  @rDivisionId int,
	  @rDayId smallint,
	  @rLectureNumber smallint, 
	  @rTimeTableSchemaId int
	  
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN  

	 BEGIN TRY	
	 BEGIN TRANSACTION 
	 If Not Exists(select 1 From sTimetable.tTimeTable TT Inner Join sTimetable.tProxySetting PS  ON TT.TimeTableSchemaId=PS.TimeTableSchemaId AND TT.Id=PS.TimeTableId WHERE TT.EmployeeId = @rEmployeeId AND TT.DivisionId = @rDivisionId AND TT.DayId = @rDayId
	 AND TT.LectureNumber = @rLectureNumber AND TT.SubjectId = @rSubjectId AND TT.TimeTableSchemaId = @rTimeTableSchemaId )
	 BEGIN
	 DELETE FROM sTimetable.tTimeTable 
	 WHERE EmployeeId = @rEmployeeId 
	 AND DivisionId = @rDivisionId AND DayId = @rDayId
	 AND LectureNumber = @rLectureNumber AND SubjectId = @rSubjectId 
	 AND TimeTableSchemaId = @rTimeTableSchemaId
	 
	 	SELECT 1 AS Result
	 END
	 ELSE
	 BEGIN
		SELECT -101 AS Result
	 END
	COMMIT TRANSACTION
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH		
END
GO
PRINT N'Altering [sWorkflow].[pBonafideApprovalStatusGet]...';


GO

ALTER PROCEDURE [sWorkflow].[pBonafideApprovalStatusGet]
			 @rCode nvarchar(50) =0,
			 @rStatusId int=0,
			 @rParticipantSourceId bigint = 0,
			 @rApprovingDepartmentId int

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
			SELECT 

			ADM.Title AS DepartmentTitle,
			CASE WHEN ParticipantSourceTypeId= 2001 THEN SA.Code WHEN ParticipantSourceTypeId= 95 THEN EM.Code END AS Code ,
			CASE WHEN ParticipantSourceTypeId= 2001 THEN SA.Name WHEN ParticipantSourceTypeId= 95 THEN EM.FirstName +' '+ EM.MiddleName +' ' +EM.LastName END AS Name ,
			AR.CreatedDateTime AS CreatedDateTime,
			(CASE ISNULL(asm.Id,'') WHEN '' THEN 3 ELSE asm.Id END) AS statusId,
			(CASE ISNULL(asm.title,'') WHEN '' THEN 'Pending' ELSE asm.title END) AS status
			--(select Title from sWorkflow.tActionStatusMaster WHERE Id=3) AS Status 
			--CASE WHEN @rStatusId= 0 THEN (select Top 1 Title from sWorkflow.tActionStatusMaster WHERE Id=3) WHEN ASM.Id = @rStatusId THEN ASM.Title  END AS Status
		FROM sWorkflow.tApprovalRequest AR
			INNER JOIN sWorkflow.tFunctionalityApprovingDepartment FAD  ON AR.WorkflowFunctionalityId = FAD.WorkflowFunctionalityId 
			INNER JOIN sWorkflow.tApprovingDepartmentMaster ADM ON FAD.ApprovingDepartmentId = ADM.Id
			INNER JOIN sWorkflow.tFunctionalityApprovingAuthority FAA ON ADM.Id = FAA.FunctionalityApprovingDepartmentId
			LEFT JOIN sSecurity.tRole R ON R.Id = FAA.AuthoritySourceId AND FAA.AuthoritySourceTypeId = 2015
			LEFT JOIN sWorkflow.tApprovalAction AA ON AA.ApprovalRequestId = AR.Id AND AA.ApprovingDepartmentId = ADM.ID AND AA.ApprovingDepartmentId = @rApprovingDepartmentId
			AND ADM.Id = @rApprovingDepartmentId
			LEFT JOIN sWorkflow.tActionStatusMaster ASM ON ASM.Id = AA.ActionStatusId AND((ASM.Id = @rStatusId) OR (@rStatusId =0))
			INNER JOIN sWorkflow.tWorkflowFunctionalityMaster WFM ON AR.WorkflowFunctionalityId = WFM.Id
			LEFT JOIN  sStudent.vStudentAcademic  SA ON SA.AcademicId = AR.ParticipantSourceId
			LEFT JOIN  sHrm.tEmployeeMaster  EM ON EM.Id = AR.ParticipantSourceId AND ISNULL(EM.IsOtherUser,0) = 0
		WHERE  (((SA.Code = @rCode) OR (@rCode ='')) OR ((EM.Code = @rCode) OR (@rCode =0)))
		 
		AND ((AR.ParticipantSourceId = @rParticipantSourceId) OR (@rParticipantSourceId = 0))
		AND FAD.ApprovingDepartmentId = @rApprovingDepartmentId

		UNION 

		SELECT 

			ADM.Title AS DepartmentTitle,
			CASE WHEN ParticipantSourceTypeId= 2001 THEN SA.Code WHEN ParticipantSourceTypeId= 95 THEN EM.Code END AS Code ,
			CASE WHEN ParticipantSourceTypeId= 2001 THEN SA.Name WHEN ParticipantSourceTypeId= 95 THEN EM.FirstName +' '+ EM.MiddleName +' ' +EM.LastName END AS Name ,
			AR.CreatedDateTime AS CreatedDateTime,
			(CASE ISNULL(asm.Id,'') WHEN '' THEN 3 ELSE asm.Id END) AS statusId,
			(CASE ISNULL(asm.title,'') WHEN '' THEN 'Pending' ELSE asm.title END) AS status
			--(select Title from sWorkflow.tActionStatusMaster WHERE Id=3) AS Status 
			--CASE WHEN @rStatusId= 0 THEN (select Top 1 Title from sWorkflow.tActionStatusMaster WHERE Id=3) WHEN ASM.Id = @rStatusId THEN ASM.Title  END AS Status
		FROM sWorkflow.tApprovalRequest AR
			INNER JOIN sWorkflow.tFunctionalityApprovingDepartment FAD  ON AR.WorkflowFunctionalityId = FAD.WorkflowFunctionalityId 
			INNER JOIN sWorkflow.tApprovingDepartmentMaster ADM ON FAD.ApprovingDepartmentId = ADM.Id
			INNER JOIN sWorkflow.tFunctionalityApprovingAuthority FAA ON ADM.Id = FAA.FunctionalityApprovingDepartmentId
			LEFT JOIN sSecurity.tUser U ON U.Id = FAA.AuthoritySourceId AND FAA.AuthoritySourceTypeId = 1019
			LEFT JOIN sWorkflow.tApprovalAction AA ON AA.ApprovalRequestId = AR.Id AND AA.ApprovingDepartmentId = ADM.ID  AND AA.ApprovingDepartmentId = @rApprovingDepartmentId
			AND ADM.Id = @rApprovingDepartmentId
			LEFT JOIN sWorkflow.tActionStatusMaster ASM ON ASM.Id = AA.ActionStatusId AND((ASM.Id = @rStatusId) OR (@rStatusId =0)) 
			INNER JOIN sWorkflow.tWorkflowFunctionalityMaster WFM ON AR.WorkflowFunctionalityId = WFM.Id
			LEFT JOIN  sStudent.vStudentAcademic  SA ON SA.AcademicId = AR.ParticipantSourceId
			LEFT JOIN  sHrm.tEmployeeMaster  EM ON EM.Id = AR.ParticipantSourceId AND ISNULL(EM.IsOtherUser,0) = 0

		WHERE  (((SA.Code = @rCode) OR (@rCode ='')) OR ((EM.Code = @rCode) OR (@rCode =0)))
		
		AND ((AR.ParticipantSourceId = @rParticipantSourceId) OR (@rParticipantSourceId = 0))
		AND FAD.ApprovingDepartmentId = @rApprovingDepartmentId
	END
GO
PRINT N'Creating [sAttendance].[pRptMonthlyAttendanceStudentwise]...';


GO

 
 
CREATE PROCEDURE [sAttendance].[pRptMonthlyAttendanceStudentwise]

	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='', 
	@rDepartmentId int,
	@rClassId int,
	@rDivisionId int,
	@rAttendanceTagId int,
	--@rFromDate date,
	@rUpToDate date,
	@rBatchId int,
	@rOrgId int	 ,
	@rAdmissionCategoryId int
	 	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	DECLARE @lAttendanceDate nvarchar(MAX)
	SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		
		SA.AcademicId,
		ISNULL(SA.RollNo,0) as RollNo,
		SA.Name,
		SA.Code,
		CM.ID AS ClassId,
		CM.Title AS Class,
		CM.OrderIndex AS ClassOrderIndex,
		DM.Id AS DivisionId,
		DM.Title AS Division,
		SA.DepartmentName As Department,
		DM.OrderIndex AS DivisionOrderIndex,
		SA.ClassName + '-'+ SA.DivisionName AS ClassDivision,
		ISNULL(AR.AttendanceTagCount,0) AS AttendanceTagCount,

		ISNULL((SELECT COUNT(SR.AcademicId)
						FROM sStudent.vStudentAcademic SA1 
							INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA1.AcademicId And SR.AcademicId=SA.AcademicId
							INNER JOIN sSetup.tClassMaster CM ON CM.Id = SA.ClassId	 
							 AND SR.AttendanceDate <= @rUpToDate WHERE SR.IsPresent=1 AND ((SA.OrgId=@rOrgId)OR(@rOrgId=0))
							 AND ((CM.Id =@rClassId)OR(@rClassId=0))
							AND((CM.DepartmentId = @rDepartmentId)OR(@rDepartmentId=0))),0) AS TotalPresentDays ,
		ISNULL((SELECT COUNT(SR.AcademicId)
						FROM sStudent.vStudentAcademic SA1 
							INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA1.AcademicId And SR.AcademicId=SA.AcademicId
							INNER JOIN sSetup.tClassMaster CM ON CM.Id = SA.ClassId	 
							 AND SR.AttendanceDate <= @rUpToDate WHERE ((SA.OrgId=@rOrgId)OR(@rOrgId=0))
							 AND ((CM.Id =@rClassId)OR(@rClassId=0))
							AND((CM.DepartmentId = @rDepartmentId)OR(@rDepartmentId=0))),0) AS TotalWorkingDays ,				
       -- ISNULL(MS.WorkingDays,0) As TotalWorkingDays ,

		STUFF(
         (SELECT DISTINCT  ', ' + CONVERT(NVARCHAR(MAX),SR.AttendanceDate,105)
           FROM
				sStudent.vStudentAcademic A INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.AcademicId  
			WHERE 
				 A.AcademicId = SA.AcademicId
				--AND (SR.AttendanceDate >= @rFromDate  AND SR.AttendanceDate <= @rToDate)
				AND (SR.AttendanceDate <= @rUpToDate)
				--AND SR.AttendanceTagId>0
				AND ((SR.AttendanceTagId =@rAttendanceTagId) OR (@rAttendanceTagId=0))
				AND ((SA.AdmissionCategoryId =@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
			GROUP BY SR.AcademicId,AttendanceDate
          FOR XML PATH (''))
          , 1, 1, '')  AS UptoDate 
		 
	FROM 
		sStudent.vStudentAcademic SA 
		INNER JOIN sStudent.tStudentAdmission AD ON SA.StudentId = AD.StudentId
		INNER JOIN sSetup.tClassMaster CM ON CM.Id = SA.ClassId
		INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = SA.DivisionId
		
		--Inner JOIN sAttendance.tMonthlySetup MS on MS.ClassId = SA.ClassId And MS.BatchId = SA.BatchId
		--INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.AcademicId
		       
		LEFT JOIN
		(
			SELECT 
				SR.AcademicId,COUNT(SR.AttendanceTagId) AS AttendanceTagCount 
			FROM 
				sStudent.vStudentAcademic A
				INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.AcademicId 
				INNER JOIN sStudent.tStudentAdmission SA  ON SA.StudentId = A.StudentId
			WHERE 
				((A.ClassId=@rClassId) OR (@rClassId=0))
				AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
				AND ((A.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
				AND (A.OrgId = @rOrgId)
				AND (A.BatchId = @rBatchID)
				--AND (SR.AttendanceDate >= @rFromDate  AND SR.AttendanceDate <= @rToDate)
				AND (SR.AttendanceDate <= @rUpToDate)
				AND A.StatusId=1
				--AND SR.AttendanceTagId>0
				AND ((SR.AttendanceTagId =@rAttendanceTagId) OR (@rAttendanceTagId=0))
				AND ((A.AdmissionCategoryId =@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
			GROUP BY SR.AcademicId
		) AR ON AR.AcademicId = SA.AcademicId
		
	WHERE 
		(SA.OrgId = @rOrgId)
		AND (SA.BatchId = @rBatchId)
		AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		--AND (AD.LeftDate > @rFromDate OR ISNULL(AD.LeftDate,'')= '')
		--AND (AD.AdmissionDate <= @rFromDate)
		AND SA.StatusId=1
END
GO
PRINT N'Creating [sCommunication].[pMyAdmitCardGet]...';


GO

CREATE PROCEDURE [sCommunication].[pMyAdmitCardGet]
	 
	 --@rSourceTypeId smallint,
	 @rSourceId bigint,
	 @rDivisionId int,
	 @rBatchId int,
	 @rSyncedUploadResultId int=0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	IF (@rSourceId!=0)
	BEGIN
		SELECT @rDivisionId=DivisionId FROM sStudent.tAcademic		
		 WHERE StudentId=@rSourceId AND BatchId = @rBatchId
	END
		SELECT 
			@rSourceId AS SourceId,
			UR.Id,
			UR.Title,
			UR.ExamDate,
			S.Code ,
			BM.OrgId
			 
		FROM 
			sCommunication.tUploadResult UR  
			INNER JOIN sStudent.vStudentAcademic S ON S.DivisionId = UR.DivisionId AND UR.BatchId = S.BatchId 
			AND S.StudentId = @rSourceId AND S.BatchId = @rBatchId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = S.BatchId
		WHERE 
			UR.DivisionId=@rDivisionId
			AND UR.BatchId=@rBatchId
			AND UR.IsObsolete=0
			AND ( UR.Id > @rSyncedUploadResultId OR @rSyncedUploadResultId = 0)
			and UR.ExamDate <= replace(convert(varchar, sCommon.fGetDate(), 111), '/','-') 
			AND ISNULL(UR.UploadTypeId,1) = 2
				order by UR.ExamDate,S.RollNo,S.Code DESC
END
GO

  


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