
GO
PRINT N'Dropping FK_sAssessment_tResult_AcademicId...';


GO
ALTER TABLE [sAssessment].[tResult] DROP CONSTRAINT [FK_sAssessment_tResult_AcademicId];


GO
PRINT N'Dropping FK_sAssessment_tResult_ExamId...';


GO
ALTER TABLE [sAssessment].[tResult] DROP CONSTRAINT [FK_sAssessment_tResult_ExamId];


GO
PRINT N'Dropping FK_sAssessment_tResultDetail_ResultId...';


GO
ALTER TABLE [sAssessment].[tResultDetail] DROP CONSTRAINT [FK_sAssessment_tResultDetail_ResultId];


GO
PRINT N'Creating [sErp]...';


GO
CREATE SCHEMA [sErp]
    AUTHORIZATION [dbo];


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


GO
ALTER TABLE [sAssessment].[tCCEExamSetting]
    ADD [CSGradeSetId] INT NULL;


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


GO
ALTER TABLE [sAssessment].[tCCEResultDetail]
    ADD [Term1TotalGradePoint] DECIMAL (6) NULL,
        [Term2TotalGradePoint] DECIMAL (6) NULL;


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


GO
ALTER TABLE [sAssessment].[tExamMaster]
    ADD [IsDisplayResultIndicator] BIT NULL;


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


GO
ALTER TABLE [sAssessment].[tGradeSetMaster]
    ADD [GradeStringHtml] NVARCHAR (500) NULL,
        [GradeStringText] NVARCHAR (500) NULL;


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


GO
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;

SET XACT_ABORT ON;

BEGIN TRANSACTION;

CREATE TABLE [sAssessment].[tmp_ms_xx_tResult] (
    [Id]               BIGINT         NOT NULL,
    [AcademicId]       BIGINT         NOT NULL,
    [ExamId]           INT            NOT NULL,
    [TotalMarks]       DECIMAL (8, 2) NOT NULL,
    [TotalObtain]      DECIMAL (8, 2) NOT NULL,
    [ResultStatus]     NVARCHAR (50)  NOT NULL,
    [ResultGrade]      NVARCHAR (10)  NOT NULL,
    [ResultIndicator]  NVARCHAR (50)  NULL,
    [ResultGradePoint] DECIMAL (6, 2) NOT NULL,
    [RankNumber]       INT            NOT NULL,
    [Percentage]       DECIMAL (5, 2) NOT NULL,
    [Percentile]       DECIMAL (5, 2) NOT NULL,
    [ResultRemark]     NVARCHAR (200) NOT NULL,
    [OtherRemark1]     NVARCHAR (200) NOT NULL,
    [UpdatedUserId]    BIGINT         NOT NULL,
    [UpdatedDateTime]  DATETIME       NOT NULL
);

ALTER TABLE [sAssessment].[tmp_ms_xx_tResult]
    ADD CONSTRAINT [tmp_ms_xx_clusteredindex_PK_tResult] 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   [sAssessment].[tResult])
    BEGIN
        INSERT INTO [sAssessment].[tmp_ms_xx_tResult] ([Id], [AcademicId], [ExamId], [TotalMarks], [TotalObtain], [ResultStatus], [ResultGrade], [ResultGradePoint], [RankNumber], [Percentage], [Percentile], [ResultRemark], [OtherRemark1], [UpdatedUserId], [UpdatedDateTime])
        SELECT   [Id],
                 [AcademicId],
                 [ExamId],
                 [TotalMarks],
                 [TotalObtain],
                 [ResultStatus],
                 [ResultGrade],
                 [ResultGradePoint],
                 [RankNumber],
                 [Percentage],
                 [Percentile],
                 [ResultRemark],
                 [OtherRemark1],
                 [UpdatedUserId],
                 [UpdatedDateTime]
        FROM     [sAssessment].[tResult]
        ORDER BY [Id] ASC;
    END

DROP TABLE [sAssessment].[tResult];

EXECUTE sp_rename N'[sAssessment].[tmp_ms_xx_tResult]', N'tResult';

EXECUTE sp_rename N'[sAssessment].[tmp_ms_xx_clusteredindex_PK_tResult]', N'PK_tResult', N'OBJECT';

COMMIT TRANSACTION;

SET TRANSACTION ISOLATION LEVEL READ COMMITTED;


GO
PRINT N'Creating UK_tResult...';


GO
ALTER TABLE [sAssessment].[tResult]
    ADD CONSTRAINT [UK_tResult] UNIQUE NONCLUSTERED ([AcademicId] ASC, [ExamId] ASC) WITH (ALLOW_PAGE_LOCKS = ON, ALLOW_ROW_LOCKS = ON, PAD_INDEX = OFF, IGNORE_DUP_KEY = OFF, STATISTICS_NORECOMPUTE = OFF) ON [PRIMARY];


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


GO
ALTER TABLE [sAssessment].[tStudentRemark]
    ADD [MyActivity]         NVARCHAR (200) NULL,
        [ClassTeacherRemark] NVARCHAR (200) NULL,
        [HouseRemark]        NVARCHAR (200) NULL,
        [ResultRemark3]      NVARCHAR (200) NULL,
        [GeneralRemark]      NVARCHAR (200) NULL;


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


GO
ALTER TABLE [sAssessment].[tTempAllExam]
    ADD [GraceMark]       DECIMAL (5, 2) NULL,
        [GradeStringHtml] NVARCHAR (500) NULL;


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


GO
ALTER TABLE [sCertificate].[tCharacter]
    ADD [Remark] NVARCHAR (200) NULL;


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


GO
ALTER TABLE [sCertificate].[tFirstTrial]
    ADD [Remark] NVARCHAR (200) NULL;


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


GO
ALTER TABLE [sCertificate].[tLeaving]
    ADD [LastExamName]              NVARCHAR (200) NULL,
        [LastExamResult]            NVARCHAR (200) NULL,
        [RepeatDetail]              NVARCHAR (100) NULL,
        [SubjectStudied]            NVARCHAR (300) NULL,
        [PromoteToClass]            NVARCHAR (50)  NULL,
        [FeeDetail]                 NVARCHAR (100) NULL,
        [FeeConcessionDetail]       NVARCHAR (100) NULL,
        [ExtraCurricularActivities] NVARCHAR (200) NULL,
        [NCCScoutDetail]            NVARCHAR (200) NULL;


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


GO
ALTER TABLE [sCertificate].[tPrintTemplate]
    ADD [TemplateSourceId] TINYINT NULL;


GO
PRINT N'Altering [sConfig].[tDatabaseSetting]...';


GO
ALTER TABLE [sConfig].[tDatabaseSetting]
    ADD [BackupDateTime] DATE NULL;


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


GO
ALTER TABLE [sFee].[tCollectionGroupMaster]
    ADD [ReportId]       INT NULL,
        [IsOnPrePrinted] BIT NULL;


GO
PRINT N'Starting rebuilding table [sHostel].[tHostelDepositRefund]...';


GO
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;

SET XACT_ABORT ON;

BEGIN TRANSACTION;

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

IF EXISTS (SELECT TOP 1 1
           FROM   [sHostel].[tHostelDepositRefund])
    BEGIN
        INSERT INTO [sHostel].[tmp_ms_xx_tHostelDepositRefund] ([HostelDepositHeadId], [StudentId], [RefundAmount], [RefundDate], [PayTypeId], [ChequeNo], [BankName], [Remark], [CreatedUserId], [CreatedDateTime], [UpdatedUserId], [UpdatedDateTime], [HostelId])
        SELECT [HostelDepositHeadId],
               [StudentId],
               [RefundAmount],
               [RefundDate],
               [PayTypeId],
               [ChequeNo],
               [BankName],
               [Remark],
               [CreatedUserId],
               [CreatedDateTime],
               [UpdatedUserId],
               [UpdatedDateTime],
               [HostelId]
        FROM   [sHostel].[tHostelDepositRefund];
    END

DROP TABLE [sHostel].[tHostelDepositRefund];

EXECUTE sp_rename N'[sHostel].[tmp_ms_xx_tHostelDepositRefund]', N'tHostelDepositRefund';

COMMIT TRANSACTION;

SET TRANSACTION ISOLATION LEVEL READ COMMITTED;


GO
PRINT N'Starting rebuilding table [sHostel].[tHostelMaster]...';


GO
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;

SET XACT_ABORT ON;

BEGIN TRANSACTION;

CREATE TABLE [sHostel].[tmp_ms_xx_tHostelMaster] (
    [OrgGroupId]      SMALLINT       NOT NULL,
    [Id]              INT            NOT NULL,
    [Title]           NVARCHAR (100) NOT NULL,
    [Remark]          NVARCHAR (100) NULL,
    [HostelTypeId]    INT            NOT NULL,
    [NoOfRooms]       SMALLINT       NULL,
    [IsObsolete]      BIT            NOT NULL,
    [ReportOrgTitle]  NVARCHAR (200) NULL,
    [SmallAddress1]   NVARCHAR (200) NULL,
    [SmallAddress2]   NVARCHAR (200) NULL,
    [CreatedUserId]   BIGINT         NOT NULL,
    [CreatedDateTime] DATETIME       NOT NULL,
    [UpdatedUserId]   BIGINT         NULL,
    [UpdatedDateTime] DATETIME       NULL
);

IF EXISTS (SELECT TOP 1 1
           FROM   [sHostel].[tHostelMaster])
    BEGIN
        INSERT INTO [sHostel].[tmp_ms_xx_tHostelMaster] ([OrgGroupId], [Id], [Title], [Remark], [HostelTypeId], [NoOfRooms], [IsObsolete], [CreatedUserId], [CreatedDateTime], [UpdatedUserId], [UpdatedDateTime])
        SELECT [OrgGroupId],
               [Id],
               [Title],
               [Remark],
               [HostelTypeId],
               [NoOfRooms],
               [IsObsolete],
               [CreatedUserId],
               [CreatedDateTime],
               [UpdatedUserId],
               [UpdatedDateTime]
        FROM   [sHostel].[tHostelMaster];
    END

DROP TABLE [sHostel].[tHostelMaster];

EXECUTE sp_rename N'[sHostel].[tmp_ms_xx_tHostelMaster]', N'tHostelMaster';

COMMIT TRANSACTION;

SET TRANSACTION ISOLATION LEVEL READ COMMITTED;


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


GO
ALTER TABLE [sHrm].[tEmployeeStatutoryAndOther]
    ADD [EPFJoinDate] DATE NULL;


GO
PRINT N'Starting rebuilding table [sLibrary].[tLibraryMaster]...';


GO
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;

SET XACT_ABORT ON;

BEGIN TRANSACTION;

CREATE TABLE [sLibrary].[tmp_ms_xx_tLibraryMaster] (
    [OrgGroupId]      SMALLINT       NOT NULL,
    [Id]              INT            NOT NULL,
    [Number]          INT            NULL,
    [Code]            NVARCHAR (20)  NOT NULL,
    [Title]           NVARCHAR (100) NOT NULL,
    [IsObsolete]      BIT            NOT NULL,
    [ReportOrgTitle]  NVARCHAR (200) NULL,
    [SmallAddress1]   NVARCHAR (200) NULL,
    [SmallAddress2]   NVARCHAR (200) NULL,
    [CreatedUserId]   BIGINT         NOT NULL,
    [CreatedDateTime] DATETIME       NOT NULL,
    [UpdatedUserId]   BIGINT         NOT NULL,
    [UpdatedDateTime] DATETIME       NOT NULL
);

IF EXISTS (SELECT TOP 1 1
           FROM   [sLibrary].[tLibraryMaster])
    BEGIN
        INSERT INTO [sLibrary].[tmp_ms_xx_tLibraryMaster] ([OrgGroupId], [Id], [Number], [Code], [Title], [IsObsolete], [CreatedUserId], [CreatedDateTime], [UpdatedUserId], [UpdatedDateTime])
        SELECT [OrgGroupId],
               [Id],
               [Number],
               [Code],
               [Title],
               [IsObsolete],
               [CreatedUserId],
               [CreatedDateTime],
               [UpdatedUserId],
               [UpdatedDateTime]
        FROM   [sLibrary].[tLibraryMaster];
    END

DROP TABLE [sLibrary].[tLibraryMaster];

EXECUTE sp_rename N'[sLibrary].[tmp_ms_xx_tLibraryMaster]', N'tLibraryMaster';

COMMIT TRANSACTION;

SET TRANSACTION ISOLATION LEVEL READ COMMITTED;


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


GO
ALTER TABLE [sSetup].[tClassGroupMaster]
    ADD [Inword] NVARCHAR (100) NULL;


GO
PRINT N'Creating [sErp].[tCustomerMaster]...';


GO
CREATE TABLE [sErp].[tCustomerMaster] (
    [Id]                 INT            NOT NULL,
    [OrgGroupId]         SMALLINT       NULL,
    [CRMLicenceId]       INT            NOT NULL,
    [Title]              NVARCHAR (200) NOT NULL,
    [ShortTitle]         NVARCHAR (100) NOT NULL,
    [StreetOne]          NVARCHAR (50)  NULL,
    [StreetTwo]          NVARCHAR (50)  NULL,
    [StreetThree]        NVARCHAR (50)  NULL,
    [CityName]           NVARCHAR (100) NULL,
    [StateName]          NVARCHAR (100) NULL,
    [CountryName]        NVARCHAR (100) NULL,
    [ZipCode]            NVARCHAR (20)  NULL,
    [HomePage]           NVARCHAR (100) NULL,
    [PhoneNo]            NVARCHAR (50)  NULL,
    [MobileNo]           NVARCHAR (50)  NULL,
    [ContactPerson]      NVARCHAR (100) NULL,
    [CreatedUserId]      BIGINT         NOT NULL,
    [CreatedDateTime]    DATETIME       NOT NULL,
    [UpdatedUserId]      BIGINT         NULL,
    [UpdatedDateTime]    DATETIME       NULL,
    [IsObsolete]         BIT            NOT NULL,
    [CustomerStatusId]   TINYINT        NULL,
    [ChannelId]          INT            NULL,
    [InstallationTypeId] TINYINT        NULL
);


GO
PRINT N'Creating [sErp].[tCustomerOrg]...';


GO
CREATE TABLE [sErp].[tCustomerOrg] (
    [CustomerId] INT            NOT NULL,
    [OrgId]      INT            NOT NULL,
    [OrgName]    NVARCHAR (200) NULL,
    [IsObsolete] BIT            NOT NULL
);


GO
PRINT N'Creating [sErp].[tChannelMaster]...';


GO
CREATE TABLE [sErp].[tChannelMaster] (
    [OrgGroupId]      SMALLINT       NOT NULL,
    [Id]              INT            NOT NULL,
    [Code]            NVARCHAR (100) NOT NULL,
    [Title]           NVARCHAR (100) NOT NULL,
    [IsObsolete]      BIT            NOT NULL,
    [CreatedUserId]   BIGINT         NOT NULL,
    [CreatedDateTime] DATETIME       NOT NULL,
    [UpdatedUserId]   BIGINT         NULL,
    [UpdatedDateTime] DATETIME       NULL
);


GO
PRINT N'Creating [sErp].[tInstallationTypeMaster]...';


GO
CREATE TABLE [sErp].[tInstallationTypeMaster] (
    [Id]         TINYINT        NOT NULL,
    [Code]       NVARCHAR (10)  NOT NULL,
    [Title]      NVARCHAR (100) NOT NULL,
    [IsObsolete] BIT            NOT NULL
);


GO
PRINT N'Creating PK_tInstallationTypeMaster...';


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


GO
PRINT N'Creating [sErp].[tCustomerStatusMaster]...';


GO
CREATE TABLE [sErp].[tCustomerStatusMaster] (
    [Id]         TINYINT        NOT NULL,
    [Code]       NVARCHAR (10)  NOT NULL,
    [Title]      NVARCHAR (100) NOT NULL,
    [IsObsolete] BIT            NOT NULL
);


GO
PRINT N'Creating PK_tCustomerStatusMaster...';


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


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


GO
CREATE TABLE [sAssessment].[tTempAllExamSubjectActivity] (
    [AcademicIdText]                 NVARCHAR (20)   NULL,
    [ExamIdText]                     NVARCHAR (20)   NULL,
    [CoScholasticScopeIdText]        NVARCHAR (20)   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,
    [Exam1Name]                      NVARCHAR (150)  NULL,
    [SubjectGrade1]                  NVARCHAR (50)   NULL,
    [Obtain1]                        DECIMAL (8, 2)  NULL,
    [ExamMaximum1]                   DECIMAL (8, 2)  NULL,
    [IsPresent1]                     BIT             NULL,
    [MaximumMark2]                   DECIMAL (8, 2)  NULL,
    [Exam2Name]                      NVARCHAR (150)  NULL,
    [SubjectGrade2]                  NVARCHAR (50)   NULL,
    [Obtain2]                        DECIMAL (8, 2)  NULL,
    [ExamMaximum2]                   DECIMAL (8, 2)  NULL,
    [IsPresent2]                     BIT             NULL,
    [MaximumMark3]                   DECIMAL (8, 2)  NULL,
    [Exam3Name]                      NVARCHAR (150)  NULL,
    [SubjectGrade3]                  NVARCHAR (50)   NULL,
    [Obtain3]                        DECIMAL (8, 2)  NULL,
    [ExamMaximum3]                   DECIMAL (8, 2)  NULL,
    [IsPresent3]                     BIT             NULL,
    [MaximumMark4]                   DECIMAL (8, 2)  NULL,
    [Exam4Name]                      NVARCHAR (150)  NULL,
    [SubjectGrade4]                  NVARCHAR (50)   NULL,
    [Obtain4]                        DECIMAL (8, 2)  NULL,
    [ExamMaximum4]                   DECIMAL (8, 2)  NULL,
    [IsPresent4]                     BIT             NULL,
    [MaximumMark5]                   DECIMAL (8, 2)  NULL,
    [Exam5Name]                      NVARCHAR (150)  NULL,
    [SubjectGrade5]                  NVARCHAR (50)   NULL,
    [Obtain5]                        DECIMAL (8, 2)  NULL,
    [ExamMaximum5]                   DECIMAL (8, 2)  NULL,
    [IsPresent5]                     BIT             NULL,
    [MaximumMark6]                   DECIMAL (8, 2)  NULL,
    [Exam6Name]                      NVARCHAR (150)  NULL,
    [SubjectGrade6]                  NVARCHAR (50)   NULL,
    [Obtain6]                        DECIMAL (8, 2)  NULL,
    [ExamMaximum6]                   DECIMAL (8, 2)  NULL,
    [IsPresent6]                     BIT             NULL,
    [MaximumMark7]                   DECIMAL (8, 2)  NULL,
    [Exam7Name]                      NVARCHAR (150)  NULL,
    [SubjectGrade7]                  NVARCHAR (50)   NULL,
    [Obtain7]                        DECIMAL (8, 2)  NULL,
    [ExamMaximum7]                   DECIMAL (8, 2)  NULL,
    [IsPresent7]                     BIT             NULL,
    [MaximumMark8]                   DECIMAL (8, 2)  NULL,
    [Exam8Name]                      NVARCHAR (150)  NULL,
    [SubjectGrade8]                  NVARCHAR (50)   NULL,
    [Obtain8]                        DECIMAL (8, 2)  NULL,
    [ExamMaximum8]                   DECIMAL (8, 2)  NULL,
    [IsPresent8]                     BIT             NULL,
    [SubjectGradeTerm1]              NVARCHAR (50)   NULL,
    [SubjectGradeTerm2]              NVARCHAR (50)   NULL,
    [IsMarksInDecimal]               BIT             NULL,
    [column_visible]                 BIT             NULL,
    [Percentile]                     DECIMAL (5, 2)  NULL,
    [ResultDetailId]                 BIGINT          NULL,
    [ResultId]                       BIGINT          NULL,
    [Remark1]                        NVARCHAR (150)  NULL,
    [Remark2]                        NVARCHAR (150)  NULL,
    [Remark3]                        NVARCHAR (150)  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,
    [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,
    [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,
    [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,
    [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,
    [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,
    [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,
    [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,
    [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,
    [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,
    [SubjectGroupTypeId]             SMALLINT        NULL,
    [ResultRemark1]                  NVARCHAR (200)  NULL,
    [ResultRemark2]                  NVARCHAR (200)  NULL,
    [TotalDays]                      SMALLINT        NULL,
    [PresentDays]                    SMALLINT        NULL,
    [StudentHeight]                  DECIMAL (6, 2)  NULL,
    [StudentWeight]                  DECIMAL (6, 2)  NULL,
    [ExamSeatNo]                     NVARCHAR (20)   NULL,
    [ExamId]                         INT             NULL,
    [IsDisplayParentName]            BIT             NULL,
    [FatherName]                     NVARCHAR (50)   NULL,
    [MotherName]                     NVARCHAR (50)   NULL,
    [IsShowSubjectMark]              BIT             NULL,
    [CoScholasticScopeId]            TINYINT         NULL,
    [IsDisplayPrincipalSign]         BIT             NULL,
    [IsDisplayTeacherSign]           BIT             NULL,
    [EmployeeSign]                   VARBINARY (MAX) NULL,
    [SubActivityGrade1]              NVARCHAR (10)   NULL,
    [SubActivityGrade2]              NVARCHAR (10)   NULL,
    [SubActivityGrade3]              NVARCHAR (10)   NULL,
    [SubActivityGrade4]              NVARCHAR (10)   NULL,
    [SubActivityGrade5]              NVARCHAR (10)   NULL,
    [SubActivityGrade6]              NVARCHAR (10)   NULL,
    [SubActivityId]                  INT             NULL,
    [ActivityId]                     INT             NULL,
    [SubActivityName]                NVARCHAR (50)   NULL,
    [ActivityName]                   NVARCHAR (50)   NULL,
    [SubjectActivityOrderIndex]      SMALLINT        NULL,
    [SubActivityOrderIndex]          SMALLINT        NULL,
    [ColumnSubjectCount]             SMALLINT        NULL,
    [Batch]                          NVARCHAR (100)  NULL,
    [ExamNameTerm1]                  NVARCHAR (100)  NULL,
    [ExamNameTerm2]                  NVARCHAR (100)  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,
    [MaximumMark10]                  DECIMAL (8, 2)  NULL,
    [Exam10Name]                     NVARCHAR (150)  NULL,
    [SubjectGrade10]                 NVARCHAR (50)   NULL,
    [Obtain10]                       DECIMAL (8, 2)  NULL,
    [ExamMaximum10]                  DECIMAL (8, 2)  NULL,
    [IsPresent10]                    BIT             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,
    [Exam10Code]                     NVARCHAR (20)   NULL,
    [MaximumMark9]                   DECIMAL (8, 2)  NULL,
    [Exam9Name]                      NVARCHAR (150)  NULL,
    [SubjectGrade9]                  NVARCHAR (50)   NULL,
    [Obtain9]                        DECIMAL (8, 2)  NULL,
    [ExamMaximum9]                   DECIMAL (8, 2)  NULL,
    [IsPresent9]                     BIT             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,
    [Exam9Code]                      NVARCHAR (20)   NULL,
    [ClassTeacherName]               NVARCHAR (100)  NULL,
    [FirstName]                      NVARCHAR (50)   NULL,
    [LastName]                       NVARCHAR (50)   NULL,
    [IsDisplayMonthlyAttendance]     BIT             NULL,
    [IsDisplayMonthlyAttendanceText] NVARCHAR (20)   NULL,
    [MarksheetHeaderA4]              VARBINARY (MAX) NULL,
    [IsImageHeader]                  BIT             NULL,
    [Height1]                        DECIMAL (6, 2)  NULL,
    [Height2]                        DECIMAL (6, 2)  NULL,
    [Height3]                        DECIMAL (6, 2)  NULL,
    [Weight1]                        DECIMAL (6, 2)  NULL,
    [Weight2]                        DECIMAL (6, 2)  NULL,
    [Weight3]                        DECIMAL (6, 2)  NULL,
    [Height4]                        DECIMAL (6, 2)  NULL,
    [Height5]                        DECIMAL (6, 2)  NULL,
    [Height6]                        DECIMAL (6, 2)  NULL,
    [Weight4]                        DECIMAL (6, 2)  NULL,
    [Weight5]                        DECIMAL (6, 2)  NULL,
    [Weight6]                        DECIMAL (6, 2)  NULL,
    [TotalDays1]                     TINYINT         NULL,
    [TotalDays2]                     TINYINT         NULL,
    [TotalDays3]                     TINYINT         NULL,
    [TotalDays4]                     TINYINT         NULL,
    [TotalDays5]                     TINYINT         NULL,
    [TotalDays6]                     TINYINT         NULL,
    [PresentDays1]                   TINYINT         NULL,
    [PresentDays2]                   TINYINT         NULL,
    [PresentDays3]                   TINYINT         NULL,
    [PresentDays4]                   TINYINT         NULL,
    [PresentDays5]                   TINYINT         NULL,
    [PresentDays6]                   TINYINT         NULL,
    [MyActivity1]                    NVARCHAR (200)  NULL,
    [MyActivity2]                    NVARCHAR (200)  NULL,
    [MyActivity3]                    NVARCHAR (200)  NULL,
    [MyActivity4]                    NVARCHAR (200)  NULL,
    [MyActivity5]                    NVARCHAR (200)  NULL,
    [MyActivity6]                    NVARCHAR (200)  NULL,
    [GeneralRemark1]                 NVARCHAR (200)  NULL,
    [GeneralRemark2]                 NVARCHAR (200)  NULL,
    [GeneralRemark3]                 NVARCHAR (200)  NULL,
    [GeneralRemark4]                 NVARCHAR (200)  NULL,
    [GeneralRemark5]                 NVARCHAR (200)  NULL,
    [GeneralRemark6]                 NVARCHAR (200)  NULL,
    [PresentAddress]                 NVARCHAR (500)  NULL,
    [MobileNo]                       NVARCHAR (10)   NULL
);


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


GO
CREATE TABLE [sAttendance].[tTempAttendance] (
    [LastDate]           DATE           NULL,
    [LeftDate]           DATE           NULL,
    [Builder1]           NVARCHAR (200) NULL,
    [Builder2]           NVARCHAR (200) NULL,
    [AcademicId]         BIGINT         NULL,
    [ClassDivisionTitle] NVARCHAR (50)  NULL,
    [Code]               NVARCHAR (50)  NULL,
    [RollNo]             INT            NULL,
    [Name]               NVARCHAR (200) NULL,
    [AttendanceTypeId]   INT            NULL,
    [ForYear]            INT            NULL,
    [ForMonth]           INT            NULL,
    [ClassId]            INT            NULL,
    [ClassName]          NVARCHAR (50)  NULL,
    [DivisionId]         INT            NULL,
    [DivisionName]       NVARCHAR (50)  NULL,
    [ForMonthInWord]     NVARCHAR (50)  NULL,
    [PresentCount]       INT            NULL,
    [AttendanceCount]    INT            NULL,
    [AbsentCount]        INT            NULL,
    [PresentUpto]        INT            NULL,
    [ClassOrderIndex]    INT            NULL,
    [DivisionOrderIndex] INT            NULL,
    [FooterSignature]    NVARCHAR (200) NULL,
    [TotalPresent]       INT            NULL,
    [P1]                 NVARCHAR (10)  NULL,
    [P2]                 NVARCHAR (10)  NULL,
    [P3]                 NVARCHAR (10)  NULL,
    [P4]                 NVARCHAR (10)  NULL,
    [P5]                 NVARCHAR (10)  NULL,
    [P6]                 NVARCHAR (10)  NULL,
    [P7]                 NVARCHAR (10)  NULL,
    [P8]                 NVARCHAR (10)  NULL,
    [P9]                 NVARCHAR (10)  NULL,
    [P10]                NVARCHAR (10)  NULL,
    [P11]                NVARCHAR (10)  NULL,
    [P12]                NVARCHAR (10)  NULL,
    [P13]                NVARCHAR (10)  NULL,
    [P14]                NVARCHAR (10)  NULL,
    [P15]                NVARCHAR (10)  NULL,
    [P16]                NVARCHAR (10)  NULL,
    [P17]                NVARCHAR (10)  NULL,
    [P18]                NVARCHAR (10)  NULL,
    [P19]                NVARCHAR (10)  NULL,
    [P20]                NVARCHAR (10)  NULL,
    [P21]                NVARCHAR (10)  NULL,
    [P22]                NVARCHAR (10)  NULL,
    [P23]                NVARCHAR (10)  NULL,
    [P24]                NVARCHAR (10)  NULL,
    [P25]                NVARCHAR (10)  NULL,
    [P26]                NVARCHAR (10)  NULL,
    [P27]                NVARCHAR (10)  NULL,
    [P28]                NVARCHAR (10)  NULL,
    [P29]                NVARCHAR (10)  NULL,
    [P30]                NVARCHAR (10)  NULL,
    [P31]                NVARCHAR (10)  NULL,
    [EmployeeName]       NVARCHAR (100) NULL,
    [DaysInMonth]        INT            NULL
);


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


GO
CREATE TABLE [sCommon].[tReportClient] (
    [ReportId]   SMALLINT       NOT NULL,
    [OrgGroupId] SMALLINT       NOT NULL,
    [ReportPath] NVARCHAR (300) NOT NULL
);


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


GO
CREATE TABLE [sCommon].[tTemplateSourceMaster] (
    [Id]         TINYINT       NOT NULL,
    [Code]       NVARCHAR (10) NOT NULL,
    [Title]      NVARCHAR (20) NOT NULL,
    [IsObsolete] BIT           NOT NULL
);


GO
PRINT N'Creating PK_tTemplateSourceMaster...';


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


GO
PRINT N'Creating [sCommunication].[tTempCircularScope]...';


GO
CREATE TABLE [sCommunication].[tTempCircularScope] (
    [TempCircularId] NVARCHAR (100) NOT NULL,
    [SourceTypeId]   SMALLINT       NOT NULL,
    [SourceId]       BIGINT         NOT NULL
);


GO
PRINT N'Creating FK_sAssessment_tResult_AcademicId...';


GO
ALTER TABLE [sAssessment].[tResult] WITH NOCHECK
    ADD CONSTRAINT [FK_sAssessment_tResult_AcademicId] FOREIGN KEY ([AcademicId]) REFERENCES [sStudent].[tAcademic] ([Id]) ON DELETE NO ACTION ON UPDATE NO ACTION;


GO
ALTER TABLE [sAssessment].[tResult] NOCHECK CONSTRAINT [FK_sAssessment_tResult_AcademicId];


GO
PRINT N'Creating FK_sAssessment_tResult_ExamId...';


GO
ALTER TABLE [sAssessment].[tResult] WITH NOCHECK
    ADD CONSTRAINT [FK_sAssessment_tResult_ExamId] FOREIGN KEY ([ExamId]) REFERENCES [sAssessment].[tExamMaster] ([Id]) ON DELETE NO ACTION ON UPDATE NO ACTION;


GO
ALTER TABLE [sAssessment].[tResult] NOCHECK CONSTRAINT [FK_sAssessment_tResult_ExamId];


GO
PRINT N'Creating FK_sAssessment_tResultDetail_ResultId...';


GO
ALTER TABLE [sAssessment].[tResultDetail] WITH NOCHECK
    ADD CONSTRAINT [FK_sAssessment_tResultDetail_ResultId] FOREIGN KEY ([ResultId]) REFERENCES [sAssessment].[tResult] ([Id]) ON DELETE NO ACTION ON UPDATE NO ACTION;

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



GO
ALTER TABLE [sAssessment].[tResultDetail] WITH CHECK CHECK CONSTRAINT [FK_sAssessment_tResultDetail_ResultId];


GO


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


GO
ALTER FUNCTION [sAttendance].[fHolidayForMonthGet](@rForMonth int,@rForYear int,@rBatchId int,@rDivisionId int)
RETURNS nvarchar(200) WITH EXECUTE AS CALLER
AS 
BEGIN
  DECLARE @day int,@day1 int,@day2 int,@str varchar(200)='',@lcount int=0,@OrderBy int=0
  
  --Select  COUNT(Id) from sActivity.tEventSchedule where  MONTH(FromDate)=8 and year(FromDate)= and BatchId=100100114 and  IsHoliday=1
	 
	Declare  @TempEventSchedule as table
	(
		Id int IDENTITY,
		 day5 int,
		 day6 int	
	) 
	Insert into @TempEventSchedule
	(
		day5,
		day6
	)
	Select 
		DATEPART(DD,FromDate) AS day5,
		DATEPART(DD,ToDate) AS day6
	From 
		sActivity.tEventSchedule ES
		INNER JOIN sActivity.tEventAssign EA ON EA.EventScheduleID = ES.Id 
	Where 
		IsHoliday=1 
		AND BatchId =@rBatchId 
		AND @rForMonth=DATEPART(MM,FromDate) 
		AND @rForYear<=DATEPART(YYYY,FromDate)  
		AND @rForYear>=DATEPART(YYYY,Todate)
		AND EA.SourceId = @rDivisionId
		AND EA.SourceTypeId=2005
	 
		
	 
	Select @lcount = MAX(Id) from @TempEventSchedule 
	 	 
Set @OrderBy=@OrderBy+1
	   
	While  @OrderBy <=@lcount
		BEGIN 
	 Select @day1=day5,@day2 = day6 from @TempEventSchedule WHERE ID = @OrderBy
	  while @day1<=@day2
	  BEGIN 
	  
			set @str = @str + convert(nvarchar,@day1) + ','  
			set @day1=@day1 + 1 
			
		END
		 
		Set @OrderBy = @OrderBy+1 		 
	END
	if isnull(@str,'')=''
	begin
		select @str=''
	end
	else
	begin		
		select @str=LEFT(@str,LEN(@str)-1)
	end
	return  @str
	--select @day1=DATEPART(DD,FromDate) 
	--from
	-- 	sActivity.tEventSchedule ES
	--	INNER JOIN sActivity.tEventAssign EA ON EA.EventScheduleID = ES.Id 
	--where 
	--	IsHoliday=1 
	--	AND BatchId =@rBatchId 
	--	AND @rForMonth=DATEPART(MM,FromDate) 
	--	AND @rForYear<=DATEPART(YYYY,FromDate)  
	--	AND @rForYear>=DATEPART(YYYY,Todate)
	--	AND EA.SourceId = @rDivisionId
		
	--select 
	--	@day2=DATEPART(DD,ToDate) 
	--from 
	--	sActivity.tEventSchedule ES
	--	INNER JOIN sActivity.tEventAssign EA ON EA.EventScheduleID = ES.Id 
	--where 
	--	IsHoliday=1  
	--	AND @rForMonth=DATEPART(MM,FromDate) 
	--	AND @rForYear<=DATEPART(YYYY,FromDate)  
	--	AND @rForYear>=DATEPART(YYYY,Todate)
	--	AND BatchId =@rBatchId
	--	AND EA.SourceId = @rDivisionId
	 
	--While @day1<=@day2
	--BEGIN
	--	select @str = @str + convert(varchar,@day1) + ','
	--	select @day1=@day1 + 1
	--END
	--if isnull(@str,'')=''
	--begin
	--	select @str=''
	--end
	--else
	--begin		
	--	select @str=LEFT(@str,LEN(@str)-1)
	--end
	--return  @lcount
	
	
	
END
GO
PRINT N'Creating [sAssessment].[fCSGradeStringGet]...';


GO

 CREATE FUNCTION [sAssessment].[fCSGradeStringGet](@rGradeId int)
RETURNS [nvarchar](MAX) WITH EXECUTE AS CALLER
AS 
BEGIN
DECLARE @lGradeString  VARCHAR(MAX)
 
SELECT @lGradeString = COALESCE(@lGradeString ,'') +   d.GradeCode +  ','  + d.MarkRange + ' | ' 
FROM sAssessment.tGradeSetDetail d WHERE GradeSetId = @rGradeId
ORDER BY d.MinimumScore desc

RETURN @lGradeString

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


GO
 
CREATE FUNCTION [sAttendance].[fAttendanceAdmissionDateGet]( @rAdmissionDate date,@rAttendanceDate nvarchar(20),@rLeftDate date,@rStatus nvarchar(10))
RETURNS [nvarchar](50) WITH EXECUTE AS CALLER
AS 
BEGIN
	DECLARE @lDate nvarchar(20)
	
	
if isnull(@rStatus,'') = ''
BEGIN
	Set @ldate = @rAttendanceDate	
	if ISDATE(@ldate)=1
	BEGIN
	if(@rAdmissionDate > @rAttendanceDate)
	BEGIN
		SET @rStatus = 'NA'
		RETURN @rStatus
	END
	if(@rLeftDate < @rAttendanceDate)
	BEGIN
		SET @rStatus='L'
		RETURN @rStatus
	END
	 END	
	END	    
	RETURN @rStatus
	
END
GO
PRINT N'Creating [sTransport].[fAssignRouteCodeGet]...';


GO

CREATE FUNCTION [sTransport].[fAssignRouteCodeGet](@rTransportId int,@rBusRouteId int,@rOrgId smallint,@rOrgGroupBatchId int)
RETURNS nvarchar(max) WITH EXECUTE AS CALLER
AS 
BEGIN	 
declare @rSourceIdList nvarchar(max)=''

Select @rSourceIdList=@rSourceIdList + ISNULL(VA.Code,'') +','

FROM sTransport.tAssignRoute AR 
        INNER JOIN  sStudent.vStudentLastAcademic VA ON VA.StudentId=AR.SourceId  AND AR.SourceTypeId=2003 AND VA.StatusId=1
        INNER JOIN sTransport.tBusRouteDestinationMaster BRDM ON BRDM.Id=AR.PickupDestinationId
        INNER JOIN sTransport.tBusRouteMaster BRM ON BRM.Id=BRDM.BusRouteId
          WHERE 
        BRM.TransportId=@rTransportId 
      	AND ((BRDM.Id=@rBusRouteId) OR (@rBusRouteId=0))
        AND VA.OrgGroupBatchId=@rOrgGroupBatchId
      AND ((VA.OrgId=@rOrgId) OR (@rOrgId=0))                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            
        IF (RIGHT(@rSourceIdList, 1) = ',')
   set @rSourceIdList = LEFT(@rSourceIdList, LEN(@rSourceIdList) - 1)
   
      RETURN  isnull(@rSourceIdList,'')
END
GO
PRINT N'Altering [sHrm].[vEmployeeColumnName]...';


GO










/******************************************************************************  
 Purpose          : To get Batch Wise  Class
 Created date     : 21 Nov 2013
 Author           : Kundan Patel 
 Copyright©       : Copyright © Sapphire Software Solutions
 ******************************************************************************/  
ALTER VIEW [sHrm].[vEmployeeColumnName]  
  
AS  
  
SELECT 	
	   --EM.OrgId
    --  ,EM.Id AS EmployeeId
       EM.Code
      ,EM.FirstName
      ,EM.MiddleName
      ,EM.LastName
      ,ISNULL(EM.FirstName, '') + ' ' + ISNULL(EM.MiddleName, '') + ' ' + ISNULL(EM.LastName, '') AS Name
      --,EM.StatusId
      ,SM.Title AS StatusName
      --,EM.IsObsolete
      --,EJD.Id AS EmployeeJobDetailId
      --,EJD.EmployeeDesignationId
      ,EDM.Title AS EmployeeDesignation
      --,EJD.OrganizationDepartmentId
      ,ODM.Title AS OrganizationDepartment
      ,EJD.DateOfJoining
      --,EJD.EPFNumber
      --,EJD.ESINumber
      --,EJD.EmployeeTypeId
      ,ETM.Title AS EmployeeType
      ,EGM.Title AS EmployeeGroup
      ,EJD.DateOfleaving
      ,EJD.ReasonOfleaving
      --,ELM.StreetOne
      --,ELM.StreetTwo
      --,ELM.StreetThree
      --,ELM.CityName
      --,ELM.StateName
      --,ELM.CountryName
      --,ELM.ZipCode
      --,ELM.PhoneNo
      --,ELM.FaxNo
      --,ELM.NameOfOccupier
      --,ELM.AddressOfOccupier
      --,ELM.SmallAddress1
      --,ELM.SmallAddress2
      --,ELM.RegistrationNumber
      --,ELM.LicenceNumber
      --,ELM.EsicNumber
      --,ELM.EsicAddress1
      --,ELM.EsicAddress2
      --,ELM.NatureOfIndustry
      --,ELM.ByProduct
      --,ELM.DangerousOperation
      --,ELM.NatureOfTest
      --,ELM.NatureOfTestNonHazardous
      --,ELM.RowMaterialUsed
      --,ELM.HazardousProcess
      --,ELM.Cmo
      --,ELM.NicNumber
      --,ELM.CountryId
      --,ELM.StateId
      --,EPD.Id AS EmployeePersonalDetailId
      ,EPD.UIDNumber
      ,EPD.DateOfBirth
      ,EPD.Qualification
      ,EPD.FamilyCast
      ,CCM.Title AS CasteCategory
      --,EPD.GenderId
      ,GM.Title AS Gender
      --,EPD.ReligionId
      ,RM.Title AS Religion
      --,EPD.MaritalStatusId
      ,MSM.Title AS MaritalStatus
      ,EPD.IdentificationMark1
      --,EPD.BloodGroupId
      ,BGM.Title AS BloodGroup,
      EC.MobileNumber,
      EC.PersonalEmail
      ,EC.CompanyEmail
      ,EC.PhoneNoCompany
      ,EC.ExtensionNo
      ,EC.PresentStreetOne
      ,Ec.PresentStreetTwo
      ,Ec.PresentStreetThree
      ,Ec.PresentCountry
      ,Ec.PresentState
      ,Ec.PresentCity
      ,Ec.PresentZipCode
      ,Ec.PresentContactNo
      ,Ec.PermanentStreetOne
      ,Ec.PermanentStreetTwo
      ,Ec.PermanentStreetThree
      ,Ec.PermanentCountry
      ,Ec.PermanentState
      ,Ec.PermanentCity
      ,Ec.PermanentZipCode
      ,Ec.PermanentContactNo
      ,ES.EPFNumber
      ,ES.ESINumber
      ,ES.AccountNumber
      ,ES.BankName
      ,ES.Branch
      ,ES.IFSCNumber
      ,ES.PanNumber
      ,ES.BasicPay
      ,ES.IncrementDate
      ,ES.EPFJoinDate
      
  FROM sHrm.tEmployeeMaster EM
		INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
		--LEFT JOIN sHrm.tEmployeeJobTitleMaster EJTM ON EJTM.Id=EJD.EmployeeJobTitleId
		LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id=EJD.EmployeeDesignationId
		INNER JOIN sSetup.tDepartmentMaster ODM ON ODM.Id = EJD.OrganizationDepartmentId
		INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId = EM.Id
		LEFT JOIN sCommon.tCastCategoryMaster CCM ON CCM.Id = EPD.CastCategoryId
		LEFT JOIN sCommon.tGenderMaster GM ON GM.Id=EPD.GenderId
		LEFT JOIN sCommon.tReligionMaster RM ON RM.Id=EPD.ReligionId
		LEFT JOIN sCommon.tMaritalStatusMaster MSM ON MSM.Id=EPD.MaritalStatusId
		LEFT JOIN sCommon.tBloodGroupMaster BGM ON BGM.Id=EPD.BloodGroupId
		--LEFT JOIN sHrm.tQualificationMaster QM ON QM.Id=EPD.HigestQualificationId
		INNER JOIN sHrm.tEmployeeTypeMaster ETM ON ETM.Id = EJD.EmployeeTypeId
		INNER JOIN sCommon.tStatusMaster SM ON SM.Id = EM.StatusId AND SM.StatusTypeId = 4
		LEFT JOIN sHrm.tEmployeeCommunications EC ON EC.EmployeeId = EM.Id
		LEFT JOIN sHrm.tEmployeeStatutoryAndOther ES ON ES.EmployeeId = EM.Id
		LEFT JOIN sHrm.tEmployeeGroupMaster EGM ON EGM.Id = EJD.EmployeeGroupId
GO
PRINT N'Altering [sHrm].[vEmployeeCustomSearch]...';


GO








/******************************************************************************  
 Purpose          : To get Batch Wise  Class
 Created date     : 21 Nov 2013
 Author           : Kundan Patel 
 Copyright©       : Copyright © Sapphire Software Solutions
 ******************************************************************************/  
ALTER VIEW [sHrm].[vEmployeeCustomSearch]  
  
AS  
  
SELECT 	
	   EM.OrgId
      ,EM.Id AS EmployeeId
      ,EM.Code
      ,EM.FirstName
      ,EM.MiddleName
      ,EM.LastName
      ,ISNULL(EM.FirstName, '') + ' ' + ISNULL(EM.MiddleName, '') + ' ' + ISNULL(EM.LastName, '') AS Name
      ,EM.StatusId
      ,SM.Title AS StatusName
      ,EM.IsObsolete
      ,0 AS EmployeeJobDetail
      ,EJD.EmployeeDesignationId
      ,EDM.Title AS EmployeeDesignation
      ,EJD.OrganizationDepartmentId
      ,ODM.Title AS OrganizationDepartment
      ,EJD.DateOfJoining
      --,EJD.EPFNumber
      --,EJD.ESINumber
      ,EJD.EmployeeTypeId
      ,ETM.Title AS EmployeeType
      ,EGM.Title AS EmployeeGroup
      ,EJD.DateOfleaving
      ,EJD.ReasonOfleaving
      --,ELM.StreetOne
      --,ELM.StreetTwo
      --,ELM.StreetThree
      --,ELM.CityName
      --,ELM.StateName
      --,ELM.CountryName
      --,ELM.ZipCode
      --,ELM.PhoneNo
      --,ELM.FaxNo
      --,ELM.NameOfOccupier
      --,ELM.AddressOfOccupier
      --,ELM.SmallAddress1
      --,ELM.SmallAddress2
      --,ELM.RegistrationNumber
      --,ELM.LicenceNumber
      --,ELM.EsicNumber
      --,ELM.EsicAddress1
      --,ELM.EsicAddress2
      --,ELM.NatureOfIndustry
      --,ELM.ByProduct
      --,ELM.DangerousOperation
      --,ELM.NatureOfTest
      --,ELM.NatureOfTestNonHazardous
      --,ELM.RowMaterialUsed
      --,ELM.HazardousProcess
      --,ELM.Cmo
      --,ELM.NicNumber
      --,ELM.CountryId
      --,ELM.StateId
      ,0 AS EmployeePersonalDetailId
      ,EPD.UIDNumber
      ,EPD.DateOfBirth
      ,EPD.GenderId
      ,GM.Title AS Gender
      ,EPD.ReligionId
      ,RM.Title AS Religion
      ,EPD.MaritalStatusId
      ,MSM.Title AS MaritalStatus
      ,EPD.IdentificationMark1
      ,EPD.BloodGroupId
      ,BGM.Title AS BloodGroup
      ,EPD.Qualification
      ,EPD.FamilyCast
      ,CCM.Title AS CastCategory
      ,EJD.EmployeeGroupId
      , EC.MobileNumber
      ,EC.PersonalEmail
      ,EC.CompanyEmail
      ,EC.PhoneNoCompany
      ,EC.ExtensionNo
      ,EC.PresentStreetOne
      ,Ec.PresentStreetTwo
      ,Ec.PresentStreetThree
      ,Ec.PresentCountry
      ,Ec.PresentState
      ,Ec.PresentCity
      ,Ec.PresentZipCode
      ,Ec.PresentContactNo
      ,Ec.PermanentStreetOne
      ,Ec.PermanentStreetTwo
      ,Ec.PermanentStreetThree
      ,Ec.PermanentCountry
      ,Ec.PermanentState
      ,Ec.PermanentCity
      ,Ec.PermanentZipCode
      ,Ec.PermanentContactNo
      ,ES.EPFNumber
      ,ES.ESINumber
      ,ES.AccountNumber
      ,ES.BankName
      ,ES.Branch
      ,ES.IFSCNumber
      ,ES.PanNumber
      ,ES.BasicPay
      ,ES.IncrementDate
      ,ES.EPFJoinDate
      
  FROM 
		sHrm.tEmployeeMaster EM
	INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id=EJD.EmployeeDesignationId
	INNER JOIN sSetup.tDepartmentMaster ODM ON ODM.Id = EJD.OrganizationDepartmentId
	INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId = EM.Id
	LEFT JOIN sCommon.tCastCategoryMaster CCM ON CCM.Id = EPD.CastCategoryId
	LEFT JOIN sCommon.tGenderMaster GM ON GM.Id=EPD.GenderId
	LEFT JOIN sCommon.tReligionMaster RM ON RM.Id=EPD.ReligionId
	LEFT JOIN sCommon.tMaritalStatusMaster MSM ON MSM.Id=EPD.MaritalStatusId
	LEFT JOIN sCommon.tBloodGroupMaster BGM ON BGM.Id=EPD.BloodGroupId
	INNER JOIN sHrm.tEmployeeTypeMaster ETM ON ETM.Id = EJD.EmployeeTypeId
	INNER JOIN sCommon.tStatusMaster SM ON SM.Id = EM.StatusId AND SM.StatusTypeId = 4 
	LEFT JOIN sHrm.tEmployeeCommunications EC ON EC.EmployeeId = EM.Id
	LEFT JOIN sHrm.tEmployeeStatutoryAndOther ES ON ES.EmployeeId = EM.Id
	LEFT JOIN sHrm.tEmployeeGroupMaster EGM ON EGM.Id = EJD.EmployeeGroupId
GO
PRINT N'Altering [sStudent].[vStudentCustomSearch]...';


GO



/******************************************************************************  
 Purpose          : To get Batch Wise  Class
 Created date     : 21 Nov 2013
 Author           : Kundan Patel 
 Copyright©       : Copyright © Sapphire Software Solutions
 ******************************************************************************/  
ALTER VIEW [sStudent].[vStudentCustomSearch]  
  
AS  
  
SELECT 	
	  SA.AcademicId,	  
	  SA.ClassId,
	  SA.DivisionId,
	  SA.RollNo,
	  SA.OrgId,
	  SA.BatchId,
	  BM.Title AS Batch,
	  SA.StudentId,
	  SA.SUId,
	  SA.Code,
	  SA.Number,
	  SA.FirstName,
	  SA.MiddleName,
	  SA.LastName,
	  SA.Name,
	  --SA.DepartmentId,
	  SA.StatusId,
	  SA.ClassName,
	  SA.DivisionName,
	  SA.StatusName,
	  SO.UIDNumber,
	  SO.AdhaarNumber,
      CONVERT(VARCHAR(10), SO.DateOfBirth, 111) AS DateOfBirth,
      SO.BirthdateInWord,
      SO.TransportModeId,
      TM.Title AS TransportMode,
      SO.GenderId,
      GM.Title AS Gender,
      SO.BloodGroupId,
      BGM.Title AS BloodGroup,
      SO.BirthPlace,
      SO.BirthTaluka,
      SO.BirthDistrict,
      SO.FamilyCast AS FamilyCaste,
      SO.FamilySubCast,
      
      
      SO.CastCategoryId,
      CCM.Title AS CasteCategory,
      SO.ReligionId,
      RM.Title AS Religion,
      SO.HouseId,
      HM.Title AS House,
      SO.MotherTongueId,
      MTM.Title AS MotherTongue,
      SO.NationalityId,
      NM.Title AS Nationality,
      SO.Hobby,
      SH.IdentificationMark1,
      SH.IdentificationMark2,
      SH.IsPysicalDeformity,
      SH.PysicalDeformityRemark,
      SH.IsMajorIllness,
      SH.MajorIllnessRemark,
      SH.FamilyDoctorName,
      SH.FamilyDoctorContactNo,
	  SC.PresentStreetOne,
      SC.PresentStreetTwo,
      SC.PresentStreetThree,
      SC.PresentCountry,
      SC.PresentState,
      SC.PresentCity,
      SC.PresentZipCode,
      SC.PresentContactNo,
      SC.PermanentStreetOne,
      SC.PermanentStreetTwo,
      SC.PermanentStreetThree,
      SC.PermanentCountry,
      SC.PermanentState,
      SC.PermanentCity,
      SC.PermanentZipCode,
      SC.PermanentContactNo,
      SC.EmergencyStreetOne,
      SC.EmergencyStreetTwo,
      SC.EmergencyStreetThree,
      SC.EmergencyCountry,
      SC.EmergencyState,
      SC.EmergencyCity,
      SC.EmergencyZipCode,
      SC.EmergencyContactNo,
      SC.ParentContactNo,
      SC.ParentEmail,
      SC.StudentContactNo,
      SC.StudentEmail,
	  AR.PickupDestinationId AS BusRouteDestinationId,
	  BDM.Title AS BusRouteDestination,
	  SF.FatherName,
	  SF.FatherDateOfBirth,	 
	  SF.FatherQualification,
	  SF.FatherOccupation,
	  SF.FatherContactNo,
	  SF.FatherMail,
	  SF.FatherOfficeAddress,
	  SF.FatherIncome,
	  SF.MotherName,
	  SF.MotherDateOfBirth,
	  SF.MotherQualification,
	  SF.MotherOccupation,
      SF.MotherContactNo,
      SF.MotherMail,
      SF.MotherOfficeAddress,
      SF.MotherIncome,      
	  ISNULL(SA.AdmissionCategoryId,0) AS AdmissionCategoryId,
	  AC.Title AS AdmissionCategory,
	  SAD.PreviousSchool,
	  CONVERT(VARCHAR(10), SAD.AdmissionDate, 111) AS AdmissionDate,
	  SAD.AdmissionFormNumber,
	  SAD.AdmissionNumber,
	  SAD.IsTransfer,
	  SAD.TransferFrom,
	  SAD.PassingYear,
	  SAD.IsTFWS,
	  SAD.IsCertificateHolder,
	  SAD.CertificateName,
	  AQM.Title AS AdmissionQuota,
	  SAD.LeftDate,
	  SA.IsBlackList,
	  SA.BlackListReason,
	  SA.DivisionOrder,
	  SA.ClassOrderIndex,
	  AD.RepeatCount,
	  ADI.BankAccountNumber,
	  ADi.BankBranch,
	  ADI.BankIFSCCode,
	  ADI.BankName,
	  ESM.Title AS StudentBatchStatus,
	  EnrollmentStatusId AS StudentStatusId,
	  ADI.Class9BoardRegistrationNumber,
	  ADI.Class11BoardRegistrationNumber,
	  ADI.PassportNumber,
	  ADI.PassportType,
	  ADI.PassportCountryCode,
	  ADI.PassportIssueDate,
	  ADI.PassportExpiryDate,
	  SS.SiblingName1,
	  SS.SiblingInstitue1,
	  SS.SiblingClass1,
	  SS.SiblingAge1,
	  SS.SiblingRelation1,
	  SS.SiblingName2,
	  SS.SiblingInstitue2,
	  SS.SiblingClass2,
	  SS.SiblingAge2,
	  SS.SiblingRelation2,
	  SS.SiblingName3,
	  SS.SiblingInstitue3,
	  SS.SiblingClass3,
	  SS.SiblingAge3,
	  SS.SiblingRelation3
	  
	  	  	   
  FROM sStudent.vStudentAcademic SA
    INNER JOIN sStudent.tStudentMaster SM ON SM.Id = SA.StudentId
	LEFT JOIN sStudent.tStudentAdmission SAD ON SAD.StudentId=SA.StudentId
	LEFT JOIN sCommon.tAdmissionQuotaMaster AQM ON AQM.Id = SAD.AdmissionQuotaId
	LEFT JOIN sSetup.tBatchMaster BM ON BM.Id=SA.BatchId
	LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=SA.StudentId
	LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=SA.StudentId
	LEFT JOIN sTransport.tAssignRoute AR ON AR.SourceId=SA.StudentId
	LEFT JOIN sCommon.tTransportModeMaster TM ON TM.Id=SO.TransportModeId
	LEFT JOIN sCommon.tGenderMaster GM ON GM.Id=SO.GenderId
	LEFT JOIN sCommon.tBloodGroupMaster BGM ON BGM.Id=SO.BloodGroupId
	LEFT JOIN sCommon.tCastCategoryMaster CCM ON CCM.Id=SO.CastCategoryId
	LEFT JOIN sCommon.tReligionMaster RM ON RM.Id=SO.ReligionId
	LEFT JOIN sActivity.tHouseMaster HM ON HM.Id=SO.HouseId
	LEFT JOIN sCommon.tMotherTongueMaster MTM ON MTM.Id=SO.MotherTongueId
	LEFT JOIN sCommon.tCountryMaster NM ON NM.Id=SO.NationalityId
	LEFT JOIN sTransport.tBusRouteDestinationMaster BDM ON BDM.Id=AR.PickupDestinationId
	LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId=SA.StudentId
	LEFT JOIN sStudent.tStudentHealth SH ON SH.StudentId=SA.StudentId
	LEFT JOIN sStudent.tAdmissionCategoryMaster AC ON AC.Id=SA.AdmissionCategoryId
	LEFT JOIN sStudent.tAcademicDetail AD ON AD.AcademicId = SA.AcademicId
	LEFT JOIN sStudent.tStudentadditional ADI ON ADI.StudentId = SA.StudentId
	LEFT JOIN sStudent.tEnrollmentStatusMaster ESM ON ESM.Id = SM.EnrollmentStatusId
	LEFT JOIN sStudent.tStudentSibling SS ON SS.StudentId = SA.StudentId
GO
PRINT N'Altering [sStudent].[vStudentFull]...';


GO




















/******************************************************************************  
 Purpose          : To get Doctor details  
 Created date     : 18 Jan 2012  
 Author           : Rajendra Patel 
 Copyright©       : Copyright © Sapphire Software Solutions
 Last Change Desc : Moved EmployeeMaster from sCommon to sHrm.
*******************************************************************************/  
ALTER VIEW [sStudent].[vStudentFull]  
  
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.FirstName,
	  SM.MiddleName,
	  SM.LastName,
	  [sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Name,
	  --SM.DepartmentId,
	  SM.StatusId,
	  CM.DisplayTitle AS ClassName,
	  DM.DisplayTitle AS DivisionName,
	  STM.Title AS StatusName,
	  SI.StudentPhoto,
	  CM.DepartmentId,
	  ISNULL(SM.EnrollmentStatusId,0) AS EnrollmentStatusId 
	   
  FROM 
  
	sStudent.tAcademic A
	INNER JOIN sStudent.tStudentMaster SM
		ON A.StudentId=SM.Id	
	INNER JOIN sSetup.tClassMaster CM
		ON CM.Id=A.ClassId
	INNER JOIN sSetup.tDivisionMaster DM
		ON DM.Id=A.DivisionId
	INNER JOIN sStudent.tStatusMaster STM
		ON STM.Id=SM.StatusId
	LEFT JOIN sStudent.tStudentCommunication SC 
		ON SC.StudentId=A.StudentId
	LEFT JOIN sStudent.tStudentOther SO
		ON SO.StudentId=A.StudentId
		LEFT JOIN sStudent.tStudentImages SI
		ON SI.StudentId=A.StudentId
	INNER JOIN sSetup.tOrganizationMaster OM
	    ON SM.OrgId = OM.Id
GO


PRINT N'Dropping [sSetup].[pPortalMasterTermtUpdate]...';


GO
DROP PROCEDURE [sSetup].[pPortalMasterTermtUpdate];


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


GO
ALTER PROCEDURE [sAcademic].[pClassworkGet]

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

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


GO
ALTER PROCEDURE [sAcademic].[pLessonPlanGet]

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

BEGIN 
	
	SELECT 
			LP.Id,
			TM.ClassId,
			LP.DivisionId,
			TM.SubjectId,
			LP.TopicId,
			LP.NoOfPeriodRequired,
			LP.Objective,
			LP.IndicativeHomework,
			LP.Summary,
			ISNULL(LP.StartDate,'') AS StartDate ,
			ISNULL(LP.EndDate,'') AS EndDate,
			LP.IsCompleted,
			LP.EmployeeId,
			LP.BatchId,
			LP.CreatedUserId,
			LP.CreatedDateTime,
			TM.Title AS TopicName,
			vTSD.ClassTitle+' - '+ vTSD.DivisionTitle AS ClassDivisionName,
			 
			vTSD.SubjectName,
			ISNULL(EM.FirstName,'') + ' ' + ISNULL(EM.LastName,'') AS  EmployeeName,
			LP.LearningExperience,
			LP.ToolsAndTechniques,
			LP.EssentialMaterial
	FROM 
			sAcademic.tLessonPlan LP
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id=LP.EmployeeId
			INNER JOIN sAcademic.tTopicMaster TM ON TM.Id=LP.TopicId
			INNER JOIN sAcademic.vTeacherSubjectDivision vTSD ON vTSD.DivisionId = LP.DivisionId
			AND vTSD.ClassId = TM.ClassId 
			AND vTSD.SubjectId = TM.SubjectId 
			AND vTSD.EmployeeId = LP.EmployeeId
			INNER JOIN sSetup.tClassMaster CM ON CM.Id = vTSD.ClassId
	WHERE 
		(LP.BatchId = @rBatchId) 
		AND ((LP.EmployeeId = @rEmployeeId) OR (@rEmployeeId=0))
		AND ((LP.Id = @rId) OR (@rId = 0))
		AND ((TM.ClassId = @rClassId) OR (@rClassId = 0))
		AND ((vTSD.DivisionId = @rDivisionId) OR (@rDivisionId = 0))
		AND ((TM.SubjectId = @rSubjectId) OR (@rSubjectId = 0))
		AND ((LP.IsCompleted='False') OR (LP.IsCompleted=@rIsCompleted))
		AND ((CM.DepartmentId = @rDepartmentid) OR (@rDepartmentid=0))
		 Order by id 
END
GO
PRINT N'Altering [sActivity].[pEventAttendanceGet]...';


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

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


GO
ALTER PROCEDURE [sActivity].[pEventScheduleGet]

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

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

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


GO
ALTER PROCEDURE [sAdmission].[pAdmissionFormFamilyDetailAdd]
		 @rId bigint,
		 @rFatherName nvarchar(100),
		 @rFatherDateOfBirth date,
		 @rFatherOccupation nvarchar(50),
		 @rFatherQualification nvarchar(50),
		 @rFatherContactNo nvarchar(50),
		 @rFatherMail nvarchar(50),
		 @rFatherOfficeAddress nvarchar(300),
		 @rFatherIncome int,
		 
		 @rMotherName nvarchar(100),
		 @rMotherDateOfBirth date,
		 @rMotherOccupation nvarchar(50),
		 @rMotherQualification nvarchar(50),
		 @rMotherContactNo nvarchar(50),
		 @rMotherMail nvarchar(50),
		 @rMotherOfficeAddress nvarchar(300),
		 @rMotherIncome int,
		
		 @rRelationshipName nvarchar(100),
		 @rGuardianName nvarchar(100),
		 @rGuardianDateOfBirth date,
		 @rGuardianOccupation nvarchar(50),
		 @rGuardianQualification nvarchar(50),
		 @rGuardianContactNo nvarchar(50),
		 @rGuardianMail nvarchar(50),
		 @rGuardianOfficeAddress nvarchar(300),
		 @rGuardianIncome int,
		 @rCreatedUserId bigint,
		 @rCreatedDateTime date,
		 --@rUpdatedUserId bigint,
		 --@rUpdatedDateTime date,
		 @rFatherPhoto varbinary(max)=0,
		  @rMotherPhoto varbinary(max)=0,
		 @rGuardianPhoto varbinary(max)=0
		 
		 
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	

	
 BEGIN TRANSACTION	
	
	IF NOT EXISTS (Select AdmissionFormId from sAdmission.tAdmissionFormFamilyDetail where AdmissionFormId = @rId)
	BEGIN
	INSERT INTO sAdmission.tAdmissionFormFamilyDetail
		(
		AdmissionFormId,
		 FatherName,
		 FatherDateOfBirth,
		 FatherOccupation,
		 FatherQualification,
		 FatherContactNo,
		 FatherMail,
		 FatherOfficeAddress,
		 FatherIncome,
		 MotherName,
		 MotherDateOfBirth,
		 MotherOccupation,
		 MotherQualification,
		 MotherContactNo,
		 MotherMail,
		 MotherOfficeAddress,
		 MotherIncome,
		 
		 RelationshipName,
		 RelativeName,
		 RelativeDateOfBirth,
		 RelativeOccupation,
		 RelativeQualification,
		 RelativeContactNo,
		 RelativeMail,
		 RelativeOfficeAddress,
		 RelativeIncome,
		 CreatedUserId,
		 CreatedDateTime,
		 FatherPhoto,
		 MotherPhoto,
		 RelativePhoto
		)
	VALUES
		(
	     @rId,
		 @rFatherName,
		 @rFatherDateOfBirth,
		 @rFatherOccupation,
		 @rFatherQualification,
		 @rFatherContactNo,
		 @rFatherMail,
		 @rFatherOfficeAddress,
		 @rFatherIncome,
		 
		 @rMotherName,
		 @rMotherDateOfBirth,
		 @rMotherOccupation,
		 @rMotherQualification,
		 @rMotherContactNo,
		 @rMotherMail,
		 @rMotherOfficeAddress,
		 @rMotherIncome,
		 
		 @rRelationshipName,
		 @rGuardianName,
		 @rGuardianDateOfBirth,
		 @rGuardianOccupation,
		 @rGuardianQualification,
		 @rGuardianContactNo,
		 @rGuardianMail,
		 @rGuardianOfficeAddress,
		 @rGuardianIncome,
		 
		 @rCreatedUserId,
		 @rCreatedDateTime,
		 
		 @rFatherPhoto,
		 @rMotherPhoto,
		 @rGuardianPhoto
		)
		             
	END	 
	 ELSE
	 BEGIN

	    UPDATE  sAdmission.tAdmissionFormFamilyDetail
	    SET

	     AdmissionFormId = @rId,
		 FatherName = @rFatherName,
		 FatherDateOfBirth = @rFatherDateOfBirth,
		 FatherOccupation = @rFatherOccupation,
		 FatherQualification = @rFatherQualification,
		 FatherContactNo = @rFatherContactNo,
		 FatherMail = @rFatherMail,
		 FatherOfficeAddress = @rFatherOfficeAddress,
		 FatherIncome = @rFatherIncome,
		 MotherName = @rMotherName,
		 MotherDateOfBirth = @rMotherDateOfBirth,
		 MotherOccupation = @rMotherOccupation,
		 MotherQualification = @rMotherQualification,
		 MotherContactNo = @rMotherContactNo,
		 MotherMail = @rMotherMail,
		 MotherOfficeAddress = @rMotherOfficeAddress,
		 MotherIncome = @rMotherIncome,
		 RelationshipName = @rRelationshipName,
		 RelativeName = @rGuardianName,
		 RelativeDateOfBirth = @rGuardianDateOfBirth,
		 RelativeOccupation = @rGuardianOccupation,
		 RelativeQualification = @rGuardianQualification,
		 RelativeContactNo = @rGuardianContactNo,
		 RelativeMail = @rGuardianMail,
		 RelativeOfficeAddress = @rGuardianOfficeAddress,
		 RelativeIncome = @rGuardianIncome,
		 UpdatedUserId = @rCreatedUserId,
		 UpdatedDateTime = sCommon.fGetDate(),
		 FatherPhoto = @rFatherPhoto,
		 MotherPhoto = @rMotherPhoto,
		 RelativePhoto = @rGuardianPhoto
	        
			
	      WHERE AdmissionFormId = @rId 	   
	 END  
		SELECT @rId AS Result
	
		COMMIT TRANSACTION
		
	
	
		
END
GO
PRINT N'Altering [sAdmission].[pAdmissionFormGet]...';


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

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


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

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


GO

ALTER PROCEDURE [sAssessment].[pCCEExamSettingAdd]
	 
            @rClassId int
           ,@rCCEExamId int
		   ,@rMaxMark Decimal
		   ,@rGradeSetId Int
		   ,@rExamSubGroupId Int
		   ,@rBatchId Int,
		   @rCSgradeSetId int=0
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
BEGIN  
  BEGIN
	DELETE FROM [sAssessment].[tCCEExamSetting] WHERE CCEExamId = @rCCEExamId AND ClassId = @rClassId
 	INSERT INTO [sAssessment].[tCCEExamSetting]
			   (
			    [CCEExamId]
			   ,[ClassId]
			   ,[MaxMark]
			   ,[ExamSubGroupId]
			   ,[GradeSetId]
			   ,[BatchId],
			   CSGradeSetId
			   )
		 VALUES
			   (
			    @rCCEExamId
			   ,@rClassId
			   ,@rMaxMark
			   ,@rExamSubGroupId
			   ,@rGradeSetId
			   ,@rBatchId,
			   @rCSGradeSetId
			   )
		    SELECT 1 AS Result
	END
		--COMMIT TRANSACTION         
END	 
COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sAssessment].[pCCEExamSettingGet]...';


GO
ALTER PROCEDURE [sAssessment].[pCCEExamSettingGet]
	  @rClassId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 	
SELECT
	ISNULL(EM.ID,0) AS CCEEXAMID,
	ISNULL(CE.CLASSId,0) AS CLASSID,
	ISNULL(CE.MAXMARK,0) AS MAXMARK,
	ISNULL(CE.ExamSubGroupId,0) AS ExamSubGroupId,
	ISNULL(CE.GradeSetId,0) AS GradeSetId,
	EM.Title AS ExamName,
	ISNULL(CE.CSGradeSetId,0) AS CSGradeSetId
FROM
sAssessment.tCCEEXAMSETTING CE 
RIGHT JOIN sAssessment.tCCEEXAMMASTER EM ON EM.Id = CE.CCEExamId AND CE.CLASSId = @rClassId 
--WHERE EM.ID>=7

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


GO


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

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

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

DECLARE @lTempMark decimal(6,2)
 

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

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

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

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

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


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

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

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


GO

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


GO


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

	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 


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

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

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


GO




ALTER PROCEDURE [sAssessment].[pCCERptMyGoalsGet]
	 @rOrgId int,
	 @rBatchId int,
	 @rCCEExamId int,
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rAcademicId bigint=0,
	  @rStatus int =0 ,
	@rCode nvarchar(20)=''
	
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

	SELECT 
			
			SR.MyGoal,
			SR.MyStrength,
			Sr.MyInterestHobby,
			SR.Achievements,
			SR.AcademicId,
			Convert(nvarchar,SR.AcademicId) AS AcademicIdText,
			Convert(nvarchar,EM.Id)AS ExamIdText,
			Convert(nvarchar,@rCCEExamId) AS CCEExamIdText
		
	FROM 
			 
			
			 sAssessment.tCCEResult CCER 
			INNER JOIN sStudent.tAcademic A ON CCER.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 sActivity.tHouseMaster HM ON HM.Id=SO.HouseId
			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 
			LEFT JOIN sAssessment.tStudentRemark SR ON A. Id = SR.AcademicId AND EM. Id = SR.ExamId
			Inner Join sAssessment.tExamSubGroupMaster ESM ON ESM.Id=EM.ExamSubGroupId
	where
	 A.BatchId = @rBatchId 
		
		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=''))	
END
GO
PRINT N'Altering [sAssessment].[pExamFullGet]...';


GO
 
ALTER PROCEDURE [sAssessment].[pExamFullGet]
	 @rId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 		
					 
	SELECT 
	EM.Id,
	EM.BatchId,
	ESGM.Code,
	ESGM.Title AS Name,
	ESGM.Id AS ExamGRoupId,
	EM.ClassId,
	EM.IsRankNo,
	EM.IsGrade,
	EM.IsPercentile,
	EM.IsPercentage,
	EM.IsSubjectPercentile,
	ISNULL(EM.GradeSetId,0) AS GradeSetId,
	ISNULL(EM.RankSetId,0) AS RankSetId,
	ISNULL(EM.LevelSetId,0) AS LevelSetId ,
	CASE WHEN ISNULL(IsProcessResult,0) = 0 THEN 'false' ELSE 'true' END AS IsProcessResult,
	CASE WHEN IsNull(IsMarksInDecimal,0) = 0 THEN 'false' ELSE 'true' END AS IsMarksInDecimal,
	CASE WHEN ISNULL(ISNegativeMarks,0)=0 THEN 'false' ELSE 'true' END AS ISNegativeMarks,
	Isnull(ED.Id,0) as ExamDetailId,
	ISNULL(ED.GradeSetId,0) as GradeSetDetailId,
	ISNULL(ED.ExamId,0) as ExamId,
	ISNULL(CS.Id,0) as ClassSubjectId,
	ISNULL(ED.Maximum,0) as Maximum,
	ISNULL(ED.Minimum,0) as Minimum,
	ISNULL(ED.IsIncludeInTotal,0) as IsIncludeInTotal,
	ISNULL(ED.IsDisplayInMarksheet,0) as IsDisplayInMarksheet,
	ISNULL(ED.IsShowSubjectGrade,0) as IsShowSubjectGrade,
	ISNULL(ED.IsShowSubjectMark,1) as IsShowSubjectMark,
	
	ISNULL(ED.DisplayOrder,0) as DisplayOrder,
	ISNULL(ED.ExamDate,GETDATE()) as ExamDate,
	ISNULL(ED.ExamTime,'') as ExamTime,
	ISNULL(ED.ExamTopic,'') as ExamTopic,
	GSM.Title as GradeSET,
	EGM.Title as ExamGroup,
	ESGM.Title as ExamName,
	SM.Title as SubjectName,
	CM.DisplayTitle as ClassName,
	
	CASE WHEN ISNULL(IsOnPrePrinted,0) = 0 THEN 'false' ELSE 'true' END AS IsOnPrePrinted,
	CASE WHEN ISNULL(IsDisplayBirthDate,0) = 0 THEN 'false' ELSE 'true' END AS IsDisplayBirthDate,
	CASE WHEN ISNULL(IsDisplayPhoto,0) = 0 THEN 'false' ELSE 'true' END AS IsDisplayPhoto,
	CASE WHEN ISNULL(IsDisplaySchoolName,0) = 0 THEN 'false' ELSE 'true' END AS IsDisplaySchoolName,
	CASE WHEN ISNULL(IsLockForEdit,0) = 0 THEN 'false' ELSE 'true' END AS IsLockForEdit,
	CASE WHEN ISNULL(IsIncludeCoScholastic,0) = 0 THEN 'false' ELSE 'true' END AS IsIncludeCoScholastic,
	CASE WHEN ISNULL(IsCoScholasticGrade,0) = 0 THEN 'false' ELSE 'true' END AS IsCoScholasticGrade,
	CASE WHEN ISNULL(IsCoScholasticGradeIndicator,0) = 0 THEN 'false' ELSE 'true' END AS IsCoScholasticGradeIndicator,
	CASE WHEN ISNULL(IsCoScholasticGradeDesIndicator,0) = 0 THEN 'false' ELSE 'true' END AS IsCoScholasticGradeDesIndicator,
	
	CASE WHEN ISNULL(IsDisplayAttendance,0) = 0 THEN 'false' ELSE 'true' END AS IsDisplayAttendance,
	CASE WHEN ISNULL(IsDisplayHeightWeight,0) = 0 THEN 'false' ELSE 'true' END AS IsDisplayHeightWeight,
	CASE WHEN ISNULL(IsResultStatus,0) = 0 THEN 'false' ELSE 'true' END AS IsDisplayResultStatus,
	CASE WHEN ISNULL(IsIncludeSubExam,0) = 0 then 'false' ELSE 'true' END AS IsIncludeSubExam,
	
	CASE WHEN ISNULL(IsPublished,0) = 0 then 'false' ELSE 'true' END AS IsPublished,
	CASE WHEN ISNULL(IsDisplayHighestDivisionMark,0) = 0 then 'false' ELSE 'true' END AS IsDisplayHighestDivisionMark,
	CASE WHEN ISNULL(IsDisplayHighestDivisionGrade,0) = 0 then 'false' ELSE 'true' END AS IsDisplayHighestDivisionGrade,
	CASE WHEN ISNULL(IsDisplayGradeString,0) = 0 then 'false' ELSE 'true' END AS IsDisplayGradeString,
	
	CASE WHEN ISNULL(IsExcludeAbsentTotal,0) = 0 then 'false' ELSE 'true' END AS IsExcludeAbsentTotal,
	
	EM.Remark1,
	EM.Remark2,
	EM.Remark3,
	EM.DisplayTitle,
	ISNULL(EM.ExamMaximum,0) AS ExamMaximum,
	ISNULL(EM.FooterAdjustment,0) AS FooterAdjustment,
	ISNULL(EM.DetailAdjustment,0) AS DetailAdjustment,
	ISNULL(EM.TermScopeId,0) AS TermScopeId,	
	ISNULL(EM.ReportId,0) as ReportId,
	CASE WHEN ED.ClassSubjectId=CS.Id THEN 'true' ELSE 'false' END AS Selected,
	
	ISNULL(EM.CoScholasticScopeId,0) AS CoScholasticScopeId,
	ISNULL(EM.SubjectGroupPerPage,0) AS SubjectGroupPerPage,
	CASE WHEN ISNULL(IsDisplayParentName,0) = 0 THEN 'false' ELSE 'true' END AS IsDisplayParentName,
	CASE WHEN ISNULL(IsDisplayTeacherSign,0)=0 THEN 'false' ELSE 'true' END AS IsDisplayTeacherSign,
	CASE WHEN ISNULL(IsDisplayPrincipalSign,0)=0 THEn 'false' ELSE 'true' END AS IsDisplayPrincipalSign,
	ISNULL(EM.PercentileScopeId,0) AS PercentileScopeId,
	ISNULL(EM.CoScholasticGradeSetId,0) AS CoScholasticGradeSetId,
	ISNULL(EM.DecimalFormat,'') AS DecimalFormat,
	ISNULL(EM.IsDisplayTotalMark,0) AS IsDisplayTotalMarks,
	ISNULL(EM.IsDisplayResultIndicator,0) AS IsDisplayResultIndicator
	
	
	
  FROM 
			[sAssessment].[tExamMaster] EM
			INNER JOIN sAssessment.tExamSubGroupMaster	ESGM ON ESGM.Id = EM.ExamSubGroupId
			INNER JOIN sAssessment.tExamGroupMaster EGM ON EGM.Id=ESGM.ExamGroupId
			INNER JOIN sSetup.tClassMaster CM on CM.Id=EM.ClassId
			INNER Join sSetup.tClassSubject CS ON EM.ClassId=CS.ClassId				
			INNER JOIN sSetup.tSubjectMaster SM on   CS.SubjectId=SM.Id					
			LEFT JOIN sAssessment.tExamDetail ED ON ED.ClassSubjectId = CS.Id AND ED.ExamId=EM.Id
			LEFT Join sAssessment.tGradeSetMaster GSM ON GSM.Id = ED.GradeSetId
						
WHERE       
            EM.Id=@rId
			order by Selected Desc,DisplayOrder Asc,ESGM.Title Desc
		
END
GO
PRINT N'Altering [sAssessment].[pExamMasterAdd]...';


GO

ALTER PROCEDURE [sAssessment].[pExamMasterAdd]
	 
	        @rId int
	       ,@rBatchId int
           ,@rExamSubGroupId int           
           ,@rClassId int
           ,@rIsRankNo bit
           ,@rIsGrade bit
           ,@rIsPercentile bit
           ,@rIsPercentage bit
           ,@rIsSubjectPercentile bit
           ,@rGradeSetId int
           ,@rRankSetId int
           ,@rLevelSetId int
           ,@rIsProcessResult bit
           ,@rIsMarkInDecimal bit
           ,@rIsNegativeMarks bit
           ,@rIsPrePrinted bit
           ,@rIsDisplayBirthDate bit
           ,@rIsDisplayPhoto bit
           ,@rIsDisplayschoolName bit
           ,@rIsIncludeCoScholastic bit
           ,@rIsCoScholasticGrade bit
           ,@rIsCoScholasticGradeIndicator bit
           ,@rIsCoScholasticGradeDesIndicator bit
           ,@rIsLockForEdit bit
           ,@rRemark1 nvarchar(150)
           ,@rRemark2 nvarchar(150)
           ,@rDisplayTitle nvarchar(150)
           ,@rFooterAdjustment smallint
           ,@rReportId smallint
           ,@rRemark3 nvarchar(150)
           ,@rIsDisplayHeightWeight bit
           ,@rIsDisplayAttendance bit
           ,@rIsDisplayResultStatus bit
           ,@rDetailAdjustment smallint
           ,@rTermScopeId smallint
           ,@rMaximumMark Decimal
           ,@rIsIncludeSubExam bit
           ,@rCreatedUserId bigint
           ,@rOrgId int
           ,@rIsPublished bit
           ,@rIsDisplayHighestDivisionMark bit
           ,@rIsDisplayHighestDivisionGrade bit
           ,@rIsDisplayGradeString bit,
           @rCoScholasticScopeId tinyint,
           @rIsDisplayParentsName bit=0,
			@rSubjectGroupPerPage tinyint,
			@rIsDisplayTeacherSign bit,
			@rIsDisplayPrincipalSign bit,
			@rPercentileScope tinyint=0,
			@rCoScholasticGradeSetId int =0,
			@rIsExcludeAbsentTotal bit =0,
			@rDecimalUpto nvarchar(10),
			@rIsShowAddress bit=0,
			@rIsShowTotalMarks  bit =0,
			@rIsShowResultIndicator  bit =0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
 
	
	IF(@rId = 0)	
	BEGIN
		If Exists(select Id from sAssessment.tExamMaster where ExamSubGroupId=@rExamSubGroupId AND ClassId=@rClassId AND BatchId=@rBatchId)
			BEGIN
			select -102 as Result
			RETURN
		END 
	
		--If Exists(select Id from sAssessment.tExamMaster where ExamSubGroupId=@rExamSubGroupId and ClassId=@rClassId AND BatchId=@rBatchId)
		--	BEGIN
		--	select -103 as Result
		--	RETURN
		--END 
	END
	ELSE
	BEGIN
		If Exists(select Id from sAssessment.tExamMaster where ExamSubGroupId=@rExamSubGroupId AND ClassId=@rClassId AND BatchId=@rBatchId AND Id<>@rId)
		Begin
			select -102 as Result
			RETURN
		End
		--If  Exists(select Id from sAssessment.tExamMaster where ExamSubGroupId=@rExamSubGroupId and ClassId=@rClassId AND BatchId=@rBatchId AND Id<>@rId)
		--Begin
		--	select -103 as Result
		--	RETURN
		--End

	END
	
	
	
	 	
	 DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAssessment.tExamMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO [sAssessment].[tExamMaster]
			   (
			     Id 
				,BatchId 
				--,Code 
				--,Name 
				,ExamSubGroupId 
				,ClassId 
				,IsRankNo 
				,IsGrade 
				,IsPercentile
				,IsSubjectPercentile
				,IsPercentage
				,GradeSetId 
				,RankSetId 
				,LevelSetId
				,IsProcessResult
				,IsMarksInDecimal
				,IsNegativeMarks
				,IsOnPrePrinted
				,IsDisplayBirthDate
				,IsDisplayPhoto
				,IsDisplaySchoolName
				,IsLockForEdit
				,IsIncludeCoScholastic
				,IsCoScholasticGrade
				,IsCoScholasticGradeIndicator
				,IsCoScholasticGradeDesIndicator
				,IsDisplayAttendance
				,IsDisplayHeightWeight
				,IsResultStatus
				,Remark1
				,Remark2
				,Remark3
				,DisplayTitle
				,FooterAdjustment
				,DetailAdjustment
				,ReportId
				,TermScopeId
				,ExamMaximum
				,IsIncludeSubExam
				,UpdatedUserId
				,UpdatedDateTime
				,IsPublished
				,IsDisplayHighestDivisionMark
				,IsDisplayHighestDivisionGrade
				,IsDisplayGradeString,
				CoScholasticScopeId,
				IsDisplayParentName,
				 SubjectGroupPerPage,
				 IsdisplayTeacherSign,
				 IsDisplayPrincipalSign,
				 PercentileScopeId,
				 CoScholasticGradeSetId,
				 IsExcludeAbsentTotal,
				 DecimalFormat,
				 IsDisplayTotalMark,
				 IsDisplayResultIndicator
				  
			   )
		 VALUES
			   (
				@lNextNumber 
			   ,@rBatchId 
			   --,@rCode 
			   --,@rExamName 
			   ,@rExamSubGroupId 
			   ,@rClassId 
			   ,@rIsRankNo 
			   ,@rIsGrade 
			   ,@rIsPercentile 
			   ,@rIsSubjectPercentile
			   ,@rIsPercentage 
			   ,@rGradeSetId 
			   ,@rRankSetId 
			   ,@rLevelSetId 
			   ,@rIsProcessResult
			   ,@rIsMarkInDecimal
			   ,@rIsNegativeMarks
			   ,@rIsPrePrinted
			   ,@rIsDisplayBirthDate
			   ,@rIsDisplayPhoto
			   ,@rIsDisplayschoolName
			   ,@rIsLockForEdit
			   ,@rIsIncludeCoScholastic
			   ,@rIsCoScholasticGrade
               ,@rIsCoScholasticGradeIndicator
               ,@rIsCoScholasticGradeDesIndicator
			   ,@rIsDisplayAttendance
			   ,@rIsDisplayHeightWeight
			   ,@rIsDisplayResultStatus
			   ,@rRemark1
			   ,@rRemark2
			   ,@rRemark3
			   ,@rDisplayTitle
			   ,@rFooterAdjustment
			   ,@rDetailAdjustment
			   ,@rReportId
			   ,@rTermScopeId
			   ,@rMaximumMark
			   ,@rIsIncludeSubExam
			   ,0
			   ,sCommon.fGetDate()
			   ,@rIsPublished
			   ,@rIsDisplayHighestDivisionMark
			   ,@rIsDisplayHighestDivisionGrade
			   ,@rIsDisplayGradeString,
			   @rCoScholasticScopeId,
			   @rIsDisplayParentsName,
			   
			   
			  @rSubjectGroupPerPage ,
			  @rIsDisplayTeacherSign,
			  @rIsDisplayPrincipalSign,
			  @rPercentileScope,
			  @rCoScholasticGradeSetId,
			  @rIsExcludeAbsentTotal,
			  @rDecimalUpto,
			  @rIsShowTotalMarks,
			  @rIsShowResultIndicator
			   )
				SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION         
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  [sAssessment].[tExamMaster]
	    SET
			   -- Code =@rCode 
			   --,Name = @rExamName 
			    ExamSubGroupId =@rExamSubGroupId 
			   ,ClassId =@rClassId 
			   ,IsRankNo=@rIsRankNo 
			   ,IsGrade=@rIsGrade 
			   ,IsPercentile =@rIsPercentile 
			   ,IsSubjectPercentile = @rIsSubjectPercentile
			   ,IsPercentage=@rIsPercentage 
			   ,GradeSetId =@rGradeSetId 
			   ,RankSetId=@rRankSetId 
			   ,LevelSetId=@rLevelSetId 
			   ,IsProcessResult = @rIsProcessResult
			   ,IsMarksInDecimal = @rIsMarkInDecimal			   
			   ,IsNegativeMarks = @rIsNegativeMarks
			   
			   ,IsOnPrePrinted = @rIsPrePrinted
			   ,IsDisplayBirthDate=@rIsDisplayBirthDate
			   ,IsDisplayPhoto=@rIsDisplayPhoto
			   ,IsDisplaySchoolName=@rIsDisplayschoolName
			   ,IsIncludeCoScholastic=@rIsIncludeCoScholastic
			   ,IsCoScholasticGrade=@rIsCoScholasticGrade
			   ,IsCoScholasticGradeIndicator=@rIsCoScholasticGradeIndicator
			   ,IsCoScholasticGradeDesIndicator=@rIsCoScholasticGradeDesIndicator
			   ,IsLockForEdit=@rIsLockForEdit
			   ,IsDisplayAttendance=@rIsDisplayAttendance
			   ,IsDisplayHeightWeight=@rIsDisplayHeightWeight
			   ,IsResultStatus=@rIsDisplayResultStatus
			   ,Remark1=@rRemark1
			   ,Remark2=@rRemark2
			   ,Remark3=@rRemark3
			   ,DisplayTitle=@rDisplayTitle
			   ,FooterAdjustment=@rFooterAdjustment
			   ,DetailAdjustment=@rDetailAdjustment
			   ,ReportId = @rReportId
			   ,TermScopeId=@rTermScopeId
			   ,ExamMaximum=@rMaximumMark
			   ,IsIncludeSubExam = @rIsIncludeSubExam
			   ,UpdatedUserId=@rCreatedUserId
			   ,UpdatedDateTime=sCommon.fGetDate()          
			   ,IsPublished=@rIsPublished
			   ,IsDisplayHighestDivisionMark=@rIsDisplayHighestDivisionMark
			   ,IsDisplayHighestDivisionGrade=@rIsDisplayHighestDivisionGrade
			   ,IsDisplayGradeString=@rIsDisplayGradeString,
			   CoScholasticScopeId=@rCoScholasticScopeId,
			   IsDisplayParentName=@rIsDisplayParentsName,
			   SubjectGroupPerPage = @rSubjectGroupPerPage,
			   IsDisplayTeacherSign = @rIsDisplayTeacherSign,
			   IsDisplayPrincipalSign = @rIsDisplayPrincipalSign,
			   PercentileScopeId = @rPercentileScope,
			   CoScholasticGradeSetId=@rCoScholasticGradeSetId,
			   IsExcludeAbsentTotal = @rIsExcludeAbsentTotal,
			   DecimalFormat = @rDecimalUpto,
			   IsDisplayTotalMark = @rIsShowTotalMarks,
			   IsDisplayResultIndicator = @rIsShowResultIndicator
             
	      WHERE Id = @rId 	   
	      SELECT @lNextNumber AS Result
	
		 
	 END  	

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


GO
ALTER PROCEDURE [sAssessment].[pGradeSetDetailGet]
	 @rGradeSetId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

-- used In Sub report to display grade based on gradesetId			 

BEGIN 		
		
	SELECT 
			Convert(nvarchar(20),GMD.GradeSetId) AS  GradeSetIdText,	
			GM.TITLE,
			GM.Code,
			GMD.GradeSetId,
			GMD.Id,
			GMD.GradeCode,
			GMD.GradeTitle,
			GMD.MinimumScore,
			GMD.GradePoint,
			GM.IsObsolete,
			ISNULL(GMD.MarkRange,'') AS MarkRange,
			ISNULL(GM.GradeStringHtml,'') AS GradeStringHtml,
			ISNULL(GM.GradeStringText,'') AS GradeStringText
			
  FROM 
			[sAssessment].[tGradeSetMaster] GM
			INNER JOIN sAssessment.tGradeSetDetail GMD ON GMD.GradeSetId=GM.id
WHERE 
			(GMD.GradeSetId=@rGradeSetId)  order by GMD.MinimumScore Desc
	
		
END
GO
PRINT N'Altering [sAssessment].[pGradeSetMasterAdd]...';


GO

ALTER PROCEDURE [sAssessment].[pGradeSetMasterAdd]
	 
	        @rId int
	       ,@rCode nvarchar(20)
           ,@rTitle nvarchar(100)
           ,@rIsObsolete bit
           ,@rCreatedUserId bigint           
           ,@rOrgId int,
           @rGradeStringHtml nvarchar(500)='',
           @rGradeStringText nvarchar(500)=''
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	IF(@rId = 0)	
	BEGIN
		If Exists(select Id from sAssessment.tGradeSetMaster where Code=@rCode AND OrgId=@rOrgId)
			BEGIN
			select -102 as Result
			RETURN
		END 
	
		If Exists(select Id from sAssessment.tGradeSetMaster where Title=@rTitle AND OrgId=@rOrgId)
			BEGIN
			select -103 as Result
			RETURN
		END 
	END
	ELSE
	BEGIN
		If Exists(select Id from sAssessment.tGradeSetMaster where Code=@rCode AND OrgId=@rOrgId AND Id<>@rId)
		Begin
			select -102 as Result
			RETURN
		End
		If  Exists(select Id from sAssessment.tGradeSetMaster where Title=@rTitle AND OrgId=@rOrgId AND Id<>@rId)
		Begin
			select -103 as Result
			RETURN
		End

	END
	
	
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAssessment.tGradeSetMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO [sAssessment].[tGradeSetMaster]
			   (
			    [Id]
			   ,[Code]
			   ,[Title]
			   ,[IsObsolete]
			   ,[CreatedUserId]
			   ,[CreatedDateTime]
			   ,[UpdatedUserId]
			   ,[UpdatedDateTime]
			   ,[OrgId],
			   GradeStringHtml,
			   GradeStringText
			   )
		 VALUES
			   (
				@lNextNumber
			   ,@rCode
			   ,@rTitle
			   ,@rIsObsolete
			   ,@rCreatedUserId
			   ,sCommon.fGetDate()
			   ,0
			   ,sCommon.fGetDate()
			   ,@rOrgId,
			   @rGradeStringHtml,
			   @rGradeStringText
			   )
		    SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION         
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  [sAssessment].[tGradeSetMaster]
	    SET
			  Code=@rCode
	         ,Title=@rTitle
	         ,[IsObsolete] = @rIsObsolete                          
             ,[UpdatedUserId] = @rCreatedUserId
             ,[UpdatedDateTime] = sCommon.fGetDate(),
             GradeStringHtml =@rGradeStringHtml,
             GradeStringText = @rGradeStringText          
             
	      WHERE Id = @rId 	   
	      SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION
	 END  	

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


GO

ALTER PROCEDURE [sAssessment].[pGradeSetMasterGet]
          
           --@rId bigint,
           @rCode nvarchar(20),
           @rTitle nvarchar(100),
           @rOrgId int           
           --@rIsWildCardSearch bit
          
AS
SET NOCOUNT ON

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

BEGIN
SELECT GM.Id as GradeSetId
	  ,GM.Title as Title
	  ,GM.Code as Code
      ,GM.IsObsolete as IsObsolete,
      GM.GradeStringHtml,
      GM.GradeStringtext
     
  FROM [sAssessment].[tGradeSetMaster] GM 
        
  WHERE 
	--	 CCM.Id = @rId OR @rId = 0
	--AND 
	((GM.Title Like @rTitle)OR(ISNULL(@rTitle,'') = ''))
		AND OrgId = @rOrgId

	--AND  CCM.IsObsolete = 0
         
END
GO
PRINT N'Altering [sAssessment].[pRptCCEResultGet]...';


GO



ALTER PROCEDURE [sAssessment].[pRptCCEResultGet]
	 
	 @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,
	@rToRollNo int

	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	SELECT 
			--@rBuilder1 AS Builder1,
			--@rBuilder2 AS Builder2,
			 CONVERT (nvarchar(20),EM.GradeSetId) AS GradeSetIdText,
			  CONVERT (nvarchar(20),EM.CoScholasticGradeSetId) AS CoScholasticGradeSetIdText,
			SM.Code,
			  [sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Name,
			ISNULL(SF.FatherName,'') AS FatherName,
			ISNULL(SF.MotherName,'')AS MotherName,
			A.RollNo,
			CCER.AcademicId,
			CONVERT(NVARCHAR,CCER.AcademicId) AS AcademicIdText,
			CONVERT(NVARCHAR,EM.Id)AS ExamIdText,
			CONVERT(NVARCHAR,@rCCEExamId) AS CCEExamIdText,
			 
			 
			ISNULL(SC.ParentContactNo,'') AS ContactNo,
			ISNULL(SC.PresentStreetThree,'')+' '+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(CCER.AttendanceTerm1,0) AS AttendanceTerm1,
			ISNULL(CCER.AttendanceTerm2,0) AS AttendanceTerm2,
			ISNULL(CCER.WorkingDaysTerm1,0) AS WorkingDaysTerm1,
			ISNULL(CCER.WorkingDaysTerm2,0) AS WorkingDaysTerm2,
			ISNULL(SR.StudentHeight,0) AS Height,
			ISNULL(SR.StudentWeight,0) AS Weight,
			ISNULL(SR.VisionLeft,'') AS VisionLeft,
			ISNULL(SR.VisionRight,'') AS VisionRight,
			ISNULL(SR.DentalHygiene,'') AS DentalHygiene,
			ISNULL(BGM.Title,'') AS BloodGroup,
			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,
			'' AS GradeString,
			A.BatchId,
			BM.Title,
			SR.ResultRemark1,
			SR.ResultRemark2,
			(CASE EM.IsDisplayImageHeader WHEN 1 THEN
			OI.CertificateHeaderA4 
			ELSE NULL END)AS  MarksheetHeaderA4,
				ISNULL(EM.IsDisplayImageHeader,0) AS IsImageHeader	
			
			
			--CASE WHEN ED.ClassSubjectId=CS.Id THEN 'Yes' ELSE 'false' END AS Selected
      
	FROM 
	
			
            sAssessment.tCCEResult CCER  
            
			INNER JOIN sStudent.tAcademic A ON CCER.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 sActivity.tHouseMaster HM ON HM.Id=SO.HouseId
			LEFT JOIN sCommon.tBloodGroupMaster BGM ON BGM.Id=SO.BloodGroupId
			LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=SM.Id
			INNER JOIN sAssessment.tCCEExamSetting CE ON CE.ClassId = CM.Id AND CE.CCEExamId = @rCCEExamId AND CE.BatchId = @rBatchId 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ExamSubGroupId = CE.ExamSubGroupId AND EM.ClassId = CE.ClassId AND EM.BatchId = @rBatchId 
			Inner Join sAssessment.tExamSubGroupMaster ESM ON ESM.Id=EM.ExamSubGroupId
		 --INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id
			LEFT JOIN sSetup.tTermScopeMaster TSM ON TSM.Id = EM.TermScopeId
			LEFT JOIN sAssessment.tStudentRemark SR ON A. Id = SR.AcademicId AND EM. Id = SR.ExamId
			Inner Join sSetup.tBatchMaster BM ON BM.Id=A.BatchId
			--CROSS JOIN  sAssessment.tcceRptGroup RG ON CCER.AcademicId = RG.Id
				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(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 
END
GO
PRINT N'Altering [sAssessment].[pRptResultSheetCoScholasticSubSingleGet]...';


GO




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

BEGIN 

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


GO
 

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

BEGIN 

DECLARE @GradeString nvarchar(1000),
@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,
			Convert(nvarchar(20),EM.CoScholasticScopeId) AS CoScholasticScopeIdText,
			Convert(nvarchar(20),ISNULL(EM.IsDisplayMonthlyAttendance,0)) AS IsDisplayMonthlyAttendanceText,
			ESGM.Title AS Exam,
			StuM.Code,
			StuM.FirstName+' '+StuM.MiddleName+' '+StuM.LastName AS Name,
			A.RollNo,
			R.AcademicId,			
			R.ResultStatus,
			CM.DisplayTitle AS Class,
			DM.DisplayTitle AS Division,
			R.TotalMarks,
			R.TotalObtain,
			R.Percentage,
			R.RankNumber,
			R.ResultGrade,
			R.Percentile,			
			RD.Id AS ResultDetailId,		
			ED.IsDisplayInMarksheet,
			ED.IsShowSubjectGrade,
			ED.IsIncludeInTotal,
			RD.Obtain AS SubjectObtain,
			ED.Minimum AS SubjectMinimum,
			ED.Maximum AS SubjectMaximum,
			RD.SubjectGrade,
			SM.Code AS SubjectCode,
			SM.Title AS SubjectName,
			(CASE ISNULL(ED.DisplayOrder,0)
			WHEN 0 THEN CS.OrderIndex
			ELSE ED.DisplayOrder END) AS SubjectOrderIndex,
			R.Id AS ResultId,
			CS.Id AS SubjectId,			 	
			EM.IsMarksInDecimal,
			--SM.OrderIndex AS SubjectCode,
			
			--CS.OrderIndex AS SubjectOrderIndex,
			ISNULL(EM.Remark1,'') AS Remark1,
			ISNULL(EM.Remark2,'') AS Remark2,
			ISNULL(EM.Remark3,'') AS Remark3,
			EM.DisplayTitle,
			EM.IsRankNo, 
			EM.IsGrade,
			EM.IsPercentile,
			EM.IsPercentage,
			EM.IsSubjectPercentile,
			EM.IsProcessResult,
			EM.IsMarksInDecimal,
			EM.IsNegativeMarks,
			EM.IsIncludeCoScholastic,
			EM.IsOnPrePrinted,
			EM.IsDisplayPhoto,
			EM.IsDisplayBirthDate,
			EM.IsLockForEdit,
			EM.IsDisplaySchoolName,			
			EM.IsDisplayAttendance,
			EM.IsDisplayHeightWeight,
			EM.IsResultStatus,
			REPLICATE(',',EM.FooterAdjustment) AS FooterAdjustmentText,
			REPLICATE(',',EM.DetailAdjustment) AS DetailAdjustmentText,
			EM.FooterAdjustment,
			EM.DetailAdjustment,
			--ISNULL(R.ResultRemark,'') AS ResultRemark,
			SO.DateOfBirth,
			SR.StudentHeight,
			SR.StudentWeight,		
			SR.PresentDays,			
			SR.TotalDays,
			SR.ResultRemark1,
			SR.ResultRemark2,						 
			EM.TermScopeId,
			(CASE EM.IsDisplayPhoto WHEN 1 THEN
				SI.StudentPhoto
			ELSE NULL END) AS StudentPhoto,
			RD.IsPresent,
			@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,
			ISNULL(Emp.FirstName,'') +' ' + ISNULL(EMp.LastName,'') AS ClassTeacherName,
			BM.Title AS BatchName,
			Em.DecimalFormat
			--[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					 
			INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId
			LEFT JOIN sSetup.tOrgImages OI ON OI.Orgid = OM.Id
			LEFT JOIN sStudent.tAcademicDetail AD ON AD.AcademicId=A.Id
			INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
			LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
			LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=StuM.Id
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
			LEFT JOIN sHrm.tEmployeeMaster Emp ON Emp.Id=DM.InchargeEmployeeId
			LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = Dm.InchargeEmployeeId
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.EXAMSUBGROUPID
			LEFT JOIN sAssessment.tStudentRemark SR ON R.AcademicId = SR.AcademicId AND R.ExamId = SR.ExamId
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = StuM.Id
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.batchId
	WHERE 
			
		((EM.BatchId = @rBatchId) OR  (@rBatchId = 0))
		AND ((A.ClassId=@rClassId) OR (@rClassId=0)) 
		AND ((SM.Id=@rSubjectId) OR (@rSubjectId=0))
		AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((R.RankNumber >= @rFromRank) OR (@rFromRank=0))
		AND ((R.RankNumber <= @rToRank) OR (@rToRank=0))
		AND ((R.ResultGrade = @rGrade) OR (@rGrade=''))
		AND (R.ExamId = @rExamId)
		AND ((StuM.Code=@rCode) OR (@rCode=''))
		AND ((R.Id = @rResultId) OR (@rResultId = 0))
		AND ((StuM.StatusId=@rStatusId)OR(@rStatusId=0))
		order by A.RollNo,CS.OrderIndex 
		--AND A.id = 1005000000007
END
GO
PRINT N'Altering [sAssessment].[pRptResultSheetStandardMultiExamGet]...';


GO


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

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
 begin
 

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

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

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


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

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

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

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

 --end
GO
PRINT N'Altering [sAssessment].[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
	  
	 
	   
	 
	 
	  
	 

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
 begin
 

  
-- --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),
		
		SubActivityGrade1 nvarchar(10),
		
		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(10),
		
		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(10),
		
		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(10),
		
		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(10),
		
		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(10),
		
		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 smallint,
		PresentDays smallint,
		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(10),
		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 smallint,
		PresentDays1 smallint,
		TotalDays2 smallint,
		PresentDays2 Smallint,
		TotalDays3 smallint,
		PresentDays3 smallint,
		TotalDays4 smallint,
		PresentDays4 smallint,
		TotalDays5 smallint,
		PresentDays5 smallint,
		TotalDays6 smallint,
		PresentDays6 smallint,
		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(10)
 
	)	
	
	 --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,
	ActivityName,
	SubActivityName,
	SubActivityId,
	ActivityId,
	SubActivityGradeIndicator,
	SubActivityDescriptiveIndicator,
	SubjectActivityOrderIndex,
	SubActivityOrderIndex,
	ColumnSubjectCount,
	MarksheetHeaderA4,
	IsImageHeader,
	PresentAddress,
MobileNo
	)
	
	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,
		SI.StudentPhoto,
		@GradeString 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,
		SR.TotalDays,
		SR.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,
		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
		
		
		 
			 
			
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.vCCEExamClassSubject CS ON CS.ClassSubjectId=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  
	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 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.ExamId = R.ExamId
	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 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) ) 
		 
	 
	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	
	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,
					 SubActivityGrade' + convert(nvarchar(15),@lCount)+ '=SSA.Grade										
					 From
						sAssessment.tCCESubjectSubActivityExamScore SSA
						INNER JOIN sAssessment.tResult R ON R.AcademicId = SSA.AcademicId AND R.ExamId= SSA.ExamId
						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 = SSA.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
						
	
	 execute(@query)
	 */
	 set @query ='update T SET
					
					  Exam' + convert(nvarchar(15),@lCount)+ 'Name=ESGM.Title,
					 SubActivityGrade' + convert(nvarchar(15),@lCount)+ '=SSA.Grade				
					 						
					 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 sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId
						inner JOIN 	#TempAllExam  T ON T.SubActivityId = SSA.SubjectSubActivityId And T.AcademicId = SSA.AcademicId	 					
						WHERE EM.Id =' + 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
						LEFT JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id
						inner JOIN 	#TempAllExam  T ON T.SubActivityId = SSA.SubjectSubActivityId And T.AcademicId = SSA.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
	
	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].[pRptSubjectActivityExamDetailGet]...';


GO
 

ALTER PROCEDURE [sAssessment].[pRptSubjectActivityExamDetailGet]
	  
	   @rOrgId int=0
	  ,@rExamId int=0,
	  @rClass int=0,
	  @rDivisionId int=0,
	  @rBatchId int=0,
	  @rBuilder1 nvarchar(max)='',
	  @rAcademicId bigint=0,
	  @rCode nvarchar(20)='',
	  @rFromRollNo int=0,
	  @rToRollNo int=0
	  
	  
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON 
BEGIN 	 
	SELECT 			 
				 Convert(nvarchar(20),SA.AcademicId) AS   AcademicIdText,	
				CONVERT (nvarchar(20),@rExamId) AS ExamIdText, 
				 @rBuilder1 AS Builder1,
				 SA.AcademicId,
				 SA.RollNo,
				 SA.Number,
				 SA.Name,
			   AIS.Grade,
				 SAM.Title AS SubjectActivityTitle,
				 SSA.Title AS SubjectSubActivityTitle,
				 SAM.Id AS ActivityId,
				 SSA.Id AS SubjectSubActivityId,
				 SAM.OrderIndex AS ActivityOrderIndex,
				 SSA.OrderIndex AS SubjectSubActivityOrderIndex ,
				ISNULL(EM.Remark1,'') AS Remark1,
				ISNULL(EM.Remark2,'') AS Remark2,
				ISNULL(EM.Remark3,'') AS Remark3,
				EM.DisplayTitle,
				EM.IsRankNo, 
				EM.IsGrade, 
				EM.IsPercentile,
				EM.IsPercentage,
				EM.IsSubjectPercentile,
				EM.IsProcessResult,
				EM.IsNegativeMarks,
				EM.IsIncludeCoScholastic,
				EM.IsOnPrePrinted,
				EM.IsDisplayPhoto,
				EM.IsDisplayBirthDate,
				EM.IsLockForEdit,
				EM.IsDisplaySchoolName,			
				EM.IsDisplayAttendance,
				EM.IsDisplayHeightWeight,
				EM.IsResultStatus,
				REPLICATE(',',EM.FooterAdjustment) AS FooterAdjustmentText,
				REPLICATE(',',EM.DetailAdjustment) AS DetailAdjustmentText,
				EM.FooterAdjustment,
				EM.DetailAdjustment,
				EM.IsDisplayGradeString,
				EM.IsDisplayParentName,
				SA.FirstName + ' ' +SA.MiddleName +' ' +SA.LastName AS Name,
				SO.DateOfBirth,
				CMM.Title AS ClassName,
				SA.code,
				SR.PresentDays,			
				SR.TotalDays,
				SR.StudentHeight,
				SR.StudentWeight,
				SF.FatherName,
				SF.MotherName,
				SAM.ClassSubjectId ,
				SM.Title AS SubjectName,
				SM.OrderIndex AS SubjectOrderIndex,
				CMM.DisplayTitle AS Class,
				DM.DisplayTitle AS Division,
				SR.ResultRemark1,
				SR.ResultRemark2,						 
				SI.StudentPhoto , 
				ISNULL(AIS.DescriptiveIndicator,'') AS DescriptiveIndicator,
				 CASE WHEN CS.OrderIndex % 2 = 0 THEN 2 
				ELSE 1 END   AS   ColumnSubjectCount,
				CS.OrderIndex,
				EM.SubjectGroupPerPage,
				AIS.GradeIndicator,
				EM.IsCoScholasticGradeIndicator,
				EI.EmployeeSign,
				Em.IsDisplayPrincipalSign,
				EM.IsDisplayTeacherSign,
				EM.IsCoScholasticGradeDesIndicator,
				EM.IsCoScholasticGrade,
					Em.IsDisplayParentName,
		(CASE EM.IsDisplayImageHeader WHEN 1 THEN
			OI.CertificateHeaderA4 
			ELSE NULL END)AS  MarksheetHeaderA4,
			ISNULL(EM.IsDisplayImageHeader,0) AS IsImageHeader,
			RD.Remark,
			SR.ClassTeacherRemark,
			SR.HouseRemark,
			HM.Title AS House,
			BM.Title AS BAtch  ,
			 EMP.FirstName +' ' + EMP.LastName AS TEacherName,
			 ED.IsShowSubjectGrade
			FROM 
			 sAssessment.tCCESubjectActivityMaster SAM 	
			INNER JOIN sAssessment.tCCESubjectSubActivityMaster SSA ON SAM.Id=SSA.SubjectActivityId  
			INNER JOIN sAssessment.vCCEExamClassSubject CS ON CS.ClassSubjectId=SAM.ClassSubjectId
			INNER JOIN sSetup.tClassMaster CMM ON CMM.Id=CS.ClassId 
			INNER JOIN sStudent.vStudentAcademic SA ON  SA.ClassId = CS.ClassId 
			INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=SA.StudentId			 
			LEFT JOIN sAssessment.tCCESubjectSubActivityExamScore AIS ON AIS.AcademicId =SA.AcademicId AND AIS.SubjectSubActivityId= SSA.Id  	
			LEFT JOIN sAssessment.tExamMaster EM ON EM.Id=AIS.ExamId
			LEFT JOIN sAssessment.tExamDetail ED ON EM.Id=ED.ExamId	AND ED.ClassSubjectId = CS.ClassSubjectId 		   
		    LEFT  JOIN sStudent.tStudentOther SO ON SO.StudentId=SA.StudentId
		    LEFT JOIN sActivity.tHouseMaster HM ON HM.Id=SO.HouseId
		    LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=SA.StudentId	
		    INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId	
		    INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=SA.divisionId
		    LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = Dm.InchargeEmployeeId
	        LEFT JOIN sAcademic.tTeacherSubjectDivision TSD ON TSD.DivisionId = DM.Id AND TSD.SubjectId = SM.Id 
	        LEFT JOIN sHrm.tEmployeeMaster EMP ON EMP.Id = TSD.EmployeeId
		    LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SA.StudentId
		    LEFT JOIN sAssessment.tStudentRemark SR ON SA.AcademicId = SR.AcademicId	AND EM.Id = SR.ExamId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = Stum.OrgId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id= SA.BatchID
			LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = Om.Id
			LEFT JOIN sAssessment.tResultDetailOther RD ON RD.AcademicId = SA.AcademicId AND EM.ID=RD.ExamId AND CS.ClassSubjectId=RD.ClassSubjectID    
			 WHERE
				 ((SA.AcademicId=@rAcademicId) OR(@rAcademicId=0))
				AND 
				((CS.ClassId=@rClass) OR (@rClass=0))
				And ((SA.DivisionId =@rDivisionId) or(@rDivisionId=0))	
				And ((SA.BatchId =@rBatchId) OR (@rBatchId=0))
				and ((SA.OrgId=@rOrgId) OR (@rOrgId=0))
				And AIS.ExamId=@rExamId
				AND((STum.Code = @rCode) OR(@rCode=''))
				AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
				AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
				AND  SA.StatusId = 1
				 ORDER BY SA.RollNo
	 
END
GO
PRINT N'Altering [sAssessment].[pRptSubjectRemarkGet]...';


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

BEGIN 		


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


GO
 
 
 -- exec [sAttendance].[pAttenanceRegisterGet] '','',1,1001,6,2014,100100001,100100001,100100001,'',0,0
ALTER PROCEDURE [sAttendance].[pAttenanceRegisterGet]
 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rAttendanceTypeId smallint,
	 @rOrgId int,
	 @rForMonth smallint,
	 @rForYear smallint,
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rBatchId int = 0,
	 @rStudentCode nvarchar(20)='',
	 @rDepartmentId int = 0,
	 @rAcademicId bigint = 0,
	 @PageIndex int=0,
	 @rStatus int=0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

--Select * from sAttendance.tTempAttendance

DECLARE @lFirstDate Date
	DECLARE @lResult nvarchar(max)
	DECLARE @li int 
	SET @li=1
	SET @lFirstDate = CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'/'+CONVERT(NVARCHAR(2),@rForMonth)+'/01'))	
	
	
DECLARE @lOrgId  int
--DECLARE @lSchoolRemark1  nvarchar(500)
--DECLARE @lSchoolRemark2  nvarchar(500)
--DECLARE @lSchoolRemark3  nvarchar(500)
DECLARE @lSchoolRequiredSignature  nvarchar(500)

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

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

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

 

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

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

select * from #TempDaysTempTable
 

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


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

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

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

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

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

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

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


GO

ALTER PROCEDURE [sAttendance].[pFilterStudentGet]
	 	 
		 @rClassId int=0,
		 @rDivisionId int=0,
		 @rStudentCode nvarchar(20)='',	
	 	 @rAttendanceTypeId tinyint=0,
	     @rSubjectId int=0,
	 	 
		 @rFromAttendanceDate date='',
		 @rToAttendanceDate date='',
	 	 @rBatchId int,
	 	 @rOrgId int
	 	 ,
	 	---- @rIndicator nvarchar(20)='',
	 	 @rFilterxml nvarchar(max)='',
	 	 @rFilterCriteriaId int = 0,
	 	  @rFilterCriteriaDetailId int = 0,
		 @rStatus int=0,
		 @rIsChart int,
		 @rBuilder1 nvarchar(max)=''
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rFilterxml

BEGIN 
 
			--select * from dbo.Attendance_Temp
 
		
	CREATE TABLE #tFilterStudent
	 (  
	 AcademicId  bigint,
	 PresentCount int,
	 AbsentCount int,
	 AveragePresence Decimal(10,2),
	 FilterStatus nvarchar(20),
	 FilterStatusCode nvarchar(20),	
	 StatusColor nvarchar(20),
	 FilterStatusPoint decimal(10,2),
	 FilterCriteriaDetailId int,
 
	 TotalCount int

	 )
	 
	
    
   INSERT INTO #tFilterStudent
   	SELECT 
   	SA.Id,			
			 (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				
		) AS PresentCount, 
	  (SELECT count(AcademicId) FROM sAttendance.tStudentRegister SR	 
		WHERE		 
		 SR.AttendanceDate >= @rFromAttendanceDate
		AND SR.AttendanceDate <= @rToAttendanceDate
		AND SR.AcademicId = SA.Id
		AND SR.IsPresent = 0
		AND SR.AttendanceTypeId = @rAttendanceTypeId		
		) AS AbsentCount,
		0.0,
		'',
		'',
		'',
		0.0,
		0,
		 
		(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				
		)+(SELECT count(AcademicId) FROM sAttendance.tStudentRegister SR	 
		WHERE		 
		 SR.AttendanceDate >= @rFromAttendanceDate
		AND SR.AttendanceDate <= @rToAttendanceDate
		AND SR.AcademicId = SA.Id
		AND SR.IsPresent = 0
		AND SR.AttendanceTypeId = @rAttendanceTypeId		
		) As TotalCount
			 
			
			
  FROM 
		 sStudent.tAcademic SA 
		  INNER JOIN sStudent.tStudentMaster SM ON SM.Id=SA.StudentId         
		 
         WHERE ((SM.Code=@rStudentCode) OR (@rStudentCode=0))
         AND((SM.StatusId=@rStatus) OR (@rStatus=0))
        

 
	AND	((ClassId=@rClassId) OR (@rClassId=0))
	 AND ((DivisionId=@rDivisionId) OR (@rDivisionId=0)) 
     AND  (SA.OrgId = @rOrgId)
      AND (BatchId = @rBatchId)
  
  
      UPDATE #tFilterStudent SET AveragePresence =     CAST(PresentCount AS float)/ (CAST(PresentCount AS float) + CAST(AbsentCount AS float)) * 100 
      WHERE  ((PresentCount + AbsentCount) > 0)
      
      
      	CREATE TABLE #tempGradeSetDetail
			(
				Id INT IDENTITY (1, 1),
				MinimumScore decimal(5,2),
				GradeCode nvarchar(20),				 
				GradeTitle nvarchar(100),
				GradePoint decimal(6,2),
				HighlightColor nvarchar(50),
				FilterCriteriaDetailId int, 	 			 
			) 
			INSERT INTO #tempGradeSetDetail
			SELECT MinimumScore,GradeCode,GradeTitle,GradePoint,HighlightColor,Id	
			FROM sAttendance.tFilterCriteriaDetail where FilterCriteriaId=@rFilterCriteriaId
			
			order by MinimumScore ASC
      
      	DECLARE @lCount int
      		DECLARE @MinimumScore decimal(5,2)
      		
      		DECLARE @GradeStatus nvarchar(10)
      		DECLARE @GradeColor nvarchar(10)
      		
      		
      		DECLARE @GradeCode nvarchar(10)
		DECLARE @GradeTitle nvarchar(10)
		DECLARE @GradePoint decimal(6,2)
		DECLARE @FilterCriteriaDetailId int
      SELECT @lCount =  COUNT(Id) FROM #tempGradeSetDetail
		 
		
		 while (@lCount >0 )
	BEGIN
	SELECT
		@MinimumScore =MinimumScore,
		@GradeCode = GradeCode,
		
		@GradeStatus = GradeTitle,
		@GradeColor = HighlightColor,
		
		
		@GradeTitle=GradeTitle,
		@GradePoint=GradePoint,
		@FilterCriteriaDetailId = FilterCriteriaDetailId 
		FROM #tempGradeSetDetail WHERE Id = @lCount
		
	 UPDATE #tFilterStudent SET FilterStatus =  @GradeTitle,
	     FilterStatusCode =@GradeCode,
	     
	      FilterStatusPoint= @GradePoint,
	      StatusColor = @GradeColor,
	      
	      FilterCriteriaDetailId=@FilterCriteriaDetailId
      WHERE  AveragePresence >= @MinimumScore AND FilterStatus = ''
	
	SET @lCount = @lCount - 1
	END
	
	
        select 
			CM.Title + '-' + DM.Title AS Class,A.RollNo,
			 A.Id AS AcademicId,
			 SM.Code AS StudentCode,SM.FirstName + ' ' + SM.LastName AS Name,
		   
			FS.AveragePresence,
			FS.FilterStatus,FS.StatusColor,
			DM.Id AS DivisionId,
			DM.OrderIndex AS DivisionOrderIndex,
			@rIsChart AS IsChart,
			 @rBuilder1 AS Builder1,
			FS.FilterStatusPoint ,
			FS.PresentCount,
			FS.TotalCount
		  
				
				
			
				
				 
	   from #tFilterStudent  FS 
        INNER JOIN sStudent.tAcademic A ON A.Id=FS.AcademicId 
      
        INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId
         INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
         INNER JOIN sSetup.tDivisionMaster DM ON DM.Id= A.DivisionId
         WHERE 
         
         ((FilterCriteriaDetailId = @rFilterCriteriaDetailId) OR (@rFilterCriteriaDetailId=0))
		 
         
	 
    
END
GO
PRINT N'Altering [sAttendance].[pRepeatCountGet]...';


GO
ALTER PROCEDURE [sAttendance].[pRepeatCountGet]
	 	 
	 	 @rAttendanceDate date,
		 @rSubjectId int,
		 @rClassId int=0,
		 @rDivsionId int=0,
		 @rBatchId int = 0,
		 @rSubjectBatchId int = 0
		 
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	SELECT 
			ISNULL(MAX(RepeatCount),0) as RepeatCount
			
  FROM 
            sAttendance.tStudentRegister SR
  WHERE 
		  (SR.AttendanceDate=@rAttendanceDate)
	  AND ((SR.SubjectId=@rSubjectId) OR (@rSubjectId=0))
END
GO
PRINT N'Altering [sAttendance].[pRptDailyAttendanceList]...';


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


GO



ALTER PROCEDURE [sAttendance].[pYearlyRegisterGet]

	 
	 @rAcademicId bigint=0,
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rBatchId int=0,
	 @rAttendanceTypeId tinyint=1,
	 @rStatus int=0
	 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

SELECT 
	A.Id AS AcademicId,
	A.RollNo,
	YR.AvergeAttendance,
	YR.TotalDays,
	YR.PresentDays,
	
	YR.Month1,
	YR.PresentDays1,
	YR.TotalDays1,
	
	YR.Month2,
	YR.PresentDays2,
	YR.TotalDays2,
	
	YR.Month3,
	YR.PresentDays3,
	YR.TotalDays3,
	
	YR.Month4,
	YR.PresentDays4,
	YR.TotalDays4,
	
	YR.Month5,
	YR.PresentDays5,
	YR.TotalDays5,
	
	YR.Month6,
	YR.PresentDays6,
	YR.TotalDays6,
	
	YR.Month7,
	YR.PresentDays7,
	YR.TotalDays7,
	
	YR.Month8,
	YR.PresentDays8,
	YR.TotalDays8,
	
	YR.Month9,
	YR.PresentDays9,
	YR.TotalDays9,
	
	YR.Month10,
	YR.PresentDays10,
	YR.TotalDays10,
	
	YR.Month11,
	YR.PresentDays11,
	YR.TotalDays11,
	
	YR.Month12,
	YR.PresentDays12,
	YR.TotalDays12,
	
	SM.FirstName + ' ' + SM.LastName As Name,
	SM.StatusID
	
from
	sAttendance.tYearlyRegister YR
	INNER JOIN sStudent.tAcademic A ON A.Id=YR.AcademicId
	INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId 
where 


	((YR.AcademicId=@rAcademicId) OR (@rAcademicId=0))
	AND(A.BatchId=@rBatchId)
	AND((A.ClassId=@rClassId) OR (@rClassId=0))
	AND((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
	AND ((Sm.StatusId=@rStatus) OR (@rStatus=0))
	order by A.RollNo 
 
	 END
GO
PRINT N'Altering [sCanteen].[pCanteenIssueAdd]...';


GO

ALTER PROCEDURE [sCanteen].[pCanteenIssueAdd]
	  
	  
        @rId bigint,
        @rCanteenId int,
		@rSourceTypeId smallint,
		@rSourceId bigint,
		@rIssueDate date,
		@rTotalAmount decimal(12,2),
		@rOrgGroupId int,
		@rCreatedUserId bigint,
		@rOtherName nvarchar(100),
		@rCanteenIssueXml nvarchar(max),
		@rStudentDailySpendLimit int=0
		--@rIdOut [bigint] OUTPUT
		
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	BEGIN TRY
	
	--IF(@rId = 0)	
	--BEGIN
		
	--	If Exists(select 1 from sCanteen.tCanteenIssue where CanteenId=@rCanteenId AND Id=@rId)
	--		BEGIN
	--		select -103 as Result
	--		RETURN
	--	END 
	--END
	--ELSE
	--BEGIN
		
	--	If  Exists(select 1 from sCanteen.tCanteenIssue where CanteenId=@rCanteenId AND Id<>@rId)
	--	Begin
	--		select -103 as Result
	--		RETURN
	--	End

	--END
	IF (@rSourceTypeId=2003 AND @rStudentDailySpendLimit > 0 AND @rId = 0)
	BEGIN
	DECLARE @lSpendAmount Decimal(12,2)
	SELECT @lSpendAmount = ISNUll(SUM(TotalAmount),0) from sCanteen.tCanteenIssue where CanteenId=@rCanteenId AND SourceId=@rSourceId AND @rSourceTypeId=2003 AND IssueDate = @rIssueDate
	
	if (@lSpendAmount + @rTotalAmount > @rStudentDailySpendLimit )
	BEGIN
	SELECT -101 as Result 
	RETURN
	END
	END
	
	BEGIN TRANSACTION	
	
	 DECLARE @lNextNumber bigint

		IF(@rId = 0)	
	BEGIN
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sCanteen.tCanteenIssue', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sCanteen.tCanteenIssue
		(
			CanteenId,
			Id,	
			SourceTypeId,
			SourceId,
			IssueDate,
			TotalAmount,
			CreatedUserId,
			CreatedDateTime,
			OtherName
			
		)
	VALUES
		(
		    @rCanteenId,
			@lNextNumber,
			@rSourceTypeId,
			@rSourceId,
			@rIssueDate,
			@rTotalAmount,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rOtherName
			
		)
		
		--SELECT 1 AS Result
		  SELECT @lNextNumber AS Result
		 END 
	ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sCanteen.tCanteenIssue
	    SET
			TotalAmount=@rTotalAmount
			
	      
	      WHERE Id = @rId
	      SELECT 11 AS Result
	 END  	
		
	EXEC [sCanteen].[pCanteenIssueDetailAdd] @lNextNumber,@rCanteenIssueXml
	
	
	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
	
END
GO
PRINT N'Altering [sCanteen].[pCanteenIssueMasterGet]...';


GO
ALTER PROCEDURE [sCanteen].[pCanteenIssueMasterGet]
	
	@rId bigint = 0,
	@rCanteenId int ,
	@rFromDate date,
	@rToDate date

	--@rCode nvarchar(max)
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 SELECT 
	        CI.Id,
			CI.CanteenId,
			CI.SourceTypeId,
			CI.SourceId,
			CI.IssueDate,
			CI.TotalAmount,
			CI.CreatedDateTime,
			(CASE WHEN CI.SourceTypeId=2003 THEN  isnull(SMast.Code,'')
			WHEN  CI.SourceTypeId=95  THEN isnull(EM.Code, '') ElSE ''
			 END) AS Code,
			 (CASE WHEN CI.SourceTypeId=2003 THEN  isnull(SMast.Name,'')
			WHEN  CI.SourceTypeId=95  THEN isnull(EM.FirstName +' ' + EM.MiddleName + ' ' + EM.LastName ,'') ElSE CI.OtherName
			 END) AS Name,
			 ISNULL(CI.OtherName,'') AS OtherName,
			 (CASE WHEN CI.SourceTypeId=2003 THEN  isnull(SMast.OrgId,'')
			WHEN  CI.SourceTypeId=95  THEN isnull(EM.OrgId, '') ElSE ''
			 END) AS OrgId,
			  (CASE WHEN CI.SourceTypeId=2003 THEN  isnull(SMast.SUId,'')
			 ElSE ''
			 END) AS SUId
		
	   FROM sCanteen.tCanteenIssue CI
	   LEFT JOIN  sStudent.vStudentLastAcademic SMast ON SMast.StudentId = CI.SourceId AND CI.SourceTypeId = 2003  
       LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = CI.SourceId AND CI.SourceTypeId = 95
     
      
	  
	  WHERE ((CI.Id = @rId) OR (@rId = 0))
	  AND CI.CanteenId = @rCanteenId
	  AND ((CI.IssueDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	AND ((CI.IssueDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
	--  AND ((CI.IssueDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))

	  --EXEC [sCanteen].[pCanteenIssueDetailGet] @rId,@rCanteenId
END
GO
PRINT N'Altering [sCertificate].[pCharacterAdd]...';


GO


ALTER PROCEDURE [sCertificate].[pCharacterAdd]

			@rId bigint
	       ,@rAcademicId bigint
	       ,@rNumber int
	       ,@rCharacterDate date
	       ,@rCreatedUserId bigint
	       ,@rOrgId int
	       ,@rRemark nvarchar(200)
	       
           	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
		BEGIN TRY
		BEGIN TRANSACTION	
		
		IF(@rNumber = 0)	
		BEGIN
			SELECT @rNumber = ISNULL(MAX(Number),0) + 1 FROM sCertificate.tCharacter WHERE OrgId=@rOrgId
		END	
		
		IF(@rId = 0)	
		BEGIN
			IF EXISTS(SELECT 1 FROM sCertificate.tCharacter WHERE Number=@rNumber AND OrgId=@rOrgId)
			BEGIN
				SELECT -103 AS Result
				RETURN
			END
		END
		
	 DECLARE @lNextNumber BIGINT
 
	  IF(@rId = 0)	
		BEGIN
			EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sCertificate.tCharacter', 0, 1, 1,@outNextNumber = @lNextNumber output
			INSERT INTO sCertificate.tCharacter
			(
				Id
			   ,AcademicId
			   ,Number
			   ,characterDate
			   ,OrgId
			   ,CreatedUserId
			   ,CreatedDateTime
			   ,Remark
			)
			VALUES
			(	@lNextNumber
			   ,@rAcademicId
			   ,@rNumber
			   ,@rCharacterDate
			   ,@rOrgId
			   ,@rCreatedUserId
			   ,sCommon.fGetDate() 
			   ,@rRemark
			)
		END
		ELSE
		BEGIN
			SET @lNextNumber = @rId
			UPDATE  sCertificate.tCharacter
			SET
				AcademicId=@rAcademicId,
				characterDate=@rCharacterDate,
				UpdatedUserId=@rCreatedUserId,
				UpdatedDateTime=sCommon.fGetDate(),
				Remark=@rRemark
			  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 [sCertificate].[pCharacterGet]...';


GO

ALTER PROCEDURE [sCertificate].[pCharacterGet]
	 @rId bigint = 0,
	 @rCode nvarchar(20),
	 @rName nvarchar(200),
	 @rFromNo int,
	 @rToNo int,
	 @rFromDate date,
	 @rToDate date,
	 @rOrgId smallint,
	 @rBatchId int,
	 @rIsSearch bit = 1,
	 @rClassId int,
	 @rDivisionId int
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 IF @rIsSearch = 1
		BEGIN
			 SET @rCode = sCommon.fSearchStringGet(@rCode)
			SET @rName = sCommon.fSearchStringGet(@rName)
		END
	
	SELECT 
	
			CC.Id,
			CC.AcademicId,
			SA.Code,
			SA.Name,
			SA.ClassName+'-'+SA.DivisionName as ClassDivision,
			CC.Number,
			CC.characterDate,
			CC.Remark
  FROM 
			sCertificate.tCharacter CC
			INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=CC.AcademicId AND SA.OrgId=@rOrgId AND SA.BatchId=@rBatchId
  WHERE 
  
		((CC.Id = @rId) OR (@rId = 0))
		AND ((SA.Code like @rCode) OR (ISNULL(@rCode,'') = ''))
		AND ((SA.Name like @rName) OR (ISNULL(@rName,'') = ''))
		AND ((CC.Number >= @rFromNo) OR (@rFromNo=0))
		AND ((CC.Number <= @rToNo) OR (@rToNo=0))
		AND ((CC.characterDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((CC.characterDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		AND (SA.ClassId = @rClassId OR @rClassId = 0)
		AND (SA.DivisionId =@rDivisionId OR @rDivisionId = 0)
		ORDER BY CC.Number
END
GO
PRINT N'Altering [sCertificate].[pFirstTrialAdd]...';


GO

ALTER PROCEDURE [sCertificate].[pFirstTrialAdd]
			
			@rId bigint
	       ,@rAcademicId bigint
	       ,@rNumber int
	       ,@rFirstTrialDate date
	       ,@rExamYear nvarchar(20)
	       ,@rExamCentre nvarchar(100)
	       ,@rSeatNo nvarchar(50)
	       ,@rTrial nvarchar(20)
	       ,@rCreatedUserId bigint
	       ,@rOrgId int
	       ,@rRemark nvarchar(200)
           	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	BEGIN TRY
	BEGIN TRANSACTION	
	
		IF(@rNumber = 0)	
		BEGIN
			SELECT @rNumber = ISNULL(MAX(Number),0) + 1 FROM sCertificate.tFirstTrial WHERE OrgId=@rOrgId
		END	
			
		IF(@rId = 0)	
		BEGIN
			IF EXISTS (SELECT Id FROM sCertificate.tFirstTrial WHERE AcademicId=@rAcademicId)
			BEGIN
				SELECT -103 AS Result
				RETURN
			END
			
			IF EXISTS(SELECT 1 FROM sCertificate.tFirstTrial WHERE Number=@rNumber AND OrgId=@rOrgId)
			BEGIN
				SELECT -104 AS Result
				RETURN
			END
		END
	 
	    DECLARE @lNextNumber BIGINT
	  
	  IF(@rId = 0)	
		BEGIN
			
			EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sCertificate.tFirstTrial', 0, 1, 1,@outNextNumber = @lNextNumber output
			
			INSERT INTO sCertificate.tFirstTrial
			(
				Id
			   ,AcademicId
			   ,Number
			   ,FirstTrialDate
			   ,ExamYear
			   ,ExamCentre
			   ,SeatNo
			   ,Trial
			   ,OrgId
			   ,CreatedUserId
			   ,CreatedDateTime
			   ,Remark
			)
			VALUES
			(	@lNextNumber
			   ,@rAcademicId
			   ,@rNumber
			   ,@rFirstTrialDate
			   ,@rExamYear
			   ,@rExamCentre
			   ,@rSeatNo
			   ,@rTrial
			   ,@rOrgId
			   ,@rCreatedUserId
			   ,sCommon.fGetDate()
			   ,@rRemark 
			)		
			SELECT @lNextNumber AS Result
		END
		
		ELSE
		 BEGIN
		 IF  EXISTS(SELECT Id FROM sCertificate.tFirstTrial WHERE AcademicId=@rAcademicId AND Id<>@rId)
		BEGIN
			SELECT -103 AS Result
			RETURN
		END
		 SET @lNextNumber = @rId
			UPDATE  sCertificate.tFirstTrial
			SET
				AcademicId=@rAcademicId,
				FirstTrialDate=@rFirstTrialDate,
				ExamYear=@rExamYear,
				ExamCentre=@rExamCentre,
				SeatNo=@rSeatNo,
				Trial=@rTrial,
				UpdatedUserId=@rCreatedUserId,
				UpdatedDateTime=sCommon.fGetDate(),
				Remark=@rRemark
			  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 [sCertificate].[pFirstTrialGet]...';


GO
ALTER PROCEDURE [sCertificate].[pFirstTrialGet]
	 @rId bigint = 0,
	 @rCode nvarchar(20),
	 @rName nvarchar(200),
	 @rClassId int,
	 @rDivisionId int,
	 @rFromNo int,
	 @rToNo int,
	 @rFromDate date,
	 @rToDate date,
	 @rOrgId smallint,
	 @rBatchId int,
	 @rIsSearch bit = 1
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 IF @rIsSearch = 1
		BEGIN
			SET @rCode = sCommon.fSearchStringGet(@rCode)
			SET @rName = sCommon.fSearchStringGet(@rName)
		END
	
	SELECT 
	
			FT.Id,
			FT.AcademicId,
			SA.Code,
			SA.Name,
			SA.ClassName+'-'+SA.DivisionName as ClassDivision,
			FT.Number,
			FT.FirstTrialDate,
			FT.ExamYear,
			FT.ExamCentre,
			FT.SeatNo,
			FT.Trial,
			FT.Remark
  FROM 
            sCertificate.tFirstTrial FT
       INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=FT.AcademicId
			AND SA.OrgId=@rOrgId AND SA.BatchId=@rBatchId
  WHERE 
  
      ((FT.Id = @rId) OR (@rId = 0))
     
      AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
      AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
       AND ((SA.Code like @rCode) OR (ISNULL(@rCode,'') = ''))
	AND ((SA.Name like @rName) OR (ISNULL(@rName,'') = ''))
    AND ((FT.FirstTrialDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	AND ((FT.FirstTrialDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
	AND ((FT.Number >= @rFromNo) OR (@rFromNo=0))
	AND ((FT.Number <= @rToNo) OR (@rToNo = 0))
	
	ORDER BY FT.Number
END
GO
PRINT N'Altering [sCertificate].[pLeavingAdd]...';


GO

ALTER PROCEDURE [sCertificate].[pLeavingAdd]
			
			@rId bigint
	       ,@rAcademicId bigint
	       ,@rLCNumber int
	       ,@rLCDate date
	       ,@rLeftDate date
	       ,@rLCCopy tinyint
	       ,@rLCRemark nvarchar(200)
	       ,@rLCProgress nvarchar(200)
	       ,@rLCConduct nvarchar(200)
	       ,@rLCReason nvarchar(200)
	       ,@rLCBookNumber nvarchar(20)
	       ,@rCreatedUserId bigint
	       ,@rOrgId int
	       ,@rToCollege nvarchar(200)
		   ,@rToCollegeAddress nvarchar(200)
		   ,@rLastExamName nvarchar(200)
		   ,@rLastExamResult nvarchar(200)
		   ,@rRepeatDetail nvarchar(100)
		   ,@rSubjectStudied nvarchar(300)
		   ,@rPromoteToClass nvarchar(50)
		   ,@rFeeDetail nvarchar(100)
		   ,@rFeeConcessionDetail nvarchar(100)
		   ,@rExtraCurricularActivities nvarchar(200)
		   ,@rNCCScoutDetail nvarchar(100)
           	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	BEGIN TRY
	
	 DECLARE @lNextNumber BIGINT
	 DECLARE @lStudentId bigint
	 DECLARE @lClassId bigint
	 DECLARE @lAdmissionDate Date
	 
	 SELECT @lStudentId=StudentId,@lClassId=ClassId FROM sStudent.tAcademic WHERE Id=@rAcademicId
	 
		IF(@rLCNumber = 0)	
		BEGIN
			SELECT @rLCNumber = ISNULL(MAX(LCNumber),0) + 1 FROM sCertificate.tLeaving WHERE OrgId=@rOrgId
		END	
	 
		IF(@rId = 0)	
		BEGIN
			IF EXISTS (SELECT Id FROM sCertificate.tLeaving WHERE AcademicId = @rAcademicId )-- IN(SELECT Id FROM sStudent.tAcademic WHERE StudentId=@lStudentId))
			BEGIN
				SELECT -103 AS Result
				RETURN
			END
			
			IF EXISTS(SELECT 1 FROM sCertificate.tLeaving WHERE LCNumber=@rLCNumber AND OrgId=@rOrgId)
			BEGIN
				SELECT -104 AS Result
				RETURN
			END
			
			IF EXISTS(SELECT 1 FROM sAttendance.tStudentRegister WHERE AttendanceDate>@rLeftDate AND AcademicId=@rAcademicId)
			BEGIN
				SELECT -101 AS Result
				RETURN
			END
			
			SELECT @lAdmissionDate = AdmissionDate FROM sStudent.tStudentAdmission WHERE StudentId=@lStudentId
			IF EXISTS(SELECT 1 FROM sAttendance.tStudentRegister WHERE @lAdmissionDate > @rLCDate AND AcademicId=@rAcademicId)
			BEGIN
				SELECT -105 AS Result
				RETURN
			END
			
		END
		ELSE
		BEGIN
			IF EXISTS(SELECT Id FROM sCertificate.tLeaving WHERE AcademicId=@rAcademicId AND Id<>@rId)
			BEGIN
				SELECT -103 AS Result
				RETURN
			END
		END
		
		BEGIN TRANSACTION	
			
		IF(@rId = 0)	
		BEGIN
				EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sCertificate.tLeaving', 0, 1, 1,@outNextNumber = @lNextNumber output
				INSERT INTO sCertificate.tLeaving
				(
					Id
				   ,AcademicId
				   ,LCNumber
				   ,LCDate
				   ,LeftDate
				   ,LCCopy
				   ,LCRemark
				   ,LCProgress
				   ,LCConduct
				   ,LCReason
				   ,LCBookNumber
				   ,OrgId
				   ,CreatedUserId
				   ,CreatedDateTime
				   ,ToCollege
				   ,ToCollegeAddress
				   ,LastExamName 
		           ,LastExamResult 
		           ,RepeatDetail 
		           ,SubjectStudied
		           ,PromoteToClass 
		           ,FeeDetail 
		           ,FeeConcessionDetail
		           ,ExtraCurricularActivities
		           ,NCCScoutDetail 
				   
				)
				VALUES
				(	@lNextNumber
				   ,@rAcademicId
				   ,@rLCNumber
				   ,@rLCDate
				   ,@rLeftDate
				   ,@rLCCopy
				   ,@rLCRemark
				   ,@rLCProgress
				   ,@rLCConduct
				   ,@rLCReason
				   ,@rLCBookNumber
				   ,@rOrgId
				   ,@rCreatedUserId
				   ,sCommon.fGetDate() 
				   ,@rToCollege
				   ,@rToCollegeAddress
				   ,@rLastExamName 
		           ,@rLastExamResult 
		           ,@rRepeatDetail 
		           ,@rSubjectStudied
		           ,@rPromoteToClass 
		           ,@rFeeDetail 
		           ,@rFeeConcessionDetail
		           ,@rExtraCurricularActivities
		           ,@rNCCScoutDetail 
				)	
				SELECT @lNextNumber AS Result 
				 
		END
		
		ELSE
		
		BEGIN
		
			 
			 SET @lNextNumber = @rId
				UPDATE  sCertificate.tLeaving
				SET
					AcademicId=@rAcademicId,
					LCDate=@rLCDate,
					LeftDate=@rLeftDate,
					LCCopy=@rLCCopy,
					LCRemark=@rLCRemark,
					LCProgress=@rLCProgress,
					LCConduct=@rLCConduct,
					LCReason=@rLCReason,
					LCBookNumber=@rLCBookNumber,
					UpdatedUserId=@rCreatedUserId,
					UpdatedDateTime=sCommon.fGetDate(),
					ToCollege=@rToCollege,
				    ToCollegeAddress=@rToCollegeAddress,
				    LastExamName=@rLastExamName 
				    ,LastExamResult=@rLastExamResult 
				    ,RepeatDetail=@rRepeatDetail 
				    ,SubjectStudied=@rSubjectStudied
				    ,PromoteToClass=@rPromoteToClass 
				    ,FeeDetail=@rFeeDetail 
				    ,FeeConcessionDetail=@rFeeConcessionDetail
				    ,ExtraCurricularActivities=@rExtraCurricularActivities
				    ,NCCScoutDetail=@rNCCScoutDetail 
				WHERE Id = @rId
				
		 
		END 
		
		
						UPDATE sStudent.tStudentAdmission
				SET
				  LeftStandardId=@lClassId,
				  LeftDate = @rLeftDate, 
				  LeftReason = @rLCReason, 
				  LCProgress = @rLCProgress,
				  LCConduct = @rLCConduct, 
				  LCBook = @rLCBookNumber, 
				  LCNumber = @rLCNumber,
				  LCDate = @rLCDate, 
				  LCRemark = @rLCRemark, 
				  LCCopy = @rLCCopy, 
				  LcId = @lNextNumber, 
				  UpdatedUserId = @rCreatedUserId, 
				  UpdatedDateTime =sCommon.fGetDate()
				WHERE StudentId = @lStudentId 
				
				UPDATE sStudent.tStudentMaster
				SET
				  StatusId=3,
				  UpdatedUserId = @rCreatedUserId, 
				  UpdatedDateTime =sCommon.fGetDate()
				WHERE Id = @lStudentId 
		 COMMIT TRANSACTION		
		  SELECT @lNextNumber AS Result
	
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
	
END
GO
PRINT N'Altering [sCertificate].[pLeavingGet]...';


GO
ALTER PROCEDURE [sCertificate].[pLeavingGet]
	 
	 @rId bigint = 0,
	 @rCode nvarchar(20),
	 @rName nvarchar(200),
	 @rFromNo int,
	 @rToNo int,
	 @rClassId int,
	 @rDivisionId int,
	 @rFromDate date,
	 @rToDate date,
	 @rOrgId smallint,
	 @rBatchId int,
	 @rIsSearch bit = 1
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 IF @rIsSearch = 1
		BEGIN
			SET @rCode = sCommon.fSearchStringGet(@rCode)
			SET @rName = sCommon.fSearchStringGet(@rName)
		END
	
	SELECT 
	
			L.Id,
			L.AcademicId,
			SA.Code,
			SA.Name,
			SA.ClassName+'-'+SA.DivisionName as ClassDivision,
			L.LCNumber,
			L.LCDate,
			L.LeftDate,
			L.LCCopy,
			L.LCRemark,
			L.LCProgress,
			L.LCConduct,
			L.LCReason,
			L.LCBookNumber,
			L.ToCollege,
			L.ToCollegeAddress
			,L.LastExamName 
		    ,L.LastExamResult 
		    ,L.RepeatDetail 
		    ,L.SubjectStudied
		    ,L.PromoteToClass 
		    ,L.FeeDetail 
		    ,L.FeeConcessionDetail
		    ,L.ExtraCurricularActivities
		    ,L.NCCScoutDetail 
		
  FROM 
			sCertificate.tLeaving L
			INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=L.AcademicId
			AND SA.OrgId=@rOrgId AND SA.BatchId=@rBatchId
  WHERE 
			((L.Id = @rId) OR (@rId = 0))
			AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
			AND ((SA.DivisionId =@rDivisionId) OR (@rDivisionId = 0))
			AND ((SA.Code like @rCode) OR (ISNULL(@rCode,'') = ''))
			AND ((SA.Name like @rName) OR (ISNULL(@rName,'') = ''))
			AND ((L.LCDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((L.LCDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND ((L.LCNumber >= @rFromNo) OR (@rFromNo = 0))
			AND ((L.LCNumber <= @rToNo) OR (@rToNo = 0))
			ORDER BY L.LCNumber
END
GO
PRINT N'Altering [sCertificate].[pPrintTemplateAdd]...';


GO
ALTER PROCEDURE [sCertificate].[pPrintTemplateAdd]
	 
        @rId int,
        @rTitle nvarchar(100),
        @rTemplate nvarchar(max),
        @rOrgId smallint,
        @rCreatedUserId bigint,
        @rTemplateSourceId tinyint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	IF(@rId = 0)	
	BEGIN
		--If Exists(select Id from sCommunication.tNews where Code=@rCode AND OrgGroupBatchId=@rOrgGroupBatchId)
		--	BEGIN
		--	select -102 as Result
		--	RETURN
		--END 
	
		If Exists(select Id from sCertificate.tPrintTemplate where Title=@rTitle AND OrgId=@rOrgId)
			BEGIN
			select -103 as Result
			RETURN
		END 
	END
	ELSE
	BEGIN
		--If Exists(select Id from sCommunication.tNews where Code=@rCode AND OrgGroupBatchId=@rOrgGroupBatchId AND Id<>@rId)
		--Begin
		--	select -102 as Result
		--	RETURN
		--End
		If  Exists(select Id from sCertificate.tPrintTemplate where Title=@rTitle AND OrgId=@rOrgId AND Id<>@rId)
		Begin
			select -103 as Result
			RETURN
		End

	END
	
	
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sCertificate.tPrintTemplate', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sCertificate.tPrintTemplate
		(
			Id,
			Title,
			Template,
			OrgId,
			CreatedUserId,
			CreatedDateTime,
			TemplateSourceId
		)
	VALUES
		(
			@lNextNumber,
			@rTitle,
			@rTemplate,
			@rOrgId,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rTemplateSourceId
		)
		    SELECT 1 AS Result
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sCertificate.tPrintTemplate
	    SET
			Title=@rTitle,
			Template=@rTemplate,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate()
	      
	      WHERE Id = @rId
	      SELECT 11 AS Result
	 END  	

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


GO
 


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

DECLARE @lIsDisplayImageHeader bit = 0

DECLARE @lConfigValue nvarchar(50)

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

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


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

DECLARE @lSchoolRemark1  nvarchar(500)
DECLARE @lSchoolRemark2  nvarchar(500)
DECLARE @lSchoolRemark3  nvarchar(500)
DECLARE @lSchoolRequiredSignature  nvarchar(500)

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


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


GO


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

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


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

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

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

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

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

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

DELETE FROM sTimetable.tAssignOrg WHERE OrgId = @rOrgId

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

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

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

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

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

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

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

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

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

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

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

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


GO

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

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




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

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

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


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

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

DELETE FROM sStudent.tCustomTagMaster WHERE OrgGroupId = @rOrgGroupId

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	-- special case will come orgwise and orggroupwise

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



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

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


GO

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


GO
ALTER PROCEDURE [sCommunication].[pAssignmentListGet]
	 @rBatchId int,
	 @rUserId bigint,
	 @rUserSourceId bigint,
	 @rUserSourceTypeId int,
	 @rSyncedAssignmentId bigint = 0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	
	if @rUserSourceTypeId   = 2003 -- For Student Login
	
	BEGIN
	
	
 	SELECT 	
			A1.Id as AssignmentId,
			A1.SubjectId,
			SM.Title as SubjectName,
			A1.Title,
			A1.Remark,
			A1.StartDate,
			A1.EndDate,
			ISNULL(AV.UserId,0) AS UserId,
			U.DisplayTitle as CreatedUserName,
			SM.OrgId
	 FROM 
            sCommunication.tAssignment A1       
            INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=A1.SubjectId 
            LEFT JOIN sCommunication.tAssignmentView AV ON AV.AssignmentId=A1.Id AND UserId=@rUserId     
            INNER JOIN sCommunication.tAssignmentScope AS1 ON AS1.AssignmentId=A1.Id 
            INNER JOIN ( SELECT A.DivisionId FROM sStudent.tAcademic A 
            WHERE A.StudentId = @rUserSourceId  AND A.BatchId = @rBatchId) D
            ON D.DivisionId =  AS1.SourceId AND AS1.SourceTypeId = 2005
            INNER JOIN sSecurity.tUser U ON U.Id=A1.CreatedUserId   
             WHERE 	 A1.BatchId=@rBatchId 
             AND ( A1.Id > @rSyncedAssignmentId OR @rSyncedAssignmentId = 0)
             Order by A1.CreatedDateTime DESC 
					

	
 END
 ELSE 
 BEGIN
 --IF @rUserSourceTypeId   = 2003 -- For Student Login
 	SELECT 	
			A1.Id as AssignmentId,
			A1.SubjectId,
			SM.Title as SubjectName,
			A1.Title,
			A1.Remark,
			A1.StartDate,
			A1.EndDate,
			ISNULL(AV.UserId,0) AS UserId,
			U.DisplayTitle as CreatedUserName,
			SM.OrgId
	 FROM 
            sCommunication.tAssignment A1 
            INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=A1.SubjectId 
            LEFT JOIN sCommunication.tAssignmentView AV ON AV.AssignmentId=A1.Id AND UserId=@rUserId           
            INNER JOIN sCommunication.tAssignmentScope AS1 ON AS1.AssignmentId=A1.Id 
            INNER JOIN ( SELECT EJD.OrganizationDepartmentId FROM sHrm.tEmployeeMaster EM
            INNER JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id = EJD.EmployeeId
             WHERE EM.Id = @rUserSourceId) D
            ON D.OrganizationDepartmentId =  AS1.SourceId AND AS1.SourceTypeId = 2017
             INNER JOIN sSecurity.tUser U ON U.Id=A1.CreatedUserId   
             WHERE 	 A1.BatchId=@rBatchId 
               AND ( A1.Id > @rSyncedAssignmentId OR @rSyncedAssignmentId = 0)
					Order by A1.CreatedDateTime DESC
             
 END
 END
GO
PRINT N'Altering [sCommunication].[pAssignmentScopeGet]...';


GO
ALTER PROCEDURE [sCommunication].[pAssignmentScopeGet]
	 @rAssignmentId bigint,
	 @rOrgId smallint
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 		
		
	SELECT 
			DM.Id  as SourceId,
			CM.Title+'-'+DM.Title as ClassDept,
			2005 as SourceTypeId,
			CASE WHEN CS.SourceId IS NULL OR CS.AssignmentId!=@rAssignmentId THEN 0 ELSE 1 END AS IsObsolete,
			CM.OrderIndex+DM.OrderIndex AS OrderIndex
  FROM 
			sSetup.tDivisionMaster DM
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=DM.ClassId AND CM.OrgId=@rOrgId
			LEFT JOIN sCommunication.tAssignmentScope CS ON CS.SourceId=DM.Id AND CS.SourceTypeId=2005 AND CS.AssignmentId=@rAssignmentId
	where DM.OrgId=@rOrgId
		UNION ALL
	SELECT 
			ODM.Id  as SourceId,
			ODM.Title as ClassDept,
			2017 as SourceTypeId,
			CASE WHEN CS.SourceId IS NULL OR CS.AssignmentId!=@rAssignmentId THEN 0 ELSE 1 END AS IsObsolete,
			0 AS OrderIndex
  FROM 
			sSetup.tDepartmentMaster ODM 
			LEFT JOIN sCommunication.tAssignmentScope CS ON CS.SourceId=ODM.Id AND CS.SourceTypeId=2017 AND CS.AssignmentId=@rAssignmentId
	where ODM.OrgId=@rOrgId
END
GO
PRINT N'Altering [sCommunication].[pQueryCategoryAssignedToDelete]...';


GO

ALTER PROCEDURE [sCommunication].[pQueryCategoryAssignedToDelete]
	 
	 @rSourceId bigint,
	 @rQueryCategoryId int
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 
	BEGIN TRY
		BEGIN TRANSACTION
			DELETE FROM sCommunication.tQueryCategoryAssignedTo WHERE SourceId=@rSourceId AND QueryCategoryId = @rQueryCategoryId
			SELECT 1 AS Result
		COMMIT TRANSACTION
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
			SELECT -1 AS Result
	END CATCH	
END
GO
PRINT N'Altering [sCommunication].[pQueryCloseUpdate]...';


GO

ALTER PROCEDURE [sCommunication].[pQueryCloseUpdate]
	 
	@rQueryId bigint,
	@rStatusId tinyint
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
		
BEGIN 
		UPDATE sCommunication.tQuery SET StatusId=@rStatusId WHERE Id=@rQueryId
		SELECT 1 Result
END
GO
PRINT N'Altering [sCommunication].[pStudentPresenceGet]...';


GO
ALTER PROCEDURE [sCommunication].[pStudentPresenceGet]	 	 
	   @rUserSourceId bigint,
	   @rBatchId int,
	   @rMonth int=0,
	   @rYear int=0
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
 IF @rUserSourceId <> 0
 Begin	
	Select 
		MR.AcademicId,
		ForMonth,
		DATENAME(m,STR(ForMonth) + '/1/2014') + '-' + Convert(NVarchar(5),ForYear) AS ForMonthInWord,
		ForYear,
		TotalCount,
		PresentCount,
		AbsentCount,
		ISNULL(AveragePresence,0) AS AveragePresence,
		AbsentDays		
	From 
		sAttendance.tMonthlyRegister MR  INNER JOIN sStudent.tAcademic SA 
		ON SA.Id = MR.AcademicId AND (SA.StudentId  = @rUserSourceId)
		INNER JOIN sSetup.fMonthYearForBatchGET(@rBatchId) AS MY ON
		MR.ForMonth = MY.MonthNumber AND MR.ForYear = MY.YearNumber
		Where MR.ForMonth = @rMonth AND MR.ForYear=@rYear
	ORDER BY
	MR.AcademicId
	 ,MY.YearNumber ,MY.MonthNumber
END
end
GO
PRINT N'Altering [sCommunication].[pViewResultDelete]...';


GO
ALTER PROCEDURE [sCommunication].[pViewResultDelete]

	@rOrgId int,
	@rBatchId int,
	@rClassId int,
	@rDivisionId int,
	@rCode nvarchar(20)='',
	@rName nvarchar(100)='',
	@rExamName nvarchar(150),
	@rAcademicId bigint,
	@rExamId int,
	@rExamTypeId tinyint,
	@rResultId bigint
	
	
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
		
		SET @rName = sCommon.fSearchStringGet(@rName)
		SET @rExamName = sCommon.fSearchStringGet(@rExamName)
	
		DELETE VRD
		FROM sCommunication.tViewResultDetail VRD
		INNER JOIN sCommunication.tViewResult VR ON VR.ExamId=VRD.ExamId
		AND VR.ResultId=VRD.ResultId AND VR.ExamTypeId=VRD.ExamTypeId
		INNER JOIN sStudent.vStudentAcademic vSA ON vSA.AcademicId = VR.AcademicId
		WHERE 
		(vSA.OrgId=@rOrgId)	
		AND (vSA.BatchId=@rBatchId)
		AND (VR.AcademicId=@rAcademicId)
		AND (VR.ExamId=@rExamId)
		AND (VR.ExamTypeId=@rExamTypeId)
		AND (VR.ResultId=@rResultId)
		
		
		AND ((vSA.ClassId=@rClassId) OR (@rClassId=0))
		AND ((vSA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((VR.ExamName Like @rExamName) OR (ISNULL(@rExamName,'')=''))
		AND ((vSA.Name Like @rName) OR (ISNULL(@rName,'')=''))
	    AND ((vSA.Code=@rCode) OR (ISNULL(@rCode,'')=''))

		
		DELETE VR
		FROM sCommunication.tViewResult VR
		INNER JOIN sStudent.vStudentAcademic vSA ON vSA.AcademicId = VR.AcademicId
		WHERE 
		(vSA.OrgId=@rOrgId)	
		AND (vSA.BatchId=@rBatchId)
		AND (VR.AcademicId=@rAcademicId)
		AND (VR.ExamId=@rExamId)
		AND (VR.ExamTypeId=@rExamTypeId)
		AND (VR.ResultId=@rResultId)
		AND ((vSA.ClassId=@rClassId) OR (@rClassId=0))
		AND ((vSA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((VR.ExamName Like @rExamName) OR (ISNULL(@rExamName,'')=''))
		AND ((vSA.Name Like @rName) OR (ISNULL(@rName,'')=''))
	    AND ((vSA.Code=@rCode) OR (ISNULL(@rCode,'')=''))

		SELECT 1 AS RESULT
END
GO
PRINT N'Altering [sConfig].[pBackupDetailAdd]...';


GO
ALTER PROCEDURE [sConfig].[pBackupDetailAdd]
	 
	@rId bigint,
	@rDatabaseId tinyint,
	@rDatabaseName nvarchar(100),
	@rBackupPath nvarchar(200),
	@rCreatedUserId bigint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
-- IF(@rId = 0)	
--BEGIN

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


--	INSERT INTO sSetup.tBatchMaster
--		(
--			Id,
--			Code,
--			Title,
--			OrgId,
--			IsHistory,
--			IsObsolete,
--			OrderIndex,
--			FromDate,
--			ToDate,
--			CreatedUserId,
--			CreatedDateTime
			
--		)
--	VALUES
--		(
--			@lNextNumber,
--			@rCode,
--			@rTitle,
--			@rOrgId,
--			@rIsHistory,
--			@rIsObsolete,
--			@rOrderIndex,
--			@rFromDate,
--			@rToDate,
--			@rCreatedUserId,
--			sCommon.fGetDate()
			
--		)
		             
--	END	 
--	 ELSE
--	 BEGIN
	 SET @lNextNumber = @rId
	 
		UPDATE  sConfig.tDatabaseSetting
	    SET
			BackupPath=@rBackupPath,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate(),
	        Backupdatetime=sCommon.fGetDate()
	      WHERE Id = @rDatabaseId 	  
		
	    UPDATE  sConfig.tDatabase
	    SET
			Title=@rDatabaseName
			
	      WHERE Id = @rDatabaseId 	   
	 --END  
		SELECT @lNextNumber AS Result
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sConfig].[pConfigurationSetupAdd]...';


GO
ALTER PROCEDURE [sConfig].[pConfigurationSetupAdd]
	 
	@rConfigurationId [int],
	@rItemValue nvarchar(200),
	@rSourceTypeId [int],
	@rSourceId [bigint],
	@rCreatedUserId [bigint],
	@rOrgId int
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

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

 IF NOT EXISTS(Select 1 From sConfig.tConfigurationSetup Where ConfigurationId = @rConfigurationId AND SourceId = @rSourceId AND SourceTypeId=@rSourceTypeId)
  
   BEGIN
	INSERT INTO [sConfig].[tConfigurationSetup]
           ([Id]
           ,[ConfigurationId]
           ,[ItemValue]
           ,[sourceTypeId]
           ,[SourceId]
           ,[CreatedUserId]
           ,[CreatedDateTime]        
            )
     VALUES
           (
            @lNextNumber,
            @rConfigurationId,
            @rItemValue,
            @rSourceTypeId,
            @rSourceId,
            @rCreatedUserId,
            sCommon.fGetDate()
            )
          select 1 as result
   END
  ELSE
   BEGIN
      UPDATE sConfig.tConfigurationSetup 
          SET ItemValue = @rItemValue,
          UpdatedUserId = @rCreatedUserId,
          UpdatedDateTime =  sCommon.fGetDate()
          
       Where ConfigurationId  = @rConfigurationId AND SourceId=@rSourceId AND SourceTypeId=@rSourceTypeId
		Select 11 as result
   END       
           
END
GO
PRINT N'Altering [sFee].[pCollectionGroupMasterAdd]...';


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

	END
	
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

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

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sFee.tCollectionGroupMaster
	    SET
			Code=@rCode,
			Title=@rTitle,
			StartDate=@rStartDate,
			EndDate=@rEndDate,
			Remark=@rRemark,
			IsObsolete=@rIsObsolete,
			OrderIndex=@rOrderIndex,
			ReceiptBookId=@rReceiptBookId,
			FooterRemark1=@rFooterRemark1,
			FooterRemark2=@rFooterRemark2,
			FeePeriod=@rFeePeriod,
			IsDisplayCashDetailInFolio=@rIsDisplayCashDetailInFolio,
	        ReportId=@rReportId,
	        IsOnPrePrinted=@rIsOnPrePrinted
	      WHERE Id = @rId
	      SELECT 11 AS Result
	 END  	

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


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

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


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

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


GO

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

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

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

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


GO

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


GO

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


GO

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


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

SET NOCOUNT ON

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

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


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

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


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

DECLARE @lStudentId bigint

BEGIN	
BEGIN TRY
BEGIN TRANSACTION	

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


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

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

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

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


GO

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

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


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

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

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

DELETE FO FROM sFee.tFeeOptional FO
INNER JOIN sFee.tFeeSetup FS ON FS.Id = FO.FeeSetupId
INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id 	 
INNER JOIN sFee.tFeeHeadMaster FHM ON FM.FeeHeadId = FHM.Id
WHERE  
FHM.Number = 1002
AND FHM.OrgGroupId = @rOrgGroupId
AND FS.BatchId = @rBatchId
AND FS.IsVariable = 1
AND FS.IsOptional = 1


MERGE sFee.tFeeOptional FO
USING #TempHostelFee RD
ON FO.FeeSetupId = RD.FeeSetupId AND FO.SourceTypeId = 2001 AND FO.SourceId = RD.AcademicId
--WHEN MATCHED AND
--  bi.Quantity + bo.Quantity = 0 THEN
--  DELETE
--WHEN MATCHED THEN
--  UPDATE
--  SET FA.VariableAmount = RD.Amount
WHEN NOT MATCHED BY TARGET THEN
INSERT (FeeSetupId,SourceTypeId,SourceId,BatchId)   
 VALUES (RD.FeeSetupId,2001, RD.AcademicId,@rBatchId )
-- WHEN NOT MATCHED  BY SOURCE   THEN
--DELETE 
;




	 	 
MERGE sFee.tFeeAllocation FA
USING #TempHostelFee RD
ON FA.FeeSetupId = RD.FeeSetupId AND FA.SourceTypeId = 2001 AND FA.SourceId = RD.AcademicId
--WHEN MATCHED AND
--  bi.Quantity + bo.Quantity = 0 THEN
--  DELETE
WHEN MATCHED AND RD.ReceiptAmount <= RD.Amount  THEN
  UPDATE
  SET FA.VariableAmount = RD.Amount
WHEN NOT MATCHED BY TARGET THEN
  INSERT (SourceTypeId, SourceId, FeeSetupId,VariableAmount,DiscountAmount,AdditionalAmount,NotApplicableAmount,Remark,ReferenceTypeId,ReferenceSourceId,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime)
  VALUES (2001, RD.AcademicId,RD.FeeSetupId,RD.Amount,0,0,0,'',0,0,@rCreatedUserId,getdate(),@rCreatedUserId,getdate())
--WHEN NOT MATCHED BY SOURCE THEN
--DELETE
;

DELETE FA FROM sFee.tFeeAllocation FA
INNER JOIN sFee.tFeeSetup FS ON FS.Id = FA.FeeSetupId
INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id 	 
INNER JOIN sFee.tFeeHeadMaster FHM ON FM.FeeHeadId = FHM.Id
WHERE  
FHM.Number = 1002
AND FHM.OrgGroupId = @rOrgGroupId
AND FS.BatchId = @rBatchId
AND FS.IsVariable = 1
AND FS.IsOptional = 1
AND FA.SourceId NOT IN (SELECT AcademicId FROM #TempHostelFee)


	DROP TABLE	#TempHostelFee
	
		SELECT 1 AS Result   
	COMMIT TRANSACTION
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sHostel].[pHostelMasterAdd]...';


GO

ALTER PROCEDURE [sHostel].[pHostelMasterAdd]
	 
        @rId int,
		@rTitle nvarchar(100),
		@rRemark nvarchar(100),
		@rHostelTypeId int,
		@rNoOfRooms smallint,
		@rCreatedUserId bigint,
		@rIsObsolete bit,
		@rOrgGroupId smallint,
		@rReportOrgTitle  nvarchar(200) ,
		@rSmallAddress1 nvarchar(200),
		@rSmallAddress2 nvarchar(200)
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	IF(@rId = 0)	
	BEGIN  
		If Exists(select Id from sHostel.tHostelMaster where Title=@rTitle AND OrgGroupId=@rOrgGroupId)
			BEGIN
			select -103 as Result
			RETURN
		END 
	END
	ELSE
	BEGIN
		--If Exists(select Id from sHostel.tHostelMaster where Code=@rCode AND OrgId=@rOrgId AND Id<>@rId)
		--Begin
		--	select -102 as Result
		--	RETURN
		--End
		If  Exists(select Id from sHostel.tHostelMaster where Title=@rTitle AND OrgGroupId=@rOrgGroupId AND Id<>@rId)
		Begin
			select -103 as Result
			RETURN
		End

	END
	
	
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber int

	IF(@rId = 0)	
	BEGIN
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sHostel.tHostelMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sHostel.tHostelMaster
		(
			Id,
			Title,
			Remark,
			HostelTypeId,
			NoOfRooms,
			CreatedUserId,
			CreatedDateTime,
			IsObsolete,
			OrgGroupId ,
			ReportOrgTitle,
			SmallAddress1,
			SmallAddress2
			
		)
	VALUES
		(
			@lNextNumber,
			@rTitle,
			@rRemark,
			@rHostelTypeId,
			@rNoOfRooms,
			@rCreatedUserId,
			sCommon.fGetDate(), 
			@rIsObsolete,
			@rOrgGroupId,
			@rReportOrgTitle,
			@rSmallAddress1,
			@rSmallAddress2
		)
		
		  INSERT INTO sSecurity.tUserAccess
           (
           SourceTypeId
           ,SourceId
           ,[UserId]
           
           )
		   SELECT 
		   2014
		   ,@lNextNumber
		   ,@rCreatedUserId
		
		
		    SELECT @lNextNumber AS Result
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sHostel.tHostelMaster
	    SET
			Title=@rTitle,
			Remark=@rRemark,
			HostelTypeId=@rHostelTypeId,
			NoOfRooms=@rNoOfRooms,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate(), 
			IsObsolete=@rIsObsolete,
			ReportOrgTitle=@rReportOrgTitle ,
		    SmallAddress1=@rSmallAddress1 ,
		    SmallAddress2=@rSmallAddress2 
	      
	      
	      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 [sHostel].[pHostelMasterGet]...';


GO
ALTER PROCEDURE [sHostel].[pHostelMasterGet]
	 @rId int = 0,
	 @rTitle nvarchar(100),
	 @rHostelTypeId int,
	 @rOrgGroupId int,
	 @rIsSearch bit = 1
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 IF @rIsSearch = 1
		BEGIN
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		END
	
	SELECT 
	
			HM.Id,
			HM.Title,
		    HM.Remark,
		    HM.HostelTypeId,
		    HTM.Title AS HostelType,
		    HM.NoOfRooms,	
			HM.IsObsolete,
			HM.ReportOrgTitle,
			HM.SmallAddress1,
			HM.SmallAddress2
			
      
  FROM 
            sHostel.tHostelMaster HM
            INNER JOIN sHostel.tHostelTypeMaster HTM ON HTM.Id=HM.HostelTypeId
  WHERE   
           ((HM.Id = @rId) OR (@rId = 0))
	       AND ((HM.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
	       AND ((HM.HostelTypeId=@rHostelTypeId) OR (@rHostelTypeId=0)) 
	       AND HM.OrgGroupId=@rOrgGroupId
	       Order by id 
END
GO
PRINT N'Altering [sHostel].[pHostelStudentGatePassGet]...';


GO
ALTER PROCEDURE [sHostel].[pHostelStudentGatePassGet]

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

BEGIN 
	
	SELECT 
			SM.Code,
			--SM.FirstName+' '+SM.LastName AS StudentName,
			SM.Name AS StudentName,
			SG.WhithWhom,
			SG.ApprovedBy,
			SG.Reason,
			ISNULL(SG.OutDate,'') AS OutDate,
			ISNULL(SG.InDate,'') AS InDate,
			SG.Id,
			HM.Title AS HostelName,
			SM.Code,
			SG.StudentId,
			OutTime,
			InTime,
			ISNULL(SM.SUID,'') AS SUID
	FROM 
			sHostel.tStudentGatePass SG
			INNER JOIN sStudent.vStudentLastAcademic SM ON SM.StudentId=SG.StudentId
			INNER JOIN sHostel.tHostelMaster HM ON HM.Id=SG.HostelId
	WHERE 
			((SG.Id = @rId) OR (@rId = 0))
		AND (SM.Code = @rStudentCode  OR ISNULL(@rStudentCode,'')='')
		AND ((SG.HostelId = @rHostelId) OR (@rHostelId = 0))
		--AND ((SG.OutDate=@rOutDate) OR (ISNULL(@rOutDate,'')=''))
		--AND ((SG.InDate=@rInDate) OR (ISNULL(@rInDate,'')=''))
		AND (SG.OutDate>=@rOutDate OR ISNULL(@rOutDate,'')='')
		AND (SG.OutDate<=@rInDate OR ISNULL(@rInDate,'')='')
		Order by SG.CreatedDateTime DESC
END
GO
PRINT N'Altering [sHostel].[pHostelStudentSearchGet]...';


GO
ALTER PROCEDURE [sHostel].[pHostelStudentSearchGet]
	 
	 @rOrgId int,
	 @rHostelId int,
	 @rRoomId int,
	 @rStudentId bigint,
	 @rStudentName nvarchar(100),
	 @rStudentCode nvarchar(100),
	 @rClassId int,
	 @rDivisionId int,
	 @rOrgGroupBatchId int,
	 @rSUId nvarchar(20)='',
	 @rDepartmentId  int

	 	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON 
BEGIN 		
			SELECT 		
			O.DisplayTitle AS Organization,
			HM.Title AS Hostel,
			RM.Title AS Room,
			SD.Code AS StudentCode,
			SD.Name AS StudentName,
			SD.ClassName + ' ' + SD.DivisionName AS Class,
			SD.DivisionName AS Division,
			SD.StudentId,
			SD.ClassId,
			SD.DivisionId,
			HM.Id AS HostelId,
			RM.Id AS RoomId,
			O.Id AS OrgId,
			ISNULL(AR.BedNumber,'') AS BedNumber ,
			ISnull(SD.SUID,'') AS SUID,
			ISNULL(SI.StudentPhoto, CONVERT(VARBINARY(MAX), 0)) AS StudentPhoto,
			ISnull(SD.DepartmentName,'') As DepartmentName,
			[sHostel].[fAssignRoomAssetGet](HM.Id,RM.Id,SD.StudentId) AS AssetNumber,
			ISNULL(SC.PresentCity,'') AS City,
			ISNULL(SC.ParentContactNo,'') AS ContactNo
			FROM sHostel.tAssignRoom AR 
			INNER JOIN sStudent.vStudentLastAcademic SD ON SD.StudentId = AR.SourceId AND AR.SourceTypeId = 2003
			INNER JOIN sHostel.tRoomMaster RM ON AR.RoomId = RM.Id 
			INNER JOIN sHostel.tHostelMaster HM ON HM.Id = RM.HostelId
			INNER JOIN sSetup.tOrganizationMaster O ON O.Id = SD.OrgId
			--INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SD.BatchId AND BM.IsActive = 1
			LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=SD.StudentId
			LEFT JOIN  sStudent.tStudentCommunication SC ON SC.StudentId=SD.StudentId
			
			Where 
			SourceTypeId = 2003
			--AND (SD.OrgGroupBatchId=@rOrgGroupBatchId)
			AND ((O.Id = @rOrgId) OR (ISNULL(@rOrgId,0) = 0))
			AND ((HM.Id = @rHostelId) OR (ISNULL(@rHostelId,0) = 0))
			AND ((RM.Id = @rRoomId) OR (ISNULL(@rRoomId,0) = 0))
			AND ((SD.StudentId = @rStudentId) OR (ISNULL(@rStudentId,0) = 0))
			AND ((SD.ClassId = @rClassId) OR (ISNULL(@rClassId,0) = 0))
			AND ((SD.DivisionId = @rDivisionId) OR (ISNULL(@rDivisionId,0) = 0))
			AND ((SD.Code Like @rStudentCode) OR (ISNULL(@rStudentCode,'')=''))
			AND ((SD.Name like @rStudentName + '%') OR (ISNULL(@rStudentName,'') = ''))
			AND ((SD.DepartmentId = @rDepartmentId ) OR (ISNULL(@rDepartmentId,0) = 0))
			AND ((SD.SUId like @rSUId) OR (ISNULL(@rSUId,'')=''))
END
GO
PRINT N'Altering [sHostel].[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
WHERE 
			(HM.Id=@rHostelId OR @rHostelId=0)  order by EmployeeName
		
END
GO
PRINT N'Altering [sHostel].[pRoomMasterGet]...';


GO
ALTER PROCEDURE [sHostel].[pRoomMasterGet]
	 @rId int = 0,
	 @rTitle nvarchar(100),
	 @rHostelId int,
	 @rRoomCategoryId int,
	 @rIsSearch bit = 1,
	 @rBuildingId int=0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 IF @rIsSearch = 1
		BEGIN
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		END
	
	SELECT 
	
			RM.Id,
			RM.Title,
		    RM.Remark,
		    RM.HostelId,
		    HM.Title AS Hostel,
		    RM.RoomCategoryId,
		    RCM.Title AS RoomCategory,
		    ISNULL(RCM.RoomCharge,0) AS RoomCharge,
		    RM.StudentsPerRoom,	
			RM.IsObsolete,
			ISNULL(RM.AssignedEmployeeId,0) AS AssignedEmployeeId,
			EM.Code AS AssignedEmployeeCode,
			EM.EmployeeName AS AssignedEmployeeName,
			EM.DepartmentName AS AssignedEmployeeDepartment,
			ISNULL(RM.BuildingId,0) AS BuildingId,
			ISNULL(BM.Title,'') AS BuildingName,
			ISNULL(OM.Id ,0)AS OrgId
      
  FROM 
            sHostel.tRoomMaster RM
            INNER JOIN sHostel.tHostelMaster HM ON HM.Id=RM.HostelId
            INNER JOIN sHostel.tRoomCategoryMaster RCM ON RCM.HostelId=HM.Id AND RM.RoomCategoryId = RCM.Id
            AND (RCM.Id=@rRoomCategoryId OR @rRoomCategoryId=0)
            LEFT JOIN sHrm.vExtEmployeeMaster EM ON EM.Id=RM.AssignedEmployeeId
            LEFT JOIN sHostel.tBuildingMaster BM ON BM.Id=RM.BuildingId
            LEFT JOIN sSetup.tOrganizationMaster OM ON OM.Id=EM.OrgID
  WHERE 
  
		((RM.Id = @rId) OR (@rId = 0))
	AND ((RM.BuildingId = @rBuildingId) OR (@rBuildingId = 0))	
	AND ((RM.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
	AND ((RM.HostelId=@rHostelId) OR (@rHostelId=0))
	ORDER BY RM.Id
END
GO
PRINT N'Altering [sHostel].[pRptAddressLabelGet]...';


GO


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

BEGIN 

	SELECT 
	HM.Title,
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		ISNULL(SA.StudentId,0) as SourceId,
		SA.OrgId,
		SA.DivisionId,
		SA.DivisionOrder,
		@rIsBasedOnSUId AS IsBasedOnSUId ,
		CD.PresentStreetOne AS Address1,
		CD.PresentStreetTwo AS Address2,
		CD.PresentStreetThree AS Address3,
		CD.PresentCountry AS AddressCountry,
		CD.PresentState AS AddressState,
		CD.PresentCity AS AddressCity,
		CD.PresentZipCode AS AddressZipCode,
		CD.PresentContactNo AS ContactNo,
		CD.ParentContactNo ,
		CD.StudentContactNo,
		CD.ParentEmail,
		CD.StudentEmail,
		SA.Name,
		SA.Code,
		SA.SUId
		
			
			
			
	FROM 
		sStudent.vStudentLastAcademic SA 
		LEFT JOIN sStudent.tStudentCommunication CD ON  SA.StudentId=CD.StudentId
		INNER JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 
		INNER JOIN sHostel.tRoomMaster RM ON RM.Id=AR.RoomId 
		INNER JOIN sHostel.tHostelMaster HM ON HM.Id=RM.HostelId
	 
	WHERE 
 --(SA.OrgGroupBatchId = @rOrgGroupBatchId)

		((RM.HostelId=@rHostelId) OR (@rHostelId=0))
		AND ((SA.OrgId = @rOrgId) OR (@rOrgId=0))
		AND ((RM.Id=@rRoomId) OR (@rRoomId=0))
		AND ((SA.DepartmentId = @rDepartmentId ) OR (@rDepartmentId = 0))
		AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
		AND ((SA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))
		AND ((SA.Code Like @rStudentCode) OR (ISNULL(@rStudentCode,'')=''))
	    AND ((SA.SUId like @rSUId) OR (ISNULL(@rSUId,'')=''))
		AND ((SA.FirstName like @rStudentName + '%') OR (ISNULL(@rStudentName,'') = ''))
		 
END
GO
PRINT N'Altering [sHostel].[pRptHostelDepositAddGet]...';


GO

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

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


GO

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


GO

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

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


GO

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

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


GO

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

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


GO

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

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


GO
ALTER PROCEDURE [sHostel].[pRptHostelStudentGatePassGet]

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

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


GO


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


GO


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

BEGIN 


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


GO
ALTER PROCEDURE [sHostel].[pStudentDetailListGet]
	 
	 @rHostelId int,
	 @rSUId nvarchar(20),
	 @rCode nvarchar(20),
	@rOrgId int
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

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


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

BEGIN

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

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


GO
ALTER PROCEDURE [sHostel].[pVisitorGatePassGet]


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

BEGIN 

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


GO
ALTER PROCEDURE [sHrm].[pEmployeeAttendanceRegisterAdd]
	 
	@rEmployeeId bigint,
	@rAttendanceDate date,
	@rIsPresent bit=0,
	@rAbsentReasonId int=0,
	@rUpdatedUserId bigint=0,
	@rBatchId int,
	@rIsDeleted bit
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

If(@rIsDeleted=1)
BEGIN
	DELETE FROM sHrm.tEmployeeAttendanceRegister WHERE EmployeeId=@rEmployeeId 
	AND AttendanceDate=@rAttendanceDate AND BatchId=@rBatchId
	SELECT @rEmployeeId as Result
	RETURN
END	

	BEGIN TRY
	 BEGIN TRANSACTION	
	 
	--IF NOT EXISTS(SELECT EmployeeId FROM sHrm.tEmployeeAttendanceRegister WHERE EmployeeId=@rEmployeeId 
	--AND AttendanceDate=@rAttendanceDate AND BatchId=@rBatchId)
	
	BEGIN
	
	DELETE FROM sHrm.tEmployeeAttendanceRegister WHERE EmployeeId=@rEmployeeId 
	AND AttendanceDate=@rAttendanceDate AND BatchId=@rBatchId
	
		INSERT INTO sHrm.tEmployeeAttendanceRegister
		(
			EmployeeId,
			AttendanceDate,
			IsPresent,
			AbsentReasonId,
			UpdatedUserId,
			UpdatedDateTime,
			BatchId
		)
		VALUES
		(
			@rEmployeeId,
			@rAttendanceDate,
			@rIsPresent,
			@rAbsentReasonId,
			@rUpdatedUserId,
			sCommon.fGetDate(),
			@rBatchId
		)		
	 	
	 	SELECT 1 AS Result
	 	
	END	
--ELSE
--	 BEGIN
--	   UPDATE  sHrm.tEmployeeAttendanceRegister
--	    SET
--			IsPresent=@rIsPresent,
--			AbsentReasonId=@rAbsentReasonId,
--			UpdatedUserId=@rUpdatedUserId,
--			UpdatedDateTime=sCommon.fGetDate()
	    
--	    WHERE EmployeeId=@rEmployeeId 
--			AND AttendanceDate=@rAttendanceDate
--			AND BatchId=@rBatchId 
			  
--	    SELECT 11 AS Result
	    
--	 END  	

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


GO
ALTER PROCEDURE [sHrm].[pEmployeeCustomSearchGet]
(
	@rOrgId smallint,
	@rOrderBy nvarchar(max) = 'Code',
	@rCode [nvarchar](20) = '',
	@rFirstName [nvarchar](50) = '',	
	@rLastName[nvarchar](50) = '',
	@rEmployeeTypeId[nvarchar](50) = '',
	@rStatusId[nvarchar](50) = '',
	@rOrganizationDepartmentId[nvarchar](50) = '',
	@rReligionId[nvarchar](50) = '',
	@rMaritalStatusId[nvarchar](50) = '',
	@rQualification[nvarchar](50) = '',
	@rGenderId[nvarchar](50) = '',
	@rEmployeeDesignationId[nvarchar](50) = '',
	@rBloodGroupId[nvarchar](50) = '',
	@rEmployeeGroupId[nvarchar](50)='',
	@rDOBFromDate Date = '0001-01-01',
	@rDOBToDate Date = '9999-12-31',
	@rDOJFromDate Date = '0001-01-01',
	@rDOJToDate Date = '9999-12-31',
	@rDropDownStatusId int
 )
AS
SET NOCOUNT ON

BEGIN
		DECLARE @Sql nvarchar(MAX)

		--IF(@rDOBFromDate IS NULL)
		--	SET @rDOBFromDate='0001-01-01'
		--IF(@rDOJFromDate IS NULL)
		--	SET @rDOJFromDate='0001-01-01'
		--IF(@rDOBToDate IS NULL)
		--	SET @rDOBToDate='9999-12-31'
		--IF(@rDOJToDate IS NULL)
		--	SET @rDOJToDate='9999-12-31'
		
		SET @rCode = sCommon.fSearchStringGet(@rCode)
		SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
		SET @rLastName = sCommon.fSearchStringGet(@rLastName)
		SET @rQualification = sCommon.fSearchStringGet(@rQualification)
		
		SELECT 
			*
			--ECS.EmployeeId,
			--ECS.Code AS Code,
			--ECS.Name,
			----ISNULL(ECS.EmployeeTypeId,0) AS EmployeeTypeId,			
			--ISNULL(ECS.EmployeeType,'') As EmployeeType,
			----ISNULL(ECS.StatusId,0) AS StatusId,
			--ISNULL(ECS.StatusName,'') AS StatusName,
			----ECS.OrganizationDepartmentId,
			--ECS.OrganizationDepartment,
			--ECS.IsObsolete AS IsObsolete
			into sHrm.tTempEmployee1
		FROM 
			sHrm.vEmployeeCustomSearch ECS
		WHERE 
			ECS.OrgId = @rOrgId 
			AND ((ECS.Code Like @rCode + '%') OR (@rCode = ''))
			AND ((ECS.FirstName Like @rFirstName  + '%') OR (@rFirstName = ''))	 			 
			AND ((ECS.LastName Like @rLastName + '%')OR(@rLastName = ''))
			AND ((ISNULL(ECS.Qualification,'') Like @rQualification + '%')OR(@rQualification = ''))
			AND ((ECS.DateOfBirth >= @rDOBFromDate) OR (ISNULL(@rDOBFromDate,'') = ''))
			AND ((ECS.DateOfBirth <= @rDOBToDate) OR (ISNULL(@rDOBToDate,'') = ''))	
			AND ((ECS.DateOfJoining >= @rDOJFromDate) OR (ISNULL(@rDOJFromDate,'') = ''))
			AND ((ECS.DateOfJoining <= @rDOJToDate) OR (ISNULL(@rDOJToDate,'') = ''))	
			
			AND (ISNULL(ECS.OrganizationDepartmentId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrganizationDepartmentId,','))OR @rOrganizationDepartmentId='') 
			
			AND (ISNULL(ECS.StatusId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rStatusId,','))OR @rStatusId='') 
			
		    AND (ISNULL(ECS.EmployeeTypeId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rEmployeeTypeId,','))OR @rEmployeeTypeId='') 
			
		    AND (ISNULL(ECS.EmployeeDesignationId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rEmployeeDesignationId,','))OR @rEmployeeDesignationId='') 
		    
		    AND (ISNULL(ECS.EmployeeGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rEmployeeGroupId,','))OR @rEmployeeGroupId='')
			
		    AND (ISNULL(ECS.BloodGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rBloodGroupId,','))OR @rBloodGroupId='') 
			   
		    AND (ISNULL(ECS.ReligionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rReligionId,','))OR @rReligionId='') 
			        
		    AND (ISNULL(ECS.MaritalStatusId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rMaritalStatusId,','))OR @rMaritalStatusId='') 
			 
		    AND (ISNULL(ECS.GenderId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rGenderId,','))OR @rGenderId='') 
		    
		    AND ((ECS.StatusId = @rDropDownStatusId) OR (@rDropDownStatusId=0))
			   
		SET @rOrderBy=Replace(@rOrderBy,'Code','Code')
		SET @sql=
		'SELECT 
				EmployeeId,
				Code AS Code,
				Name,
				EmployeeType,
				OrganizationDepartment AS OrganizationDepartment,
				StatusName 
		FROM sHrm.tTempEmployee1 ORDER BY '+@rOrderBy
		exec(@Sql)
		DROP Table sHrm.tTempEmployee1
END
GO
PRINT N'Altering [sHrm].[pEmployeeDataModify]...';


GO
 

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

--BEGIN TRY
--BEGIN TRANSACTION

EXEC sp_xml_preparedocument @loDoc OUTPUT,@rXML
BEGIN
	
	IF(@rSubCategoryField = 'Gender' OR @rSubCategoryField = 'Religion' OR @rSubCategoryField = 'BloodGroup'
	OR @rSubCategoryField = 'MaritalStatus' OR @rSubCategoryField = 'OrganizationDepartment' OR @rSubCategoryField = 'EmployeeType'
			OR @rSubCategoryField = 'EmployeeGroup' OR @rSubCategoryField = 'EmployeeGrade' OR @rSubCategoryField = 'Relationship' OR  @rSubCategoryField = 'EmployeeDesignation'
			OR  @rSubCategoryField = 'Payroll' OR  @rSubCategoryField = 'PayrollGroup' 
			)
	BEGIN
		SET @rSubCategoryField = @rSubCategoryField + 'Id'
	END
	ELSE IF (@rSubCategoryField = 'CasteCategory' )
		BEGIN
			SET @rSubCategoryField = Replace(@rSubCategoryField,'Caste','Cast')+'Id'
		END
			
	CREATE TABLE ListofData(Id bigint,EmployeeId bigint,SubCategory nvarchar(150),UpdatedUserId bigint,IsExist bit);
	IF(@rCategoryId= 1)
		BEGIN
		insert into ListofData
		select 0,E.EmployeeId,E.SubCategory,E.UpdatedUserId,0
		from
		(
				SELECT EmployeeId,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Employees/Employees', 2)
				WITH (
						EmployeeId BIGINT, 
						SubCategory nvarchar(150),
						UpdatedUserId bigint)	
						)E 	
		UPDATE ListofData SET IsExist=1 WHERE EmployeeId NOT IN(SELECT EmployeeId FROM sHrm.tEmployeeCommunications) 
		
		set @sql='INSERT INTO sHrm.tEmployeeCommunications 
					(EmployeeId,'+@rSubCategoryField+',CreatedUserId,CreatedDateTime)
					SELECT
						LD.EmployeeId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
					FROM
						ListofData LD WHERE LD.IsExist=1'
		Exec sp_executesql @sql
		set @sql='UPDATE sHrm.tEmployeeCommunications set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sHrm.tEmployeeCommunications EC 
					INNER JOIN ListofData LD ON EC.EmployeeId=LD.EmployeeId AND IsExist=0'
		
		Exec sp_executesql @sql
		
		
		
		Drop Table ListofData
			 SELECT 1 AS StatusId
	    END
	    
	Else IF(@rCategoryId= 2)
		BEGIN
		insert into ListofData
		select 0,E.EmployeeId,E.SubCategory,E.UpdatedUserId,0
		from
		(
				SELECT EmployeeId,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Employees/Employees', 2)
				WITH (
						EmployeeId BIGINT, 
						SubCategory nvarchar(100),
						UpdatedUserId bigint)	
						)E 	
		UPDATE ListofData SET IsExist=1 WHERE EmployeeId NOT IN(SELECT EmployeeId FROM sHrm.tEmployeePersonalDetail) 
		
		IF(@rSubCategoryField = 'DateOfBirth')
		BEGIN			
					
			 				
			set @sql='UPDATE sHrm.tEmployeePersonalDetail set '+@rSubCategoryField+' = LD.SubCategory,
						UpdatedUserId=LD.UpdatedUserId,
						UpdatedDateTime=sCommon.fGetDate()  
						from sHrm.tEmployeePersonalDetail EPD 
						INNER JOIN ListofData LD ON EPD.EmployeeId=LD.EmployeeId'			
			Exec sp_executesql @sql
			set @sql='UPDATE sHrm.tEmployeePersonalDetail SET '+@rSubCategoryField+' = null WHERE DateOfBirth=''1900-01-01'''
			Exec sp_executesql @sql
		END
		ELSE
		BEGIN
			
			 				
			set @sql='UPDATE sHrm.tEmployeePersonalDetail set '+@rSubCategoryField+' = LD.SubCategory,
						UpdatedUserId=LD.UpdatedUserId,
						UpdatedDateTime=sCommon.fGetDate()  
						from sHrm.tEmployeePersonalDetail EPD 
						INNER JOIN ListofData LD ON EPD.EmployeeId=LD.EmployeeId'
			
			Exec sp_executesql @sql
		END
		Drop Table ListofData
			 SELECT 1 AS StatusId
	    END	
	    
	Else IF(@rCategoryId= 3)
		BEGIN
		insert into ListofData
		select 0,E.EmployeeId,E.SubCategory,E.UpdatedUserId,0
		from
		(
				SELECT EmployeeId,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Employees/Employees', 2)
				WITH (
						EmployeeId BIGINT, 
						SubCategory nvarchar(100),
						UpdatedUserId bigint)	
						)E 	
	
		set @sql='UPDATE sHrm.tEmployeeJobDetail set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sHrm.tEmployeeJobDetail EJ 
					INNER JOIN ListofData LD ON EJ.EmployeeId=LD.EmployeeId'
		
		Exec sp_executesql @sql
		Drop Table ListofData
			 SELECT 1 AS StatusId
	    END	
  Else IF(@rCategoryId= 4)
	BEGIN
		insert into ListofData
		select 0,E.EmployeeId,E.SubCategory,E.UpdatedUserId,0
		from
		(
				SELECT EmployeeId,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Employees/Employees', 2)
				WITH (
						EmployeeId BIGINT, 
						SubCategory nvarchar(100),
						UpdatedUserId bigint)	
						)E 	
		UPDATE ListofData SET IsExist=1 WHERE EmployeeId NOT IN(SELECT EmployeeId FROM sHrm.tEmployeeMaster) 
		
		
		set @sql='UPDATE sHrm.tEmployeeMaster set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sHrm.tEmployeeMaster HEM 
					INNER JOIN ListofData LD ON HEM.Id=LD.EmployeeId AND IsExist=0'
		
		Exec sp_executesql @sql
		Drop Table ListofData
			SELECT 1 AS StatusId
	    END
	    
	    Else IF(@rCategoryId= 5)
		BEGIN
		insert into ListofData
		select 0,E.EmployeeId,E.SubCategory,E.UpdatedUserId,0
		from
		(
				SELECT EmployeeId,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Employees/Employees', 2)
				WITH (
						EmployeeId BIGINT, 
						SubCategory nvarchar(100),
						UpdatedUserId bigint)	
						)E 
						
		UPDATE ListofData SET IsExist=1 WHERE EmployeeId NOT IN(SELECT EmployeeId FROM sHrm.tEmployeeStatutoryAndOther) 
		
		set @sql='INSERT INTO sHrm.tEmployeeStatutoryAndOther 
					(EmployeeId,'+@rSubCategoryField+',IsVPFDeduction,UpdatedUserId,UpdatedDateTime)
					SELECT
						LD.EmployeeId,Ld.SubCategory,0,LD.UpdatedUserId,sCommon.fGetDate()
					FROM
						ListofData LD WHERE LD.IsExist=1'
		Exec sp_executesql @sql			
		
		
		IF(@rSubCategoryField = 'EPFJoinDate')
		BEGIN			
		    set @sql='UPDATE sHrm.tEmployeeStatutoryAndOther set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sHrm.tEmployeeStatutoryAndOther ESO 
					INNER JOIN ListofData LD ON ESO.EmployeeId=LD.EmployeeId'			
			Exec sp_executesql @sql
			set @sql='UPDATE sHrm.tEmployeeStatutoryAndOther SET '+@rSubCategoryField+' = NULL WHERE EPFJoinDate=''1900-01-01'''
			Exec sp_executesql @sql
		END
		ELSE
		BEGIN
			set @sql='UPDATE sHrm.tEmployeeStatutoryAndOther set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sHrm.tEmployeeStatutoryAndOther ESO 
					INNER JOIN ListofData LD ON ESO.EmployeeId=LD.EmployeeId'

			Exec sp_executesql @sql
		END
		
		
		Drop Table ListofData
			 SELECT 1 AS StatusId
	    END	
	    
	    
END 
	--   COMMIT TRANSACTION
		
	--END TRY
	
	--BEGIN CATCH 
	--	ROLLBACK TRANSACTION
	--	Drop Table ListofData
	--	SELECT -1 AS Result
	--END CATCH
GO
PRINT N'Altering [sHrm].[pEmployeeMasterModify]...';


GO
ALTER PROCEDURE [sHrm].[pEmployeeMasterModify]
	
	@rId [bigint],
	@rCode [nvarchar](20),
	@rFirstName [nvarchar](100),
	@rMiddleName [nvarchar](100),
	@rLastName [nvarchar](100),
	@rEmployeeTypeId int,
	@rDepartmentId int,
	@rDateOfBirth Date,
	@rDateOfJoining Date,
	@rGenderId int,
	@rStatusId [smallint],
	@rIsObsolete [bit],
	@rUpdatedUserId [bigint],
	@rEmployeePhoto varbinary(max),
	@rEmployeeDesignationId [int],
	@rEmployeeGradeId int,
	@rEmployeeGroupId int,
	@rShortName nvarchar(50)
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 

	
	DECLARE @lOrgId int
	
	SELECT @lOrgId = OrgId FROM sHrm.tEmployeeMaster WHERE Id=@rId

	IF EXISTS(SELECT Id FROM sHrm.tEmployeeMaster WHERE Code=@rCode AND OrgId=@lOrgId AND Id<>@rId)
		BEGIN
		SELECT -101 as Result
		RETURN
	END 
			
	 UPDATE sHrm.tEmployeeMaster
		SET
		    Code = @rCode, 
			FirstName = @rFirstName,
			MiddleName = @rMiddleName,
			LastName = @rLastName,
			StatusId = @rStatusId,
			ShortName=@rShortName,
			IsObsolete = @rIsObsolete,
			UpdatedUserId = @rUpdatedUserId,
			UpdatedDateTime = sCommon.fGetDate()
	  WHERE 
			Id = @rId
	  
	SELECT @rId AS RESULT
	
	BEGIN 
	UPDATE sHrm.tEmployeeJobDetail
		SET 
			EmployeeDesignationId = @rEmployeeDesignationId,	
			OrganizationDepartmentId = @rDepartmentId,
			DateOfJoining =	@rDateOfJoining,
			UpdatedUserId = @rUpdatedUserId,
			EmployeeTypeId = @rEmployeeTypeId,
			EmployeeGradeId = @rEmployeeGradeId,
			EmployeeGroupId = @rEmployeeGroupId
		WHERE 
			EmployeeId = @rId
	
	UPDATE sHrm.tEmployeePersonalDetail
		SET 
			DateOfBirth	=	@rDateOfBirth,
			GenderId	=	@rGenderId,
			UpdatedUserId = @rUpdatedUserId
		WHERE 
			EmployeeId = @rId	
	
	IF @rStatusId = 9
	BEGIN
		UPDATE sSecurity.tUser
			SET 
				IsObsolete = 1,
				UpdatedUserId = @rUpdatedUserId,
				UpdatedDateTime = sCommon.fGetDate()
			WHERE 
				SourceId = @rId AND SourceTypeId = 95
	END
	ELSE IF @rStatusId = 7
	BEGIN
		UPDATE sSecurity.tUser
			SET 
				IsObsolete = 0,
				UpdatedUserId = @rUpdatedUserId,
				UpdatedDateTime = sCommon.fGetDate()
			WHERE 
				SourceId = @rId AND SourceTypeId = 95
	END
	  
	  --BEGIN
	  --   Execute sHrm.pEmployeeJobDetailModify 
	  --     0,@rId,0,@rEmployeeDesignationId,@rLocationId,@rDepartmentId,@rDateOfJoining,'','',0,0,@rUpdatedUserId,
	  --     0,0,@rEmployeeTypeId,@rProcessTypeId,NULL,NULL,NULL,0,0
	     --Execute sHrm.pEmployeePersonalDetailModify
	     --  0,@rId,'',@rDateOfBirth,@rGenderId,0,0,'','',0,0,'','','','','',0,'',0,'',0,0,@rUpdatedUserId,@rIsBirthDateUnknown
	     
	  END
END
GO
PRINT N'Altering [sHrm].[pEmployeeProfileFullGet]...';


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


GO
ALTER PROCEDURE [sHrm].[pEmployeeStatutoryDetailAdd]

	       @rEmployeeId bigint,
	       @rAccountNumber nvarchar(20),
	       @rBankName nvarchar(200),
           @rBranch nvarchar(50),          
           @rEPFNumber nvarchar(20),
           @rPanNumber nvarchar(20),
           @rIsVPFDeduction bit,
           @rVPFContributionId tinyint,
           @rVPFContributionEffectiveFrom date,
           @rVPFPercentage decimal(5,2),
           @rVPFAmount decimal(22,6),
           @rESINumber nvarchar(20),        
           @rIFSCNumber nvarchar(50),           
           @rIncomeTaxStatusId int,
           @rUpdatedUserId bigint,            
           @rIncrementDate date,
           @rBasicPay decimal(12,2),
           @rPayrollId int,
           @rPayrollGroupId int,
           @rPayscale nvarchar(150)='',
           @rEPFJoinDate date = NULL
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
BEGIN TRY
BEGIN TRANSACTION
	DECLARE @lNextNumber BIGINT 
 	  
IF NOT EXISTS(Select 1 From sHrm.tEmployeeStatutoryAndOther Where EmployeeId = @rEmployeeId)
   BEGIN
	INSERT INTO sHrm.tEmployeeStatutoryAndOther
           (
            [EmployeeId]
           ,[EPFNumber]
           ,[IsVPFDeduction]
           ,[VPFContributionId]
           ,[VPFContributionEffectiveFrom]
           ,[VPFPercentage]
           ,[VPFAmount]
           ,[ESINumber]
           ,[BankName]
           ,[Branch]
           ,[AccountNumber]
           ,[IFSCNumber]
           ,[PanNumber]
           ,[IncomeTaxStatusId]
           ,[UpdatedUserId]
           ,[UpdatedDateTime]
           ,[IncrementDate]
           ,[BasicPay]
           ,[PayrollId]
           ,[PayrollGroupId]
           ,[Payscale]
           ,[EPFJoinDate]
           )
     VALUES
           (
           @rEmployeeId,
           @rEPFNumber,
           @rIsVPFDeduction,
           @rVPFContributionId,
           @rVPFContributionEffectiveFrom,
           @rVPFPercentage,
           @rVPFAmount,
           @rESINumber,
           @rBankName,
           @rBranch,
           @rAccountNumber,
           @rIFSCNumber,
           @rPanNumber,
           @rIncomeTaxStatusId,
           @rUpdatedUserId,
           sCommon.fGetDate(),
           @rIncrementDate,
           @rBasicPay,
           @rPayrollId,
           @rPayrollGroupId,
           @rPayscale,
           @rEPFJoinDate
           )
     END
     ELSE
     BEGIN
      UPDATE sHrm.tEmployeeStatutoryAndOther
      SET 
		  [EPFNumber] = @rEPFNumber,
		  [IsVPFDeduction] = @rIsVPFDeduction, 
		  [VPFContributionId] = @rVPFContributionId, 
		  [VPFContributionEffectiveFrom] = @rVPFContributionEffectiveFrom, 
		  [VPFPercentage] = @rVPFPercentage, 
		  [VPFAmount] = @rVPFAmount, 
		  [ESINumber] = @rESINumber, 
		  [BankName] = @rBankName, 
		  [Branch] = @rBranch, 
		  [AccountNumber] = @rAccountNumber, 
		  [IFSCNumber] = @rIFSCNumber, 
		  [PanNumber] = @rPanNumber, 
		  [IncomeTaxStatusId] = @rIncomeTaxStatusId, 
		  [UpdatedUserId] = @rUpdatedUserId, 
		  [UpdatedDateTime] = sCommon.fGetDate(), 
		  [IncrementDate] = @rIncrementDate, 
		  [BasicPay] = @rBasicPay,
		  [PayrollId]=@rPayrollId,
          [PayrollGroupId]=@rPayrollGroupId,
          [Payscale]=@rPayscale,
          [EPFJoinDate]=@rEPFJoinDate
	  WHERE 
			EmployeeId = @rEmployeeId
     END    
     
	SELECT 1 AS RESULT
	COMMIT TRANSACTION
	END TRY
	BEGIN CATCH
	ROLLBACK TRANSACTION
	SELECT -1 AS RESULT
	END CATCH				
END
GO
PRINT N'Altering [sHrm].[pEmployeeStatutoryDetailGet]...';


GO
ALTER PROCEDURE [sHrm].[pEmployeeStatutoryDetailGet]
	
	@rOrgId smallint,
	@rEmployeeId [bigint] = 0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 SELECT 
		    [EmployeeId]
		  , [EPFNumber]
		  , [IsVPFDeduction]
		  ,ISNULL([VPFContributionId],0) AS VPFContributionId
		  ,ISNULL([VPFContributionEffectiveFrom],'1/1/0001')  AS VPFContributionEffectiveFrom
		  ,ISNULL([VPFPercentage],0) AS VPFPercentage
		  ,ISNULL([VPFAmount],0) AS VPFAmount
		  ,[ESINumber]
		  ,[BankName]
		  ,[Branch]
		  ,[AccountNumber]
		  ,[IFSCNumber]
		  ,[PanNumber]
		  ,ISNULL([IncomeTaxStatusId],0) AS IncomeTaxStatusId       
		  ,ISNULL([IncrementDate],'1/1/0001') AS IncrementDate
		  ,ISNULL([BasicPay],0) AS BasicPay
		  ,ISNULL([PayrollId],0) AS PayrollId
		  ,ISNULL([PayrollGroupId],0) AS PayrollGroupId 
		  ,ISNULL([Payscale],'') AS Payscale
		  ,ISNULL([EPFJoinDate],'1/1/0001') AS EPFJoinDate
	FROM 
			[sHrm].[tEmployeeStatutoryAndOther] 
			 
	Where 
			 EmployeeId = @rEmployeeId	  
END
GO
PRINT N'Altering [sHrm].[pLeaveListingGet]...';


GO

ALTER PROCEDURE [sHrm].[pLeaveListingGet]
(
	@rOrgId int,
    @rId bigint = 0,
    @rEmployeeId  bigint,   
    @rFromDate date,
    @rLeaveTypeId int,
    @rTodate date,
    @rOrgGroupBatchId int,
    @rEmployeeCode nvarchar(100),
    @rEmployeeName nvarchar(100),
    @rStatusId int = 0 
 )
AS
SET NOCOUNT ON

BEGIN
    
	SELECT 
		   L.[Id] AS LeaveId
		  ,L.[EmployeeId]
		  ,L.[ReportDate]
		  ,L.[FromDate]
		  ,L.[ToDate]
		  ,L.[LeavePeriodId]
		  ,L.[LeaveTypeId]
		  ,L.[LeaveReason]
		  ,LPM.Title AS LeavePeriod
		  ,LTM.Title AS LeaveType
		  ,EM.EmployeeName
		  ,EM.Code AS EmployeeCode
		  ,L.NoOfLeave
		  ,ISNULL(L.StatusId,0) AS StatusId
		  ,ISNULL(SM.Title,'Pending') AS StatusName
		  ,ISNULL(L.LeaveRemark,'') AS  LeaveRemark
		  ,OM.DisplayTitle AS OrganizationName
      
  FROM 
			[sHrm].[tLeave] L 
	  INNER JOIN sSetup.tBatchMaster BM ON BM.Id = L.BatchId		
	  INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
	  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 = L.StatusId
  WHERE 
		  (L.Id = @rId OR @rId = 0)
      AND (EJD.EmployeeManagerId = @rEmployeeId OR @rEmployeeId = 0)
      AND ((L.FromDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
      AND ((L.ToDate <= @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 (L.StatusId = @rStatusId OR @rStatusId = 0)      
END
GO
PRINT N'Altering [sLibrary].[pBookLogGet]...';


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

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


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

	UNION

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

	UNION 

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


GO

ALTER PROCEDURE [sLibrary].[pMagazineReceiveGet]
	 
	 @rId bigint = 0,
	 @rLibraryId int,
	 @rMagazineId bigint,
	 @rMagazineCode nvarchar(25),
	 @rFromReceiveDate date,
	 @rToReceiveDate date
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
		SET @rMagazineCode = sCommon.fSearchStringGet(@rMagazineCode)
	SELECT 
	     MR.Id AS MagazineReceiveId,
	     MR.MagazineId,
	     MM.Code AS MagazineCode,
	     MM.Title AS MagazineName,
	     MR.ReceiveDate,
	     ISNULL(MR.VolumeNumber,'') AS VolumeNumber,
	     ISNULL(IssueNumber,0) AS IssueNumber,
	     ISNULL(MM.Price,0) AS Price,
		 ISNULL(FM.Title,'') AS FrequencyName,
		  LM.ReportOrgTitle,
	      LM.SmallAddress1,
	      LM.SmallAddress2
		
	    
  FROM 
		sLibrary.tMagazineReceive MR
			INNER JOIN sLibrary.tMagazineMaster MM ON MM.Id=MR.MagazineId
			LEFT JOIN sCommon.tFrequencyMaster FM ON MM.FrequencyId=FM.Id
			LEFT JOIN sLibrary.tLibraryMaster LM ON LM.Id=MM.LibraryId
  WHERE 
		MM.LibraryId=@rLibraryId
		AND ((MR.Id = @rId) OR (@rId = 0))
		AND ((MR.MagazineId = @rMagazineId) OR (@rMagazineId = 0))
		ANd ((MM.Code like @rMagazineCode) OR (ISNULL(@rMagazineCode,'') = ''))
		AND (MR.ReceiveDate>=@rFromReceiveDate OR ISNULL(@rFromReceiveDate,'')='')
		AND (MR.ReceiveDate<=@rToReceiveDate OR ISNULL(@rToReceiveDate,'')='')
END
GO
PRINT N'Altering [sLibrary].[pReaderBookLogListGet]...';


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


GO

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

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

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


GO
ALTER PROCEDURE [sLibrary].[pRptAccessionRegisterGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='',
	 @rBookSupplier nvarchar(200),
	 @rBookPublisher nvarchar(200),
	 @rBookSubject nvarchar(200),
	 @rBookLanguage nvarchar(200),
	 @rBookTag nvarchar(200),
	 @rBookCustomTag nvarchar(200),
	 @rLibraryId int,
	 @rAccessionNo nvarchar(50)='',
	 @rClassificationNo nvarchar(50)=''
         
           
AS
SET NOCOUNT ON
BEGIN
BEGIN	  
			SET @rBookSupplier = sCommon.fSearchStringGet(@rBookSupplier)
			SET @rBookPublisher = sCommon.fSearchStringGet(@rBookPublisher)
			SET @rBookSubject = sCommon.fSearchStringGet(@rBookSubject)
			SET @rBookLanguage = sCommon.fSearchStringGet(@rBookLanguage)
			SET @rBookTag = sCommon.fSearchStringGet(@rBookTag)
			SET @rBookCustomTag = sCommon.fSearchStringGet(@rBookCustomTag)
	        END
SELECT   
	   @rBuilder1 AS Builder1,
	   @rBuilder2 AS Builder2,
	   BM.Id AS BookId,
	   BM.Code AS BookCode,
	   BM.Title AS BookName,
	   BM.Author,
	   BM.Publisher,
	   BM.ClassificationNo,
	   BM.BookSubject,
	   BM.AccessionNo,
	   BM.Edition,
	   BM.NoOfPages,
	   BM.BookLanguage,
	   BM.Supplier,
	   BM.PurchaseDate,
	   BM.Price,
	   BM.ISBNNumber,
	   BM.Location,
	   BM.BookRemark,
	   LM.ReportOrgTitle,
	   LM.SmallAddress1,
	   LM.SmallAddress2
	  
  FROM  
		
		 sLibrary.tBookMaster BM 
		 LEFT JOIN sLibrary.tLibraryMaster LM ON LM.Id=BM.LibraryId
 
  WHERE 
  
	 BM.LibraryId=@rLibraryId
		AND ((BM.Supplier like @rBookSupplier) OR (@rBookSupplier=''))
		AND ((BM.Publisher like @rBookPublisher) OR (@rBookPublisher=''))
		AND ((BM.BookSubject like @rBookSubject) OR (@rBookSubject=''))
		AND ((BM.BookLanguage like @rBookLanguage) OR (@rBookLanguage=''))
		AND ((BM.BookTag like @rBookTag) OR (@rBookTag=''))
		AND ((BM.BookCustomTag like @rBookCustomTag) OR (@rBookCustomTag=''))
		AND ((BM.AccessionNo like @rAccessionNo) OR (@rAccessionNo=''))
		AND ((BM.ClassificationNo like @rClassificationNo) OR (@rClassificationNo=''))
	
END
GO
PRINT N'Altering [sLibrary].[pRptBookListGet]...';


GO

ALTER PROCEDURE [sLibrary].[pRptBookListGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='',
	 @rBookSupplier nvarchar(200),
	 @rBookPublisher nvarchar(200),
	 @rBookSubject nvarchar(200),
	 @rBookLanguage nvarchar(200),
	 @rBookTag nvarchar(200),
	 @rBookCustomTag nvarchar(200),
	 @rLibraryId int
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
		
BEGIN 

			BEGIN	  
			SET @rBookSupplier = sCommon.fSearchStringGet(@rBookSupplier)
			SET @rBookPublisher = sCommon.fSearchStringGet(@rBookPublisher)
			SET @rBookSubject = sCommon.fSearchStringGet(@rBookSubject)
			SET @rBookLanguage = sCommon.fSearchStringGet(@rBookLanguage)
			SET @rBookTag = sCommon.fSearchStringGet(@rBookTag)
			SET @rBookCustomTag = sCommon.fSearchStringGet(@rBookCustomTag)
	        END

	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			BM.Code,
			BM.Title As BookTitle,
			BM.Publisher,BM.Supplier,
			BM.BookSubject,
			BM.BookLanguage,
			BM.BookCustomTag,
			BM.BookCustomTag,
			BM.Location,
			BM.ISBNNumber,
			 LM.ReportOrgTitle,
	        LM.SmallAddress1,
	        LM.SmallAddress2
			
	FROM 
			sLibrary.tBookMaster BM
			 LEFT JOIN sLibrary.tLibraryMaster LM ON LM.Id=BM.LibraryId
			
	WHERE 
			BM.LibraryId=@rLibraryId
		AND ((BM.Supplier like @rBookSupplier) OR (@rBookSupplier=''))
		AND ((BM.Publisher like @rBookPublisher) OR (@rBookPublisher=''))
		AND ((BM.BookSubject like @rBookSubject) OR (@rBookSubject=''))
		AND ((BM.BookLanguage like @rBookLanguage) OR (@rBookLanguage=''))
		AND ((BM.BookTag like @rBookTag) OR (@rBookTag=''))
		AND ((BM.BookCustomTag like @rBookCustomTag) OR (@rBookCustomTag=''))
		
	END
GO
PRINT N'Altering [sLibrary].[pRptBookLogPenaltyListGet]...';


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

		(CASE WHEN BL.ReaderSourceTypeId = 95 THEN Emp.EmployeeName
			WHEN BL.ReaderSourceTypeId = 2003 THEN vSF.Name
			ELSE
			''
			END) AS Name,
			
		(CASE WHEN BL.ReaderSourceTypeId = 95 THEN Emp.DepartmentName
			WHEN BL.ReaderSourceTypeId = 2003 THEN (vSF.ClassName + ' - '+ vSF.DivisionName)
			ELSE '' END) AS ClassDepartmentName,	
		 
		(CASE WHEN BL.ReaderSourceTypeId = 95 THEN	Emp.Code
			 WHEN BL.ReaderSourceTypeId = 2003 THEN	vSF.Code
			 ELSE '' END) AS Code, 	
			 	 
	   BL.ReaderSourceTypeId,
	   BL.ReaderSourceId,
	   BL.LogDate,
	   BL.DueDate,
	   BM.Code AS BookCode,
	   BM.Title AS BookName,
	   BLP.PenaltyDays,
	   BLP.PenaltyRate,
	   BLP.PenaltyAmount,
	   LM.ReportOrgTitle,
	   LM.SmallAddress1,
	   LM.SmallAddress2
	   
  FROM  
		sLibrary.tBookLog BL
		INNER JOIN sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId
		INNER JOIN sLibrary.tBookLogPenalty BLP ON BLP.BookLogId = BL.Id
		LEFT JOIN sHrm.vExtEmployeeMaster Emp
			ON Emp.Id = BL.ReaderSourceId AND BL.ReaderSourceTypeId = 95 
		LEFT JOIN sStudent.vStudentFull vSF
			ON vSF.StudentId = BL.ReaderSourceId AND BL.ReaderSourceTypeId = 2003 
			AND (SELECT IsActive FROM sSetup.tBatchMaster WHERE Id=vSF.BatchId AND IsActive = 1) = 1				
		LEFT JOIN sSetup.tDepartmentMaster DM ON DM.Id = vSF.DepartmentId		
		LEFT JOIN sLibrary.tLibraryMaster LM ON LM.Id=BM.LibraryId
	
  WHERE 
  
	BL.LibraryId=@rLibraryId
	AND (BL.LogDate>=@rFromLogDate OR ISNULL(@rFromLogDate,'')='')
	AND (BL.LogDate<=@rToLogDate OR ISNULL(@rToLogDate,'')='')
	AND ((BL.ReaderSourceTypeId=@rSourceTypeId) OR (@rSourceTypeId=0))
END
GO
PRINT N'Altering [sLibrary].[pRptBookLogRegisterGet]...';


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

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


GO

ALTER PROCEDURE [sLibrary].[pRptFavouriteBooksCountGet]

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

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


GO

ALTER PROCEDURE [sLibrary].[pRptReaderBookListGet]

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

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

BEGIN  
	
	
	
	
	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
		@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 PPE.WorkingDays else 0 END) 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 
		
		
	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	
	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
	LEFT JOIN sCommon.tReportRemarkGroupOrg RGO ON RGO.OrgId = tEM.OrgID AND RGO.ReportRemarkGroupId =  4
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 (ROG.ReportId = @rReportId OR @rReportId = 0) 
END
GO
PRINT N'Altering [sSecurity].[pPendingLoginStudentdGet]...';


GO
ALTER PROCEDURE [sSecurity].[pPendingLoginStudentdGet]
	
	@rOrgId smallint,
	@rBatchId int,
	@rIsPendingLogin bit,
	@rIsCreatedLogin bit
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	SELECT  TOP 50
			ISNULL(U.Id,0) AS Id,
			SC.StudentId,
			SC.Code,
			SC.Name,
			SC.ClassName + '-' + SC.DivisionName AS ClassName,
			SC.RollNo,
			ISNULL(SC.ParentContactNo,'') AS MobileNo,
			ISNULL(SC.ParentEmail,'') AS EmailId,
			U.LoginTitle AS UserName,
			U.LoginPassword
	FROM 
			sStudent.vStudentCommunication SC
	LEFT JOIN sSecurity.tUser U ON U.SourceId = SC.StudentId AND U.SourceTypeId=2003 
	WHERE 
				(U.LoginPassWord is Null AND @rIsPendingLogin=1)
			OR (U.LoginPassWord is NOT Null AND @rIsCreatedLogin=1)
			AND	(SC.OrgId = @rOrgId)
			AND	(SC.BatchId = @rBatchId) 
	Order By SC.DivisionOrderIndex,SC.RollNo
	
END
GO
PRINT N'Altering [sSetup].[pPortalEmailConfigurationAdd]...';


GO
ALTER PROCEDURE [sSetup].[pPortalEmailConfigurationAdd]
	
	@rStrXml nvarchar(MAX),
    @rOrgId int
    
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET @rStrXml=REPLACE(@rStrXml,'&','AND')
DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION 
	 BEGIN
	 
	 DELETE FROM sAlert.tEmailConfiguration WHERE OrgId = @rOrgId
	 
	 INSERT INTO sAlert.tEmailConfiguration
		(
			OrgId,
			MailTypeId,
			SMTPServer,
			SMTPPort,
			EnableSSL,
			SendUserName,
			SendPassword,
			FromMail
			)
		SELECT		
			OrgId,
			MailTypeId,
			sSetup.fPortalXMLTagsReplaceReverse(SMTPServer),
			SMTPPort,
			EnableSSL,
			sSetup.fPortalXMLTagsReplaceReverse(SendUserName),
			sSetup.fPortalXMLTagsReplaceReverse(SendPassword),
			sSetup.fPortalXMLTagsReplaceReverse(FromMail)
			
						
		FROM OPENXML (@loDoc, '/Table/RowData', 1)
		WITH ( 
				OrgId smallint,
				MailTypeId tinyint,
				SMTPServer nvarchar(500),
				SMTPPort int,
				EnableSSL bit,
				SendUserName nvarchar(200),
				SendPassword nvarchar(200),
				FromMail nvarchar(200)
			  ) 
		
		
        SELECT 1 AS Result
	 END	
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sSetup].[pPortalEmployeeDesignationMasterUpdate]...';


GO


ALTER PROCEDURE [sSetup].[pPortalEmployeeDesignationMasterUpdate]
	 
	@rStrXml [nvarchar](max),
	@rOrgId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET @rStrXml=REPLACE(@rStrXml,'&','AND')

DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml
BEGIN
	BEGIN TRY
	

	 BEGIN	
	
	UPDATE sHrm.tEmployeeDesignationMaster
		SET
			OrgId = A.OrgId,
			Code = sSetup.fPortalXMLTagsReplaceReverse(A.Code),
			Title = sSetup.fPortalXMLTagsReplaceReverse(A.Title),
			IsObsolete = A.IsObsolete,
			CreatedUserId = A.CreatedUserId,
			CreatedDateTime = A.CreatedDateTime,
			UpdatedUserId = A.UpdatedUserId,
			UpdatedDateTime = A.UpdatedDateTime
		 FROM
		 (
		SELECT		
			OrgId,
			Id,
			Code,
			Title,
			IsObsolete,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime
		
						
		FROM OPENXML (@loDoc, '/Table/RowData', 1)
		WITH ( 
				[OrgId] [smallint],
				[Id] [int],
				[Code] [nvarchar](100),
				[Title] [nvarchar](100),
				[IsObsolete] [bit],
				[CreatedUserId] [bigint],
				[CreatedDateTime] [datetime],
				[UpdatedUserId] [bigint],
				[UpdatedDateTime] [datetime]
			  )) A
			  WHERE sHrm.tEmployeeDesignationMaster.Id = A.Id
		
		
		
		 INSERT INTO sHrm.tEmployeeDesignationMaster
		(
			OrgId,
			Id,
			Code,
			Title,
			IsObsolete,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime
			)
		SELECT		
			A.OrgId,
			A.Id,
			sSetup.fPortalXMLTagsReplaceReverse(A.Code),
			sSetup.fPortalXMLTagsReplaceReverse(A.Title),
			A.IsObsolete,
			A.CreatedUserId,
			A.CreatedDateTime,
			A.UpdatedUserId,
			A.UpdatedDateTime
						
		FROM OPENXML (@loDoc, '/Table/RowData', 1)
		WITH ( 
				[OrgId] [smallint],
				[Id] [int],
				[Code] [nvarchar](100),
				[Title] [nvarchar](100),
				[IsObsolete] [bit],
				[CreatedUserId] [bigint],
				[CreatedDateTime] [datetime],
				[UpdatedUserId] [bigint],
				[UpdatedDateTime] [datetime]
			  ) A LEFT JOIN sHrm.tEmployeeDesignationMaster EDM
			  ON A.Id = EDM.Id WHERE EDM.Id IS NULL
		
		 EXEC sp_xml_removedocument @loDoc
        SELECT 1 AS Result
	 END	
	
	END TRY
	
	BEGIN CATCH 
		
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sSetup].[pPortalEmployeeGradeMasterUpdate]...';


GO


ALTER PROCEDURE [sSetup].[pPortalEmployeeGradeMasterUpdate]
	 
	@rStrXml [nvarchar](max),
	@rOrgId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET @rStrXml=REPLACE(@rStrXml,'&','AND')

DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml
BEGIN
	BEGIN TRY
	

	 BEGIN	
	
	UPDATE sHrm.tEmployeeGradeMaster
		SET
		
			Code = sSetup.fPortalXMLTagsReplaceReverse(A.Code),
			Title = sSetup.fPortalXMLTagsReplaceReverse(A.Title),
			IsFixPay = A.IsFixPay,
			IsPayrollApplicable = A.IsPayrollApplicable,
			OrgId = A.OrgId,
			IsObsolete = A.IsObsolete,
			CreatedUserId = A.CreatedUserId,
			CreatedDateTime = A.CreatedDateTime,
			UpdatedUserId = A.UpdatedUserId,
			UpdatedDateTime = A.UpdatedDateTime,
			OrderIndex = A.OrderIndex
		
		 FROM
		 (
		SELECT		
			Id,
			Code,
			Title,
			IsFixPay,
			IsPayrollApplicable,
			OrgId,
			IsObsolete,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime,
			OrderIndex
		
						
		FROM OPENXML (@loDoc, '/Table/RowData', 1)
		WITH ( 
			[Id] [int],
			[Code] [nvarchar](50),
			[Title] [nvarchar](100),
			[IsFixPay] [bit],
			[IsPayrollApplicable] [bit],
			[OrgId] [smallint],
			[IsObsolete] [bit],
			[CreatedUserId] [bigint],
			[CreatedDateTime] [datetime],
			[UpdatedUserId] [bigint],
			[UpdatedDateTime] [datetime],
			[OrderIndex] [int]
			  )) A
			  WHERE sHrm.tEmployeeGradeMaster.Id = A.Id
		
		
		
		 INSERT INTO sHrm.tEmployeeGradeMaster
		(
			Id,
			Code,
			Title,
			IsFixPay,
			IsPayrollApplicable,
			OrgId,
			IsObsolete,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime,
			OrderIndex
			)
		SELECT		
			A.Id,
			sSetup.fPortalXMLTagsReplaceReverse(A.Code),
			sSetup.fPortalXMLTagsReplaceReverse(A.Title),
			A.IsFixPay,
			A.IsPayrollApplicable,
			A.OrgId,
			A.IsObsolete,
			A.CreatedUserId,
			A.CreatedDateTime,
			A.UpdatedUserId,
			A.UpdatedDateTime,
			A.OrderIndex
						
		FROM OPENXML (@loDoc, '/Table/RowData', 1)
		WITH ( 
			[Id] [int],
			[Code] [nvarchar](50),
			[Title] [nvarchar](100),
			[IsFixPay] [bit],
			[IsPayrollApplicable] [bit],
			[OrgId] [smallint],
			[IsObsolete] [bit],
			[CreatedUserId] [bigint],
			[CreatedDateTime] [datetime],
			[UpdatedUserId] [bigint],
			[UpdatedDateTime] [datetime],
			[OrderIndex] [int]
			  ) A LEFT JOIN sHrm.tEmployeeGradeMaster EGM
			  ON A.Id = EGM.Id WHERE EGM.Id IS NULL
		
		 EXEC sp_xml_removedocument @loDoc
        SELECT 1 AS Result
	 END	
	
	END TRY
	
	BEGIN CATCH 
		
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sSetup].[pPortalEmployeeJobDetailUpdate]...';


GO


ALTER PROCEDURE [sSetup].[pPortalEmployeeJobDetailUpdate]
	 
	@rStrXml [nvarchar](max),
	@rOrgId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET @rStrXml=REPLACE(@rStrXml,'&','AND')

DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml
BEGIN
	BEGIN TRY
	

	 BEGIN	
	
	UPDATE sHrm.tEmployeeJobDetail
		SET
			OrgId = A.OrgId,
			EmployeeDesignationId = A.EmployeeDesignationId,
			OrganizationDepartmentId = A.OrganizationDepartmentId,
			DateOfJoining = A.DateOfJoining,
			UpdatedUserId = A.UpdatedUserId,
			UpdatedDateTime = A.UpdatedDateTime,
			EmployeeTypeId = A.EmployeeTypeId,
			DateOfleaving = A.DateOfleaving,
			ReasonOfleaving = sSetup.fPortalXMLTagsReplaceReverse(A.ReasonOfleaving),
			EmployeeGroupId = A.EmployeeGroupId,
			EmployeeGradeId = A.EmployeeGradeId,
			JobRemark = sSetup.fPortalXMLTagsReplaceReverse(A.JobRemark),
			EmployeeManagerId = A.EmployeeManagerId
		 FROM
		 (
		SELECT		
		OrgId,
		EmployeeId,
		EmployeeDesignationId,
		OrganizationDepartmentId,
		DateOfJoining,
		UpdatedUserId,
		UpdatedDateTime,
		EmployeeTypeId,
		DateOfleaving,
		ReasonOfleaving,
		EmployeeGroupId,
		EmployeeGradeId,
	    JobRemark,
		EmployeeManagerId
						
		FROM OPENXML (@loDoc, '/Table/RowData', 1)
		WITH ( 
			[OrgId] [smallint],
			[EmployeeId] [bigint],
			[EmployeeDesignationId] [int],
			[OrganizationDepartmentId] [int],
			[DateOfJoining] [date],
			[UpdatedUserId] [bigint],
			[UpdatedDateTime] [datetime],
			[EmployeeTypeId] [int],
			[DateOfleaving] [date],
			[ReasonOfleaving] [nvarchar](200),
			[EmployeeGroupId] [tinyint],
			[EmployeeGradeId] [int],
			[JobRemark] [nvarchar](200),
			[EmployeeManagerId] [bigint]
			  )) A
			  WHERE sHrm.tEmployeeJobDetail.EmployeeId = A.EmployeeId
		
		
		
		 INSERT INTO sHrm.tEmployeeJobDetail
		(
			OrgId,
			EmployeeId,
			EmployeeDesignationId,
			OrganizationDepartmentId,
			DateOfJoining,
			UpdatedUserId,
			UpdatedDateTime,
			EmployeeTypeId,
			DateOfleaving,
			ReasonOfleaving,
			EmployeeGroupId,
			EmployeeGradeId,
			JobRemark,
			EmployeeManagerId
			)
		SELECT		
			A.OrgId,
			A.EmployeeId,
			A.EmployeeDesignationId,
			A.OrganizationDepartmentId,
			A.DateOfJoining,
			A.UpdatedUserId,
			A.UpdatedDateTime,
			A.EmployeeTypeId,
			A.DateOfleaving,
			sSetup.fPortalXMLTagsReplaceReverse(A.ReasonOfleaving),
			A.EmployeeGroupId,
			A.EmployeeGradeId,
			sSetup.fPortalXMLTagsReplaceReverse(A.JobRemark),
			A.EmployeeManagerId
						
		FROM OPENXML (@loDoc, '/Table/RowData', 1)
		WITH ( 
				[OrgId] [smallint],
				[EmployeeId] [bigint],
				[EmployeeDesignationId] [int],
				[OrganizationDepartmentId] [int],
				[DateOfJoining] [date],
				[UpdatedUserId] [bigint],
				[UpdatedDateTime] [datetime],
				[EmployeeTypeId] [int],
				[DateOfleaving] [date],
				[ReasonOfleaving] [nvarchar](200),
				[EmployeeGroupId] [tinyint],
				[EmployeeGradeId] [int],
				[JobRemark] [nvarchar](200),
				[EmployeeManagerId] [bigint]
			  ) A LEFT JOIN sHrm.tEmployeeJobDetail EJD
			  ON A.EmployeeId = EJD.EmployeeId WHERE EJD.EmployeeId IS NULL
		
		 EXEC sp_xml_removedocument @loDoc
        SELECT 1 AS Result
	 END	
	
	END TRY
	
	BEGIN CATCH 
		
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sSetup].[pPortalEmployeeMasterUpdate]...';


GO


ALTER PROCEDURE [sSetup].[pPortalEmployeeMasterUpdate]
	 
	@rStrXml [nvarchar](max),
	@rOrgId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET @rStrXml=REPLACE(@rStrXml,'&','AND')

DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml
BEGIN
	BEGIN TRY
	

	 BEGIN	
	
	UPDATE sHrm.tEmployeeMaster
		SET
			OrgID = A.OrgID,
			Code = A.Code,
			FirstName = sSetup.fPortalXMLTagsReplaceReverse(A.FirstName),
			MiddleName = sSetup.fPortalXMLTagsReplaceReverse(A.MiddleName),
			LastName = sSetup.fPortalXMLTagsReplaceReverse(A.LastName),
			ShortName = sSetup.fPortalXMLTagsReplaceReverse(A.ShortName),
			StatusId = A.StatusId,
			IsObsolete = A.IsObsolete,
			CreatedUserId = A.CreatedUserId,
			CreatedDateTime = A.CreatedDateTime,
			UpdatedUserId = A.UpdatedUserId,
			UpdatedDateTime = A.UpdatedDateTime
		 FROM
		 (
		SELECT		
			OrgID,
			Id,
			Code,
			FirstName,
			MiddleName,
			LastName,
			ShortName,
			StatusId,
			IsObsolete,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,		
			UpdatedDateTime
						
		FROM OPENXML (@loDoc, '/Table/RowData', 1)
		WITH ( 
			[OrgID] [smallint],
			[Id] [bigint],
			[Code] [nvarchar](20),
			[FirstName] [nvarchar](100),
			[MiddleName] [nvarchar](100),
			[LastName] [nvarchar](100),
			[ShortName] [nvarchar](50),
			[StatusId] [smallint],
			[IsObsolete] [bit],
			[CreatedUserId] [bigint],
			[CreatedDateTime] [datetime],
			[UpdatedUserId] [bigint],
			[UpdatedDateTime] [datetime]
			  )) A
			  WHERE sHrm.tEmployeeMaster.Id = A.Id
		
		
		
		 INSERT INTO sHrm.tEmployeeMaster
		(
			OrgID,
			Id,
			Code,
			FirstName,
			MiddleName,
			LastName,
			ShortName,
			StatusId,
			IsObsolete,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,		
			UpdatedDateTime
			)
		SELECT		
			A.OrgID,
			A.Id,
			A.Code,
			sSetup.fPortalXMLTagsReplaceReverse(A.FirstName),
			sSetup.fPortalXMLTagsReplaceReverse(A.MiddleName),
			sSetup.fPortalXMLTagsReplaceReverse(A.LastName),
			sSetup.fPortalXMLTagsReplaceReverse(A.ShortName),
			A.StatusId,
			A.IsObsolete,
			A.CreatedUserId,
			A.CreatedDateTime,
			A.UpdatedUserId,		
			A.UpdatedDateTime
						
		FROM OPENXML (@loDoc, '/Table/RowData', 1)
		WITH ( 
				[OrgID] [smallint],
				[Id] [bigint],
				[Code] [nvarchar](20),
				[FirstName] [nvarchar](100),
				[MiddleName] [nvarchar](100),
				[LastName] [nvarchar](100),
				[ShortName] [nvarchar](50),
				[StatusId] [smallint],
				[IsObsolete] [bit],
				[CreatedUserId] [bigint],
				[CreatedDateTime] [datetime],
				[UpdatedUserId] [bigint],
				[UpdatedDateTime] [datetime]
			  ) A LEFT JOIN sHrm.tEmployeeMaster EM
			  ON A.Id = EM.Id WHERE EM.Id IS NULL
		
		 EXEC sp_xml_removedocument @loDoc
        SELECT 1 AS Result
	 END	
	
	END TRY
	
	BEGIN CATCH 
		
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sSetup].[pPortalEmployeePersonalDetailUpdate]...';


GO


ALTER PROCEDURE [sSetup].[pPortalEmployeePersonalDetailUpdate]
	 
	@rStrXml [nvarchar](max),
	@rOrgId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET @rStrXml=REPLACE(@rStrXml,'&','AND')

DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml
BEGIN
	BEGIN TRY
	

	 BEGIN	
	
	UPDATE sHrm.tEmployeePersonalDetail
		SET
			OrgId = A.OrgId,
			UIDNumber = A.UIDNumber,
			DateOfBirth = A.DateOfBirth,
			GenderId = A.GenderId,
			ReligionId = A.ReligionId,
			MaritalStatusId = A.MaritalStatusId,
			IdentificationMark1 = sSetup.fPortalXMLTagsReplaceReverse(A.IdentificationMark1),
			BloodGroupId = A.BloodGroupId,
			Qualification = sSetup.fPortalXMLTagsReplaceReverse(A.Qualification),
			UpdatedUserId = A.UpdatedUserId,
			UpdatedDateTime = A.UpdatedDateTime,
			FamilyCast = sSetup.fPortalXMLTagsReplaceReverse(A.FamilyCast),
			CastCategoryId = A.CastCategoryId
			
		 FROM
		 (
		SELECT		
			OrgID,
			EmployeeId,
			UIDNumber,
			DateOfBirth,
			GenderId,
			ReligionId,
			MaritalStatusId,
			IdentificationMark1,
			BloodGroupId,
			Qualification,
			UpdatedUserId,
			UpdatedDateTime,
			FamilyCast,
			CastCategoryId
						
		FROM OPENXML (@loDoc, '/Table/RowData', 1)
		WITH ( 
				[OrgId] [smallint],
				[EmployeeId] [bigint],
				[UIDNumber] [nvarchar](50),
				[DateOfBirth] [date],
				[GenderId] [tinyint],
				[ReligionId] [int],
				[MaritalStatusId] [tinyint],
				[IdentificationMark1] [nvarchar](100),
				[BloodGroupId] [tinyint],
				[Qualification] [nvarchar](150),
				[UpdatedUserId] [bigint],
				[UpdatedDateTime] [datetime],
				[FamilyCast] [nvarchar](150),
				[CastCategoryId] [int]
			  )) A
			  WHERE sHrm.tEmployeePersonalDetail.EmployeeId = A.EmployeeId
		
		
		
		 INSERT INTO sHrm.tEmployeePersonalDetail
		(
			OrgID,
			EmployeeId,
			UIDNumber,
			DateOfBirth,
			GenderId,
			ReligionId,
			MaritalStatusId,
			IdentificationMark1,
			BloodGroupId,
			Qualification,
			UpdatedUserId,
			UpdatedDateTime,
			FamilyCast,
			CastCategoryId
			)
		SELECT		
			A.OrgID,
			A.EmployeeId,
			A.UIDNumber,
			A.DateOfBirth,
			A.GenderId,
			A.ReligionId,
			A.MaritalStatusId,
			sSetup.fPortalXMLTagsReplaceReverse(A.IdentificationMark1),
			A.BloodGroupId,
			sSetup.fPortalXMLTagsReplaceReverse(A.FamilyCast),
			A.UpdatedUserId,
			A.UpdatedDateTime,
			sSetup.fPortalXMLTagsReplaceReverse(A.IdentificationMark1),
			A.CastCategoryId
						
		FROM OPENXML (@loDoc, '/Table/RowData', 1)
		WITH ( 
				[OrgId] [smallint],
				[EmployeeId] [bigint],
				[UIDNumber] [nvarchar](50),
				[DateOfBirth] [date],
				[GenderId] [tinyint],
				[ReligionId] [int],
				[MaritalStatusId] [tinyint],
				[IdentificationMark1] [nvarchar](100),
				[BloodGroupId] [tinyint],
				[Qualification] [nvarchar](150),
				[UpdatedUserId] [bigint],
				[UpdatedDateTime] [datetime],
				[FamilyCast] [nvarchar](150),
				[CastCategoryId] [int]
			  ) A LEFT JOIN sHrm.tEmployeePersonalDetail EPD
			  ON A.EmployeeId = EPD.EmployeeId WHERE EPD.EmployeeId IS NULL
		
		 EXEC sp_xml_removedocument @loDoc
        SELECT 1 AS Result
	 END	
	
	END TRY
	
	BEGIN CATCH 
		
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sSetup].[pPortalEmployeeTypeMasterUpdate]...';


GO


ALTER PROCEDURE [sSetup].[pPortalEmployeeTypeMasterUpdate]
	 
	@rStrXml [nvarchar](max),
	@rOrgId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET @rStrXml=REPLACE(@rStrXml,'&','AND')

DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml
BEGIN
	BEGIN TRY
	

	 BEGIN	
	
	UPDATE sHrm.tEmployeeTypeMaster
		SET
			OrgId = A.OrgId,
			Code = sSetup.fPortalXMLTagsReplaceReverse(A.Code),
			Title = sSetup.fPortalXMLTagsReplaceReverse(A.Title),
			IsObsolete = A.IsObsolete,
			CreatedUserId = A.CreatedUserId,
			CreatedDateTime = A.CreatedDateTime,
			UpdatedUserId = A.UpdatedUserId,
			UpdatedDateTime = A.UpdatedDateTime
		 FROM
		 (
		SELECT		
			OrgId,
			Id,
			Code,
			Title,
			IsObsolete,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime
		
						
		FROM OPENXML (@loDoc, '/Table/RowData', 1)
		WITH ( 
				[OrgId] [smallint],
				[Id] [int],
				[Code] [nvarchar](100),
				[Title] [nvarchar](100),
				[IsObsolete] [bit],
				[CreatedUserId] [bigint],
				[CreatedDateTime] [datetime],
				[UpdatedUserId] [bigint],
				[UpdatedDateTime] [datetime]
			  )) A
			  WHERE sHrm.tEmployeeTypeMaster.Id = A.Id
		
		
		
		 INSERT INTO sHrm.tEmployeeTypeMaster
		(
			OrgId,
			Id,
			Code,
			Title,
			IsObsolete,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime
			)
		SELECT		
			A.OrgId,
			A.Id,
			sSetup.fPortalXMLTagsReplaceReverse(A.Code),
			sSetup.fPortalXMLTagsReplaceReverse(A.Title),
			A.IsObsolete,
			A.CreatedUserId,
			A.CreatedDateTime,
			A.UpdatedUserId,
			A.UpdatedDateTime
						
		FROM OPENXML (@loDoc, '/Table/RowData', 1)
		WITH ( 
				[OrgId] [smallint],
				[Id] [int],
				[Code] [nvarchar](100),
				[Title] [nvarchar](100),
				[IsObsolete] [bit],
				[CreatedUserId] [bigint],
				[CreatedDateTime] [datetime],
				[UpdatedUserId] [bigint],
				[UpdatedDateTime] [datetime]
			  ) A LEFT JOIN sHrm.tEmployeeTypeMaster EDM
			  ON A.Id = EDM.Id WHERE EDM.Id IS NULL
		
		 EXEC sp_xml_removedocument @loDoc
        SELECT 1 AS Result
	 END	
	
	END TRY
	
	BEGIN CATCH 
		
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sSetup].[pPortalMasterOrganizationUpdate]...';


GO


ALTER PROCEDURE [sSetup].[pPortalMasterOrganizationUpdate]
	 
	@rStrXml [nvarchar](max),
	@rOrgId int=0,
	@rOrgGroupId int=0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET @rStrXml=REPLACE(@rStrXml,'&','AND')

DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml
BEGIN
	BEGIN TRY
	

	 BEGIN	

IF EXISTS(SELECT 1 FROM sSetup.tOrganizationMaster WHERE Id = 	@rOrgId)
BEGIN
	UPDATE sSetup.tOrganizationMaster
		SET
			Code = A.Code,
			Title = A.Title,
			DisplayTitle = A.DisplayTitle,
			AffiliationId = A.AffiliationId,
			LanguageId = A.LanguageId,
			StreetOne = sSetup.fPortalXMLTagsReplaceReverse(A.StreetOne),
			StreetTwo = sSetup.fPortalXMLTagsReplaceReverse(A.StreetTwo),
			StreetThree = sSetup.fPortalXMLTagsReplaceReverse(A.StreetThree),
			CityName = A.CityName,
			StateName = A.StateName,
			CountryName = A.CountryName,
			ZipCode = A.ZipCode,
			HomePage = A.HomePage,
			PhoneNo = A.PhoneNo,
			FaxNo = A.FaxNo,
			ReportOrgTitle = A.ReportOrgTitle,
			SmallAddress1 = A.SmallAddress1,
			SmallAddress2 = A.SmallAddress2,
			RegistrationDetail = A.RegistrationDetail,
			CreatedUserId = A.CreatedUserId,
			CreatedDateTime = A.CreatedDateTime,
			UpdatedUserId = A.UpdatedUserId,
			UpdatedDateTime = A.UpdatedDateTime,
			IsObsolete = A.IsObsolete,
			OrgGroupId = A.OrgGroupId,
			OrgLogo = [sCommon].[Base64Decode](A.OrgLogo),
			EmployeeId = A.EmployeeId,
			OrderIndex = A.OrderIndex,
			PrincipalSignature = [sCommon].[Base64Decode](A.PrincipalSignature),
			OrgSubGroupId = A.OrgSubGroupId,
			TermPatternId = A.TermPatternId,
			LoginBG = [sCommon].[Base64Decode](A.LoginBG),
			WeekOffs = A.WeekOffs,
			StudentNameFormatId = A.StudentNameFormatId,
			ReportOrgGroupTitle = A.ReportOrgGroupTitle,
			DegreeAwarded = A.DegreeAwarded,
			ShortCode = A.ShortCode,
			NoOfTerm = A.NoOfTerm,
			LetterHeadMargin = A.LetterHeadMargin
		 FROM
		 (
		SELECT		
			Id,
			Code,
			Title,
			DisplayTitle,
			AffiliationId,
			LanguageId,
			StreetOne,
			StreetTwo,
			StreetThree,
			CityName,
			StateName,
			CountryName,
			ZipCode,
			HomePage,
			PhoneNo,
			FaxNo,
			ReportOrgTitle,
			SmallAddress1,
			SmallAddress2,
			RegistrationDetail,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime,
			IsObsolete,
			OrgGroupId,
			OrgLogo,
			EmployeeId,
			OrderIndex,
			PrincipalSignature,
			OrgSubGroupId,
			TermPatternId,
			LoginBG,
			WeekOffs,
			StudentNameFormatId,
			ReportOrgGroupTitle,
			DegreeAwarded,
			ShortCode,
			NoOfTerm,
			LetterHeadMargin
						
		FROM OPENXML (@loDoc, '/Table/RowData', 1)
		WITH ( 
				[Id] [smallint],
				[Code] [nvarchar](20),
				[Title] [nvarchar](100),
				[DisplayTitle] [nvarchar](100),
				[AffiliationId] [smallint],
				[LanguageId] [smallint],
				[StreetOne] [nvarchar](50),
				[StreetTwo] [nvarchar](50),
				[StreetThree] [nvarchar](50),
				[CityName] [nvarchar](100),
				[StateName] [nvarchar](100),
				[CountryName] [nvarchar](100),
				[ZipCode] [nvarchar](20),
				[HomePage] [nvarchar](100),
				[PhoneNo] [nvarchar](50),
				[FaxNo] [nvarchar](50),
				[ReportOrgTitle] [nvarchar](200),
				[SmallAddress1] [nvarchar](200),
				[SmallAddress2] [nvarchar](200),
				[RegistrationDetail] [nvarchar](200),
				[CreatedUserId] [bigint],
				[CreatedDateTime] [datetime],
				[UpdatedUserId] [bigint],
				[UpdatedDateTime] [datetime],
				[IsObsolete] [bit],
				[OrgGroupId] [smallint],
				[OrgLogo] nvarchar(Max),
				[EmployeeId] [bigint],
				[OrderIndex] [int],
				[PrincipalSignature] nvarchar(Max),
				[OrgSubGroupId] [int],
				TermPatternId tinyint,
				LoginBG nvarchar(Max),
				WeekOffs nvarchar(50),
				StudentNameFormatId tinyint,
				ReportOrgGroupTitle nvarchar(200),
				DegreeAwarded nvarchar(100),
			    ShortCode nvarchar(20),
			    NoOfTerm tinyint,
			    LetterHeadMargin int
			  )) A
			  WHERE sSetup.tOrganizationMaster.Id = A.Id
		
END
ELSE
BEGIN		
		
		 INSERT INTO sSetup.tOrganizationMaster
		(
			Id,
			Code,
			Title,
			DisplayTitle,
			AffiliationId,
			LanguageId,
			StreetOne,
			StreetTwo,
			StreetThree,
			CityName,
			StateName,
			CountryName,
			ZipCode,
			HomePage,
			PhoneNo,
			FaxNo,
			ReportOrgTitle,
			SmallAddress1,
			SmallAddress2,
			RegistrationDetail,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime,
			IsObsolete,
			OrgGroupId,
			OrgLogo,
			EmployeeId,
			OrderIndex,
			PrincipalSignature,
			OrgSubGroupId,
			TermPatternId,
			LoginBG,
			WeekOffs,
			StudentNameFormatId,
			ReportOrgGroupTitle,
			DegreeAwarded,
			ShortCode,
			NoOfTerm,
			LetterHeadMargin
			)
		SELECT		
			A.Id,
			A.Code,
			A.Title,
			A.DisplayTitle,
			A.AffiliationId,
			A.LanguageId,
			sSetup.fPortalXMLTagsReplaceReverse(A.StreetOne),
			sSetup.fPortalXMLTagsReplaceReverse(A.StreetTwo),
			sSetup.fPortalXMLTagsReplaceReverse(A.StreetThree),
			A.CityName,
			A.StateName,
			A.CountryName,
			A.ZipCode,
			A.HomePage,
			A.PhoneNo,
			A.FaxNo,
			A.ReportOrgTitle,
			A.SmallAddress1,
			A.SmallAddress2,
			A.RegistrationDetail,
			A.CreatedUserId,
			A.CreatedDateTime,
			A.UpdatedUserId,
			A.UpdatedDateTime,
			A.IsObsolete,
			A.OrgGroupId,
			[sCommon].[Base64Decode](A.OrgLogo),
			A.EmployeeId,
			A.OrderIndex,
			[sCommon].[Base64Decode](A.PrincipalSignature),
			A.OrgSubGroupId,
			A.TermPatternId,
			[sCommon].[Base64Decode](A.LoginBG),
			A.WeekOffs,
			A.StudentNameFormatId,
			A.ReportOrgGroupTitle,
			A.DegreeAwarded,
			A.ShortCode,
			A.NoOfTerm,
			A.LetterHeadMargin
						
		FROM OPENXML (@loDoc, '/Table/RowData', 1)
		WITH ( 
				[Id] [smallint],
				[Code] [nvarchar](20),
				[Title] [nvarchar](100),
				[DisplayTitle] [nvarchar](100),
				[AffiliationId] [smallint],
				[LanguageId] [smallint],
				[StreetOne] [nvarchar](50),
				[StreetTwo] [nvarchar](50),
				[StreetThree] [nvarchar](50),
				[CityName] [nvarchar](100),
				[StateName] [nvarchar](100),
				[CountryName] [nvarchar](100),
				[ZipCode] [nvarchar](20),
				[HomePage] [nvarchar](100),
				[PhoneNo] [nvarchar](50),
				[FaxNo] [nvarchar](50),
				[ReportOrgTitle] [nvarchar](200),
				[SmallAddress1] [nvarchar](200),
				[SmallAddress2] [nvarchar](200),
				[RegistrationDetail] [nvarchar](200),
				[CreatedUserId] [bigint],
				[CreatedDateTime] [datetime],
				[UpdatedUserId] [bigint],
				[UpdatedDateTime] [datetime],
				[IsObsolete] [bit],
				[OrgGroupId] [smallint],
				[OrgLogo] nvarchar(Max),
				[EmployeeId] [bigint],
				[OrderIndex] [int],
				[PrincipalSignature] nvarchar(Max),
				[OrgSubGroupId] [int],
				TermPatternId tinyint,
				LoginBG nvarchar(Max),
				WeekOffs nvarchar(50),
				StudentNameFormatId tinyint,
				ReportOrgGroupTitle nvarchar(200),
				DegreeAwarded nvarchar(100),
			    ShortCode nvarchar(20),
			    NoOfTerm tinyint,
			    LetterHeadMargin int
			  ) A LEFT JOIN sSetup.tOrganizationMaster OM
			  ON A.Id = OM.Id WHERE OM.Id IS NULL
			  
	EXECUTE [sCommon].[pOrganizationSetupAdd]  @rOrgId,1
			  
	END	
		 EXEC sp_xml_removedocument @loDoc
        SELECT 1 AS Result
	 END	
	
	END TRY
	
	BEGIN CATCH 
		
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sSetup].[pPortalMonthlyRegisterUpdate]...';


GO


ALTER PROCEDURE [sSetup].[pPortalMonthlyRegisterUpdate]
	 
	@rStrXml [nvarchar](max),
	@rDivisionId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET @rStrXml=REPLACE(@rStrXml,'&','AND')

DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml
BEGIN
	BEGIN TRY
	

	 BEGIN	
	
	 
	 DELETE MR FROM sAttendance.tMonthlyRegister MR 
	 INNER JOIN sStudent.tAcademic SA ON SA.Id = MR.AcademicId
	 INNER JOIN 
	 (SELECT AcademicId, AttendanceTypeId, SubjectId,ForMonth,ForYear FROM OPENXML(@loDoc, '/Table/RowData', 1)
	 WITH
	 (		
		[AcademicId] [bigint],
		[AttendanceTypeId] [tinyint],
		[SubjectId] [int],
		[ForMonth] [tinyint],
		[ForYear] [smallint]
	  ))A ON MR.AcademicId = A.AcademicId 
		AND MR.AttendanceTypeId = A.AttendanceTypeId 
		AND ISNULL(MR.SubjectId,0) = ISNULL(A.SubjectId,0)
		AND MR.ForMonth = A.ForMonth
		AND MR.ForYear = A.ForYear
		WHERE SA.DivisionId=@rDivisionId
		
	--UPDATE sAttendance.tMonthlyRegister
	--	SET
	--		AttendanceTypeId = A.AttendanceTypeId,
	--		SubjectId = A.SubjectId,
	--		ForMonth = A.ForMonth,
	--		ForYear = A.ForYear,
	--		TotalCount = A.TotalCount,
	--		PresentCount = A.PresentCount,
	--		AbsentCount = A.AbsentCount,
	--		AveragePresence = A.AveragePresence,
	--		AbsentDays = A.AbsentDays,
	--		UpdatedUserId = A.UpdatedUserId,
	--		UpdatedDateTime = A.UpdatedDateTime
	--	 FROM
	--	 (
	--	SELECT		
	--		AcademicId,
	--		AttendanceTypeId,
	--		SubjectId,
	--		ForMonth,
	--		ForYear,
	--		TotalCount,
	--		PresentCount,
	--		AbsentCount,
	--		AveragePresence,
	--		AbsentDays,
	--		UpdatedUserId,
	--		UpdatedDateTime
						
	--	FROM OPENXML (@loDoc, '/Table/RowData', 1)
	--	WITH ( 
	--		[AcademicId] [bigint],
	--		[AttendanceTypeId] [tinyint],
	--		[SubjectId] [int],
	--		[ForMonth] [tinyint],
	--		[ForYear] [smallint],
	--		[TotalCount] [tinyint],
	--		[PresentCount] [tinyint],
	--		[AbsentCount] [tinyint],
	--		[AveragePresence] [decimal](6, 2),
	--		[AbsentDays] [nvarchar](200),
	--		[UpdatedUserId] [bigint],
	--		[UpdatedDateTime] [datetime]
	--		  )) A
	--		  WHERE sAttendance.tMonthlyRegister.AcademicId = A.AcademicId 
	--		  AND sAttendance.tMonthlyRegister.AttendanceTypeId = A.AttendanceTypeId 
	--		  AND sAttendance.tMonthlyRegister.SubjectId = A.SubjectId 
	--		  AND sAttendance.tMonthlyRegister.ForMonth = A.ForMonth 
	--		  AND sAttendance.tMonthlyRegister.ForYear = A.ForYear 
		
		
		
		 INSERT INTO sAttendance.tMonthlyRegister
		(
			AcademicId,
			AttendanceTypeId,
			SubjectId,
			ForMonth,
			ForYear,
			TotalCount,
			PresentCount,
			AbsentCount,
			AveragePresence,
			AbsentDays,
			UpdatedUserId,
			UpdatedDateTime
			)
		SELECT		
			A.AcademicId,
			A.AttendanceTypeId,
			A.SubjectId,
			A.ForMonth,
			A.ForYear,
			A.TotalCount,
			A.PresentCount,
			A.AbsentCount,
			A.AveragePresence,
			A.AbsentDays,
			A.UpdatedUserId,
			A.UpdatedDateTime
						
		FROM OPENXML (@loDoc, '/Table/RowData', 1)
		WITH ( 
			[AcademicId] [bigint],
			[AttendanceTypeId] [tinyint],
			[SubjectId] [int],
			[ForMonth] [tinyint],
			[ForYear] [smallint],
			[TotalCount] [tinyint],
			[PresentCount] [tinyint],
			[AbsentCount] [tinyint],
			[AveragePresence] [decimal](6, 2),
			[AbsentDays] [nvarchar](200),
			[UpdatedUserId] [bigint],
			[UpdatedDateTime] [datetime]
			  ) A LEFT JOIN sAttendance.tMonthlyRegister MR
			  ON A.AcademicId = MR.AcademicId 
			  AND A.AttendanceTypeId = MR.AttendanceTypeId 
			  AND ISNULL(MR.SubjectId,0) = ISNULL(A.SubjectId,0)
			  AND A.ForMonth = MR.ForMonth 
			  AND A.ForYear = MR.ForYear 
			  WHERE MR.AcademicId IS NULL
		
		 EXEC sp_xml_removedocument @loDoc
        SELECT 1 AS Result
	 END	
	
	END TRY
	
	BEGIN CATCH 
		
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sSetup].[pPortalSMSConfigurationAdd]...';


GO
ALTER PROCEDURE [sSetup].[pPortalSMSConfigurationAdd]
	
	@rStrXml nvarchar(MAX),
    @rOrgId int
    
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET @rStrXml=REPLACE(@rStrXml,'&','AND')
DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION 
	 BEGIN
	 
	 DELETE FROM sAlert.tSMSConfiguration WHERE OrgId = @rOrgId
	 
	 INSERT INTO sAlert.tSMSConfiguration
		(
			OrgId,
			SMSURL,
			SMSCreditURL,
			LoginId,
			LoginPassword,
			LoginSenderId,
			SMSXMLURL,
			VendorId,
			SMSUnicodeURL
			)
		SELECT		
			OrgId,
			sSetup.fPortalXMLTagsReplaceReverse(SMSURL),
			sSetup.fPortalXMLTagsReplaceReverse(SMSCreditURL),
			sSetup.fPortalXMLTagsReplaceReverse(LoginId),
			sSetup.fPortalXMLTagsReplaceReverse(LoginPassword),
			sSetup.fPortalXMLTagsReplaceReverse(LoginSenderId),
			sSetup.fPortalXMLTagsReplaceReverse(SMSXMLURL),
			VendorId,
			sSetup.fPortalXMLTagsReplaceReverse(SMSUnicodeURL)
			
						
		FROM OPENXML (@loDoc, '/Table/RowData', 1)
		WITH ( 
				OrgId smallint,
				SMSURL nvarchar(1000),
				SMSCreditURL nvarchar(1000),
				LoginId nvarchar(50),
				LoginPassword nvarchar(50),
				LoginSenderId nvarchar(50),
				SMSXMLURL nvarchar(1000),
				VendorId smallint,
				SMSUnicodeURL nvarchar(1000)
			  ) 
		
		
        SELECT 1 AS Result
	 END	
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sSetup].[pPortalStudentCommunicationUpdate]...';


GO


ALTER PROCEDURE [sSetup].[pPortalStudentCommunicationUpdate]
	 
	
	@rStrXml [nvarchar](max),
	@rDivisionId int
	
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET @rStrXml=REPLACE(@rStrXml,'&','AND')

DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml
BEGIN
	--BEGIN TRY
	
	
	 BEGIN	

	 UPDATE sStudent.tStudentCommunication
		SET
			PresentStreetOne = sSetup.fPortalXMLTagsReplaceReverse(A.PresentStreetOne),
			PresentStreetTwo = sSetup.fPortalXMLTagsReplaceReverse(A.PresentStreetTwo),
			PresentStreetThree = sSetup.fPortalXMLTagsReplaceReverse(A.PresentStreetThree),
			PresentCity = sSetup.fPortalXMLTagsReplaceReverse(A.PresentCity),
			PresentZipCode = A.PresentZipCode,
			PermanentStreetOne = sSetup.fPortalXMLTagsReplaceReverse(A.PermanentStreetOne),
			PermanentStreetTwo = sSetup.fPortalXMLTagsReplaceReverse(A.PermanentStreetTwo),
			PermanentStreetThree = sSetup.fPortalXMLTagsReplaceReverse(A.PermanentStreetThree),
			PermanentCity = sSetup.fPortalXMLTagsReplaceReverse(A.PermanentCity),
			PermanentZipCode = A.PermanentZipCode,
			EmergencyStreetOne = sSetup.fPortalXMLTagsReplaceReverse(A.EmergencyStreetOne),
			EmergencyStreetTwo = sSetup.fPortalXMLTagsReplaceReverse(A.EmergencyStreetTwo),
			EmergencyStreetThree = sSetup.fPortalXMLTagsReplaceReverse(A.EmergencyStreetThree),
			EmergencyCity = sSetup.fPortalXMLTagsReplaceReverse(A.EmergencyCity),
			EmergencyZipCode = A.EmergencyZipCode,
			UpdatedUserId = A.UpdatedUserId,			
			ParentContactNo= A.ParentContactNo,
			ParentEmail= A.ParentEmail,
			StudentContactNo= A.StudentContactNo,
			StudentEmail= A.StudentEmail,
			UpdatedDateTime = A.UpdatedDateTime,
			CreatedDateTime = A.CreatedDateTime
		FROM
		(
		SELECT		
			StudentId,
			PresentStreetOne,
			PresentStreetTwo,
			PresentStreetThree,
			PresentCity,
			PresentZipCode,
			PermanentStreetOne,
			PermanentStreetTwo,
			PermanentStreetThree,
			PermanentCity,
			PermanentZipCode,
			EmergencyStreetOne,
			EmergencyStreetTwo,
			EmergencyStreetThree,
			EmergencyCity,
			EmergencyZipCode,
			UpdatedUserId,						
			ParentContactNo,
			ParentEmail,
			StudentContactNo,
			StudentEmail,
			UpdatedDateTime,
			CreatedDateTime
			
						
		FROM OPENXML (@loDoc, '/Table/StudentCommunication', 1)
		WITH ( 
				StudentId bigint,
				PresentStreetOne nvarchar(150),
				PresentStreetTwo nvarchar(150),
				PresentStreetThree nvarchar(150),
				PresentCity nvarchar(50),
				PresentZipCode nvarchar(20),
				PermanentStreetOne nvarchar(150),
				PermanentStreetTwo nvarchar(150),
				PermanentStreetThree nvarchar(150),
				PermanentCity nvarchar(50),
				PermanentZipCode nvarchar(20),
				EmergencyStreetOne nvarchar(150),
				EmergencyStreetTwo nvarchar(150),
				EmergencyStreetThree nvarchar(150),
				EmergencyCity nvarchar(50),
				EmergencyZipCode nvarchar(20),
				UpdatedUserId bigint,				
				ParentContactNo nvarchar(20),
				ParentEmail nvarchar(50),
				StudentContactNo nvarchar(20),
				StudentEmail nvarchar(50),
				UpdatedDateTime DateTime,
				CreatedDateTime DateTime
			  )) A
			  WHERE  sStudent.tStudentCommunication.StudentId = A.StudentId
		

		--	 DELETE FROM sStudent.tStudentCommunication WHERE
	 -- --StudentId IN (Select StudentId From sStudent.tAcademic Where DivisionId = @rDivisionId)
	 -- StudentId IN(
	 -- SELECT		
		--	StudentId
		--			FROM OPENXML (@loDoc, '/Table/StudentCommunication', 1)
		--WITH ( 
		--		StudentId bigint
		--		))

	 INSERT INTO sStudent.tStudentCommunication
		(
			StudentId,
			PresentStreetOne,
			PresentStreetTwo,
			PresentStreetThree,
			PresentCity,
			PresentZipCode,
			PermanentStreetOne,
			PermanentStreetTwo,
			PermanentStreetThree,
			PermanentCity,
			PermanentZipCode,
			EmergencyStreetOne,
			EmergencyStreetTwo,
			EmergencyStreetThree,
			EmergencyCity,
			EmergencyZipCode,
			CreatedUserId,			
			ParentContactNo,
			ParentEmail,
			StudentContactNo,
			StudentEmail,
			PresentContactNo,
			PermanentContactNo,
			EmergencyContactNo,
			UpdatedDateTime,
			CreatedDateTime
			)
		SELECT		
			A.StudentId,
			sSetup.fPortalXMLTagsReplaceReverse(A.PresentStreetOne),
			sSetup.fPortalXMLTagsReplaceReverse(A.PresentStreetTwo),
			sSetup.fPortalXMLTagsReplaceReverse(A.PresentStreetThree),
			sSetup.fPortalXMLTagsReplaceReverse(A.PresentCity),
			A.PresentZipCode,
			sSetup.fPortalXMLTagsReplaceReverse(A.PermanentStreetOne),
			sSetup.fPortalXMLTagsReplaceReverse(A.PermanentStreetTwo),
			sSetup.fPortalXMLTagsReplaceReverse(A.PermanentStreetThree),
			sSetup.fPortalXMLTagsReplaceReverse(A.PermanentCity),
			A.PermanentZipCode,
			sSetup.fPortalXMLTagsReplaceReverse(A.EmergencyStreetOne),
			sSetup.fPortalXMLTagsReplaceReverse(A.EmergencyStreetTwo),
			sSetup.fPortalXMLTagsReplaceReverse(A.EmergencyStreetThree),
			sSetup.fPortalXMLTagsReplaceReverse(A.EmergencyCity),
			A.EmergencyZipCode,
			A.CreatedUserId,			
			A.ParentContactNo,
			A.ParentEmail,
			A.StudentContactNo,
			A.StudentEmail,
			A.PresentContactNo,
			A.PermanentContactNo,
			A.EmergencyContactNo,
			A.UpdatedDateTime,
			A.CreatedDateTime
			
						
		FROM OPENXML (@loDoc, '/Table/StudentCommunication', 1)
		WITH ( 
				StudentId bigint,
				PresentStreetOne nvarchar(1150),
				PresentStreetTwo nvarchar(150),
				PresentStreetThree nvarchar(150),
				PresentCity nvarchar(50),
				PresentZipCode nvarchar(20),
				PermanentStreetOne nvarchar(150),
				PermanentStreetTwo nvarchar(150),
				PermanentStreetThree nvarchar(150),
				PermanentCity nvarchar(50),
				PermanentZipCode nvarchar(20),
				EmergencyStreetOne nvarchar(150),
				EmergencyStreetTwo nvarchar(150),
				EmergencyStreetThree nvarchar(150),
				EmergencyCity nvarchar(50),
				EmergencyZipCode nvarchar(20),
				CreatedUserId bigint,
				ParentContactNo nvarchar(20),
				ParentEmail nvarchar(50),
				StudentContactNo nvarchar(20),
				StudentEmail nvarchar(50),
				PresentContactNo  nvarchar(20),
				PermanentContactNo  nvarchar(20),
				EmergencyContactNo  nvarchar(20),
				UpdatedDateTime Datetime,
				CreatedDateTime DateTime
				
			  ) A LEFT JOIN sStudent.tStudentCommunication C
			  ON A.StudentId = C.StudentId WHERE C.StudentId IS NULL
			  --WHERE  A.StudentId NOT IN (SELECT StudentId FROM sStudent.tCommunication WHERE
		
		
 EXEC sp_xml_removedocument @loDoc
		
        SELECT 1 AS Result
	 END	

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


GO

ALTER PROCEDURE [sSetup].[pPortalStudentMasterUpdate]
	 
	
	@rStrXml [nvarchar](max),
	@rDivisionId int
	
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

SET @rStrXml=REPLACE(@rStrXml,'&','AND')

DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml
BEGIN
	BEGIN TRY
	

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


GO


ALTER PROCEDURE [sSetup].[pPortalStudentOtherUpdate]
	 
	
	@rStrXml [nvarchar](max),
	@rDivisionId int
	
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET @rStrXml=REPLACE(@rStrXml,'&','AND')

DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml
BEGIN
	--BEGIN TRY
	
	
	 BEGIN	
	 --DELETE FROM sStudent.tStudentOther WHERE StudentId IN
	 --(Select StudentId From sStudent.tAcademic Where DivisionId = @rDivisionId)
	
	 UPDATE sStudent.tStudentOther
		SET
			DateOfBirth = A.DateOfBirth,
			BirthDateInWord = A.BirthDateInWord,
			GenderId = A.GenderId,
			BloodGroupId = A.BloodGroupId,
			FamilyCast = sSetup.fPortalXMLTagsReplaceReverse(A.FamilyCast),
			FamilySubCast = sSetup.fPortalXMLTagsReplaceReverse(A.FamilySubCast),
			UpdatedUserId = A.UpdatedUserId,
			UpdatedDateTime = A.UpdatedDateTime,
			CreatedDateTime = A.CreatedDateTime
		FROM
		(
		SELECT		
			StudentId,
			DateOfBirth,
			BirthDateInWord,
			GenderId,
			BloodGroupId,
			FamilyCast,
			FamilySubCast,
			UpdatedUserId,
			UpdatedDateTime,
			CreatedDateTime
						
		FROM OPENXML (@loDoc, '/Table/StudentOther', 1)
		WITH ( 
				StudentId bigint,
				DateOfBirth Date,
				BirthDateInWord nvarchar(150),
				GenderId tinyint,
				BloodGroupId tinyint,
				FamilyCast nvarchar(100),
				FamilySubCast nvarchar(100),
				UpdatedUserId bigint,
				UpdatedDateTime DateTime,
				CreatedDateTime DateTime
			  )) A
			  WHERE sStudent.tStudentOther.StudentId = A.StudentId
		
		
		
		
	  INSERT INTO sStudent.tStudentOther
		(
			StudentId,
			DateOfBirth,
			BirthDateInWord,
			GenderId,
			BloodGroupId,
			FamilyCast,
			FamilySubCast,
			C.CreatedUserId,
			UpdatedDateTime,
			CreatedDateTime
			)
		SELECT		
			A.StudentId,
			A.DateOfBirth,
			A.BirthDateInWord,
			A.GenderId,
			A.BloodGroupId,
			sSetup.fPortalXMLTagsReplaceReverse(A.FamilyCast),
			sSetup.fPortalXMLTagsReplaceReverse(A.FamilySubCast),
			A.CreatedUserId,
			A.UpdatedDateTime,
			A.CreatedDateTime
						
		FROM OPENXML (@loDoc, '/Table/StudentOther', 1)
		WITH ( 
				StudentId bigint,
				DateOfBirth Date,
				BirthDateInWord nvarchar(150),
				GenderId tinyint,
				BloodGroupId tinyint,
				FamilyCast nvarchar(100),
				FamilySubCast nvarchar(100),
				CreatedUserId bigint,
				UpdatedDateTime DateTime,
				CreatedDateTime DateTime
			  ) A LEFT JOIN sStudent.tStudentOther O
			  ON A.StudentId = O.StudentId WHERE O.StudentId IS NULL
		
		
		 EXEC sp_xml_removedocument @loDoc
		
        SELECT 1 AS Result
	 END	
	
	
		
		
	--END TRY
	
	--BEGIN CATCH 
		
	--	SELECT -1 AS Result
	--END CATCH	
		
END
GO
PRINT N'Altering [sStudent].[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
	
	
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
			
		)
	VALUES
		(
			@lNextNumber,
			@rStudentId,
			@rClassId,
			@rDivisionId,
			@rRollNo,
			@rOrgId,
			@rBatchId,
			@rCreatedUserId,
			sCommon.fGetDate()
			,1
			,1
		)	
		
	   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() 
			
	      WHERE 
	       --Id = @rAcademicId  AND 
	       StudentId=@rStudentId  AND 
	       BatchId = @rBatchId
	      
	 END  			
		COMMIT TRANSACTION
		SELECT @lNextNumber AS Result
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sStudent].[pEnrollmentStatusAdd]...';


GO

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


GO

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


GO
ALTER PROCEDURE [sStudent].[pRollNoGenerationGet]
	 
	 @rClassID int,
	 @rDivisionId int,
	 @rOrgId int,
	 @rBatchId int,
	 @rStatusId smallint=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 --IF(@rIsSearch=1)
		--BEGIN
		--	SET @rCode = sCommon.fSearchStringGet(@rCode)
		--	SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		--END
	
	SELECT 
			SO.AcademicId,
			SO.StudentId,
			SO.GenderId,
			SO.ClassId,
			SO.DivisionId,
			SO.RollNo AS RollNo,
			SO.FirstName,
			SO.LastName,
			SO.FirstName+ ' ' + SO.MiddleName + ' '+SO.LastName AS Name,
			SO.Code,
			SO.MiddleName,
			So.StatusNAme,
			SO.StatusId
  FROM 
			[sStudent].[vStudentOther]  SO
           --sStudent.tAcademic A
           --INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId 
           --INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId  
  WHERE 
			(SO.ClassId=@rClassId OR @rClassId=0)
			AND (SO.DivisionId=@rDivisionId OR @rDivisionId=0)
			AND SO.BatchId=@rBatchId
			 
			AND SO.OrgID=@rOrgId
			AND ((So.StatusId=@rStatusId) OR (@rStatusId=0)) order by SO.RollNo
			
END
GO
PRINT N'Altering [sStudent].[pRptCountCategorywiseStudentGet]...';


GO
 

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

BEGIN 
  
	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			CM.DisplayTitle AS Class,
			DM.DisplayTitle AS Division,
			ISNULL(GM.Title,'') As Gender,
			A.ClassId,
			A.DivisionId,
			A.Id AS AcademicId,
			A.RollNo,
			SO.DateOfBirth,
			CM.DisplayTitle+' '+DM.DisplayTitle AS ClassDivision,
			SM.FirstName +' '+ SM.MiddleName +' '+ SM.LastName AS Name,
			SM.Code,
			CASE WHEN  @rReportId=10135 OR @rReportId=20702-- Caste Category
			THEN ISNULL(CCM.Title,'') 
		    WHEN  @rReportId=10136 OR @rReportId=20703 -- Religion
			THEN ISNULL(RM.Title,'') 
			WHEN  @rReportId=20704 -- Gender
			THEN ISNULL(GM.Title,'') 
			WHEN @rReportId=20328 OR @rReportId=20705 -- Admission Catgory 
			THEN ISNULL(SCM.Title,'')
			WHEN  @rReportId=10152 -- BloodGroupwise Summary
			THEN ISNULL(BGM.Title,'') 
			WHEN  @rReportId=20329 OR @rReportId=20706--Agegroupwise
			THEN  ([sStudent].[fStudentAgeGroupGet](SO.DateOfBirth,@rAsOnDate,@rOrgId))
			--WHEN  @rReportId=20426 OR @rReportId=20707  --Age wise
			--THEN  ([sStudent].[fStudentAgeGet](SO.DateOfBirth,@rAsOnDate,@rOrgId) + ' Y')
			WHEN    @rReportId = 20866 OR @rReportId=20426 OR @rReportId=20707
			
			THEN RIGHT('00'+ CAST([sStudent].[fStudentAgeGet](SO.DateOfBirth,@rAsOnDate,@rOrgId) AS VARCHAR(2)), 2)
			
			END AS Head,
			DM.OrderIndex AS DivisionOrder,
			@rClassGroup As ClassGroup,
			@rDivisionGroup As DivisionGroup,
			Cm.OrderINdex AS ClassOrderIndex
			FROM 
			sStudent.tAcademic A		
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId	
			LEFT JOIN sStudent.tStudentOther SO ON A.StudentId=SO.StudentId
			LEFT JOIN sStudent.tStudentAdmission SA ON SA.StudentId=A.StudentId
			LEFT JOIN sCommon.tGenderMaster GM ON GM.Id=SO.GenderId
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
			LEFT JOIN sCommon.tCastCategoryMaster CCM ON CCM.Id=SO.CastCategoryId
			LEFT JOIN sCommon.tReligionMaster RM ON RM.Id=SO.ReligionId
			LEFT JOIN sCommon.tBloodGroupMaster BGM ON BGM.Id=SO.BloodGroupId
			LEFT JOIN sStudent.tAdmissionCategoryMaster SCM ON SCM.Id=SM.AdmissionCategoryId
		
	WHERE 
		A.OrgId=@rOrgId
		AND	A.BatchId = @rBatchId 
		AND ((A.ClassId=@rClassId) OR (@rClassId=0))
		AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND SM.StatusId = 1
		AND ((SM.Code=@rStudentCode) OR (@rStudentCode=''))
		AND ((CM.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
	    AND (ISNULL(CCM.Id,0) IN(SELECT cast(item as int) FROM  sCommon.fnsplit(@rCasteCategoryIds,','))OR @rCasteCategoryIds='')
	    AND (ISNULL(RM.Id,0) IN(SELECT cast(item as int) FROM  sCommon.fnsplit(@rReligionIds,','))OR @rReligionIds='')
	    AND (ISNULL(GM.Id,0) IN(SELECT cast(item as int) FROM  sCommon.fnsplit(@rGenderIds,','))OR @rGenderIds='')
	    AND (ISNULL(SCM.Id,0) IN(SELECT cast(item as int) FROM  sCommon.fnsplit(@rAdmissionCatgoryIds,','))OR @rAdmissionCatgoryIds='')
	    
END
GO
PRINT N'Altering [sStudent].[pRptStudentInformationFormGet]...';


GO

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

	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

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


GO
ALTER PROCEDURE [sStudent].[pStudentFamilyAdd]
	 
			 @rStudentId	bigint
			,@rFatherName	nvarchar(100)
			,@rFatherDateOfBirth	date
			,@rFatherOccupation	nvarchar(50)
			,@rFatherQualification	nvarchar(50)
			,@rFatherContactNo	nvarchar(50)
			,@rFatherMail	nvarchar(50)
			,@rFatherOfficeAddress	nvarchar(50)
			,@rFatherIncome	int
			,@rMotherName	nvarchar(100)
			,@rMotherDateOfBirth	date
			,@rMotherOccupation	nvarchar(50)
			,@rMotherQualification	nvarchar(50)
			,@rMotherContactNo	nvarchar(50)
			,@rMotherMail	nvarchar(50)
			,@rMotherOfficeAddress	nvarchar(50)
			,@rMotherIncome	int
			,@rRelationshipName	nvarchar(100)
			,@rRelativeName	nvarchar(100)
			,@rRelativeDateOfBirth	date
			,@rRelativeOccupation	nvarchar(50)
			,@rRelativeQualification	nvarchar(50)
			,@rRelativeContactNo	nvarchar(50)
			,@rRelativeMail	nvarchar(50)
			,@rRelativeOfficeAddress	nvarchar(50)
			,@rRelativeIncome	int
			,@rCreatedUserId	bigint
			,@rOrgId int
			,@rMarriageAnniversaryDate Date,
			@rLiveWithId tinyint=0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
 IF NOT EXISTS (Select 1 FROM sStudent.tStudentFamily Where StudentId = @rStudentId)
BEGIN

	 


INSERT INTO  [sStudent].[tStudentFamily]
           (
            StudentId
           ,FatherName
           ,FatherDateOfBirth
           ,FatherOccupation
           ,FatherQualification
           ,FatherContactNo
           ,FatherMail
           ,FatherOfficeAddress
           ,FatherIncome
           ,MotherName
           ,MotherDateOfBirth
           ,MotherOccupation
           ,MotherQualification
           ,MotherContactNo
           ,MotherMail
           ,MotherOfficeAddress
           ,MotherIncome
           ,RelationshipName
           ,RelativeName
           ,RelativeDateOfBirth
           ,RelativeOccupation
           ,RelativeQualification
           ,RelativeContactNo
           ,RelativeMail
           ,RelativeOfficeAddress
           ,RelativeIncome
           ,CreatedUserId
           ,CreatedDateTime
           ,UpdatedUserId
           ,UpdatedDateTime
           ,MarriageAnniversaryDate,
            LiveWithId
           )
     VALUES
           (
			 @rStudentId
			,@rFatherName
			,@rFatherDateOfBirth
			,@rFatherOccupation
			,@rFatherQualification
			,@rFatherContactNo
			,@rFatherMail
			,@rFatherOfficeAddress
			,@rFatherIncome
			,@rMotherName
			,@rMotherDateOfBirth
			,@rMotherOccupation
			,@rMotherQualification
			,@rMotherContactNo
			,@rMotherMail
			,@rMotherOfficeAddress
			,@rMotherIncome
			,@rRelationshipName
			,@rRelativeName
			,@rRelativeDateOfBirth
			,@rRelativeOccupation
			,@rRelativeQualification
			,@rRelativeContactNo
			,@rRelativeMail
			,@rRelativeOfficeAddress
			,@rRelativeIncome
			,@rCreatedUserId
			,sCommon.fGetDate()
			,@rCreatedUserId
			,sCommon.fGetDate()
			,@rMarriageAnniversaryDate,
			@rLiveWithId
           )
		             
	END	 
	 ELSE
	 BEGIN
	 
	    UPDATE  sStudent.tStudentFamily
	  
			 SET 
				   [FatherName] = @rFatherName
				  ,[FatherDateOfBirth] = @rFatherDateOfBirth
				  ,[FatherOccupation] = @rFatherOccupation
				  ,[FatherQualification] = @rFatherQualification
				  ,[FatherContactNo] = @rFatherContactNo
				  ,[FatherMail] = @rFatherMail
				  ,[FatherOfficeAddress] = @rFatherOfficeAddress
				  ,[FatherIncome] = @rFatherIncome
				  ,[MotherName] = @rMotherName
				  ,[MotherdateOfBirth] = @rMotherDateOfBirth
				  ,[MotherOccupation] = @rMotherOccupation
				  ,[MotherQualification] = @rMotherQualification
				  ,[MotherContactNo] = @rMotherContactNo
				  ,[MotherMail] = @rMotherMail
				  ,[MotherOfficeAddress] = @rMotherOfficeAddress
				  ,[MotherIncome] = @rMotherIncome
				  ,[RelationshipName] = @rRelationshipName
				  ,[RelativeName] = @rRelativeName
				  ,[RelativedateOfBirth] = @rRelativedateOfBirth
				  ,[RelativeOccupation] = @rRelativeOccupation
				  ,[RelativeQualification] = @rRelativeQualification
				  ,[RelativeContactNo] = @rRelativeContactNo
				  ,[RelativeMail] = @rRelativeMail
				  ,[RelativeOfficeAddress] = @rRelativeOfficeAddress
				  ,[RelativeIncome] = @rRelativeIncome  
				  ,UpdatedUserId = @rCreatedUserId
				  ,UpdatedDateTime = sCommon.fgetdate()
				  ,MarriageAnniversaryDate=@rMarriageAnniversaryDate,
				  LiveWithId=@rLiveWithId
			
	      WHERE [StudentId] = @rStudentId	   
	      
	      
	 END  
		SELECT @rStudentId AS Result
		
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sStudent].[pStudentFamilyGet]...';


GO
ALTER PROCEDURE [sStudent].[pStudentFamilyGet]
	
	 @rStudentId bigint=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
			SELECT [StudentId]
				  ,[FatherName]
				  ,FatherDateOfBirth
				  --,ISNULL(FatherDateOfBirth,'0001/01/01') AS FatherDateOfBirth
				  ,[FatherOccupation]
				  ,[FatherQualification]
				  ,[FatherContactNo]
				  ,[FatherMail]
				  ,[FatherOfficeAddress]
				  ,[FatherIncome]
				  ,[MotherName]
				  ,MotherDateOfBirth
				  --,ISNULL(MotherDateOfBirth,'0001/01/01') AS MotherDateOfBirth
				  ,[MotherOccupation]
				  ,[MotherQualification]
				  ,[MotherContactNo]
				  ,[MotherMail]
				  ,[MotherOfficeAddress]
				  ,[MotherIncome]
				  ,RelationshipName
				  ,[RelativeName]
				  ,RelativeDateOfBirth
				  --,ISNULL(RelativeDateOfBirth,'0001/01/01') AS RelativeDateOfBirth
				  ,[RelativeOccupation]
				  ,[RelativeQualification]
				  ,[RelativeContactNo]
				  ,[RelativeMail]
				  ,[RelativeOfficeAddress]
				  ,[RelativeIncome] 
				  ,[MarriageAnniversaryDate],
				  ISNULL(LiveWithId,0) AS LiveWithId
  FROM 
				  sStudent.tStudentFamily SF

  WHERE      
      ((SF.StudentId = @rStudentId) OR (@rStudentId = 0))

  --ORDER BY  SF.RelationshipId ASC  
		
END
GO
PRINT N'Altering [sStudent].[pStudentFullGet]...';


GO



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

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

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


GO

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


GO

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

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

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


GO
ALTER PROCEDURE [sStudent].[pValidateImportStudent]

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

DECLARE @lCount INT
DECLARE @lInterrorCode INT,
		@intDoc INT,
        @lCode nvarchar(50),
        @lClass nvarchar(100),
        @lDivision nvarchar(100),        
        @lRegistrationNumber nvarchar(20),  
        @lAdmissionDate nvarchar(15),        
        @lDOB nvarchar(15),             
        @1ReturnCode int = 1,
        @1ExistStudentCode nvarchar(max) = '',
        @1ExistStudentRegistrationNumber nvarchar(max) = '',
        @1ValidAdmissionDate nvarchar(max) = '',
        @1ValidDOB nvarchar(max) = '',
        @1DuplicateStudentCode nvarchar(max) = '',
        @1DuplicateStudentRegistrationNumber nvarchar(max) = '',
        @lSUId nvarchar(20),
        @1ExistStudentSUId nvarchar(max) = '',
        @1DuplicateStudentSUId nvarchar(max) = '',
        @lLeftDate nvarchar(15),
        @lLCDate nvarchar(15),
        @1ValidLeftDate nvarchar(max) = '',
        @1ValidLCDate nvarchar(max) = ''
        
       
EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc
 
CREATE TABLE #tTable1 
 (
		Id bigint identity,
        Code nvarchar(50),
        RegistrationNumber nvarchar(20),
        FirstName nvarchar(100),
        LastName nvarchar(100),
		Class nvarchar(100),
		Division nvarchar(100),
		AdmissionStandard nvarchar(100),
		AdmissionDate nvarchar(15),
        DOB nvarchar(15),
        Gender nvarchar(10),
        --AdmissionCategory nvarchar(100),
		Religion nvarchar(100),
		CastCategory nvarchar(100),
        SUId nvarchar(20),
        LeftDate nvarchar(15),
        LCDate nvarchar(15),
        LeftStandard nvarchar(100)
        --Id1 bigint NULL,
        --departmentId int NULL
 
  )
  INSERT INTO #tTable1
	(
	    Code,
	    RegistrationNumber, 
	    FirstName,
	    LastName,
	    Class,
	    Division,
	    AdmissionStandard,
	    AdmissionDate,
	    DOB,
	    Gender,
	    --AdmissionCategory,
	    Religion,
	    CastCategory,
	    SUId,
	    LeftDate,
        LCDate,
        LeftStandard
    ) 
   SELECT
        Code,
	    RegistrationNumber, 
	    FirstName,
	    LastName,
	    Class,
	    Division,
	    AdmissionStandard,
	    AdmissionDate,
	    DOB,
	    Gender,
	    --AdmissionCategory,
	    Religion,
	    CastCategory,
	    SUId,
	    LeftDate,
        LCDate,
        LeftStandard 
   
   FROM OPENXML (@intDoc, '/Table/ImportStudent', 1)
   With
   (
        Code nvarchar(50) '@Code',
        RegistrationNumber nvarchar(20) '@RegistrationNumber',
        FirstName nvarchar(100) '@FirstName',
        LastName nvarchar(100) '@LastName',
		Class nvarchar(100) '@Class',
		Division nvarchar(100) '@Division',
		AdmissionStandard nvarchar(100) '@AdmissionStandard',
		AdmissionDate nvarchar(15) '@AdmissionDate',
		DOB nvarchar(15) '@DOB',
		Gender nvarchar(10) '@Gender',
		--AdmissionCategory nvarchar(100) '@AdmissionCategory',
		Religion nvarchar(100) '@Religion',
		CastCategory nvarchar(100) '@CastCategory',
		SUId nvarchar(20) '@SUId',
		LeftDate nvarchar(15) '@LeftDate',
		LCDate nvarchar(15) '@LCDate',
		LeftStandard nvarchar(100) '@LeftStandard'
   )   
EXEC sp_xml_removedocument @intDoc
		
SELECT @lCount =  COUNT(Id) FROM #tTable1
 
WHILE @lCount > 0 
  BEGIN
  
       SELECT         
         
         @lCode = Code, 
         @lRegistrationNumber = RegistrationNumber,
         @lAdmissionDate = AdmissionDate,
         @lDOB=DOB,
         @lSUId=SUId,
         @lLeftDate=LeftDate,
         @lLCDate=LCDate
        FROM #tTable1 WHERE Id = @lCount 
     
    IF Exists ((select 1 from sStudent.tStudentMaster where Code COLLATE DATABASE_DEFAULT = @lCode COLLATE DATABASE_DEFAULT AND OrgId = @rOrgId))         
          BEGIN
  			    SET @1ExistStudentCode = @1ExistStudentCode + @lCode + ','
	       END	  
	IF Exists ((select 1 from sStudent.tStudentMaster SM INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SM.OrgId where SM.SUId COLLATE DATABASE_DEFAULT = @lSUId COLLATE DATABASE_DEFAULT AND OM.OrgGroupId = @rOrgGroupId))         
          BEGIN
  			    SET @1ExistStudentSUId = @1ExistStudentSUId + @lSUId + ','
	       END	         
	IF Exists ((select 1 from sStudent.tStudentMaster where RegistrationNumber COLLATE DATABASE_DEFAULT = @lRegistrationNumber COLLATE DATABASE_DEFAULT AND OrgId = @rOrgId))         
          BEGIN
				IF(ISNULL(@lRegistrationNumber,'')!='')
				BEGIN
  					SET @1ExistStudentRegistrationNumber = @1ExistStudentRegistrationNumber + CAST(@lRegistrationNumber as varchar(max)) + ','
				END
	       END
	IF(ISDATE(@lAdmissionDate) = 0 AND @lAdmissionDate!='')
	BEGIN
		SET @1ValidAdmissionDate=@1ValidAdmissionDate + @lCode + '-' + @lAdmissionDate+','
	END
	IF(ISDATE(@lDOB) = 0 AND @lDOB!='')
	BEGIN
		SET @1ValidDOB=@1ValidDOB + @lCode + '-' + @lDOB+','
	END
	
	IF(ISDATE(@lLeftDate) = 0 AND @lLeftDate!='')
	BEGIN
		SET @1ValidLeftDate=@1ValidLeftDate + @lCode + '-' + @lLeftDate+','
	END
	
	IF(ISDATE(@lLCDate) = 0 AND @lLCDate!='')
	BEGIN
		SET @1ValidLCDate=@1ValidLCDate + @lCode + '-' + @lLCDate+','
	END
	
     SET @lCount = @lCount - 1	
   END	
   
   SELECT @lCount =  COUNT(Id) FROM #tTable1
 
	WHILE @lCount > 0 
		BEGIN
			SELECT         
         
			 @lClass = Class, 
			 @lDivision = Division
     
			FROM #tTable1 WHERE Id = @lCount
			
			IF NOT EXISTS (SELECT 1 FROM sSetup.tDivisionMaster DM 
					INNER JOIN sSetup.tClassMaster CM ON CM.Id=DM.ClassId 
						WHERE CM.Title COLLATE DATABASE_DEFAULT =@lClass COLLATE DATABASE_DEFAULT AND DM.Title COLLATE DATABASE_DEFAULT =@lDivision COLLATE DATABASE_DEFAULT AND DM.OrgId=@rOrgId)	
			BEGIN
				
				SELECT 'Enter proper value for Division ' + @lClass + ' ' + @lDivision AS StudentCode
				RETURN
			END
			SET @lCount = @lCount - 1	
		END
   	
		IF EXISTS(SELECT 1 fROM #tTable1 WHERE Code IS NULL OR Code COLLATE DATABASE_DEFAULT ='' COLLATE DATABASE_DEFAULT)
		BEGIN
			SELECT 'ID No Should not be empty' AS StudentCode
		END
		--ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE Number IS NULL OR Number='')
		--BEGIN
		--	SELECT 'Number Should not be empty' AS StudentCode
		--END
		ELSE IF EXISTS(SELECT 1 FROM #tTable1 WHERE LastName IS NULL OR LastName COLLATE DATABASE_DEFAULT ='' COLLATE DATABASE_DEFAULT)
		BEGIN
			SELECT 'Surname Should not be empty' AS StudentCode
		END
		ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE FirstName IS NULL OR FirstName COLLATE DATABASE_DEFAULT='' COLLATE DATABASE_DEFAULT)
		BEGIN
			SELECT 'First Name Should not be empty' AS StudentCode
		END
		ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE Class IS NULL OR Class COLLATE DATABASE_DEFAULT ='' COLLATE DATABASE_DEFAULT)
		BEGIN
			SELECT 'Class Should not be empty' AS StudentCode
		END
		ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE Division IS NULL OR Division COLLATE DATABASE_DEFAULT ='' COLLATE DATABASE_DEFAULT)
		BEGIN
			SELECT 'Division Should not be empty' AS StudentCode
		END
		--ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE AdmissionStandard IS NULL OR AdmissionStandard='')
		--BEGIN
		--	SELECT 'Admission Standard Should not be empty' AS StudentCode
		--END
		--ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE Gender IS NULL OR Gender='')
		--BEGIN
		--	SELECT 'Gender Should not be empty' AS StudentCode
		--END
		--ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE AdmissionCategory IS NULL OR AdmissionCategory='')
		--BEGIN
		--	SELECT 'Admission Category Should not be empty' AS StudentCode
		--END
		ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE AdmissionDate IS NULL OR AdmissionDate COLLATE DATABASE_DEFAULT='' COLLATE DATABASE_DEFAULT)
		BEGIN
			SELECT 'Admission Date Should not be empty or check the date format' AS StudentCode
		END
		ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE Class COLLATE DATABASE_DEFAULT NOT IN(SELECT Title FROM sSetup.tClassMaster WHERE OrgId=@rOrgId))
		BEGIN
			SELECT 'Enter proper value for Class as per Institute Setup > Class Master' AS StudentCode
		END				
		ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE AdmissionStandard  COLLATE DATABASE_DEFAULT !='' COLLATE DATABASE_DEFAULT AND AdmissionStandard COLLATE DATABASE_DEFAULT NOT IN(SELECT Title FROM sSetup.tClassMaster WHERE OrgId=@rOrgId))
		BEGIN
			SELECT 'Enter proper value for Admission Class as per Admin Tool > Institute Setup > Class Master' AS StudentCode
		END
		ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE Religion COLLATE DATABASE_DEFAULT !='' COLLATE DATABASE_DEFAULT AND Religion COLLATE DATABASE_DEFAULT NOT IN(SELECT Title FROM sCommon.tReligionMaster WHERE OrgGroupId=@rOrgGroupId))
		BEGIN
			SELECT 'Enter proper value / Check spelling for Religion per Admin Tool > Master > Religion Master' AS StudentCode
		END
		ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE Gender COLLATE DATABASE_DEFAULT !='' COLLATE DATABASE_DEFAULT AND Gender COLLATE DATABASE_DEFAULT NOT IN(SELECT Title FROM sCommon.tGenderMaster))
		BEGIN
			SELECT 'Enter proper value / Check spelling for gender ( Male / Female )' AS StudentCode
		END
		ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE CastCategory COLLATE DATABASE_DEFAULT !='' COLLATE DATABASE_DEFAULT AND CastCategory COLLATE DATABASE_DEFAULT NOT IN(SELECT Title FROM sCommon.tCastCategoryMaster))
		BEGIN
			SELECT 'Enter proper value for Cast Category (OBC,SC,ST,GENERAL)' AS StudentCode
		END
		--ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE  LeftStandard COLLATE DATABASE_DEFAULT NOT IN(SELECT Title FROM sSetup.tClassMaster WHERE OrgId=@rOrgId) AND @lLeftDate!='')
		--BEGIN
		--	SELECT 'Enter proper value for Left Standard as per Institute Setup > Class Master' AS StudentCode
		--END	
		--ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE LeftDate IS NULL OR LeftDate COLLATE DATABASE_DEFAULT ='' COLLATE DATABASE_DEFAULT AND LeftStandard COLLATE DATABASE_DEFAULT !='' COLLATE DATABASE_DEFAULT)
		--BEGIN
		--	SELECT 'LeftDate Should not be empty or check the date format' AS StudentCode
		--END
		ELSE
		BEGIN
		SELECT @1DuplicateStudentCode=COALESCE(@1DuplicateStudentCode ,'') + Code + ',' FROM #tTable1 GROUP BY Code HAVING ( COUNT(Code) > 1 )	
		SELECT @1DuplicateStudentSUId=COALESCE(@1DuplicateStudentSUId ,'') + SUId + ',' FROM #tTable1 GROUP BY SUId HAVING ( COUNT(SUId) > 1 )	
			IF(@1DuplicateStudentSUId IS NOT NULL AND @1DuplicateStudentSUId != '' AND @lIsActivateUniqueId=1)
				BEGIN
					SET @1DuplicateStudentSUId = 'Duplicate SUId ' + @1DuplicateStudentSUId
					SELECT @1DuplicateStudentSUId AS StudentCode
				END
			ELSE IF(@1DuplicateStudentCode IS NOT NULL AND @1DuplicateStudentCode COLLATE DATABASE_DEFAULT != '' COLLATE DATABASE_DEFAULT)
				BEGIN
					SET @1DuplicateStudentCode = 'Duplicate Code ' + @1DuplicateStudentCode
					SELECT @1DuplicateStudentCode AS StudentCode
				END
			ELSE
				BEGIN
				SELECT @1DuplicateStudentRegistrationNumber=COALESCE(@1DuplicateStudentRegistrationNumber ,'') + CONVERT(VARCHAR(20),RegistrationNumber) + ',' FROM #tTable1 GROUP BY RegistrationNumber HAVING ( COUNT(RegistrationNumber) > 1 AND ISNULL(RegistrationNumber,'')!='')	
				IF(@1DuplicateStudentRegistrationNumber IS NOT NULL AND @1DuplicateStudentRegistrationNumber  COLLATE DATABASE_DEFAULT != '' COLLATE DATABASE_DEFAULT)
				BEGIN
					SET @1DuplicateStudentRegistrationNumber = 'Duplicate Registration Number ' + @1DuplicateStudentRegistrationNumber
					SELECT @1DuplicateStudentRegistrationNumber AS StudentCode
				END
		ELSE IF((@1ExistStudentSUId IS NULL OR @1ExistStudentSUId = '' OR @lIsActivateUniqueId=0) AND (@1ExistStudentCode IS NULL OR @1ExistStudentCode = '') AND (@1ExistStudentRegistrationNumber IS NULL OR @1ExistStudentRegistrationNumber = '')
		AND (@1ValidAdmissionDate IS NULL OR @1ValidAdmissionDate = '') AND (@1ValidDOB IS NULL OR @1ValidDOB = ''))
		BEGIN
			SELECT '' AS StudentCode
		END
		ELSE IF (@1ExistStudentSUId IS NOT NULL AND @1ExistStudentSUId != '' AND @lIsActivateUniqueId=1)
		BEGIN
			SET @1ExistStudentSUId = 'Exist SUId ' + @1ExistStudentSUId
			Select @1ExistStudentSUId AS StudentCode
		END
		ELSE IF (@1ExistStudentCode IS NOT NULL AND @1ExistStudentCode COLLATE DATABASE_DEFAULT != '' COLLATE DATABASE_DEFAULT)
		BEGIN
			SET @1ExistStudentCode = 'Exist Code ' + @1ExistStudentCode
			Select @1ExistStudentCode AS StudentCode
		END
		ELSE IF (@1ExistStudentRegistrationNumber IS NOT NULL AND @1ExistStudentRegistrationNumber COLLATE DATABASE_DEFAULT != '' COLLATE DATABASE_DEFAULT)
		BEGIN
			SET @1ExistStudentRegistrationNumber = 'Exist Registration Number ' + @1ExistStudentRegistrationNumber
			Select @1ExistStudentRegistrationNumber AS StudentCode
		END
		ELSE IF (@1ValidAdmissionDate IS NOT NULL AND @1ValidAdmissionDate != '')
		BEGIN
			SET @1ValidAdmissionDate = 'Wrong Admission Date ' + @1ValidAdmissionDate
			Select @1ValidAdmissionDate AS StudentCode
		END
		ELSE IF (@1ValidDOB IS NOT NULL AND @1ValidDOB != '')
		BEGIN
			SET @1ValidDOB = 'Wrong DOB ' + @1ValidDOB
			Select @1ValidDOB AS StudentCode
		END
		ELSE IF (@1ValidLeftDate IS NOT NULL AND @1ValidLeftDate != '' AND @lLCDate!='')
		BEGIN
			SET @1ValidLeftDate = 'Wrong LeftDate ' + @1ValidLeftDate
			Select @1ValidLeftDate AS StudentCode
		END
		ELSE IF (@1ValidLCDate IS NOT NULL AND @1ValidLCDate != '' AND @lLCDate!='')
		BEGIN
			SET @1ValidLCDate = 'Wrong LCDate ' + @1ValidLCDate
			Select @1ValidLCDate AS StudentCode
		END
		END
		END
END
GO
PRINT N'Altering [sStudent].[pXMLStudentImportAdd]...';


GO

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

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

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

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


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

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

   	FROM
			sStudent.tTempStudentId TS	
		INNER JOIN sStudent.tStudentHealth SA ON SA.StudentId=TS.StudentId 
		
		
		INSERT INTO  [sStudent].[tStudentImages]
           ([StudentId]
           ,[StudentPhoto]
           ,[FatherPhoto]
           ,[MotherPhoto]
           ,[RelativePhoto]
           ,[UpdatedDateTime])
           
           SELECT           
            TS.NewStudentId
           ,[StudentPhoto]
           ,[FatherPhoto]
           ,[MotherPhoto]
           ,[RelativePhoto]
           ,sCommon.fGetDate()
         	FROM
			sStudent.tTempStudentId TS	
		INNER JOIN sStudent.tStudentImages SA ON SA.StudentId=TS.StudentId      
	
	DROP TABLE sStudent.tTempStudentId
	
    SELECT 1 AS Result
	
	COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT Error_message()
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sTally].[pReceiptTallyPostingAdd]...';


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

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

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

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


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


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

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


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

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

DELETE FROM sAdmission.tInquiryModeMaster

DELETE FROM sFee.tFeeMainGroupMaster

DELETE FROM sPayroll.tPayElementDefault

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


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

DELETE FROM sCommon.tRangeGroupMaster

DELETE FROM sHostel.tLogStatusMaster

DELETE FROM sSetup.tStudentNameFormatMaster

DELETE FROM sCommon.tMainCastCategoryMaster

DELETE FROM sOp.tFunctionalityMaster
DELETE FROM sOp.tPaymentGatewayMaster

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

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

DELETE FROM sActivity.tEventMainTypeMaster
DELETE FROM sAlert.tOSType

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

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

DELETE FROM sCommon.tTemplateSourceMaster
DELETE FROM sErp.tCustomerStatusMaster
DELETE FROM sErp.tInstallationTypeMaster
END
GO
PRINT N'Altering [sTransport].[pAssignRouteGet]...';


GO

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

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

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


GO

ALTER PROCEDURE [sTransport].[pFuelLogsGet]
		   
		   @rBuilder1 nvarchar(max)='',
		   @rBuilder2 nvarchar(max)='', 
           @rId int=0,
           @rVehicleId int,
           @rFromLogDate date,
           @rToLogDate date,
           @rOrgGroupBatchId int
           ,@rTransportId int = 0
          
AS
SET NOCOUNT ON

BEGIN
SELECT 
		
	   @rBuilder1 AS Builder1,
	   @rBuilder2 AS Builder2,
	   FL.Id AS FuelLogsId,
	   FL.VehicleId,
	   FL.LogDate,
	   FL.FuelAdded,
	   FL.Price,
	   FL.TotalAmount,
	   FL.LastReading,
	   FL.CurrentReading,
	   VMast.Title AS VehicleName,
	   VMast.RegistrationNumber,
	   ISNULL(FTM.Title,'') AS FuelTypeName
     
  FROM sTransport.tFuelLogs FL 
  INNER JOIN sTransport.tVehicleMaster VMast
	ON VMast.Id = FL.VehicleId
  LEFT JOIN sTransport.tFuelTypeMaster FTM
	ON FTM.Id = VMast.FuelTypeId	
   	
  WHERE 
	FL.OrgGroupBatchId=@rOrgGroupBatchId
	AND ((FL.Id = @rId) OR (@rId=0))
	AND ((FL.VehicleId = @rVehicleId) OR (@rVehicleId=0))
	AND ((FL.LogDate >= @rFromLogDate) OR (ISNULL(@rFromLogDate,'') = ''))
	AND ((FL.LogDate <= @rToLogDate) OR (ISNULL(@rToLogDate,'') = ''))
	AND ((VMast.TransportId = @rTransportId) OR (@rTransportId=0))
END
GO
PRINT N'Altering [sTransport].[pRptBusRouteDetailGet]...';


GO

ALTER PROCEDURE [sTransport].[pRptBusRouteDetailGet]
          
           @rTitle nvarchar(100)='',
           @rOrgGroupBatchId int,
           @rRouteId int=0,
           @rRouteCode nvarchar(50)='',
           @rRouteNumber int=0,
           @rTransportId int = 0
           
          
AS
SET NOCOUNT ON
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
			SET @rRouteCode = sCommon.fSearchStringGet(@rRouteCode)

BEGIN
SELECT 

	  BRM.Id as BusRouteId,
	  BRM.Title as BusRoute,
	  BRM.Remark,
	  BRM.DriverName,
	  BRM.DriverMobileNo,
	  BRM.ConductorName,
	  BRM.ConductorMobileNo,
	  BRM.VehicleId,
	  BRM.OrderIndex as BusRouteOrderIndex,
      VM.Title AS Vehicle,
      VM.RegistrationNumber,
      ISNULL(VTM.Title,'') AS TypeOfVehicle,
      VM.NoOfSeats,
      BRDM.Id AS BusRouteDestinationId,
      BRDM.Title AS BusRouteDestination,
      BRDM.Amount,
      BRDM.PickupTime,
      BRDM.DropTime
      
  FROM [sTransport].[tBusRouteMaster] BRM 
  INNER JOIN sTransport.tVehicleMaster VM ON VM.Id = BRM.VehicleId
  INNER JOIN sTransport.tBusRouteDestinationMaster BRDM ON BRDM.BusRouteId = BRM.Id
  LEFT JOIN sTransport.tVehicleTypeMaster VTM ON VTM.Id = VM.VehicleTypeId
  
  WHERE 
	((BRM.Title Like @rTitle) OR (ISNULL(@rTitle,'') = ''))
	--AND BRM.OrgGroupBatchId=@rOrgGroupBatchId
	AND ((BRM.Id=@rRouteId) OR (@rRouteId=0))
	AND ((BRM.RouteCode Like @rRouteCode) OR (ISNULL(@rRouteCode,'') = ''))
	AND ((BRM.RouteNumber =@rRouteNumber) OR (@rRouteNumber = 0))
	AND ((VM.TransportId=@rTransportId) OR (@rTransportId=0))
    order by BRM.OrderIndex,BRDM.OrderIndex
END
GO
PRINT N'Altering [sTransport].[pRptRoutewiseStudentListGet]...';


GO





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

BEGIN 


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


GO
CREATE PROCEDURE [sErp].[pChannelMasterAdd]
	 @rOrgGroupId smallint,
	 @rId int, 
	 @rCode nvarchar(100), 
	 @rTitle nvarchar(100), 
	 @rIsObsolete bit, 
	 @rCreatedUserId bigint, 
	 @rUpdatedUserId bigint        	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	IF(@rId = 0)	
	BEGIN
		If Exists(select Id from sErp.tChannelMaster where Code=@rCode AND OrgGroupId=@rOrgGroupId)
			BEGIN
			select -102 as Result
			RETURN
		END 
	
		If Exists(select Id from sErp.tChannelMaster where Title=@rTitle AND OrgGroupId=@rOrgGroupId)
			BEGIN
			select -103 as Result
			RETURN
		END 
	END
	ELSE
	BEGIN
		If Exists(select Id from sErp.tChannelMaster where Code=@rCode AND OrgGroupId=@rOrgGroupId AND Id<>@rId)
		Begin
			select -102 as Result
			RETURN
		End
		If  Exists(select Id from sErp.tChannelMaster where Title=@rTitle  AND OrgGroupId=@rOrgGroupId AND Id<>@rId)
		Begin
			select -103 as Result
			RETURN
		End

	END
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sErp.tChannelMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sErp.tChannelMaster
		(
			 OrgGroupId,
			 Id,
			 Code,
			 Title,
			 IsObsolete,
			 CreatedUserId,
			 CreatedDateTime,
			 UpdatedUserId, 
			 UpdatedDateTime

		)
	VALUES
		(
			 @rOrgGroupId ,
			 @lNextNumber, 
			 @rCode , 
			 @rTitle , 
			 @rIsObsolete , 
			 @rCreatedUserId , 
			 sCommon.fGetDate(),
			 @rUpdatedUserId  ,			  
			 sCommon.fGetDate()
		)
		    SELECT 1 AS Result
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sErp.tChannelMaster
	    SET
			Title=@rTitle,
			Code=@rCode,
			IsObsolete=@rIsObsolete,			
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate()
	      
	      WHERE Id = @rId
	      SELECT 11 AS Result
	 END  	

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


GO
CREATE PROCEDURE [sErp].[pChannelMasterGet]

	 @rId int,
	  @rOrgGroupId smallint,
	 @rTitle nvarchar(100),
	 @rCode nvarchar(100)
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	BEGIN
		SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		SET @rCode = sCommon.fSearchStringGet(@rCode)
	END
	
	SELECT 
			CM.Id,
			CM.Code	,	
			CM.Title,
				
		    CM.OrgGroupId,
		    CM.CreatedUserId,
		    CM.CreatedDateTime,
		    CM.IsObsolete
		    
	FROM 
			sErp.tChannelMaster CM
	WHERE 
		(CM.OrgGroupId = @rOrgGroupId)
		AND	((CM.Id = @rId) OR (@rId = 0))
		AND ((CM.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
		AND ((CM.Code like @rCode) OR (ISNULL(@rCode,'') = ''))
		
		ORDER BY CM.CreatedDateTime DESC
END
GO
PRINT N'Creating [sErp].[pCustomerMasterAdd]...';


GO
CREATE PROCEDURE [sErp].[pCustomerMasterAdd]  	 	 
	   @rId int, 
	   @rOrgGroupId smallint, 
	   @rCRMLicenceId int, 
	   @rTitle nvarchar(200), 
	   @rShortTitle nvarchar(100), 
	   @rStreetOne nvarchar(50), 
	   @rStreetTwo nvarchar(50), 
	   @rStreetThree nvarchar(50), 
	   @rCityName nvarchar(100), 
	   @rStateName nvarchar(100), 
	   @rCountryName nvarchar(100), 
	   @rZipCode nvarchar(20), 
	   @rHomePage nvarchar(100), 
	   @rPhoneNo nvarchar(50), 
       @rMobileNo nvarchar(50), 
       @rContactPerson nvarchar(100), 
       @rCreatedUserId bigint,       
       @rUpdatedUserId bigint,      
       @rIsObsolete bit, 
       @rCustomerStatusId tinyint,
       @rChannelId int, 
       @rInstallationTypeId tinyint
    	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	IF(@rId = 0)	
	BEGIN
		--If Exists(select Id from sErp.tChannelMaster where Code=@rCode AND OrgGroupId=@rOrgGroupId)
		--	BEGIN
		--	select -102 as Result
		--	RETURN
		--END 
	
		If Exists(select Id from sErp.tCustomerMaster where Title=@rTitle AND OrgGroupId=@rOrgGroupId)
			BEGIN
			select -103 as Result
			RETURN
		END 
	END
	ELSE
	BEGIN
		--If Exists(select Id from sErp.tChannelMaster where Code=@rCode AND OrgGroupId=@rOrgGroupId AND Id<>@rId)
		--Begin
		--	select -102 as Result
		--	RETURN
		--End
		If  Exists(select Id from sErp.tCustomerMaster where Title=@rTitle  AND OrgGroupId=@rOrgGroupId AND Id<>@rId)
		Begin
			select -103 as Result
			RETURN
		End

	END
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sErp.tCustomerMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sErp.tCustomerMaster
		(
			Id, 
			OrgGroupId, 
			CRMLicenceId, 
			Title, 
			ShortTitle, 
			StreetOne, 
			StreetTwo, 
			StreetThree, 
			CityName, 
			StateName, 
			CountryName, 
			ZipCode, 
			HomePage, 
			PhoneNo, 
            MobileNo, 
            ContactPerson, 
            CreatedUserId, 
            CreatedDateTime, 
            UpdatedUserId, 
            UpdatedDateTime, 
            IsObsolete, 
            CustomerStatusId, 
            ChannelId, 
            InstallationTypeId
        )
	VALUES
		(
			 @lNextNumber , 
			 @rOrgGroupId , 
			 @rCRMLicenceId , 
			 @rTitle , 
			 @rShortTitle, 
			 @rStreetOne , 
			 @rStreetTwo , 
		     @rStreetThree , 
			 @rCityName, 
	         @rStateName, 
	         @rCountryName, 
	         @rZipCode , 
			 @rHomePage , 
			 @rPhoneNo , 
			 @rMobileNo , 
			 @rContactPerson , 
			 @rCreatedUserId ,  
			 sCommon.fGetDate(),     
			 @rUpdatedUserId ,  
			 sCommon.fGetDate(),    
			 @rIsObsolete , 
			 @rCustomerStatusId ,
			 @rChannelId , 
			 @rInstallationTypeId 
		)
		    SELECT 1 AS Result
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sErp.tCustomerMaster
	    SET
			Title=@rTitle,			
			IsObsolete=@rIsObsolete,			
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate()
	      
	      WHERE Id = @rId
	      SELECT 11 AS Result
	 END  	

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


GO
CREATE PROCEDURE [sErp].[pCustomerMasterGet]

	  @rId int,
	  @rOrgGroupId smallint,
	  @rTitle nvarchar(100),
	  @rShortTitle nvarchar(100),
	  @rCRMLicenceId int=0, 
	  @rCustomerStatusId tinyint,
      @rChannelId int, 
      @rInstallationTypeId tinyint
	
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	BEGIN
		SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		SET @rShortTitle = sCommon.fSearchStringGet(@rShortTitle)
	END
	
	SELECT 
			CM.Id,
			CM.OrgGroupId,				
			CM.Title,
			CM.ShortTitle,
			CM.IsObsolete,
			CM.CRMLicenceId,
			CS.Id AS CustomerStatusTypeId,
			CS.Title AS CustomerStatus,
			CC.Id AS ChannelTypeId,
			CC.Title AS ChannelName,
			IT.Id AS InstallationId,
			IT.Title AS InstallationType			  		    		    
	FROM 
			 sErp.tCustomerMaster CM
			 LEFT JOIN  sErp.tCustomerStatusMaster CS ON CM.CustomerStatusId=CS.Id
			 LEFT JOIN sErp.tChannelMaster CC ON CM.ChannelId=CC.Id
			 LEFT JOIN sErp.tInstallationTypeMaster IT ON CM.InstallationTypeId=IT.Id
	WHERE 
		(CM.OrgGroupId = @rOrgGroupId)
		AND	((CM.Id = @rId) OR (@rId = 0))
		AND ((CM.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))		
		AND	((CM.CRMLicenceId = @rCRMLicenceId) OR (@rCRMLicenceId = 0))
		AND ((CM.ShortTitle like @rShortTitle) OR (ISNULL(@rShortTitle,'') = ''))
		AND ((CM.CustomerStatusId like @rCustomerStatusId) OR (@rCustomerStatusId=0))
		AND ((CM.ChannelId like @rChannelId) OR (@rChannelId=0))
		AND ((CM.InstallationTypeId like @rInstallationTypeId) OR (@rInstallationTypeId=0))
		ORDER BY CM.CreatedDateTime DESC
END
GO
PRINT N'Creating [sAcademic].[pXMLTopicMasterAdd]...';


GO
CREATE PROCEDURE [sAcademic].[pXMLTopicMasterAdd]
	(
		@rXml  nvarchar(MAX),
		@rOrgId int,
		@rClassId int,
		@rSubjectId int,
		@rCreatedUserId bigint 
		
	)
AS

SET NOCOUNT ON

BEGIN

 

DECLARE @lInterrorCode INT,
			@intDoc INT
DECLARE @lNextNumber BIGINT			
 
	EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXml
	
	 
	
	 EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAcademic.tTopicMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	INSERT INTO sAcademic.tTopicMaster
	(		Id,
			Number,
			Title,
			SubjectId,
			ClassID,
			OrgId,
			CreatedUserId,
			CreatedDateTime 
			
	)
	SELECT	
			@lNextNumber,
			A.Number,
			A.Title,
			@rSubjectId,
			@rClassID,
			@rOrgId,
			@rCreatedUserId,
			sCommon.fGetDate() 
			 
			
	FROM OPENXML (@intDoc, '/Table/TopicMaster', 1)
	WITH
	(
			 
			Number nvarchar(100) '@Number',
			Title nvarchar(100) '@Title' 
			 
	)A  
	

	EXEC sp_xml_removedocument @intDoc
	
	SELECT @lNextNumber = MAX(ID) FROM sAcademic.tTopicMaster Where OrgId=@rOrgId
    EXECUTE sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sAcademic.tTopicMaster', @rCurrentNumber = @lNextNumber 

	SELECT 1 as Result
	 
END
GO
PRINT N'Creating [sActivity].[pXMLEventHoliday]...';


GO


CREATE PROCEDURE [sActivity].[pXMLEventHoliday]
	(
		@rXmlDoc nvarchar(MAX),
		@rOrgId int
	) 
AS

SET NOCOUNT ON

BEGIN
SET @rXmlDoc=REPLACE(@rXmlDoc,'&','AND')
DECLARE @lInterrorCode INT,
			@intDoc INT
			
BEGIN TRY
BEGIN TRANSACTION	
	EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc
	
	DECLARE @lNextNumber BIGINT    
	DECLARE @lOrgId smallint
	
	SELECT @lOrgId=max(OrgId) FROM OPENXML (@intDoc, '/Table/StudentMaster', 1)
	WITH
	(
		OrgId int '@OrgId'
	) 	
	
	
	
	-----------------------  UPDATE EventSchedule
	UPDATE sActivity.tEventSchedule
	SET	
		FromDate = A.FromDate,
		ToDate = A.ToDate,
		Title = A.Title,
		UpdatedUserId = 9999000000003,
		UpdatedDateTime = sCommon.fGetDate() 
	FROM 
	(
	SELECT
		Id,
		FromDate,
		ToDate,
		Title,
		BatchId
	FROM OPENXML (@intDoc, '/Table/Holiday', 1)
	WITH
	(
		Id int '@Id',
		FromDate datetime '@FromDate',
		ToDate datetime '@ToDate',
		Title nvarchar(100) '@Title',
		BatchId int '@BatchId'	
	))A
	 WHERE sCommon.fGetIntIdForOrg(A.Id,@rOrgId) = sActivity.tEventSchedule.Id 
	AND sCommon.fGetIntIdForOrg(A.BatchId,@rOrgId) = sActivity.tEventSchedule.BatchId 
	

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

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

END
GO
PRINT N'Creating [sAlert].[pStudentListGet]...';


GO
CREATE PROCEDURE [sAlert].[pStudentListGet]
	 	 
	 	 @rOrgId int,
	 	 @rBatchId int,
	 	 @rClassId int,
	 	 @rDivisionId int,
	 	 @rTemplate nvarchar(max),
	 	 @rMailSubject nvarchar(500)=''
	 	 
	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]',SC.Name),
			'[Code]',SC.Code),
			'[ClassName]',SC.ClassName +' - '+ SC.DivisionName), 
			'[RollNo]',SC.RollNo),
			'[Organization]',OM.DisplayTitle),
			'[Batch]',BM.Title),
			'[Department]',DM.Title) AS MsgText,
			@rMailSubject AS Subject,
			SC.AcademicId AS SourceId,
			2001 AS SourceTypeId
	From 
		sStudent.vStudentCommunication SC
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SC.OrgId
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SC.BatchId
		INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id = SC.DepartmentId
			
	WHERE
	(SC.OrgId=@rOrgId)
	AND (SC.BatchId=@rBatchId)
	AND ((SC.ClassId=@rClassId) OR (@rClassId=0))
	AND ((SC.DivisionId=@rDivisionId) OR (@rDivisionId=0))
    ORDER BY SC.ClassOrderIndex,SC.DivisionOrderIndex,SC.Rollno 
END
GO
PRINT N'Creating [sAssessment].[pCSClassActivityAdd]...';


GO


CREATE PROCEDURE [sAssessment].[pCSClassActivityAdd]
	 
     --       @rAcademicId bigint
     --      ,@rExamId int
     --      ,@rIndicator nvarchar(200)
		   --,@rGrade nvarchar(10)
		   --,@rDescriptiveIndicator nvarchar(max)
		   
		   @rCCECSId int,
		   @rClassId int,
		   @rTotalMark decimal(12,2),
		   @rConvertToMark decimal(12,2),
		    @rIsDeleted bit 
		   --,@rIndicatodIds nvarchar(50)
		   --,@rIsIndicatodIds bit
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
 
	 BEGIN TRANSACTION	
	  
IF NOT EXISTS(SELECT CCECSID FROM sAssessment.tCCECSForClass WHERE CCECSId=333300048 AND ClassId=333300006 )
BEGIN
	INSERT INTO sAssessment.tCCECSForClass
			   (
			    [CCECSId]
			   ,ClassId
			   ,TotalMark
			   ,ConvertToMark
			  
			   )
		 VALUES
			   (
				@rCCECSId
			   ,@rClassId	
			   , @rTotalMark
			   , @rConvertToMark
			   
			   )
		   
	END	 
	
	 ELSE
	 BEGIN
	-- IF EXISTS(Select CCECSId from sAssessment.tCCECSExamScore WHere CCECSId=@rCCECSId )
	-- BEGIN
	--	SET @CCECSID= @rCCECSId
	--	SELECT @CCECSID AS Result
	--END
	--ELSE
	--BEGIN
	IF @rIsDeleted = 1
	 BEGIN
	    UPDATE  [sAssessment].[tCCECSForClass]
	    SET
			 
	          [CCECSId]=@rCCECSId
	         ,ClassId =@rClassId
	         ,TotalMark=@rTotalMark
			 ,ConvertToMark =@rConvertToMark
			 
	      WHERE CCECSId=@rCCECSId AND ClassId =@rClassID
	       SELECT 1 AS Result
	END
	ELSE IF EXISTS(Select CCECSId from sAssessment.tCCECSExamScore CS
					 INNER JOIN sStudent.tAcademic A ON CS.AcademicId = A.Id 
				   INNER JOIN sAssessment.tCCECSMaster CM ON CM.Id = CS.CCECSId	
				   where CS.CCECSId = @rCCECSId And A.ClassId =@rClassId) 
	BEGIN
	SELECT -101 AS RESULT
END
Else 
BEGIN
	Delete from sAssessment.tCCECSForClass where CCECSId =@rCCECSId 
	 SELECT 1 AS Result
END
	 END  
  
 
	 
COMMIT TRANSACTION		
 
	 
END
GO
PRINT N'Creating [sAssessment].[pCSClassGroupActivityGet]...';


GO
CREATE PROCEDURE [sAssessment].[pCSClassGroupActivityGet]
 
	  @rOrgId int
	 ,
	  @rExamId int=0,
	  @rClassId int
	  
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 	
BEGIN TRY
			SELECT 		
				ISNULL(CGM.Title,'') AS CSGroup,
				ISNULL(CM.Title,'') AS CS,				
			 
				CGM.GradeSetId,
				CM.Id as CMID,
				Isnull(CCFC.TotalMark,0) AS TotalMark,
				Isnull(CCFC.ConvertToMark,0) AS ConvertToMark,
				CASE WHEN ISNULL(CCFC.CCECSId,0)=0 THEN  'False' ELSE 'True' END AS Checked
				
						
			FROM   
				sAssessment.tCCECSMaster CM 
				INNER JOIN sAssessment.tCCECSGroupMaster CGM ON CGM.Id=CM.CCECAGroupId AND CM.OrgId=@rOrgId
				INNER JOIN sAssessment.tCCECSClass CL ON CL.CCECSGroupId = CGM.Id 
				INNER JOIN sAssessment.tCCECSForClass CCFC ON CCFC.CCECSId = CM.Id AND CCFC.ClassId = @rClassId 		 
				
				WHERE 
					   CM.OrgId = @rOrgId
					 AND CL.ClassId = @rClassId
		
			ORDER BY CGM.OrderIndex
			 
END TRY
BEGIN CATCH
	SELECT -1 AS RESULT
END CATCH
END
GO
PRINT N'Creating [sAttendance].[pMonthlyAttenanceRegisterGet]...';


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

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

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

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


GO
CREATE PROCEDURE [sAttendance].[pStudentAttendanceGet]
	 	 
	 	 @rUserSourceId bigint,
	 	 @rBatchId int,
	 	 @rOrgId int,
	 	 @rAttendanceTypeId int=1,
	 	  @rForMonth int=0,
	 	 @rForYear int=0
	 	
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN  
	 
	SELECT 
			SA.AcademicId,
			ISNULL(SA.RollNo,0) as RollNo,
			SA.Name,
			SA.Code,
			ISNULL(SR.IsPresent,'true') as IsPresent,
			ISNULL(SR.AbsentReasonId,0) as AbsentReasonId,
			 
			SR.RepeatCount,
			 
			ISNULL(SR.AttendanceTagId,0) AS AttendanceTagId,
			Day(SR.AttendanceDate) AS AttendanceDay,
			MOnth(SR.AttendanceDate) AS AttendanceMonth,
			YEar(SR.AttendanceDate) AS AttendanceYear,
			SR.AttendanceDate
			
  FROM   
			sStudent.vStudentAcademic SA 
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.AcademicId 
			
			--AND (SR.AttendanceDate=@rAttendanceDate)
			--AND (ISNULL(SR.SubjectId,0)=@rSubjectId)
			--AND (ISNULL(SR.RepeatCount,0)=@rRepeatCount)
		 
  WHERE 
		 -- ((SA.ClassId=@rClassId) OR (@rClassId=0))
	  --AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
        (SA.OrgId = @rOrgId)
      AND (SA.BatchId = @rBatchID)
      AND SA.StudentId=@rUserSourceId
      AND SR.AttendanceTypeId=@rAttendanceTypeId
      AND Month(SR.AttendanceDate)=@rForMonth
      AND Year(SR.AttendanceDate)=@rForYear
      --AND (SA.StatusId != 3)
      --AND (AD.LeftDate > @rAttendanceDate OR ISNULL(AD.LeftDate,'')= '')
      --AND (AD.AdmissionDate <= @rAttendanceDate)
      ORDER BY RollNo
   
END
GO
PRINT N'Creating [sAttendance].[pStudentAttendanceXMLInsert]...';


GO
 
CREATE PROCEDURE [sAttendance].[pStudentAttendanceXMLInsert]
	
	@rStrXml nvarchar(MAX),
    @rOrgId int,
    @rClassId int=0,
    @rDivisionId int,
    @rAttendanceDate date='',
    @rAttendanceTypeId tinyint,
    @rCreatedUserId bigint,
    @rSubjectId int=0,
    @rRepeatCount tinyint=0,
    @rBatchId int=0 
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET @rStrXml=REPLACE(@rStrXml,'&','AND')
DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION 
	 BEGIN
	 
	 
	 
	 DELETE SR FROM sAttendance.tStudentRegister SR 
	 INNER JOIN sStudent.tAcademic SA ON SA.Id = SR.AcademicId
	 --INNER JOIN (SELECT AcademicId FROM OPENXML(@loDoc, '/Table/RowData', 1)
	 --WITH
	 --(AcademicId bigint))A ON SR.AcademicId = A.AcademicId 
	    WHERE 
	    SR.AttendanceTypeId = @rAttendanceTypeId AND SR.AttendanceDate = @rAttendanceDate
	    --AND SA.ClassId = @rClassId 
	    AND SA.DivisionId=@rDivisionId 
	    AND SA.OrgId = @rOrgId 
	    AND ((ISNULL(SR.SubjectId,0) = ISNULL(@rSubjectId,0)) OR ( ISNULL(@rSubjectId,0)=0))
	    AND ((ISNULL(SR.RepeatCount,0) = ISNULL(@rRepeatCount,0)) OR (ISNULL(@rRepeatCount,0)=0))
	     AND SA.BatchId =@rBatchId
	 
	 INSERT INTO sAttendance.tStudentRegister 
		(
			AcademicId,
			EmployeeId,
			AttendanceTypeId,
			AttendanceDate,
			SubjectId,
			RepeatCount,
			IsPresent,
			AbsentReasonId,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime,
			AttendanceTagId
			)
		SELECT	
		DISTINCT	
			AcademicId,
			EmployeeId,
			@rAttendanceTypeId,
			@rAttendanceDate,
			ISNULL(@rSubjectId,0),
			ISNULL(@rRepeatCount,0),
			IsPresent,
			ISNULL(AbsentReasonId,0),
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rCreatedUserId,
			sCommon.fGetDate(),
			ISNULL(AttendanceTagId,0)
						
		FROM OPENXML (@loDoc, '/Table/RowData', 1)
		WITH ( 
				AcademicId bigint,
				EmployeeId bigint,
				IsPresent bit,
				AbsentReasonId int,
				AttendanceTagId smallint
		   ) AS At
		LEFT JOIN sStudent.tAcademic A ON A.Id=At.AcademicID
		INNER JOIN sStudent.tStudentAdmission SA ON SA.StudentId=A.StudentId
		 WHere SA.AdmissionDate <= @rAttendanceDate
		 AND ((SA.LeftDate >= @rAttendanceDate) OR  ISNULL(SA.LeftDate,'') = '') 
        SELECT 1 AS Result
	 END	
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Creating [sCommunication].[pQueryStatusUpdate]...';


GO

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


GO

CREATE PROCEDURE [sCommunication].[pTempCircularAdd]
	 
        @rId bigint,
		@rTitle nvarchar(200),
		@rRemark nvarchar(max),
		@rStartDate date,
		@rCreatedUserId bigint,
        @rOrgGroupId smallint,
        @rOrgGroupBatchId int,
        @rAssigneeId tinyint,
        @rCircularTypeId int,
        @rTempCircularId nvarchar(100)
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	BEGIN TRY
	BEGIN TRANSACTION	
	DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sCommunication.tCircular', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sCommunication.tCircular
		(
			Id,
			Title,
			Remark,
			StartDate,
			CreatedUserId,
			CreatedDateTime,
			OrgGroupId,
			OrgGroupBatchId,
			AssigneeId,
			CircularTypeId
		)
	VALUES
		(
			@lNextNumber,
			@rTitle,
			@rRemark,
			@rStartDate,
			@rCreatedUserId,
			sCommon.fGetDate(), 
			@rOrgGroupId,
			@rOrgGroupBatchId,
			@rAssigneeId,
			@rCircularTypeId
		)
		
		SELECT @lNextNumber AS Result  
		    
		INSERT INTO sCommunication.tCircularScope
		SELECT @lNextNumber,SourceTypeId,SourceId
		FROM sCommunication.tTempCircularScope 
		WHERE TempCircularId = @rTempCircularId
		
		DELETE FROM sCommunication.tTempCircularScope WHERE TempCircularId = @rTempCircularId
		
		
	END	 

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


GO

CREATE PROCEDURE [sCommunication].[pTempCircularScopeAdd]
			@rTempCircularId nvarchar(100)
           ,@rSourceTypeId smallint
           ,@rSourceId bigint
           ,@rIsDeleted bit
           	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
 

If(@rIsDeleted=1)
BEGIN
	Delete from sCommunication.tTempCircularScope where TempCircularId=@rTempCircularId AND SourceTypeId=@rSourceTypeId
AND SourceId=@rSourceId
	Select @rSourceId as Result
END	
ELSE
BEGIN 
 
	If Exists(select TempCircularId from sCommunication.tTempCircularScope where TempCircularId=@rTempCircularId AND SourceTypeId=@rSourceTypeId
	AND SourceId=@rSourceId)
		BEGIN
			SELECT @rSourceId AS Result
			RETURN
	  END 
	ELSE
			BEGIN
			INSERT INTO sCommunication.tTempCircularScope
			(
				TempCircularId
			   ,SourceTypeId
			   ,SourceId
			)
			VALUES
			(	
				@rTempCircularId
			   ,@rSourceTypeId
			   ,@rSourceId
			)		
			SELECT 1 AS Result
		 
	END	
END
GO
PRINT N'Creating [sCommunication].[pTempCircularScopeGet]...';


GO
CREATE PROCEDURE [sCommunication].[pTempCircularScopeGet]
	 @rTempCircularId nvarchar(100)
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 		
		
			 SELECT
			 CS.TempCircularId,
			 CS.SourceTypeId,
			 CS.SourceId,
			 OM.DisplayTitle AS Source,
			 'Organization' AS SourceType,
			 '' AS RollNo,
             '' AS Code,
             '' AS ClassDepartment,
             OM.DisplayTitle AS OrgName
			 
			FROM sCommunication.tTempCircularScope CS
			INNER JOIN sSetup.tOrganizationMaster OM
				ON CS.SourceId=OM.Id
			WHERE CS.TempCircularId=@rTempCircularId AND CS.SourceTypeId=2021

			UNION ALL

			SELECT
			 CS.TempCircularId,
			 CS.SourceTypeId,
			 CS.SourceId,
			 DM.DisplayTitle AS Source,
			 'Department' AS SourceType,
			 '' AS RollNo,
             '' AS Code,
             DM.Title AS ClassDepartment,
             OM.DisplayTitle AS OrgName
			 
			FROM sCommunication.tTempCircularScope CS
			INNER JOIN sSetup.tDepartmentMaster DM
				ON CS.SourceId=DM.Id
			INNER JOIN sSetup.tOrganizationMaster OM
				ON DM.OrgId=OM.Id 
			WHERE CS.TempCircularId=@rTempCircularId AND CS.SourceTypeId=2017

			UNION ALL

			SELECT
			 CS.TempCircularId,
			 CS.SourceTypeId,
			 CS.SourceId,
			 CM.DisplayTitle AS Source,
			 'Class' AS SourceType,
			 '' AS RollNo,
             '' AS Code,
             DMast.Title AS ClassDepartment,
             OM.DisplayTitle AS OrgName
			 
			FROM sCommunication.tTempCircularScope CS
			INNER JOIN  sSetup.tClassMaster CM
				ON CS.SourceId=CM.Id
			INNER JOIN sSetup.tDepartmentMaster DMast
				ON CM.DepartmentId =DMast.Id		
			INNER JOIN sSetup.tOrganizationMaster OM
				ON DMast.OrgId=OM.Id
			WHERE CS.TempCircularId=@rTempCircularId AND CS.SourceTypeId=2016

			UNION ALL

			SELECT
			 CS.TempCircularId,
			 CS.SourceTypeId,
			 CS.SourceId,
			 DM.DisplayTitle AS Source,
			 'Division' AS SourceType,
			 '' AS RollNo,
             '' AS Code,
             DMast.Title AS ClassDepartment,
             OM.DisplayTitle AS OrgName
			 
			FROM sCommunication.tTempCircularScope CS
			INNER JOIN   sSetup.tDivisionMaster DM
				ON CS.SourceId=DM.Id
			INNER JOIN 	sSetup.tClassMaster CM
				ON DM.ClassId=CM.Id	
			INNER JOIN sSetup.tDepartmentMaster DMast
				ON CM.DepartmentId =DMast.Id
			INNER JOIN sSetup.tOrganizationMaster OM
				ON DMast.OrgId=OM.Id		
				
			WHERE CS.TempCircularId=@rTempCircularId AND CS.SourceTypeId=2005


			UNION ALL
			
			SELECT
			 CS.TempCircularId,
			 CS.SourceTypeId,
			 CS.SourceId,
			 [sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Source,
			 'Student' AS SourceType,
			 SA.RollNo,
             SA.Code,
             SA.ClassName+' - '+SA.DivisionName AS ClassDepartment,
             OM.DisplayTitle AS OrgName
			 
			FROM sCommunication.tTempCircularScope CS
		    INNER JOIN sStudent.tStudentMaster SM
				ON CS.SourceId=SM.Id
			INNER JOIN  sStudent.vStudentAcademic SA
				ON CS.SourceId=SA.StudentId AND SA.IsActiveBatch=1 AND SA.StatusId=1		
			INNER JOIN sSetup.tOrganizationMaster OM
				ON SM.OrgId = OM.Id
			WHERE CS.TempCircularId=@rTempCircularId AND CS.SourceTypeId=2003
			
			UNION ALL
			
			SELECT
			 CS.TempCircularId,
			 CS.SourceTypeId,
			 CS.SourceId,
			 SA.Name AS Source,
			 'Student' AS SourceType,
			 SA.RollNo,
             SA.Code,
             SA.ClassName+' - '+SA.DivisionName AS ClassDepartment,
             OM.DisplayTitle AS OrgName
			 
			FROM sCommunication.tTempCircularScope CS
		   	INNER JOIN  sStudent.vStudentAcademic SA
				ON CS.SourceId=SA.AcademicId AND SA.IsActiveBatch=1 AND SA.StatusId=1
			INNER JOIN sSetup.tOrganizationMaster OM
				ON SA.OrgId = OM.Id	
			WHERE CS.TempCircularId=@rTempCircularId AND CS.SourceTypeId=2001
			
			UNION ALL
			
			SELECT
			
			 CS.TempCircularId,
			 CS.SourceTypeId,
			 CS.SourceId,
			 vEC.FirstName +' '+ vEC.LastName AS Source,
			 'Employee' AS SourceType,
			 '' AS RollNo,
             vEC.Code,
             vEC.DepartmentName AS ClassDepartment,
             OM.DisplayTitle AS OrgName
			
			FROM sCommunication.tTempCircularScope CS
			INNER JOIN sHrm.vEmployeeCommunication vEC 
				ON CS.SourceId=vEC.EmployeeId AND vEC.StatusId=7
			INNER JOIN sSetup.tOrganizationMaster OM
				ON vEC.OrgId = OM.Id		
			WHERE 
			CS.TempCircularId=@rTempCircularId AND CS.SourceTypeId=95


END
GO
PRINT N'Creating [sCommunication].[pTempCircularScopeRemove]...';


GO


CREATE PROCEDURE [sCommunication].[pTempCircularScopeRemove]
			
			@rTempCircularId nvarchar(100)
           ,@rSourceTypeId smallint
           ,@rSourceId bigint
           
           	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	BEGIN TRY
	
	BEGIN TRANSACTION	    
	
	Delete from sCommunication.tTempCircularScope where TempCircularId=@rTempCircularId AND SourceTypeId=@rSourceTypeId
      AND SourceId=@rSourceId
      
	Select 1 as Result
		
	COMMIT TRANSACTION
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH			
END
GO
PRINT N'Creating [sCommunication].[pTempCircularScopeValidate]...';


GO
CREATE PROCEDURE [sCommunication].[pTempCircularScopeValidate]
	 
        @rTempCircularId nvarchar(100),
		@rSourceTypeId smallint,
		@rSourceId bigint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
					/* Source Type Value
					   2021 - Organization
					   2004 - Department
					   2016 - Class
					   2005 - Division
					   2003 - Student */


		If EXISTS(select 1 from sCommunication.tTempCircularScope CS where CS.SourceId=@rSourceId AND
					CS.SourceTypeId=@rSourceTypeId AND CS.TempCircularId=@rTempCircularId)
			BEGIN
				select -101 as Result,'Item Already Exists' AS Msg
				RETURN
			END 

	
	IF(@rSourceTypeId = 2021) -- Organization	
		BEGIN
			If EXISTS(select 1 from  sCommunication.tTempCircularScope CS
			 INNER JOIN  sSetup.tDepartmentMaster DM 
				ON CS.SourceId=DM.Id AND CS.SourceTypeId= 2004
				where DM.OrgId=@rSourceId  AND CS.TempCircularId=@rTempCircularId)
					BEGIN
						select -103 as Result,'Department already Exists' AS Msg
						RETURN
					END 
			If EXISTS(select 1 from  sCommunication.tTempCircularScope CS 
			 INNER JOIN  sSetup.tClassMaster CM 
				ON CS.SourceId=CM.Id AND CS.SourceTypeId= 2016
				where CM.OrgId=@rSourceId  AND CS.TempCircularId=@rTempCircularId)
					BEGIN
						select -103 as Result,'Class already Exists' AS Msg
						RETURN
					END 
					
			If EXISTS(select 1 from  sCommunication.tTempCircularScope CS 
			 INNER JOIN  sSetup.tDivisionMaster DM 
				ON CS.SourceId=DM.Id AND CS.SourceTypeId= 2005
				where DM.OrgId=@rSourceId  AND CS.TempCircularId=@rTempCircularId)
					BEGIN
						select -103 as Result,'Division already Exists' AS Msg
						RETURN
					END 
					
			If EXISTS(select 1 from  sCommunication.tTempCircularScope CS 
			 INNER JOIN  sStudent.tStudentMaster SM
				ON CS.SourceId=SM.Id AND CS.SourceTypeId= 2003
				where SM.OrgId=@rSourceId  AND CS.TempCircularId=@rTempCircularId)
					BEGIN
						select -103 as Result,'Student already Exists' AS Msg
						RETURN
					END 		
	    END
	
	IF(@rSourceTypeId = 2004) -- Department	
		BEGIN
			If EXISTS(select 1 from  sCommunication.tTempCircularScope CS
			 INNER JOIN  sSetup.tDepartmentMaster DM
				ON CS.SourceId=DM.OrgId AND CS.SourceTypeId= 2021
				where DM.Id=@rSourceId  AND CS.TempCircularId=@rTempCircularId)
					BEGIN
						select -102 as Result,'Organization already Exists' AS Msg
						RETURN
					END 
			If EXISTS(select 1 from  sCommunication.tTempCircularScope CS
			 INNER JOIN sSetup.tClassMaster CM
				ON CS.SourceId=CM.Id AND CS.SourceTypeId= 2016
				where CM.DepartmentId=@rSourceId  AND CS.TempCircularId=@rTempCircularId)
					BEGIN
						select -103 as Result,'Class already Exists' AS Msg
						RETURN
					END 
					
			If EXISTS(select 1 from  sCommunication.tTempCircularScope CS 
			 INNER JOIN  sSetup.tDivisionMaster DM 
				ON CS.SourceId=DM.Id AND CS.SourceTypeId= 2005
			 INNER JOIN sSetup.tClassMaster CM
				ON CM.Id=DM.ClassId
				where CM.DepartmentId=@rSourceId  AND CS.TempCircularId=@rTempCircularId)
					BEGIN
						select -103 as Result,'Division already Exists' AS Msg
						RETURN
					END 
					
			If EXISTS(select 1 from  sCommunication.tTempCircularScope CS 
			 INNER JOIN sStudent.tAcademic SA 
				ON CS.SourceId=SA.StudentId AND CS.SourceTypeId=2003
			 INNER JOIN sSetup.tClassMaster CM
				ON CM.Id=SA.ClassId
   			 INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
				where CM.DepartmentId=@rSourceId  AND CS.TempCircularId=@rTempCircularId)
					BEGIN
						select -103 as Result,'Student already Exists' AS Msg
						RETURN
					END 			
	    END
	    
    IF(@rSourceTypeId = 2016) -- Class	
	BEGIN
		If EXISTS(select 1 from  sCommunication.tTempCircularScope CS 
		 INNER JOIN  sSetup.tClassMaster CM
			ON CS.SourceId=CM.OrgId AND CS.SourceTypeId= 2021
			where CM.Id=@rSourceId  AND CS.TempCircularId=@rTempCircularId)
				BEGIN
					select -102 as Result,'Organization already Exists' AS Msg
					RETURN
				END 
		If EXISTS(select 1 from  sCommunication.tTempCircularScope CS 
		 INNER JOIN  sSetup.tClassMaster CM
			ON CS.SourceId=CM.DepartmentId AND CS.SourceTypeId= 2004
			where CM.Id=@rSourceId  AND CS.TempCircularId=@rTempCircularId)
				BEGIN
					select -102 as Result,'Department already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from  sCommunication.tTempCircularScope CS
		 INNER JOIN  sSetup.tDivisionMaster DM 
			ON CS.SourceId=DM.Id AND CS.SourceTypeId= 2005
			where DM.ClassId=@rSourceId  AND CS.TempCircularId=@rTempCircularId)
				BEGIN
					select -103 as Result,'Division already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from sCommunication.tTempCircularScope CS 
		  INNER JOIN sStudent.tAcademic SA 
				ON CS.SourceId=SA.StudentId AND CS.SourceTypeId=2003
		  INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.ClassId=@rSourceId  AND CS.TempCircularId=@rTempCircularId)
				BEGIN
					select -103 as Result,'Student already Exists' AS Msg
					RETURN
				END 			
    END
    
    IF(@rSourceTypeId = 2005) -- Division	
	BEGIN
		If EXISTS(select 1 from  sCommunication.tTempCircularScope CS
		 INNER JOIN  sSetup.tDivisionMaster DM 
			ON CS.SourceId=DM.OrgId AND CS.SourceTypeId= 2021
			where DM.Id=@rSourceId  AND CS.TempCircularId=@rTempCircularId)
				BEGIN
					select -102 as Result,'Organization already Exists' AS Msg
					RETURN
				END 
		If EXISTS(select 1 from  sCommunication.tTempCircularScope CS
		 INNER JOIN sSetup.tClassMaster CM 
			ON CS.SourceId=CM.DepartmentId AND CS.SourceTypeId= 2004
		 INNER JOIN  sSetup.tDivisionMaster DM 
			ON DM.ClassId=CM.Id
			where DM.Id=@rSourceId  AND CS.TempCircularId=@rTempCircularId)
				BEGIN
					select -102 as Result,'Department already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from  sCommunication.tTempCircularScope CS 
		 INNER JOIN  sSetup.tDivisionMaster DM 
			ON CS.SourceId=DM.ClassId AND CS.SourceTypeId= 2016
			where DM.Id=@rSourceId  AND CS.TempCircularId=@rTempCircularId)
				BEGIN
					select -102 as Result,'Class already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from sCommunication.tTempCircularScope CS 
		  INNER JOIN sStudent.tAcademic SA 
				ON CS.SourceId=SA.StudentId AND CS.SourceTypeId=2003
		  INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.DivisionId=@rSourceId  AND CS.TempCircularId=@rTempCircularId)
				BEGIN
					select -103 as Result,'Student already Exists' AS Msg
					RETURN
				END 			
    END
    
    IF(@rSourceTypeId = 2003) -- Student	
	BEGIN
		If EXISTS(select 1 from  sCommunication.tTempCircularScope CS 
		 INNER JOIN  sStudent.tStudentMaster SM 
			ON CS.SourceId=SM.OrgId AND CS.SourceTypeId= 2021
			where SM.Id=@rSourceId  AND CS.TempCircularId=@rTempCircularId)
				BEGIN
					select -102 as Result,'Organization already Exists' AS Msg
					RETURN
				END 
		If EXISTS(select 1 from sCommunication.tTempCircularScope CS 
		 INNER JOIN  sSetup.tClassMaster CM 
			ON CS.SourceId=CM.DepartmentId AND CS.SourceTypeId= 2004
		 INNER JOIN sStudent.tAcademic SA 
				ON CM.Id=SA.ClassId 
		 INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.StudentId=@rSourceId  AND CS.TempCircularId=@rTempCircularId)
				BEGIN
					select -102 as Result,'Department already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from  sCommunication.tTempCircularScope CS 
		 INNER JOIN sStudent.tAcademic SA 
				ON CS.SourceId=SA.ClassId AND CS.SourceTypeId= 2016
		 INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.StudentId=@rSourceId  AND CS.TempCircularId=@rTempCircularId)
				BEGIN
					select -102 as Result,'Class already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from  sCommunication.tTempCircularScope CS
		 INNER JOIN sStudent.tAcademic SA 
				ON CS.SourceId=SA.DivisionId AND CS.SourceTypeId= 2005
		 INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.StudentId=@rSourceId  AND CS.TempCircularId=@rTempCircularId)
				BEGIN
					select -102 as Result,'Division already Exists' AS Msg
					RETURN
				END 			
    END
			select 1 as Result,'' AS Msg
	
END
GO
PRINT N'Creating [sFee].[pRptFeeRegisterAllStudentListGet]...';


GO
CREATE PROCEDURE [sFee].[pRptFeeRegisterAllStudentListGet]
		@rReportId int,
		@rReceiptBookId int,
		@rAdmissionCategoryId int,
		@rClassId int,
		@rDivisionId int,
		@rFromDate date,
		@rToDate date,
		@rFromReceiptNo int,
		@rToReceiptNo int,
		@rBatchId int,
		@rUserId bigint,
		@rBuilder1 nvarchar(max),
		@rBuilder2 nvarchar(max),
		@rIsCancel bit,
		@rOrgId int,
		@rOrgGroupBatchId int,
		@rStatusId int,
		@rCommonBatch nvarchar(100),
		@rDepartmentId int,
		@rFromRollNo int,
	    @rToRollNo int,
	    @rCode nvarchar(20),
	    @rIsDetail bit=0,
		@rIsFilter bit,
		@rIsHeader bit,
		@rCreatedUserName nvarchar(100)='',
		@rFeeHeadId nvarchar(max) = '',
		@rIsDisplayOrgGroup bit=0,
		@rPayTypeId int=0

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
		SET @rToDate = NULL
BEGIN 	
	SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		@rIsCancel AS IsCancel,
		@rIsDetail AS IsDetail,
		@rIsFilter As IsFilter,
		@rIsHeader As IsHeader,
		@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
		R.Id AS ReceiptId,
		R.ReceiptNumber,
		SA.ClassId,
		SA.ClassName,
		SA.DivisionId,
		SA.DivisionName,
		SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
		SA.RollNo,
		SA.AcademicId,
		SA.FirstName,
		SA.MiddleName,
		SA.LastName,
		SA.Code,
		SA.Name,
		PTM.Title AS PayType,
		R.ChequeNo,
		R.BankName,
		R.ReceiptAmount,
		R.ReceiptDate,
		FM.Title AS FeeDetail,
		ISNULL(FM.Code,'') AS FeeCode,
		FM.OrderIndex AS FeeOrderIndex,
		RD.Amount AS DetailAmount,
		ISNULL(R.ReceiptBookId,'0') As ReceiptBookId,
		ISNULL(RBM.Title,'') AS ReceiptBookTitle,
		ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
		ISNULL(FHM.Title,'') AS FeeHead,
		ISNULL(FHM.Code,'') AS FeeHeadCode,
		ISNULL(FHM.OrderIndex,0) AS FeeHeadOrderIndex,
		SA.OrgId,
		O.DisplayTitle AS OrgName,
		O.OrderIndex AS OrgOrderIndex,
		ISNULL(R.Remark,'') AS Remark,
		DM.Id AS DepartmentId,
		DM.Title AS DepartmentName,
		SA.ClassOrderIndex,
		ISNULL(SO.GenderId,0) AS GenderId,
		ISNULL(SA.BatchName,'') BatchName,
		ISNULL(FM.FeeHeadId,0) AS FeeHeadId,
		sFinanceCommon.fNumberToWordsWithDecimal(ISNULL(R.ReceiptAmount,0.00),1,2,O.OrgGroupId) AS ReceiptAmountInWords,
		R.ChequeDate
  FROM 
		sStudent.vStudentAcademic SA
		LEFT JOIN sFee.tReceipt R 
			ON SA.AcademicId=R.SourceId AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))
		LEFT JOIN sFinanceCommon.tPayTypeMaster PTM
			ON PTM.Id=R.PayTypeId
		LEFT JOIN sFee.tReceiptDetail RD
			ON RD.ReceiptId=R.Id
		LEFT JOIN sFee.tFeeSetup FS
			ON FS.Id=RD.FeeSetupId
		LEFT JOIN sFee.tFeeMaster FM
			ON FM.Id=FS.FeeId
		LEFT JOIN sFee.tFeeHeadMaster FHM
			ON FHM.Id=FM.FeeHeadId
		LEFT JOIN sFee.tReceiptBookMaster RBM 
			ON RBM.Id=R.ReceiptBookId
		INNER JOIN sSetup.tDepartmentMaster DM
			ON SA.DepartmentId=DM.Id
		INNER JOIN sSetup.tOrganizationMaster O
			ON O.Id=SA.OrgId
		LEFT JOIN sSecurity.tUser U
			ON U.Id=R.CreatedUserId
		LEFT JOIN sStudent.tStudentOther SO
			ON SO.StudentId = SA.StudentId
WHERE 
	--R.SourceTypeId = 2001
	--AND	
	((SA.AdmissionCategoryId = @rAdmissionCategoryId) OR (@rAdmissionCategoryId = 0))
	AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
	AND ((SA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))
	AND ((R.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId = 0))
	AND ((R.ReceiptNumber >= @rFromReceiptNo) OR (@rFromReceiptNo = 0))
	AND ((R.ReceiptNumber <= @rToReceiptNo) OR (@rToReceiptNo = 0))
	AND ((R.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
	AND ((R.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
	AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)
	AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
	AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0))
	AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
	--AND (R.IsObsolete = @rIsCancel) 
	AND (SA.StatusId = @rStatusId OR @rStatusId=0)
	AND ((SA.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
	AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
	AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
	AND ((SA.Code=@rCode) OR (@rCode=''))
	AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
	AND ((ISNULL(U.DisplayTitle,'') like @rCreatedUserName) OR (ISNULL(@rCreatedUserName,'')=''))
	AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
	AND ((R.PayTypeId=@rPayTypeId) OR (@rPayTypeId=0))
	ORDER BY R.ReceiptNumber
END
GO
PRINT N'Creating [sFee].[pRptFeeStatusStudentwisewithPaidDateGet]...';


GO

CREATE PROCEDURE [sFee].[pRptFeeStatusStudentwisewithPaidDateGet]
	    
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN
	SELECT 1
END
GO
PRINT N'Creating [sFee].[pWinFeeDetailDelete]...';


GO


CREATE PROCEDURE [sFee].[pWinFeeDetailDelete]
	 
		@rBatchId int,
		@rClassId int,
		@rDivisionId int
		
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	BEGIN TRY
		BEGIN TRANSACTION	
		BEGIN
			DELETE WFD FROM sFee.tWinfeeDetail WFD
			INNER JOIN sStudent.tAcademic A ON A.Id = WFD.AcademicId AND A.BatchId = WFD.BatchId 
			WHERE 
			(WFD.BatchId = @rBatchId)
			AND ((A.ClassId = @rClassId) OR (@rClassId=0))
			AND ((A.DivisionId = @rDivisionId) OR (@rDivisionId=0))
			SELECT 1 AS Result
		END		
COMMIT TRANSACTION	
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH			
END
GO
PRINT N'Creating [sHostel].[pImportHostelRoomAdd]...';


GO
CREATE PROCEDURE [sHostel].[pImportHostelRoomAdd]
	(	
		@rStrXml nvarchar(MAX) 
		 
	)
AS

SET NOCOUNT ON

BEGIN
SET @rStrXml=REPLACE(@rStrXml,'&','AND')
DECLARE @lInterrorCode INT,
			@intDoc INT
DECLARE @lNextNumber BIGINT
			
 
BEGIN TRANSACTION	
	EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rStrXml
	 
	 
	UPDATE sHostel.tAssignRoom
	SET
		 RoomId = A1.RoomId,
		 SourceTypeId = 2003,
		 SourceId = A1.SourceId
	FROM
	(
		SELECT	
			 RoomId,
			 SourceId
			 			
			FROM OPENXML (@intDoc, '/Table/ImportBook', 1)
			WITH
			(
				RoomId int '@RoomId',
				SourceId bigint '@SourceId' 
				
			))A1 
			 
	INSERT INTO sHostel.tAssignRoom
	(
		 RoomId,
		 SourceTypeId,
		 SourceId
	)
	SELECT
		 RoomId,
		 2003,
		 SourceId
		
	FROM OPENXML (@intDoc, '/Table/ImportBook', 1)
	WITH
	(
		RoomId int '@RoomId', --DepartmentId int '@DepartmentId',
		SourceId bigint '@SourceId' 
		
	)  
	
	EXEC sp_xml_removedocument @intDoc
	COMMIT TRANSACTION
	SELECT 1 AS Result
	 

END
GO
PRINT N'Creating [sHostel].[pRptStudentLedgerGet]...';


GO
CREATE PROCEDURE [sHostel].[pRptStudentLedgerGet]
	 
	
	 @rHostelId int,
	 @rCode  nvarchar(20)='',
	 @rSUId nvarchar(20)='',
	 @rHostelDepositHeadId int,
	 @rOrgId int,
     @rIsBasedOnSUId bit = 0
	 
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON 
BEGIN 
Declare @lbal decimal
SET @lbal=0;
 select
        A.DepositDate,
        A.Credit,
        A.Debit,
CASE WHEN @rIsBasedOnSUId=0 THEN  A.Code Else ISNULL(A.suid,'') END AS Code,
        A.StudentName,
        RM.Title AS Room,
        A.Class ,
        A.Credit - A.Debit AS Bal
  FROM
 (
			SELECT 
			DA.DepositDate AS DepositDate,
			ISnull (DA.Amount,0) AS Credit,
		    0 AS Debit,
		    VA.Code As Code,
		    VA.Name As StudentName,
		    VA.StudentId AS StudentId,
		   VA.ClassName + ' ' + VA.DivisionName AS Class,
		    ISNUll(VA.SUId,'') As  SUId,
		   -- @lbal+ISnull (DA.Amount,0)-0 As balance 
		   ISnull(DA.Amount,0)-0 As balance 
		    
			FROM sStudent.vStudentLastAcademic  VA
			INNER JOIN sHostel.tHostelDepositAdd DA  ON VA.StudentId = DA.StudentId 
			Where 
		  ((VA.Code like @rCode) OR (ISNULL(@rCode,'') = ''))
			AND DA.HostelId = @rHostelId
			AND ((VA.SUId like @rSUId) OR (ISNULL(@rSUId,'')=''))
			AND (DA.HostelDepositHeadId = @rHostelDepositHeadId)
			AND ((VA.OrgId = @rOrgId) OR (ISNULL(@rOrgId,0) = 0)) 
			UNION ALL 
			SELECT 
			DAJ.AdjustmentDate As DepositDate,
			0  AS Credit,
			ISnull (DAJ.Amount,0)  AS Debit,
		    VA.Code As Code,
		    VA.Name As StudentName, 
		    VA.StudentId AS StudentId,
		    VA.ClassName + ' ' + VA.DivisionName AS Class,
		     ISNUll(VA.SUId,'') As  SUId,
		    -- @lbal+0-ISnull (DAJ.Amount,0) As balance 
		     0-ISnull(DAJ.Amount,0) As balance 
			FROM sStudent.vStudentLastAcademic  VA
			  INNER JOIN sHostel.tHostelDepositAdjustment DAJ ON DAJ.StudentId = VA.StudentId
		     
			Where 
				((VA.Code like @rCode) OR (ISNULL(@rCode,'') = ''))
			AND DAJ.HostelId = @rHostelId
			AND ((VA.SUId like @rSUId) OR (ISNULL(@rSUId,'')=''))
			AND (DAJ.HostelDepositHeadId = @rHostelDepositHeadId) 
			AND ((VA.OrgId = @rOrgId) OR (ISNULL(@rOrgId,0) = 0))
			
			UNION ALL 
			SELECT 
			DR.RefundDate As DepositDate,
			0  AS Credit,
			ISnull (DR.RefundAmount,0)  AS Debit,
		    VA.Code As Code,
		    VA.Name As StudentName,
		    VA.StudentId AS StudentId,
		    VA.ClassName + ' ' + VA.DivisionName AS Class,
		    ISNUll(VA.SUId,'') As  SUId,
		    -- @lbal+0-ISnull (DR.RefundAmount,0) As balance 
		    0-ISnull(DR.RefundAmount,0) As balance
			FROM sStudent.vStudentLastAcademic  VA
			  INNER JOIN sHostel.tHostelDepositRefund DR ON DR.StudentId = VA.StudentId
		     
			Where 
			((VA.Code like @rCode) OR (ISNULL(@rCode,'') = ''))
			AND DR.HostelId = @rHostelId 
			AND ((VA.SUId like @rSUId) OR (ISNULL(@rSUId,'')=''))
			AND (DR.HostelDepositHeadId = @rHostelDepositHeadId) 
			AND ((VA.OrgId = @rOrgId) OR (ISNULL(@rOrgId,0) = 0))
			) A
			LEFT JOIN sHostel.tAssignRoom  AR ON AR.SourceId=A.StudentId AND  AR.SourceTypeId = 2003
			LEFT JOIN sHostel.tRoomMaster RM ON AR.RoomId = RM.Id 
			--Group By A.DepositDate,A.Credit,A.Debit,A.Code,A.SUId,A.StudentName,Rm.title,A.Class,  A.Balance
			order by  A.DepositDate 
END
GO
PRINT N'Creating [sHostel].[pStudentLedgerGet]...';


GO
CREATE PROCEDURE [sHostel].[pStudentLedgerGet]
	 
	
	 @rHostelId int,
	 @rCode  nvarchar(20)='',
	 @rSUId nvarchar(20)='',
	 @rHostelDepositHeadId int,
	 @rOrgId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON 
BEGIN 
 SELECT A.Date,
        A.Credit,
        A.Debit
          FROM(
			SELECT 
			DA.DepositDate AS Date,
			ISnull (DA.Amount,0) AS Credit,
		    0 AS Debit
			FROM sStudent.vStudentLastAcademic  VA
			INNER JOIN sHostel.tHostelDepositAdd DA  ON VA.StudentId = DA.StudentId 
			Where 
			((VA.Code = @rCode) OR (ISNULL(@rCode,0) = 0))
			AND DA.HostelId = @rHostelId 
			AND ((VA.SUId like @rSUId) OR (ISNULL(@rSUId,'')=''))
			AND (DA.HostelDepositHeadId = @rHostelDepositHeadId) 
			AND ((VA.OrgId = @rOrgId) OR (ISNULL(@rOrgId,0) = 0)) 
			
			UNION ALL 
			SELECT 
			DAJ.AdjustmentDate As Date,
			0  AS Credit,
			ISnull (DAJ.Amount,0)  AS Debit
			FROM sStudent.vStudentLastAcademic  VA
			  INNER JOIN sHostel.tHostelDepositAdjustment DAJ ON DAJ.StudentId = VA.StudentId
		     
			Where 
			((VA.Code = @rCode) OR (ISNULL(@rCode,0) = 0))
			AND DAJ.HostelId = @rHostelId 
			AND ((VA.SUId like @rSUId) OR (ISNULL(@rSUId,'')=''))
			AND (DAJ.HostelDepositHeadId = @rHostelDepositHeadId) 
			AND ((VA.OrgId = @rOrgId) OR (ISNULL(@rOrgId,0) = 0)) 
			UNION ALL 
			SELECT 
			DR.RefundDate As Date,
			0  AS Credit,
			ISnull (DR.RefundAmount,0)  AS Debit
			FROM sStudent.vStudentLastAcademic  VA
			  INNER JOIN sHostel.tHostelDepositRefund DR ON DR.StudentId = VA.StudentId
		     
			Where 
			((VA.Code = @rCode) OR (ISNULL(@rCode,0) = 0))
			AND DR.HostelId = @rHostelId
			AND ((VA.SUId like @rSUId) OR (ISNULL(@rSUId,'')=''))
			AND (DR.HostelDepositHeadId = @rHostelDepositHeadId) 
			AND ((VA.OrgId = @rOrgId) OR (ISNULL(@rOrgId,0) = 0)) 
			)A 
			Order BY A.Date
END
GO
PRINT N'Creating [sHostel].[pStudentLedgerGet_NEW]...';


GO
-- exec [sHostel].[pStudentLedgerGet_NEW1] 100100027,'15012018',''
-- drop proc [sHostel].[pStudentLedgerGet_NEW] 
CREATE PROC [sHostel].[pStudentLedgerGet_NEW]

	 @rHostelId int,
	 @rCode  nvarchar(20)='',
	 @rSUId nvarchar(20)='',
	 @rHostelDepositHeadId int,
	 @rOrgId int,
     @rIsBasedOnSUId bit = 0
	 
AS
BEGIN

WITH Tb0 as
( 
			SELECT 
			DA.DepositDate AS DepositDate,
			ISnull (DA.Amount,0) AS Credit,
		    0 AS Debit,
		    VA.Code As Code,
		    VA.Name As StudentName,
		    VA.StudentId AS StudentId,
		    VA.ClassName + ' ' + VA.DivisionName AS Class,
		    ISNUll(VA.SUId,'') As  SUId
		    
			FROM sStudent.vStudentLastAcademic  VA
			INNER JOIN sHostel.tHostelDepositAdd DA  ON VA.StudentId = DA.StudentId 
			Where 
		  ((VA.Code like @rCode) OR (ISNULL(@rCode,'') = ''))
			AND DA.HostelId = @rHostelId
			AND ((VA.SUId like @rSUId) OR (ISNULL(@rSUId,'')=''))
			AND (DA.HostelDepositHeadId = @rHostelDepositHeadId)
			AND ((VA.OrgId = @rOrgId) OR (ISNULL(@rOrgId,0) = 0)) 
			
	UNION
			SELECT 
			DAJ.AdjustmentDate As DepositDate,
			0  AS Credit,
			ISnull (DAJ.Amount,0)  AS Debit,
		    VA.Code As Code,
		    VA.Name As StudentName, 
		    VA.StudentId AS StudentId,
		    VA.ClassName + ' ' + VA.DivisionName AS Class,
		     ISNUll(VA.SUId,'') As  SUId
			FROM sStudent.vStudentLastAcademic  VA
			  INNER JOIN sHostel.tHostelDepositAdjustment DAJ ON DAJ.StudentId = VA.StudentId
		     
			Where 
				((VA.Code like @rCode) OR (ISNULL(@rCode,'') = ''))
			AND DAJ.HostelId = @rHostelId
			AND ((VA.SUId like @rSUId) OR (ISNULL(@rSUId,'')=''))
			AND (DAJ.HostelDepositHeadId = @rHostelDepositHeadId) 
			AND ((VA.OrgId = @rOrgId) OR (ISNULL(@rOrgId,0) = 0))
			
	 UNION
			SELECT 
			DR.RefundDate As DepositDate,
			0  AS Credit,
			ISnull (DR.RefundAmount,0)  AS Debit,
		    VA.Code As Code,
		    VA.Name As StudentName,
		    VA.StudentId AS StudentId,
		    VA.ClassName + ' ' + VA.DivisionName AS Class,
		    ISNUll(VA.SUId,'') As  SUId
			FROM sStudent.vStudentLastAcademic  VA
			  INNER JOIN sHostel.tHostelDepositRefund DR ON DR.StudentId = VA.StudentId
		     
			Where 
			((VA.Code like @rCode) OR (ISNULL(@rCode,'') = ''))
			AND DR.HostelId = @rHostelId 
			AND ((VA.SUId like @rSUId) OR (ISNULL(@rSUId,'')=''))
			AND (DR.HostelDepositHeadId = @rHostelDepositHeadId) 
			AND ((VA.OrgId = @rOrgId) OR (ISNULL(@rOrgId,0) = 0))
)
,Tb1 as
( 
	SELECT DepositDate,Credit,Debit,Row_Number() over (order by [DepositDate] asc) as [OrderId],StudentId,Code,SUId,StudentName,Class FROM Tb0
)
 
  SELECT T1.[DepositDate],
         T1.[Credit],
         T1.[Debit],(Sum(T2.Credit) - Sum(T2.Debit)) as Balance,
         CASE WHEN @rIsBasedOnSUId=0 THEN  T1.Code Else ISNULL(T1.SUId,'') END AS Code,
         T1.StudentName,
         RM.Title AS Room,
         T1.Class,
         HM.Title As HostelName,
         HM.SmallAddress1 AS SmallAddress1,
         HM.SmallAddress2 AS SmallAddress2,
         HM.ReportOrgTitle AS ReportOrgTitle
 FROM Tb1 as T1
INNER JOIN Tb1 as T2 ON T1.[OrderId] >= T2.[OrderId] 
LEFT JOIN sHostel.tAssignRoom  AR ON AR.SourceId=T1.StudentId AND  AR.SourceTypeId = 2003
LEFT JOIN sHostel.tRoomMaster RM ON AR.RoomId = RM.Id
LEFT JOIN sHostel.tHostelMaster HM ON HM.Id=RM.HostelId
Group By T1.[DepositDate],T1.[Credit],T1.[Debit],T1.StudentId,T1.SUId,T1.Code,T1.StudentName,T1.Class,RM.Title,HM.Title,HM.SmallAddress1,HM.SmallAddress2,
HM.ReportOrgTitle
 Order by T1.[DepositDate]
END
GO
PRINT N'Creating [sHrm].[pDivisionWiseStudentGet]...';


GO
CREATE PROCEDURE [sHrm].[pDivisionWiseStudentGet]

	 --@rOrgId int,
	 @rBatchId int,
	 @rDivisionId int,
	 @rOrgGroupBatchId int
	 --@rEmployeeId bigint
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
 
SELECT
A.Code,
A.OrganizationName,
A.RollNo,
A.ClassName+'-'+A.DivisionName AS ClassDivisionName,
A.Name

 FROM
                   sStudent.vStudentAcademic  
                   A INNER JOIN sSetup.tBatchMaster B ON A.BatchId = B.Id 
                   WHERE
                   B.OrgGroupBatchId = @rOrgGroupBatchId
                   AND A.DivisionId=@rDivisionId
                   --AND A.IsActiveBatch=1                 
                   AND A.StatusId=1
                   ORDER BY A.RollNo
               

END
GO
PRINT N'Creating [sHrm].[pTeacherSubjectGet]...';


GO
CREATE PROCEDURE [sHrm].[pTeacherSubjectGet]

	 --@rOrgId int,
	@rBatchId int,
	 @rEmployeeId bigint,
	 @rOrgGroupBatchId int
	 
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
 
SELECT
 --SM.Title AS SubjectName,
 DISTINCT
 OM.Id, 
 DM.OrderIndex,
 --DM.Code AS ClassDivisionName,
 DM.ClassDivisionName AS ClassDivisionName,
 OM.DisplayTitle AS OrgName,
 --Sm.Id,
 DM.DivisionId As DivisionId  ,
 (SELECT  Count (AcademicId) FROM sStudent.vStudentAcademic A INNER JOIN sSetup.tBatchMaster B ON A.BatchId = B.Id
  WHERE DivisionId=DM.DivisionId AND B.OrgGroupBatchId = @rOrgGroupBatchId
  AND A.StatusId=1) AS StudentCount
 FROM
 sAcademic.tTeacherSubjectDivision TSD 
 					--INNER JOIN sSetup.tSubjectMaster SM ON TSD.SubjectId=SM.Id 
					INNER JOIN sSetup.vBatchClassDivision DM ON DM.DivisionId=TSD.DivisionId
                    
                    INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = DM.OrgId
                   WHERE TSD.EmployeeId=@rEmployeeId
                   --AND OM.Id=@rOrgId
                   ORDER BY OM.Id,DM.OrderIndex

END
GO
PRINT N'Creating [sLibrary].[pAssignBooksBulkForClassGet]...';


GO

CREATE PROCEDURE [sLibrary].[pAssignBooksBulkForClassGet]
	 
	 @rLibraryId int,
	 @rClassId int,
	 @rOrgId smallint,
	 @rBatchId int,
	 @rDivisionId int

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 

	SELECT 
	
	VA.Name,
	VA.Code,
	VA.RollNo,
	VA.StudentId
	 
  FROM 
  sStudent.vStudentLastAcademic  VA
 
  WHERE   
 VA.ClassId=@rClassId
 AND VA.BatchId=@rBatchId
 AND VA.OrgId=@rOrgId
 AND VA.DivisionId=@rDivisionId
 order by VA.RollNo
    
END
GO
PRINT N'Creating [sLibrary].[pLibraryMasterAdd]...';


GO

CREATE PROCEDURE [sLibrary].[pLibraryMasterAdd]
	 
        @rId int,
        @rCode nvarchar(20),
		@rTitle nvarchar(100),
		@rNumber int,
		@rCreatedUserId bigint,
		@rIsObsolete bit,
		@rOrgGroupId smallint,
		@rReportOrgTitle  nvarchar(200) ,
		@rSmallAddress1 nvarchar(200),
		@rSmallAddress2 nvarchar(200)
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	IF(@rId = 0)	
	BEGIN  
		If Exists(select Id from sLibrary.tLibraryMaster where Title=@rTitle AND OrgGroupId=@rOrgGroupId)
			BEGIN
			select -103 as Result
			RETURN
		END 
		If Exists(select Id from sLibrary.tLibraryMaster where Code=@rCode AND OrgGroupId=@rOrgGroupId)
			BEGIN
			select -102 as Result
			RETURN
		END 
	END
	ELSE
	BEGIN
		If Exists(select Id from sLibrary.tLibraryMaster where Code=@rCode AND OrgGroupId=@rOrgGroupId AND Id<>@rId)
		Begin
			select -102 as Result
			RETURN
		End
		If  Exists(select Id from sLibrary.tLibraryMaster where Title=@rTitle AND OrgGroupId=@rOrgGroupId AND Id<>@rId)
		Begin
			select -103 as Result
			RETURN
		End

	END
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber int

	IF(@rId = 0)	
	BEGIN
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sLibrary.tLibraryMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sLibrary.tLibraryMaster
		(
			Id,
			Number,
			Code,
			Title,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime,
			IsObsolete,
			OrgGroupId ,
			ReportOrgTitle,
			SmallAddress1,
			SmallAddress2
			
		)
	VALUES
		(
			@lNextNumber,
			@rNumber,
			@rCode,
			@rTitle,
			@rCreatedUserId,
			sCommon.fGetDate(), 
			@rCreatedUserId,
			sCommon.fGetDate(), 
			@rIsObsolete,
			@rOrgGroupId,
			@rReportOrgTitle,
			@rSmallAddress1,
			@rSmallAddress2
		)
		
		  INSERT INTO sSecurity.tUserAccess
           (
           SourceTypeId
           ,SourceId
           ,[UserId]
           
           )
		   SELECT 
		   2011
		   ,@lNextNumber
		   ,@rCreatedUserId
		
		
		    SELECT @lNextNumber AS Result
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sLibrary.tLibraryMaster
	    SET
			Title=@rTitle,
			Number=@rNumber,
			Code=@rCode,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate(), 
			IsObsolete=@rIsObsolete,
			ReportOrgTitle=@rReportOrgTitle ,
		    SmallAddress1=@rSmallAddress1 ,
		    SmallAddress2=@rSmallAddress2 
	      WHERE Id = @rId
	      SELECT @lNextNumber AS Result
	 END  	

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


GO
CREATE PROCEDURE [sLibrary].[pLibraryMasterGet]
	 @rId int = 0,
	 @rTitle nvarchar(100),
	 @rCode nvarchar(20),
	 @rOrgGroupId int,
	 @rIsSearch bit = 1
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 IF @rIsSearch = 1
		BEGIN
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		END
	SELECT 
			Id,
			ISNULL(Number,0) AS Number,
			Code,
			Title,
			IsObsolete,
			ReportOrgTitle,
			SmallAddress1,
			SmallAddress2
      
  FROM 
            sLibrary.tLibraryMaster 
  WHERE   
           ((Id = @rId) OR (@rId = 0))
	       AND ((Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
	       AND ((Code like @rCode) OR (ISNULL(@rCode,'') = ''))
	       AND OrgGroupId=@rOrgGroupId
	       Order by id 
END
GO
PRINT N'Creating [sPayroll].[pRptPaysheetDetail]...';


GO

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

BEGIN  
DECLARE @lOrgGroupId int = 0
DECLARE @lCurrencyCode nvarchar(20) = ''
    SELECT  @lCurrencyCode = [sFinanceCommon].[fDefaultCurrencyCodeGet](@lOrgGroupId) 
	SELECT
		@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 EM.FirstName+' '+EM.MiddleName+' ' +EM.LastName From  sHrm.tEmployeeMaster EM
			INNER JOIN sHrm.tEmployeeJobDetail EJ ON EM.Id=EJ.EmployeeId
			INNER JOIN sHrm.tEmployeeDesignationMaster ED ON ED.Id=EJ.EmployeeDesignationId
			Where EJ.OrgId=EM.OrgId AND ED.Code='PRINCIPAL')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=100100001
			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=100100001
			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=100100001
			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=100100001
			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=100100001
			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=100100001
			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=100100001
			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=100100001
			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=100100001
			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=100100001
			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=100100001
			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=100100001
			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=100100001
			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=100100001
			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=100100001
			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
				
			
			
	FROM 
	sHrm.tEmployeeMaster EM
    INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.EmployeeId = EM.Id
END
GO
PRINT N'Creating [sSetup].[pPortalEventAssignAdd]...';


GO
CREATE PROCEDURE [sSetup].[pPortalEventAssignAdd]
	
	@rStrXml nvarchar(MAX),
    @rBatchId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET @rStrXml=REPLACE(@rStrXml,'&','AND')
DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION 
	 BEGIN
	 
	 DELETE EA FROM sActivity.tEventAssign EA 
	 INNER JOIN sActivity.tEventSchedule ES ON ES.Id = EA.EventScheduleId
	 WHERE ES.BatchId=@rBatchId
	 
	 INSERT INTO sActivity.tEventAssign 
		(
			Id,
			EventScheduleId,
			SourceTypeId,
			SourceId
			)
		SELECT		
			Id,
			EventScheduleId,
			SourceTypeId,
			SourceId
						
		FROM OPENXML (@loDoc, '/Table/RowData', 1)
		WITH ( 
				Id bigint,
			    EventScheduleId int,
			    SourceTypeId smallint,
				SourceId bigint
			  ) 
		
        SELECT 1 AS Result
	 END	
	
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Creating [sSetup].[pPortalEventAttendancesAdd]...';


GO
CREATE PROCEDURE [sSetup].[pPortalEventAttendancesAdd]
	
	@rStrXml nvarchar(MAX),
    @rBatchId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET @rStrXml=REPLACE(@rStrXml,'&','AND')
DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION 
	 BEGIN
	 
	 DELETE EA FROM sActivity.tEventAttendance EA 
	 INNER JOIN sActivity.tEventSchedule ES ON ES.Id = EA.EventScheduleId
	 WHERE ES.BatchId=@rBatchId
	  
	 INSERT INTO sActivity.tEventAttendance
		(
			EventScheduleId,
			SourceTypeId,
			SourceId,
			IsSelfPresent,
			IsFatherPresent,
			IsMotherPresent,
			IsGuardianPresent,
			SchoolFeedback,
			ParentFeedback,
			SchoolAction,
			ParentAction,
			IsTrackForReview
			)
		SELECT		
			EventScheduleId,
			SourceTypeId,
			SourceId,
			IsSelfPresent,
			IsFatherPresent,
			IsMotherPresent,
			IsGuardianPresent,
			SchoolFeedback,
			ParentFeedback,
			SchoolAction,
			ParentAction,
			IsTrackForReview
						
		FROM OPENXML (@loDoc, '/Table/RowData', 1)
		WITH ( 
				EventScheduleId int,
				SourceTypeId smallint,
				SourceId bigint,
				IsSelfPresent bit,
				IsFatherPresent bit,
				IsMotherPresent bit,
				IsGuardianPresent bit,
				SchoolFeedback nvarchar(500),
				ParentFeedback nvarchar(500),
				SchoolAction nvarchar(500),
				ParentAction nvarchar(500),
				IsTrackForReview bit
			  ) 
		
        SELECT 1 AS Result
	 END	
	
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Creating [sSetup].[pPortalEventScheduleAdd]...';


GO
CREATE PROCEDURE [sSetup].[pPortalEventScheduleAdd]
	
	@rStrXml nvarchar(MAX),
    @rBatchId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET @rStrXml=REPLACE(@rStrXml,'&','AND')
DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION 
	 BEGIN
	 
	 DELETE FROM sActivity.tEventSchedule WHERE BatchId=@rBatchId
	 
	 INSERT INTO sActivity.tEventSchedule 
		(
			Id,
			BatchId,
			FromDate,
			ToDate,
			Title,
			Remark,
			IsCommonForAll,
			IsHoliday,
			IsEnrollment,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime,
			EventTypeId
			)
		SELECT		
			Id,
			BatchId,
			FromDate,
			ToDate,
			Title,
			Remark,
			IsCommonForAll,
			IsHoliday,
			IsEnrollment,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime,
			EventTypeId
						
		FROM OPENXML (@loDoc, '/Table/RowData', 1)
		WITH ( 
				Id int,
				BatchId int,
				FromDate date,
				ToDate date,
				Title nvarchar(100),
				Remark nvarchar(100),
				IsCommonForAll bit,
				IsHoliday bit,
				IsEnrollment bit,
				CreatedUserId bigint,
				CreatedDateTime datetime,
				UpdatedUserId bigint,
				UpdatedDateTime datetime,
				EventTypeId int
			  ) 
		
        SELECT 1 AS Result
	 END	
	
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Creating [sSetup].[pPortalMasterEventTypeUpdate]...';


GO


CREATE PROCEDURE [sSetup].[pPortalMasterEventTypeUpdate]
	 
	@rStrXml [nvarchar](max)
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET @rStrXml=REPLACE(@rStrXml,'&','AND')

DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml
BEGIN
	BEGIN TRY
	

	 BEGIN	
	
	UPDATE sActivity.tEventTypeMaster
		SET
			Code = A.Code,
			Title = A.Title,
			CreatedUserId = A.CreatedUserId,
			CreatedDateTime = A.CreatedDateTime,
			IsObsolete = A.IsObsolete,
			UpdatedUserId = A.UpdatedUserId,
			UpdatedDateTime = A.UpdatedDateTime,
			HighlightColor = A.HighlightColor,
			OrderIndex=A.OrderIndex,
			EventMainTypeId=A.EventMainTypeId
		 FROM
		 (
		SELECT		
			OrgGroupId,
			Id,
			Code,
			Title,
			CreatedUserId,
			CreatedDateTime,
			IsObsolete,
			UpdatedUserId,
			UpdatedDateTime,
			HighlightColor,
			OrderIndex,
			EventMainTypeId
						
		FROM OPENXML (@loDoc, '/Table/RowData', 1)
		WITH ( 
				[OrgGroupId] [smallint],
				[Id] [int],
				[Code] [nvarchar](20),
				[Title] [nvarchar](100),
				[CreatedUserId] [bigint],
				[CreatedDateTime] [datetime],
				[IsObsolete] [bit],
				[UpdatedUserId] [bigint],
				[UpdatedDateTime] [datetime],
				[HighlightColor] [nvarchar](100),
				[OrderIndex] [int],
				[EventMainTypeId] [tinyint]
			  )) A
			  WHERE sActivity.tEventTypeMaster.Id = A.Id
		
		
		
		 INSERT INTO sActivity.tEventTypeMaster
		(
			OrgGroupId,
			Id,
			Code,
			Title,
			CreatedUserId,
			CreatedDateTime,
			IsObsolete,
			UpdatedUserId,
			UpdatedDateTime,
			HighlightColor,
			OrderIndex,
			EventMainTypeId
			)
		SELECT		
			A.OrgGroupId,
			A.Id,
			A.Code,
			A.Title,
			A.CreatedUserId,
			A.CreatedDateTime,
			A.IsObsolete,
			A.UpdatedUserId,
			A.UpdatedDateTime,
			A.HighlightColor,
			A.OrderIndex,
			A.EventMainTypeId
						
		FROM OPENXML (@loDoc, '/Table/RowData', 1)
		WITH ( 
				[OrgGroupId] [smallint],
				[Id] [int],
				[Code] [nvarchar](20),
				[Title] [nvarchar](100),
				[CreatedUserId] [bigint],
				[CreatedDateTime] [datetime],
				[IsObsolete] [bit],
				[UpdatedUserId] [bigint],
				[UpdatedDateTime] [datetime],
				[HighlightColor] [nvarchar](100),
				[OrderIndex] [int],
				[EventMainTypeId] [tinyint] 
			  ) A LEFT JOIN sActivity.tEventTypeMaster ETM
			  ON A.Id = ETM.Id WHERE ETM.Id IS NULL
		
		 EXEC sp_xml_removedocument @loDoc
        SELECT 1 AS Result
	 END	
	
	END TRY
	
	BEGIN CATCH 
		
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Creating [sSetup].[pPortalMasterTermUpdate]...';


GO


CREATE PROCEDURE [sSetup].[pPortalMasterTermUpdate]
	 
	@rStrXml [nvarchar](max),
	@rOrgId int=0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET @rStrXml=REPLACE(@rStrXml,'&','AND')

DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml
BEGIN
	BEGIN TRY
	

	 BEGIN	
	
	UPDATE sSetup.tTermMaster
		SET
			Number=A.Number,
			Code = A.Code,
			Title = A.Title,
			FromDate=A.FromDate,
			ToDate=A.ToDate,
			BatchId=A.BatchId,
			OrgId = A.OrgId,
			IsObsolete = A.IsObsolete,
			CreatedUserId = A.CreatedUserId,
			CreatedDateTime = A.CreatedDateTime,
			UpdatedUserId = A.UpdatedUserId,
			UpdatedDateTime = A.UpdatedDateTime
		 FROM
		 (
		SELECT		
			Id,
			Number,
			Code,
			Title,
			FromDate,
			ToDate,
			BatchId,
			OrgId,
			IsObsolete,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime
						
		FROM OPENXML (@loDoc, '/Table/RowData', 1)
		WITH ( 
				[Id] [int],
				[Number] [smallint],
				[Code] [nvarchar](20),
				[Title] [nvarchar](100),
				[FromDate] [date],
				[ToDate] [date],
				[BatchId] [int],
				[OrgId] [smallint],
				[IsObsolete] [bit],
				[CreatedUserId] [bigint],
				[CreatedDateTime] [datetime],
				[UpdatedUserId] [bigint],
				[UpdatedDateTime] [datetime]
			  )) A
			  WHERE sSetup.tTermMaster.Id = A.Id
		
		
		
		 INSERT INTO sSetup.tTermMaster
		(
			Id,
			Number,
			Code,
			Title,
			FromDate,
			ToDate,
			BatchId,
			OrgId,
			IsObsolete,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime
			)
		SELECT		
			A.Id,
			A.Number,
			A.Code,
			A.Title,
			A.FromDate,
			A.ToDate,
			A.BatchId,
			A.OrgId,
			A.IsObsolete,
			A.CreatedUserId,
			A.CreatedDateTime,
			A.UpdatedUserId,
			A.UpdatedDateTime
						
		FROM OPENXML (@loDoc, '/Table/RowData', 1)
		WITH ( 
				[Id] [int],
				[Number] [smallint],
				[Code] [nvarchar](20),
				[Title] [nvarchar](100),
				[FromDate] [date],
				[ToDate] [date],
				[BatchId] [int],
				[OrgId] [smallint],
				[IsObsolete] [bit],
				[CreatedUserId] [bigint],
				[CreatedDateTime] [datetime],
				[UpdatedUserId] [bigint],
				[UpdatedDateTime] [datetime]
			  ) A LEFT JOIN sSetup.tTermMaster TM
			  ON A.Id = TM.Id WHERE TM.Id IS NULL
		
		 EXEC sp_xml_removedocument @loDoc
        SELECT 1 AS Result
	 END	
	
	END TRY
	
	BEGIN CATCH 
		
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Creating [sStudent].[pChangeStudentClassAdd]...';


GO
CREATE PROCEDURE [sStudent].[pChangeStudentClassAdd]
	 
	 
	@rStudentId bigint=0,
	@rClassId int=0,
	@rDivisionId int=0,
	@rRollNo int=0,
	@rOrgId int=0,
	@rBatchId int=0,
	@rCreatedUserId bigint=0 
	 
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	 
	DECLARE @lNextNumber BIGINT,@lExistCode nvarchar(max)   
	SET @rRollNo = ISNULL(@rRollNo,0)
	
	 
 IF   EXISTS(Select Id from sStudent.tAcademic where StudentId=@rStudentId AND BatchId=@rBatchId AND OrgId=@rOrgId AND ClassId=@rClassId)
BEGIN
	Select @lExistCode  = COALESCE(@lExistCode ,'') + CONVERT(VARCHAR(15),SM.Code) + ' , ' from sStudent.tStudentMaster SM
	INNER JOIN sStudent.tAcademic A ON A.StudentId=SM.Id AND A.BatchId=@rBatchId   AND A.ClassId=@rClassId
	Select  @lExistCode   
	Return
	END	 
	   
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sStudent.tAcademic', 0, 1, 1,@outNextNumber = @lNextNumber output
 
	INSERT INTO sStudent.tAcademic
		(
			Id,
			StudentId,
			ClassId,
			DivisionId,
			RollNo,
			OrgId,
			BatchId,
			CreatedUserId,
			CreatedDateTime,
			IsCurrent,
			BatchStatusId
			
		)
	VALUES
		(
			@lNextNumber,
			@rStudentId,
			@rClassId,
			@rDivisionId,
			@rRollNo,
			@rOrgId,
			@rBatchId,
			@rCreatedUserId,
			sCommon.fGetDate()
			,1
			,1
		)	
	 
	 
--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 
		SELECT 101 AS Result
		
	 
		
END
GO
PRINT N'Creating [sStudent].[pStudentImportExamWiseGet]...';


GO

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

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

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


GO
CREATE PROCEDURE [sStudent].[pStudentLastAcademicGet]
	 
	 @rCode nvarchar(20),
	 @rOrgId int,
	 @rNumber bigint,
	-- @rBatchId int,
	 @rStudentId bigint,
	 @rSUID  nvarchar(20)
	 --@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.vStudentLastAcademic 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	
			
	 
	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.Name AS Name,
			SA.AcademicId,
			SA.ClassId,
			SA.DivisionId,
			ISNULL(SA.RollNo,0) AS RollNo,
			SA.BatchId,
			--SA.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
  FROM 
           sStudent.vStudentLastAcademic SA
     LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=SA.StudentId
     LEFT JOIN sStudent.tAcademicDetail AD ON AD.AcademicID = SA.AcademicId
  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.SUId=@rSUID)OR(ISNULL(@rSUID,'')=''))
			--AND(SA.BatchId=@rBatchId)
END
GO
PRINT N'Creating [sStudent].[pSUIDGenerationGet]...';


GO

CREATE PROCEDURE [sStudent].[pSUIDGenerationGet]
	 
	 @rOrgGroupId smallint,
	 @rOrgId smallint,
	 @rDepartmentId int,
	 @rClassID int,
	 @rDivisionId int,
	 @rRecordStatusId smallint
	 

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	SELECT 
			vSA.StudentId,
			vSA.OrgId,
			vSA.OrganizationName,
			VSA.DepartmentName,
			vSA.ClassName+' - '+vSA.DivisionName AS ClassDivisionName,
			vSA.RollNo,
			vSA.Code,
			ISNULL(vSA.SUId,'') AS SUID,
			vSA.Name
	FROM 
			sStudent.vStudentLastAcademic vSA
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = vSA.OrgId
	WHERE 
			(OM.OrgGroupId = @rOrgGroupId)
			AND ((vSA.OrgId=@rOrgId) OR (@rOrgId=0))
			AND ((vSA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
			AND ((vSA.ClassId=@rClassId) OR (@rClassId=0))
			AND ((vSA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			AND ((vSA.RecordStatusId=@rRecordStatusId) OR (@rRecordStatusId=0))
			ORDER BY OM.OrderIndex,vSA.DivisionOrder,vSA.RollNo
END
GO
PRINT N'Creating [sStudent].[pSUIDGenerationUpdate]...';


GO
CREATE PROCEDURE [sStudent].[pSUIDGenerationUpdate]
	 
	@rStudentId bigint,
	@rSUId nvarchar(20),
	@rCreatedUserId bigint,
	@rOrgGroupId smallint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	DECLARE @lSUId nvarchar(20)

	SELECT @lSUId=SUId FROM sStudent.tStudentMaster SM
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SM.OrgId
	WHERE SM.SUId=@rSUId AND OM.OrgGroupId=@rOrgGroupId AND SM.Id<>@rStudentId

	IF @lSUId IS NOT NULL
	BEGIN
		SELECT -103 AS Result,@lSUId AS SUId
		RETURN
	END 
	
	BEGIN TRY
	 BEGIN TRANSACTION	
	 BEGIN
	    UPDATE  sStudent.tStudentMaster
	    SET
		    SUId=@rSUId,
			RecordStatusId = 501,				  
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate() 
	      WHERE Id = @rStudentId 	   
	 END  
		SELECT 1 AS RESULT
		COMMIT TRANSACTION
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS RESULT
	END CATCH	
		
END
GO
PRINT N'Creating [sStudent].[pUserControlStudentLastAcademicSearchGet]...';


GO

CREATE PROCEDURE [sStudent].[pUserControlStudentLastAcademicSearchGet]
	 
	@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 = 0,
	@rOrgGroupBatchId int = 0
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON			 

BEGIN 	 
		BEGIN
			SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
			SET @rLastName = sCommon.fSearchStringGet(@rLastName)
		END
 IF(@rRollNo IS NULL)
	BEGIN
	SELECT 
			SA.AcademicId,
			SA.StudentId,
			SA.FirstName,
			SA.LastName,
			SA.MiddleName,
			SA.Name,
			SA.Code,
			SA.ClassId,
			SA.ClassName,
			SA.DivisionId,
			SA.DivisionName,
			SA.Number,
			SA.RollNo,
			SA.StatusId,
			SA.StatusName,
			SA.OrgId,
			--SA.Age,
			ISNULL(SA.AdmissionCategoryId,0) AS AdmissionCategoryId,
			SA.BatchId,
			SA.SUId
  FROM 
          sStudent.vStudentLastAcademic SA
  WHERE 
 
		((SA.ClassId=@rClassId)OR(@rClassId=0))
		AND((SA.DivisionId=@rDivisionId)OR(@rDivisionId=0))
		AND((SA.Code=@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 OR @rOrgId = 0)
		AND ( OrgGroupBatchId = @rOrgGroupBatchId	or @rOrgGroupBatchId = 0)	
		AND(SA.BatchId=@rBatchId or @rBatchId = 0)
		--AND((SA.Number=@rNumber)OR(@rNumber=0))	

ORDER BY SA.ClassId,SA.DivisionId,SA.RollNo
END
ELSE
BEGIN
	SELECT 
			SA.AcademicId,
			SA.StudentId,
			SA.FirstName,
			SA.LastName,
			SA.MiddleName,
			SA.Name,
			SA.Code,
			SA.ClassId,
			SA.ClassName,
			SA.DivisionId,
			SA.DivisionName,
			SA.Number,
			SA.RollNo,
			SA.StatusId,
			SA.StatusName,
			SA.OrgId,
			--SA.Age,
			ISNULL(SA.AdmissionCategoryId,0) AS AdmissionCategoryId 
  FROM 
          sStudent.vStudentLastAcademic SA             
  WHERE 
 
		((SA.ClassId=@rClassId)OR(@rClassId=0))
		AND((SA.DivisionId=@rDivisionId)OR(@rDivisionId=0))
		AND((SA.Code=@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) OR (@rOrgId=0))
			AND ( OrgGroupBatchId = @rOrgGroupBatchId	or @rOrgGroupBatchId = 0)	
		AND(SA.BatchId=@rBatchId or @rBatchId = 0)
		--AND(SA.BatchId=@rBatchId)
		--AND((SA.Number=@rNumber)OR(@rNumber=0))	

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


GO
CREATE PROCEDURE [sStudent].[pXMLChangeStudentClassAdd]
(
@rXmlDoc nvarchar(MAX)='',
@rOrgId smallint,
@rBatchId int,
@rClassId int,
@rDivisionId int
)
AS
SET NOCOUNT ON
DECLARE @intDoc INT
DECLARE @lNextNumber BIGINT 
DECLARE @idoc int
DECLARE @doc nvarchar(max)
SET @doc =@rXmlDoc
EXEC sp_xml_preparedocument @idoc OUTPUT, @doc
BEGIN

DECLARE @NodeName nVARCHAR(100),@lExistCode nvarchar(max)
SET @NodeName = '/Students/Students'

-- SET @rXmlDoc=REPLACE(@rXmlDoc,'&','AND')
 
EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sStudent.tAcademic', 0, 1, 1,@outNextNumber = @lNextNumber output


	IF EXISTS(SELECT SM.Code
	from
	(
			SELECT StudentId FROM
			OPENXML (@idoc,@nodename, 2)
			WITH (
					StudentId bigint)	
	)E
	INNER JOIN sStudent.tStudentMaster SM ON SM.Id=E.StudentId AND SM.OrgId=@rOrgId
	INNER JOIN sStudent.tAcademic A ON A.StudentId=SM.Id AND A.BatchId=@rBatchId)
	
	BEGIN
		SELECT @lExistCode  = COALESCE(@lExistCode ,'') + CONVERT(VARCHAR(15),SM.Code) + ' , ' 
		from
		(
				SELECT StudentId FROM
				OPENXML (@idoc, @nodename, 2)
				WITH (
						StudentId bigint)	
		)E
		INNER JOIN sStudent.tStudentMaster SM ON SM.Id=E.StudentId AND SM.OrgId=@rOrgId
		INNER JOIN sStudent.tAcademic A ON A.StudentId=SM.Id AND A.BatchId=@rBatchId
		SELECT @lExistCode
	 	RETURN
	END
 
INSERT INTO sStudent.tAcademic
(
		Id,
		StudentId,
		ClassId,
		DivisionId,
		RollNo,
		OrgId,
		BatchId,
		CreatedUserId,
		CreatedDateTime
)
SELECT
		@lNextNumber+ ROW_NUMBER() OVER(ORDER BY StudentId),
		StudentId,
		@rClassId,
		@rDivisionId,
		RollNo,
		@rOrgId,
		@rBatchId,
		CreatedUserId,
		sCommon.fgetdate()
FROM OPENXML (@idoc, @NodeName, 2)
WITH
(
		StudentId bigint,
		 
		RollNo int,
		CreatedUserId bigint
)  

	SELECT @lNextNumber = MAX(ID) FROM sStudent.tAcademic Where OrgId=@rOrgId
    EXECUTE sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sStudent.tAcademic', @rCurrentNumber = @lNextNumber 

	EXEC sp_xml_removedocument @idoc

Select 101 AS Result
--END
END
GO
PRINT N'Creating [sTransport].[pPickupListGet]...';


GO

CREATE PROCEDURE [sTransport].[pPickupListGet]
          
         
           @rTransportId int =0,
          -- @rPickupDestinationId int=0
          @rBusRouteId int=0,
          @rOrgGroupBatchId int
          
AS
SET NOCOUNT ON
			
BEGIN

SELECT 
       ISnull(VA.Code,'')AS Code,
       ISnull(VA.Name,'')AS Name,
       ISNULL(BRDM.Title,'') AS PickUpPoint,
       ISNULL(BRDM2.Title,'') As DropPoint,
       ISnull(VA.ClassName,'') + '-' + ISnull(VA.DivisionName,'') AS Class,
       ISnull(VA.OrganizationName,'')AS OrganizationName,
       ISNULL(BRM.Title,'') As BusRoute
     
    
  FROM
    sStudent.vStudentLastAcademic VA
    INNER JOIN sTransport.tAssignRoute AR ON AR.SourceId=VA.StudentId AND AR.SourceTypeId=2003 AND VA.StatusId=1
    LEFT JOIN sTransport.tBusRouteDestinationMaster BRDM ON BRDM.Id=AR.PickupDestinationId
    LEFT JOIN sTransport.tBusRouteDestinationMaster BRDM2 ON BRDM2.Id=AR.DropDestinationId	
    LEFT JOIN sTransport.tBusRouteMaster BRM ON BRM.Id=BRDM.BusRouteId
  
        
  WHERE 
	 BRM.TransportId = @rTransportId
	 AND BRDM.BusRouteId=@rBusRouteId
	-- AND VA.OrgGroupBatchId=@rOrgGroupBatchId
  -- AND AR.PickupDestinationId=@rPickupDestinationId
   Order By BRDM.Title
END
GO
PRINT N'Creating [sTransport].[pQuickAssignRouteAdd]...';


GO


CREATE PROCEDURE [sTransport].[pQuickAssignRouteAdd]
	 
	
	@rAssignRouteDetailXml [nvarchar](max),
	@rOrgId smallint,
	@rOrgGroupBatchId int=0,
	@rBusRouteId int=0
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rAssignRouteDetailXml
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION 
	 BEGIN	
	  
	 Delete AR from sTransport.tAssignRoute AR INNER JOIN sStudent.vStudentLastAcademic VA ON VA.StudentId=AR.sourceId
	 INNER JOIN sTransport.tBusRouteDestinationMaster B ON B.Id=AR.PickupDestinationId
	   where  VA.OrgId=@rOrgId AND VA.OrgGroupBatchId=@rOrgGroupBatchId AND  B.BusRouteId=@rBusRouteId AND AR.SourceTypeId=2003
	 INSERT INTO sTransport.tAssignRoute
		(
			SourceTypeId,
			SourceId,
			PickupDestinationId,
			DropDestinationId
			)
		SELECT
		    
			SourceTypeId,
			SourceId,
			PickupDestinationId,
			DropDestinationId
		FROM OPENXML (@loDoc, '/Table/AssignRouteDetail', 1)
		WITH ( 
				SourceTypeId smallint,
				SourceId bigint,
				PickupDestinationId int,
				DropDestinationId int
			  ) 
        SELECT 1 AS Result
	 END	
	 
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Creating [sTransport].[pQuickAssignRouteGet]...';


GO

CREATE PROCEDURE [sTransport].[pQuickAssignRouteGet]
           
           @rBusRouteId int=0,
           @rTransportId int = 0
          
AS
SET NOCOUNT ON

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

SELECT  
		
		
       ISNULL(BRDM.Title,'') AS PickUpPoint,
       ISNULL(BRDM.Id,0) PickUpRouteId
		
		
  FROM 
  sTransport.tBusRouteMaster BRM
 INNER JOIN sTransport.tBusRouteDestinationMaster BRDM ON BRM.Id=BRDM.BusRouteId
   -- LEFT JOIN sTransport.tBusRouteDestinationMaster BRDM2 ON BRM.Id=BRDM2.BusRouteId
 
 
  WHERE 
		 BRM.TransportId = @rTransportId
		 AND BRM.Id=@rBusRouteId 
END
GO
PRINT N'Creating [sTransport].[pRouteListGet]...';


GO

CREATE PROCEDURE [sTransport].[pRouteListGet]
           @rTransportId int =0,
           @rOrgGroupBatchId int
AS
SET NOCOUNT ON
			
BEGIN
SELECT 
		   ISNULL(BRM.RouteNumber,0) AS RouteNumber,
		   BRM.Title as BusRoute,
		  ISnull(BRM.Id,0) as BusRouteId,
		  ISNULL(VM.NoOfSeats,0) AS Capacity,
		  Count(BRM.Id) AS NoOfStudent,
		  ISNULL(VT.Title,'')AS VehicleType ,
		   ISNULL(VM.Title,'')AS VehicleName
		--FROM
		--   sTransport.tBusRouteMaster BRM
		--   INNER JOIN sTransport.tBusRouteDestinationMaster BRDM ON BRDM.BusRouteId=BRM.Id
		--   LEFT JOIN sTransport.tVehicleMaster VM ON VM.Id=BRM.VehicleId
		--   LEFT JOIN sTransport.tVehicleTypeMaster VT ON VT.Id=VM.VehicleTypeId
		--   LEFT JOIN sTransport.tAssignRoute AR ON AR.PickupDestinationId=BRDM.Id
		--   INNER JOIN sStudent.vStudentLastAcademic VA ON VA.StudentId=AR.SourceId AND AR.SourceTypeId=2003
		   
		 
  FROM
     sStudent.vStudentLastAcademic VA
     INNER JOIN sTransport.tAssignRoute AR ON AR.SourceId=VA.StudentId AND AR.SourceTypeId=2003 AND VA.StatusId=1
     INNER JOIN sTransport.tBusRouteDestinationMaster BRDM ON BRDM.Id=AR.PickupDestinationId
     LEFT JOIN sTransport.tBusRouteMaster BRM ON BRM.Id=BRDM.BusRouteId
     LEFT JOIN sTransport.tVehicleMaster VM ON VM.Id=BRM.VehicleId
     LEFT JOIN sTransport.tVehicleTypeMaster VT ON VT.Id=VM.VehicleTypeId
        
  WHERE 
	 BRM.TransportId = @rTransportId
	 And BRM.IsObsolete=0
	-- AND VA.OrgGroupBatchId=@rOrgGroupBatchId
    GROUP BY  BRM.Title,BRM.RouteNumber,BRM.OrderIndex,VM.NoOfSeats,BRM.Id,VM.Title,VT.Title,VM.Title
    order by BRM.OrderIndex
    
END
GO
PRINT N'Creating [sTransport].[pRptAssignRouteGet]...';


GO

CREATE PROCEDURE [sTransport].[pRptAssignRouteGet]
           @rTransportId int =0,
           @rBusRouteId int,
           @rOrgGroupBatchId int,
           @rOrgId smallint
AS
SET NOCOUNT ON
			
BEGIN
declare @string nvarchar(max)
SELECT 
		   BRM.Title as BusRoute,
		   ISnull(BRDM.Title,'') as PickupPoint,
		   BRM.OrderIndex AS RouteOrder,
		   BRDM.OrderIndex AS PickupOrder,
		   BRM.Id AS BusRouteId,
		   VA.OrgId AS OrgId,
		   VA.OrganizationName  AS OrganizationName,
		   BRDM.Id AS PickupDestinationId,
		  [sTransport].[fAssignRouteCodeGet](@rTransportId,BRDM.Id,VA.OrgId,@rOrgGroupBatchId) AS Code
		FROM
		sTransport.tAssignRoute AR
		INNER JOIN sStudent.vStudentLastAcademic VA  ON AR.SourceId=VA.StudentId AND AR.SourceTypeId=2003
		LEFT JOIN sTransport.tBusRouteDestinationMaster BRDM ON BRDM.Id=AR.PickupDestinationId
		LEFT JOIN sTransport.tBusRouteMaster BRM ON BRM.Id=BRDM.BusRouteId
  WHERE 
	 BRM.TransportId = @rTransportId
	 And BRM.IsObsolete=0
	 AND ((VA.OrgId=@rOrgId) OR (@rOrgId=0))
	 AND ((BRDM.BusRouteId=@rBusRouteId)OR (@rBusRouteId=0) )
	 AND VA.OrgGroupBatchId=@rOrgGroupBatchId
   
END
GO
PRINT N'Creating [sTransport].[pRptBlankPrintRouteGet]...';


GO

CREATE PROCEDURE [sTransport].[pRptBlankPrintRouteGet]
           @rTransportId int =0,
           @rBusRouteId int
          -- @rOrgGroupBatchId int
AS
SET NOCOUNT ON
			
BEGIN
SELECT 
		   ISNULL(BRM.RouteNumber,0) AS RouteNumber,
		   BRM.Title as BusRoute,
		   ISNULL(BRM.Id,0)AS BusRouteId,
		   ISnull(BRDM.Title,'') as PickupPoint,
		    BRM.OrderIndex
		FROM
		   sTransport.tBusRouteMaster BRM
		   INNER JOIN sTransport.tBusRouteDestinationMaster BRDM ON BRDM.BusRouteId=BRM.Id
  WHERE 
	 BRM.TransportId = @rTransportId
	 AND BRM.IsObsolete=0
	 AND ((BRM.Id=@rBusRouteId )OR(@rBusRouteId=0))
	 --AND VA.OrgGroupBatchId=@rOrgGroupBatchId
    --order by BRM.OrderIndex
END
GO

ALTER PROCEDURE [sCanteen].[pCanteenIssueMasterGet]
	
	@rId bigint = 0,
	@rCanteenId int ,
	@rFromDate date,
	@rToDate date

	--@rCode nvarchar(max)
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 SELECT 
	        CI.Id,
			CI.CanteenId,
			CI.SourceTypeId,
			CI.SourceId,
			CI.IssueDate,
			CI.TotalAmount,
			CI.CreatedDateTime,
			(CASE WHEN CI.SourceTypeId=2003 THEN  isnull(SMast.Code,'')
			WHEN  CI.SourceTypeId=95  THEN isnull(EM.Code, '') ElSE ''
			 END) AS Code,
			 (CASE WHEN CI.SourceTypeId=2003 THEN  isnull(SMast.Name,'')
			WHEN  CI.SourceTypeId=95  THEN isnull(EM.FirstName +' ' + EM.MiddleName + ' ' + EM.LastName ,'') ElSE CI.OtherName
			 END) AS Name,
			 ISNULL(CI.OtherName,'') AS OtherName,
			 (CASE WHEN CI.SourceTypeId=2003 THEN  isnull(SMast.OrgId,'')
			WHEN  CI.SourceTypeId=95  THEN isnull(EM.OrgId, '') ElSE ''
			 END) AS OrgId,
			  (CASE WHEN CI.SourceTypeId=2003 THEN  isnull(SMast.SUId,'')
			 ElSE ''
			 END) AS SUId
		
	   FROM sCanteen.tCanteenIssue CI
	   LEFT JOIN  sStudent.vStudentLastAcademic SMast ON SMast.StudentId = CI.SourceId AND CI.SourceTypeId = 2003  
       LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = CI.SourceId AND CI.SourceTypeId = 95
     
      
	  
	  WHERE ((CI.Id = @rId) OR (@rId = 0))
	  AND CI.CanteenId = @rCanteenId
	  AND ((CI.IssueDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	AND ((CI.IssueDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
	--  AND ((CI.IssueDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
order by CI.IssueDate desc
	  --EXEC [sCanteen].[pCanteenIssueDetailGet] @rId,@rCanteenId
END

GO

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

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

 SELECT @lStudentId= StudentId From sStudent.tAcademic Where Id=@rStudentId
  IF(@rId = 0)
  BEGIN
  
 DECLARE @lDepositAdd decimal(12,2)
  DECLARE @lAdjustmentAdd decimal(12,2)
 SELECT @lDepositAdd = (SELECT ISNULL(SUM(D.Amount),0) FROM sHostel.tHostelDepositAdd D 
	    WHERE D.StudentId = @lStudentId
	    AND D.HostelDepositHeadId = @rHostelDepositHeadId   AND D.HostelId=@rHostelId)
 
  SELECT @lAdjustmentAdd = (SELECT ISNULL(SUM(D.Amount),0) FROM sHostel.tHostelDepositAdjustment D 
	    WHERE D.StudentId = @lStudentId
	     AND D.HostelDepositHeadId = @rHostelDepositHeadId   AND D.HostelId=@rHostelId)
 
if ( @lDepositAdd - @lAdjustmentAdd < @rRefundAmount )
BEGIN
SELECT -101 AS RESULT -- Less then 0 amount re
RETURN
END
END
 
 
 ---- AMOUNT VALIDATIEON
 --IF EXISTS (SELECT 1 FROM sHostel.tHostelDepositRefund DR WHERE StudentId= @lStudentId AND HostelDepositHeadId = @rHostelDepositHeadId AND HostelId=@rHostelId)
 --BEGIN
	--SELECT @lRefundAmount = (SELECT ISNULL(SUM(D.Amount),0) FROM sHostel.tHostelDepositAdd D 
	--INNER JOIN sHostel.tHostelDepositRefund DR1 ON DR1.HostelDepositHeadId=D.HostelDepositHeadId AND DR1.StudentId=D.StudentId AND D.StudentId = @lStudentId
	--WHERE D.HostelDepositHeadId = DR1.HostelDepositHeadId AND D.StudentId=DR1.StudentId AND D.HostelId=DR1.HostelId)

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

GO


ALTER PROCEDURE [sSecurity].[pPendingLoginStudentdGet]
	
	@rOrgId smallint,
	@rBatchId int,
	@rIsPendingLogin bit,
	@rIsCreatedLogin bit
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	SELECT  TOP 100
			ISNULL(U.Id,0) AS Id,
			SC.StudentId,
			SC.Code,
			SC.Name,
			SC.ClassName + '-' + SC.DivisionName AS ClassName,
			SC.RollNo,
			ISNULL(SC.ParentContactNo,'') AS MobileNo,
			ISNULL(SC.ParentEmail,'') AS EmailId,
			U.LoginTitle AS UserName,
			U.LoginPassword
	FROM 
			sStudent.vStudentCommunication SC
	LEFT JOIN sSecurity.tUser U ON U.SourceId = SC.StudentId AND U.SourceTypeId=2003
	WHERE 
			((U.LoginPassWord is Null AND @rIsPendingLogin=1) OR (U.LoginPassWord is NOT Null AND @rIsCreatedLogin=1))
			AND	(SC.OrgId = @rOrgId)
			AND	(SC.BatchId = @rBatchId) 
	Order By SC.DivisionOrderIndex,SC.RollNo
	
END

GO

ALTER PROCEDURE [sTransport].[pPickupListGet]
          
         
           @rTransportId int =0,
          -- @rPickupDestinationId int=0
          @rBusRouteId int=0,
          @rOrgGroupBatchId int
          
AS
SET NOCOUNT ON
			
BEGIN

SELECT 
       ISnull(VA.Code,'')AS Code,
       ISnull(VA.Name,'')AS Name,
       ISNULL(BRDM.Title,'') AS PickUpPoint,
       ISNULL(BRDM2.Title,'') As DropPoint,
       ISnull(VA.ClassName,'') + '-' + ISnull(VA.DivisionName,'') AS Class,
       ISnull(VA.OrganizationName,'')AS OrganizationName,
       ISNULL(BRM.Title,'') As BusRoute
     
    
  FROM
    sStudent.vStudentLastAcademic VA
    INNER JOIN sTransport.tAssignRoute AR ON AR.SourceId=VA.StudentId AND AR.SourceTypeId=2003 AND VA.StatusId=1
    LEFT JOIN sTransport.tBusRouteDestinationMaster BRDM ON BRDM.Id=AR.PickupDestinationId
    LEFT JOIN sTransport.tBusRouteDestinationMaster BRDM2 ON BRDM2.Id=AR.DropDestinationId	
    LEFT JOIN sTransport.tBusRouteMaster BRM ON BRM.Id=BRDM.BusRouteId
  
        
  WHERE 
	 BRM.TransportId = @rTransportId
	 AND BRDM.BusRouteId=@rBusRouteId
	 AND VA.OrgGroupBatchId=@rOrgGroupBatchId
  -- AND AR.PickupDestinationId=@rPickupDestinationId
   Order By BRDM.Title
END

GO

ALTER PROCEDURE [sTransport].[pQuickAssignRouteAdd]
	 
	
	@rAssignRouteDetailXml [nvarchar](max),
	@rOrgId smallint,
	@rOrgGroupBatchId int=0,
	@rBusRouteId int=0
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rAssignRouteDetailXml
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION 
	 BEGIN	
	  
	 Delete AR from sTransport.tAssignRoute AR INNER JOIN sStudent.vStudentLastAcademic VA ON VA.StudentId=AR.sourceId
	 INNER JOIN sTransport.tBusRouteDestinationMaster B ON B.Id=AR.PickupDestinationId
	   where  VA.OrgId=@rOrgId  AND  B.BusRouteId=@rBusRouteId AND AR.SourceTypeId=2003
	  --AND VA.OrgGroupBatchId=@rOrgGroupBatchId
	 INSERT INTO sTransport.tAssignRoute
		(
			SourceTypeId,
			SourceId,
			PickupDestinationId,
			DropDestinationId
			)
		SELECT
		    
			SourceTypeId,
			SourceId,
			PickupDestinationId,
			DropDestinationId
		FROM OPENXML (@loDoc, '/Table/AssignRouteDetail', 1)
		WITH ( 
				SourceTypeId smallint,
				SourceId bigint,
				PickupDestinationId int,
				DropDestinationId int
			  ) 
        SELECT 1 AS Result
	 END	
	 
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO


ALTER PROCEDURE [sTransport].[pRouteListGet]
           @rTransportId int =0,
           @rOrgGroupBatchId int
AS
SET NOCOUNT ON
			
BEGIN
SELECT 
		   ISNULL(BRM.RouteNumber,0) AS RouteNumber,
		   BRM.Title as BusRoute,
		  ISnull(BRM.Id,0) as BusRouteId,
		  ISNULL(VM.NoOfSeats,0) AS Capacity,
		  Count(BRM.Id) AS NoOfStudent,
		  ISNULL(VT.Title,'')AS VehicleType ,
		   ISNULL(VM.Title,'')AS VehicleName
		--FROM
		--   sTransport.tBusRouteMaster BRM
		--   INNER JOIN sTransport.tBusRouteDestinationMaster BRDM ON BRDM.BusRouteId=BRM.Id
		--   LEFT JOIN sTransport.tVehicleMaster VM ON VM.Id=BRM.VehicleId
		--   LEFT JOIN sTransport.tVehicleTypeMaster VT ON VT.Id=VM.VehicleTypeId
		--   LEFT JOIN sTransport.tAssignRoute AR ON AR.PickupDestinationId=BRDM.Id
		--   INNER JOIN sStudent.vStudentLastAcademic VA ON VA.StudentId=AR.SourceId AND AR.SourceTypeId=2003
		   
		 
  FROM
     sStudent.vStudentLastAcademic VA
     INNER JOIN sTransport.tAssignRoute AR ON AR.SourceId=VA.StudentId AND AR.SourceTypeId=2003 AND VA.StatusId=1
     INNER JOIN sTransport.tBusRouteDestinationMaster BRDM ON BRDM.Id=AR.PickupDestinationId
     LEFT JOIN sTransport.tBusRouteMaster BRM ON BRM.Id=BRDM.BusRouteId
     LEFT JOIN sTransport.tVehicleMaster VM ON VM.Id=BRM.VehicleId
     LEFT JOIN sTransport.tVehicleTypeMaster VT ON VT.Id=VM.VehicleTypeId
        
  WHERE 
	 BRM.TransportId = @rTransportId
	 And BRM.IsObsolete=0
     AND VA.OrgGroupBatchId=@rOrgGroupBatchId
    GROUP BY  BRM.Title,BRM.RouteNumber,BRM.OrderIndex,VM.NoOfSeats,BRM.Id,VM.Title,VT.Title,VM.Title
    order by BRM.OrderIndex
    
END
GO

ALTER PROCEDURE [sStudent].[pSUIDGenerationGet]
	 
	 @rOrgGroupId smallint,
	 @rOrgId smallint,
	 @rDepartmentId int,
	 @rClassID int,
	 @rDivisionId int,
	 @rRecordStatusId smallint,
	 @rBatchId int=0
	 

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	SELECT 
			vSA.StudentId,
			vSA.OrgId,
			vSA.OrganizationName,
			VSA.DepartmentName,
			vSA.ClassName+' - '+vSA.DivisionName AS ClassDivisionName,
			vSA.RollNo,
			vSA.Code,
			ISNULL(vSA.SUId,'') AS SUID,
			vSA.Name
	FROM 
			sStudent.vStudentLastAcademic vSA
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = vSA.OrgId
	WHERE 
			(OM.OrgGroupId = @rOrgGroupId)
			AND (vSA.OrgId=@rOrgId)
			AND (vSA.BatchId=@rBatchId)
			AND ((vSA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
			AND ((vSA.ClassId=@rClassId) OR (@rClassId=0))
			AND ((vSA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			AND ((vSA.RecordStatusId=@rRecordStatusId) OR (@rRecordStatusId=0))
			ORDER BY OM.OrderIndex,vSA.DivisionOrder,vSA.RollNo
END

GO

 
ALTER PROCEDURE [sHostel].[pAssignRoomAssetAdd]
	 
        @rRoomAssetId int,
        @rSourceTypeId smallint,
        @rSourceId bigint,
        @rHostelId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	 
	BEGIN
	IF NOT EXISTS (SELECT * FROM sHostel.tAssignRoomAsset WHERE RoomAssetId = @rRoomAssetId and SourceTypeId =@rSourceTypeId and SourceId =@rSourceId and HostelId = @rHostelId )
	BEGIN
	INSERT INTO sHostel.tAssignRoomAsset
		(
		   RoomAssetId,
		   SourceTypeId,
		   SourceId,
		   HostelId
		
		)
	VALUES
		(
			@rRoomAssetId,
		    @rSourceTypeId,
		    @rSourceId,
		    @rHostelId
		
		)
		    SELECT 1 AS Result
	END	 
	END


	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO

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

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

 SELECT @lStudentId= StudentId From sStudent.tAcademic Where Id=@rStudentId
  IF(@rId = 0)
  BEGIN
  
 DECLARE @lDepositAdd decimal(12,2)
 DECLARE @lAdjustmentAdd decimal(12,2)
  DECLARE @lRefundAdd decimal(12,2)
  
 SELECT @lDepositAdd = (SELECT ISNULL(SUM(D.Amount),0) FROM sHostel.tHostelDepositAdd D 
	    WHERE D.StudentId = @lStudentId
	    AND D.HostelDepositHeadId = @rHostelDepositHeadId   AND D.HostelId=@rHostelId)
 
  SELECT @lAdjustmentAdd = (SELECT ISNULL(SUM(D.Amount),0) FROM sHostel.tHostelDepositAdjustment D 
	    WHERE D.StudentId = @lStudentId
	     AND D.HostelDepositHeadId = @rHostelDepositHeadId   AND D.HostelId=@rHostelId)
	     
SELECT @lRefundAdd = (SELECT ISNULL(SUM(R.RefundAmount),0) FROM sHostel.tHostelDepositRefund R 
	    WHERE R.StudentId = @lStudentId
	     AND R.HostelDepositHeadId = @rHostelDepositHeadId  AND R.HostelId=@rHostelId)
 
 
IF ( @lDepositAdd - @lAdjustmentAdd - @lRefundAdd < @rRefundAmount )
BEGIN
SELECT -101 AS RESULT -- Less then 0 amount re
RETURN
END
END
 
 
 ---- AMOUNT VALIDATIEON
 --IF EXISTS (SELECT 1 FROM sHostel.tHostelDepositRefund DR WHERE StudentId= @lStudentId AND HostelDepositHeadId = @rHostelDepositHeadId AND HostelId=@rHostelId)
 --BEGIN
	--SELECT @lRefundAmount = (SELECT ISNULL(SUM(D.Amount),0) FROM sHostel.tHostelDepositAdd D 
	--INNER JOIN sHostel.tHostelDepositRefund DR1 ON DR1.HostelDepositHeadId=D.HostelDepositHeadId AND DR1.StudentId=D.StudentId AND D.StudentId = @lStudentId
	--WHERE D.HostelDepositHeadId = DR1.HostelDepositHeadId AND D.StudentId=DR1.StudentId AND D.HostelId=DR1.HostelId)

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

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

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

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

	COMMIT TRANSACTION
		
END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
	
END

GO

 

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

BEGIN
SELECT 
		DHM.Title AS DepositHeadName,
		vSA.OrgId,
		DR.HostelDepositHeadId,
		DR.StudentId AS StudentId,
		vSA.AcademicId AS AcademicId,
		DR.RefundDate,
		DR.PayTypeId,
		DR.ChequeNo,
		DR.BankName,
		DR.Remark,
		DR.CreatedDateTime,
		vSA.Code,
        vSA.Name AS StudentName,        
        vSA.ClassName+' - '+vSA.DivisionName AS ClassDivisionName,
		 ISnull(DR.RefundAmount,0) AS RefundAmount,
		 ISNULL(vSA.SUId,'')AS SUId,
		 DR.Id
        
        
  FROM 		
		sStudent.vStudentLastAcademic vSA
		INNER JOIN sHostel.tHostelDepositRefund DR ON DR.StudentId = vSA.StudentId
		INNER JOIN sHostel.tHostelDepositHeadMaster DHM ON DHM.Id = DR.HostelDepositHeadId
		
  WHERE  
		--vSA.BatchId = @rBatchId 
		((DR.Id=@rId OR @rId=0))
		AND ((vSA.OrgId=@rOrgId OR @rOrgId=0))
		AND (DR.HostelDepositHeadId=@rHostelDepositHeadId OR @rHostelDepositHeadId=0)
		AND ((DR.RefundAmount >= @rFromRefundAmount) OR (@rFromRefundAmount = 0))
		AND ((DR.RefundAmount <= @rToRefundAmount) OR (@rToRefundAmount = 0))
		AND ((DR.RefundDate >= @rFromRefundDate) OR (ISNULL(@rFromRefundDate,'') = ''))
		AND ((DR.RefundDate <= @rToRefundDate) OR (ISNULL(@rToRefundDate,'') = ''))
		AND ((vSA.Code=@rCode) OR (ISNULL(@rCode,'')=''))
		AND (DR.HostelId=@rHostelId)
		GROUP BY
		DHM.Title,vSA.OrgId,DR.HostelDepositHeadId,DR.StudentId,vSA.AcademicId,DR.RefundAmount,DR.RefundDate,DR.PayTypeId,
		DR.ChequeNo,DR.BankName,DR.Remark,DR.CreatedDateTime,vSA.Code,vSA.Name,vSA.ClassName,vSA.DivisionName ,vSA.SUId , DR.Id
		Order By DR.RefundDate     
END

GO
 
ALTER PROCEDURE [sHostel].[pHostelStudentSearchGet]
	 
	 @rOrgId int,
	 @rHostelId int,
	 @rRoomId int,
	 @rStudentId bigint,
	 @rStudentName nvarchar(100),
	 @rStudentCode nvarchar(100),
	 @rClassId int,
	 @rDivisionId int,
	 @rOrgGroupBatchId int,
	 @rSUId nvarchar(20)='',
	 @rDepartmentId  int,
	 @rOrgGroupId smallint=0
	 

	 	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON 
BEGIN 		
			SELECT 		
			O.DisplayTitle AS Organization,
			HM.Title AS Hostel,
			RM.Title AS Room,
			SD.Code AS StudentCode,
			SD.Name AS StudentName,
			SD.ClassName + ' ' + SD.DivisionName AS Class,
			SD.DivisionName AS Division,
			SD.StudentId,
			SD.ClassId,
			SD.DivisionId,
			HM.Id AS HostelId,
			RM.Id AS RoomId,
			O.Id AS OrgId,
			ISNULL(AR.BedNumber,'') AS BedNumber ,
			ISnull(SD.SUID,'') AS SUID,
			ISNULL(SI.StudentPhoto, CONVERT(VARBINARY(MAX), 0)) AS StudentPhoto,
			ISnull(SD.DepartmentName,'') As DepartmentName,
			[sHostel].[fAssignRoomAssetGet](HM.Id,RM.Id,SD.StudentId) AS AssetNumber,
			ISNULL(SC.PresentCity,'') AS City,
			ISNULL(SC.ParentContactNo,'') AS ContactNo
			FROM sHostel.tAssignRoom AR 
			INNER JOIN sStudent.vStudentLastAcademic SD ON SD.StudentId = AR.SourceId AND AR.SourceTypeId = 2003
			INNER JOIN sHostel.tRoomMaster RM ON AR.RoomId = RM.Id 
			INNER JOIN sHostel.tHostelMaster HM ON HM.Id = RM.HostelId
			INNER JOIN sSetup.tOrganizationMaster O ON O.Id = SD.OrgId
			--INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SD.BatchId AND BM.IsActive = 1
			LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=SD.StudentId
			LEFT JOIN  sStudent.tStudentCommunication SC ON SC.StudentId=SD.StudentId
			
			Where 
			SourceTypeId = 2003
			--AND (SD.OrgGroupBatchId=@rOrgGroupBatchId)
			AND ((O.Id = @rOrgId) OR (ISNULL(@rOrgId,0) = 0))
			AND ((HM.Id = @rHostelId) OR (ISNULL(@rHostelId,0) = 0))
			AND ((RM.Id = @rRoomId) OR (ISNULL(@rRoomId,0) = 0))
			AND ((SD.StudentId = @rStudentId) OR (ISNULL(@rStudentId,0) = 0))
			AND ((SD.ClassId = @rClassId) OR (ISNULL(@rClassId,0) = 0))
			AND ((SD.DivisionId = @rDivisionId) OR (ISNULL(@rDivisionId,0) = 0))
			AND ((SD.Code Like @rStudentCode) OR (ISNULL(@rStudentCode,'')=''))
			AND ((SD.Name like @rStudentName + '%') OR (ISNULL(@rStudentName,'') = ''))
			AND ((SD.DepartmentId = @rDepartmentId ) OR (ISNULL(@rDepartmentId,0) = 0))
			AND ((SD.SUId like @rSUId) OR (ISNULL(@rSUId,'')=''))
			AND HM.OrgGroupId=@rOrgGroupId
			
END
GO


ALTER PROCEDURE [sSecurity].[pResetPortalUserPermission]
	
	@rOrgGroupId smallint ,
	@rUserType nvarchar(50) 
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN	

BEGIN TRY

DECLARE @lIsWindowSupport bit	 
SELECT @lIsWindowSupport = ISNULL(IsWindowSupport,0)   FROM sSetup.tOrgGroupMaster OGM 
WHERE OGM.Id = @rOrgGroupId

BEGIN TRANSACTION	

	IF @rUserType = 'AdminPortal'
	BEGIN
		DELETE FROM  sSecurity.tPermission WHERE OrgGroupId=@rOrgGroupId AND RoleId=sCommon.fGetIntIdForOrg(2,@rOrgGroupId)
		
		 Delete from sSecurity.tRoleModulePermission  where RoleId= sCommon.fGetIntIdForOrg(2,@rOrgGroupId)
			
		INSERT INTO  sSecurity.tRoleModulePermission 
		(
			RoleId,
			ModuleId
		) 
		Select RoleId=sCommon.fGetIntIdForOrg(2,@rOrgGroupId),ModuleId from sSecurity.tModulePermission Where OrgGroupId =@rOrgGroupId 
		 
	END
	 
	ELSE IF @rUserType = 'EmployeePortal'
	BEGIN
		Delete from sSecurity.tRoleModulePermission  where RoleId= sCommon.fGetIntIdForOrg(10,@rOrgGroupId)
			
		INSERT INTO  sSecurity.tRoleModulePermission 
		(
			RoleId,
			ModuleId
		) 
		Select RoleId=sCommon.fGetIntIdForOrg(10,@rOrgGroupId),ModuleId from sSecurity.tModulePermission Where OrgGroupId =@rOrgGroupId 
	END
	
	ELSE IF @rUserType = 'StudentPortal'
	BEGIN
		Delete from sSecurity.tRoleModulePermission  where RoleId= sCommon.fGetIntIdForOrg(22,@rOrgGroupId)
			
		INSERT INTO  sSecurity.tRoleModulePermission 
		(
			RoleId,
			ModuleId
		) 
		Select RoleId=sCommon.fGetIntIdForOrg(22,@rOrgGroupId),ModuleId from sSecurity.tModulePermission Where OrgGroupId =@rOrgGroupId 
	END
	
	
	ELSE IF @rUserType = 'OrganizationPortalTask'
	BEGIN
		DELETE FROM sSecurity.tOrganizationTask WHERE OrgGroupId=@rOrgGroupId 
	END

	 IF @rUserType = 'OrganizationPortalTask'
	BEGIN
	
	-- 1	, --Security	
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,139,23) --User
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,141,6)  -- Assign Permission
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,142,23) -- Login
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,245,6)  -- Change Password
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20158,3) -- Change Organization
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20175,2) -- Manage Student Login
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20176,2) -- Manage Employee Login
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20250,2) -- Manage Multi Child Login
		
	--	2	, --Alert	
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20170,6) -- Send Predefine Alert
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20195,2) -- SMS History
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20201,2) -- Email Configuration
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20215,2) -- Event Template
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20216,2) -- Send Custom Alert
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20221,2) -- Send Alert Others
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20297,2) -- Custom Template Master
	-- 3	, --Configuration	
		
	-- 135	, --Employee	
	    INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,10097,2) -- Employee List
	    --INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,10097,2) -- Employee List
	    
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20222,2) -- Employee Profile
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20223,2) -- View Employee Profile
		--INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20246,2) -- My Profile
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20249,2) -- Employee List
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20270,31) -- Upload Employee Photo
 
				
				
	--- 151	, --Setup		
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20001,2) -- Organization Master
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20002,2) -- Department Master
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20003,2) -- Class Master
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20004,2) -- Division Master
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20005,2) -- Term Master
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20006,2) -- Subject Master
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20007,2) -- Batch Master
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20008,2) -- Class Subject Master
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20055,2) -- Batch Class
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20285,2) -- Organization Group Batch Master
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20323,2) -- Upload Organization Photo
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20407,2) -- Organization Group Master
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20545,2) -- Org. Main Group Master
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20546,2) -- Org. Sub Group Master	
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20616,31) -- Batch Admin	
		
	 --	152	, --Student
		
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20021,2) -- Student List
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,10187,2) -- My Profile
		--INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20147,2) -- Student Custom Search
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20207,2) -- Student Full
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20312,2) -- Student Full Profile
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20269,31) -- Upload Student Photo
		
		 

 
		
	--		153	, --Attendance	
	INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20241,2) -- My Attendance
			
	 --154	, --Fee
	 INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20565,2) -- My Fee
	 
	 -- 155	, --Timetable
	 
	 -- 156	, --Assessment General
	 INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20564,2) -- My Result
	 
	-- 162	, --Communication
	
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20179,31) -- Upload Result
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20083,31) -- Query Category Master
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20086,31) -- Circular
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20094,31) -- Assignment
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20100,31) -- New blogs
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20105,31) -- News
		
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20116,31) -- Poll
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20130,31) -- Behaviour List
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20204,2) -- My Poll
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20180,2) -- Student View Result
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20181,2) -- Employee View Result
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20182,2) -- View Book List
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20171,7) -- Assign Task
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20172,2) -- View Task
		--INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20241,2) -- Student View Presence
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20085,2) -- Circular List
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20088,2) -- Query List
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20089,31) --New Query
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20091,2) -- Circular View
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20093,2) -- Assignment List
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20097,31) -- View Query
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20099,2) -- Blog List
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20101,2) -- Blog View
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20102,2) -- My Blog
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20103,2) -- Blog Activity
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20104,2) -- News List
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20106,2) -- News View
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20107,2) -- Query Queue

		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20114,2) -- Group Member
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20115,2) -- Poll List
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20117,2) -- Poll View
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20118,2) -- Poll Vote
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20125,31) -- Behaviour type Master
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20126,31) -- Behaviour Entry
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20246,2) -- My Profile
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20577,2) --  Birthday
		--INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20222,2) --   My Staff
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20617,2) --20617   --My Class
		
 

		--INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20110,31) -- Discussion
		--INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20112,31) -- Discussion Group
		--INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20109,31) -- Discussion List
		--INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20111,2) --  Discussion View
		--INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20113,2) -- Discussion Activities
		
	-- 209	, --Activity
	
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20054,3) -- Calendar
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20056,31) -- Event Schedule
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20058,31) -- Activity Type Master
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20059,31) -- Activity
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20151,31) -- House Master
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20152,31) -- Club Master
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20153,22) -- Assign Club
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20621,31) -- Event Type Master
		
	
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20197,2) -- Enrollment List
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20198,2) -- My Event List
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20199,7) -- View Event
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20209,2) -- My Activity List
		
		--INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20187,31) -- Placement
		--INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20188,31) -- Placement Invite
		--INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20189,31) -- Placement Registration
		--INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20190,2) -- View Palcement
		
	-- 210	, --Library
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20566,2) -- My Book
	
	
	-- 211	, --EExam
	--218	, --Placement
	
	-- 219	, --Gallery
	
	
 

 
	
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20186,31) -- Add Photo
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20185,3) -- View Photo
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,9136,31) -- Link Master
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,9137,18) -- Link Viewer 
		--INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,9126,31) -- Vedio Master
		--INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,9127,31) -- Vedio Type Master
		--INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,9128,2) -- Vedio Viewer
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20183,2) -- View Category
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20184,31) -- Add Category
		
	-- 220	, --Portal Academic
	
	
	
	-- 222	, --Employee Attendance
	-- 225	 --Academic
	INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20622,31) -- Teacher Subject Division
	INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20563,2) -- My Classwork
	INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20561,31) -- Classwork
	
	
-- 20554	Topic Master
--20555	Lesson Plan

 
  IF (@lIsWindowSupport = 1)
BEGIN
DELETE FROM sSecurity.tOrganizationTask WHERE OrgGroupId=@rOrgGroupId AND  
  TaskId IN (20565,20564,20566)
--20564	My Result
--20565	My Fee
--20566	My Books
END
ELSE
BEGIN
DELETE FROM sSecurity.tOrganizationTask WHERE OrgGroupId=@rOrgGroupId  
AND TaskId IN (20180,20181,20182 )
--20180	View Result
--20182	View Books
--20181  Employee View Result
END
	
	END	

	ELSE IF @rUserType = 'AdminPortal'
	BEGIN
	
	
			INSERT INTO sSecurity.tPermission
		(
			TaskId, 
			RoleId, 
			Permission, 
			IsObsolete, 
			CreatedUserId, 
			CreatedDateTime, 
			UpdatedUserId, 
			UpdatedDateTime,
			OrgGroupId
		)
	SELECT  
			TaskId,
			sCommon.fGetIntIdForOrg(2,@rOrgGroupId),
			AvailablePermission,
			0,
			1,
			sCommon.fGetDate(),
			1,
			sCommon.fGetDate(),
			@rOrgGroupId
	FROM 
		sSecurity.tOrganizationTask
	WHERE OrgGroupId = @rOrgGroupId
 
 
 IF (@lIsWindowSupport = 1)
BEGIN
DELETE FROM sSecurity.tPermission WHERE OrgGroupId=@rOrgGroupId AND RoleId=sCommon.fGetIntIdForOrg(22,@rOrgGroupId)
AND TaskId IN (20565,20564,20566)
--20564	My Result
--20565	My Fee
--20566	My Books
END
ELSE
BEGIN
DELETE FROM sSecurity.tPermission WHERE OrgGroupId=@rOrgGroupId AND RoleId=sCommon.fGetIntIdForOrg(22,@rOrgGroupId)
AND TaskId IN (20180,20182 )
--20180	View Result
--20182	View Books
END
 
 
 DELETE FROM sSecurity.tRoleDashlet WHERE RoleId = sCommon.fGetIntIdForOrg(10,@rOrgGroupId)
INSERT INTO sSecurity.tRoleDashlet (DashletId,RoleId)
SELECT  
			Id,
			sCommon.fGetIntIdForOrg(10,@rOrgGroupId)
			 
	FROM 
		sSecurity.tDashletMaster
		WHERE IsObsolete = 0
	 
  		
	END	
	
	ELSE IF ((@rUserType = 'EmployeePortal') OR (@rUserType = 'TeacherPortal'))
	BEGIN
	
	IF (@rUserType = 'EmployeePortal')
		DELETE FROM sSecurity.tPermission WHERE OrgGroupId=@rOrgGroupId AND RoleId=sCommon.fGetIntIdForOrg(10,@rOrgGroupId)
	ELSE IF (@rUserType = 'TeacherPortal')
		DELETE FROM sSecurity.tPermission WHERE OrgGroupId=@rOrgGroupId AND RoleId=sCommon.fGetIntIdForOrg(24,@rOrgGroupId)
	--ELSE IF (@rUserType = 'PrinciplePortal')
	--	DELETE FROM sSecurity.tPermission WHERE OrgGroupId=@rOrgGroupId AND RoleId=sCommon.fGetIntIdForOrg(25,@rOrgGroupId)	
	
    -- SELECT TaskId, ',-- ' + Title FROM sSecurity.tScreen WHERE ScreenGroupId = 114 
	-- SELECT TaskId, ',-- ' + Title FROM sSecurity.tScreen WHERE ScreenGroupId = 213 
	
	
	
			INSERT INTO sSecurity.tPermission
		(
			TaskId, 
			RoleId, 
			Permission, 
			IsObsolete, 
			CreatedUserId, 
			CreatedDateTime, 
			UpdatedUserId, 
			UpdatedDateTime,
			OrgGroupId
		)
	SELECT  
			Id,
			CASE
				WHEN @rUserType = 'EmployeePortal' THEN sCommon.fGetIntIdForOrg(10,@rOrgGroupId)
				WHEN @rUserType = 'TeacherPortal' THEN sCommon.fGetIntIdForOrg(24,@rOrgGroupId)
				--WHEN @rUserType = 'PrinciplePortal' THEN sCommon.fGetIntIdForOrg(25,@rOrgGroupId)
			END AS RoleId, 
			--sCommon.fGetIntIdForOrg(10,@rOrgGroupId),
			AvailablePermission,
			0,
			1,
			sCommon.fGetDate(),
			1,
			sCommon.fGetDate(),
			@rOrgGroupId
	FROM 
		sSecurity.tTask
	WHERE ID IN(
142     ,--Login
245     , -- Change Password
--9128	, -- Video Viewer
9137	, -- Link Viewer
20246   , -- My Profile
20054	, -- Calendar
20085	, -- Circular List
20088	, -- Query List
--20089	, -- New Query
--20091	, -- Circular View
20093	, -- Assignment List
--20095	, -- Assignment View
--20097	, -- View Query
20099	, -- Blog List
20101	, -- Blog View
20104	, -- News List
--20106	, -- News View
--20109	, -- Discussion List
--20110	, -- Discussion
--20111	, -- Discussion View
--20112	, -- Discussion Group
--20114	, -- Group Members
--20117	, -- Poll View
--20118	, -- Poll Vote
--20172	, -- View Task
--20181	,-- Result
--20246	,-- My Profile
--20577   ,-- Birthday
--20222   -- My Staff
20172	, -- View Task
20198	, -- My Event List
20204	, -- My Poll
20209	, -- My Activity List
--20241	, -- My Attendance
--20563	, -- My Classwork
--20564	, -- My Result
--20565	, -- My Fee
20566	, -- My Book List
20577   ,-- Birthday
20222   -- My Staff
--20191   ,-- My eTest
--20617   --My Class
 
				)
IF (@lIsWindowSupport = 1)
BEGIN
DELETE FROM sSecurity.tPermission WHERE OrgGroupId=@rOrgGroupId AND RoleId=sCommon.fGetIntIdForOrg(22,@rOrgGroupId)
AND TaskId IN (20566)
--20566	My Books
END
ELSE
BEGIN
DELETE FROM sSecurity.tPermission WHERE OrgGroupId=@rOrgGroupId AND RoleId=sCommon.fGetIntIdForOrg(22,@rOrgGroupId)
AND TaskId IN (20182 )

--20182	View Books
END

DELETE FROM sSecurity.tRoleDashlet WHERE RoleId = sCommon.fGetIntIdForOrg(10,@rOrgGroupId)
INSERT INTO sSecurity.tRoleDashlet (DashletId,RoleId)
SELECT  
			Id,
			sCommon.fGetIntIdForOrg(10,@rOrgGroupId)
			 
	FROM 
		sSecurity.tDashletMaster
	WHERE ID IN( 
	1,
	2,
	3,
	4,
	5,
	6,
	7,
	8,
	10,
	11,
	12,
	13,
	14,
	15,	 
	17,
	18
	
	)	
	AND IsObsolete = 0
	
 DELETE FROM sSecurity.tRoleModulePermission WHERE RoleId = sCommon.fGetIntIdForOrg(24,@rOrgGroupId)

	INSERT  INTO sSecurity.tRoleModulePermission (ModuleId,RoleId)
    SELECT  
			DISTINCT 
			ModuleId,
			sCommon.fGetIntIdForOrg(24,@rOrgGroupId)
			
			 
	FROM 
	
	sSecurity.tPermission P INNER JOIN sSecurity.tTask T ON P.TaskId = T.Id
	WHERE P.OrgGroupId=@rOrgGroupId AND RoleId=sCommon.fGetIntIdForOrg(24,@rOrgGroupId)
	
	
	DELETE FROM sSecurity.tRoleModulePermission WHERE RoleId = sCommon.fGetIntIdForOrg(10,@rOrgGroupId)

	INSERT  INTO sSecurity.tRoleModulePermission (ModuleId,RoleId)
    SELECT  
			DISTINCT 
			ModuleId,
			sCommon.fGetIntIdForOrg(10,@rOrgGroupId)
			
			 
	FROM 
	
	sSecurity.tPermission P INNER JOIN sSecurity.tTask T ON P.TaskId = T.Id
	WHERE P.OrgGroupId=@rOrgGroupId AND RoleId=sCommon.fGetIntIdForOrg(10,@rOrgGroupId)
	 
	END	
	
	ELSE IF @rUserType = 'ClerkPortal'
	BEGIN
	
		DELETE FROM sSecurity.tPermission WHERE OrgGroupId=@rOrgGroupId AND RoleId=sCommon.fGetIntIdForOrg(26,@rOrgGroupId)
	
		INSERT INTO sSecurity.tPermission
		(
			TaskId, 
			RoleId, 
			Permission, 
			IsObsolete, 
			CreatedUserId, 
			CreatedDateTime, 
			UpdatedUserId, 
			UpdatedDateTime,
			OrgGroupId
		)
		SELECT  
				Id,
				sCommon.fGetIntIdForOrg(26,@rOrgGroupId),
				AvailablePermission,
				0,
				1,
				sCommon.fGetDate(),
				1,
				sCommon.fGetDate(),
				@rOrgGroupId
		FROM 
			sSecurity.tTask
		WHERE ModuleId IN(
		152, -- Student
		154, -- Fee
		159, -- Certificate
		161, -- Admission
		230) -- Student Setting
		
		DELETE P FROM sSecurity.tPermission P INNER JOIN sSecurity.tTask T ON T.Id = P.TaskId
		WHERE P.OrgGroupId=@rOrgGroupId AND P.RoleId=sCommon.fGetIntIdForOrg(26,@rOrgGroupId) AND T.ModuleId = 154 
		AND P.TaskId NOT IN(
							20108, -- Fee Receipt List
							20068, -- Fee Receipt 
							20025, -- Student Fee
							20225  -- Fee Report
							)
							
							
	DELETE FROM sSecurity.tRoleModulePermission WHERE RoleId = sCommon.fGetIntIdForOrg(26,@rOrgGroupId)

	INSERT  INTO sSecurity.tRoleModulePermission (ModuleId,RoleId)
    SELECT  
			DISTINCT 
			ModuleId,
			sCommon.fGetIntIdForOrg(26,@rOrgGroupId)
			
			 
	FROM 
	
	sSecurity.tPermission P INNER JOIN sSecurity.tTask T ON P.TaskId = T.Id
	WHERE P.OrgGroupId=@rOrgGroupId AND RoleId=sCommon.fGetIntIdForOrg(26,@rOrgGroupId)
		
	END
	
	
	
	
	
	
	
	
	
		ELSE IF @rUserType = 'PrinciplePortal'
	BEGIN
	
		DELETE FROM sSecurity.tPermission WHERE OrgGroupId=@rOrgGroupId AND RoleId=sCommon.fGetIntIdForOrg(25,@rOrgGroupId)
	
		INSERT INTO sSecurity.tPermission
		(
			TaskId, 
			RoleId, 
			Permission, 
			IsObsolete, 
			CreatedUserId, 
			CreatedDateTime, 
			UpdatedUserId, 
			UpdatedDateTime,
			OrgGroupId
		)
		SELECT  
			Id,
			 sCommon.fGetIntIdForOrg(25,@rOrgGroupId),  
			AvailablePermission,
			0,
			1,
			sCommon.fGetDate(),
			1,
			sCommon.fGetDate(),
			@rOrgGroupId
		FROM 
			sSecurity.tTask
		WHERE ModuleId IN(
				--Clerk 
				152, -- Student
				154, -- Fee
				159, -- Certificate
				161, -- Admission
				230 )
				OR Id In 
				(
					--142     ,--Login
--245     , -- Change Password
--9128	, -- Video Viewer
9137	, -- Link Viewer
20246   , -- My Profile
20054	, -- Calendar
20085	, -- Circular List
20088	, -- Query List
--20089	, -- New Query
--20091	, -- Circular View
20093	, -- Assignment List
--20095	, -- Assignment View
--20097	, -- View Query
20099	, -- Blog List
20101	, -- Blog View
20104	, -- News List
--20106	, -- News View
--20109	, -- Discussion List
--20110	, -- Discussion
--20111	, -- Discussion View
--20112	, -- Discussion Group
--20114	, -- Group Members
--20117	, -- Poll View
--20118	, -- Poll Vote
--20172	, -- View Task
--20181	,-- Result
--20246	,-- My Profile
--20577   ,-- Birthday
--20222   -- My Staff
20172	, -- View Task
20198	, -- My Event List
20204	, -- My Poll
--20209	, -- My Activity List
--20241	, -- My Attendance
--20563	, -- My Classwork
--20564	, -- My Result
--20565	, -- My Fee
20566	, -- My Book List
20577   ,-- Birthday
20222   -- My Staff
--20191   ,-- My eTest
--20617   --My Class
				)
	 
							
							
	DELETE FROM sSecurity.tRoleModulePermission WHERE RoleId = sCommon.fGetIntIdForOrg(25,@rOrgGroupId)

	INSERT  INTO sSecurity.tRoleModulePermission (ModuleId,RoleId)
    SELECT  
			DISTINCT 
			ModuleId,
			sCommon.fGetIntIdForOrg(25,@rOrgGroupId)
			
			 
	FROM 
	
	sSecurity.tPermission P INNER JOIN sSecurity.tTask T ON P.TaskId = T.Id
	WHERE P.OrgGroupId=@rOrgGroupId AND RoleId=sCommon.fGetIntIdForOrg(25,@rOrgGroupId)
		
	END
	
	
	
	
	
	
	
	
	ELSE IF @rUserType = 'HeadClerkPortal'
	BEGIN
	
		DELETE FROM sSecurity.tPermission WHERE OrgGroupId=@rOrgGroupId AND RoleId=sCommon.fGetIntIdForOrg(27,@rOrgGroupId)
	
		INSERT INTO sSecurity.tPermission
		(
			TaskId, 
			RoleId, 
			Permission, 
			IsObsolete, 
			CreatedUserId, 
			CreatedDateTime, 
			UpdatedUserId, 
			UpdatedDateTime,
			OrgGroupId
		)
		SELECT  
				Id,
				sCommon.fGetIntIdForOrg(27,@rOrgGroupId),
				AvailablePermission,
				0,
				1,
				sCommon.fGetDate(),
				1,
				sCommon.fGetDate(),
				@rOrgGroupId
		FROM 
			sSecurity.tTask
		WHERE ModuleId IN(
		152, -- Student
		154, -- Fee
		159, -- Certificate
		161, -- Admission
		230) -- Student Setting
		
		DELETE FROM sSecurity.tRoleModulePermission WHERE RoleId = sCommon.fGetIntIdForOrg(27,@rOrgGroupId)

	INSERT  INTO sSecurity.tRoleModulePermission (ModuleId,RoleId)
    SELECT  
			DISTINCT 
			ModuleId,
			sCommon.fGetIntIdForOrg(27,@rOrgGroupId)
			
			 
	FROM 
	
	sSecurity.tPermission P INNER JOIN sSecurity.tTask T ON P.TaskId = T.Id
	WHERE P.OrgGroupId=@rOrgGroupId AND RoleId=sCommon.fGetIntIdForOrg(27,@rOrgGroupId)
	END
	
	ELSE IF @rUserType = 'FrontOfficePortal'
	BEGIN
	
		DELETE FROM sSecurity.tPermission WHERE OrgGroupId=@rOrgGroupId AND RoleId=sCommon.fGetIntIdForOrg(28,@rOrgGroupId)
	
		INSERT INTO sSecurity.tPermission
		(
			TaskId, 
			RoleId, 
			Permission, 
			IsObsolete, 
			CreatedUserId, 
			CreatedDateTime, 
			UpdatedUserId, 
			UpdatedDateTime,
			OrgGroupId
		)
		SELECT  
				Id,
				sCommon.fGetIntIdForOrg(28,@rOrgGroupId),
				AvailablePermission,
				0,
				1,
				sCommon.fGetDate(),
				1,
				sCommon.fGetDate(),
				@rOrgGroupId
		FROM 
			sSecurity.tTask
		WHERE Id IN(
		-- Front Office
		20284, -- Visitor Log
		20696, -- Courier Dispatch
		20698, -- Courier Receive
		--20173, -- Contact Type Master
		--20174, -- Contact Master
		
		-- Employee Center 
		--20246,  -- My Profile
		--20576,  -- My Payroll
		--20181,  -- Result
		
		-- My Communication
		20054,  -- Calender
		20085,  -- Circular List
		20088,  -- Query List
		20099,  -- Blog List
		20104,  -- News List
		20109,  -- Discussion List
		20172,  -- View Task
		20222,  -- My Staff
		20577,  -- Birthdays
		20723,  -- E-Book List
		20724,  -- My Messages
		20183,  -- Photos
		--9128,   -- Videos
		20204,  -- My Poll
		20107,  -- Query Queue
		20093,  -- My Assignment
		20103,  -- Blog Activities
		--20209,  -- My Activity
		20198,  -- My Event
		20692,  -- Useful Info
		9137 ,  -- Useful Links
		20113   -- Discussion Activities
		) 
		
		DELETE FROM sSecurity.tRoleModulePermission WHERE RoleId = sCommon.fGetIntIdForOrg(28,@rOrgGroupId)

	INSERT  INTO sSecurity.tRoleModulePermission (ModuleId,RoleId)
    SELECT  
			DISTINCT 
			ModuleId,
			sCommon.fGetIntIdForOrg(28,@rOrgGroupId)
			
			 
	FROM 
	
	sSecurity.tPermission P INNER JOIN sSecurity.tTask T ON P.TaskId = T.Id
	WHERE P.OrgGroupId=@rOrgGroupId AND RoleId=sCommon.fGetIntIdForOrg(28,@rOrgGroupId)
	END


	ELSE IF @rUserType = 'ParentPortal'
	BEGIN
	
	DELETE FROM sSecurity.tPermission WHERE OrgGroupId=@rOrgGroupId AND RoleId=sCommon.fGetIntIdForOrg(22,@rOrgGroupId)
	
    --	SELECT TaskId FROM sSecurity.tScreen WHERE ScreenGroupId = 114 
	--	SELECT TaskId FROM sSecurity.tScreen WHERE ScreenGroupId = 172 
		INSERT INTO sSecurity.tPermission
		(
			TaskId, 
			RoleId, 
			Permission, 
			IsObsolete, 
			CreatedUserId, 
			CreatedDateTime, 
			UpdatedUserId, 
			UpdatedDateTime,
			OrgGroupId
		)
	SELECT  
			Id,
			sCommon.fGetIntIdForOrg(22,@rOrgGroupId),
			AvailablePermission,
			0,
			1,
			sCommon.fGetDate(),
			1,
			sCommon.fGetDate(),
			@rOrgGroupId
	FROM 
		sSecurity.tTask
	WHERE ID IN(
142     ,--Login
245     , -- Change Password
--9128	, -- Video Viewer
9137	, -- Link Viewer
10187	, -- My Profile
--20312   , -- Student Full Profile
20054	, -- Calendar
20085	, -- Circular List
20088	, -- Query List
--20089	, -- New Query
--20091	, -- Circular View
20093	, -- Assignment List
--20095	, -- Assignment View
--20097	, -- View Query
20099	, -- Blog List
20101	, -- Blog View
20104	, -- News List
--20106	, -- News View
--20109	, -- Discussion List
--20110	, -- Discussion
--20111	, -- Discussion View
--20112	, -- Discussion Group
--20114	, -- Group Members
--20117	, -- Poll View
--20118	, -- Poll Vote
20130	, -- Behaviour List
--20172	, -- View Task
20180	, -- Student View Result
20182	, -- View Book List
20183	, -- View Category
--20190	, -- View Placement
--20191	, -- My eTest
20198	, -- My Event List
20204	, -- My Poll
20209	, -- My Activity List
20241	, -- My Attendance
20563	, -- My Classwork
20564	, -- My Result
20565	, -- My Fee
20566	, -- My Book List
20577   ,-- Birthday
20222   ,-- My Staff
--20191   ,-- My eTest
20617   --My Class

)
	
IF (@lIsWindowSupport = 1)
BEGIN
DELETE FROM sSecurity.tPermission WHERE OrgGroupId=@rOrgGroupId AND RoleId=sCommon.fGetIntIdForOrg(22,@rOrgGroupId)
AND TaskId IN (20565,20564,20566)
--20564	My Result
--20565	My Fee
--20566	My Books
END
ELSE
BEGIN
DELETE FROM sSecurity.tPermission WHERE OrgGroupId=@rOrgGroupId AND RoleId=sCommon.fGetIntIdForOrg(22,@rOrgGroupId)
AND TaskId IN (20180,20182 )
--20180	View Result
--20182	View Books
END
	
DELETE FROM sSecurity.tRoleDashlet WHERE RoleId = sCommon.fGetIntIdForOrg(22,@rOrgGroupId)

INSERT  INTO sSecurity.tRoleDashlet (DashletId,RoleId)
SELECT  
			Id,
			sCommon.fGetIntIdForOrg(22,@rOrgGroupId)
			 
	FROM 
		sSecurity.tDashletMaster
	WHERE ID IN( 
	1,
	2,
	3,
	7,
	12,
	13,
	14,
	15,	 
	17,
	18
	
	)
	AND IsObsolete = 0


DELETE FROM sSecurity.tRoleModulePermission WHERE RoleId = sCommon.fGetIntIdForOrg(22,@rOrgGroupId)

	INSERT  INTO sSecurity.tRoleModulePermission (ModuleId,RoleId)
    SELECT  
			DISTINCT 
			ModuleId,
			sCommon.fGetIntIdForOrg(22,@rOrgGroupId)
			
			 
	FROM 
	
	sSecurity.tPermission P INNER JOIN sSecurity.tTask T ON P.TaskId = T.Id
	WHERE P.OrgGroupId=@rOrgGroupId AND RoleId=sCommon.fGetIntIdForOrg(22,@rOrgGroupId)
	 
	END		

	
	SELECT 1 AS RESULT
COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END

GO

 

ALTER PROCEDURE [sFee].[pRptFeeSummaryGet]
		@rReportId int,
		@rReceiptBookId int,
		@rAdmissionCategoryId int,
		@rClassId int,
		@rDivisionId int,
		@rUptoDate date,
		@rBatchId int,
		@rUserId bigint,
		@rBuilder1 nvarchar(max),
		@rBuilder2 nvarchar(max),
		@rIsDetail bit,
		@rOrgId int,
		@rOrgGroupBatchId int,
		@rIsExemption bit =0,
		@rStatusId int,
		@rCommonBatch nvarchar(100),
		@rDepartmentId int,
		@rFromRollNo int,
	    @rToRollNo int,
	    @rCode nvarchar(20),
	    @rIsFilter bit,
		@rIsHeader bit,
		@rCreatedUserName nvarchar(100)='',
		@rFeeHeadId nvarchar(max) = '',
		@rIsDisplayOrgGroup bit=0,
		@rExemptionTypeId int=0
		
		
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 	
	SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		@rIsDetail AS IsDetail,
		@rIsFilter As IsFilter,
		@rIsHeader As IsHeader, 
		@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
		SA.AcademicId,
		SA.RollNo,
		SA.Name,
		SA.Code,
		SA.ClassId,
		SA.DivisionId,
		SA.ClassName,
		SA.DivisionName,
		SA.DivisionOrder AS DivisionOrderIndex,
		SA.ClassOrderIndex AS ClassOrderIndex,
		SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
		FS.Id AS FeeSetupId,
		
		ISNULL(FS.IsVariable,0)AS IsVariable,
		ISNULL(FS.Amount,0)AS Amount,
		ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
		ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
		ISNULL(FA.VariableAmount,0.00)AS FAAmount,
		ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
		ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
		ISNULL(FA.NotApplicableAmount,0.00)AS NotApplicableAmount,
		ISNULL(R.PaidAmount,0) AS PaidAmount,
		ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)AS PendingAmount,
		ISNULL(FA.Remark,'') AS Remark,
		FS.ReceiptBookId,
		FS.FeeName,
		SA.OrgId,
		O.DisplayTitle AS OrgName,
		O.OrderIndex AS OrgOrderIndex,
		ISNULL(RBM.Title,'') AS ReceiptBookTitle,
		ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
		SA.DepartmentId,
		SA.DepartmentName,
		SA.ExemptionTypeId,
		ISNULL(ETM.Title,'') AS ExemptionType,
		FHM.Id AS FeeHeadId,
		FHM.Title AS FeeHeadName,
		FHM.OrderIndex AS FeeHeadOrderIndex
  FROM 
  
			 sStudent.vStudentAcademic SA
		INNER JOIN 
		(
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName,
				FM.FeeHeadId
			FROM sFee.tFeeSetup FS1
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
			AND ((SA1.ClassId=@rClassId) OR (@rClassId=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 ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				UNION ALL
				
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName,
				FM.FeeHeadId
			FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO
			ON FO.FeeSetupId=FS1.Id 
	    INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND FS1.BatchId = SA1.BatchId
			AND ((SA1.ClassId=@rClassId) OR (@rClassId=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 ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
		) FS ON FS.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
		LEFT JOIN
		(
		    SELECT 
					ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
		    FROM
					sFee.tReceipt R 
				INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
				INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
				INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId 
				AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND (SA1.ClassId=@rClassId OR @rClassId=0) 
				AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
			WHERE		
				(R.SourceTypeId = 2001)
				AND (R.IsObsolete = 0) 
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND (SA1.OrgGroupBatchId = @rOrgGroupBatchId)
				AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND (R.ReceiptDate <= @rUptoDate)
				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
					GROUP BY FeeSetupId,R.SourceId
		
		) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
		 INNER JOIN sSetup.tOrganizationMaster O ON
		 SA.OrgId = O.Id
		 INNER JOIN sFee.tReceiptBookMaster RBM 
			ON FS.ReceiptBookId=RBM.Id
		 INNER JOIN sFee.tFeeHeadMaster FHM 
			ON FHM.Id=FS.FeeHeadId	
		 LEFT JOIN sFee.tExemptionTypeMaster ETM
			ON ETM.Id = SA.ExemptionTypeId
			
	WHERE	
	((@rIsExemption = 0 AND  1 = 1) OR (@rIsExemption = 1  AND  ISNULL(FA.DiscountAmount,0) > 0))
    AND	((SA.BatchId=@rBatchId) OR (@rBatchId=0))   
    AND	((SA.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))   
    AND (SA.StatusId=@rStatusId OR @rStatusId=0)
	--AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
	AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
	AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
	AND ((SA.Code=@rCode) OR (@rCode=''))
	AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))		
	AND ((SA.ExemptionTypeId=@rExemptionTypeId) OR (@rExemptionTypeId=0))		
	AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
	AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			Order by SA.RollNo
				
				
--	UNION ALL
	
--	SELECT 
--		R.Id AS ReceiptId,
--		0 AS ClassId,
--		--SA.ClassName,
--		0 AS DivisionId,
--		--SA.DivisionName,
--		EM.DepartmentId,
--		EM.DepartmentName AS ClassDept,
--		0 AS RollNo,
--		EM.Code,
--		EM.EmployeeName,
--		PTM.Title AS PayType,
--		R.ReceiptAmount
			
--  FROM 
--			sFee.tReceipt R
--		INNER JOIN sCommon.tSourceTypeMaster STM
--			ON STM.Id=R.SourceTypeId AND R.SourceTypeId = 95
--		INNER JOIN sHrm.vExtEmployeeMaster EM
--			ON EM.EmployeeId=R.SourceId
--		INNER JOIN sFinanceCommon.tPayTypeMaster PTM
--			ON PTM.Id=R.PayTypeId
			
--WHERE 
--		((EM.DepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))
--	AND ((R.ReceiptNumber >= @rFromReceiptNo) OR (@rFromReceiptNo = 0))
--	AND ((R.ReceiptNumber <= @rToReceiptNo) OR (@rToReceiptNo = 0))
--	AND ((R.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
--	AND ((R.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
--	AND (R.BatchId = @rBatchId)
END

GO

 
ALTER PROCEDURE [sHostel].[pStudentLedgerGet]
	 
	
	 @rHostelId int,
	 @rCode  nvarchar(20)='',
	 @rSUId nvarchar(20)='',
	 @rHostelDepositHeadId int,
	 @rOrgId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON 
BEGIN 
 SELECT A.Date,
        A.Credit,
        A.Debit
          FROM(
			SELECT 
			DA.DepositDate AS Date,
			ISnull (DA.Amount,0) AS Credit,
		    0 AS Debit
			FROM sStudent.vStudentLastAcademic  VA
			INNER JOIN sHostel.tHostelDepositAdd DA  ON VA.StudentId = DA.StudentId 
			Where 
			((VA.Code = @rCode) OR (ISNULL(@rCode,'') = ''))
			AND DA.HostelId = @rHostelId 
			AND ((VA.SUId like @rSUId) OR (ISNULL(@rSUId,'')=''))
			AND (DA.HostelDepositHeadId = @rHostelDepositHeadId) 
			AND ((VA.OrgId = @rOrgId) OR (ISNULL(@rOrgId,0) = 0)) 
			
			UNION ALL 
			SELECT 
			DAJ.AdjustmentDate As Date,
			0  AS Credit,
			ISnull (DAJ.Amount,0)  AS Debit
			FROM sStudent.vStudentLastAcademic  VA
			  INNER JOIN sHostel.tHostelDepositAdjustment DAJ ON DAJ.StudentId = VA.StudentId
		     
			Where 
			((VA.Code = @rCode) OR (ISNULL(@rCode,'') = ''))
			AND DAJ.HostelId = @rHostelId 
			AND ((VA.SUId like @rSUId) OR (ISNULL(@rSUId,'')=''))
			AND (DAJ.HostelDepositHeadId = @rHostelDepositHeadId) 
			AND ((VA.OrgId = @rOrgId) OR (ISNULL(@rOrgId,0) = 0)) 
			UNION ALL 
			SELECT 
			DR.RefundDate As Date,
			0  AS Credit,
			ISnull (DR.RefundAmount,0)  AS Debit
			FROM sStudent.vStudentLastAcademic  VA
			  INNER JOIN sHostel.tHostelDepositRefund DR ON DR.StudentId = VA.StudentId
		     
			Where 
			((VA.Code = @rCode) OR (ISNULL(@rCode,'') = ''))
			AND DR.HostelId = @rHostelId
			AND ((VA.SUId like @rSUId) OR (ISNULL(@rSUId,'')=''))
			AND (DR.HostelDepositHeadId = @rHostelDepositHeadId) 
			AND ((VA.OrgId = @rOrgId) OR (ISNULL(@rOrgId,0) = 0)) 
			)A 
			Order BY A.Date
END

GO
ALTER PROCEDURE [sStudent].[pSUIDGenerationGet]
	 
	 @rOrgGroupId smallint,
	 @rOrgId smallint,
	 @rDepartmentId int,
	 @rClassID int,
	 @rDivisionId int,
	 @rRecordStatusId smallint,
	 @rBatchId int=0
	 

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	SELECT 
			vSA.StudentId,
			vSA.OrgId,
			vSA.OrganizationName,
			VSA.DepartmentName,
			vSA.ClassName+' - '+vSA.DivisionName AS ClassDivisionName,
			vSA.RollNo,
			vSA.Code,
			ISNULL(vSA.SUId,'') AS SUID,
			vSA.Name
	FROM 
			sStudent.vStudentLastAcademic vSA
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = vSA.OrgId
	WHERE 
			(OM.OrgGroupId = @rOrgGroupId)
			AND (vSA.OrgId=@rOrgId)
			AND (vSA.BatchId=@rBatchId)
			AND ((vSA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
			AND ((vSA.ClassId=@rClassId) OR (@rClassId=0))
			AND ((vSA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			AND ((vSA.RecordStatusId=@rRecordStatusId) OR (@rRecordStatusId=0))
			ORDER BY OM.OrderIndex,vSA.DivisionOrder,vSA.RollNo
END
GO

if not EXISTS (select 1 from [sCommon].[tDepends] WHERE Id = 20914)
BEGIN

INSERT INTO [sCommon].[tDepends]
           ([Id]
           ,[ParentTable]
           ,[DependentTable]
           ,[SourceTypeFieldName]
           ,[SourceTypeId]
           ,[FunctionalityType]
           ,[ScreenId]
           ,[TableId])
     VALUES(20914,'sHostel.tRoomAssetMaster','sHostel.tAssignRoomAsset.RoomAssetId',NULL,NULL,1,20044,NULL)
END
GO

if not EXISTS (select 1 from [sCommon].[tDepends] WHERE Id = 20911)
BEGIN
INSERT INTO [sCommon].[tDepends]
           ([Id]
           ,[ParentTable]
           ,[DependentTable]
           ,[SourceTypeFieldName]
           ,[SourceTypeId]
           ,[FunctionalityType]
           ,[ScreenId]
           ,[TableId])
     VALUES(20911,'sHostel.tAssetTypeMaster','sHostel.tRoomAssetMaster.AssetTypeId',NULL,NULL,1,20044,NULL),
     (20912,'sHostel.tHostelDepositHeadMaster','sHostel.tHostelDepositAdjustment.HostelDepositHeadId',NULL,NULL,1,20526,NULL),
     (20913,'sHostel.tHostelDepositHeadMaster','sHostel.tHostelDepositAdd.HostelDepositHeadId',NULL,NULL,1,20526,NULL)
 END          
GO

UPDATE  sCommon.tDepends SET ParentTable = 'sSetup.tDepartmentMaster' Where ID IN (1095,9229)







