 
 delete from sEExam.tEntryModeMaster
delete from sCommon.tReportTypeMaster
GO
PRINT N'Dropping [sFee].[tOnlinePayment]...';


GO
DROP TABLE [sFee].[tOnlinePayment];


GO
PRINT N'Dropping [sFee].[tOnlinePaymentDetail]...';


GO
DROP TABLE [sFee].[tOnlinePaymentDetail];


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


GO
CREATE SCHEMA [sOp]
    AUTHORIZATION [dbo];


GO
PRINT N'Altering [sActivity].[tHouseMaster]...';


GO
ALTER TABLE [sActivity].[tHouseMaster]
    ADD [ColorCode] NVARCHAR (50) NULL;


GO
PRINT N'Altering [sAlert].[tSMSConfiguration]...';


GO
ALTER TABLE [sAlert].[tSMSConfiguration]
    ADD [SMSUnicodeURL] NVARCHAR (1000) NULL;


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


GO
ALTER TABLE [sAssessment].[tCCECSIndicatorMaster] ALTER COLUMN [Title] NVARCHAR (200) NULL;


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


GO
ALTER TABLE [sAssessment].[tExamDetail] ALTER COLUMN [Maximum] DECIMAL (10, 2) NOT NULL;

ALTER TABLE [sAssessment].[tExamDetail] ALTER COLUMN [Minimum] DECIMAL (10, 2) NOT NULL;


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


GO
ALTER TABLE [sAssessment].[tTempAllExam]
    ADD [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;


GO
PRINT N'Altering [sCommon].[tReport]...';


GO
ALTER TABLE [sCommon].[tReport]
    ADD [SelectableField] NVARCHAR (2000) NULL;


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


GO
ALTER TABLE [sFee].[tCollectionGroupMaster]
    ADD [FooterRemark1] NVARCHAR (200) NULL,
        [FooterRemark2] NVARCHAR (200) NULL,
        [FeePeriod]     NVARCHAR (100) NULL;


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


GO
ALTER TABLE [sFee].[tReceiptBookMaster]
    ADD [GroupTitle] NVARCHAR (200) NULL;


GO
PRINT N'Starting rebuilding table [sHrm].[tEmployeeAttendance]...';


GO
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;

SET XACT_ABORT ON;

BEGIN TRANSACTION;

CREATE TABLE [sHrm].[tmp_ms_xx_tEmployeeAttendance] (
    [EmployeeId]       BIGINT          NOT NULL,
    [ForMonth]         TINYINT         NOT NULL,
    [ForYear]          SMALLINT        NOT NULL,
    [TotalWorkingDays] TINYINT         NOT NULL,
    [LWP]              DECIMAL (12, 2) NOT NULL,
    [PaidLeave]        DECIMAL (12, 2) NULL,
    [BatchId]          INT             NOT NULL
);

IF EXISTS (SELECT TOP 1 1
           FROM   [sHrm].[tEmployeeAttendance])
    BEGIN
        INSERT INTO [sHrm].[tmp_ms_xx_tEmployeeAttendance] ([EmployeeId], [ForMonth], [ForYear], [TotalWorkingDays], [LWP], [BatchId])
        SELECT [EmployeeId],
               [ForMonth],
               [ForYear],
               [TotalWorkingDays],
               [LWP],
               [BatchId]
        FROM   [sHrm].[tEmployeeAttendance];
    END

DROP TABLE [sHrm].[tEmployeeAttendance];

EXECUTE sp_rename N'[sHrm].[tmp_ms_xx_tEmployeeAttendance]', N'tEmployeeAttendance';

COMMIT TRANSACTION;

SET TRANSACTION ISOLATION LEVEL READ COMMITTED;


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


GO
ALTER TABLE [sHrm].[tEmployeeStatutoryAndOther]
    ADD [Payscale] NVARCHAR (150) NULL;


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


GO
ALTER TABLE [sPayroll].[tPayProcessEmployee]
    ADD [PaidLeave] DECIMAL (12, 2) NULL;


GO
PRINT N'Altering [sProcurement].[tStockIssue]...';


GO
ALTER TABLE [sProcurement].[tStockIssue]
    ADD [IssueToSourceTypeId] INT    NULL,
        [IssueToSourceId]     BIGINT NULL;


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


GO
ALTER TABLE [sSetup].[tOrganizationMaster]
    ADD [DegreeAwarded] NVARCHAR (100) NULL,
        [ShortCode]     NVARCHAR (20)  NULL,
        [NoOfTerm]      TINYINT        NULL;


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


GO
ALTER TABLE [sStudent].[tAcademic]
    ADD [BatchStatusId]   SMALLINT NULL,
        [ExemptionTypeId] INT      NULL;


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


GO
ALTER TABLE [sStudent].[tAcademicDetail]
    ADD [PercentageAttendance] DECIMAL (5, 2) NULL,
        [RepeatCount]          TINYINT        NULL;


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


GO
ALTER TABLE [sStudent].[tStudentCustomSearch]
    ADD [RepeatCount]     SMALLINT NULL,
        [StudentStatusId] SMALLINT NULL;


GO
PRINT N'Altering [sTally].[tFeeLedgerMapping]...';


GO
ALTER TABLE [sTally].[tFeeLedgerMapping]
    ADD [LedgerGroup] NVARCHAR (300) NULL;


GO
PRINT N'Altering [sTimetable].[tClassRoom]...';


GO
ALTER TABLE [sTimetable].[tClassRoom]
    ADD [MaxNoOfBatch] TINYINT NULL;


GO
PRINT N'Creating [sOp].[tFunctionalityMaster]...';


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


GO
PRINT N'Creating PK_tFunctionalityMaster...';


GO
ALTER TABLE [sOp].[tFunctionalityMaster]
    ADD CONSTRAINT [PK_tFunctionalityMaster] 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 [sOp].[tPayTypeMaster]...';


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


GO
PRINT N'Creating PK_tPayTypeMaster...';


GO
ALTER TABLE [sOp].[tPayTypeMaster]
    ADD CONSTRAINT [PK_tPayTypeMaster] 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 [sOp].[tTransactionStatusMaster]...';


GO
CREATE TABLE [sOp].[tTransactionStatusMaster] (
    [Id]        INT            NOT NULL,
    [Code]      NVARCHAR (20)  NOT NULL,
    [Title]     NVARCHAR (100) NOT NULL,
    [ColorCode] NVARCHAR (20)  NOT NULL
);


GO
PRINT N'Creating PK_tTransactionStatusMaster...';


GO
ALTER TABLE [sOp].[tTransactionStatusMaster]
    ADD CONSTRAINT [PK_tTransactionStatusMaster] 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 [sOp].[tPaymentTransaction]...';


GO
CREATE TABLE [sOp].[tPaymentTransaction] (
    [Id]                      BIGINT          NOT NULL,
    [TransactionSourceTypeId] SMALLINT        NOT NULL,
    [TransactionSourceId]     BIGINT          NOT NULL,
    [PayerSourceTypeId]       SMALLINT        NOT NULL,
    [PayerSourceId]           BIGINT          NOT NULL,
    [PayDateTime]             DATETIME        NOT NULL,
    [PayAmount]               DECIMAL (12, 2) NOT NULL,
    [TransactionStatusId]     INT             NOT NULL,
    [FunctionalityId]         SMALLINT        NOT NULL,
    [MerchantTransactionId]   BIGINT          NULL,
    [BankTransactionId]       BIGINT          NULL,
    [BankName]                NVARCHAR (100)  NULL,
    [PaymentType]             NVARCHAR (50)   NULL,
    [CardNumber]              NVARCHAR (100)  NULL,
    [TransactionResponse]     NVARCHAR (1000) NULL
);


GO
PRINT N'Creating [sOp].[tPaymentGatewayMaster]...';


GO
CREATE TABLE [sOp].[tPaymentGatewayMaster] (
    [Id]    SMALLINT       NOT NULL,
    [Code]  NVARCHAR (50)  NOT NULL,
    [Title] NVARCHAR (150) NOT NULL
);


GO
PRINT N'Creating PK_tPaymentGatewayMaster...';


GO
ALTER TABLE [sOp].[tPaymentGatewayMaster]
    ADD CONSTRAINT [PK_tPaymentGatewayMaster] 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 [sOp].[tGatewayConfiguration]...';


GO
CREATE TABLE [sOp].[tGatewayConfiguration] (
    [OrgGroupId]       SMALLINT        NOT NULL,
    [PaymentGatewayId] SMALLINT        NULL,
    [GatewayURL]       NVARCHAR (1000) NULL,
    [ServerPort]       NVARCHAR (50)   NULL,
    [LoginId]          NVARCHAR (50)   NULL,
    [LoginPassword]    NVARCHAR (50)   NULL,
    [ProductId]        NVARCHAR (100)  NULL
);


GO
PRINT N'Creating PK_tGatewayConfiguration...';


GO
ALTER TABLE [sOp].[tGatewayConfiguration]
    ADD CONSTRAINT [PK_tGatewayConfiguration] PRIMARY KEY CLUSTERED ([OrgGroupId] ASC) WITH (ALLOW_PAGE_LOCKS = ON, ALLOW_ROW_LOCKS = ON, PAD_INDEX = OFF, IGNORE_DUP_KEY = OFF, STATISTICS_NORECOMPUTE = OFF);


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


GO
CREATE TABLE [sCommon].[tReportOrgGroup] (
    [ReportId]        SMALLINT        NOT NULL,
    [OrgGroupId]      SMALLINT        NOT NULL,
    [SelectableField] NVARCHAR (2000) NULL
);


GO
PRINT N'Creating [sFee].[tExemptionTypeMaster]...';


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


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


GO
CREATE TABLE [sFee].[tFeeInvoice] (
    [Id]              BIGINT          NOT NULL,
    [SourceTypeId]    SMALLINT        NULL,
    [SourceId]        BIGINT          NULL,
    [InvoiceNumber]   INT             NOT NULL,
    [InvoiceDate]     DATE            NOT NULL,
    [InvoiceAmount]   DECIMAL (12, 2) NULL,
    [BatchId]         INT             NULL,
    [OrgGroupBatchId] INT             NULL,
    [CreatedUserId]   BIGINT          NOT NULL,
    [CreatedDateTime] DATETIME        NOT NULL
);


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


GO
CREATE TABLE [sFee].[tFeeInvoiceDetail] (
    [FeeInvoiceId] BIGINT          NOT NULL,
    [FeeSetupId]   INT             NOT NULL,
    [Amount]       DECIMAL (12, 2) NOT NULL
);


GO
PRINT N'Creating [sFee].[tOnlineFee]...';


GO
CREATE TABLE [sFee].[tOnlineFee] (
    [Id]            BIGINT          NOT NULL,
    [SourceTypeId]  SMALLINT        NOT NULL,
    [SourceId]      BIGINT          NOT NULL,
    [PayDateTime]   DATETIME        NOT NULL,
    [FeeAmount]     DECIMAL (12, 2) NOT NULL,
    [PenaltyAmount] DECIMAL (12, 2) NOT NULL,
    [NetAmount]     DECIMAL (12, 2) NOT NULL,
    [ReceiptBookId] INT             NULL
);


GO
PRINT N'Creating [sFee].[tOnlineFeeDetail]...';


GO
CREATE TABLE [sFee].[tOnlineFeeDetail] (
    [OnlineFeeId] BIGINT          NULL,
    [FeeSetupId]  INT             NOT NULL,
    [Amount]      DECIMAL (12, 2) NOT NULL
);


GO
PRINT N'Creating [sHrm].[tCertificateEmployment]...';


GO
CREATE TABLE [sHrm].[tCertificateEmployment] (
    [Id]              BIGINT         NOT NULL,
    [EmployeeId]      BIGINT         NOT NULL,
    [Number]          INT            NOT NULL,
    [IssueDate]       DATE           NOT NULL,
    [OrgId]           SMALLINT       NOT NULL,
    [CreatedUserId]   BIGINT         NOT NULL,
    [CreatedDateTime] DATETIME       NOT NULL,
    [UpdatedUserId]   BIGINT         NULL,
    [UpdatedDateTime] DATETIME       NULL,
    [RequestRemark]   NVARCHAR (200) NULL,
    [EmployeeRemark]  NVARCHAR (200) NULL
);


GO
PRINT N'Creating [sPayroll].[tForm16B]...';


GO
CREATE TABLE [sPayroll].[tForm16B] (
    [Id]          INT            NOT NULL,
    [OrderNumber] INT            NULL,
    [MainGroup]   NVARCHAR (200) NULL,
    [SubGroup]    NVARCHAR (200) NULL,
    [Title]       NCHAR (10)     NULL,
    [IsEntry]     BIT            NULL
);


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


GO
CREATE TABLE [sSetup].[tOrgImages] (
    [OrgId]               SMALLINT        NOT NULL,
    [CertificateHeaderA4] VARBINARY (MAX) NULL,
    [MarksheetHeaderA4]   VARBINARY (MAX) NULL
);


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


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


GO
PRINT N'Creating PK_tBatchStatusMaster...';


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


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


GO
CREATE TABLE [sStudent].[tStudentadditional] (
    [StudentId]         BIGINT         NOT NULL,
    [BankAccountNumber] NVARCHAR (20)  NULL,
    [BankName]          NVARCHAR (100) NULL,
    [BankBranch]        NVARCHAR (100) NULL,
    [BankIFSCCode]      NVARCHAR (20)  NULL
);


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


GO
CREATE TABLE [sStudent].[tStudentBatchStatus] (
    [AcademicId]      BIGINT         NOT NULL,
    [StatusDate]      DATE           NULL,
    [Remark]          NVARCHAR (200) NULL,
    [BatchStatusId]   SMALLINT       NULL,
    [CreatedUserId]   BIGINT         NOT NULL,
    [CreatedDateTime] DATETIME       NOT NULL,
    [UpdatedUserId]   BIGINT         NULL,
    [UpdatedDateTime] DATETIME       NULL
);


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


GO
CREATE TABLE [sTimetable].[tDivisionClassRoom] (
    [TimeTableSchemaId] INT NOT NULL,
    [DivisionId]        INT NOT NULL,
    [ClassRoomId]       INT NOT NULL
);


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


GO
CREATE TABLE [sTimetable].[tSubjectClassRoom] (
    [TimeTableSchemaId] INT NOT NULL,
    [SubjectId]         INT NOT NULL,
    [ClassRoomId]       INT NOT NULL
);


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


GO
CREATE TABLE [sTimetable].[tTimeTableDetail] (
    [TimetableId]  INT    NOT NULL,
    [EmployeeId]   BIGINT NOT NULL,
    [SubjectId]    INT    NOT NULL,
    [SchoolRoomId] INT    NULL
);


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


GO
ALTER TABLE [sCertificate].[tLeaving]
    ADD [TotalDays]   SMALLINT NULL,
        [PresentDays] SMALLINT NULL;


GO
PRINT N'Creating PK_tAdmissionStatusMaster...';


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


GO
PRINT N'Creating PK_tInquiryModeMaster...';


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


GO
PRINT N'Creating PK_tCCEExamMaster...';


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


GO
PRINT N'Creating PK_tCCERptGroup...';


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


GO
PRINT N'Creating PK_tAttendanceForMaster...';


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


GO
PRINT N'Creating PK_tMainCastCategoryMaster...';


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


GO
PRINT N'Creating PK_tRangeGroupMaster...';


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


GO
PRINT N'Creating PK_tReligionMaster...';


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


GO
PRINT N'Creating PK_tReportTypeMaster...';


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


GO
PRINT N'Creating PK_tConfigurationLevelMaster...';


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


GO
PRINT N'Creating PK_tEntryModeMaster...';


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


GO
PRINT N'Creating PK_tLogStatusMaster...';


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


GO
PRINT N'Creating PK_tEmployeeICardTemplate...';


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


GO
PRINT N'Creating PK_tDashletMaster...';


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


GO
PRINT N'Creating PK_tRole...';


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


GO
PRINT N'Creating PK_tStudentNameFormatMaster...';


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


GO
PRINT N'Creating PK_tTermPatternMaster...';


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


GO
PRINT N'Creating PK_tTermScopeMaster...';


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


GO
PRINT N'Creating PK_tICardTemplate...';


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


GO
PRINT N'Creating PK_tCustomQuery...';


GO
ALTER TABLE [sSystem].[tCustomQuery]
    ADD CONSTRAINT [PK_tCustomQuery] 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 [sSecurity].[tScreenGroupMapping].[IX_tScreenGroupMapping]...';


GO
CREATE UNIQUE NONCLUSTERED INDEX [IX_tScreenGroupMapping]
    ON [sSecurity].[tScreenGroupMapping]([ScreenGroupId] ASC, [ScreenId] ASC) WITH (ALLOW_PAGE_LOCKS = ON, ALLOW_ROW_LOCKS = ON, PAD_INDEX = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, IGNORE_DUP_KEY = OFF, STATISTICS_NORECOMPUTE = OFF, ONLINE = OFF, MAXDOP = 0)
    ON [PRIMARY];


GO


PRINT N'Dropping [sFinanceCommon].[fNumberToWords]...';


GO
DROP FUNCTION [sFinanceCommon].[fNumberToWords];


GO
PRINT N'Dropping [sFinanceCommon].[fNumberToWordsWithDecimal]...';


GO
DROP FUNCTION [sFinanceCommon].[fNumberToWordsWithDecimal];


GO
PRINT N'Dropping [sHrm].[fMonthWiseNoOfLeave]...';


GO
DROP FUNCTION [sHrm].[fMonthWiseNoOfLeave];

GO
PRINT N'Altering [sFinanceCommon].[fCurrencyCodeGet]...';


GO
ALTER FUNCTION [sFinanceCommon].[fCurrencyCodeGet](@rCurrencyType [tinyint])
RETURNS [nvarchar](100) WITH EXECUTE AS CALLER
AS 
BEGIN
		RETURN ('Rs.')
	END
GO
PRINT N'Creating [sFinanceCommon].[fNumberToWords]...';


GO
CREATE FUNCTION [sFinanceCommon].[fNumberToWords](@rNumber [decimal](38, 0), @rCurrencyType [tinyint] = 0,@rOrgGroupId [smallint] = 0)
RETURNS [varchar](8000) WITH EXECUTE AS CALLER
AS 
BEGIN

--SET NOCOUNT ON
--DECLARE @rNumber DECIMAL(38, 0)
--SET @rNumber = 7654321098

DECLARE @lInputNumber VARCHAR(38)
DECLARE @lNumberTable TABLE (cNumber CHAR(2), cWord VARCHAR(10))
DECLARE @lOutputString VARCHAR(8000)
DECLARE @lLength INT
DECLARE @lCounter INT
DECLARE @lCount INT
DECLARE @lPosition INT
DECLARE @lChunk CHAR(3) -- for chunks of 3 numbers
DECLARE @lTensones CHAR(2)
DECLARE @lHundreds CHAR(1)
DECLARE @lTens CHAR(1)
DECLARE @lOnes CHAR(1)

IF @rNumber = 0 RETURN 'Zero'
--IF @rNumber = 0 SELECT 'Zero'

-- initialize the variables
SELECT @lInputNumber = CONVERT(NVARCHAR(38), @rNumber)
     , @lOutputString = ''
     , @lCounter = 1
SELECT @lLength   = LEN(@lInputNumber)
     , @lPosition = LEN(@lInputNumber) - 2
     , @lCount    = LEN(@lInputNumber) / 3

-- make sure there is an extra loop added for the remaining numbers
IF LEN(@lInputNumber) % 3 <> 0 SET @lCount = @lCount + 1

-- insert data for the numbers and words
INSERT INTO @lNumberTable   SELECT '00', ''
    UNION ALL SELECT '01', 'One'      UNION ALL SELECT '02', 'Two'
    UNION ALL SELECT '03', 'Three'    UNION ALL SELECT '04', 'Four'
    UNION ALL SELECT '05', 'Five'     UNION ALL SELECT '06', 'Six'
    UNION ALL SELECT '07', 'Seven'    UNION ALL SELECT '08', 'Eight'
    UNION ALL SELECT '09', 'Nine'     UNION ALL SELECT '10', 'Ten'
    UNION ALL SELECT '11', 'Eleven'   UNION ALL SELECT '12', 'Twelve'
    UNION ALL SELECT '13', 'Thirteen' UNION ALL SELECT '14', 'Fourteen'
    UNION ALL SELECT '15', 'Fifteen'  UNION ALL SELECT '16', 'Sixteen'
    UNION ALL SELECT '17', 'Seventeen' UNION ALL SELECT '18', 'Eighteen'
    UNION ALL SELECT '19', 'Nineteen' UNION ALL SELECT '20', 'Twenty'
    UNION ALL SELECT '30', 'Thirty'   UNION ALL SELECT '40', 'Forty'
    UNION ALL SELECT '50', 'Fifty'    UNION ALL SELECT '60', 'Sixty'
    UNION ALL SELECT '70', 'Seventy'  UNION ALL SELECT '80', 'Eighty'
    UNION ALL SELECT '90', 'Ninety'   

WHILE @lCounter <= @lCount BEGIN

	-- get chunks of 3 numbers at a time, padded with leading zeros
	SET @lChunk = RIGHT('000' + SUBSTRING(@lInputNumber, @lPosition, 3), 3)
 
	--SELECT @lInputNumber, @lPosition, @lChunk
 
	IF @lChunk <> '000' BEGIN
		SELECT @lTensones = SUBSTRING(@lChunk, 2, 2)
		     , @lHundreds = SUBSTRING(@lChunk, 1, 1)
		     , @lTens = SUBSTRING(@lChunk, 2, 1)
		     , @lOnes = SUBSTRING(@lChunk, 3, 1)

		-- If twenty or less, use the word directly from @lNumberTable
		IF CONVERT(INT, @lTensones) <= 20 OR @lOnes = '0' BEGIN
			SET @lOutputString = (SELECT cWord 
                                      FROM @lNumberTable 
                                      WHERE @lTensones = cNumber)
                   + CASE @lCounter WHEN 1 THEN '' -- No name
                       WHEN 2 THEN ' Thousand ' WHEN 3 THEN ' Million '
                       WHEN 4 THEN ' Billion '  WHEN 5 THEN ' Trillion '
                       WHEN 6 THEN ' Quadrillion ' WHEN 7 THEN ' Quintillion '
                       WHEN 8 THEN ' Sextillion '  WHEN 9 THEN ' Septillion '
                       WHEN 10 THEN ' Octillion '  WHEN 11 THEN ' Nonillion '
                       WHEN 12 THEN ' Decillion '  WHEN 13 THEN ' Undecillion '
                       ELSE '' END
                               + @lOutputString
		    END
		 ELSE BEGIN -- break down the ones and the tens separately

             SET @lOutputString = ' ' 
                            + (SELECT cWord 
                                    FROM @lNumberTable 
                                    WHERE @lTens + '0' = cNumber)
					         + '-'
                             + (SELECT cWord 
                                    FROM @lNumberTable 
                                    WHERE '0'+ @lOnes = cNumber)
                   + CASE @lCounter WHEN 1 THEN '' -- No name
                       WHEN 2 THEN ' Thousand ' WHEN 3 THEN ' Million '
                       WHEN 4 THEN ' Billion '  WHEN 5 THEN ' Trillion '
                       WHEN 6 THEN ' Quadrillion ' WHEN 7 THEN ' Quintillion '
                       WHEN 8 THEN ' Sextillion '  WHEN 9 THEN ' Septillion '
                       WHEN 10 THEN ' Octillion '  WHEN 11 THEN ' Nonillion '
                       WHEN 12 THEN ' Decillion '   WHEN 13 THEN ' Undecillion '
                       ELSE '' END
                            + @lOutputString
		END

		-- now get the hundreds
		IF @lHundreds <> '0' BEGIN
			SET @lOutputString  = (SELECT cWord 
                                      FROM @lNumberTable 
                                      WHERE '0' + @lHundreds = cNumber)
					            + ' Hundred ' 
                                + @lOutputString
		END
	END

	SELECT @lCounter = @lCounter + 1
	     , @lPosition = @lPosition - 3

END

-- Remove any double spaces
SET @lOutputString = LTRIM(RTRIM(REPLACE(@lOutputString, '  ', ' ')))
SET @lOutputString = UPPER(LEFT(@lOutputString, 1)) + SUBSTRING(@lOutputString, 2, 8000)

IF @rCurrencyType <> 0
	BEGIN
		SET @lOutputString = sFinanceCommon.fDefaultCurrencyTitleGet(@rOrgGroupId) + ' ' + @lOutputString -- return the result
	END
	
	RETURN @lOutputString
--SELECT @lOutputString -- return the result
END

--select dbo.udf_NumberToWords (1234567890) + CHAR(10)
GO
PRINT N'Creating [sFinanceCommon].[fNumberToWordsWithDecimal]...';


GO
CREATE FUNCTION [sFinanceCommon].[fNumberToWordsWithDecimal](@rAmount [decimal](38, 8), @rCurrencyType [tinyint] = 0, @rScale [tinyint] = 2,@rOrgGroupId [smallint] = 0)
RETURNS [nvarchar](4000) WITH EXECUTE AS CALLER
AS 
/*
DECLARE @rAmount DECIMAL(38, 8)
DECLARE @rCurrencyType dTinyInt --// 0 = Without Currency Type, 1 = Accounting, 2 = Foreign, 3 = Reporting
DECLARE @rScale  TINYINT

SET @rAmount = 0
SET @rCurrencyType = 0
SET @rScale = 0
*/		
BEGIN
	DECLARE @lIntPart		 NVARCHAR(1000)
	DECLARE @lDecimalPart		 NVARCHAR(100)
	DECLARE @lAmountChar  NVARCHAR(38)
	DECLARE @lDecimalPartAmount SMALLINT
	DECLARE @lWords NVARCHAR(4000)

	SET @lAmountChar = @rAmount
	SELECT @lWords = + '' + sFinanceCommon.fNumberToWords(FLOOR(@rAmount), @rCurrencyType,@rOrgGroupId) 
	
	IF CHARINDEX('.', @lAmountChar) > 0
		BEGIN
			SET @lDecimalPartAmount = SUBSTRING(SUBSTRING(@lAmountChar, CHARINDEX('.', @lAmountChar) + 1, LEN(@lAmountChar)), 1, @rScale)
			IF @lDecimalPartAmount > 0 
				BEGIN
						SET @lWords = @lWords
								    + ' and'
						
						IF @rCurrencyType <> 0
						BEGIN
							SET @lWords = @lWords + ' ' + sFinanceCommon.fDefaultCurrencyTitleGet(@rOrgGroupId)
						END		   
						
						SET @lWords = @lWords
								    + ' ' + sFinanceCommon.fNumberToWords(@lDecimalPartAmount, @rCurrencyType,@rOrgGroupId)
				END

		END
					 
	--SELECT @lWords, CHARINDEX('.', @lAmountChar), @lAmountChar
	RETURN @lWords 
END
GO
PRINT N'Creating [sHrm].[fMonthWiseNoOfLeave]...';


GO


CREATE FUNCTION [sHrm].[fMonthWiseNoOfLeave](@rType bit, @rFromDate Date,@rTodate Date,@rForMonth int,@rForYear int, @rLeavePeriodId int,@rLaveTypeId int)
RETURNS  DECIMAL(12,2)       

  WITH EXECUTE AS CALLER
AS 
BEGIN    
         DECLARE @rTempFromDate date
		 DECLARE @rDays  DECIMAL(12,2)
         DECLARE @rIsLWP bit
         
         SELECT @rIsLWP = IsLWP from sHrm.tLeaveTypeMaster Where Id = @rLaveTypeId
         
         IF(@rIsLWP = @rType)
		 BEGIN
		 SET @rTempFromDate = @rFromDate
		 
		 IF(DATEPART(MONTH,@rFromDate) = DATEPART(MONTH,@rTodate)) 
		   SET @rTempFromDate = @rFromDate
		  ELSE IF(DATEPART(MONTH,@rFromDate) = @rForMonth)
		    SET @rTempFromDate = @rFromDate
		  ELSE IF(DATEPART(MONTH,@rToDate) = @rForMonth) 
		   BEGIN
		     SELECT @rTempFromDate = CONVERT(VARCHAR(25),DATEADD(dd,-(DAY(@rToDate)-1),@rToDate),101) 
		   END
		 
		;WITH c(d) AS
		(
		    SELECT TOP (DATEDIFF(DAY, @rTempFromDate, @rTodate)+1)
			DATEADD(DAY, ROW_NUMBER() OVER (ORDER BY name)-1, @rTempFromDate)
			FROM sys.all_columns
			WHERE DATEPART(MONTH,@rTempFromDate)=@rForMonth 
		) 
		 SELECT    
		 @rDays = COUNT(*)
		 FROM c WHERE DATEPART(MONTH,(DATEADD(MONTH, DATEDIFF(MONTH, 0, d), 0))) = @rForMonth
		 AND DATEPART(YEAR,(DATEADD(MONTH, DATEDIFF(MONTH, 0, d), 0))) = @rForYear
		
		 GROUP BY DATEDIFF(MONTH, 0, d)	 
	--	tMonth_Year 
    
    IF(@rLeavePeriodId = 2)
       SET  @rDays = (@rDays /2)
    END
 
    ELSE
      BEGIN
      SET @rDays = 0
      END
    
    RETURN  @rDays
    
END
GO
PRINT N'Creating [sFinanceCommon].[fCurrencyTitleGet]...';


GO
CREATE FUNCTION [sFinanceCommon].[fCurrencyTitleGet](@rCurrencyType [tinyint])
RETURNS [nvarchar](100) WITH EXECUTE AS CALLER
AS 
BEGIN
		RETURN ('Rupees')
	END
GO
PRINT N'Creating [sFinanceCommon].[fDefaultCurrencyCodeGet]...';


GO
CREATE FUNCTION [sFinanceCommon].[fDefaultCurrencyCodeGet](@rOrgGroupId int)
RETURNS [nvarchar](100) WITH EXECUTE AS CALLER
AS 
BEGIN
DECLARE @lCurrencyCode VARCHAR(100)
SELECT  
@lCurrencyCode = (CASE WHEN CS.Id IS NULL
  THEN CM.ItemValue  
 ELSE CS.ItemValue END)
 FROM 
sConfig.tConfigurationMaster CM LEFT JOIN sConfig.tConfigurationSetup CS 
ON CM.Id = CS.ConfigurationId AND CS.SourceTypeId = 5 AND CS.SourceId = @rOrgGroupId
WHERE CM.Id = 154

IF (@lCurrencyCode IS NULL)
SET @lCurrencyCode = 'Rs.'

		RETURN (@lCurrencyCode)
	END
GO
PRINT N'Creating [sFinanceCommon].[fDefaultCurrencyMinorCodeGet]...';


GO

CREATE FUNCTION [sFinanceCommon].[fDefaultCurrencyMinorCodeGet](@rOrgGroupId int)
RETURNS [nvarchar](100) WITH EXECUTE AS CALLER
AS 
BEGIN
DECLARE @lCurrencyCode VARCHAR(100)
SELECT  
@lCurrencyCode = (CASE WHEN CS.Id IS NULL
 THEN CM.ItemValue  
 ELSE CS.ItemValue END)
 FROM 
sConfig.tConfigurationMaster CM LEFT JOIN sConfig.tConfigurationSetup CS 
ON CM.Id = CS.ConfigurationId AND CS.SourceTypeId = 5 AND CS.SourceId = @rOrgGroupId
WHERE CM.Id = 156
IF (@lCurrencyCode IS NULL)
SET @lCurrencyCode = 'Paisa'
		RETURN (@lCurrencyCode)
	END
GO
PRINT N'Creating [sFinanceCommon].[fDefaultCurrencyMinorTitleGet]...';


GO
CREATE FUNCTION [sFinanceCommon].[fDefaultCurrencyMinorTitleGet](@rOrgGroupId int)
RETURNS [nvarchar](100) WITH EXECUTE AS CALLER
AS 
BEGIN
DECLARE @lCurrencyCode VARCHAR(100)
SELECT  
@lCurrencyCode = (CASE WHEN CS.Id IS NULL
  THEN CM.ItemValue  
 ELSE CS.ItemValue END)
 FROM 
sConfig.tConfigurationMaster CM LEFT JOIN sConfig.tConfigurationSetup CS 
ON CM.Id = CS.ConfigurationId AND CS.SourceTypeId = 5 AND CS.SourceId = @rOrgGroupId
WHERE CM.Id = 155
IF (@lCurrencyCode IS NULL)
SET @lCurrencyCode = 'Paisa'
		RETURN (@lCurrencyCode)
	END
GO
PRINT N'Creating [sFinanceCommon].[fDefaultCurrencyTitleGet]...';


GO
CREATE FUNCTION [sFinanceCommon].[fDefaultCurrencyTitleGet](@rOrgGroupId int)
RETURNS [nvarchar](100) WITH EXECUTE AS CALLER
AS 
BEGIN
DECLARE @lCurrencyCode VARCHAR(100)
SELECT  
@lCurrencyCode = (CASE WHEN CS.Id IS NULL
  THEN CM.ItemValue  
 ELSE CS.ItemValue END)
 FROM 
sConfig.tConfigurationMaster CM LEFT JOIN sConfig.tConfigurationSetup CS 
ON CM.Id = CS.ConfigurationId AND CS.SourceTypeId = 5 AND CS.SourceId = @rOrgGroupId
WHERE CM.Id = 153
IF (@lCurrencyCode IS NULL)
SET @lCurrencyCode = 'Rupees'
		RETURN (@lCurrencyCode)
	END
GO
PRINT N'Altering [sHrm].[vTeacherWorkload]...';


GO




/******************************************************************************
	Purpose          : External view to get data from sHrm.tEmployeeMaster table
	Created date     : 03 Sep 2010
	Author           : Rajendra Patel
	Copyright©       : Copyright © Sapphire Software
	
	Last Change Desc : Added for jobtitle
*******************************************************************************/

ALTER VIEW [sHrm].[vTeacherWorkload]

AS
	 SELECT EM.Id,
	        EM.Id AS EmployeeId,
	        EM.Code,
			--ISNULL(EM.FirstName, '') + ' ' + ISNULL(EM.MiddleName, '') + ' ' + ISNULL(EM.LastName, '') EmployeeName,	 
	        ISNULL(EM.FirstName, '') + ' ' + ISNULL(EM.LastName, '') EmployeeName,
	       	EM.FirstName,
			EM.MiddleName,
			EM.LastName,	
			ISNULL(EM.ShortName,'') AS 	ShortName,	
			EM.OrgID,
			EPD.GenderId,
			EPD.DateOfBirth,
			EJD.DateOfJoining,
			EJD.DateOfleaving,
			EJD.ReasonOfleaving,
			EJD.JobRemark,
			EM.StatusId,
			EM.CreatedUserId,
			EM.CreatedDateTime,
			EM.UpdatedUserId,
			EM.UpdatedDateTime,
			EM.IsObsolete,
			ISNULL(EC.PhoneNoCompany,'') AS PhoneNoCompany,
			ISNULL(EC.CompanyEmail,'') AS CompanyEmail,
			ISNULL(EC.ExtensionNo,'') AS ExtensionNo,
			vEU.Id AS UserId,  
			ISNULL(ODM.Id,0) AS DepartmentId,  
			ISNULL(ODM.Title,'') AS DepartmentCode,  
			ISNULL(ODM.Title,'') AS DepartmentName,
		    ISNULL(EC.MobileNumber,'') AS MobileNumber,
			EJD.EmployeeTypeId,
			ISNULL(ETM.Title,'') AS EmployeeType,
			ISNULL(EDM.Id,0) AS DesignationId,
			ISNULL(EDM.Title,'') AS Designation,
			95 AS ParticipantSourceTypeId,
			DATEDIFF(yy,DateOfBirth,GETDATE()) AS Age,
			ISNULL(EGM.Title,'') AS EmployeeGroup,
			ISNULL(EGM.Id,0) AS EmployeeGroupId,
			0 AS GradeNumber,
		    ISNULL(EJD.EmployeeGradeId,0) AS EmployeeGradeId,
		    EGM.Title AS EmployeeGrade,
		    EI.EmployeePhoto,
		    ISNULL(EPD.Qualification,'') AS Qualification,
		  AT.TimeTableSchemaId
	 
	   FROM 
		   sHrm.tEmployeeMaster EM
	   INNER JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id = EJD.EmployeeId 
	   INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EM.Id = EPD.EmployeeId	 		     
	   LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id = EJD.EmployeeDesignationId	
	   LEFT JOIN sHrm.tEmployeeTypeMaster ETM ON ETM.Id = EJD.EmployeeTypeId	
	   LEFT JOIN sHrm.tEmployeeCommunications EC ON EM.Id = EC.EmployeeId 
	   LEFT JOIN sHrm.tEmployeeGroupMaster EGM ON EGM.Id=EJD.EmployeeGroupId 	  
	   LEFT JOIN sSecurity.tUser vEU ON EM.Id = vEU.SourceId AND vEU.SourceTypeId=95
	   LEFT JOIN sSetup.tDepartmentMaster ODM ON EJD.OrganizationDepartmentId = ODM.Id 
	   LEFT JOIN sHrm.tEmployeeImages EI ON EM.Id=EI.EmployeeId
	  INNER JOIN sTimetable.tAssignTeacher AT ON AT.EmployeeId=Em.Id
GO
PRINT N'Altering [sSetup].[vBatchClassDivisionWorkload]...';


GO











/******************************************************************************  
 Purpose          : To get Batch Wise  Class
 Created date     : 21 Nov 2013
 Author           : Kundan Patel 
 Copyright©       : Copyright © Sapphire Software Solutions
 ******************************************************************************/  
ALTER VIEW [sSetup].[vBatchClassDivisionWorkload]  

  

AS  
  
SELECT 	

	  DM.Id as DivisionId,
	  ISNULL(CM.Id,0) AS ClassId,
	  --BC.BatchId as BatchId,
	  CM.DisplayTitle AS ClassName,
	  DM.Title AS DivisionName,
	  ISNULL(CM.DisplayTitle,'')+'-'+ISNULL(DM.Title,'') as ClassDivisionName,
	  CM.IsObsolete,
	  CM.OrderIndex,
	  Dm.OrgId ,
	  AO.TimeTableSchemaId, 
	  CASE WHEN AO.OrgId IS NULL THEN 'False' ELSE 'True' END AS CheckOrg
  FROM 
	sSetup.tDivisionMaster DM
	INNER JOIN sSetup.tClassMaster CM ON CM.Id=DM.ClassId
	--INNER JOIN sSetup.tBatchClass BC ON CM.Id=BC.ClassId
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = Dm.OrgId
	INNER JOIN sTimetable.tAssignOrg AO ON AO.OrgId=OM.Id
GO
PRINT N'Altering [sStudent].[vStudentAcademic]...';


GO


 
ALTER VIEW [sStudent].[vStudentAcademic]  
  
AS  
 
SELECT 
	  A.Id AS AcademicId,	  
	  A.ClassId,
	  A.DivisionId,
	  A.RollNo,
	  A.OrgId,
	  A.BatchId,
	  SM.Id AS StudentId,
	  SM.Code,
	  ISNULL(SM.Number,0) AS Number,
	  SM.RegistrationNumber,
	  SM.FirstName,
	  SM.MiddleName,
	  SM.LastName,
	   [sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Name,
	  Convert(Nvarchar(20),A.RollNo) + '-' + SM.FirstName+' '+SM.LastName AS RollNoName,	  
	  SM.StatusId,
	  CM.DisplayTitle AS ClassName,
	  DM.DisplayTitle AS DivisionName,
	  STM.Title AS StatusName,	  
	  SM.RecordStatusId,	  
	  DM.InchargeEmployeeId, 
	  BM.OrgGroupBatchId,	  
	  SM.AdmissionCategoryId,
	  DM.OrderIndex DivisionOrder,
	  BM.IsActive AS IsActiveBatch,
	  BM.Title AS BatchName,
	  ISNULL(DeptM.Id,0) AS DepartmentId,
	  ISNULL(DeptM.Title,'') AS DepartmentName,
	  SM.IsBlackList,
	  SM.BlackListReason,
	  CM.OrderIndex AS ClassOrderIndex,
	  ISNULL(A.ExemptionTypeId,0) AS ExemptionTypeId
  FROM 
	sStudent.tAcademic A
	INNER JOIN sStudent.tStudentMaster SM
		ON A.StudentId=SM.Id	
	INNER JOIN sSetup.tClassMaster CM
		ON CM.Id=A.ClassId
	INNER JOIN sSetup.tDivisionMaster DM
		ON DM.Id=A.DivisionId
	INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId 
	INNER JOIN sStudent.tStatusMaster STM
		ON STM.Id=SM.StatusId
	INNER JOIN sSetup.tDepartmentMaster DeptM
		ON DeptM.Id=CM.DepartmentId
	INNER JOIN sSetup.tOrganizationMaster OM
	    ON SM.OrgId = OM.Id
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.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,
	  BSM.Title AS StudentBatchStatus,
	  SBS.BatchStatusId AS StudentStatusId
	  
	  	  	   
  FROM sStudent.vStudentAcademic SA
	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.tNationalityMaster 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.tStudentBatchStatus SBS ON SBS.AcademicId = SA.AcademicId
	LEFT JOIN sStudent.tBatchStatusMaster BSM ON BSM.Id = SBS.BatchStatusId
GO
PRINT N'Altering [sStudent].[vStudentColumnName]...';


GO




/******************************************************************************  
 Purpose          : To get Batch Wise  Class
 Created date     : 21 Nov 2013
 Author           : Kundan Patel 
 Copyright©       : Copyright © Sapphire Software Solutions
 ******************************************************************************/  
ALTER VIEW [sStudent].[vStudentColumnName]  
  
AS  
  
SELECT 	
	  --SA.AcademicId,	  
	  --SA.ClassId,
	  --SA.DivisionId,
	  SA.RollNo,
	  --SA.OrgId,
	  --SA.BatchId,
	  BM.Title AS Batch,
	  --SA.StudentId,
	  SA.Code AS [ID No],
	  SA.Number,
	  SA.FirstName,
	  SA.MiddleName,
	  SA.LastName,
	  SA.Name,
	  --SA.DepartmentId,
	  --SA.StatusId,
	  SA.ClassName,
	  SA.DivisionName,
	  SA.StatusName,
	  SO.UIDNumber,
	  SO.AdhaarNumber,
      SO.DateOfBirth,
      SO.BirthdateInWord,
      --SO.TransportModeId,
      TM.Title AS TransportMode,
      --SO.GenderId,
      GM.Title AS Gender,
      --SO.BloodGroupId,
      BGM.Title AS BloodGroup,
      SO.BirthPlace,
      SO.BirthTaluka,
      SO.BirthDistrict,
      SO.FamilyCast As FamilyCaste,
      --SO.FamilySubCast,
      --SO.CastCategoryId,
      
      CCM.Title AS CasteCategory,
      --SO.ReligionId,
      RM.Title AS Religion,
      --SO.HouseId,
      HM.Title AS House,
      --SO.MotherTongueId,
      MTM.Title AS MotherTongue,
      --SO.NationalityId,
      NM.Title AS Nationality,
      SO.Hobby,
      SH.IdentificationMark1,
      SH.IdentificationMark2,
      SH.IsPysicalDeformity,
      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,      
	  AC.Title AS AdmissionCategory,
	  SAD.PreviousSchool,
	  SAD.AdmissionDate,
	  SAD.AdmissionFormNumber,
	  SAD.AdmissionNumber,
	  SAD.IsTransfer,
	  SAD.TransferFrom,
	  SAD.PassingYear,
	  SAD.IsTFWS,
	  SAD.IsCertificateHolder,
	  SAD.CertificateName,
	  AQM.Title AS AdmissionQuota,
	  SAD.LeftDate,
	  SA.BlackListReason,
	  SA.DivisionOrder,
	  SA.ClassOrderIndex,
	  AD.BankAccountNumber,
	  AD.BankName,
	  AD.BankBranch,
	  AD.BankIFSCCode,
	  BSM.Title AS StudentBatchStatus
	  
	  
  FROM sStudent.vStudentAcademic SA
	INNER JOIN sStudent.tStudentAdmission SAD ON SAD.StudentId=SA.StudentId
	INNER JOIN sCommon.tAdmissionQuotaMaster AQM ON AQM.Id = SAD.AdmissionQuotaId
	INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA.BatchId
	INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=SA.StudentId
	INNER JOIN sStudent.tStudentCommunication SC ON SC.StudentId=SA.StudentId
	INNER JOIN sTransport.tAssignRoute AR ON AR.SourceId=SA.StudentId
	INNER JOIN sCommon.tTransportModeMaster TM ON TM.Id=SO.TransportModeId
	INNER JOIN sCommon.tGenderMaster GM ON GM.Id=SO.GenderId
	INNER JOIN sCommon.tBloodGroupMaster BGM ON BGM.Id=SO.BloodGroupId
	INNER JOIN sCommon.tCastCategoryMaster CCM ON CCM.Id=SO.CastCategoryId
	INNER JOIN sCommon.tReligionMaster RM ON RM.Id=SO.ReligionId
	INNER JOIN sActivity.tHouseMaster HM ON HM.Id=SO.HouseId
	INNER JOIN sCommon.tMotherTongueMaster MTM ON MTM.Id=SO.MotherTongueId
	INNER JOIN sCommon.tNationalityMaster NM ON NM.Id=SO.NationalityId
	INNER JOIN sTransport.tBusRouteDestinationMaster BDM ON BDM.Id=AR.PickupDestinationId
	INNER JOIN sStudent.tStudentFamily SF ON SF.StudentId=SA.StudentId
	INNER JOIN sStudent.tStudentHealth SH ON SH.StudentId=SA.StudentId
	INNER JOIN sStudent.tAdmissionCategoryMaster AC ON AC.Id=SA.AdmissionCategoryId
	INNER JOIN sStudent.tStudentadditional AD ON AD.StudentId= SA.StudentId
	INNER JOIN sStudent.tStudentBatchStatus SBS ON SBS.AcademicId = SA.AcademicId
	INNER JOIN sStudent.tBatchStatusMaster BSM ON BSM.Id = SBS.BatchStatusId
GO
PRINT N'Refreshing [sFee].[vFeeColumnName]...';


GO
EXECUTE sp_refreshview N'sFee.vFeeColumnName';


GO
PRINT N'Refreshing [sFee].[vFeeCustomSearch]...';


GO
EXECUTE sp_refreshview N'sFee.vFeeCustomSearch';


GO
PRINT N'Refreshing [sAssessment].[vGeneralExamCustomSearch]...';


GO
EXECUTE sp_refreshview N'sAssessment.vGeneralExamCustomSearch';


GO
PRINT N'Refreshing [sAssessment].[vGeneralExamColumnName]...';


GO
EXECUTE sp_refreshview N'sAssessment.vGeneralExamColumnName';


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


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].[vStudentCommunication]  
  
AS  
  
SELECT 
	  A.Id AS AcademicId,	  
	  A.ClassId,
	  A.DivisionId,
	  A.RollNo,
	  A.OrgId,
	  A.BatchId,
	  SM.Id AS StudentId,
	  SM.Code,
	  SM.Number,
	  SM.FirstName,
	  SM.LastName,
	  [sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Name,
	  CM.DepartmentId,
	  SM.StatusId,
	  CM.DisplayTitle AS ClassName,
	  DM.DisplayTitle AS DivisionName,
	  STM.Title AS StatusName,
	  ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
	  ISNULL(SC.ParentEmail,'') AS ParentEmail,
	  ISNULL(SC.StudentContactNo,'') AS StudentContactNo,
	  ISNULL(SC.StudentEmail,'') AS StudentEmail,
	  SO.DateOfBirth,
	  CM.OrderIndex AS ClassOrderIndex,
	  DM.OrderIndex AS DivisionOrderIndex,
	  ISNULL(BM.IsActive,0) AS IsActiveBatch,
	  BM.OrgGroupBatchId,
	  SF.FatherContactNo,
	  SF.FatherMail,
	  SF.MotherContactNo,
	  SF.MotherMail
  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.tStudentFamily SF
		ON SF.StudentId=A.StudentId
	LEFT JOIN sStudent.tStudentOther SO
		ON SO.StudentId=A.StudentId
	INNER JOIN sSetup.tOrganizationMaster OM
	    ON SM.OrgId = OM.Id	
	INNER JOIN sSetup.tBatchMaster BM 
		ON BM.Id = A.BatchId
GO
PRINT N'Creating [sTimetable].[vAssignOrganization]...';


GO



/******************************************************************************  
 Purpose          : To get Batch Wise  Class
 Created date     : 21 Nov 2013
 Author           : Kundan Patel 
 Copyright©       : Copyright © Sapphire Software Solutions
 ******************************************************************************/  
CREATE VIEW [sTimetable].[vAssignOrganization]  
  
AS  
  
SELECT 
		OM.Id,
		OM.Title,
		AO.TimeTableSchemaId
FROM	sTimetable.tAssignOrg AO 
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id= AO.OrgId
Where IsObsolete = 0
GO
PRINT N'Creating [sTimetable].[vClass]...';


GO



/******************************************************************************  
 Purpose          : To get Batch Wise  Class
 Created date     : 21 Nov 2013
 Author           : Kundan Patel 
 Copyright©       : Copyright © Sapphire Software Solutions
 ******************************************************************************/  
CREATE VIEW [sTimetable].[vClass]  
  
AS  
  
SELECT 
			CM.Id,
			OM.CODE + ' :' + CM.CODE AS CODE,
			AO.TimeTableSchemaId,
			AO.OrgId
			
FROM		sSetup.tClassMaster CM 
			INNER JOIN sTimetable.tAssignOrg AO ON AO.OrgId = CM.OrgId 
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id= AO.OrgId
GO
PRINT N'Creating [sTimetable].[vDivision]...';


GO





/******************************************************************************  
 Purpose          : To get Batch Wise  Class
 Created date     : 21 Nov 2013
 Author           : Kundan Patel 
 Copyright©       : Copyright © Sapphire Software Solutions
 ******************************************************************************/  
CREATE VIEW [sTimetable].[vDivision]  
  
AS  
  
SELECT	DM.Id,
		OM.CODE + ' :' + DM.CODE AS CODE,
		AO.TimeTableSchemaId,
		AO.OrgId,
		DM.InchargeEmployeeId,
		DM.ClassId,
		DM.OrderIndex		 
FROM	sSetup.tDivisionMaster DM 
		INNER JOIN sTimetable.tAssignOrg AO ON AO.OrgId = DM.OrgId 
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id= AO.OrgId
GO
PRINT N'Creating [sTimetable].[vDivisionWorkLoad]...';


GO




/******************************************************************************  
 Purpose          : To get Batch Wise  Class
 Created date     : 21 Nov 2013
 Author           : Kundan Patel 
 Copyright©       : Copyright © Sapphire Software Solutions
 ******************************************************************************/  
CREATE VIEW [sTimetable].[vDivisionWorkLoad]  
  
AS  
  
SELECT DW.*,
	   SM.Title  AS SubjectName,
	   SM.Code AS Subjectcode,
	   SM.OrgId		   
FROM sTimeTable.tDivisionWorkLoad DW
	 INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = DW.SubjectId
GO
PRINT N'Creating [sTimetable].[vSubject]...';


GO


/******************************************************************************  
 Purpose          : Time Table Subjects
 Created date     : 21 Nov 2013
 Author           : Kundan Patel 
 Copyright©       : Copyright © Sapphire Software Solutions
 ******************************************************************************/  
CREATE VIEW [sTimetable].[vSubject]  
  
AS  
  
SELECT 
		SM.Id,
		OM.CODE + ' :' + SM.CODE AS CODE,
		AO.TimeTableSchemaId,
		AO.OrgId,
		CS.ClassId 
FROM	sSetup.tSubjectMaster SM 
		INNER JOIN sSetup.tClassSubject CS ON CS.SubjectId = SM.Id
		INNER JOIN sTimetable.tAssignOrg AO ON AO.OrgId = SM.OrgId 
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id= AO.OrgId
GO
PRINT N'Creating [sTimetable].[vTeacher]...';


GO



/******************************************************************************  
 Purpose          : Time Table Subjects
 Created date     : 21 Nov 2013
 Author           : Kundan Patel 
 Copyright©       : Copyright © Sapphire Software Solutions
 ******************************************************************************/  
CREATE VIEW [sTimetable].[vTeacher]  
  
AS  
  
SELECT 
		EM.Id,
		OM.CODE + ' :' + EM.CODE AS CODE,
		EM.ShortName,
		ISNULL(EM.FirstName,'') + ' '  + ISNULL(EM.MiddleName,'') + ' ' + ISNULL(EM.LastName,'') as TeacherName,
		AO.TimeTableSchemaId,
		AO.OrgId
		--CS.ClassId 
FROM	shrm.tEmployeeMaster EM 
		INNER JOIN sTimetable.tAssignOrg AO ON AO.OrgId = EM.OrgId 	
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id= EM.OrgId
GO
PRINT N'Creating [sTimetable].[vTeacherWorkLoad]...';


GO








/******************************************************************************  
 Purpose          : To get Batch Wise  Class
 Created date     : 21 Nov 2013
 Author           : Kundan Patel 
 Copyright©       : Copyright © Sapphire Software Solutions
 ******************************************************************************/  
CREATE VIEW [sTimetable].[vTeacherWorkLoad]  
  
AS  
  
SELECT	TWL.*,
		DM.CODE DivisionCode,
		CM.Id AS ClassId,		
		CM.Title AS ClassName,
		DM.Title AS DivisionName,
		EM.ShortName + '-' + SM.Code AS Code,		
		EM.FirstName + ' ' + EM.MiddleName + ' ' + EM.LastName AS EmployeeName,
		SM.Title As SubjectName,
		EM.OrgID,
	    TWL.NOOFLECTURE -(SELECT COUNT(*) FROM sTimetable.tTimeTable TT WHERE
		TT.SubjectId=TWL.SubjectId AND TT.EmployeeId=TWL.EmployeeId 
		AND TT.DivisionId=TWL.DivisionId) AS RemainLecture
FROM sTimeTable.tTeacherWorkLoad TWL
 INNER JOIN sHRM.tEmployeeMaster EM ON EM.Id = TWL.EmployeeId
 INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = TWL.DivisionId
 INNER JOIN sSetup.tClassMaster CM ON CM.Id = DM.ClassId
 INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = TWL.SubjectId
GO

GO
PRINT N'Refreshing [sOmr].[vOMRSubject]...';


GO
EXECUTE sp_refreshview N'sOmr.vOMRSubject';


GO
PRINT N'Refreshing [sSetup].[vExamSubject]...';


GO
EXECUTE sp_refreshview N'sSetup.vExamSubject';


GO
PRINT N'Refreshing [sFee].[vUserReceiptBook]...';


GO
EXECUTE sp_refreshview N'sFee.vUserReceiptBook';


GO
PRINT N'Refreshing [sFee].[vReceiptBook]...';


GO
EXECUTE sp_refreshview N'sFee.vReceiptBook';


GO
PRINT N'Refreshing [sFee].[vReceiptBookBatch]...';


GO
EXECUTE sp_refreshview N'sFee.vReceiptBookBatch';


GO
PRINT N'Refreshing [sHrm].[vEmployeeAttendanceYearMonth]...';


GO
EXECUTE sp_refreshview N'sHrm.vEmployeeAttendanceYearMonth';


GO
PRINT N'Refreshing [sPayroll].[vEmployeePayrollYear]...';


GO
EXECUTE sp_refreshview N'sPayroll.vEmployeePayrollYear';


GO
PRINT N'Refreshing [sHrm].[vEmployeeCustomSearch]...';


GO
EXECUTE sp_refreshview N'sHrm.vEmployeeCustomSearch';


GO
PRINT N'Refreshing [sHrm].[vEmployeeColumnName]...';


GO
EXECUTE sp_refreshview N'sHrm.vEmployeeColumnName';


GO
PRINT N'Refreshing [sProcurement].[vExtStockIssueDetail]...';


GO
EXECUTE sp_refreshview N'sProcurement.vExtStockIssueDetail';


GO
PRINT N'Refreshing [sProcurement].[vExtStockIssue]...';


GO
EXECUTE sp_refreshview N'sProcurement.vExtStockIssue';


GO
PRINT N'Refreshing [sLibrary].[vOrganizationLibrary]...';


GO
EXECUTE sp_refreshview N'sLibrary.vOrganizationLibrary';


GO
PRINT N'Refreshing [sSetup].[vBatchClassDivisionWorkload]...';


GO
EXECUTE sp_refreshview N'sSetup.vBatchClassDivisionWorkload';


GO
PRINT N'Refreshing [sStudent].[vStudentCommunication]...';


GO
EXECUTE sp_refreshview N'sStudent.vStudentCommunication';


GO
PRINT N'Refreshing [sSetup].[vUserOrganization]...';


GO
EXECUTE sp_refreshview N'sSetup.vUserOrganization';


GO
PRINT N'Refreshing [sStudent].[vStudentOther]...';


GO
EXECUTE sp_refreshview N'sStudent.vStudentOther';


GO
PRINT N'Refreshing [sStudent].[vStudentName]...';


GO
EXECUTE sp_refreshview N'sStudent.vStudentName';


GO
PRINT N'Refreshing [sStudent].[vStudentFull]...';


GO
EXECUTE sp_refreshview N'sStudent.vStudentFull';


GO
PRINT N'Refreshing [sStudent].[vStudentAcademic]...';


GO
EXECUTE sp_refreshview N'sStudent.vStudentAcademic';


GO
PRINT N'Refreshing [sAssessment].[vGeneralExamCustomSearch]...';


GO
EXECUTE sp_refreshview N'sAssessment.vGeneralExamCustomSearch';


GO
PRINT N'Refreshing [sAssessment].[vGeneralExamColumnName]...';


GO
EXECUTE sp_refreshview N'sAssessment.vGeneralExamColumnName';


GO
PRINT N'Refreshing [sStudent].[vStudentAllDetail]...';


GO
EXECUTE sp_refreshview N'sStudent.vStudentAllDetail';


GO
PRINT N'Refreshing [sCommon].[vExtStudentWithAllUser]...';


GO
EXECUTE sp_refreshview N'sCommon.vExtStudentWithAllUser';


GO
PRINT N'Refreshing [sStudent].[vQualification]...';


GO
EXECUTE sp_refreshview N'sStudent.vQualification';


GO
PRINT N'Refreshing [sStudent].[vOccupation]...';


GO
EXECUTE sp_refreshview N'sStudent.vOccupation';


GO
PRINT N'Refreshing [sStudent].[vCity]...';


GO
EXECUTE sp_refreshview N'sStudent.vCity';


GO
PRINT N'Refreshing [sStudent].[vArea]...';


GO
EXECUTE sp_refreshview N'sStudent.vArea';


GO
PRINT N'Refreshing [sCertificate].[vPrintTemplateStudentDetail]...';


GO
EXECUTE sp_refreshview N'sCertificate.vPrintTemplateStudentDetail';


GO
PRINT N'Refreshing [sStudent].[vStudentCustomSearch]...';


GO
EXECUTE sp_refreshview N'sStudent.vStudentCustomSearch';


GO
PRINT N'Refreshing [sStudent].[vStudentColumnName]...';


GO
EXECUTE sp_refreshview N'sStudent.vStudentColumnName';


GO
PRINT N'Refreshing [sFee].[vFeeColumnName]...';


GO
EXECUTE sp_refreshview N'sFee.vFeeColumnName';


GO
PRINT N'Refreshing [sFee].[vFeeCustomSearch]...';


GO
EXECUTE sp_refreshview N'sFee.vFeeCustomSearch';


GO

 
PRINT N'Dropping [sFee].[pOnlinePaymentAdd]...';


GO
DROP PROCEDURE [sFee].[pOnlinePaymentAdd];


GO
PRINT N'Dropping [sTimetable].[pNooflectureGet]...';


GO
DROP PROCEDURE [sTimetable].[pNooflectureGet];


 


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


GO
ALTER PROCEDURE [sAcademic].[pLessonPlanGet]

	 @rId bigint,
	 @rClassId int,
	 @rSubjectId int,
	 @rDivisionId int,
	 @rIsCompleted bit,
	 @rBatchId int,
	 @rEmployeeId bigint
	
	 	 
	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,
			LP.StartDate,
			LP.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	 
	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
	WHERE 
		(LP.BatchId = @rBatchId) 
		AND (LP.EmployeeId = @rEmployeeId)
		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))
END
GO
PRINT N'Altering [sActivity].[pHouseMasterAdd]...';


GO

ALTER PROCEDURE [sActivity].[pHouseMasterAdd]
	 
	        @rId int,
	        @rNumber int,
	        @rCode nvarchar(50),
            @rTitle nvarchar(100),
            @rOrderIndex int,
            @rIsObsolete bit,
            @rCreatedUserId bigint,           
            @rOrgId int,
            @rHouseGroupId int,
            @rColorCode nvarchar(20)
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	IF(@rId = 0)	
	BEGIN
		IF EXISTS (SELECT Id FROM sActivity.tHouseMaster WHERE Code=@rCode AND OrgId=@rOrgId)
		BEGIN
			SELECT -101 AS Result
			RETURN
		END 
		IF EXISTS (SELECT Id FROM sActivity.tHouseMaster WHERE Title=@rTitle AND OrgId=@rOrgId)
			BEGIN
			SELECT -102 AS Result
			RETURN
		END 
		IF EXISTS (SELECT Id FROM sActivity.tHouseMaster WHERE Number=@rNumber AND OrgId=@rOrgId)
		BEGIN
			SELECT -103 AS Result
			RETURN
		END
		IF EXISTS (SELECT Id FROM sActivity.tHouseMaster WHERE OrderIndex=@rOrderIndex AND OrgId=@rOrgId)
		BEGIN
			SELECT -104 AS Result
			RETURN
		END 
	END
	ELSE
	BEGIN
		IF EXISTS (SELECT Id FROM sActivity.tHouseMaster WHERE Code=@rCode AND OrgId=@rOrgId AND Id<>@rId)
		BEGIN
			SELECT -101 As Result
			RETURN
		END 
		IF EXISTS (SELECT Id FROM sActivity.tHouseMaster WHERE Title=@rTitle AND OrgId=@rOrgId AND Id<>@rId)
		BEGIN
			SELECT -102 AS Result
			RETURN
		END
		IF EXISTS (SELECT Id FROM sActivity.tHouseMaster WHERE Number=@rNumber AND OrgId=@rOrgId AND Id<>@rId)
			BEGIN
			SELECT -103 AS Result
			RETURN
		END
		IF EXISTS (SELECT Id FROM sActivity.tHouseMaster WHERE OrderIndex=@rOrderIndex AND OrgId=@rOrgId AND Id<>@rId)
		BEGIN
			SELECT -104 AS Result
			RETURN
		END
	END
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber INT     
	
IF(@rId = 0)	
	BEGIN
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sActivity.tHouseMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	INSERT INTO [sActivity].[tHouseMaster]
			   (
			    [Id],
			    [Number], 
			    [Code],
			    [Title],
			    [OrderIndex],
			    [IsObsolete],
			    [CreatedUserId],
			    [CreatedDateTime],
			    [OrgId],
			    [HouseGroupId],
			    ColorCode
			   )
		 VALUES
			   (
				@lNextNumber,
			    @rNumber,
			    @rCode,
			    @rTitle,
			    @rOrderIndex,
			    @rIsObsolete,
			    @rCreatedUserId,
			    sCommon.fGetDate(),
			    @rOrgId,
			    @rHouseGroupId,
			    @rColorCode
			   )
			   SELECT 1 AS RESULT
	 END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  [sActivity].[tHouseMaster]
	    SET
			  [Number] = @rNumber,
	          [Code] = @rCode,
	          [Title] = @rTitle,
	          [OrderIndex] = @rOrderIndex,
              [IsObsolete] = @rIsObsolete,                          
              [UpdatedUserId] = @rCreatedUserId,
              [UpdatedDateTime] = sCommon.fGetDate(),
              [HouseGroupId] = @rHouseGroupId,
              ColorCode = @rColorCode         
	      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 [sActivity].[pHouseMasterGet]...';


GO

ALTER PROCEDURE [sActivity].[pHouseMasterGet]
          
		@rId int,
		@rCode nvarchar(50),
		@rTitle nvarchar(100),
		@rOrgId smallint,
		@rHouseGroupId int
AS
SET NOCOUNT ON

		SET @rCode = sCommon.fSearchStringGet(@rCode)
		SET @rTitle = sCommon.fSearchStringGet(@rTitle)

BEGIN

	SELECT 
		
		HM.Id, 
		HM.Number,
		HM.Code,
		HM.Title,
		HM.OrderIndex,
		HM.IsObsolete,
		HM.HouseGroupId,
		HGM.Title AS HouseGroupName,
		HM.ColorCode
		
	FROM
	
		sActivity.tHouseMaster HM
		INNER JOIN sActivity.tHouseGroupMaster HGM 
			ON HM.HouseGroupId = HGM.Id
	
	WHERE 
		((HM.Id = @rId) OR (@rId = 0))
		AND ((HM.Code Like @rCode)OR(ISNULL(@rCode,'') = ''))
		AND ((HM.Title Like @rTitle)OR(ISNULL(@rTitle,'') = ''))
		AND (HM.OrgId = @rOrgId)
		AND ((HM.HouseGroupId = @rHouseGroupId) OR (@rHouseGroupId = 0))
		ORDER BY  HM.OrderIndex
END
GO
PRINT N'Altering [sAdmission].[pAdmissionInquiryAdd]...';


GO
ALTER PROCEDURE [sAdmission].[pAdmissionInquiryAdd]
		 @rId bigint
		,@rFirstName nvarchar(100)
		,@rMiddleName nvarchar(100)
		,@rLastName nvarchar(100)
		,@rForClassId int
		,@rForBatchId	int =0
		--,@rForBatch	nvarchar(20)
		,@rDateOfBirth date
		,@rOrgId smallint
		--,@rStatusId	smallint
		,@rInquiryStatusMasterId int
		,@rStreetOne nvarchar(50)
		,@rStreetTwo nvarchar(50)
		,@rStreetThree nvarchar(50)
		,@rCountry nvarchar(50)
		,@rState nvarchar(50)
		,@rCity	nvarchar(50)
		,@rZipCode nvarchar(20)
		,@rContactNo nvarchar(20)
		,@rContactEmail	nvarchar(50)
		,@rRemark nvarchar(200)
		,@rInquiryModeId tinyint
		,@rInquiryReferenceId int
		,@rAdmissionCategoryId int
		,@rPreviousSchool nvarchar(200)
		,@rMeritMarks decimal(10,2) 
		,@rMeritGrade nvarchar(20)
		,@rMeritMarksBreakup nvarchar(100)
		,@rGenderId tinyint
		,@rFollowupDate date
		,@rFollowupRemark nvarchar(150)
		,@rCreatedUserId bigint
		,@rInquiryDate date
		,@rNumber bigint 
		,@rHandledBy nvarchar 
		,@rOrgGroupId int 
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	-- BEGIN TRY
	Declare @lStatusId smallint
	SET @lStatusId=0
	select @lStatusId=StatusId  from sAdmission.tInquiryStatusMaster where Id = @rInquiryStatusMasterId
	
--IF(@rId = 0)	
--BEGIN
--	If Exists(select Id from sAdmission.tAdmissionInquiry where FirstName=@rFirstName AND MiddleName=@rMiddleName AND
--	LastName=@rLastName AND ISNULL(DateOfBirth,'')=ISNULL(@rDateOfBirth,'') AND OrgId=@rOrgId)
--	BEGIN
--		select -103 as Result
--		RETURN
--	END 
--END
--ELSE
--BEGIN
--	If  Exists(select Id from sAdmission.tAdmissionInquiry where FirstName=@rFirstName AND MiddleName=@rMiddleName AND
--	LastName=@rLastName AND ISNULL(DateOfBirth,'')=ISNULL(@rDateOfBirth,'') AND OrgId=@rOrgId AND Id<>@rId)
--	BEGIN
--		select -103 as Result
--		RETURN
--	END
--END
 BEGIN TRANSACTION	
IF(@rId = 0)	
	BEGIN	

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


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

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


GO


ALTER PROCEDURE [sAdmission].[pRptAdmissionFormGet]
	
	@rId bigint,
	@rRelationShipId int=0

AS
 SET NOCOUNT ON
			 

BEGIN 
	
	select 
	 Convert(nvarchar(20),AF.Id) AS AdmissionFormIdText,
	 Convert(nvarchar(20),@rRelationShipId) AS RelationShipIdText,
	 AF.Id AdmissionFromId,
	 AF.FormNo,
	 AF.FirstName+' '+AF.MiddleName+' '+AF.LastName AS Name,
	 AF.ForClassId,
	 ISNULL(AF.DateOfBirth,'') AS DateOfBirth,
	 AF.BatchId,
	 CM.Title AS ClassName,
	 AF.OrgId,
	 AF.StreetOne,
	 AF.StreetTwo,
	 AF.StreetThree,
	 AF.Country,
	 AF.City,
	 AF.State,
	 AF.ZipCode,
	 AF.ContactEmail,
	 AF.ContactNo,
	 AF.PreviousSchool,
	 AF.StudentPhoto,
	 ISNULL(AF.ReligionId,0) AS ReligionId,
	 RM.Title AS ReligionName,
	 AF.MeritGrade,
	 AF.MeritMarks,
	 AF.GenderId,
	 GM.Title AS Gender,
	 AF.FamilyCast,
	 AF.FamilySubCast,
	 ISNULL(AF.CastCategoryId,0) AS CastCategoryId,
	 CCM.Title CastCategory ,
	 OM.DisplayTitle ,
	 BM.Title As Batch,
	 ISNULL(AFM.FatherName,'') AS FatherName ,
	 AFM.FatherDateOfBirth,
	 AFM.FatherOccupation,
	 AFM.FatherOfficeAddress,
	 AFM.FatherIncome,
	 AFM.FatherQualification,
	 AFM.FatherContactNo,
	 AFM.FatherMail,
	 ISNULL(AFM.MotherName,'') AS MotherName,
	 AFM.MotherDateOfBirth,
	 AFM.MotherIncome,
	 AFM.MotherOccupation,
	 AFM.MotherOfficeAddress,
	 AFM.MotherQualification,
	 AFM.MotherContactNo,
	 AFM.MotherMail,
	 isnull(AFM.RelativeName,'') AS RelativeName ,
	 AFM.RelativeDateOfBirth,
	 AFM.RelativeOccupation,
	 AFM.RelativeContactNo,
	 AFM.RelativeMail,
	 AFM.RelativeOfficeAddress,
	 AFM.RelativeIncome,
	 AFM.RelativeQualification,
	 AFM.RelationshipName ,
	 isnull(AC.IsParentAcademicRequired,0) AS IsParentAcademicRequired ,
	 isnull (AC.IsStudentAcademicRequired,0) AS IsStudentAcademicRequired ,
	 isnull(AC.IsSiblingDetailRequired,0) AS IsSiblingDetailRequired,
	 isnull(AC.IsReferenceDetailRequired,0) AS IsReferenceDetailRequired ,
	 isnull(AC.IsFamilyDetailRequired,0) AS IsFamilyDetailRequired ,
	 isnull(AC.IsFixStudentAcademic,0) AS IsFixStudentAcademic
	 
	      
  FROM  
		    sAdmission.tAdmissionForm AF 
		     
			--INNER JOIN sCommon.tStatusMaster SM ON SM.Id=AF.StatusId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=AF.OrgId
			INNER JOIN sSetup.tBatchMaster BM  ON  BM.Id=AF.BatchId
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=AF.ForClassId
			LEFT JoIN sCommon.tReligionMaster RM ON RM.Id=AF.ReligionId
			LEFT JOIN sCommon.tGenderMaster GM ON GM.Id=AF.GenderId
			--LEFT JOIN sAdmission.tAdmissionFormParentAcademic PA ON PA.AdmissionFormId=AF.Id
			--INNER JOIN sCommon.tRelationshipMaster RSM ON RSM.Id=PA.RelationshipId
			LEFT JOIN sCommon.tCastCategoryMaster CCM  ON CCM.Id=AF.CastCategoryId
			LEFT JOIN sAdmission.tAdmissionFormFamilyDetail AFM ON AFM.AdmissionFormId=AF.Id
			LEFT JOIN  sAdmission.tAdmissionCriteria AC ON AC.ClassId=CM.Id  AND AC.BatchId=AF.BatchId
				
 WHERE 	
  AF.Id = @rId
 

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


GO
ALTER PROCEDURE [sAlert].[pAbsentStudentGet]
	 	 
	 	 @rBatchId int,
	 	 @rClassId int,
	 	 @rDivisionId int,
	 	 @rOrgId int,
	 	 @rTemplate nvarchar(max),
	 	 @rAttendanceTypeId tinyint,
	 	 @rSubjectId int,
	 	 @rFromDate date,
	 	 @rToDate date,
	 	 @rIsPresent bit,
	 	 @rMailSubject nvarchar(500)=''
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

--SET @rToDate = dateadd(d,1,@rToDate)
	
	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,
			CASE WHEN @rIsPresent=0 THEN
			replace (replace (
			replace(@rTemplate,'[Name]',SC.Name),
			'[AbsentDates]',SR.AttendanceDate),
			'[AbsentReason]',ISNULL(AR.Title,''))
			ELSE
			replace (
			replace(@rTemplate,'[Name]',SC.Name),
			'[PresentDates]',SR.AttendanceDate)
			END
			 AS MsgText,
			 @rMailSubject AS Subject
		
	From 
		sStudent.vStudentCommunication SC
	INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SC.AcademicId
	LEFT JOIN sAttendance.tAbsentReasonMaster AR ON SR.AbsentReasonId = AR.Id
			
	WHERE
			((SC.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SC.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND (SC.OrgId=@rOrgId)
		AND (SC.BatchId=@rBatchId)
		AND (SC.StatusId=1)
		AND ((SR.AttendanceTypeId=@rAttendanceTypeId) OR (@rAttendanceTypeId=0))
			AND ((SR.SubjectId=@rSubjectId) OR (@rSubjectId=0))
			AND ((SR.AttendanceDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((SR.AttendanceDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND (SR.IsPresent = @rIsPresent)
		
   ORDER BY SC.ClassOrderIndex,SC.DivisionOrderIndex,SC.Rollno 
END
GO
PRINT N'Altering [sAlert].[pBookDueGet]...';


GO
ALTER PROCEDURE [sAlert].[pBookDueGet]
	 	 
	 	 @rBatchId int,
	 	 @rClassId int,
	 	 @rDivisionId int,
	 	 @rDepartmentId int,
	 	 @rOrgId int,
	 	 @rTemplate nvarchar(max),
	 	 @rDueDate date
	 	 
	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(@rTemplate,'[Name]',SC.Name),
			'[BookCode]',BM.Code),
			'[BookName]',BM.Title),
			'[DueDate]',BL.DueDate)
			 AS Template,
			 '2001' AS SourceTypeId
		
		
	From 
		sStudent.vStudentCommunication SC
	INNER JOIN sLibrary.tBookLog BL ON BL.ReaderSourceId=SC.StudentId AND BL.ReaderSourceTypeId=2003 
			AND BL.IsCurrentStatus=1 AND BL.StatusId=523 AND BL.DueDate <= @rDueDate
	INNER JOIN sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId AND BL.ResourceSourceTypeId=2009
	WHERE
			((SC.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SC.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND (SC.OrgId=@rOrgId)
		AND (SC.BatchId=@rBatchId)
		AND (SC.StatusId=1)
		
	UNION ALL
	
	Select 
			EC.EmployeeId AS AcademicId,
			EC.Code,
			EC.EmployeeName AS name,
			EC.PhoneNoCompany AS MobileNo,	
			EC.CompanyEmail AS EmailId,
			'' AS StudentContactNo,
			'' AS StudentEmail,
			'' AS FatherContactNo,
			'' AS FatherMail,
			'' AS MotherContactNo,
			'' AS MotherMail,
			replace (
			replace (
			replace (
			replace(@rTemplate,'[Name]',EC.EmployeeName),
			'[BookCode]',BM.Code),
			'[BookName]',BM.Title),
			'[DueDate]',BL.DueDate)
			 AS Template,
			  '95' AS SourceTypeId
		
		
	From 
		sHrm.vEmployeeCommunication EC
	INNER JOIN sLibrary.tBookLog BL ON BL.ReaderSourceId=EC.EmployeeId AND BL.ReaderSourceTypeId=95 
				AND BL.IsCurrentStatus=1 AND BL.StatusId=523 AND BL.DueDate <= @rDueDate
	INNER JOIN sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId AND BL.ResourceSourceTypeId=2009
	WHERE
			((EC.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		AND (EC.OrgId=@rOrgId)
		AND (EC.StatusId=7)
END
GO
PRINT N'Altering [sAlert].[pBusRouteGet]...';


GO
ALTER PROCEDURE [sAlert].[pBusRouteGet]
	 	 
	 	 @rBatchId int,
	 	 @rClassId int,
	 	 @rDivisionId int,
	 	 @rOrgId int,
	 	 @rTemplate nvarchar(max),
	 	 @rBusRouteId int,
	 	 @rOrgGroupBatchId int 
	 	 
	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(@rTemplate,'[Name]',SC.Name),
			'[BusRoute]',BRM.Title),
			'[PickupPoint]',BRDM.Title),
			'[PickupTime]',BRDM.PickupTime),
			'[DropTime]',BRDM.DropTime)
			 AS Template
		
	From 
		sStudent.vStudentCommunication SC
	INNER JOIN sTransport.tAssignRoute AR ON AR.SourceId=SC.StudentId AND AR.SourceTypeId=2003
	INNER JOIN sTransport.tBusRouteDestinationMaster BRDM ON BRDM.Id=AR.PickupDestinationId 
			AND ((BRDM.BusRouteId=@rBusRouteId) OR (@rBusRouteId=0))
	INNER JOIN sTransport.tBusRouteMaster BRM ON BRM.Id=BRDM.BusRouteId
		
	WHERE
		((SC.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SC.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((SC.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((SC.BatchId=@rBatchId) OR (@rBatchId=0))
		AND (BRM.OrgGroupBatchId=@rOrgGroupBatchId)
		AND (SC.StatusId=1)
END
GO
PRINT N'Altering [sAlert].[pChargeReceiptEntryGet]...';


GO
ALTER PROCEDURE [sAlert].[pChargeReceiptEntryGet]
	 	 
	 	 @rReceiptId bigint,
	 	 @rBatchId int,
	 	 @rClassId int,
	 	 @rDivisionId int,
	 	 @rOrgId int,
	 	 @rSubject nvarchar(100),
	 	 @rTemplate nvarchar(max),
	 	 @rReceiptBookId int,
	 	 @rFromDate date,
	 	 @rToDate date
	 	 
	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,
			@rSubject AS Subject,
			replace (
			replace (
			replace (
			replace(@rTemplate,'[Name]',SC.Name),
			'[ReceiptNumber]',CR.ReceiptNumber),
			'[ReceiptDate]',CR.ReceiptDate),
			'[Amount]',(SELECT SUM(Amount) FROM sFee.tChargeReceiptDetail WHERE ChargeReceiptId=CR.Id))
			 AS MsgText
		
		
	From 
		sStudent.vStudentCommunication SC
	INNER JOIN sFee.tChargeReceipt CR ON CR.SourceId=SC.AcademicId AND CR.SourceTypeId=2001 AND CR.IsObsolete=0
			AND ((CR.ChargeReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
			AND ((CR.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			--AND ((R.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND ((CR.Id=@rReceiptId) OR (@rReceiptId=0))
		
	WHERE
			((SC.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SC.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((SC.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((SC.BatchId=@rBatchId) OR (@rBatchId=0))
		AND (SC.StatusId=1)
		
		ORDER BY CR.ReceiptNumber
END
GO
PRINT N'Altering [sAlert].[pEmployeeBirthdayWishSchedulerGet]...';


GO
ALTER PROCEDURE [sAlert].[pEmployeeBirthdayWishSchedulerGet]
	 	 
	 	 @rOrgId smallint,
	 	 @rTemplate nvarchar(max),
	 	 @rMailSubject nvarchar(100)
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	Select 
			EC.MobileNumber AS MobileNo,	
			EC.PersonalEmail AS EmailId,
			replace(replace(@rTemplate,'[Name]',EC.EmployeeName),'[SchoolName]',OM.Title)
			 
			 AS MsgText,
			@rMailSubject AS Subject
		
	From 
		sHrm.vEmployeeCommunication EC
		INNER JOIN sSetup.tOrganizationMaster OM ON EC.OrgId = OM.Id
	WHERE
			(DAY(EC.DateOfBirth) = DAY(GETDATE()))
		AND (MONTH(EC.DateOfBirth) = MONTH(GETDATE()))
		AND (EC.StatusId=7)
		AND (EC.OrgId=@rOrgId)
END
GO
PRINT N'Altering [sAlert].[pFeeDueGet]...';


GO

ALTER PROCEDURE [sAlert].[pFeeDueGet]
		
		 @rBatchId int,
	 	 @rClassId int,
	 	 @rDivisionId int,
	 	 @rOrgId int,
	 	 @rTemplate nvarchar(max),
	 	 @rReceiptBookId int,
	 	 @rToDate date,
	 	  @rMailSubject nvarchar(500)=''
	 	 
		
		
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 	
 
SELECT 
            D.AcademicId,
			D.RollNo,
			D.Name,
			D.Code,
			D.MobileNo,	
			D.EmailId,
			D.StudentContactNo,
			D.StudentEmail,
			D.FatherContactNo,
			D.FatherMail,
			D.MotherContactNo,
			D.MotherMail,
			SUM(D.PendingAmount) As PendingAmount,
			replace (
			replace(@rTemplate,'[Name]',D.Name),
			'[PendingAmount]',convert(int,(SUM(D.PendingAmount))))
			 AS Template,
			  @rMailSubject AS Subject
			
			
			FROM
			(
	
 			SELECT
			 			 
			SA.AcademicId,
			SA.RollNo,
			SA.Name,
			SA.Code,
			SC.ParentContactNo AS MobileNo,	
			SC.ParentEmail AS EmailId,
			ISNULL(SC.StudentContactNo,'') AS StudentContactNo,
			ISNULL(SC.StudentEmail,'') AS StudentEmail,
			ISNULL(SC.FatherContactNo,'') AS FatherContactNo,
			ISNULL(SC.FatherMail,'') AS FatherMail,
			ISNULL(SC.MotherContactNo,'') AS MotherContactNo,
			ISNULL(SC.MotherMail,'') AS MotherMail,
			--replace (
			--replace(@rTemplate,'[Name]',SA.Name),
			--'[PendingAmount]',(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(R.PaidAmount,0.00)))
			-- AS Template,
		 
			--replace(@rTemplate,'[Name]',SA.Name) 
			-- AS Template,
			 SA.DivisionOrder,
			(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(R.PaidAmount,0.00))  AS PendingAmount
			 	 
  FROM 
  
		sStudent.vStudentAcademic SA
		INNER JOIN 
		(
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName
			FROM sFee.tFeeSetup FS1
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId
			    AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))
				--AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			WHERE 
					((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				--AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=0)
				--AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((FS1.StartDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
				
				UNION ALL
				
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName
			FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO
			ON FO.FeeSetupId=FS1.Id
	    INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND SA1.BatchId = FS1.BatchId 
			 AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
			AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0)) 
			--AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
		WHERE
				((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				--AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=1)
				--AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((FS1.StartDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
				
		) 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 sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId				
				AND (SA1.ClassId=@rClassId OR @rClassId=0) AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))
				AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
			WHERE		
				(R.SourceTypeId = 2001)
				AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND (R.IsObsolete = 0) 
				--AND (R.OrgGroupBatchId = @rOrgGroupBatchId)
				AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
				--AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
				--AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				GROUP BY FeeSetupId,R.SourceId
		
		) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
		 INNER JOIN sSetup.tOrganizationMaster O ON
		 SA.OrgId = O.Id
		 INNER JOIN sFee.tReceiptBookMaster RBM 
			ON FS.ReceiptBookId=RBM.Id
		 LEFT JOIN  sStudent.vStudentCommunication SC ON
		 SC.StudentId = SA.StudentId
		 
	
	WHERE	
	         SA.StatusId = 1 AND
			((SA.BatchId=@rBatchId) OR (@rBatchId=0)) 
			--AND (SA.StatusId = @rStatusId OR @rStatusId=0)
			AND ((FS.StartDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
			--AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
			--AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
			--AND ((SA.Code=@rCode) OR (@rCode=''))
			--AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
			AND (ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00) -ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00) > 0)		 
			
				
 ) D
 GROUP BY 
			D.AcademicId,
			D.RollNo,
			D.Name,
			D.Code,
			D.MobileNo,	
			D.EmailId,
			D.StudentContactNo,
			D.StudentEmail,
			D.FatherContactNo,
			D.FatherMail,
			D.MotherContactNo,
			D.MotherMail,
			D.DivisionOrder 
 Order by D.DivisionOrder,D.Rollno	
				
END
GO
PRINT N'Altering [sAlert].[pFeeReceiptEntryGet]...';


GO
ALTER PROCEDURE [sAlert].[pFeeReceiptEntryGet]
	 	 
	 	 @rReceiptId bigint,
	 	 @rBatchId int,
	 	 @rClassId int,
	 	 @rDivisionId int,
	 	 @rOrgId int,
	 	 @rSubject nvarchar(100),
	 	 @rTemplate nvarchar(max),
	 	 @rReceiptBookId int,
	 	 @rFromDate date,
	 	 @rToDate date
	 	 
	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,
			@rSubject AS Subject,
			replace (
			replace (
			replace (
			replace(@rTemplate,'[Name]',SC.Name),
			'[ReceiptNumber]',R.ReceiptNumber),
			'[ReceiptDate]',R.ReceiptDate),
			'[PaidAmount]',convert(int,R.ReceiptAmount))
			 AS MsgText
		
		
	From 
		sStudent.vStudentCommunication SC
	INNER JOIN sFee.tReceipt R ON R.SourceId=SC.AcademicId AND R.SourceTypeId=2001 AND R.IsObsolete=0
			AND ((R.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
			AND ((R.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			--AND ((R.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND ((R.Id=@rReceiptId) OR (@rReceiptId=0))
		
	WHERE
			((SC.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SC.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((SC.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((SC.BatchId=@rBatchId) OR (@rBatchId=0))
		AND (SC.StatusId=1)
		ORDER BY R.ReceiptNumber
END
GO
PRINT N'Altering [sAlert].[pHostelAdmissionGet]...';


GO
ALTER PROCEDURE [sAlert].[pHostelAdmissionGet]
	 	 
	 	 @rBatchId int,
	 	 @rClassId int,
	 	 @rDivisionId int,
	 	 @rOrgId int,
	 	 @rTemplate nvarchar(max),
	 	 @rHostelId int,
	 	 @rOrgGroupId int,
	 	 @rAdmissionDate date,
	 	 @rSourceId bigint=0  
	 	 
	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(@rTemplate,'[Name]',sc.name),
			'[HostelName]',HM.Title),
			'[BuildingName]',BM.Title),
			'[RoomName]',RM.Title),	
			'[AdmissionDate]',HA.AllocateDate)
			 AS MsgText,
			 '' AS Subject
	From 
		sStudent.vStudentCommunication SC
	INNER JOIN sSetup.tBatchMaster BMast ON BMast.Id=SC.BatchId AND BMast.IsActive = 1
	INNER JOIN sHostel.tAssignRoom AR ON AR.SourceId = SC.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 AND ((HM.Id=@rHostelId) OR (@rHostelId=0))
	INNER JOIN sHostel.tHostelAdmission HA ON HA.SourceId = SC.StudentId AND AR.SourceTypeId=2003
	LEFT JOIN sHostel.tBuildingMaster BM ON BM.Id = RM.BuildingId 
	
	WHERE
		((SC.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SC.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((SC.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((SC.BatchId=@rBatchId) OR (@rBatchId=0))
		AND (HM.OrgGroupId=@rOrgGroupId)
		AND (HA.AllocateDate = @rAdmissionDate)
		AND ((HA.SourceId=@rSourceId) OR (@rSourceId=0))
		AND (SC.StatusId=1)
END
GO
PRINT N'Altering [sAlert].[pHostelChangeRoomGet]...';


GO
ALTER PROCEDURE [sAlert].[pHostelChangeRoomGet]
	 	 
	 	 @rBatchId int,
	 	 @rClassId int,
	 	 @rDivisionId int,
	 	 @rOrgId int,
	 	 @rTemplate nvarchar(max),
	 	 @rHostelId int,
	 	 @rOrgGroupId int,
	 	 @rLogDate date,
	 	 @rSourceId bigint=0 
	 	 
	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(@rTemplate,'[Name]',sc.name),
			'[HostelName]',HM.Title),
			'[BuildingName]',BM.Title),
			'[ChangeRoomName]',RM.Title),
			'[LogDate]',CR.LogDate)
			 AS MsgText,
			 '' AS Subject
	From 
		sStudent.vStudentCommunication SC
	INNER JOIN sSetup.tBatchMaster BMast ON BMast.Id=SC.BatchId AND BMast.IsActive = 1	
	INNER JOIN sHostel.tChangeRoom CR ON CR.SourceId=SC.StudentId  AND CR.SourceTypeId=2003
	INNER JOIN sHostel.tRoomMaster RM ON RM.Id = CR.RoomId
	INNER JOIN sHostel.tHostelMaster HM ON HM.Id = RM.HostelId AND ((HM.Id=@rHostelId) OR (@rHostelId=0))
	LEFT JOIN sHostel.tBuildingMaster BM ON BM.Id = RM.BuildingId
	
	WHERE
		((SC.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SC.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((SC.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((SC.BatchId=@rBatchId) OR (@rBatchId=0))
		AND (HM.OrgGroupId=@rOrgGroupId)
		AND (CR.LogDate=@rLogDate)
		AND ((CR.SourceId=@rSourceId) OR (@rSourceId=0))
		AND (SC.StatusId=1)
END
GO
PRINT N'Altering [sAlert].[pHostelVacantGet]...';


GO
ALTER PROCEDURE [sAlert].[pHostelVacantGet]
	 	 
	 	 @rBatchId int,
	 	 @rClassId int,
	 	 @rDivisionId int,
	 	 @rOrgId int,
	 	 @rTemplate nvarchar(max),
	 	 @rHostelId int,
	 	 @rOrgGroupId int,
	 	 @rVacantDate date,
	 	 @rSourceId bigint=0    
	 	 
	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(@rTemplate,'[Name]',sc.name),
			'[HostelName]',HM.Title),
			'[BuildingName]',BM.Title),
			'[RoomName]',RM.Title),	
			'[VacantDate]',HA.VacantDate)
			 AS MsgText,
			 '' AS Subject
	From 
		sStudent.vStudentCommunication SC
	INNER JOIN sSetup.tBatchMaster BMast ON BMast.Id=SC.BatchId AND BMast.IsActive = 1	
	INNER JOIN sHostel.tAssignRoom AR ON AR.SourceId = SC.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 AND ((HM.Id=@rHostelId) OR (@rHostelId=0))
	INNER JOIN sHostel.tHostelAdmission HA ON HA.SourceId = SC.StudentId AND AR.SourceTypeId=2003
	LEFT JOIN sHostel.tBuildingMaster BM ON BM.Id = RM.BuildingId 
	
	WHERE
		((SC.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SC.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((SC.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((SC.BatchId=@rBatchId) OR (@rBatchId=0))
		AND (HM.OrgGroupId=@rOrgGroupId)
		AND (HA.VacantDate = @rVacantDate)
		AND ((HA.SourceId=@rSourceId) OR (@rSourceId=0))
		AND (SC.StatusId=1)
END
GO
PRINT N'Altering [sAlert].[pMonthlyAttendanceGet]...';


GO
ALTER PROCEDURE [sAlert].[pMonthlyAttendanceGet]
	 	 
	 	 @rBatchId int,
	 	 @rClassId int,
	 	 @rDivisionId int,
	 	 @rOrgId int,
	 	 @rTemplate nvarchar(max),
	 	 @rAttendanceTypeId tinyint,
	 	 @rSubjectId int,
	 	 @rForYear smallint,
	 	 @rForMonth tinyint,
	 	 @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 (
			replace(@rTemplate,'[Name]',SC.Name),
			'[ForYear]',MR.ForYear),
			'[ForMonth]',MM.Title),
			'[TotalCount]',MR.TotalCount),
			'[PresentCount]',MR.PresentCount),
			'[AbsentCount]',MR.AbsentCount),
			'[AveragePresence]',MR.AveragePresence),
			'[AbsentDates]',MR.AbsentDays)
			 AS MsgText,
			 @rMailSubject AS Subject
		
		
	From 
		sStudent.vStudentCommunication SC
	INNER JOIN sAttendance.tMonthlyRegister MR ON MR.AcademicId=SC.AcademicId	
			AND ((MR.AttendanceTypeId=@rAttendanceTypeId) OR (@rAttendanceTypeId=0))
			AND ((MR.SubjectId=@rSubjectId) OR (@rSubjectId=0))
			AND ((MR.ForYear=@rForYear) OR (@rForYear=0))
			AND ((MR.ForMonth=@rForMonth) OR (@rForMonth=0))
	INNER JOIN sCommon.tMonthMaster MM ON MR.ForMonth = MM.Id
		
	WHERE
			((SC.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SC.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND (SC.OrgId=@rOrgId)
		AND (SC.BatchId=@rBatchId)
		AND (SC.StatusId=1)
		ORDER BY SC.DivisionOrderIndex,SC.Rollno
END
GO
PRINT N'Altering [sAlert].[pNewAdmissionGet]...';


GO
ALTER PROCEDURE [sAlert].[pNewAdmissionGet]
	
	@rClassId int,
	@rDivisionId int,
	@rOrgId smallint,
	@rBatchId int,
	@rTemplate nvarchar(max),
	@rFromDate date,
	@rToDate date
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	declare @Sql nvarchar(max)
	
	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(@rTemplate,'[Name]',sc.name),
			'[standard]',sc.classname),
			'[SchoolName]',OM.Title)
			 AS Template
	FROM 
			sStudent.vStudentCommunication SC
			INNER JOIN sSetup.tOrganizationMaster OM ON SC.OrgId = OM.Id
		INNER JOIN sStudent.tStudentAdmission SA ON SA.StudentId=SC.StudentId
				AND ((ISNULL(SA.AdmissionDate,'') >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
				AND ((ISNULL(SA.AdmissionDate,'') <= @rToDate) OR (ISNULL(@rToDate,'')=''))
	WHERE	
			((SC.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SC.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND (SC.OrgId=@rOrgId)
		AND (SC.BatchId=@rBatchId)
		AND (SC.StatusId=1)
		
		ORDER BY SC.ClassOrderIndex,SC.Code
END
GO
PRINT N'Altering [sAlert].[pResultGet]...';


GO
ALTER PROCEDURE [sAlert].[pResultGet]
	 	 
	 	 @rBatchId int,
	 	 @rClassId int,
	 	 @rDivisionId int,
	 	 @rOrgId int,
	 	 @rTemplate nvarchar(max),
	 	 @rExamId int
	 	 
	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 (
			replace (
			replace (
			replace(@rTemplate,'[Name]',SC.Name),
			'[ExamName]',ES.Title),
			'[TotalMarks]',CONVERT(int,TotalMarks)),
			'[ObtainMarks]',CONVERT(int,TotalObtain)),
			'[ResultStatus]',R.ResultStatus),
			'[ResultGrade]',R.ResultGrade),
			'[ResultGradePoint]',R.ResultGradePoint),
			'[RankNumber]',R.RankNumber),
			'[Percentage]',R.Percentage),
			'[Percentile]',R.Percentile)
			 AS Template
		
	From 
		sStudent.vStudentCommunication SC
	INNER JOIN sAssessment.tResult R ON R.AcademicId=SC.AcademicId AND (R.ExamId=@rExamId OR @rExamId=0)
	INNER JOIN sAssessment.tExamMaster E ON R.ExamId = E.Id
	INNER JOIN sAssessment.tExamSubGroupMaster ES ON ES.Id = E.ExamSubGroupId
		
	WHERE
			((SC.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SC.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND (SC.OrgId=@rOrgId)
		AND (SC.BatchId=@rBatchId)
		AND (SC.StatusId=1)
	ORDER BY SC.DivisionOrderIndex,SC.Rollno
END
GO
PRINT N'Altering [sAlert].[pResultWithSubjectGet]...';


GO
ALTER PROCEDURE [sAlert].[pResultWithSubjectGet]
	 	 @rBatchId int,
	 	 @rClassId int,
	 	 @rDivisionId int,
	 	 @rOrgId int,
	 	 @rTemplate nvarchar(max),
	 	 @rExamId int,
	 	 @rSubjectId int=0
	 	 
	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 (
			replace (
			replace (
			replace (
			replace (
			replace(@rTemplate,'[Name]',SC.Name),
			'[ExamName]',ES.Title),
			'[SubjectMark]',[sAlert].[fResultGet](R.Id,@rSubjectId)),
			'[SubjectMarkWithMax]',[sAlert].[fResultWithMaxGet](R.Id,@rSubjectId)),
			'[TotalMarks]',CONVERT(int,TotalMarks)),
			'[ObtainMarks]',CONVERT(int,TotalObtain)),
			'[ResultStatus]',R.ResultStatus),
			'[ResultGrade]',R.ResultGrade),
			'[ResultGradePoint]',R.ResultGradePoint),
			'[RankNumber]',R.RankNumber),
			'[Percentage]',R.Percentage),
			'[Percentile]',R.Percentile)
			 AS Template
		
	From 
	sStudent.vStudentCommunication SC
	INNER JOIN sAssessment.tResult R ON R.AcademicId=SC.AcademicId AND (R.ExamId=@rExamId OR @rExamId=0)
	INNER JOIN sAssessment.tExamMaster E ON R.ExamId = E.Id
	INNER JOIN sAssessment.tExamSubGroupMaster ES ON ES.Id = E.ExamSubGroupId
	 
	WHERE
			((SC.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SC.DivisionId=@rDivisionId) OR (@rDivisionId=0))	 
		AND (SC.OrgId=@rOrgId)
		AND (SC.BatchId=@rBatchId)
		AND (SC.StatusId=1)
	ORDER BY SC.DivisionOrderIndex,SC.Rollno
END
GO
PRINT N'Altering [sAlert].[pSMSConfigurationAdd]...';


GO
ALTER PROCEDURE [sAlert].[pSMSConfigurationAdd]
	
	@rOrgId smallint,
	@rSMSURL nvarchar(1000),
	@rSMSCreditURL nvarchar(1000),
	@rLoginId nvarchar(50),
	@rLoginPassword nvarchar(50),
	@rLoginSenderId nvarchar(50),
	@rSMSXMLURL nvarchar(1000),
	@rVendorId smallint,
	@rOrgGroupId smallint,
	@rIsAllOrg bit,
	@rSMSUnicodeURL nvarchar(1000)=''
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	 
	 IF(@rIsAllOrg=1)
	 BEGIN
		DECLARE @lCount INT
		CREATE TABLE #tTable  
		(
			Id bigint identity,
			OrgId smallint
		)
		INSERT INTO #tTable
		(
			OrgId
		)
		SELECT Id FROM sSetup.tOrganizationMaster WHERE OrgGroupId=@rOrgGroupId
		
		SELECT @lCount =  COUNT(Id) FROM #tTable
		WHILE @lCount > 0 
		BEGIN
			SELECT @rOrgId=OrgId FROM #tTable WHERE Id = @lCount
			IF NOT EXISTS(SELECT OrgId FROM sAlert.tSMSConfiguration WHERE OrgId=@rOrgId)
BEGIN

	INSERT INTO sAlert.tSMSConfiguration
		(
			OrgId,
			SMSURL,
			SMSCreditURL,
			LoginId,
			LoginPassword,
			LoginSenderId,
			SMSXMLURL,
			VendorId,
			SMSUnicodeURL
		)
	VALUES
		(
			@rOrgId,
			@rSMSURL,
			@rSMSCreditURL,
			@rLoginId,
			@rLoginPassword,
			@rLoginSenderId,
			@rSMSXMLURL,
			@rVendorId,
			@rSMSUnicodeURL
		)
		             
	END	 
	 ELSE
	 BEGIN
	    UPDATE  sAlert.tSMSConfiguration
	    SET
			SMSURL=@rSMSURL,
			SMSCreditURL=@rSMSCreditURL,
			LoginId=@rLoginId,
			LoginPassword=@rLoginPassword,
			LoginSenderId=@rLoginSenderId,
			SMSXMLURL=@rSMSXMLURL,
			VendorId=@rVendorId,
			SMSUnicodeURL=@rSMSUnicodeURL
	      
	      WHERE OrgId = @rOrgId 	   
	 END  
		SELECT @rOrgId AS Result
			SET @lCount = @lCount - 1
		END
	 END
	 ELSE
	 BEGIN
	 
 IF NOT EXISTS(SELECT OrgId FROM sAlert.tSMSConfiguration WHERE OrgId=@rOrgId)
BEGIN

	INSERT INTO sAlert.tSMSConfiguration
		(
			OrgId,
			SMSURL,
			SMSCreditURL,
			LoginId,
			LoginPassword,
			LoginSenderId,
			SMSXMLURL,
			VendorId,
			SMSUnicodeURL
		)
	VALUES
		(
			@rOrgId,
			@rSMSURL,
			@rSMSCreditURL,
			@rLoginId,
			@rLoginPassword,
			@rLoginSenderId,
			@rSMSXMLURL,
			@rVendorId,
			@rSMSUnicodeURL
		)
		             
	END	 
	 ELSE
	 BEGIN
	    UPDATE  sAlert.tSMSConfiguration
	    SET
			SMSURL=@rSMSURL,
			SMSCreditURL=@rSMSCreditURL,
			LoginId=@rLoginId,
			LoginPassword=@rLoginPassword,
			LoginSenderId=@rLoginSenderId,
			SMSXMLURL=@rSMSXMLURL,
			VendorId=@rVendorId,
			SMSUnicodeURL=@rSMSUnicodeURL
	      
	      
	      WHERE OrgId = @rOrgId 	   
	 END  
		SELECT @rOrgId AS Result
	END
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sAlert].[pSMSConfigurationGet]...';


GO
ALTER PROCEDURE [sAlert].[pSMSConfigurationGet]
	 
	 @rOrgId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			
BEGIN 
	SELECT
			SC.SMSURL,
			SC.SMSCreditURL,
			SC.LoginId,
			SC.LoginPassword,
			SC.LoginSenderId,
			SC.SMSXMLURL,
			SC.VendorId,
			ISNULL(SC.SMSUnicodeURL,'') AS SMSUnicodeURL
	FROM
			sAlert.tSMSConfiguration SC
	WHERE 
			SC.OrgId=@rOrgId
END
GO
PRINT N'Altering [sAlert].[pSMSHistoryGet]...';


GO
ALTER PROCEDURE [sAlert].[pSMSHistoryGet]
	
	@rOrgId smallint,
	@rStatusId int,
	@rContactId nvarchar(50),
	@rEventId int,
	@rSourceEvent nvarchar(50),
	@rUserName nvarchar(100),
	@rAlertModeId tinyint,
	@rFromDate date,
	@rToDate date,
	@rOrgGroupId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	SELECT 
			AL.Id AS Id,
			AL.ContactId,
			AL.AlertMessage,
			AL.AlertSubject,
			CASE WHEN AL.ResultMessage='' THEN 'Pending' ELSE AL.ResultMessage END AS ResultMessage,
			--AL.ResultMessage
			EM.Title AS EventName,
			AL.SourceEvent,
			U.DisplayTitle AS UserName,
			AL.CreatedDateTime,
			OM.Id AS OrgId,
			OM.DisplayTitle AS Organization
	FROM
			sAlert.tAlertLog AL
		INNER JOIN sAlert.tEventMaster EM ON EM.Id=AL.EventId
		LEFT JOIN sSecurity.tUser U ON U.Id=AL.CreatedUserId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=AL.OrgId 
	WHERE
			((AL.OrgId=@rOrgId) OR (@rOrgId=0))
		AND	((AL.StatusId=@rStatusId) OR (@rStatusId=0))
		AND ((AL.ContactId=@rContactId) OR (ISNULL(@rContactId,'')=''))
		AND ((AL.EventId=@rEventId) OR (@rEventId=0))
		AND ((AL.SourceEvent=@rSourceEvent) OR (ISNULL(@rSourceEvent,'')=''))
		AND ((AL.AlertModeId=@rAlertModeId) OR (@rAlertModeId=0))
		AND ((U.DisplayTitle like @rUserName) OR (ISNULL(@rUserName,'')=''))
		AND ((CONVERT(date,AL.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((CONVERT(date,AL.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		AND OM.OrgGroupId = @rOrgGroupId
		ORDER BY AL.CreatedDateTime DESC
		
		
--SELECT DISTINCT OM.Title, D.Code,OM.OrderIndex,D.OrderIndex FROM sSetup.tDivisionMaster D
--INNER JOIN ssetup.tOrganizationMaster OM
--ON D.OrgId = OM.Id
--WHERE D.Id IN
--(
--select DivisionId from sStudent.tAcademic A INNER JOIN
--sStudent.tStudentCommunication SC ON A.StudentId = SC.StudentId
--INNER JOIN SAlert.tAlertLog AL ON SC.ParentContactNo = AL.ContactId
--AND AL.OrgId IN (SELECT Id From sSetup.tOrganizationMaster WHERE OrgGroupId = 1141 )
--AND AL.AlertModeId = 2)
--order by  OM.OrderIndex,D.OrderIndex


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


GO
ALTER PROCEDURE [sAlert].[pStudentBirthdayWishGet]
	 	 
	 	 @rBatchId int,
	 	 @rClassId int,
	 	 @rDivisionId int,
	 	 @rOrgId int,
	 	 @rTemplate nvarchar(max),
	 	 @rDateOfBirth date
	 	 
	 	 
	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(@rTemplate,'[Name]',SC.Name),'[SchoolName]',OM.Title)
			 AS Template
	From 
		sStudent.vStudentCommunication SC
		INNER JOIN sSetup.tOrganizationMaster OM ON SC.OrgId = OM.Id
		
	WHERE
			((SC.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SC.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND (SC.OrgId=@rOrgId)
		AND (SC.BatchId=@rBatchId)
		AND (DAY(SC.DateOfBirth) = DAY(@rDateOfBirth))
		AND (MONTH(SC.DateOfBirth) = MONTH(@rDateOfBirth))
		AND (SC.StatusId=1)
	ORDER BY SC.DivisionOrderIndex,SC.Rollno
END
GO
PRINT N'Altering [sAlert].[pStudentBirthdayWishSchedulerGet]...';


GO
ALTER PROCEDURE [sAlert].[pStudentBirthdayWishSchedulerGet]
	 	 
	 	 @rOrgId smallint,
	 	 @rTemplate nvarchar(max),
	 	 @rMailSubject nvarchar(100)
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	Select 
 
			SC.ParentContactNo AS MobileNo,	
			SC.ParentEmail AS EmailId,
			replace(replace(@rTemplate,'[Name]',SC.Name),'[SchoolName]',OM.Title)
			 AS MsgText,
			@rMailSubject AS Subject
		
	From 
		sStudent.vStudentCommunication SC
		INNER JOIN sSetup.tOrganizationMaster OM ON SC.OrgId = OM.Id
	WHERE
			(DAY(SC.DateOfBirth) = DAY(GETDATE()))
		AND (MONTH(SC.DateOfBirth) = MONTH(GETDATE()))
		AND (SC.StatusId=1)
		AND (SC.OrgId=@rOrgId)
		AND SC.IsActiveBatch = 1
END
GO
PRINT N'Altering [sAssessment].[pCSIndicatorDetailAdd]...';


GO

ALTER PROCEDURE [sAssessment].[pCSIndicatorDetailAdd]
	 
	        @rId int
           ,@rCCECSId int
           ,@rTitle nvarchar(200)
           --,@rCode nvarchar(200)
           ,@rNumber smallint
		   ,@rOrderIndex int	
		   ,@rGradeSetDetailId int	  
		   ,@rUpdatedUserId bigint
		   ,@rIsObsolete bit
		   ,@rOrgId int	
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 
IF(@rId = 0)	
BEGIN
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAssessment.tCCECSIndicatorMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	INSERT INTO [sAssessment].[tCCECSIndicatorMaster]
			   (
			    [Id]
			   ,[CCECSId]
			   ,[Title]
			   --,[Code]
			   ,[Number] 
			   ,[OrgId]
			   ,[IsObsolete]
			   ,[OrderIndex]	
			   ,[GradeSetDetailId] 
			   ,[UpdatedUserId]
			   ,[UpdatedDateTime]
			   )
		 VALUES
			   (
				@lNextNumber
			   ,@rCCECSId
			   ,@rTitle
			   --,@rCode
			   ,@rNumber
			   ,@rOrgId
			   ,@rIsObsolete
			   ,@rOrderIndex
			   ,@rGradeSetDetailId
			   ,@rUpdatedUserId			   
			   ,sCommon.fGetDate()
			   )
		    SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION         
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  [sAssessment].[tCCECSIndicatorMaster]
	    SET
			 
	          CCECSId=@rCCECSId
	         ,Title=@rTitle
	         --,Code=@rCode
	         ,Number=@rNumber
	         ,OrgId=@rOrgId
	         ,IsObsolete=@rIsObsolete
			 ,OrderIndex=@rOrderIndex
			 ,GradeSetDetailId=@rGradeSetDetailId
			 ,UpdatedUserId =@rUpdatedUserId
			 ,UpdatedDateTime=sCommon.fGetDate()
	      WHERE Id = @rId 	   
	      SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION
	 END  
		
	--END
--END	
COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sAssessment].[pExamDetailAdd]...';


GO

ALTER PROCEDURE [sAssessment].[pExamDetailAdd]
	 
	        @rId int
           ,@rExamId int
		   ,@rClassSubjectId int
		   ,@rMinimum decimal(10,2)
		   ,@rMaximum Decimal(10,2)
		   ,@rIsIncludeInTotal bit
		   ,@rIsDisplayInMarkSheet bit
		   ,@rIsShowSubjectGrade bit
		   ,@rDisplayOrder tinyint
		   ,@rGradeSetDetailId int
		   ,@rExamDate date
		   ,@rExamTime nvarchar(50)
		   ,@rExamTopic nvarchar(100)
		   ,@rCreatedUserId bigint
		   ,@rOrgId int
		   ,@rIsObsolete bit,
		   @rIsShowSubjectMark bit=1
		 
		   
		  	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

--IF(@rId = 0)	
IF NOT EXISTS (SELECT 1 FROM [sAssessment].[tExamDetail] WHERE ExamId = @rExamId
				AND ClassSubjectId = @rClassSubjectId )
	BEGIN
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAssessment.tExamDetail', 0, 1, 1,@outNextNumber = @lNextNumber output
	INSERT INTO [sAssessment].[tExamDetail]
			   (
			    [Id]
			   ,ExamId 
			   ,ClassSubjectId 
			   ,Minimum 
			   ,Maximum 
			   ,IsIncludeInTotal 
			   ,IsDisplayInMarkSheet 
			   ,IsShowSubjectGrade 
			   ,DisplayOrder 
			   ,GradeSetId 
			   ,ExamDate 
			   ,ExamTime 
			   ,ExamTopic 
			   ,UpdatedUserId
			   ,UpdatedDateTime,
			   IsShowSubjectMark
			   )
		 VALUES
			   (
				@lNextNumber
			   ,@rExamId 
			   ,@rClassSubjectId 
			   ,@rMinimum 
			   ,@rMaximum 
			   ,@rIsIncludeInTotal 
			   ,@rIsDisplayInMarkSheet 
			   ,@rIsShowSubjectGrade 
			   ,@rDisplayOrder 
			   ,@rGradeSetDetailId 
			   ,@rExamDate 
			   ,@rExamTime 
			   ,@rExamTopic 
			   ,0
			   ,sCommon.fGetDate(),
			   @rIsShowSubjectMark 
			   )
		    SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION         
	END	 
ELSE
    BEGIN


IF @rIsObsolete = 1 
	  
	BEGIN
	IF EXISTS (SELECT R.Id FROM sAssessment.tResultDetail R INNER JOIN  [sAssessment].[tExamDetail] ED ON R.ExamDetailId = ED.Id and R.ExamDetailId=@rId AND R.Obtain > @rMaximum) 
    BEGIN
		SELECT -104 AS Result
		RETURN
    END
			
			 SET @lNextNumber = @rId
				UPDATE  [sAssessment].[tExamDetail]
				SET
						ExamId =@rExamId 
					   ,ClassSubjectId =@rClassSubjectId 
					   ,Minimum=@rMinimum 
					   ,Maximum=@rMaximum 
					   ,IsIncludeInTotal =@rIsIncludeInTotal 
					   ,IsDisplayInMarkSheet =@rIsDisplayInMarkSheet 
					   ,IsShowSubjectGrade =@rIsShowSubjectGrade 
					   ,DisplayOrder =@rDisplayOrder 
					   ,GradeSetId =@rGradeSetDetailId 
					   ,ExamDate =@rExamDate 
					   ,ExamTime=@rExamTime 
					   ,ExamTopic =@rExamTopic 
					   ,UpdatedUserId=@rCreatedUserId
					   ,UpdatedDateTime=sCommon.fGetDate(),
					   IsShowSubjectMark=@rIsShowSubjectMark 
				  WHERE Id = @rId 	   
				  SELECT @lNextNumber AS Result
			
				--COMMIT TRANSACTION
			 END 
	ELSE
		BEGIN
		
			IF EXISTS (SELECT R.Id FROM sAssessment.tResultDetail R INNER JOIN  [sAssessment].[tExamDetail] ED ON R.ExamDetailId = ED.Id and R.ExamDetailId=@rId) 
			AND @rIsObsolete = 0
			BEGIN
				SELECT -105 AS Result
				RETURN
			END
		
			DELETE FROM [sAssessment].[tExamDetail] WHERE ID = @rId
			SELECT @rId AS Result
		END		  
	END 

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


GO
 
ALTER PROCEDURE [sAssessment].[pExamFullDetailGet]
	 @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 
	
	
	
  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					
			INNER 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].[pMarkEntryAllSubjectGet]...';


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

BEGIN 		
DECLARE @cols AS NVARCHAR(MAX),
@query  AS NVARCHAR(MAX),@query1  AS NVARCHAR(MAX),@query2  AS NVARCHAR(MAX),@query3 AS NVARCHAR(MAX)
select @cols = STUFF((SELECT  ',' + QUOTENAME(Ed.Id) 
					  From sAssessment.tExamMaster E
					  INNER JOIN sAssessment.tExamDetail Ed ON Ed.ExamId =E.Id 
					  AND ClassId = @rClassId AND E.Id =  @rExamId 
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')
set @query = 'SELECT AcademicId,ResultId,0 AS ResultDetailId, ExamId,Name,RollNo,Code,IsMarkInDecimal, ' + @cols + '
FROM
(
Select ISNULL(RD.Obtain,0) AS Obtain,ED.Id AS ExamDetailId,A.AcademicId,ED.ExamId,A.Name,A.RollNo,
A.Code,ISNULL(R.Id,0) AS ResultId,ISNULL(EM.IsMarksInDecimal,0) AS IsMarkInDecimal
FROM sStudent.vStudentAcademic A 
INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId=CM.Id AND A.DivisionId=DM.Id
INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
LEFT JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.AcademicId
INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
LEFT JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
WHERE A.StatusId =1 AND A.BatchId = '+ CONVERT(nvarchar(15),@rBatchId) + ' AND A.ClassId= ' + convert(nvarchar(15),@rClassId) +  '  And A.DivisionId= ' + convert(nvarchar(15),@rDivisionId) + ' And  ED.ExamId = ' + convert(nvarchar(15),@rExamId) + '
) MAIN
PIVOT
(
	MAX(Obtain)
FOR ExamDetailId IN (' + @cols + ')
)pvt Order by RollNo,Code,Academicid'
--print (@query)
execute(@query)
		
END
GO
PRINT N'Altering [sAssessment].[pMarkEntryGenerate]...';


GO


ALTER PROCEDURE [sAssessment].[pMarkEntryGenerate]
	 	
	@rExamId int,
	@rClassId int,
	@rDivisionId int,
	@rExamList nvarchar(500),
	@rOrgId int,
	@rBatchId int 	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

DECLARE @loDoc INT
BEGIN
	BEGIN TRY
	 BEGIN	
	 DECLARE @lNextNumber BIGINT 
	 DECLARE @lResultId BIGINT
	 DECLARE @lCount INT
	 DECLARE @lMarkInDecimal bit
	 Declare @lExamId BigInt
	 DECLARE @Query nvarchar(max)
	 
------- Result Master Entry	 
     IF NOT EXISTS (SELECT 1 FROM sAssessment.tResult R INNER JOIN sStudent.tAcademic A ON A.Id = R.AcademicId AND A.BatchId=@rBatchId
				AND R.ExamId=@rExamId AND A.ClassId=@rClassId AND (A.DivisionId=@rDivisionId OR @rDivisionId=0))		
	BEGIN
	
		EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAssessment.tResult', 0, 1, 1,@outNextNumber = @lNextNumber output	
		
		INSERT INTO sAssessment.tResult (Id,ExamId,AcademicId,TotalMarks,TotalObtain,ResultStatus,ResultGrade,ResultGradePoint,
		RankNumber,Percentage,Percentile,ResultRemark,OtherRemark1,UpdatedUserId,UpdatedDateTime) 
		
		SELECT @lNextNumber + ROW_NUMBER() OVER(ORDER BY A.AcademicId) AS Id,@rExamId,A.AcademicId,0,0,'','',0,0,0,0,'','',1,GETDATE() 
		From sStudent.vStudentAcademic A
		Where A.ClassId=@rClassId AND (A.DivisionId=@rDivisionId OR @rDivisionId=0) AND A.StatusId=1 AND A.BatchId=@rBatchId
		
		SELECT @lCount = COUNT(1) FROM sStudent.vStudentAcademic WHERE ClassId=@rClassId AND (DivisionId=@rDivisionId OR @rDivisionId =0) AND BatchId=@rBatchId
		SET @lNextNumber  = @lCount + @lNextNumber 
		
		EXECUTE sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sAssessment.tResult', @rCurrentNumber = @lNextNumber
			
	END
 --------- Result Detail Entry  
  
    IF EXISTS (SELECT 1 FROM sAssessment.tResultDetail RD 
    INNER JOIN sAssessment.tResult R ON R.Id=RD.ResultId AND R.ExamId=@rExamId
    INNER JOIN sStudent.vStudentAcademic A ON A.AcademicId=R.AcademicId AND A.ClassId = @rClassId AND A.BatchId=@rBatchId
    AND (A.DivisionId=@rDivisionId OR @rDivisionId = 0)
    )
    BEGIN	

		SET @Query = '  UPDATE RD SET RD.OBTAIN =  (A.OBTAIN/Maxi)*ED.Maximum FROM
						(SELECT 
						Sum(Obtain) AS Obtain,Sum(Maximum) AS Maxi,RM.AcademicId,ED.ClassSubjectId
						FROM sAssessment.tResult RM 
							INNER JOIN sAssessment.tResultDetail RD ON RD.ResultId=RM.Id
							INNER JOIN sAssessment.tExamMaster EM ON EM.Id = RM.ExamId
							INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = RM.AcademicId AND SA.BatchId = ' + CONVERT(nvarchar,@rBatchId) + ' AND SA.ClassId = ' + CONVERT(nvarchar,@rClassId) + '
							AND (SA.DIVISIONID= ' + CONVERT(NVARCHAR,@RDivisionId) + ' OR ' +  CONVERT(NVARCHAR,@RDivisionId)+ ' = 0 )
							INNER JOIN sAssessment.tExamDetail ED ON RD.ExamDetailId=ED.Id AND ED.ExamId = EM.Id
							WHERE RM.ExamId IN ' + @rExamList + '  
						GROUP BY RM.AcademicId,ED.ClassSubjectId) A
					INNER JOIN sAssessment.tResult R ON R.AcademicId =A.AcademicId
					INNER JOIN sAssessment.tResultDetail RD ON RD.ResultId = R.Id
					INNER JOIN sAssessment.tExamMaster EM ON EM.Id = R.ExamId
					INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = R.AcademicId AND SA.ClassId = ' + CONVERT(nvarchar,@rClassId) + '
					AND (SA.DIVISIONID= ' + CONVERT(NVARCHAR,@RDivisionId) + ' OR ' +  CONVERT(NVARCHAR,@RDivisionId)+ ' = 0 )
					INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId = EM.Id  AND ED.ClassSubjectId=A.ClassSubjectId 
					AND RD.ExamDetailId=ED.Id AND ED.ExamId = ' + CONVERT(nvarchar,@rExamId)
		EXECUTE(@query)
		--PRINT(@Query)
    END
   ELSE
	BEGIN
		EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAssessment.tResultDetail', 0, 1, 1,@outNextNumber = @lNextNumber output	
				
				SET @Query = 'INSERT INTO sAssessment.tResultDetail (Id,ResultId,ExamDetailId,IsPresent,Obtain) 
						SELECT ' + CONVERT(NVARCHAR,@lNextNumber) + ' + ROW_NUMBER() OVER(ORDER BY ED1.ClassSubjectId) AS Id,
						R.Id,ED1.Id AS ExamDetailId,1 AS IsPresent,
						CASE WHEN  (SELECT Sum(ISNULL(Obtain,0))/SUM(Maximum)  AS Obtain FROM sAssessment.tResult RM 
						INNER JOIN sAssessment.tResultDetail RD ON RD.ResultId=RM.Id
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id = RM.ExamId
						
						INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = RM.AcademicId AND SA.BatchId = ' + CONVERT(nvarchar,@rBatchId) + ' AND SA.ClassId = ' + CONVERT(NVARCHAR,@rClassId) + '
						AND (SA.DIVISIONID= ' + CONVERT(NVARCHAR,@rDivisionId) + ' OR ' + CONVERT(NVARCHAR,@rDivisionId) + ' = 0 )
						INNER JOIN sAssessment.tExamDetail ED ON RD.ExamDetailId=ED.Id AND ED.ExamId = EM.Id
						INNER JOIN sAssessment.tOptionalSubject OS ON OS.AcademicId = SA.AcademicId AND OS.ClassSubjectId = ED.ClassSubjectId 
						WHERE RM.ExamId IN ' + @rExamList + ' AND RM.AcademicId = R.AcademicId AND ED.ClassSubjectId= ED1.ClassSubjectId
					    GROUP BY RM.AcademicId,ED.ClassSubjectId) * ED1.Maximum IS NULL THEN 0 ELSE 
						
						(SELECT Sum(ISNULL(Obtain,0))/SUM(Maximum)  AS Obtain FROM sAssessment.tResult RM 
						INNER JOIN sAssessment.tResultDetail RD ON RD.ResultId=RM.Id
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id = RM.ExamId
						INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = RM.AcademicId AND SA.ClassId = ' + CONVERT(NVARCHAR,@rClassId) + '
						AND (SA.DIVISIONID= ' + CONVERT(NVARCHAR,@rDivisionId) + ' OR ' + CONVERT(NVARCHAR,@rDivisionId) + ' = 0 )
						INNER JOIN sAssessment.tExamDetail ED ON RD.ExamDetailId=ED.Id AND ED.ExamId = EM.Id
						INNER JOIN sAssessment.tOptionalSubject OS ON OS.AcademicId = SA.AcademicId AND OS.ClassSubjectId = ED.ClassSubjectId 
						WHERE RM.ExamId IN ' + @rExamList + ' AND RM.AcademicId = R.AcademicId AND ED.ClassSubjectId= ED1.ClassSubjectId
					    GROUP BY RM.AcademicId,ED.ClassSubjectId) END  * ED1.Maximum  AS OBTAIN
					FROM 	sAssessment.tResult R 
							INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = R.AcademicId AND SA.ClassId = ' + CONVERT(NVARCHAR,@rClassId) + '
							INNER JOIN sAssessment.tExamDetail ED1 ON ED1.ExamId = R.ExamId
							AND (SA.DIVISIONID= ' + CONVERT(NVARCHAR,@rDivisionId) + ' OR ' + CONVERT(NVARCHAR,@rDivisionId) + ' = 0 )					
							and R.ExamId=' + CONVERT(NVARCHAR,@rExamId)
			
								
		--print(@Query)
		execute(@Query)
		
		SELECT @lCount = COUNT(RD.Id) FROM sAssessment.tResultDetail RD 
		INNER JOIN sAssessment.tResult R ON RD.ResultId = R.Id AND R.ExamId=@rExamId 
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.AcademicId AND SA.ClassId=@rClassId AND (SA.DivisionId=@rDivisionId OR @rDivisionId =0) AND SA.BatchId=@rBatchId
		SET @lNextNumber  = @lCount + @lNextNumber 
		
		EXECUTE sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sAssessment.tResultDetail', @rCurrentNumber = @lNextNumber 
	
	END
		SELECT 1 AS RESULT
   END
   COMMIT TRANSACTION
	END TRY

	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
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
	 --,@rcolumn_visible bit
	 
	

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
 begin
 

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

 
  
DECLARE @GradeString nvarchar(1000),
@GradeSetId int , @IsIncludeSubExam bit
SELECT @GradeSetId = GradesetId,
	   @IsIncludeSubExam = ISNULL(IsIncludeSubExam,0)  FROM sAssessment.tExamMaster WHERE Id = @rExamId
SELECT @GradeString = [sAssessment].[fGradeStringGet](@GradeSetId)
 
--#TempAllExam
	CREATE TABLE #TempAllExam
	(
		AcademicIdText nvarchar(20),
		ExamIdText nvarchar(20),
		CoScholasticScopeIdText nvarchar(20),
		
		AcademicId bigint,
		ExamName Nvarchar(150),
		StudCode NVarchar(20),
		StudentName Nvarchar(150),
		RollNo int,
		ResultStatus Nvarchar(20),	
		ClassName NVarchar(50),		
		Division NVarchar(50),
		TotalMark decimal(8,2),
		TotalObtain decimal(8,2),
		Percentage decimal(8,2),
		RankNumber int,
		ResultGrade NVarchar(50),
		
		MaximumMark1 decimal(8,2),		
		SubjectGrade1 NVarchar(50),
		Obtain1 decimal(8,2),
		ExamMaximum1 decimal(8,2),
		IsPresent1 bit,
						
		MaximumMark2 decimal(8,2),	
		SubjectGrade2 NVarchar(50),
		Obtain2 decimal(8,2),
		ExamMaximum2 decimal(8,2),
		IsPresent2 bit,
				
		MaximumMark3 decimal(8,2),
		SubjectGrade3 NVarchar(50),
		Obtain3 decimal(8,2),
		ExamMaximum3 decimal(8,2),
		IsPresent3 bit,		
		
		MaximumMark4 decimal(8,2),	
		SubjectGrade4 NVarchar(50),
		Obtain4 decimal(8,2),
		ExamMaximum4 decimal(8,2),
		IsPresent4 bit,	
				
		MaximumMark5 decimal(8,2),		
		SubjectGrade5 NVarchar(50),
		Obtain5 decimal(8,2),
		ExamMaximum5 decimal(8,2),
		IsPresent5 bit,	
				
		MaximumMark6 decimal(8,2),		
		SubjectGrade6 NVarchar(50),
		Obtain6 decimal(8,2),
		ExamMaximum6 decimal(8,2),
		IsPresent6 bit,	
		
		MaximumMark7 decimal(8,2),		
		SubjectGrade7 NVarchar(50),
		Obtain7 decimal(8,2),
		ExamMaximum7 decimal(8,2),
		IsPresent7 bit,	
		
		MaximumMark8 decimal(8,2),	
		SubjectGrade8 NVarchar(50),
		Obtain8 decimal(8,2),
		ExamMaximum8 decimal(8,2),
		IsPresent8 bit,	
		
		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,	
		
		 
		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),
		
		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),
		
		
		IsDisplayParentName bit,
		FatherName nvarchar(30),
		MotherName nvarchar(30),
		IsShowSubjectMark bit, 
		IsOptionalSubject bit,
		CoScholasticScopeId tinyint,
		IsDisplayPrincipalSign bit,
		IsDisplayTeacherSign bit,
		EmployeeSign varbinary(max),
		Batch nvarchar(100),
		ExamNameTerm1 NVarchar(100),
		ExamNameTerm2 NVarchar(100) 
		 
		
	)	
	 --print 'temp created'    	
	INSERT INTO  #TempAllExam 
	(
	AcademicIdText,
	ExamIdText,
	CoScholasticScopeIdText,
	
	AcademicId,
	ExamName,
	StudCode,
	StudentName,
	RollNo,
	ResultStatus,
	ClassName,
	Division,
	TotalMark,
	TotalObtain,
	Percentage,
	RankNumber,
	ResultGrade,
	IsMarksInDecimal,
	column_visible,
	--Obtain,
	Percentile,
	--ClassSubject,
	ResultDetailId,
	ResultId,

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


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

		ISNULL(EM.Remark1,'') AS Remark1,
		ISNULL(EM.Remark2,'') AS Remark2,
		ISNULL(EM.Remark3,'') AS Remark3,
		EM.DisplayTitle,
		EM.IsRankNo, 
		EM.IsGrade,
		EM.IsPercentile,
		EM.IsPercentage,
		EM.IsSubjectPercentile,
		EM.IsProcessResult,
		EM.IsNegativeMarks,
		EM.IsIncludeCoScholastic,
		EM.IsOnPrePrinted,
		EM.IsDisplayPhoto,
		EM.IsDisplayBirthDate,
		EM.IsLockForEdit,
		EM.IsDisplaySchoolName,			
		EM.IsDisplayAttendance,
		EM.IsDisplayHeightWeight,
		EM.IsResultStatus,
		REPLICATE(',',EM.FooterAdjustment) AS FooterAdjustmentText,
		REPLICATE(',',EM.DetailAdjustment) AS DetailAdjustmentText,
		EM.FooterAdjustment,
		EM.DetailAdjustment,
		ISNULL(R.ResultRemark,'') AS ResultRemark,
		SO.DateOfBirth,
		AD.HeightTerm1,
		AD.WeightTerm1,
		AD.HeightTerm2,
		AD.WeightTerm2,
		AD.HeightAnnual,
		AD.WeightAnnual,
		AD.PresentDaysTerm1,
		AD.PresentDaysTerm2,
		AD.PresentDaysAnnual,
		AD.TotalDaysTerm1,
		AD.TotalDaysTerm2,
		AD.TotalDaysAnnual,
		EM.TermScopeId,
		SI.StudentPhoto,
		@GradeString AS GradeString,
		EM.IsDisplayGradeString,
		ED.IsDisplayInMarksheet,
		ED.IsShowSubjectGrade,
		ED.IsIncludeInTotal,
	    ED.ClassSubjectId,
		CS.SubjectId AS SubjectId,
		--ED.Maximum,
		(CASE ISNULL(ED.DisplayOrder,0)
		WHEN 0 THEN CS.OrderIndex
		ELSE ED.DisplayOrder END) AS SubjectOrderIndex,
		
		--SM.OrderIndex AS SubjectOrderIndex,
		RD.SubjectGrade,
		SM.Title AS SubjectName,
		ISNULL(SM.Code,'') AS SubjectCode,
		ED.Minimum,
		ED.Maximum,
		RD.Obtain,
		SR.ResultRemark1,
		SR.ResultRemark2,
		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,
		EI.EmployeeSign,
		BM.Title AS Batch 
		
		
		 
			
FROM 
	sAssessment.tResultDetail RD
	INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
	INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId		
	INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
	INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId					 
	INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
	INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
	INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
	INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
	INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
	LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = Dm.InchargeEmployeeId
	
	INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.EXAMSUBGROUPID
	LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=StuM.Id
	LEFT JOIN sStudent.tAcademicDetail AD ON AD.AcademicId=A.Id
	LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=StuM.Id
	LEFT JOIN sAssessment.tStudentRemark SR ON R.AcademicId = SR.AcademicId AND R.ExamId = SR.ExamId
	LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = StuM.Id
	LEFT JOIN sAssessment.tOptionalSubject OS ON OS.AcademicId = R.AcademicId AND OS.ClassSubjectId = ED.ClassSubjectId  AND ED.ExamId = R.ExamId
	
	--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
 

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

 
  
DECLARE @GradeString nvarchar(1000),
@GradeSetId int , @IsIncludeSubExam bit
SELECT @GradeSetId = GradesetId,
	   @IsIncludeSubExam = ISNULL(IsIncludeSubExam,0)  FROM sAssessment.tExamMaster WHERE Id = @rExamId
SELECT @GradeString = [sAssessment].[fGradeStringGet](@GradeSetId)
 
--#TempAllExam
	CREATE TABLE #TempAllExam
	(
		AcademicIdText nvarchar(20),
		ExamIdText nvarchar(20),
		CoScholasticScopeIdText nvarchar(20),
		
		AcademicId bigint,
		ExamName Nvarchar(150),
		StudCode NVarchar(20),
		StudentName Nvarchar(150),
		RollNo int,
		ResultStatus Nvarchar(20),	
		ClassName NVarchar(50),		
		Division NVarchar(50),
		TotalMark decimal(8,2),
		TotalObtain decimal(8,2),
		Percentage decimal(8,2),
		RankNumber int,
		ResultGrade NVarchar(50),
		
		--MaximumMark1 decimal(8,2),		
		SubjectGrade1 NVarchar(50),
		--Obtain1 decimal(8,2),
		--ExamMaximum1 decimal(8,2),
		IsPresent1 bit,
						
		MaximumMark2 decimal(8,2),	
		SubjectGrade2 NVarchar(50),
		Obtain2 decimal(8,2),
		ExamMaximum2 decimal(8,2),
		IsPresent2 bit,
				
		MaximumMark3 decimal(8,2),
		SubjectGrade3 NVarchar(50),
		Obtain3 decimal(8,2),
		ExamMaximum3 decimal(8,2),
		IsPresent3 bit,		
		
		MaximumMark4 decimal(8,2),	
		SubjectGrade4 NVarchar(50),
		Obtain4 decimal(8,2),
		ExamMaximum4 decimal(8,2),
		IsPresent4 bit,	
				
		MaximumMark5 decimal(8,2),		
		SubjectGrade5 NVarchar(50),
		Obtain5 decimal(8,2),
		ExamMaximum5 decimal(8,2),
		IsPresent5 bit,	
				
		MaximumMark6 decimal(8,2),		
		SubjectGrade6 NVarchar(50),
		Obtain6 decimal(8,2),
		ExamMaximum6 decimal(8,2),
		IsPresent6 bit,	
		
		MaximumMark7 decimal(8,2),		
		SubjectGrade7 NVarchar(50),
		Obtain7 decimal(8,2),
		ExamMaximum7 decimal(8,2),
		IsPresent7 bit,	
		
		MaximumMark8 decimal(8,2),	
		SubjectGrade8 NVarchar(50),
		Obtain8 decimal(8,2),
		ExamMaximum8 decimal(8,2),
		IsPresent8 bit,	
		
		SubjectGradeTerm1 NVarchar(50),
		SubjectGradeTerm2 NVarchar(50),
		IsMarksInDecimal bit,
		column_visible bit,
		--Obtain decimal(5,2),
		Percentile decimal(5,2),
		--ClassSubject nvarchar(100),
		ResultDetailId bigint,
		ResultId bigint,	
		Remark1 nvarchar(150),
		Remark2 nvarchar(150),
		Remark3 nvarchar(150),
		DisplayTitle nvarchar(150),		
		IsRankNo bit, 
		IsGrade bit,
		IsPercentile bit,
		IsPercentage bit,
		IsSubjectPercentile bit,
		IsProcessResult bit,
		IsNegativeMarks bit,
		IsIncludeCoScholastic bit,
		IsOnPrePrinted bit,
		IsDisplayPhoto bit,
		IsDisplayBirthDate bit,
		IsLockForEdit bit,
		IsDisplaySchoolName bit,			
		IsDisplayAttendance bit,
		IsDisplayHeightWeight bit,
		IsResultStatus bit,
		FooterAdjustmentText nvarchar(max),
		DetailAdjustmentText nvarchar(max),
		FooterAdjustment smallint,
		DetailAdjustment smallint,
		ResultRemark nvarchar(200),
		DateOfBirth date,
		HeightTerm1 decimal(5,2),
		WeightTerm1 decimal(5,2),
		HeightTerm2 decimal(5,2),
		WeightTerm2 decimal(5,2),
		HeightAnnual decimal(5,2),
		WeightAnnual decimal(5,2),
		PresentDaysTerm1 smallint,
		PresentDaysTerm2 smallint,
		PresentDaysAnnual smallint,
		TotalDaysTerm1 smallint,
		TotalDaysTerm2 smallint,
		TotalDaysAnnual smallint,
		TotalMarkTerm1 decimal(8,2),
		TotalObtainTerm1 decimal(8,2),
		PercentageTerm1 decimal(8,2),
		RankNumberTerm1 int,
		ResultGradeTerm1 NVarchar(50),
		PercentileTerm1 decimal(8,2),
		ResultStatusTerm1 Nvarchar(20),		   
		TotalMarkTerm2 decimal(8,2),
		TotalObtainTerm2 decimal(8,2),
		PercentageTerm2 decimal(8,2),
		RankNumberTerm2 int,
		ResultGradeTerm2 NVarchar(50),
		PercentileTerm2 decimal(8,2),
		ResultStatusTerm2 Nvarchar(20), 
		TermScopeId tinyint,		 
		StudentPhoto varbinary(max),
		GradeString nvarchar(1000),
		IsDisplayGradeString bit,		 
		IsDisplayInMarksheet bit,
		IsShowSubjectGrade bit,
		IsIncludeInTotal bit,
		ClassSubjectID int,
		SubjectId int,
		--Maximum decimal(5,2),
		SubjectOrderIndex smallint,
		SubjectGrade NVarchar(50),
		SubjectName NVarchar(150),
		SubjectCode Nvarchar(50),	
		SubjectMinimum decimal(8,2),		
		SubjectMaximum decimal(8,2),
		SubjectObtain  decimal(8,2),
		
		Exam1Name Nvarchar(150),		
		TotalMarks1 decimal(8,2),		
		TotalObtain1 decimal(8,2),
		Percentage1 decimal(8,2),
		RankNumber1 int,
		ResultGrade1 NVarchar(50),
		Percentile1 decimal(8,2),
		ResultStatus1 Nvarchar(20),
		
		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
		

	)	
	
	 --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
	
 
	 
	)
	
	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 
		
		
		
		 
			 
			
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
	
	--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 
				    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
				
				
				 
			FROM 
			 sAssessment.tCCESubjectActivityMaster SAM 	
			INNER JOIN sAssessment.tCCESubjectSubActivityMaster SSA ON SAM.Id=SSA.SubjectActivityId  
			INNER JOIN sAssessment.vCCEExamClassSubject CS ON CS.ClassSubjectId=SAM.ClassSubjectId
			INNER JOIN sSetup.tClassMaster CMM ON CMM.Id=CS.ClassId 
			 INNER JOIN sStudent.vStudentAcademic SA ON  SA.ClassId = CS.ClassId 
			 INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=SA.StudentId			 
			 LEFT JOIN sAssessment.tCCESubjectSubActivityExamScore AIS ON AIS.AcademicId =SA.AcademicId AND AIS.SubjectSubActivityId= SSA.Id  	
			 LEFT JOIN sAssessment.tExamMaster EM ON EM.Id=AIS.ExamId  
		     LEFT  JOIN sStudent.tStudentOther SO ON SO.StudentId=SA.StudentId
		    LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=SA.StudentId	
		    INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId	
		   INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=SA.divisionId
		    LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = Dm.InchargeEmployeeId
	
		    LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SA.StudentId
		    LEFT JOIN sAssessment.tStudentRemark SR ON SA.AcademicId = SR.AcademicId	AND EM.Id = SR.ExamId

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


GO

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

BEGIN 	
 
			SELECT 		
				 
				 @rBuilder1 AS Builder1,
				 SA.AcademicId,
				 SA.RollNo,
				 SA.Number,
				 SA.Name,
				  
				 ISNULL(AIS.Marks,0) AS Marks,
				 
				 SAM.Title AS SubjectActivityTitle,
				 SSA.Title AS SubjectSubActivityTitle,
				 SAM.Id AS ActivityId,
				 SSA.Id AS SubjectSubActivityId,
				 SAM.OrderIndex AS ActivityOrderIndex,
				 SSA.OrderIndex AS SubjectSubActivityOrderIndex,
				 SM.Title AS SubjectTitle,
				 SAM.ClassSubjectId,
				 AIS.DescriptiveIndicator,
				 CS.OrderIndex AS SubOrderIndex
				 
			FROM 
			  sAssessment.tCCESubjectActivityMaster SAM 	
			INNER JOIN sAssessment.tCCESubjectSubActivityMaster SSA ON SAM.Id=SSA.SubjectActivityId  
			INNER JOIN sAssessment.vCCEExamClassSubject CS ON CS.ClassSubjectId=SAM.ClassSubjectId
			
			INNER JOIN sSetup.tClassMaster CMM ON CMM.Id=CS.ClassId 
			INNER JOIN sStudent.vStudentAcademic SA ON   SA.ClassId = CMM.Id 
			LEFT JOIN sAssessment.tCCESubjectSubActivityExamScore AIS ON AIS.AcademicId =SA.AcademicId AND AIS.SubjectSubActivityId= SSA.Id And AIS.ExamId=@rExamId
			 INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId
			 WHERE
				 ((SAM.ClassSubjectId=@rClass) OR (@rClass=0))
				And SA.DivisionId =@rDivisionID	
				And SA.BatchId =@rBatchId
				--AND AIS.ExamId=@rExamId
				and ((SSA.SubjectActivityId=@rActivityId) OR (@rActivityId=0))
				AND((SSA.Id=@rSubjectSubActivityId) OR (@rSubjectSubActivityId=0))	
				and SSA.OrgId=@rOrgId
				AND  SA.StatusId = 1		
		 
			 ORDER BY SA.RollNo
			
 
END
GO
PRINT N'Altering [sAssessment].[pRptSubjectActivityExamMarkGet]...';


GO

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

BEGIN 	
 
			SELECT 		
				 
				 @rBuilder1 AS Builder1,
				 SA.AcademicId,
				 SA.RollNo,
				 SA.Number,
				 SA.Name,
				  
				 ISNULL(AIS.Marks,0) AS Marks,
				 
				 SAM.Title AS SubjectActivityTitle,
				 SSA.Title AS SubjectSubActivityTitle,
				 SAM.Id AS ActivityId,
				 SSA.Id AS SubjectSubActivityId,
				 SAM.OrderIndex AS ActivityOrderIndex,
				 SSA.OrderIndex AS SubjectSubActivityOrderIndex,
				 SM.Title AS SubjectName,
				 SAM.ClassSubjectId 
				 
			FROM 
			  sAssessment.tCCESubjectActivityMaster SAM 	
			INNER JOIN sAssessment.tCCESubjectSubActivityMaster SSA ON SAM.Id=SSA.SubjectActivityId  
			INNER JOIN sAssessment.vCCEExamClassSubject CS ON CS.ClassSubjectId=SAM.ClassSubjectId
			
			INNER JOIN sSetup.tClassMaster CMM ON CMM.Id=CS.ClassId 
			INNER JOIN sStudent.vStudentAcademic SA ON   SA.ClassId = CMM.Id 
			LEFT JOIN sAssessment.tCCESubjectSubActivityExamScore AIS ON AIS.AcademicId =SA.AcademicId AND AIS.SubjectSubActivityId= SSA.Id And AIS.ExamId=@rExamId
			 INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId
			 WHERE
				 ((SAM.ClassSubjectId=@rClass) OR (@rClass=0))
				And SA.DivisionId =@rDivisionID	
				And SA.BatchId =@rBatchId
				--AND AIS.ExamId=@rExamId
				and ((SSA.SubjectActivityId=@rActivityId) OR (@rActivityId=0))
				AND((SSA.Id=@rSubjectSubActivityId) OR (@rSubjectSubActivityId=0))	
				and SSA.OrgId=@rOrgId
				AND  SA.StatusId = 1		
		 
			 ORDER BY SA.RollNo
			
 
END
GO
PRINT N'Altering [sAssessment].[pRptSubjectActivityExamScoreGet]...';


GO

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

BEGIN 	
BEGIN TRY
			SELECT 		
				 
				 @rBuilder1 AS Builder1,
				 SA.AcademicId,
				 SA.RollNo,
				 SA.Number,
				 SA.Name,
				  
				 ISNULL(AIS.Grade,'') AS Term1Indicator,
				 SAM.Title AS SubjectActivityTitle,
				 SSA.Title AS SubjectSubActivityTitle,
				 SAM.Id AS ActivityId,
				 SSA.Id AS SubjectSubActivityId,
				 SAM.OrderIndex AS ActivityOrderIndex,
				 SSA.OrderIndex AS SubjectSubActivityOrderIndex
				 
			FROM 
			 	
			 sAssessment.tCCESubjectActivityMaster SAM 	
			INNER JOIN sAssessment.tCCESubjectSubActivityMaster SSA ON SAM.Id=SSA.SubjectActivityId  
			INNER JOIN sAssessment.vCCEExamClassSubject CS ON CS.ClassSubjectId=SAM.ClassSubjectId
			INNER JOIN sSetup.tClassMaster CMM ON CMM.Id=CS.ClassId 
			INNER JOIN sStudent.vStudentAcademic SA ON   SA.ClassId = CMM.Id 
			LEFT JOIN sAssessment.tCCESubjectSubActivityExamScore AIS ON AIS.AcademicId =SA.AcademicId  AND AIS.SubjectSubActivityId= SSA.Id  And AIS.ExamId=@rExamId
			
			 WHERE
				 SAM.ClassSubjectId=@rClassSubjectId 
				And SA.DivisionId =@rDivisionID	
				And SA.BatchId =@rBatchId	
				AND AIS.ExamId=@rExamId
				and ((SSA.SubjectActivityId=@rActivityId) OR (@rActivityId=0))
				AND((SSA.Id=@rSubjectSubActivityId) OR (@rSubjectSubActivityId=0))	
				and SSA.OrgId=@rOrgId
				AND  SA.StatusId = 1
						
		 
			 ORDER BY SA.RollNo
			
END TRY
BEGIN CATCH
	SELECT -1 AS RESULT
END CATCH
END
GO
PRINT N'Altering [sAttendance].[pDeleteAttendance]...';


GO


ALTER PROCEDURE [sAttendance].[pDeleteAttendance]
	 
		@rAttendanceTypeId int=0,	 
		@rClassId int=0,
		@rDivisionId int=0,	
		@rSubjectId int=0,
		@rAcademicId bigint,
		@rBatchId int=0,	 
		@rOrgId int=0,
		@rOrgGroupBatchId int=0,
		@rStatusId int=0, 
	    @rCode nvarchar(20)='',
	    @rDeleteType nvarchar(20)='',
	    @rFromAttendanceDate Date ='',
	    @rToAttendanceDate Date ='',
	    @rRepeatCount tinyint=0
	    
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 	

IF (@rDeleteType = 'DayRegister')

BEGIN

DELETE sAttendance.tStudentRegister
		FROM sAttendance.tStudentRegister SR
		INNER JOIN sStudent.tAcademic vSA 
		ON vSA.ID=SR.AcademicId
	WHERE 
		SR.AttendanceTypeId=@rAttendanceTypeId
		AND ((SR.AttendanceDate >= @rFromAttendanceDate))
		AND ((SR.AttendanceDate <= @rToAttendanceDate))
		AND ((vSA.ClassId=@rClassId) OR (@rClassId=0))
		AND ((vSA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((SR.SubjectId=@rSubjectId) OR (@rSubjectId=0))
		AND ((SR.AcademicId=@rAcademicId) OR (@rAcademicId=0))
		AND ((SR.RepeatCount=@rRepeatCount) OR (@rRepeatCount=0))
		AND vSA.BatchId=@rBatchId
END

IF(@rDeleteType = 'MonthlyRegister')

BEGIN

DELETE sAttendance.tMonthlyRegister
		FROM sAttendance.tMonthlyRegister MR
		INNER JOIN sStudent.tAcademic vSA 
		ON vSA.Id=MR.AcademicId
	WHERE 
		MR.AttendanceTypeId=@rAttendanceTypeId
		AND ((vSA.ClassId=@rClassId) OR (@rClassId=0))
		AND ((vSA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((MR.SubjectId=@rSubjectId) OR (@rSubjectId=0))
		AND ((MR.AcademicId=@rAcademicId) OR (@rAcademicId=0))
		AND vSA.BatchId=@rBatchId
		
		
		
		DELETE sAttendance.tYearlyRegister
		FROM sAttendance.tYearlyRegister MR
		INNER JOIN sStudent.tAcademic vSA 
		ON vSA.Id=MR.AcademicId
	WHERE 
		 
		  ((vSA.ClassId=@rClassId) OR (@rClassId=0))
		AND ((vSA.DivisionId=@rDivisionId) OR (@rDivisionId=0))		 
		AND ((MR.AcademicId=@rAcademicId) OR (@rAcademicId=0))
		AND vSA.BatchId=@rBatchId
END

IF(@rDeleteType = 'StudentSetup')

BEGIN

DELETE sAttendance.tStudentSetup
		FROM sAttendance.tStudentSetup SS
		INNER JOIN sStudent.vStudentAcademic vSA 
		ON vSA.AcademicId=SS.AcademicId
	WHERE 
	    (vSA.ClassId=@rClassId) OR (@rClassId=0)
		AND ((vSA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((SS.AcademicId=@rAcademicId) OR (@rAcademicId=0))
		AND vSA.BatchId=@rBatchId
END

SELECT 1 AS Result

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


GO
ALTER PROCEDURE [sAttendance].[pStudentRegisterXMLInsert]
	
	@rStrXml nvarchar(MAX),
    @rOrgId int,
    @rClassId int=0,
    @rDivisionId int,
    @rAttendanceDate date='',
    @rAttendanceTypeId tinyint,
    @rCreatedUserId bigint,
    @rSubjectId int=0,
    @rRepeatCount tinyint=0,
    @rBatchId int=0
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET @rStrXml=REPLACE(@rStrXml,'&','AND')
DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION 
	 BEGIN
	 
	 DELETE SR FROM sAttendance.tStudentRegister SR 
	 INNER JOIN sStudent.tAcademic SA ON SA.Id = SR.AcademicId
	 --INNER JOIN (SELECT AcademicId FROM OPENXML(@loDoc, '/Table/RowData', 1)
	 --WITH
	 --(AcademicId bigint))A ON SR.AcademicId = A.AcademicId 
	    WHERE 
	    SR.AttendanceTypeId = @rAttendanceTypeId AND SR.AttendanceDate = @rAttendanceDate
	    --AND SA.ClassId = @rClassId 
	    AND SA.DivisionId=@rDivisionId 
	    AND SA.OrgId = @rOrgId 
	    AND ((SR.SubjectId = @rSubjectId) OR (@rSubjectId=0))
	    AND ((SR.RepeatCount = @rRepeatCount) OR (@rRepeatCount=0))
	    AND SA.BatchId =@rBatchId
	 
	 INSERT INTO sAttendance.tStudentRegister 
		(
			AcademicId,
			EmployeeId,
			AttendanceTypeId,
			AttendanceDate,
			SubjectId,
			RepeatCount,
			IsPresent,
			AbsentReasonId,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime
			)
		SELECT		
			AcademicId,
			EmployeeId,
			@rAttendanceTypeId,
			@rAttendanceDate,
			@rSubjectId,
			@rRepeatCount,
			IsPresent,
			AbsentReasonId,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rCreatedUserId,
			sCommon.fGetDate()
						
		FROM OPENXML (@loDoc, '/Table/RowData', 1)
		WITH ( 
				AcademicId bigint,
				EmployeeId bigint,
				IsPresent bit,
				AbsentReasonId int
			  )		
		
        SELECT 1 AS Result
	 END	
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [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
           	
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
				)
				VALUES
				(	@lNextNumber
				   ,@rAcademicId
				   ,@rLCNumber
				   ,@rLCDate
				   ,@rLeftDate
				   ,@rLCCopy
				   ,@rLCRemark
				   ,@rLCProgress
				   ,@rLCConduct
				   ,@rLCReason
				   ,@rLCBookNumber
				   ,@rOrgId
				   ,@rCreatedUserId
				   ,sCommon.fGetDate() 
				)	
				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()
				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].[pRptBonafiedCertificateGet]...';


GO


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

DECLARE @lConfigValue nvarchar(50)

	 SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 124 AND SourceTypeId = 1016 AND SourceId = @rOrgId
	
	if (@lConfigValue IS NULL) OR (@lConfigValue = 'False')
	SET @lIsShowPhoto = 0
	ELSE
	SET @lIsShowPhoto = 1
	
	SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 125 AND SourceTypeId = 1016 AND SourceId = @rOrgId
	
	IF (@lConfigValue IS NULL) OR (@lConfigValue = 'False')
	SET @lIsOnPrePrinted = 0
	ELSE
	SET @lIsOnPrePrinted = 1
	
	
	SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 157 AND SourceTypeId = 1016 AND SourceId = @rOrgId
	
	IF (@lConfigValue IS NULL) OR (@lConfigValue = 'False')
	SET @lIsDisplayReligion = 0
	ELSE
	SET @lIsDisplayReligion = 1
	

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


GO



ALTER PROCEDURE [sCertificate].[pRptCharacterCertificateGet]
	 
	 @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 @lConfigValue nvarchar(50)

DECLARE @lIsDisplayImageHeader bit=0

SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 127 AND SourceTypeId = 1016 AND SourceId = @rOrgId
	
	IF (@lConfigValue IS NULL) OR (@lConfigValue = 'False')
	SET @lIsOnPrePrinted = 0
	ELSE
	SET @lIsOnPrePrinted = 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,
			C.Id,
			C.AcademicId,
			SM.Code,
			SM.FirstName+' '+SM.MiddleName+' '+SM.LastName AS Name,
			CM.DisplayTitle+' - '+DM.DisplayTitle AS Class,
			BM.Title AS Batch,
			SO.DateOfBirth,
			ISNULL(SO.BirthDateInWord,'') AS DOBInWords,
			ISNULL(SO.BirthPlace,'') AS BirthPlace,
			ISNULL(SO.BirthTaluka,'') AS Taluka,
			ISNULL(SO.BirthDistrict,'')	AS District,		
			C.characterDate,
			C.Number,
			ISNULL(SO.FamilyCast,'') AS Caste,
			ISNULL(SO.FamilySubCast,'') AS SubCaste,
			ISNULL(OM.CityName,'') AS City,
			ISNULL(OM.StateName,'') AS CityState,
			SO.GenderId,
			SI.StudentPhoto,
			OM.OrgLogo,
			OM.Title AS OrgName,
			OM.StateName+' '+OM.StreetTwo+' '+OM.StreetThree AS OrgAddress,
			OM.PhoneNo,
			SM.StatusId,
			A.RollNo,
			DM.OrderIndex AS DivisionOrder,
			OM.ReportOrgTitle,
			OM.SmallAddress1,
			OM.SmallAddress2,
			OM.RegistrationDetail,
			@lIsOnPrePrinted AS IsOnPrePrinted,
			@lIsDisplayImageHeader AS IsDisplayImageHeader,
			OI.CertificateHeaderA4  
	FROM 
			sCertificate.tCharacter C
			INNER JOIN sStudent.tAcademic A ON C.AcademicId=A.Id
			LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=A.StudentId
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId
			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
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id=A.BatchId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId
			left JOIN sSetup.tOrgImages OI ON OI.OrgId = OM.Id
	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 ((C.Number=@rNumber) OR (@rNumber=''))
		AND ((C.Number >= @rFromNo) OR (@rFromNo=''))
		AND ((C.Number <= @rToNo) OR (@rToNo=''))
		AND ((C.characterDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((C.characterDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		--Group By C.AcademicId,C.Number,SM.Code,SM.FirstName,SM.LastName,SM.MiddleName,CM.DisplayTitle,BM.Title,SO.DateOfBirth,SO.BirthDateInWord,
		--SO.BirthPlace,SO.BirthTaluka,SO.BirthDistrict,C.characterDate,OM.CityName,OM.StateName,SO.FamilyCast,SO.FamilySubCast,SO.GenderId,SI.StudentPhoto,SM.StatusId,OM.OrgLogo,OM.Title,
		--OM.StreetOne,OM.StreetThree,OM.StreetTwo,OM.PhoneNo
	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 = 126 AND SourceTypeId = 1016 AND SourceId = @rOrgId
	
	IF (@lConfigValue IS NULL) OR (@lConfigValue = 'False')
	SET @lIsOnPrePrinted = 0
	ELSE
	SET @lIsOnPrePrinted = 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,
			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,
			DM.DisplayTitle+' - '+CM.DisplayTitle AS Class,
			@lIsDisplayImageHeader AS IsDisplayImageHeader,
			OI.CertificateHeaderA4  
			
	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
			
	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
DECLARE @lIsDisplayReligion bit=0
DECLARE @lConfigValue nvarchar(50)
DECLARE @lIsDisplayImageHeader bit = 0



SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 128 AND SourceTypeId = 1016 AND SourceId = @rOrgId
	
	IF (@lConfigValue IS NULL) OR (@lConfigValue = 'False')
	SET @lIsOnPrePrinted = 0
	ELSE
	SET @lIsOnPrePrinted = 1
	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(NM.Title,'') AS Nationality,
			--0 As CastCategoryId,
			--ISNULL(SO.CastCategoryId,0) As CastCategoryId,
			ISNULL(RM.Title,'') AS Religion,
			ISNULL(so.BirthPlace,'') AS BirthPlace,
			ISNULL(SO.BirthTaluka,'') AS BirthTaluka,
			ISNULL(SO.BirthDistrict,'') AS BirthDistrict,
			SO.DateOfBirth,
			ISNULL(SO.BirthDateInWord,'') AS BirthDateInWord,
			SA.PreviousSchool,
			SA.AdmissionDate,
			L.LCNumber,
			L.LeftDate,
			L.LCReason,
			L.LCProgress,
			L.LCConduct,
			L.LCRemark,
			L.LCDate,
			SO.GenderId,
			ISNULL(SO.FamilySubCast,'') AS SubCaste,
			ISNULL(SO.FamilyCast,'') AS Caste,
			ISNULL(OM.CityName,'') AS City,
			ISNULL(OM.StateName,'') AS CityState,
			CM.DisplayTitle AS AdmissionStandard,
			CMS.DisplayTitle AS CurrentStandard,
			'' AS CurrentStandardInWords,
			SM.StatusId,
			'' AS Result,
			'' AS FailOrPass,
			'' AS SubjectNAme,
			--ISNULL(SubM.Title,'') AS SubjectNAme,
			'' AS PromotedorNot,
			'' AS PromotedToClass,
			'' AS LastFeesPaid,
			'' AS AnyConcession,
			'' AS NCCScoutDetail,
			'' AS GamesPlayed,
			OM.OrgLogo,
			OM.Title AS OrgTitle,
			OM.StreetOne+' '+OM.StreetTwo+' '+OM.StreetThree AS OrgAddress,
			OM.PhoneNo,
			vSA.RollNo,
			DM.OrderIndex AS DivisionOrder,
			OM.SmallAddress1,
			OM.SmallAddress2,
			OM.RegistrationDetail,
			@lIsOnPrePrinted AS IsOnPrePrinted,
			@lIsDisplayReligion AS IsDisplayReligion,
			AD.PresentDaysAnnual AS PresentDaysSum,
			AD.TotalDaysAnnual AS TotalDaysSum,
			vSA.ClassName AS ClassName,
			vSA.DivisionName AS DivisionName,
			@lIsDisplayImageHeader AS IsDisplayImageHeader,
			OI.CertificateHeaderA4  ,
			isnull(MainCastCategoryId,0) AS CastCategoryId
			
			
			--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.tNationalityMaster NM ON NM.Id=SO.NationalityId
			LEFT JOIN sStudent.tAcademicDetail AD ON AD.AcademicId=vSA.AcademicId
			--LEFT JOIN sSetup.tClassSubject CS ON CS.ClassId=A.ClassId
			--LEFT JOIN sSetup.tSubjectMaster SubM ON SM.Id=CS.SubjectId
			Left JOIN sSetup.tOrgImages OI ON OI.OrgId = OM.Id
			Left JOIN sCommon.tCastCategoryMaster CSM ON CSM.Id=SO.CastCategoryId
	WHERE 
		L.OrgId=@rOrgId
		AND	vSA.BatchId = @rBatchId 
		AND ((SM.Code = @rCode) OR (ISNULL(@rCode,'') = ''))
		AND ((SM.FirstName = @rName) OR (ISNULL(@rName,'') = ''))
		--AND ((L.LCNumber=@rNumber) OR (@rNumber=''))
		AND ((L.LCDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((L.LCDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		--AND ((L.LCDate=@rLCDate) OR (ISNULL(@rLCDate,'')=''))
		--AND ((L.LeftDate=@rLeftDate) OR (ISNULL(@rLeftDate,'')=''))
		--AND ((L.LCCopy=@rLCCopy) OR (@rLCCopy=0))
		--AND ((L.LCBookNumber=@rLCBookNumber) OR (@rLCBookNumber=''))
		AND ((vSA.ClassId=@rClassId) OR(@rClassId=0))
		AND ((vSA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((L.LCNumber=@rLCNumber) OR (@rLCNumber=''))
		AND ((L.LCNumber >= @rFromNo) OR (@rFromNo=''))
		AND ((L.LCNumber <= @rToNo) OR (@rToNo=''))
		--group by MR.PresentCount,MR.TotalCount, SubM.Title, SM.Code,L.AcademicId,SM.FirstName,SM.LastName,SM.MiddleName,SF.FatherName,SF.MotherName,NM.Title,
		--SO.CastCategoryId,RM.Title,so.BirthPlace,SO.BirthTaluka,SO.BirthDistrict,SO.DateOfBirth,SO.BirthDateInWord,SA.PreviousSchool,
		--	SA.AdmissionDate,L.LeftDate,L.LCReason,L.LCProgress,L.LCConduct,L.LCRemark,L.LCDate,SO.GenderId,
		--	OM.CityName,OM.StateName,CM.DisplayTitle,CMS.DisplayTitle,SM.StatusId,OM.OrgLogo,OM.PhoneNo,OM.Title,OM.StreetOne,OM.StreetTwo,OM.StreetThree
	END
GO
PRINT N'Altering [sCommon].[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 CAST(LEFT(Id, 4) AS INT) = @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 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


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

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


GO
ALTER PROCEDURE [sFee].[pAutoAssignAdmissionFee]
	@rAcademicId bigint,	
	@rClassId int,	 
	@rCreatedUserId bigint,
	@rOrgId int,
	@rOrgGroupId int,
	@rBatchId int,	 
	@rAdmissionCategoryId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION

 
DECLARE @lIsAdmissionOptional bit 
DECLARE @lAdmissionHeadId int 
 
 
SELECT @lAdmissionHeadId = FeeHeadId FROM sFee.tFeeMainGroupOrgGroupwise WHERE OrgGroupId = @rOrgGroupId AND FeeMainGroupId = 1


IF (@lAdmissionHeadId > 0)
BEGIN
 
 
SELECT  @lIsAdmissionOptional =  FS.IsOptional  
FROM sFee.tFeeSetup FS INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
WHERE FM.FeeHeadId = @lAdmissionHeadId
	  AND FS.BatchId = @rBatchId AND FS.ClassId = @rClassId AND FS.AdmissionCategoryId = @rAdmissionCategoryId
	  

IF ( @lIsAdmissionOptional = 1)
 
BEGIN
IF NOT EXISTS (SELECT 1  
FROM sFee.tFeeOptional FO INNER JOIN sFee.tFeeSetup FS  ON FO.FeeSetupId = FS.Id  
 INNER JOIN  sFee.tFeeMaster FM ON FS.FeeId = FM.Id
WHERE FM.FeeHeadId = @lAdmissionHeadId
AND FS.BatchId = @rBatchId AND ClassId = @rClassId 
AND FS.AdmissionCategoryId = @rAdmissionCategoryId
--AND FS.IsOptional = 1 
AND FO.SourceTypeId = 2001 AND FO.SourceId = @rAcademicId )
BEGIN
INSERT INTO sFee.tFeeOptional (FeeSetupId,SourceTypeId,SourceId,BatchId)
SELECT FS.Id AS FeeSetupId,2001 AS SourceTypeId,@rAcademicId AS SourceId,@rBatchId AS BatchId 
FROM sFee.tFeeSetup FS INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
WHERE FM.FeeHeadId = @lAdmissionHeadId
AND FS.BatchId = @rBatchId AND ClassId = @rClassId 
AND AdmissionCategoryId = @rAdmissionCategoryId
AND FS.IsOptional = 1
END
END

 

END
COMMIT TRANSACTION
SELECT 1 AS Result    
		

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


GO
ALTER PROCEDURE [sFee].[pChargeReceiptGet]
	 @rId bigint,
	 @rReceiptNumber int,
	 @rOrgId int,
	 @rBatchId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 --IF(@rIsSearch=1)
		--BEGIN
		--	SET @rCode = sCommon.fSearchStringGet(@rCode)
		--	SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		Declare @rSourceTypeId smallint
		select @rSourceTypeId=SourceTypeId from sFee.tChargeReceipt where (ReceiptNumber=@rReceiptNumber OR Id=@rId) and OrgId=@rOrgId
		--END
		--print @rSourceTypeId
IF @rSourceTypeId=95
BEGIN
		SELECT 
			distinct(CR.Id),
			CR.SourceTypeId,
			CR.SourceId,
			EM.EmployeeCode as SourceCode,
			EM.EmployeeName as GuestName,
			EM.DepartmentName AS ClassDiv,
			CR.Remark,
			CR.ReceiptNumber,
			CR.ReceiptDate,
			CR.PayTypeId,
			CR.ChequeNo,
			CR.BankName,
			CR.IsObsolete,
			--CRD.Id as DetailId,
			--CRD.ChargeId,
			--CRD.Remark as DetailRemark,
			--CRD.Amount,
			--CM.Code,
			--CM.Title,
			CM.ChargeCategoryId,
			CR.ChargeReceiptBookId AS ReceiptBookId,
			ISNULL(CR.ReceiptAmount,0) AS ReceiptAmount,
			CR.OrgId,
			CR.BatchId
			--CRD.IsObsolete
  FROM 
           sFee.tChargeReceipt CR
       INNER JOIN sFee.tChargeReceiptDetail CRD ON CRD.ChargeReceiptId=CR.Id
       INNER JOIN sFee.tChargeMaster CM ON CM.Id=CRD.ChargeId
       INNER JOIN sHRM.vExtEmployeeJobDetail EM ON EM.EmployeeId=CR.SourceId AND CR.SourceTypeId=95
  WHERE 
			((CR.Id=@rId OR @rId=0))
			AND ((CR.ReceiptNumber=@rReceiptNumber) OR (@rReceiptNumber=''))
			AND (CR.IsObsolete=0)
			AND (CR.OrgId=@rOrgId)
			AND (CR.BatchId=@rBatchId)
			--AND (CRD.IsObsolete=0)
END
ELSE IF @rSourceTypeId=2001
BEGIN
		SELECT 
			distinct(CR.Id),
			CR.SourceTypeId,
			CR.SourceId,
			SA.Code as SourceCode,
			SA.Name as GuestName,
			SA.ClassName+'-'+SA.DivisionName AS ClassDiv,
			CR.Remark,
			CR.ReceiptNumber,
			CR.ReceiptDate,
			CR.PayTypeId,
			CR.ChequeNo,
			CR.BankName,
			CR.IsObsolete,
			--CRD.Id as DetailId,
			--CRD.ChargeId,
			--CRD.Remark as DetailRemark,
			--CRD.Amount,
			--CM.Code,
			--CM.Title,
			CM.ChargeCategoryId,
			CR.ChargeReceiptBookId AS ReceiptBookId,
			ISNULL(CR.ReceiptAmount,0) AS ReceiptAmount,
			CR.OrgId,
			CR.BatchId
			--CRD.IsObsolete
  FROM 
           sFee.tChargeReceipt CR
       INNER JOIN sFee.tChargeReceiptDetail CRD ON CRD.ChargeReceiptId=CR.Id
       INNER JOIN sFee.tChargeMaster CM ON CM.Id=CRD.ChargeId
       INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=CR.SourceId AND CR.SourceTypeId=2001 
       --AND SA.StatusId=1
  WHERE 
			((CR.Id=@rId OR @rId=0))
			AND ((CR.ReceiptNumber=@rReceiptNumber) OR (@rReceiptNumber=''))
			AND (CR.IsObsolete=0)
			AND (CR.OrgId=@rOrgId)
			AND (CR.BatchId=@rBatchId)
			--AND (CRD.IsObsolete=0)
END
ELSE
BEGIN
	SELECT 
			distinct(CR.Id),
			3 as SourceTypeId,
			0 as SourceId,
			'' as SourceCode,
			CR.GuestName,
			'' AS ClassDiv,
			CR.Remark,
			CR.ReceiptNumber,
			CR.ReceiptDate,
			CR.PayTypeId,
			CR.ChequeNo,
			CR.BankName,
			CR.IsObsolete,
			--CRD.Id as DetailId,
			--CRD.ChargeId,
			--CRD.Remark as DetailRemark,
			--CRD.Amount,
			--CM.Code,
			--CM.Title,
			CM.ChargeCategoryId,
			CR.ChargeReceiptBookId AS ReceiptBookId,
			ISNULL(CR.ReceiptAmount,0) AS ReceiptAmount,
			CR.OrgId,
			CR.BatchId
			--CRD.IsObsolete
  FROM 
           sFee.tChargeReceipt CR
       INNER JOIN sFee.tChargeReceiptDetail CRD ON CRD.ChargeReceiptId=CR.Id AND ISNULL(CR.SourceTypeId,0)=0
       INNER JOIN sFee.tChargeMaster CM ON CM.Id=CRD.ChargeId
  WHERE 
			((CR.Id=@rId OR @rId=0))
			AND ((CR.ReceiptNumber=@rReceiptNumber) OR (@rReceiptNumber=''))
			AND (CR.IsObsolete=0)
			AND (CR.OrgId=@rOrgId)
			AND (CR.BatchId=@rBatchId)
			--AND (CRD.IsObsolete=0)
END	
END
GO
PRINT N'Altering [sFee].[pChargeReceiptListGet]...';


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

BEGIN 

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








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


GO
ALTER PROCEDURE [sFee].[pCollectionGroupGet]
		
		@rSourceId bigint,
		@rSourceTypeId int=0,
		@rReceiptBookId int=0,
		@rReceiptId bigint=0,
		@rBatchId int,
		@rCollectionGroupId int =0 
		
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
		
BEGIN 	
	DECLARE @lClassId int
		DECLARE @lAdmissionCategoryId int
		SELECT @lClassId=ClassId,@lAdmissionCategoryId=AdmissionCategoryId FROM sStudent.vStudentAcademic WHERE AcademicId=@rSourceId	
		

SELECT SUM(CG.PayableAmount) AS PendingAmount 
,CollectionGroupId,StartDate,EndDate,CollectionGroupName,ReceiptBookId,ReceiptBook FROM

(SELECT 
			FM.Id AS FeeId,
			FM.Title AS FeeName,
			FS.Id AS FeeSetupId,			 
			FS.ReceiptBookId,
			RBM.Title AS ReceiptBook,
			ISNULL(R.PaidAmount,0) AS PaidAmount,
			ISNULL(FS.Amount,0) +  ISNULL(FA.VariableAmount,0) -  ISNULL(FA.DiscountAmount,0) -  ISNULL(FA.NotApplicableAmount,0) + ISNULL(FA.AdditionalAmount,0.00)-ISNULL(R.PaidAmount,0)AS PayableAmount,
			--FM.OrderIndex,
			FS.CollectionGroupId,
			CGM.StartDate,
			CGM.EndDate,
			CGM.Title AS CollectionGroupName,
			CGM.OrderIndex
  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
			FROM sFee.tFeeSetup FS1
				WHERE FS1.ClassId=@lClassId AND FS1.BatchId = @rBatchId  
				AND ((FS1.CollectionGroupId=@rCollectionGroupId) OR (@rCollectionGroupId=0))
				AND FS1.AdmissionCategoryId=@lAdmissionCategoryId AND IsOptional=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
			FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO
			ON FO.FeeSetupId=FS1.Id AND (FO.SourceId=@rSourceId) AND ((FO.SourceTypeId=@rSourceTypeId) OR (@rSourceTypeId=0))
		WHERE
				FS1.ClassId=@lClassId AND FS1.BatchId =@rBatchId AND FS1.AdmissionCategoryId=@lAdmissionCategoryId AND IsOptional=1
				AND ((FS1.CollectionGroupId=@rCollectionGroupId) OR (@rCollectionGroupId=0))
				
		) FS ON FS.FeeId=FM.Id
		INNER JOIN sFee.tCollectionGroupMaster CGM ON CGM.Id = FS.CollectionGroupId
		INNER JOIN sFee.tReceiptBookMaster RBM
			ON RBM.Id=FS.ReceiptBookId
		LEFT JOIN
		(
		    SELECT ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId FROM
		    sFee.tReceipt R INNER JOIN sFee.tReceiptDetail RD ON	RD.ReceiptId = R.Id 	
		    INNER JOIN sFee.tFeeSetup FSR ON FSR.Id = RD.FeeSetupId 	
			WHERE						
			 (R.ReceiptBookId = @rReceiptBookId	OR @rReceiptBookId = 0)	
			 AND ((FSR.CollectionGroupId=@rCollectionGroupId) OR (@rCollectionGroupId=0))
			AND R.SourceId= @rSourceId
			AND ((R.SourceTypeId=@rSourceTypeId) OR (@rSourceTypeId=0))
			AND R.IsObsolete = 0 			 
			 GROUP BY FeeSetupId
		
		) R ON R.FeeSetupId = FS.Id 
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=FS.Id AND 
			(FA.SourceId=@rSourceId) AND ((FA.SourceTypeId=@rSourceTypeId) OR (@rSourceTypeId=0))
			
where 

((FS.ReceiptBookId=@rReceiptBookId)OR(@rReceiptBookId=0))
AND (((ISNULL(FS.Amount,0) +  ISNULL(FA.VariableAmount,0) -  ISNULL(FA.NotApplicableAmount,0) -  ISNULL(FA.DiscountAmount,0) + ISNULL(FA.AdditionalAmount,0.00)-ISNULL(R.PaidAmount,0))>0) AND(@rReceiptId=0) OR(@rReceiptId<>0))
AND(FS.BatchId=@rBatchId)
  ) AS CG
  GROUP BY CollectionGroupId,StartDate,EndDate,CollectionGroupName,OrderIndex,ReceiptBookId,ReceiptBook
  ORDER BY CG.OrderIndex
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)=''
        
	
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
		)
	VALUES
		(
			@rOrgGroupBatchId,
			@lNextNumber,
			@rCode,
			@rTitle,
			@rStartDate,
			@rEndDate,
			@rRemark,
			@rIsObsolete,
			@rOrderIndex,
			@rReceiptBookId,
			@rFooterRemark1,
			@rFooterRemark2,
			@rFeePeriod
		)
		    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
	      
	      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
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
	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].[pDepositAddAdd]...';


GO
ALTER PROCEDURE [sFee].[pDepositAddAdd]
	 
	@rId bigint,
	@rDepositHeadId int,
	@rStudentId bigint,
	@rAmount decimal(12,2),
	@rDepositDate date,
	@rPayTypeId tinyint,
	@rChequeNo nvarchar(20),
	@rBankName nvarchar(200),
	@rRemark nvarchar(200),
	@rCreatedUserId bigint,
	@rBatchId int,
	@rOrgGroupId smallint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

DECLARE @lStudentId bigint
DECLARE @lClassId int

BEGIN	
BEGIN TRY
BEGIN TRANSACTION	

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

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

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

    BEGIN 
    SET @lNextNumber = @rId
	    UPDATE sFee.tDepositAdd
	    SET
	    DepositHeadId=@rDepositHeadId,
	    StudentId=@lStudentId,
		Amount=@rAmount,
		DepositDate=@rDepositDate,
		PayTypeId=@rPayTypeId,
		ChequeNo=@rChequeNo,
		BankName=@rBankName,
		Remark=@rRemark,
		UpdatedUserId=@rCreatedUserId,
	    UpdatedDateTime=sCommon.fGetDate()	    
	    WHERE Id = @rId 
	    SELECT @lNextNumber AS Result
	 END  
	
	COMMIT TRANSACTION
		
END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
	
END
GO
PRINT N'Altering [sFee].[pDepositAdjustmentAdd]...';


GO
ALTER PROCEDURE [sFee].[pDepositAdjustmentAdd]
	
	@rId bigint, 
	@rDepositHeadId int,
	@rStudentId bigint,
	@rAmount decimal(12,2),
	@rAdjustmentDate date,
	@rRemark nvarchar(200),
	@rCreatedUserId bigint,
	@rBatchId int,
	@rOrgGroupId smallint 
	
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  sFee.tDepositAdd D  INNER JOIN sFee.tDepositAdjustment DA ON D.DepositHeadId = DA.DepositHeadId 
									AND D.StudentId=@lStudentId  AND D.DepositDate > @rAdjustmentDate)
		BEGIN
			SELECT -101 as Result
			RETURN
		END 
	END 
 
	-- AMOUNT VALIDATIEON
	--BEGIN
	--	 If EXISTS
	--		(SELECT ISNULL(SUM(D.Amount),0),DepositHeadId,StudentId FROM sFee.tDepositAdd D 
	--		WHERE D.DepositHeadId = @rDepositHeadId AND D.StudentId=@lStudentId Group by StudentId,DepositHeadId Having Sum(D.Amount) 
	--	 < (SELECT ISNULL(SUM(Amount),0)+ @rAmount AS TotalAmount FROM sFee.tDepositAdjustment DA 
	--		WHERE DA.DepositHeadId = @rDepositHeadId AND DA.StudentId=@lStudentId AND Id <> @rId )) 	
	--	BEGIN
	--		SELECT -102 as Result
	--		RETURN
	--	END 
	--END				
 
DECLARE @lNextNumber bigint 
IF(@rId = 0)
BEGIN
EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sFee.tDepositAdjustment', 0, 1, 1,@outNextNumber = @lNextNumber output 
	INSERT INTO sFee.tDepositAdjustment
		(
		Id,
		DepositHeadId,
		StudentId,
		Amount,
		AdjustmentDate,
		Remark,
		CreatedUserId,
		CreatedDateTime
		)
	VALUES
		(
		@lNextNumber,
		@rDepositHeadId,
		@lStudentId,
		@rAmount,
		@rAdjustmentDate,
		@rRemark,
		@rCreatedUserId,
		sCommon.fGetDate()
		) 
		SELECT 1 AS Result   
	END	
ELSE
    BEGIN
    SET @lNextNumber = @rId
	    UPDATE sFee.tDepositAdjustment
	    SET
	    DepositHeadId=@rDepositHeadId,
	    StudentId=@lStudentId,
		Amount=@rAmount,
		AdjustmentDate=@rAdjustmentDate,
		Remark=@rRemark,
		UpdatedUserId=@rCreatedUserId,
	    UpdatedDateTime=sCommon.fGetDate()	    
	    WHERE Id = @rId 
	    SELECT @lNextNumber AS Result
	 END  
	
	COMMIT TRANSACTION
		
END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
	
END
GO
PRINT N'Altering [sFee].[pFeeAllocationGet]...';


GO
ALTER PROCEDURE [sFee].[pFeeAllocationGet]
	 
		
		@rSourceId bigint ,
		@rSourceTypeId int,
		@rBatchId int,
		@rStudentId bigint =0
		
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
		
BEGIN 	
	if (@rStudentId <> 0)
	SELECT @rSourceId = Id FROM sStudent.tAcademic WHERE StudentId = @rStudentId AND BatchId = @rBatchId
		DECLARE @lClassId int
		DECLARE @lAdmissionCategoryId int
		SELECT @lClassId=ClassId,@lAdmissionCategoryId=AdmissionCategoryId FROM sStudent.vStudentAcademic WHERE AcademicId=@rSourceId

SELECT 
			FM.Title AS FeeName,
			FS.Id AS FeeSetupId,
			ISNULL(FS.IsOptional,0)AS IsOptional,
			ISNULL(FS.IsVariable,0)AS IsVariable,
			ISNULL(FS.Amount,0)AS Amount,
			ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
			ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
			ISNULL(FA.VariableAmount,0.00)AS FAAmount,
			ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
			ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
			ISNULL(R.PaidAmount,0) AS PaidAmount,
			ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)AS PendingAmount,
			ISNULL(FA.NotApplicableAmount,0.00) AS NotApplicableAmount,
			ISNULL(FA.Remark,'') AS Remark,
			FM.OrderIndex,
			0 AS ReceiptNumber,
			'1900-01-01'AS ReceiptDate,
			ISNULL(FS.ReceiptBookId,0) AS ReceiptBookId,
			FS.CollectionGroupId,
			FM.FeeHeadId
			
  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
				 
			FROM sFee.tFeeSetup FS1
			   
				WHERE FS1.ClassId=@lClassId AND FS1.AdmissionCategoryId=@lAdmissionCategoryId AND IsOptional=0
				AND FS1.BatchId = @rBatchId
				UNION ALL
				
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				ISNULL(FS1.CollectionGroupId,0) AS CollectionGroupId 
				 
			FROM sFee.tFeeSetup FS1
			 
		INNER JOIN sFee.tFeeOptional FO
			ON FO.FeeSetupId=FS1.Id AND (FO.SourceId=@rSourceId) AND(FO.SourceTypeId=@rSourceTypeId)
			WHERE
			 FS1.BatchId = @rBatchId
			AND	FS1.ClassId=@lClassId AND FS1.AdmissionCategoryId=@lAdmissionCategoryId AND IsOptional=1
		) FS ON FS.FeeId=FM.Id
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=FS.Id AND (FA.SourceId=@rSourceId) AND(FA.SourceTypeId=@rSourceTypeId)
		LEFT JOIN
		(
		    SELECT ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId
		    FROM
		    sFee.tReceipt R INNER JOIN sFee.tReceiptDetail RD ON	RD.ReceiptId = R.Id 		
			WHERE						
			 R.SourceId= @rSourceId
			AND ((R.SourceTypeId = @rSourceTypeId) OR (@rSourceTypeId=0))
			AND R.IsObsolete = 0 
			AND R.BatchId = @rBatchId
			 GROUP BY FeeSetupId
		) R ON R.FeeSetupId = FS.Id	
WHERE 
	FS.BatchId=@rBatchId
ORDER BY FS.StartDate ASC,FM.OrderIndex ASC

END
GO
PRINT N'Altering [sFee].[pFeeImportAdd]...';


GO

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

	IF EXISTS (SELECT 1 FROM sFee.tFeeSetup WHERE BatchId = @rToBatchId)
	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
	Select @lCount = COUNT(Id) From #TempFeeMaster
	
	While (@lCount > 0)
	BEGIN
		-- 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,
				StartDate,EndDate,ReceiptBookId,@rCreatedUserId,GETDATE(),null,null,IsServiceTax,null	
		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].[pFeeReceiptView]...';


GO
ALTER PROCEDURE [sFee].[pFeeReceiptView]
	 
		@rReceiptId bigint
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 		
	SELECT 
			--FM.Id AS FeeId,
			FM.Title AS FeeName,
			--FS.Id AS FeeSetupId,
			--FRD.ReceiptId,
			FRD.Amount AS PaidAmount,
			FS.Id AS FeeSetupId
			--FR.ReceiptAmount
      
  FROM 
		sFee.tFeeMaster FM
		INNER JOIN sFee.tFeeSetup FS
			ON FS.FeeId=FM.Id
		INNER JOIN sFee.tReceiptDetail FRD
			ON FRD.FeeSetupId=FS.Id
		INNER JOIN sFee.tReceipt FR
			ON FR.Id=FRD.ReceiptId
			
where 

FRD.ReceiptId=@rReceiptId


ORDER BY FS.StartDate,FM.OrderIndex ASC


END
GO
PRINT N'Altering [sFee].[pReceiptBookMasterAdd]...';


GO

ALTER PROCEDURE [sFee].[pReceiptBookMasterAdd]
	 
	        @rId int
	       ,@rCode nvarchar(20)
           ,@rTitle nvarchar(100)
           ,@rFullTitle nvarchar(200)
           ,@rAddress1 nvarchar(200)
           ,@rAddress2 nvarchar(200)
           ,@rBankAccountNumber nvarchar(50)
           ,@rIsObsolete bit
           ,@rRemark1 nvarchar(500)
           ,@rRemark2 nvarchar(500)
           ,@rCreatedUserId bigint           
           ,@rOrgGroupId int
           ,@rIsOnPrePrinted bit
           ,@rReportId int
           ,@rIsSupressLogo bit
           ,@rOrderIndex int
           ,@rIsDisplaySchoolName bit
           ,@rIsMonthDetailOnly bit
           ,@rIsServiceTaxApplicable bit
           ,@rServiceTaxPercentage decimal(6,2)
           ,@rBankName nvarchar(150)=''
           ,@rIsFeeInvoiceHeadwise bit = 0
           ,@rGroupTitle nvarchar(200)=''
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber INT     
	
If Exists(select top(1)* from sFee.tReceiptBookMaster where Title=@rTitle AND OrgGroupId=@rOrgGroupId) 
BEGIN
	If NOT Exists(select top(1)* from sFee.tReceiptBookMaster where Title=@rTitle AND OrgGroupId=@rOrgGroupId AND Id=@rId)
	BEGIN
		select -101 as Result
	END
	ELSE
	BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  [sFee].[tReceiptBookMaster]
	    SET
			  --Code=@rCode
	          Title=@rTitle
	          ,FullTitle=@rFullTitle
	         ,Address1=@rAddress1
	         ,Address2=@rAddress2
	         ,BankAccountNumber=@rBankAccountNumber
	         ,[IsObsolete] = @rIsObsolete      
	         ,[Remark1] = @rRemark1
	         ,[Remark2] = @rRemark2
             ,[UpdatedUserId] = @rCreatedUserId
             ,[UpdatedDateTime] = sCommon.fGetDate()
             ,IsOnPrePrinted=@rIsOnPrePrinted
             ,ReportId=@rReportId
             ,IsSupressLogo=@rIsSupressLogo   
             ,OrderIndex=@rOrderIndex
             ,IsDisplaySchoolName=@rIsDisplaySchoolName
             ,IsMonthDetailOnly=@rIsMonthDetailOnly
             ,IsServiceTaxApplicable=@rIsServiceTaxApplicable
			 ,ServiceTaxPercentage=@rServiceTaxPercentage
			 ,BankName=@rBankName
			 ,IsFeeInvoiceHeadwise=@rIsFeeInvoiceHeadwise
			 ,GroupTitle =@rGroupTitle
             
	      WHERE Id = @rId 	 
	      SELECT @lNextNumber AS Result
	 END  
END
ELSE
BEGIN
IF(@rId = 0)	
BEGIN

	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sFee.tReceiptBookMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	
	INSERT INTO [sFee].[tReceiptBookMaster]
			   (
			    [Id]
			   ,[Code]
			   ,[Title]
			   ,[FullTitle]
			   ,[Address1] 
			   ,[Address2] 
			   ,[BankAccountNumber] 
			   ,[IsObsolete]
			   ,[Remark1] 
			   ,[Remark2] 
			   ,[CreatedUserId]
			   ,[CreatedDateTime]
			   ,[OrgGroupId]
			   ,IsOnPrePrinted
			   ,ReportId
			   ,IsSupressLogo
			   ,OrderIndex
			   ,IsDisplaySchoolName
			   ,IsMonthDetailOnly
			   ,IsServiceTaxApplicable
			   ,ServiceTaxPercentage
			   ,BankName
			   ,IsFeeInvoiceHeadwise
			   ,GroupTitle
			   )
		 VALUES
			   (
				@lNextNumber
			   ,@rCode
			   ,@rTitle
			   ,@rFullTitle
			   ,@rAddress1
			   ,@rAddress2
			   ,@rBankAccountNumber
			   ,@rIsObsolete
			   ,@rRemark1
			   ,@rRemark2
			   ,@rCreatedUserId
			   ,sCommon.fGetDate()
			   ,@rOrgGroupId
			   ,@rIsOnPrePrinted
			   ,@rReportId
			   ,@rIsSupressLogo
			   ,@rOrderIndex
			   ,@rIsDisplaySchoolName
			   ,@rIsMonthDetailOnly
			   ,@rIsServiceTaxApplicable
			   ,@rServiceTaxPercentage
			   ,@rBankName
			   ,@rIsFeeInvoiceHeadwise
			   ,@rGroupTitle
			   )
			   
 
INSERT INTO sSecurity.tUserAccess
           (
            SourceTypeId
            ,SourceId
           ,[UserId]
           
           )
SELECT 
		   2013
		   ,@lNextNumber
		  ,@rCreatedUserId
			   
			   
		    SELECT @lNextNumber AS Result
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  [sFee].[tReceiptBookMaster]
	    SET
			  --Code=@rCode
	          Title=@rTitle
	          ,FullTitle=@rFullTitle
	         ,Address1=@rAddress1
	         ,Address2=@rAddress2
	         ,BankAccountNumber=@rBankAccountNumber
	         ,[IsObsolete] = @rIsObsolete          
	         ,[Remark1] = @rRemark1
	         ,[Remark2] = @rRemark2                     
             ,[UpdatedUserId] = @rCreatedUserId
             ,[UpdatedDateTime] = sCommon.fGetDate()   
             ,IsOnPrePrinted=@rIsOnPrePrinted
             ,ReportId=@rReportId
             ,IsSupressLogo=@rIsSupressLogo
             ,OrderIndex=@rOrderIndex              
             ,IsDisplaySchoolName=@rIsDisplaySchoolName
             ,IsMonthDetailOnly=@rIsMonthDetailOnly
             ,IsServiceTaxApplicable=@rIsServiceTaxApplicable
			 ,ServiceTaxPercentage=@rServiceTaxPercentage
			 ,BankName=@rBankName
			 ,IsFeeInvoiceHeadwise=@rIsFeeInvoiceHeadwise
			 ,GroupTitle =@rGroupTitle
             
	      WHERE Id = @rId 	   
	      SELECT @lNextNumber AS Result
	 END  
		
	END
COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sFee].[pReceiptBookMasterGet]...';


GO

ALTER PROCEDURE [sFee].[pReceiptBookMasterGet]
          
           @rId bigint,
           @rCode nvarchar(20),
           @rTitle nvarchar(100),
           @rOrgGroupId int,
           @rIsWildCardSearch bit
 
AS
SET NOCOUNT ON

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

BEGIN
SELECT RBM.Id 
	  ,RBM.Code
      ,RBM.Title
      ,RBM.FullTitle
      ,RBM.Address1
      ,RBM.Address2
      ,RBM.BankAccountNumber
      ,RBM.IsObsolete
      ,RBM.Remark1
      ,RBM.Remark2
      ,ISNULL(RBM.IsOnPrePrinted ,0) AS IsOnPrePrinted
      ,ISNULL(RBM.IsSupressLogo,0) AS IsSupressLogo
      ,RBM.ReportId  
       --,RBM.OrderIndex  
      ,ISNULL(RBM.OrderIndex,0) AS OrderIndex
      ,ISNULL(RBM.IsDisplaySchoolName,0) AS IsDisplaySchoolName
      ,ISNULL(RBM.IsMonthDetailOnly,0) AS IsMonthDetailOnly
      ,ISNULL(RBM.IsServiceTaxApplicable,0) AS IsServiceTaxApplicable
	  ,ISNULL(RBM.ServiceTaxPercentage,0) AS ServiceTaxPercentage
	  ,ISNULL(RBM.BankName,'') AS BankName
	  ,ISNULL(RBM.IsFeeInvoiceHeadwise,0) AS IsFeeInvoiceHeadwise
	  ,ISNULL(RBM.GroupTitle,'') AS GroupTitle
      
     
  FROM [sFee].[tReceiptBookMaster] RBM  
        
  WHERE 
		 RBM.Id = @rId OR @rId = 0
	AND ((RBM.Code Like @rCode)OR(ISNULL(@rCode,'') = ''))
	AND ((RBM.Title Like @rTitle)OR(ISNULL(@rTitle,'') = ''))
	AND  RBM.OrgGroupId = @rOrgGroupId 
	--AND  QM.IsObsolete = 0
         
END
GO
PRINT N'Altering [sFee].[pRptChargeReceiptDetailsGet]...';


GO
ALTER PROCEDURE [sFee].[pRptChargeReceiptDetailsGet]
	 
		@rReceiptId bigint
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 		
	SELECT 
			CRD.ChargeReceiptId,
			CR.ReceiptNumber,
			CR.ReceiptDate,
			SA.AcademicId,
			--For Name
			(CASE WHEN CR.SourceTypeId = 2001 THEN SA.Name 
			WHEN CR.SourceTypeId = 3 THEN CR.GuestName
			WHEN CR.SourceTypeId = 95 THEN EM.FirstName + ' ' + EM.LastName
			END ) AS NAME, 
			--For Code
			(CASE WHEN CR.SourceTypeId = 2001 THEN SA.Code 
			WHEN CR.SourceTypeId = 95 THEN EM.Code
			END ) AS Code,
			--SA.Code,
			SA.RollNo,
			SA.ClassId,
			SA.DivisionId,
			SA.ClassName,
			SA.DivisionName,
			SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
			CM.Id AS ChargeId,
			CM.Title AS ChargeName,
			CRD.Amount AS PaidAmount,
			PTM.Title AS PayType,
			ISNULL(CR.ChequeNo,'') AS ChequeNo,
			ISNULL(CR.BankName,'') AS BankName,
			ISNULL(RBM.Address1,'') AS Address1,
			ISNULL(RBM.Address2,'') AS Address2,
			ISNULL(RBM.FullTitle,'') AS FullTitle,
			CR.Remark,
			U.DisplayTitle AS UserName,
			OM.OrgLogo,
			CR.SourceTypeId,
			ISNULL(RBM.Title,'') AS ChargeReceiptBookName,
			ISNULL(CCM.Title,'') AS ChargeCategoryName,
			ISNULL(RBM.IsOnPrePrinted,0) AS IsOnPrePrinted,
			ISNULL(RBM.IsSupressLogo,0) AS IsSupressLogo,
			ISNULL(RBM.IsDisplaySchoolName,0) AS IsDisplaySchoolName,
			sFinanceCommon.fNumberToWordsWithDecimal (ISNULL(CR.ReceiptAmount,0.00),1,2,OM.OrgGroupId) AS ReceiptAmountInWords,
			OM.Title AS OrganizationName,
			CR.ReceiptAmount,
			CM.OrderIndex
			
	FROM 
			sFee.tChargeMaster CM
			INNER JOIN sFee.tChargeReceiptDetail CRD
				ON CRD.ChargeId=CM.Id
			INNER JOIN sFee.tChargeReceipt CR
				ON CR.Id=CRD.ChargeReceiptId 	 
			INNER JOIN sFee.tChargeCategoryMaster CCM
				ON CCM.ChargeReceiptBookId=	CR.ChargeReceiptBookId AND CCM.Id=CM.ChargeCategoryId
			INNER JOIn sFinanceCommon.tPayTypeMaster PTM
				ON PTM.Id=CR.PayTypeId
			INNER JOIN sFee.tChargeReceiptBookMaster RBM 
				ON RBM.Id=CR.ChargeReceiptBookId
			INNER JOIN sSecurity.tUser U
				ON U.Id=CR.CreatedUserId
			LEFT JOIN sStudent.vStudentAcademic SA
				ON SA.AcademicId=CR.SourceId AND CR.SourceTypeId = 2001	
			LEFT JOIN sHrm.tEmployeeMaster EM
				ON EM.Id=CR.SourceId AND CR.SourceTypeId = 95	
			LEFT JOIN sSetup.tOrganizationMaster OM
				ON OM.Id=SA.OrgId				
	WHERE 
			CRD.ChargeReceiptId=@rReceiptId

ORDER BY CM.OrderIndex ASC

END
GO
PRINT N'Altering [sFee].[pRptDepositAddReceiptGet]...';


GO

ALTER PROCEDURE [sFee].[pRptDepositAddReceiptGet]
          
		   @rId bigint,
		   @rOrgId int,          
           @rDepositHeadId int,
           @rBatchId int
           
           
AS
SET NOCOUNT ON 

BEGIN
SELECT  
		DHM.Title AS DepositHeadName,
		DA.Id,
		DA.DepositHeadId,
		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
        
  FROM 		
		sStudent.vStudentAcademic vSA
		INNER JOIN sFee.tDepositAdd DA ON DA.StudentId = vSA.StudentId
		INNER JOIN sFee.tDepositHeadMaster DHM ON DHM.Id = DA.DepositHeadId 
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=vSA.OrgId
		INNER JOIn sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=DA.PayTypeId
  WHERE  
		vSA.BatchId = @rBatchId 
		AND (vSA.OrgId=@rOrgId OR @rOrgId=0)
		AND (DA.DepositHeadId=@rDepositHeadId OR @rDepositHeadId=0)
		AND (DA.Id=@rId)
		Order By DA.DepositDate
END
GO
PRINT N'Altering [sFee].[pRptDepositAdjustmentReceiptGet]...';


GO

ALTER PROCEDURE [sFee].[pRptDepositAdjustmentReceiptGet]
          
		   @rId bigint,          
		   @rOrgId int,          
           @rDepositHeadId int,
           @rBatchId int
           
AS
SET NOCOUNT ON

BEGIN
SELECT  
		DHM.Title AS DepositHeadName,
		DA.Id,
		DA.DepositHeadId,
		DA.StudentId AS StudentId,
		vSA.AcademicId AS AcademicId,
		DA.Amount,
		DA.AdjustmentDate,
		DA.Remark,
		DA.CreatedDateTime,
		vSA.RollNo,
		vSA.Code,
        vSA.Name AS StudentName,        
        vSA.ClassName+' - '+vSA.DivisionName AS ClassDivisionName,
        OM.Id AS OrgId,
        OM.DisplayTitle AS OrganizationName,
        sFinanceCommon.fNumberToWordsWithDecimal(ISNULL(DA.Amount,0.00),1,2,OM.OrgGroupId) AS ReceiptAmountInWords
  FROM 		
		sStudent.vStudentAcademic vSA
		INNER JOIN sFee.tDepositAdjustment DA ON DA.StudentId = vSA.StudentId
		INNER JOIN sFee.tDepositHeadMaster DHM ON DHM.Id = DA.DepositHeadId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=vSA.OrgId
  WHERE  
		vSA.BatchId = @rBatchId 
		AND (vSA.OrgId=@rOrgId OR @rOrgId=0)
		AND (DA.DepositHeadId=@rDepositHeadId OR @rDepositHeadId=0)
		AND (DA.Id=@rId)
		Order By DA.CreatedDateTime
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,
		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,
		FS.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
  FROM 
		sFee.tFeeSetup FS 
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AdmissionCategoryId = FS.AdmissionCategoryId AND SA.ClassId = FS.ClassId
		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
		
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='')
END
GO
PRINT N'Altering [sFee].[pRptFeeReceiptDetailListGet]...';


GO

ALTER PROCEDURE [sFee].[pRptFeeReceiptDetailListGet]
		@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

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
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,
		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
  FROM 
			sFee.tReceipt R
		INNER JOIN sStudent.vStudentAcademic SA
			ON SA.AcademicId=R.SourceId AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))
		INNER JOIN sFinanceCommon.tPayTypeMaster PTM
			ON PTM.Id=R.PayTypeId
		INNER JOIN sFee.tReceiptDetail RD
			ON RD.ReceiptId=R.Id
		INNER JOIN sFee.tFeeSetup FS
			ON FS.Id=RD.FeeSetupId
		INNER JOIN sFee.tFeeMaster FM
			ON FM.Id=FS.FeeId
		INNER JOIN sFee.tFeeHeadMaster FHM
			ON FHM.Id=FM.FeeHeadId
		INNER 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 ((R.BatchId=@rBatchId) OR (@rBatchId=0))
	AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
	AND (R.IsObsolete = @rIsCancel) 
	AND (SA.StatusId = @rStatusId OR @rStatusId=0)
	AND ((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='')
	ORDER BY R.ReceiptNumber
	
--	UNION ALL
	
--	SELECT 
--		R.Id AS ReceiptId,
--		0 AS ClassId,
--		--SA.ClassName,
--		0 AS DivisionId,
--		--SA.DivisionName,
--		EM.DepartmentId,
--		EM.DepartmentName AS ClassDept,
--		0 AS RollNo,
--		EM.Code,
--		EM.EmployeeName,
--		PTM.Title AS PayType,
--		R.ReceiptAmount
			
--  FROM 
--			sFee.tReceipt R
--		INNER JOIN sCommon.tSourceTypeMaster STM
--			ON STM.Id=R.SourceTypeId AND R.SourceTypeId = 95
--		INNER JOIN sHrm.vExtEmployeeMaster EM
--			ON EM.EmployeeId=R.SourceId
--		INNER JOIN sFinanceCommon.tPayTypeMaster PTM
--			ON PTM.Id=R.PayTypeId
			
--WHERE 
--		((EM.DepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))
--	AND ((R.ReceiptNumber >= @rFromReceiptNo) OR (@rFromReceiptNo = 0))
--	AND ((R.ReceiptNumber <= @rToReceiptNo) OR (@rToReceiptNo = 0))
--	AND ((R.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
--	AND ((R.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
--	AND (R.BatchId = @rBatchId)
END
GO
PRINT N'Altering [sFee].[pRptFeeReceiptDetailsGet]...';


GO
ALTER PROCEDURE [sFee].[pRptFeeReceiptDetailsGet]
			@rReportId int=0,
			@rReceiptId bigint = 0

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 	
 
DECLARE @lOrgGroupId int = 0
DECLARE @lAmountInWord nvarchar(500) = ''
DECLARE @lReceiptAmount Decimal(12,2) = 0.0
DECLARE @lCurrencyCode nvarchar(20) = ''

 
 SELECT @lOrgGroupId = OrgGroupId ,@lReceiptAmount = R.ReceiptAmount  FROM sFee.tReceipt R 
 INNER JOIN sSetup.tOrgGroupBatchMaster OB ON R.OrgGroupBatchId = OB.Id 
 WHERE R.Id = @rReceiptId

SELECT  @lAmountInWord = sFinanceCommon.fNumberToWordsWithDecimal(ISNULL(@lReceiptAmount,0.00),1,2,@lOrgGroupId)
SELECT  @lCurrencyCode = [sFinanceCommon].[fDefaultCurrencyCodeGet](@lOrgGroupId) 

	SELECT 
			FRD.ReceiptId,
			FR.ReceiptNumber,
			FR.ReceiptDate,
			SA.AcademicId,
			SA.FirstName+' '+SA.MiddleName+' '+SA.LastName AS Name,
			SA.Code,
			SA.RollNo,
			SA.ClassId,
			SA.DivisionId,
			SA.ClassName,
			SA.DivisionName,
			SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
			FM.FeeHeadId,
			FHM.Title AS FeeHead,
			FM.Id AS FeeId,
			FM.Title AS FeeName,
			FRD.Amount AS PaidAmount,
			PTM.Title AS PayType,
			ISNULL(FR.ChequeNo,'') AS ChequeNo,
			ISNULL(FR.BankName,'') AS BankName,
			ISNULL(RBM.Address1,'') AS Address1,
			ISNULL(RBM.Address2,'') AS Address2,
			ISNULL(RBM.FullTitle,'') AS FullTitle,
			ISNULL(FR.TotalReceiptAmount,0.00) AS TotalReceiptAmount,
			ISNULL(FR.ReceiptAmount,0.00) AS ReceiptAmount,			
			@lAmountInWord AS ReceiptAmountInWords,
			ISNULL(FR.DiscountAmount,0.00) AS DiscountAmount,
			FR.Remark,
			ISNULL(U.DisplayTitle,'') AS UserName,
			OM.OrgLogo,
			RBM.Remark1,
			RBM.Remark2,			 
			ISNULL(RBM.IsOnPrePrinted,0) AS IsOnPrePrinted,
			ISNULL(RBM.IsSupressLogo,0) AS IsSupressLogo,
			ISNULL(RBM.IsDisplaySchoolName,0) AS IsDisplaySchoolName,
			RBM.ReportId,
			OM.Title AS OrganizationName,
			(CASE  WHEN (RBM.ReportId = 20775 OR RBM.ReportId = 20777 OR RBM.ReportId = 20874  ) AND ISNULL(RBM.IsMonthDetailOnly,0) = 0  THEN 
				[sFee].[fFeeHeadMonthDetailGet](FR.ID,FHM.Id) -- Fee name in detail	
				WHEN (RBM.ReportId = 20775 OR RBM.ReportId = 20777 OR RBM.ReportId = 20874   ) AND ISNULL(RBM.IsMonthDetailOnly,0) = 1  THEN				
				 [sFee].[fFeeHeadMonthNameGet](FR.ID,FHM.Id) -- Month name in detail				 
			--WHEN ISNULL(RBM.IsMonthDetailOnly,0) = 1 THEN 
			WHEN  RBM.ReportId = 20576  THEN -- HM patel report
				[sFee].[fReceiptMonthDetailGet](FR.ID)						 
			ELSE '' END) AS MonthDetail,
			
			DM.Title AS DepartmentName,
			FM.OrderIndex AS FeeOrderIndex,
			FHM.OrderIndex AS FeeHeadOrderIndex,
			FR.IsObsolete AS IsCancelReceipt,
			@lCurrencyCode AS CurrencyCode,
			BM.Title AS Batch,
			FR.ChequeDate AS ChequeDate,
			ISNULL(RBM.IsMonthDetailOnly,0) AS IsMonthDetailOnly,
	       ISNULL(RBM.IsFeeInvoiceHeadwise,0) AS IsFeeInvoiceHeadwise,
	       ISNULL(GroupTitle,'') AS GroupTitle
	FROM 
	
			sFee.tReceipt FR				
			INNER JOIN sFee.tReceiptDetail FRD
				ON FR.Id=FRD.ReceiptId AND FR.SourceTypeId=2001				
			INNER JOIN sFee.tFeeSetup FS
				ON FRD.FeeSetupId = FS.Id				
			INNER JOIN sFee.tFeeMaster FM
				ON FS.FeeId=FM.Id						
			INNER JOIN sFee.tFeeHeadMaster FHM
				ON FHM.Id=FM.FeeHeadId
			INNER JOIN sStudent.vStudentAcademic SA
				ON SA.AcademicId = FR.SourceId
			INNER JOIn sFinanceCommon.tPayTypeMaster PTM
				ON PTM.Id=FR.PayTypeId
			--LEFT JOIN sFee.tFeeAllocation FA
			--	ON FA.FeeSetupId=FS.Id
			INNER JOIN sFee.tReceiptBookMaster RBM 
				ON RBM.Id=FR.ReceiptBookId
			LEFT JOIN sSecurity.tUser U
				ON U.Id=FR.CreatedUserId
			INNER JOIN sSetup.tDepartmentMaster DM
				ON SA.DepartmentId =DM.Id
			LEFT JOIN sSetup.tOrganizationMaster OM
				ON OM.Id=DM.OrgId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = FR.BatchId
	WHERE 
	 FR.Id=@rReceiptId 
ORDER BY FS.StartDate,FM.OrderIndex ASC

END
GO
PRINT N'Altering [sFee].[pRptFeeReceiptListGet]...';


GO

		ALTER PROCEDURE [sFee].[pRptFeeReceiptListGet]
		
		@rReportId int=0,
		@rReceiptBookId int=0,
		@rAdmissionCategoryId int=0,
		@rClassId int=0,
		@rDivisionId int=0,
		@rFromDate date='',
		@rToDate date='',
		@rFromReceiptNo int=0,
		@rToReceiptNo int=0,
		@rBatchId int,
		@rUserId bigint=0,
		@rBuilder1 nvarchar(max)=0,
		@rBuilder2 nvarchar(max)=0,
		@rIsDetail bit=0,
		@rIsCancel bit=0,
		@rOrgId int,
		@rOrgGroupBatchId int,
		@rStatusId int=0,
		@rPaytypeId int=0,
		@rCommonBatch nvarchar(100)='',
		@rDepartmentId int=0,
		@rFromRollNo int=0,
	    @rToRollNo int=0,
	    @rCode nvarchar(20),
	    @rIsFilter bit=0,
	    @rIsHeader bit=0,
	    @rCreatedUserName nvarchar(100)='',
	    @rFeeHeadId nvarchar(max) = '',
	    @rIsDisplayOrgGroup bit=0,
	    @rIsDiscount bit = 0
	    
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 	
	SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		@rIsDetail AS IsDetail,
		@rIsCancel AS IsCancel,
		@rIsFilter As IsFilter,
		@rIsHeader As IsHeader,
		@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
		R.Id AS ReceiptId,
		R.ReceiptNumber,
		SA.ClassId,
		--SA.ClassName,
		SA.DivisionId,
		--SA.DivisionName,
		SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
		SA.RollNo,
		SA.Code,
		SA.Name,
		ISNULL(PTM.Title,'') AS PayType,
		ISNULL(R.ChequeNo,'') AS ChequeNo,
		ISNULL(R.BankName,'') AS BankName,
		R.ReceiptAmount,
		R.ReceiptDate,
		R.CreatedUserId,
		ISNULL(U.LoginTitle,'') AS UserName,
		ISNULL(RBM.Title,'') AS ReceiptBookTitle,
		ISNULL(RBM.BankName,'') AS ReceiptBookBank,
		ISNULL(RBM.BankAccountNumber,'') AS BankAccountNumber,
		ISNULL(R.ReceiptBookId,'0') As ReceiptBookId,
		ISNULL((CASE @rReportId WHEN 20461 THEN [sFee].[fReceiptFeeDetailGet](R.Id)
		 ELSE '' END),'') AS FeeDetail,
		 R.Remark,
		 R.DiscountAmount,
		 ISNULL(RBM.OrderIndex,0) AS ReceiptBookOrderIndex
		 
		 
			
  FROM 
			sFee.tReceipt R
		--INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
		--INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
		--INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
	 
		INNER JOIN sStudent.vStudentAcademic SA
			ON SA.AcademicId=R.SourceId AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))
		INNER JOIN sFinanceCommon.tPayTypeMaster PTM
			ON PTM.Id=R.PayTypeId
		LEFT JOIN sSecurity.tUser U
			ON U.Id=R.CreatedUserId
		INNER JOIN sFee.tReceiptBookMaster RBM 
			ON RBM.Id=R.ReceiptBookId
			
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 ((R.BatchId=@rBatchId) OR (@rBatchId=0))
	AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
	AND (R.IsObsolete = @rIsCancel) 
	AND (SA.StatusId=@rStatusId OR @rStatusId=0)
	AND (R.PayTypeId = @rPaytypeId OR @rPaytypeId=0)
	AND ((SA.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
	AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
	AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
	AND ((SA.Code=@rCode) OR (@rCode=''))
	AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
	AND ((ISNULL(U.DisplayTitle,'') like @rCreatedUserName) OR (ISNULL(@rCreatedUserName,'')=''))
	AND ((@rIsDiscount =1 AND R.DiscountAmount!=0) OR (@rIsDiscount=0))
	--AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
	ORDER BY R.ReceiptNumber
--	UNION ALL
	
--	SELECT 
--		R.Id AS ReceiptId,
--		0 AS ClassId,
--		--SA.ClassName,
--		0 AS DivisionId,
--		--SA.DivisionName,
--		EM.DepartmentId,
--		EM.DepartmentName AS ClassDept,
--		0 AS RollNo,
--		EM.Code,
--		EM.EmployeeName,
--		PTM.Title AS PayType,
--		R.ReceiptAmount
			
--  FROM 
--			sFee.tReceipt R
--		INNER JOIN sCommon.tSourceTypeMaster STM
--			ON STM.Id=R.SourceTypeId AND R.SourceTypeId = 95
--		INNER JOIN sHrm.vExtEmployeeMaster EM
--			ON EM.EmployeeId=R.SourceId
--		INNER JOIN sFinanceCommon.tPayTypeMaster PTM
--			ON PTM.Id=R.PayTypeId
			
--WHERE 
--		((EM.DepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))
--	AND ((R.ReceiptNumber >= @rFromReceiptNo) OR (@rFromReceiptNo = 0))
--	AND ((R.ReceiptNumber <= @rToReceiptNo) OR (@rToReceiptNo = 0))
--	AND ((R.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
--	AND ((R.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
--	AND (R.BatchId = @rBatchId)
END
GO
PRINT N'Altering [sFee].[pRptFeeSummaryGet]...';


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
  FROM 
  
			 sStudent.vStudentAcademic SA
		INNER JOIN 
		(
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName
			FROM sFee.tFeeSetup FS1
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
			AND ((SA1.ClassId=@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 (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
			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 (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 (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
					GROUP BY FeeSetupId,R.SourceId
		
		) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
		 INNER JOIN sSetup.tOrganizationMaster O ON
		 SA.OrgId = O.Id
		 INNER JOIN sFee.tReceiptBookMaster RBM 
			ON FS.ReceiptBookId=RBM.Id
		 LEFT JOIN 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.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))		
			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
PRINT N'Altering [sHostel].[pRoomListGet]...';


GO
ALTER PROCEDURE [sHostel].[pRoomListGet]
          
           @rHostelId int,
           @rRoomCategoryId int,
           @rBuildingId int
           
AS
SET NOCOUNT ON

BEGIN

SELECT 
		RM.Id,
		RM.HostelId,
		RM.Title,
		ISNULL(RM.StudentsPerRoom,0) AS StudentsPerRoom,
		ISNULL(COUNT(AR.SourceID),0) AS StudentsAllocated,
		RM.RoomCategoryId,
	    RCM.Title AS RoomCategory,
	    ISNULL(RCM.RoomCharge,0) AS RoomCharge,
	    ISNULL(BM.Title,'') AS BuildingName
      
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 RCM.Id = RM.RoomCateGoryId
		AND (RCM.Id=@rRoomCategoryId OR @rRoomCategoryId=0)
	  LEFT JOIN [sHostel].[tAssignRoom] AR ON AR.RoomId = RM.Id
	  LEFT JOIN sHostel.tBuildingMaster BM ON BM.HostelId=HM.Id AND BM.Id = RM.BuildingId
WHERE 
    ((RM.HostelId=@rHostelId) OR (@rHostelId=0))
	AND RM.IsObsolete=0
	AND (BM.Id=@rBuildingId OR @rBuildingId=0)
	Group by RM.Id,RM.HostelId,RM.Title,RM.StudentsPerRoom,RM.RoomCategoryId,RCM.Title,RCM.RoomCharge,BM.Title
END
GO
PRINT N'Altering [sHrm].[pEmployeeAttendanceAdd]...';


GO
ALTER PROCEDURE [sHrm].[pEmployeeAttendanceAdd]

	       @rEmployeeId bigint,
           @rForMonth tinyint,
           @rForYear smallint,
           @rTotalWorkingDays tinyint,
           @rLWP decimal(12,2),
           @rPaidLeave decimal(12,2)=0,
           @rBatchId int
           
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
BEGIN TRY
BEGIN TRANSACTION

IF EXISTS (Select 1 FROM sHrm.tEmployeeAttendance Where EmployeeId = @rEmployeeId AND ForYear = @rForYear AND ForMonth = @rForMonth AND BatchId = @rBatchId)  
  BEGIN
     DELETE FROM sHrm.tEmployeeAttendance Where EmployeeId = @rEmployeeId AND ForYear = @rForYear AND ForMonth = @rForMonth AND BatchId = @rBatchId
  END
   
	INSERT INTO [sHrm].[tEmployeeAttendance]
           (
           [EmployeeId]
           ,[ForMonth]
           ,[ForYear]
           ,[TotalWorkingDays]
           ,[LWP]
           ,[PaidLeave]
           ,[BatchId]
           )
     VALUES
           (
           @rEmployeeId,
           @rForMonth,
           @rForYear,
           @rTotalWorkingDays,
           @rLWP,
           @rPaidLeave,
           @rBatchId
           )
		 
	SELECT 1 AS RESULT
	COMMIT TRANSACTION
	END TRY
	BEGIN CATCH
	ROLLBACK TRANSACTION
	SELECT -1 AS RESULT
	END CATCH						
END
GO
PRINT N'Altering [sHrm].[pEmployeeAttendanceGet]...';


GO
ALTER PROCEDURE [sHrm].[pEmployeeAttendanceGet]
	 
	@rForYear  bigint,
	@rForMonth tinyint,
	@rBatchId int,
	@rOrgId int
 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

	DECLARE @lFirstDate Date
	SET @lFirstDate = CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'/'+CONVERT(NVARCHAR(2),@rForMonth)+'/01'))

BEGIN 
       SELECT  
         EM.Code AS EmployeeCode,
         EM.EmployeeName,   
         EM.EmployeeId,
         ISNULL(WD.TotalDays,0) AS TotalDays,      
         --ISNULL(WD.TotalDays,MY.NoOfDays) AS TotalDays,
         ISNULL(AT.TotalWorkingDays,ISNULL(WD.WorkingDays,0)) AS WorkingDays, 
         --ISNULL(AT.TotalWorkingDays,0) AS WorkingDays,
         ISNULL(AT.LWP,0) AS LWP,         
         ISNULL(AT.PaidLeave,0) AS PaidLeave,
         CONVERT(DECIMAL(12,2),(ISNULL(AT.TotalWorkingDays,0) - ISNULL(AT.LWP,0))) AS PresentDays,
         ISNULL(EM.EmployeeGrade,'') AS EmployeeGrade
         --CONVERT(INT,(ISNULL(WD.TotalDays,MY.NoOfDays) - ISNULL(AT.LWP,0))) AS PresentDays
    --     (Select NoOfLeave FROM sHrm.tLeave L Where L.BatchId = WD.BatchId AND L.EmployeeId = EM.EmployeeId
    --      AND DATEPART(MONTH,L.FromDate)=7
		  --AND DATENAME(YEAR,L.FromDate)=14) AS NoOfLeave
         --L.NoOfLeave
         --WD.WorkingDays - L.NoOfLeave AS PresentDay
    
        FROM 
		sHrm.vEmployeeCommonDetail EM 
		INNER JOIN sHrm.tWorkingDays WD ON  EM.EmployeeGradeId = WD.EmployeeGradeId
		AND WD.ForMonth=@rForMonth AND WD.ForYear=@rForYear AND WD.BatchId = @rBatchId
		LEFT JOIN sHrm.tEmployeeAttendance AT ON AT.EmployeeId=EM.EmployeeId		 
		AND AT.ForMonth=@rForMonth AND AT.ForYear=@rForYear
		--LEFT JOIN sSetup.fMonthYearForBatchGET(@rBatchId) AS MY ON 
		--MY.MonthNumber=@rForMonth AND MY.YearNumber=@rForYear		
		--LEFT JOIN sHrm.tLeave L ON L.EmployeeId = EM.EmployeeId  
    	WHERE EM.OrgID = @rOrgId 
    	AND ((EM.DateOfleaving >= @lFirstDate) OR ISNULL(EM.DateOfleaving,'') = '')
    	ORDER BY EM.Code
END
GO
PRINT N'Altering [sHrm].[pEmployeeCommunicationsAdd]...';


GO
ALTER PROCEDURE [sHrm].[pEmployeeCommunicationsAdd]
	 
	     @rEmployeeId bigint,
         @rPresentStreetOne nvarchar(150)='',
         @rPresentStreetTwo nvarchar(150)='',
         @rPresentStreetThree nvarchar(150)='',
         @rPresentCountry nvarchar(50)='',
         @rPresentState nvarchar(50)='',
         @rPresentCity nvarchar(50)='',
         @rPresentZipCode nvarchar(20)='',
         @rPresentContactNo nvarchar(20)='',
         @rPermanentStreetOne nvarchar(150)='',
         @rPermanentStreetTwo nvarchar(150)='',
         @rPermanentStreetThree nvarchar(150)='',
         @rPermanentCountry nvarchar(50)='',
         @rPermanentState nvarchar(50)='',
         @rPermanentCity nvarchar(50)='',
         @rPermanentZipCode nvarchar(20)='',
         @rPermanentContactNo nvarchar(20)='',
         @rEmergencyStreetOne nvarchar(150)='',
         @rEmergencyStreetTwo nvarchar(150)='',
         @rEmergencyStreetThree nvarchar(150)='',
         @rEmergencyCountry nvarchar(50)='',
         @rEmergencyState nvarchar(50)='',
         @rEmergencyCity nvarchar(50)='',
         @rEmergencyZipCode nvarchar(20)='',
         @rEmergencyContactNo nvarchar(20)='',
         @rPhoneNoCompany nvarchar(50)='',
         @rExtensionNo nvarchar(10)='',
         @rCompanyEmail nvarchar(100)='',
         @rPersonalEmail nvarchar(100)='',
         @rMobileNumber nvarchar(20)='',
         @rCreatedUserId bigint=0
    
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
IF NOT EXISTS(SELECT * FROM [sHrm].[tEmployeeCommunications] WHERE EmployeeId = @rEmployeeId)
BEGIN 
	--DECLARE @lNextNumber BIGINT     
	--EXECUTE sCommon.pTableRowIdGet 0, 'sStudent.tStudentCommunication', 0, 1, 1,@outNextNumber = @lNextNumber output

	INSERT INTO [sHrm].[tEmployeeCommunications]
           (
				[EmployeeId]
			   ,[PresentStreetOne]
			   ,[PresentStreetTwo]
			   ,[PresentStreetThree]
			   ,[PresentCountry]
			   ,[PresentState]
			   ,[PresentCity]
			   ,[PresentZipCode]
			   ,[PresentContactNo]
			   ,[PermanentStreetOne]
			   ,[PermanentStreetTwo]
			   ,[PermanentStreetThree]
			   ,[PermanentCountry]
			   ,[PermanentState]
			   ,[PermanentCity]
			   ,[PermanentZipCode]
			   ,[PermanentContactNo]
			   ,[EmergencyStreetOne]
			   ,[EmergencyStreetTwo]
			   ,[EmergencyStreetThree]
			   ,[EmergencyCountry]
			   ,[EmergencyState]
			   ,[EmergencyCity]
			   ,[EmergencyZipCode]
			   ,[EmergencyContactNo]
			   ,[PhoneNoCompany]
			   ,[ExtensionNo]
			   ,[CompanyEmail]
			   ,[PersonalEmail]
			   ,[MobileNumber]
			   ,[CreatedUserId]
			   ,[CreatedDateTime]
			   ,[UpdatedUserId]
			   ,[UpdatedDateTime]
           )
     VALUES
           (
			 @rEmployeeId,
			 @rPresentStreetOne,
			 @rPresentStreetTwo,
			 @rPresentStreetThree,
			 @rPresentCountry,
			 @rPresentState,
			 @rPresentCity,
			 @rPresentZipCode,
			 @rPresentContactNo,
			 @rPermanentStreetOne,
			 @rPermanentStreetTwo,
			 @rPermanentStreetThree,
			 @rPermanentCountry,
			 @rPermanentState,
			 @rPermanentCity,
			 @rPermanentZipCode,
			 @rPermanentContactNo,
			 @rEmergencyStreetOne,
			 @rEmergencyStreetTwo,
			 @rEmergencyStreetThree,
			 @rEmergencyCountry,
			 @rEmergencyState,
			 @rEmergencyCity,
			 @rEmergencyZipCode,
			 @rEmergencyContactNo,
			 @rPhoneNoCompany,
			 @rExtensionNo,
			 @rCompanyEmail,
			 @rPersonalEmail,
			 @rMobileNumber,
			 @rCreatedUserId,
			 sCommon.fGetDate(),
			 @rCreatedUserId,
			 sCommon.fGetDate()
        )
		SELECT 1 AS Result             
	END	 
	 ELSE
	 BEGIN
	 --SET @lNextNumber = @rStudentId
	  UPDATE [sHrm].[tEmployeeCommunications]
   SET 
      
       [PresentStreetOne] = @rPresentStreetOne
      ,[PresentStreetTwo] = @rPresentStreetTwo
      ,[PresentStreetThree] = @rPresentStreetThree
      ,[PresentCountry] = @rPresentCountry
      ,[PresentState] = @rPresentState
      ,[PresentCity] = @rPresentCity
      ,[PresentZipCode] = @rPresentZipCode
      ,[PresentContactNo] = @rPresentContactNo
      ,[PermanentStreetOne] = @rPermanentStreetOne
      ,[PermanentStreetTwo] = @rPermanentStreetTwo
      ,[PermanentStreetThree] = @rPermanentStreetThree
      ,[PermanentCountry] = @rPermanentCountry
      ,[PermanentState] = @rPermanentState
      ,[PermanentCity] = @rPermanentCity
      ,[PermanentZipCode] = @rPermanentZipCode
      ,[PermanentContactNo] = @rPermanentContactNo
      ,[EmergencyStreetOne] = @rEmergencyStreetOne
      ,[EmergencyStreetTwo] = @rEmergencyStreetTwo
      ,[EmergencyStreetThree] = @rEmergencyStreetThree
      ,[EmergencyCountry] = @rEmergencyCountry
      ,[EmergencyState] = @rEmergencyState
      ,[EmergencyCity] = @rEmergencyCity
      ,[EmergencyZipCode] = @rEmergencyZipCode
      ,[EmergencyContactNo] = @rEmergencyContactNo
      ,[PhoneNoCompany] = @rPhoneNoCompany
      ,[ExtensionNo] = @rExtensionNo 
      ,[CompanyEmail] = @rCompanyEmail 
      ,[PersonalEmail] = @rPersonalEmail 
      ,[MobileNumber] = @rMobileNumber     
      ,[UpdatedUserId] = @rCreatedUserId
      ,[UpdatedDateTime] =  sCommon.fGetDate() 
	   
	   WHERE EmployeeId = @rEmployeeId	   
	 END  
		SELECT 11 AS Result
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
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			
		
		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
		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].[pEmployeeMonthWiseLeaveGet]...';


GO
ALTER PROCEDURE [sHrm].[pEmployeeMonthWiseLeaveGet]
	 
	@rEmployeeId bigint,	 
	@rForMonth int,
	@rForYear int,
	@rBatchId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
 
 --SELECT     
 -- WorkingDays,
 -- EmployeeId,
 -- SUM(NoOfLEave) AS NoOfLeave
  
 --FROM (	 	
 
 SELECT   
         --EM.EmployeeId,           
         --ISNULL(WD.WorkingDays,0) AS WorkingDays,       
        ISNULL(SUM(ISNULL([sHrm].[fMonthWiseNoOfLeave](1,L.FromDate,L.ToDate,@rForMonth,@rForYear,L.LeavePeriodId,L.LeaveTypeId),0)),0) AS NoOfLeave,
        ISNULL(SUM(ISNULL([sHrm].[fMonthWiseNoOfLeave](0,L.FromDate,L.ToDate,@rForMonth,@rForYear,L.LeavePeriodId,L.LeaveTypeId),0)),0) AS PaidLeave
        FROM 
		sHrm.vEmployeeCommonDetail EM 
		LEFT JOIN
		sHrm.tLeave L 
	    ON L.EmployeeId = EM.EmployeeId	 AND L.BatchId = @rBatchId 	AND L.StatusId = 550 -- apporved 
    	WHERE EM.EmployeeId = @rEmployeeId  
 
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)=''
	
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]
           )
     VALUES
           (
           @rEmployeeId,
           @rEPFNumber,
           @rIsVPFDeduction,
           @rVPFContributionId,
           @rVPFContributionEffectiveFrom,
           @rVPFPercentage,
           @rVPFAmount,
           @rESINumber,
           @rBankName,
           @rBranch,
           @rAccountNumber,
           @rIFSCNumber,
           @rPanNumber,
           @rIncomeTaxStatusId,
           @rUpdatedUserId,
           sCommon.fGetDate(),
           @rIncrementDate,
           @rBasicPay,
           @rPayrollId,
           @rPayrollGroupId,
           @rPayscale
           )
     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
	     
	  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
	FROM 
			[sHrm].[tEmployeeStatutoryAndOther] 
			 
	Where 
			 EmployeeId = @rEmployeeId	  
END
GO
PRINT N'Altering [sHrm].[pRptEmployeeAllDetailList]...';


GO
ALTER PROCEDURE [sHrm].[pRptEmployeeAllDetailList]
	
	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='',
	@rReportId int=0,
	@rOrgId smallint,
	@rStrEmployeeId nvarchar(max),
	@rEmployeeTypeId [int],
	@rDepartmentId [int]= 0,
	@rGradeId [int]= 0,
	@rDesignationId [int]= 0,
	@rGenderId [int]= 0,		
	@rEmployeeId [bigint]= 0,
	@rAgeFrom nvarchar(10),
	@rAgeTo nvarchar(10),
	@rEmployeeCode nvarchar(50)='',
	@rEmployeeGroupId smallint,
	@rEmployeeStatusId smallint
									
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

BEGIN
DECLARE @lIsOnPrePrinted bit = 0

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

SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 129 AND SourceTypeId = 1016 AND SourceId = @rOrgId
	
	IF (@lConfigValue IS NULL) OR (@lConfigValue = 'False')
	SET @lIsOnPrePrinted = 0
	ELSE
	SET @lIsOnPrePrinted = 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,
		    EM.Id,
	        EM.Id AS EmployeeId,
	        EM.Code,
	        EM.EmployeeName,
	       	EM.FirstName,
			EM.MiddleName,
			EM.LastName,	
			EM.ShortName,
			EM.OrgID,
			EM.GenderId,
			EM.DateOfBirth,
			EM.DateOfJoining,
			EM.DateOfleaving,
			EM.ReasonOfleaving,
			EM.JobRemark,
			EM.StatusId,
			EM.CreatedUserId,
			EM.CreatedDateTime,
			EM.UpdatedUserId,
			EM.UpdatedDateTime,
			EM.IsObsolete,
			EM.PhoneNoCompany,
			EM.CompanyEmail,
			EM.ExtensionNo,
			EM.UserId,
			EM.DepartmentId,
			EM.DepartmentCode,  
			EM.DepartmentName,
		    EM.MobileNumber,
			EM.EmployeeTypeId,
			EM.DesignationId,
			EM.Designation,
			EM.ParticipantSourceTypeId,
			EM.EmployeeGroup,
			EM.EmployeeGroupId,
			EM.EmployeePhoto,
			EC.PresentStreetOne,
			EC.PresentStreetTwo,
			EC.PresentStreetThree,
			EC.PresentCity,
			EC.PresentState,
			EC.PresentCountry,
			EC.PresentZipCode,
			EC.PresentContactNo,
			@lIsOnPrePrinted AS IsOnPrePrinted,
			GM.Title AS Gender,
			EM.EmployeeType,
			EM.Qualification,
			@lIsDisplayImageHeader AS IsDisplayImageHeader,
			OI.CertificateHeaderA4  
			
	FROM 
			[sHrm].[vExtEmployeeMaster] EM
			INNER JOIN sHrm.tEmployeeCommunications EC ON EM.Id=EC.EmployeeId
			LEFT JOIN sCommon.tGenderMaster GM ON GM.Id = EM.GenderId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=EM.OrgId
			left JOIN sSetup.tOrgImages OI ON OI.OrgId = OM.Id
	WHERE
			((EM.Code LIKE @rEmployeeCode)OR @rEmployeeCode = '' )
	   AND (ISNULL(EM.EmployeeId,0) NOT IN( SELECT cast(item as bigint) FROM  sCommon.fnsplit(@rStrEmployeeId,',')) OR @rStrEmployeeId='') 
	   AND (EM.EmployeeTypeId = @rEmployeeTypeId OR @rEmployeeTypeId = 0)
	   AND (EM.DepartmentId = @rDepartmentId OR @rDepartmentId = 0)
	   AND (EM.StatusId = @rEmployeeStatusId OR @rEmployeeStatusId = 0)
	   AND (EM.EmployeeGroupId=@rEmployeeGroupId OR @rEmployeeGroupId=0)
	   AND (EM.EmployeeGradeId = @rGradeId OR @rGradeId = 0)
	   AND (EM.DesignationId = @rDesignationId OR @rDesignationId = 0)	 	   
	   AND (EM.GenderId = @rGenderId OR @rGenderId = 0)  	    
	   AND (EM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)	   
	   --AND ((DATEDIFF(yy,EM.DateOfBirth,GETDATE()) <= @rAgeTo) OR (ISNULL(@rAgeTo,0)=0))
	   --AND ((DATEDIFF(yy,EM.DateOfBirth,GETDATE()) >= @rAgeFrom)OR (ISNULL(@rAgeFrom,0)=0))
	   AND  EM.OrgId = @rOrgId
END
GO
PRINT N'Altering [sPayroll].[pPayProcessEmployeeAdd]...';


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

BEGIN

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


GO




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

EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sPayroll.tPayrollMaster',@lNextNumber = @lNextNumber output
 
INSERT INTO [sPayroll].[tPayrollMaster]
           (
			[Id],
           [Code],
           [Title],
           [CreatedUserId],
           [CreatedDateTime],
           --[UpdatedUserId],
           --[UpdatedDateTime],
           [OrgGroupId],
           [IsActive]
           )
     VALUES
           (
            @lNextNumber,
           @rCode ,
           @rTitle ,
           @rCreatedUserId, 
           sCommon.fGetDate(),
           --@rCreatedUserId,
           --sCommon.fGetDate(), 
           @rOrgGroupId, 
           @rIsActive
           ) 
           
           	INSERT INTO sSecurity.tUserAccess
           (
           SourceTypeId
           ,SourceId
           ,[UserId]
           
           )
		   SELECT 
		   2019
		   ,@lNextNumber
		   ,@rCreatedUserId	
           
           SELECT 1 AS Result
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE [sPayroll].[tPayrollMaster]
	    SET
			code = @rCode,
			Title = @rTitle,
			UpdatedUserId= @rCreatedUserId,
			UpdatedDateTime =sCommon.fGetDate(),	
			IsActive = @rIsActive
	      
	      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 [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
	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
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 [sSetup].[pOrganizationMasterAdd]...';


GO
ALTER PROCEDURE [sSetup].[pOrganizationMasterAdd]
	 
	@rId int,
	@rCode nvarchar(20),
	@rTitle nvarchar(100),
	@rDisplayTitle nvarchar(100),
	@rAffiliationId smallint,
	@rLanguageId smallint,
	--@rInstituteTypeId smallint,
	--@rInstituteSubTypeId smallint,
	@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),
	@rFaxNo nvarchar(50),
	@rReportOrgTitle nvarchar(200),
	@rSmallAddress1 nvarchar(100),
	@rSmallAddress2 nvarchar(100),
	@rRegistrationDetail nvarchar(200),
	@rCreatedUserId bigint,
	@rUpdatedUserId bigint,
	@rIsObsolete bit,
	@rOrgGroupId smallint,
	@rOrgLogo varbinary(max),
	@rIsLogo bit,
	@rEmployeeId bigint,
	@rOrderIndex int,
	--@rIcardOrgTitle nvarchar(200),
	--@rIcardAddress1 nvarchar(200),
	--@rIcardAddress2 nvarchar(200),
	--@rICardAddress3 nvarchar(200),
	--@rLabelColor nvarchar(20),
	--@rDetailColor nvarchar(20),
	--@rHeaderColor nvarchar(20),
	@rOrgSubGroupId int=0,
	@rTermPatternId int=0,
	@rNameFormateId tinyint = 1,
	@rWeekOffs nvarchar(20),
	@rReportOrgGroupTitle nvarchar(200)='',
	@rDegreeAwarded nvarchar(100) = '',
	@rShortCode nvarchar(20) = '',
	@rNoOfTerm tinyint=0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	BEGIN TRANSACTION	
	IF EXISTS (SELECT 1 FROM sSetup.tOrganizationMaster WHERE @rId = 0 AND Code=@rCode)
	BEGIN
		SELECT -100 AS RESULT
		RETURN
	END
	
	IF(@rId=0)
	BEGIN
	SET @rId=@rCode
		 
	INSERT INTO sSetup.tOrganizationMaster
		(
			Id,
			Code,
			Title,
			DisplayTitle,
			AffiliationId,
			LanguageId,
			--InstituteTypeId,
			--InstituteSubTypeId,
			StreetOne,
			StreetTwo,
			StreetThree,
			CityName,
			StateName,
			CountryName,
			ZipCode,
			HomePage,
			PhoneNo,
			FaxNo,
			ReportOrgTitle,
			SmallAddress1,
			SmallAddress2,
			RegistrationDetail,
			CreatedUserId,
			CreatedDateTime,
			IsObsolete,
			OrgGroupId,
			EmployeeId,
			OrderIndex,
			--,
			--IcardOrgTitle,
			--IcardAddress1,
			--IcardAddress2,
			--ICardAddress3,
			--LabelColor,
			--DetailColor,
			--HeaderColor,
			OrgSubGroupId,
			TermPatternId,
			StudentNameFormatId,
			WeekOffs,
			ReportOrgGroupTitle,
			DegreeAwarded,
			ShortCode,
			NoOfTerm
			--OrgLogo
		)
	VALUES
		(
			@rCode,
			@rCode,
			@rTitle,
			@rDisplayTitle,
			@rAffiliationId,
			@rLanguageId,
			--@rInstituteTypeId,
			--@rInstituteSubTypeId,
			@rStreetOne,
			@rStreetTwo,
			@rStreetThree,
			@rCityName,
			@rStateName,
			@rCountryName,
			@rZipCode,
			@rHomePage,
			@rPhoneNo,
			@rFaxNo,
			--@rReportOrgTitle,
			@rTitle,
			@rSmallAddress1,
			@rSmallAddress2,
			@rRegistrationDetail,
			@rCreatedUserId,
			sCommon.fGetDate(), 
			@rIsObsolete,
			@rOrgGroupId,
			@rEmployeeId,
			@rOrderIndex,
			--,
			--@rIcardOrgTitle,
			--@rIcardAddress1,
			--@rIcardAddress2,
			--@rIcardAddress3,
			--@rLabelColor,
			--@rDetailColor,
			--@rHeaderColor,
			@rOrgSubGroupId,
			@rTermPatternId,
			1,
			ISNULL(@rWeekOffs,'0'),
			@rReportOrgGroupTitle,
			@rDegreeAwarded,
			@rShortCode,
			@rNoOfTerm
			--@rOrgLogo
		)
		 EXECUTE [sCommon].[pOrganizationSetupAdd] @rId
		 --print @rId
		 SELECT @rCode AS Result
		             
	END	 
	 ELSE
	 BEGIN
	 --SET @lNextNumber = @rId
	    UPDATE  sSetup.tOrganizationMaster
	    SET
			Code=@rCode,
			Title=@rTitle,
			DisplayTitle=@rDisplayTitle,
			AffiliationId=@rAffiliationId,
			LanguageId=@rLanguageId,
			--InstituteTypeId=@rInstituteTypeId,
			--InstituteSubTypeId=@rInstituteSubTypeId,
			StreetOne=@rStreetOne,
			StreetTwo=@rStreetTwo,
			StreetThree=@rStreetThree,
			CityName=@rCityName,
			StateName=@rStateName,
			CountryName=@rCountryName,
			ZipCode=@rZipCode,
			HomePage=@rHomePage,
			PhoneNo=@rPhoneNo,
			FaxNo=@rFaxNo,
			ReportOrgTitle=@rReportOrgTitle,
			SmallAddress1=@rSmallAddress1,
			SmallAddress2=@rSmallAddress2,
			RegistrationDetail=@rRegistrationDetail,
			UpdatedUserId=@rUpdatedUserId,
			UpdatedDateTime=sCommon.fGetDate(), 
			IsObsolete=@rIsObsolete,
			OrgGroupId=@rOrgGroupId,
			EmployeeId=@rEmployeeId,
			OrderIndex=@rOrderIndex,	 
			--IcardOrgTitle=@rIcardOrgTitle,
			--IcardAddress1=@rIcardAddress1,
			--IcardAddress2=@rIcardAddress2,
			--IcardAddress3=@rIcardAddress3,
			--LabelColor=@rLabelColor,
			--DetailColor=@rDetailColor,
			--HeaderColor=@rHeaderColor,
			OrgSubGroupId=@rOrgSubGroupId,
			TermPatternId=@rTermPatternId,
			StudentNameFormatId= @rNameFormateId,
			WeekOffs=@rWeekOffs,
			ReportOrgGroupTitle=@rReportOrgGroupTitle,
			DegreeAwarded=@rDegreeAwarded,
			ShortCode =@rShortCode,
			NoOfTerm = @rNoOfTerm
			--OrgLogo=@rOrgLogo
	      
	      
	      WHERE Id = @rId 
	      
	      IF(@rIsLogo = 1)
	      BEGIN
			UPDATE  sSetup.tOrganizationMaster
				SET
					OrgLogo=@rOrgLogo
			WHERE Id = @rId 
	      END
	      
	      SELECT @rId AS Result	   
	 END  
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sSetup].[pOrganizationMasterGet]...';


GO
ALTER PROCEDURE [sSetup].[pOrganizationMasterGet]
	 
	 @rId int = 0,
	 @rCode nvarchar(20),
	 @rTitle nvarchar(100),
	 @rOrgGroupId smallint,
	 @rIsSearch bit
	 
	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 
	
			OM.Id,
			OM.Code,
			OM.Title,
			OM.DisplayTitle,
			OM.AffiliationId,
			AM.Title AS AffiliationTitle,
			OM.LanguageId,
			LM.Title AS LanguageTitle,
			--OM.InstituteTypeId,
			--ITM.Title AS InstituteTypeTitle,
			--OM.InstituteSubTypeId,
			--ISTM.Title AS InstituteSubTypeTitle,
			OM.StreetOne,
			OM.StreetTwo,			 
			OM.StreetThree,
			OM.CityName,
			OM.StateName,
			OM.CountryName,
			OM.ZipCode,
			OM.HomePage,
			OM.PhoneNo,
			OM.FaxNo,
			OM.ReportOrgTitle,
			OM.SmallAddress1,
			OM.SmallAddress2,
			OM.RegistrationDetail,			 
			OM.CreatedUserId,
			OM.CreatedDateTime,
			OM.UpdatedUserId,
			OM.UpdatedDateTime,
			OM.IsObsolete,
			OM.OrgGroupId,
			OM.OrgLogo,
			ISNULL(OM.WeekOffs,0) AS WeekOffs ,
			--OM.IcardOrgTitle,
			--OM.IcardAddress1,
			--OM.ICardAddress2,
			--OM.ICardAddress3,
			--OM.LabelColor,
			--OM.DetailColor,
			--OM.HeaderColor,
			ISNULL(OM.OrgSubGroupId,0) AS OrgSubGroupId, 
			--OB.Code AS BatchName,
			--OB.FromDate,
			--OB.ToDate,
			ISNULL(OM.EmployeeId,0) AS EmployeeId,
		    ISNULL(EM.Code,'') AS EmployeeCode,
		    ISNULL(EM.FirstName,'')+ ' ' + ISNULL(EM.MiddleName,'')+ ' ' + ISNULL(EM.LastName,'') AS EmployeeName,
			ISNULL(OM.OrderIndex,0) AS OrderIndex,
			ISNULL(OM.TermPatternId,0) AS TermPatternId,
			ISNULL(OM.StudentNameFormatId,0) AS NameFormateId,
			ISNULL(OM.ReportOrgGroupTitle,'') AS ReportOrgGroupTitle,
			ISNULL(OM.DegreeAwarded,'') AS DegreeAwarded,
			ISNULL(OM.ShortCode,'') AS ShortCode,
			ISNULL(OM.NoOfTerm,'') AS NoOfTerm
      
  FROM 
            sSetup.tOrganizationMaster OM
           INNER JOIN sSetup.tAffiliationMaster AM
				ON AM.Id=OM.AffiliationId
		  -- INNER JOIN sSetup.tInstituteTypeMaster ITM
				--ON ITM.Id=OM.InstituteTypeId
		  -- INNER JOIN sSetup.tInstituteSubTypeMaster ISTM
				--ON ISTM.Id=OM.InstituteSubTypeId
		   INNER JOIN sSetup.tLanguageMaster LM
				ON LM.Id=OM.LanguageId
		  -- INNER JOIN sSetup.tOrgGroupBatchMaster OB 
				--ON OB.OrgGroupId=OM.OrgGroupId 
		   LEFT JOIN sHrm.tEmployeeMaster EM 
				ON EM.Id = OM.EmployeeId AND EM.IsObsolete = 0
  WHERE 
  
        ((OM.Id = @rId) OR (@rId = 0))
	AND ((OM.Code like @rCode) OR (ISNULL(@rCode,'') = '')) 
	AND ((OM.Title like @rTitle) OR (ISNULL(@rTitle,'') = '')) 
	AND ((OM.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId = 0))
	AND (OM.Id != 1)
 ORDER BY OM.OrderIndex
END
GO
PRINT N'Altering [sStudent].[pAcademicAdd]...';


GO
ALTER PROCEDURE [sStudent].[pAcademicAdd]
	 
	@rAcademicId bigint,
	@rStudentId bigint,
	@rClassId int,
	@rDivisionId int,
	@rRollNo int,
	@rOrgId int,
	@rBatchId int,
	@rCreatedUserId bigint,
	@rUpdatedUserId bigint
	
	
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
		)		
        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].[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) = ''
	 
	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
			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].[pRptStudentIcardGet]...';


GO



ALTER PROCEDURE [sStudent].[pRptStudentIcardGet]
	 
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rOrgId smallint,
	 @rBatchId int,
	 @rStrCode nvarchar(max),
	 @rClassId int,
	 @rDivisionId int,
	 @rStudentId bigint,
	 @rFromRollNo int,
	 @rToRollNo int,
	 @rStatusId int,
	 @rDateOfBirth int,
	 @rDepartmentId int
	 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

DECLARE @lIcardBorder nvarchar(10)

SELECT @lIcardBorder = ItemValue FROM sConfig.tConfigurationSetup WHERE configurationId = 130 AND SourceTypeId = 1016 AND SourceId = @rOrgId --ItemKey = 'sConfig.tConfigurationSetup' 
	SELECT			 
			SD.AcademicId,
			SD.StudentId, 
			SD.ClassId,
			SD.DivisionId,
			SD.ClassName,
			SD.DivisionName,
			SD.ClassDivision,
			SD.Batch,
			SD.Code,
			SD.Number AS StudentNumber,
			SD.RegistrationNumber,	
			SD.RollNo,				
			SD.FirstName,
			SD.MiddleName,			
			SD.LastName,
			SD.Name,		 
			SD.StatusId,
			SD.DateOfBirth,		
			SD.BloodGroup,
			ISNULL(SD.PresentStreetone,'') AS PresentStreetone,
			ISNULL(SD.PresentStreetTwo,'') AS PresentStreetTwo,
			ISNULL(SD.PresentStreetThree,'') AS PresentStreetThree,
		    ISNULL(SD.PresentCity,'') AS PresentCity,
		    ISNULL(SD.PresentZipCode,'') AS PresentZipCode,
			SD.PresentContactNo,						 
			SD.ParentContactNo AS ParentContactNo,
			SD.StudentContactNo,			
			SD.StudentPhoto,
			SD.AdmissionCategory, 
			SD.DivisionOrder,		 
			OM.Title AS OrgName,	
			ISNULL(HM.Title,'') AS HouseName,	
			OM.PrincipalSignature,
			ISNULL(ICO.ICardOrgTitle,'') AS ICardOrgTitle,
			ISNULL(ICO.ICardAddress1,'') AS ICardAddress1,
			ISNULL(ICO.ICardAddress2,'') AS ICardAddress2,
			ISNULL(ICO.ICardAddress3,'') AS ICardAddress3,			
			OM.OrgLogo AS ICardLogo,
			
			--ISNULL(ICO.ICardBackground,0) AS ICardBackground,	
			--ISNULL(ICO.ICardBackBackground,0) AS ICardBackBackground,	
			
			 ICO.ICardBackground  AS ICardBackground,	
			 ICO.ICardBackBackground  AS ICardBackBackground,						
			  
			ISNULL(ICO.LabelColor,'Black') AS LabelColor,
			ISNULL(ICO.DetailColor,'Black') AS DetailColor,
			ISNULL(ICO.HeaderColor,'Black') AS HeaderColor,
			ISNULL(SF.FatherName,'') AS FatherName,
			ISNULL(SF.FatherContactNo,'') AS FatherContactNo,
			ISNULL(SF.MotherName,'') AS MotherName,
			ISNULL(SF.MotherContactNo,'') AS MotherContactNo,
			ISNULL(BRM.Title,'') AS RouteName,
			ISNULL(BRDM.Title,'') AS PickupPoint,
			@lIcardBorder AS IcardBorder,
			HM.ColorCode,
			OM.OrgLogo,
			OM.SmallAddress1
	FROM 
			sStudent.vStudentAllDetail SD
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=SD.OrgId
			INNER JOIN sStudent.tStudentOther SO ON SD.StudentId = So.StudentId 			
			LEFT JOIN sActivity.tHouseMaster HM ON SO.HouseId = HM.Id 
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SD.StudentId 
			LEFT JOIN sTransport.tAssignRoute AR ON AR.SourceId =SD.StudentId 
			LEFT JOIN sTransport.tBusRouteDestinationMaster BRDM ON BRDM.Id =AR.PickupDestinationId 
			LEFT JOIN sTransport.tBusRouteMaster BRM ON BRM.Id =BRDM.BusRouteId 
			LEFT JOIN sStudent.tICardOrg ICO ON SD.OrgId = ICO.OrgId
			--LEFT JOIN sSetup.tOrganizationConfiguration OC ON OM.Id = OC.OrgId
			 
	WHERE 
		SD.OrgId=@rOrgId
		AND	SD.BatchId = @rBatchId 
		AND (ISNULL(SD.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rStrCode,',')) OR @rStrCode='') 
		AND ((SD.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SD.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((SD.StudentId=@rStudentId) OR (@rStudentId=0))
		AND ((SD.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((SD.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((SD.StatusId=@rStatusId)OR(@rStatusId=0))
		AND ((SD.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		 
END
GO
PRINT N'Altering [sStudent].[pStudentCustomSearchGet]...';


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

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

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


GO

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

--BEGIN TRY
--BEGIN TRANSACTION

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

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

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

		IF(@rSubCategoryField = 'RelativeDateOfBirth' )
		BEGIN
		SET @sql='UPDATE sStudent.tStudentFamily SET '+@rSubCategoryField+' = null WHERE RelativeDateOfBirth=''1900-01-01'''
			Exec sp_executesql @sql
		END		
				
		
		
		Drop Table ListofData
			 SELECT 1 AS StatusCode
	    END
	    
    Else IF(@rCategoryId= 5)
	     BEGIN
		insert into ListofData
		select 0,E.StudentId,E.SubCategory,E.UpdatedUserId,0
		from
		(
				SELECT StudentId,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Students/Students', 2)
				WITH (
						StudentId BIGINT, 
						SubCategory nvarchar(100),
						UpdatedUserId bigint)	
						)E 	
		UPDATE ListofData SET IsExist=1 WHERE StudentId NOT IN(SELECT StudentId FROM sStudent.tStudentHealth) 
		
		set @sql='INSERT INTO sStudent.tStudentHealth 
					(StudentId,'+@rSubCategoryField+',UpdatedUserId,UpdatedDateTime)
					SELECT
						LD.StudentId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
					FROM
						ListofData LD WHERE LD.IsExist=1'				
		Exec sp_executesql @sql
		set @sql='UPDATE sStudent.tStudentHealth set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sStudent.tStudentHealth SA 
					INNER JOIN ListofData LD ON SA.StudentId=LD.StudentId AND IsExist=0'
		
		Exec sp_executesql @sql
		Drop Table ListofData
			 SELECT 1 AS StatusCode
	    END		 
	 
	 Else IF(@rCategoryId= 6)
	    BEGIN
		insert into ListofData
		select E.Id,0,E.SubCategory,E.UpdatedUserId,0
		from
		(
				SELECT Id,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Students/Students', 2)
				WITH (
						Id BIGINT, 
						SubCategory nvarchar(100),
						UpdatedUserId bigint)	
						)E 	
		UPDATE ListofData SET IsExist=1 WHERE Id NOT IN(SELECT AcademicId FROM sStudent.tAcademicDetail) 
		
		set @sql='INSERT INTO sStudent.tAcademicDetail 
					(AcademicId,'+@rSubCategoryField+')
					SELECT
						LD.Id,Ld.SubCategory
					FROM
						ListofData LD WHERE LD.IsExist=1'				
		Exec sp_executesql @sql
		set @sql='UPDATE sStudent.tAcademicDetail set '+@rSubCategoryField+' = LD.SubCategory
					from sStudent.tAcademicDetail AD 
					INNER JOIN ListofData LD ON AD.AcademicId=LD.Id AND IsExist=0'
		
		Exec sp_executesql @sql
		Drop Table ListofData
			 SELECT 1 AS StatusCode
	    END	
	    
	Else IF(@rCategoryId= 7)
	     BEGIN
		insert into ListofData
		select 0,E.StudentId,E.SubCategory,E.UpdatedUserId,0
		from
		(
				SELECT StudentId,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Students/Students', 2)
				WITH (
						StudentId BIGINT, 
						SubCategory nvarchar(100),
						UpdatedUserId bigint)	
						)E 	
		UPDATE ListofData SET IsExist=1 WHERE StudentId NOT IN(SELECT Id FROM sStudent.tStudentMaster) 
		
		--set @sql='INSERT INTO sStudent.tStudentMaster 
		--			(StudentId,'+@rSubCategoryField+',UpdatedUserId,UpdatedDateTime)
		--			SELECT
		--				LD.StudentId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
		--			FROM
		--				ListofData LD WHERE LD.IsExist=1'				
		--Exec sp_executesql @sql
		
		set @sql='UPDATE sStudent.tStudentMaster set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sStudent.tStudentMaster SA 
					INNER JOIN ListofData LD ON SA.Id=LD.StudentId AND IsExist=0'
		
		Exec sp_executesql @sql
		Drop Table ListofData
			 SELECT 1 AS StatusCode
	    END			 
	 
	 
	 
	 Else IF(@rCategoryId= 8)
	     BEGIN
		insert into ListofData
		select 0,E.StudentId,E.SubCategory,0,0
		from
		(
				SELECT StudentId,SubCategory FROM
				OPENXML (@loDoc, '/Students/Students', 2)
				WITH (
						StudentId BIGINT, 
						SubCategory nvarchar(100)
						 )	
						)E 	
		UPDATE ListofData SET IsExist=1 WHERE StudentId NOT IN(SELECT StudentId FROM sStudent.tStudentadditional) 
		
		set @sql='INSERT INTO sStudent.tStudentadditional
					(StudentId,'+@rSubCategoryField+')
					SELECT
						LD.StudentId,Ld.SubCategory
					FROM
						ListofData LD WHERE LD.IsExist=1'				
		Exec sp_executesql @sql
		
		set @sql='UPDATE sStudent.tStudentadditional set '+@rSubCategoryField+' = LD.SubCategory 
					 
					from sStudent.tStudentadditional SA 
					INNER JOIN ListofData LD ON SA.StudentId=LD.StudentId AND IsExist=0'
		
		Exec sp_executesql @sql
		Drop Table ListofData
			 SELECT 1 AS StatusCode
	    END	
	    
END 
 

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


GO



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

BEGIN 
	 
		BEGIN
			SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
			SET @rLastName = sCommon.fSearchStringGet(@rLastName)
		END
	IF(@rRollNo IS NULL)
	BEGIN
	SELECT 
			SF.AcademicId,
			SF.StudentId,
			SF.FirstName + ' ' + SF.MiddleName + ' ' + SF.LastName AS Name,
			SF.FirstName,
			SF.LastName,
			SF.Code,
			SF.BatchId,
			BM.Title AS BatchName,
			SF.ClassId,
			SF.ClassName,
			SF.DivisionId,
			SF.DivisionName,
			SF.Number,
			ISNULL(SF.RollNo,0) AS RollNo,
			SF.StatusId,
			SF.StatusName,
			SF.OrgId,
			ISNULL(OM.DisplayTitle,'') AS DisplayTitle,
			SB.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
           --INNER JOIN sSetup.tOrgGroupBatchMaster OGB ON OGB.OrgGroupId = OGM.Id 
           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.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(OM.DisplayTitle,'') AS DisplayTitle,
			SB.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.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.BatchStatusId =@rBatchStatusId) OR (@rBatchStatusId=0))
ORDER BY SF.ClassId,SF.DivisionId,SF.RollNo
END
  
		
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.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.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.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.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.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.BatchStatusId =@rBatchStatusId) OR (@rBatchStatusId=0))
ORDER BY SF.ClassId,SF.DivisionId,SF.RollNo

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


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

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

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


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

BEGIN 

	DECLARE @lAcademicId bigint
	DECLARE @lIsAdmissionCategoryChange bit
	SET @lIsAdmissionCategoryChange=1
	SELECT @lAcademicId=AcademicId FROM sStudent.vStudentAcademic SA 
	WHERE 
			((SA.Code=@rCode)OR(ISNULL(@rCode,'')=''))
			AND ((SA.StudentId=@rStudentId)OR(@rStudentId=0))
			AND(SA.OrgId=@rOrgId)
			AND(SA.BatchId=@rBatchId)
			
	IF(ISNULL(@lAcademicId,0) != 0)
	BEGIN
		IF EXISTS (SELECT 1 FROM sFee.tFeeAllocation WHERE SourceTypeId=2001 AND SourceId=@lAcademicId)
		BEGIN
			SET @lIsAdmissionCategoryChange=0
		END
		ELSE IF EXISTS (SELECT 1 FROM sFee.tFeeOptional WHERE SourceTypeId=2001 AND SourceId=@lAcademicId)
		BEGIN
			SET @lIsAdmissionCategoryChange=0
		END
		ELSE IF EXISTS (SELECT 1 FROM sFee.tReceipt WHERE SourceTypeId=2001 AND SourceId=@lAcademicId)
		BEGIN
			SET @lIsAdmissionCategoryChange=0
		END
	END	
			
	 --IF(@rIsSearch=1)
		--BEGIN
		--	SET @rCode = sCommon.fSearchStringGet(@rCode)
		--	SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		--END
	
	SELECT 
			SA.StudentId AS Id,
			ISNULL(SA.Code,'') AS Code,
			ISNULL(SA.Number,0)AS Number,
			ISNULL(SA.RegistrationNumber,'') AS RegistrationNumber,
			SA.FirstName,
			ISNULL(SA.MiddleName,'')AS MiddleName,
			SA.LastName,
			SA.OrgId,
			ISNULL(SA.AdmissionCategoryId,0) AS AdmissionCategoryId,
			SA.StatusId,
			SA.RecordStatusId,
			SA.FirstName+' '+SA.LastName AS Name,
			SA.AcademicId,
			SA.ClassId,
			SA.DivisionId,
			ISNULL(SA.RollNo,0) AS RollNo,
			SA.BatchId,
			--SA.DateOfBirth,
			ISNULL(SO.GenderId,0) AS GenderId,
			SA.ClassName+'-'+SA.DivisionName AS ClassDiv,
			ISNULL(SA.AdmissionCategoryId,0) AS AdmissionCategoryId,
			@lIsAdmissionCategoryChange AS IsAdmissionCategoryChange
      
  FROM 
           sStudent.vStudentAcademic SA
     LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=SA.StudentId
  WHERE 
 
			((SA.Code=@rCode)OR(ISNULL(@rCode,'')=''))
			AND ((SA.StudentId=@rStudentId)OR(@rStudentId=0))
			AND((SA.Number=@rNumber) OR (@rNumber=0))
			AND(SA.OrgId=@rOrgId)
			AND(SA.BatchId=@rBatchId)
END
GO
PRINT N'Altering [sStudent].[pValidateImportStudent]...';


GO
ALTER PROCEDURE [sStudent].[pValidateImportStudent]

	@rOrgGroupId int,
    @rOrgId int,
	@rXmldoc [nvarchar](max)
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
DECLARE @lCount INT
DECLARE @lInterrorCode INT,
		@intDoc INT,
        @lCode nvarchar(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) = ''
       
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)
        
        --Id1 bigint NULL,
        --departmentId int NULL
 
  )
  INSERT INTO #tTable1
	(
	    Code,
	    RegistrationNumber, 
	    FirstName,
	    LastName,
	    Class,
	    Division,
	    AdmissionStandard,
	    AdmissionDate,
	    DOB,
	    Gender,
	    --AdmissionCategory,
	    Religion,
	    CastCategory
    ) 
   SELECT
        Code,
	    RegistrationNumber, 
	    FirstName,
	    LastName,
	    Class,
	    Division,
	    AdmissionStandard,
	    AdmissionDate,
	    DOB,
	    Gender,
	    --AdmissionCategory,
	    Religion,
	    CastCategory    
   
   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'
   )   
EXEC sp_xml_removedocument @intDoc
		
SELECT @lCount =  COUNT(Id) FROM #tTable1
 
WHILE @lCount > 0 
  BEGIN
  
       SELECT         
         
         @lCode = Code, 
         @lRegistrationNumber = RegistrationNumber,
         @lAdmissionDate = AdmissionDate,
         @lDOB=DOB
         
        FROM #tTable1 WHERE Id = @lCount 
     
    IF Exists ((select 1 from sStudent.tStudentMaster where Code = @lCode AND OrgId = @rOrgId))         
          BEGIN
  			    SET @1ExistStudentCode = @1ExistStudentCode + @lCode + ','
	       END	  
	IF Exists ((select 1 from sStudent.tStudentMaster where RegistrationNumber = @lRegistrationNumber 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
     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=@lClass AND DM.Title=@lDivision 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='')
		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='')
		BEGIN
			SELECT 'Surname Should not be empty' AS StudentCode
		END
		ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE FirstName IS NULL OR FirstName='')
		BEGIN
			SELECT 'First Name Should not be empty' AS StudentCode
		END
		ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE Class IS NULL OR Class='')
		BEGIN
			SELECT 'Class Should not be empty' AS StudentCode
		END
		ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE Division IS NULL OR Division='')
		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='')
		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 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!='' AND AdmissionStandard 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!='' AND Religion 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!='' AND Gender 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!='' AND CastCategory NOT IN(SELECT Title FROM sCommon.tCastCategoryMaster))
		BEGIN
			SELECT 'Enter proper value for Cast Category (OBC,SC,ST,GENERAL)' AS StudentCode
		END
		ELSE
		BEGIN
		SELECT @1DuplicateStudentCode=COALESCE(@1DuplicateStudentCode ,'') 
		+ Code + ',' FROM #tTable1 GROUP BY Code HAVING ( COUNT(Code) > 1 )	
		IF(@1DuplicateStudentCode IS NOT NULL AND @1DuplicateStudentCode != '')
		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 != '')
		BEGIN
			SET @1DuplicateStudentRegistrationNumber = 'Duplicate Registration Number ' + @1DuplicateStudentRegistrationNumber
			SELECT @1DuplicateStudentRegistrationNumber AS StudentCode
		END
		ELSE
		IF((@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 (@1ExistStudentCode IS NOT NULL AND @1ExistStudentCode != '')
		BEGIN
			SET @1ExistStudentCode = 'Exist Code ' + @1ExistStudentCode
			Select @1ExistStudentCode AS StudentCode
		END
		ELSE IF (@1ExistStudentRegistrationNumber IS NOT NULL AND @1ExistStudentRegistrationNumber != '')
		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
		END
		END
END
GO
PRINT N'Altering [sStudent].[pXMLAcademicImportAdd]...';


GO
 

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

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

DECLARE @lToClassId int
SELECT @lToClassId = ClassId FROM sSetup.tDivisionMaster WHERE Id = @rToDivisionId
 
Declare @lExistCode nvarchar(max)
 
	IF EXISTS(SELECT SM.Code
	from
	(
			SELECT StudentId FROM
			OPENXML (@loDoc, '/Table/StudentImportDetail', 1)
			WITH (
					StudentId bigint)	
	)E
	INNER JOIN sStudent.tStudentMaster SM ON SM.Id=E.StudentId AND SM.OrgId=@rToOrgId
	INNER JOIN sStudent.tAcademic A ON A.StudentId=SM.Id AND A.BatchId=@rToBatchId)
	BEGIN
		SELECT @lExistCode  = COALESCE(@lExistCode ,'') + CONVERT(VARCHAR(15),SM.Code) + ' , ' 
		from
		(
				SELECT StudentId FROM
				OPENXML (@loDoc, '/Table/StudentImportDetail', 1)
				WITH (
						StudentId bigint)	
		)E
		INNER JOIN sStudent.tStudentMaster SM ON SM.Id=E.StudentId AND SM.OrgId=@rToOrgId
		INNER JOIN sStudent.tAcademic A ON A.StudentId=SM.Id AND A.BatchId=@rToBatchId
		SELECT @lExistCode
		RETURN
	END
	
	BEGIN TRY
	BEGIN TRANSACTION
	DECLARE @lCount INT
	DECLARE @lNextNumber BIGINT 
	
	EXECUTE sCommon.pTableRowIdGet @rToOrgId, 'sStudent.tAcademic', 0, 1, 1,@outNextNumber = @lNextNumber output
 
	 INSERT INTO sStudent.tAcademic
		(
			Id,
			StudentId,
			ClassId,
			BatchId,
			DivisionId,
			RollNo,
			OrgId,
			CreatedUserId,
			CreatedDateTime,
			IsCurrent
			)
		SELECT
		
			@lNextNumber+ ROW_NUMBER() OVER(ORDER BY StudentId),
			StudentId,
			@lToClassId,
			@rToBatchId,
			@rToDivisionId,
			0,
			@rToOrgId,
			@rCreatedUserId,
			sCommon.fGetDate(),
			1
		FROM OPENXML (@loDoc, '/Table/StudentImportDetail', 1)
		WITH ( 
				StudentId bigint
			  ) 
		
		SELECT @lCount = COUNT(1) FROM OPENXML (@loDoc, '/Table/StudentImportDetail', 1)
				 WITH ( Id int )
		SET @lNextNumber  = @lCount + @lNextNumber 
		
		EXECUTE sCommon.pTableRowIdModify @rToOrgId, @rTableTitle = 'sStudent.tAcademic', @rCurrentNumber = @lNextNumber 
	    SELECT 1 AS Result
		
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sTally].[pFeeLedgerMappingAdd]...';


GO
ALTER PROCEDURE [sTally].[pFeeLedgerMappingAdd]	 
      @rXmlDoc nvarchar(MAX)     
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

SET @rXmlDoc=REPLACE(@rXmlDoc,'&','AND')
DECLARE @lInterrorCode INT,
			@intDoc INT
			
	BEGIN TRY
	 BEGIN TRANSACTION	
		
		EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc

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

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


GO
ALTER PROCEDURE [sTally].[pFeeLedgerMappingGet]

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

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


GO
ALTER PROCEDURE [sTally].[pReceiptPostingGet]

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

BEGIN 
				SELECT	ReceiptDate,
						FHM.Title AS FeeName,
						PM.Title AS PayType,
						Sum(FRD.Amount) AS Amount,
						FHM.Id AS FeeId,
						FR.PayTypeId AS PayTypeId 
				FROM sFee.tReceipt FR 
					INNER JOIN sFee.tReceiptDetail FRD ON FR.Id = FRD.ReceiptId
					INNER JOIN sFee.tFeeSetup FS ON FS.Id = FRD.FeeSetupId
					INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
					INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FM.FeeHeadId
					INNER JOIN sFinanceCommon.tPayTypeMaster PM ON PM.Id = FR.PayTypeId
					WHERE	FR.ReceiptBookId = @rReceiptBookId 
							AND FR.IsObsolete = 0 
							AND FR.OrgGroupBatchId = @rOrgGroupBatchId
							AND FR.ReceiptDate = @rReceiptDate
				group by ReceiptDate,FHM.Title,PM.Title,FHM.Id,FR.PayTypeId
		
END
GO
PRINT N'Altering [sTimetable].[pAssignClassRoomAdd]...';


GO


ALTER PROCEDURE [sTimetable].[pAssignClassRoomAdd]

	@rAssignClassRoomXml [nvarchar](max),
	@rTimeTableSchemaId int,
	@rSchoolBuildingId int
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rAssignClassRoomXml
	
BEGIN 
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	 BEGIN
	 DELETE AC FROM sTimetable.tAssignClassRoom AC INNER JOIN sTimetable.tClassRoom CR ON CR.Id = AC.ClassRoomId
	  WHERE TimeTableSchemaId=@rTimeTableSchemaId AND CR.SchoolBuildingId = @rSchoolBuildingId
	--IF(@rIsObsolete = 0)
	--BEGIN
	--	DELETE FROM sTimetable.tAssignClassRoom WHERE TimeTableSchemaId=@rTimeTableSchemaId AND ClassRoomId=@rClassRoomId
	--END
	--ELSE IF NOT EXISTS(SELECT 1 FROM sTimetable.tAssignClassRoom WHERE TimeTableSchemaId=@rTimeTableSchemaId AND ClassRoomId=@rClassRoomId)
	--BEGIN
		INSERT INTO sTimetable.tAssignClassRoom
		(
			TimeTableSchemaId,
			ClassRoomId
		)
		SELECT
		
		    TimeTableSchemaId ,
	        ClassRoomId 
		FROM OPENXML (@loDoc, '/Table/AssignClassRoom', 1)
		WITH ( 
				TimeTableSchemaId int,
				ClassRoomId int
			  ) 
	END
	SELECT 1 AS Result
	
	COMMIT TRANSACTION
	
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
END
GO
PRINT N'Altering [sTimetable].[pAssignClassRoomGet]...';


GO

ALTER PROCEDURE [sTimetable].[pAssignClassRoomGet]
	 
	@rId int,
	@rSchoolBuildingId int	
	
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 
	SELECT
				--AO.TimeTableSchemaId AS Id,
				CR.Id AS ClassRoomId,
				CR.Title AS Title ,
				CR.Code ,
				  
				CASE WHEN AC.TimeTableSchemaId IS NULL THEN 'False' ELSE 'True' END AS IsObsolete
	FROM
			 sTimetable.tClassRoom CR 
			LEFT JOIN sTimetable.tAssignClassRoom AC ON AC.ClassRoomId=CR.Id AND AC.TimeTableSchemaId=@rId 
	WHERE 
		CR.SchoolBuildingId = @rSchoolBuildingId
END
GO
PRINT N'Altering [sTimetable].[pAssignTeacherAdd]...';


GO


ALTER PROCEDURE [sTimetable].[pAssignTeacherAdd]
	 
	@rTimeTableSchemaId int,
	@rAssignTeacherXml [nvarchar](max),
	@rOrgId smallint
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rAssignTeacherXml	
BEGIN 
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	 BEGIN
		
		 DELETE AT FROM sTimetable.tAssignTeacher AT INNER JOIN sHrm.tEmployeeMaster EMP ON EMP.Id = AT.EmployeeId
		  WHERE TimeTableSchemaId=@rTimeTableSchemaId AND OrgID =@rOrgId
		  
		 
		INSERT INTO sTimetable.tAssignTeacher
		(
			TimeTableSchemaId,
			EmployeeId
		)
		SELECT
		
		    TimeTableSchemaId ,
	        EmployeeId 
		FROM OPENXML (@loDoc, '/Table/AssignTeacher', 1)
		WITH ( 
				TimeTableSchemaId int,
				EmployeeId bigint
			  ) 
	END
	SELECT 1 AS Result
	
	COMMIT TRANSACTION
	
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
END
GO
PRINT N'Altering [sTimetable].[pClassRoomAdd]...';


GO
 ALTER  PROCEDURE  [sTimetable].[pClassRoomAdd]
	 
        @rId	int	,
		@rSchoolBuildingId	int	,
		@rCode	nvarchar(100)	,
		@rTitle	nvarchar(100)	,
		@rRemark	nvarchar(100)	,
		@rIsShared bit,
		@rIsObsolete	bit	,
		@rCreatedUserId	bigint	,
	--	@rUpdatedDateTime	datetime,
		@rOrgId int	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	--BEGIN TRY
	
	 
	
	-- BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

	--IF Exists(Select Id from sTimetable.tClassRoom where Title=@rTitle AND Code =@rCode AND SchoolBuildingId = @rSchoolBuildingId)
	--BEGIN
	--	Select -101 AS Result
	--	Return
	--END
	
	 
	
 
	
	IF Exists (Select Id from sTimetable.tClassRoom where Title =@rTitle  AND SchoolBuildingId = @rSchoolBuildingId AND Id<>@rId)
	BEGIN
		select -101 As Result
		Return
	END
	
	 
	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sTimetable.tClassRoom', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sTimetable.tClassRoom
		(
			Id,
			SchoolBuildingId,
			Code,
			Title,
			Remark,
			IsShared,
			IsObsolete,
			CreatedUserId,
			CreatedDateTime	
		)
	VALUES
		(
			@lNextNumber,
			@rSchoolBuildingId,
			@rCode,
			@rTitle,
			@rRemark,
			@rIsShared,
			@rIsObsolete,
			@rCreatedUserId	,	
			sCommon.fGetDate()
		)
		    SELECT 1 AS Result
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sTimetable.tClassRoom
	    SET
		 
			SchoolBuildingId=@rSchoolBuildingId,
			Code=@rCode,
			Title=@rTitle,
			Remark=@rRemark,
			IsShared=@rIsShared,
			IsObsolete=@rIsObsolete,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate()
	      
	      WHERE Id = @rId
	      SELECT 1 AS Result
	 END  	

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


GO



ALTER PROCEDURE [sTimetable].[pDivisionWorkLoadGet]
	  
	 --@rAffiliationId int,
	 --@rTitle nvarchar(200),
	 @rDivisionId int,
	 --@rId int,
	 --@rAcademicId bigint
	-- @rBatchId int=0,
	 
	 @rTimeTableSchemaId int,
	 @rOrgId smallint

	 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

	  --BEGIN
	  
			--SET @rTitle = sCommon.fSearchStringGet(@rTitle)
			
	  --END
	 
	 
 
 
		
   Select  
		Sub.Title AS SubjectTitle,
		CS.SubjectId AS SubjectId,
		ISNULL(DWL.NoOfLecture,0) AS DivisionWiseLecture,
		DM.Id AS DivisionId,		
		ISNULL(SUM(TWL.NoOfLecture),0) TeacherwiseLeacture
		FROM  sSetup.tClassMaster CM
		INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId = CM.Id 
		INNER JOIN sSetup.tClassSubject CS ON CS.ClassId = DM.ClassId
		INNER JOIN sSetup.tSubjectMaster Sub  ON Sub.Id = CS.SubjectId
		LEFT JOIN sTimetable.tDivisionWorkLoad DWL ON DWL.DivisionId = DM.Id AND DWL.SUBJECTID = CS.SUBJECTID AND DWL.TimeTableSchemaId = @rTimeTableSchemaId 	
        LEFT JOIN sTimetable.tTeacherWorkLoad TWL ON  TWL.SubjectId= DWL.SubjectId AND TWL.DivisionId = DWL.DivisionId AND TWL.TimeTableSchemaId = @rTimeTableSchemaId 	
        --LEFT JOIN sHrm.tEmployeeMaster EMP ON EMP.Id =TWl.EmployeeId  AND EMP.OrgID =@rOrgId
      WHERE DM.Id = @rDivisionId 
      GROUP BY 
		CS.SubjectId,
		DWL.NoOfLecture,
		Sub.Title
		,DM.Id,CS.OrderIndex 
	order by cs.orderindex
	
      
        
	
		
END
GO
PRINT N'Altering [sTimetable].[pSubjectTimeOffAdd]...';


GO
 ALTER  PROCEDURE  [sTimetable].[pSubjectTimeOffAdd]
	 
        @rSubjectTimeOffXml [nvarchar](max),
		@rTimeTableSchemaId	int	,
		@rSubjectId	int	
		WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rSubjectTimeOffXml	
BEGIN 
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	 BEGIN
		
		 DELETE  FROM sTimetable.tSubjectTimeOff   WHERE TimeTableSchemaId=@rTimeTableSchemaId AND SubjectId =@rSubjectId
		  
		 
		INSERT INTO sTimetable.tSubjectTimeOff
		(
			TimeTableSchemaId,
			SubjectId,
			DayId,
			LectureNumber
		)
		SELECT
		
		    TimeTableSchemaId,
			SubjectId,
			DayId,
			LectureNumber
		FROM OPENXML (@loDoc, '/Table/SubjectTimeoff', 1)
		WITH ( 
				TimeTableSchemaId int,
				SubjectId int,
				DayId tinyint,
				LectureNumber tinyint
				
			  ) 
	END
	SELECT 1 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]
	 
	
	@rTWLXml [nvarchar](max),
	
	@rDivisionId int,
	@rSubjectId int,
	@rEmployeeId bigint,
	@rNoOfLecture smallint,
	@rIsTeacherWorkLoad bit,
	@rTimeTableSchemaId int
	
 
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rTWLXml
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=DWL.NoOfLecture,
	@lTWLNoOfLecture=SUM(TWL.NoOfLecture) 
	from
	sTimetable.tDivisionWorkLoad DWL
	INNER JOIN sTimetable.tTeacherWorkLoad TWL
	ON DWL.DivisionId=TWL.DivisionId AND DWL.SubjectId=TWL.SubjectId 
	WHERE DWL.DivisionId=@rDivisionId AND DWL.SubjectId=@rSubjectId 
	AND TWL.TimeTableSchemaId=@rTimeTableSchemaId
	GROUP BY DWL.NoOfLecture
	

	 IF(@lDWLNoOfLecture<@lTWLNoOfLecture+@rNoOfLecture)
	BEGIN
	SELECT -102 AS RESULT
	RETURN
	  END
	  END
	END
	
	
	 
	
	 BEGIN 
	--IF (@rIsTeacherWorkLoad=0)
	--  BEGIN
	 --DELETE FROM sTimetable.tTeacherWorkLoad 
		--		 WHERE DivisionId=@rDivisionId AND SubjectId=@rSubjectId
				 
		--END			 
		 
	
 
	 INSERT INTO sTimetable.tTeacherWorkLoad
		(
			EmployeeId,
			BatchId,
			DivisionId,
			SubjectId,
			NoOfLecture,
			CreatedUserId,
			CreatedDateTime,
			TimeTableSchemaId
			)
		SELECT
			EmployeeId,
			BatchId,
			DivisionId,
			SubjectId,
			ISNULL(NoOfLecture,0) AS NoOfLecture,
			CreatedUserId,
			sCommon.fGetDate(),
			TimeTableSchemaId 
		FROM OPENXML (@loDoc, '/Table/TeacherWorkLoadDetail', 1)
		WITH ( 
				EmployeeId bigint,
				BatchId int,
				DivisionId int,
				SubjectId int,
				NoOfLecture smallint,
				CreatedUserId bigint,
				CreatedDateTime datetime,
				TimeTableSchemaId int
			  ) 
		
        SELECT 1 AS Result
	  END
END
	

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


GO



ALTER PROCEDURE [sTimetable].[pTeacherWorkLoadGet]
	 @rSubjectId int = 0,
	 @rDivisionId int,
	-- @rBatchId int,
	 @rEmployeeId bigint,
	 @rTimeTableSchemaId int,
	 @rOrgId smallint
	 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

	  --BEGIN
	  
			--SET @rTitle = sCommon.fSearchStringGet(@rTitle)
			
	  --END
  Select  
		SM.Title AS SubjectTitle,
		 SM.Id AS SubjectId,
		-- TWL.EmployeeId,
		-- TWL.DivisionId,
		 --TWL.SubjectId,
		--ISNULL(DWL.NoOfLecture,0) AS DivisionWiseLecture,
		VBCD.Id AS DivisionId,	
		TWL.NoOfLecture,	
		 TWL.NoOfLecture AS TeacherwiseLeacture,
		VEM.Code AS EmployeeCode,
		VEM.ShortName AS EmpShortName,
		VEM.FirstName + ' ' + VEM.MiddleName + ' ' + VEm.LastName AS  EmployeeTitle,
		ISNULL(VEM.Id,0) AS EmployeeId,
		VBCD.Code AS DivisionTitle
		 
		FROM 
		
		  sTimetable.tTeacherWorkLoad TWL 
		INNER JOIN  sHrm.vExtEmployeeMaster VEM  ON VEM.Id=TWL.EmployeeId
       INNER JOIN sSetup.tDivisionMaster VBCD  ON VBCD.Id=TWL.DivisionId 
       --AND VBCD.BatchId=@rBatchId 
        INNER JOIN sSetup.tSubjectMaster SM ON TWL.SubjectId=SM.Id 
		
		
		
		-- sSetup.tClassMaster CM
		--INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = CM.Id 
		--INNER JOIN sSetup.vClassSubject CS ON CS.ClassId = DM.ClassId
		--INNER JOIN sSetup.tSubjectMaster Sub  ON Sub.Id = CS.SubjectId 
		 
  --      INNER JOIN sTimetable.tTeacherWorkLoad TWL ON  TWL.SubjectId= Sub.Id AND TWL.DivisionId = DM.Id 
  --       AND TWL.TimeTableSchemaId=@rTimeTableSchemaId 
        
  --      LEFT JOIN sHrm.tEmployeeMaster EMP ON EMP.Id =TWL.EmployeeId  
        --AND EMP.OrgID =@rOrgId 
      WHERE
      TWL.TimeTableSchemaId=@rTimeTableSchemaId  
      AND ((VBCD.Id = @rDivisionId  ) or (@rDivisionId=0))
      AND ((TWL.SubjectId=@rSubjectId) or (@rSubjectId=0))
      AND ((TWL.EmployeeId=@rEmployeeId) or (@rEmployeeId=0))
       
  
     
     
      
        
	
		
END
GO
PRINT N'Altering [sTimetable].[pTimeTableAssignTeacherGet]...';


GO

ALTER PROCEDURE [sTimetable].[pTimeTableAssignTeacherGet]
	 
	@rId int	,
	@rOrgId smallint 
   -- @rOrgGroupId  smallint
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
		
BEGIN 
	SELECT
				
				EMP.CODE,
				EMP.FIRSTNAME + ' ' + ISNULL(EMP.MIDDLENAME,'') + ' ' + EMP.LASTNAME  AS NAME,
				EMP.ID AS EMPLOYEEID ,
				--OM.DisplayTitle AS Organization,
				
				 CASE WHEN AT.TimeTableSchemaId IS NULL THEN 'False' ELSE 'True' END AS IsObsolete
	FROM
			sHrm.tEmployeeMaster EMP
			 LEFT JOIN sTimetable.tAssignTeacher AT ON AT.EMPLOYEEID = EMP.ID AND AT.TimeTableSchemaId=@rId
			  
			  

			
	 WHERE
	 	EMP.OrgId=@rOrgId 
	ORDER BY  EMP.Code
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


END


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


GO




ALTER PROCEDURE [sTool].[pUpgradeVersion]
	 
	@rVersionId int,
	@rVersion nvarchar(20),
	@rOrgGroupId int
	 
	 
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

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


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

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

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

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

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

-- update tablerowid master data from excel to table

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

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

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



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




exec [sTool].[pTableRowIdCurrentNumberSet] @rOrgGroupId


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

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


IF NOT EXISTS(SELECT 1 FROM sAdmission.tInquiryStatusMaster WHERE OrgGroupId = @rOrgGroupId)
BEGIN				
				INSERT INTO sAdmission.tInquiryStatusMaster
					   ([Id]
					   ,[Code]
					   ,[Title]
					   ,[IsObsolete]
					   ,[CreatedUserId]
					   ,[CreatedDateTime]
					   ,[UpdatedUserId]
					   ,[UpdatedDateTime]
					   ,[OrgGroupId]
					   ,StatusId)
				 SELECT
						 sCommon.fGetIntIdForOrg(Id,@rOrgGroupId)
						,Title
						,Title
						,0
						,1
						,getdate()
						,NULL
						,NULL
						,@rOrgGroupId
						,Id						
						FROM sCommon.tStatusMaster
						where statustypeId = 104
						
	DECLARE @lMaxId int
	SET @lMaxId = sCommon.fGetIntIdForOrg(213,@rOrgGroupId)					
	EXECUTE sCommon.pTableRowIdModify @rOrgGroupId, @rTableTitle = 'sAdmission.tInquiryStatusMaster', @rCurrentNumber = @lMaxId
						
END




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

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

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

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


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

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

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


			
			
END

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

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

END

UPDATE sSystem.tDatabaseInfo SET ApplicationId = 1

UPDATE sSystem.tDatabaseInfo SET 
VersionNumber = @rVersion,
VersionId = @rVersionId,
LastVersionUpdateDateTime = getdate() ,
IsNewVersion = 1
WHERE ApplicationId = 1 
 



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


GO

ALTER PROCEDURE [sTransport].[pBusRouteMasterGet]
          
           @rTitle nvarchar(100),
           @rOrgGroupBatchId int,
           @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
      ,BRM.IsObsolete as BusRouteIsObsolete
      ,ISNULL(BRM.RouteCode,'') AS RouteCode
      ,ISNULL(BRM.RouteNumber,0) AS RouteNumber
     
  FROM [sTransport].[tBusRouteMaster] BRM 
        
  WHERE 
	--BRM.OrgGroupBatchId=@rOrgGroupBatchId
	--AND 
	((BRM.Title Like @rTitle) OR (ISNULL(@rTitle,'') = ''))
	AND ((BRM.RouteCode Like @rRouteCode) OR (ISNULL(@rRouteCode,'') = ''))
	AND ((BRM.RouteNumber = @rRouteNumber) OR (@rRouteNumber = 0))
	AND ((BRM.TransportId = @rTransportId) OR (@rTransportId = 0))
    order by BRM.OrderIndex
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
END
GO
PRINT N'Altering [sTransport].[pRptBuswiseCapacityUtilizationListGet]...';


GO

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

BEGIN 

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


GO





ALTER PROCEDURE [sTransport].[pRptRoutewiseStudentListGet]
	 
	
	 
	 @rOrgGroupBatchId int,
	 @rOrgId int,
	 @rDepartmentId int,
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rClassId int,
	 @rDivisionId int,
	 @rRouteId int,
	 @rDestinationId int,
	 @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'Altering [sTransport].[pVehicleMasterAdd]...';


GO
ALTER PROCEDURE [sTransport].[pVehicleMasterAdd]
	 
	@rId int,
	@rTitle nvarchar(100),
	@rRegistrationNumber nvarchar(100)='',
	@rVehicleTypeId int,
	@rNoOfSeats int,
	@rCreatedUserId bigint,
	@rIsObsolete bit,
	@rOrgGroupId int,
	@rLastServiceDate date='',
	@rNextServiceDate date='',
	@rFuelTypeId int=0,
	@rServiceCenter nvarchar(200)='',
	@rServiceCenterContact nvarchar(50)='',
	@rTransportId int=0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
 IF(@rId = 0)	
BEGIN
		If Exists(select Id from sTransport.tVehicleMaster where Title=@rTitle  AND OrgGroupId=@rOrgGroupId AND TransportId = @rTransportId)
			BEGIN
			select -103 as Result
			RETURN
		END 
	END	
	DECLARE @lNextNumber BIGINT     
		
	IF(@rId = 0)	
	BEGIN
	
EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sTransport.tVehicleMaster', 0, 1, 1,@outNextNumber = @lNextNumber output

	INSERT INTO sTransport.tVehicleMaster
		(
			Id,
			Title,
			RegistrationNumber,
			VehicleTypeId,
			NoOfSeats,
			CreatedUserId,
			CreatedDateTime,
			IsObsolete,
			OrgGroupId,
			LastServiceDate,
			NextServiceDate,
			FuelTypeId,
	        ServiceCenter,
	        ServiceCenterContact,
	        TransportId
		)
	VALUES
		(
			@lNextNumber,
			@rTitle,
			ISNULL(@rRegistrationNumber,''),
			@rVehicleTypeId,
			@rNoOfSeats,
			@rCreatedUserId,
			sCommon.fGetDate(), 
			@rIsObsolete,
			@rOrgGroupId,
			@rLastServiceDate,
			@rNextServiceDate,
			@rFuelTypeId,
			@rServiceCenter,
	        @rServiceCenterContact,
	        @rTransportId
			
		)
		    select @lNextNumber as Result         
	END	 
	 ELSE
		If  Exists(select Id from sTransport.tVehicleMaster where Title=@rTitle  AND Id<>@rId  AND TransportId = @rTransportId)
		Begin
			select -103 as Result
			RETURN
		
	END	
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sTransport.tVehicleMaster
	    SET
			Title=@rTitle,
			RegistrationNumber=@rRegistrationNumber,
			VehicleTypeId=@rVehicleTypeId,
			NoOfSeats=@rNoOfSeats,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate(), 
			IsObsolete=@rIsObsolete,
			LastServiceDate=@rLastServiceDate,
			NextServiceDate=@rNextServiceDate,
			FuelTypeId=@rFuelTypeId,
			ServiceCenter=@rServiceCenter,
	        ServiceCenterContact=@rServiceCenterContact
	      
	      
	      WHERE Id = @rId and OrgGroupId=@rOrgGroupId and TransportId = @rTransportId
	       SELECT 105 AS Result
	
	 END  
		
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sTransport].[pVehicleMasterGet]...';


GO
ALTER PROCEDURE [sTransport].[pVehicleMasterGet]
	 @rId int = 0,
	 @rTitle nvarchar(100),
	 @rRegistrationNumber nvarchar(100)='',
	 @rOrgGroupId int,
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rIsSearch bit = 1,
	 @rVehicleTypeId int = 0,
	 @rTransportId int = 0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 IF @rIsSearch = 1
		BEGIN
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
			SET @rRegistrationNumber = sCommon.fSearchStringGet(@rRegistrationNumber)
		END
	
	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			VM.Id,
			VM.Title,
		    VM.RegistrationNumber,
		    VM.NoOfSeats,	
			VM.IsObsolete,
			ISNULL(VM.LastServiceDate,'') AS LastServiceDate,
			ISNULL(VM.NextServiceDate,'') AS NextServiceDate,
			ISNULL(VM.FuelTypeId,0) AS FuelTypeId,
			ISNULL(ServiceCenter,'') AS ServiceCenter,
            ISNULL(ServiceCenterContact,'') AS ServiceCenterContact,
            ISNULL(VM.VehicleTypeId,0) AS VehicleTypeId, 
		    ISNULL(VTM.Title,'') AS VehicleTypeName
  FROM 
            sTransport.tVehicleMaster VM
            LEFT JOIN sTransport.tVehicleTypeMaster VTM ON VTM.Id = VM.VehicleTypeId
  WHERE 
  
      ((VM.Id = @rId) OR (@rId = 0))
	AND ((VM.VehicleTypeId = @rVehicleTypeId) OR (@rVehicleTypeId = 0))
	AND ((VM.Title like @rTitle) OR (ISNULL(@rTitle,'') = '')) 
	AND ((ISNULL(VM.RegistrationNumber,'') like @rRegistrationNumber) OR (ISNULL(@rRegistrationNumber,'') = '')) 
	AND VM.OrgGroupId=@rOrgGroupId
	AND ((VM.TransportId = @rTransportId) OR (@rTransportId = 0))
END
GO
PRINT N'Creating [sOp].[pPaymentTransactionAdd]...';


GO

CREATE PROCEDURE [sOp].[pPaymentTransactionAdd]
	
			@rId bigint=0,
			@rTransactionSourceTypeId smallint,
			@rTransactionSourceId bigint,
			@rPayerSourceTypeId smallint,
			@rPayerSourceId bigint,
			@rPayAmount decimal(12,2),
			@rTransactionStatusId int,
			@rFunctionalityId smallint,
			@rOrgId int

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
		BEGIN TRY
		BEGIN TRANSACTION	
	 
	DECLARE @lNextNumber BIGINT     
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sOp.tPaymentTransaction', 0, 1, 1,@outNextNumber = @lNextNumber output

		INSERT INTO sOp.tPaymentTransaction
			(
				Id,
				TransactionSourceTypeId,
				TransactionSourceId,
				PayerSourceTypeId,
				PayerSourceId,
				PayDateTime,
				PayAmount,
				TransactionStatusId,
				FunctionalityId
			)
		VALUES
			(
				@lNextNumber,
				@rTransactionSourceTypeId,
				@rTransactionSourceId,
				@rPayerSourceTypeId,
				@rPayerSourceId,
				sCommon.fGetDate(),
				@rPayAmount,
				@rTransactionStatusId,
				@rFunctionalityId
			)

	SELECT @lNextNumber AS Result
	
	COMMIT TRANSACTION
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END
GO
PRINT N'Creating [sOp].[pGatewayConfigurationAdd]...';


GO
CREATE PROCEDURE [sOp].[pGatewayConfigurationAdd]
	
	
	@rOrgGroupId smallint,
	@rPaymentGatewayId smallint,
	@rGatewayURL nvarchar(1000),
	@rServerPort nvarchar(50),
	@rLoginId nvarchar(50),
	@rLoginPassword nvarchar(50),
	@rProductId nvarchar(100)
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	BEGIN TRY
	BEGIN TRANSACTION	
	 
	IF NOT EXISTS(SELECT OrgGroupId FROM sOp.tGatewayConfiguration WHERE OrgGroupId=@rOrgGroupId)
	BEGIN
		INSERT INTO sOp.tGatewayConfiguration
			(
				OrgGroupId,
				PaymentGatewayId,
				GatewayURL,
				ServerPort,
				LoginId,
				LoginPassword,
				ProductId
			)
		VALUES
			(
				@rOrgGroupId,
				@rPaymentGatewayId,
				@rGatewayURL,
				@rServerPort,
				@rLoginId,
				@rLoginPassword,
				@rProductId
			)
			             
		END	 
	ELSE
	BEGIN
	    UPDATE  sOp.tGatewayConfiguration
	    SET
			
			PaymentGatewayId=@rPaymentGatewayId,
			GatewayURL=@rGatewayURL,
			ServerPort=@rServerPort,
			LoginId=@rLoginId,
			LoginPassword=@rLoginPassword,
			ProductId=@rProductId
	     
	     WHERE OrgGroupId = @rOrgGroupId 	   
	END  
		
	SELECT @rOrgGroupId AS Result
	
	COMMIT TRANSACTION		
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END
GO
PRINT N'Creating [sOp].[pGatewayConfigurationGet]...';


GO
CREATE PROCEDURE [sOp].[pGatewayConfigurationGet]
	 
	 @rOrgGroupId smallint
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			
BEGIN 
	SELECT
			GC.OrgGroupId,
			GC.PaymentGatewayId,
			GC.GatewayURL,
			GC.ServerPort,
			GC.LoginId,
			GC.LoginPassword,
			GC.ProductId
	FROM
			sOp.tGatewayConfiguration GC
	WHERE 
			GC.OrgGroupId=@rOrgGroupId
END
GO
PRINT N'Creating [sOp].[pPaymentTransactionGet]...';


GO

CREATE PROCEDURE [sOp].[pPaymentTransactionGet]

		@rId bigint,
		@rFromDate date,
		@rToDate date,
		@rTransactionStatusId int,
		@rFunctionalityId smallint,
		@rFirstName nvarchar(50)=''           
AS
SET NOCOUNT ON

BEGIN
	SELECT  
		TSM.Title As TransactionStatus,
		FM.Title AS Functionality,
		PT.PayAmount,
		PT.PayDateTime,
		SM.Code,
		SM.FirstName + ' ' + SM.LastName AS Name,
		CM.DisplayTitle AS ClassName,
		TSM.ColorCode,
		PT.TransactionSourceTypeId,
		PT.TransactionSourceId,
		PT.BankName,
		PT.Id AS PaymentTransactionId,
		PT.TransactionStatusId
	FROM 
		sOp.tPaymentTransaction PT 
		INNER JOIN sOp.tTransactionStatusMaster TSM ON TSM.ID = PT.TransactionStatusId
		INNER JOIN  sOp.tFunctionalityMaster FM ON FM.Id = PT.FunctionalityId
		INNER JOIN sStudent.tAcademic A ON A.Id = PT.PayerSourceId
		INNER JOIN sStudent.tStudentMaster SM ON SM.Id = A.StudentId
		INNER JOIN sSetup.tClassMaster CM ON CM.Id = A.ClassId
	WHERE 
		 ((PT.TransactionStatusId = @rTransactionStatusId) OR (@rTransactionStatusId=0))
		 AND ((PT.FunctionalityId =@rFunctionalityId) OR (@rFunctionalityId=0))
		 AND ((PT.PayDateTime >=@rFromDate) OR (ISNULL(@rFromDate,'')=''))
		 AND ((PT.PayDateTime < DateAdd(Day,1,@rToDate)) OR (ISNULL(@rToDate,'')=''))
		 AND ((PT.PayerSourceId=@rId) OR (@rId=0))
		 AND ((SM.FirstName like @rFirstName) OR (@rFirstName=''))
		 order by PT.PayDateTime desc
END
GO
PRINT N'Creating [sOp].[pPaymentTransactionUpdate]...';


GO
CREATE PROCEDURE [sOp].[pPaymentTransactionUpdate]
	 
	@rPaymentTransactionId bigint,
	@rMerchantTransactionId nvarchar(50),
	@rBankTransactionId bigint,
	@rBankName nvarchar(100),
	@rPaymentType nvarchar(50),
	@rCardNumber nvarchar(100),
	@rTransactionResponse nvarchar(500)
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN	
BEGIN TRY
BEGIN TRANSACTION	
 
    BEGIN 
	    UPDATE sOp.tPaymentTransaction
	    SET
	    MerchantTransactionId=@rMerchantTransactionId,
	    BankTransactionId=@rBankTransactionId,
	    BankName=@rBankName,
	    PaymentType=@rPaymentType,
	    CardNumber=@rCardNumber,
	    TransactionResponse=@rTransactionResponse
	    WHERE Id = @rPaymentTransactionId 
	    SELECT @rPaymentTransactionId AS Result
	END  
	
	COMMIT TRANSACTION
	
END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END
GO
PRINT N'Creating [sOp].[pOnlineFeeGet]...';


GO

CREATE PROCEDURE [sOp].[pOnlineFeeGet]

		@rOnlineFeeId bigint,
		@rSourceTypeId smallint
		
AS
SET NOCOUNT ON

BEGIN
	
	SELECT  
		TOF.Id AS OnlineFeeId,
		TOF.SourceTypeId,
		TOF.SourceId,
		TOF.PayDateTime,
		TOF.FeeAmount,
		TOF.PenaltyAmount,
		TOF.NetAmount,
		TOF.ReceiptBookId,
		A.OrgId,
		A.BatchId
	FROM 
		 sFee.tOnlineFee TOF
		 INNER JOIN sOp.tPaymentTransaction PT ON PT.TransactionSourceId=TOF.Id
		 INNER JOIN sStudent.tAcademic A ON A.Id = TOF.SourceId
	WHERE 
		 TOF.Id = @rOnlineFeeId AND PT.TransactionSourceTypeId = @rSourceTypeId	 
END
GO
PRINT N'Creating [sAdmission].[pRptAdmissionFormParentAcademicSubGet]...';


GO


CREATE  PROCEDURE [sAdmission].[pRptAdmissionFormParentAcademicSubGet]
	
	@rId bigint ,
	 @rRelationShipId int=0

AS
 SET NOCOUNT ON
			 

BEGIN 
	
	select 
	 Convert(nvarchar(20),AF.Id) AS AdmissionFormIdText,
	 Convert(nvarchar(20),@rRelationShipId) AS RelationShipIdText,
	 AF.Id,
	 PA.AcademicYear,
	 PA.AdmissionClass,
	 PA.InstituteAffiliaton,
	 PA.InstituteCity,
	 PA.InstituteName,
	 PA.RelationshipId,
	 PA.Language AS Medium
	
	      
  FROM  
		    sAdmission.tAdmissionForm AF 
			INNER JOIN sAdmission.tAdmissionFormParentAcademic PA ON PA.AdmissionFormId=AF.Id
			INNER JOIN sCommon.tRelationshipMaster RM ON RM.Id=PA.RelationshipId
				
 WHERE 	
  AF.Id = @rId 
 AND PA.RelationShipId = @rRelationShipId
				
END
GO
PRINT N'Creating [sAdmission].[pRptAdmissionFormReferenceSubGet]...';


GO


CREATE  PROCEDURE [sAdmission].[pRptAdmissionFormReferenceSubGet]
	
	@rId bigint

AS
 SET NOCOUNT ON
			 

BEGIN 
	
	select 
	 Convert(nvarchar(20),AF.Id) AS AdmissionFormIdText,
	 AF.Id,
	 AFR.ReferenceDetail,
	 isnull(AFR.ReferenceName,'') AS ReferenceName ,
	 AFR.ReferenceRelation,
	 AFR.ReferenceContactNo
	
	      
  FROM  
		    sAdmission.tAdmissionForm AF 
			INNER JOIN sAdmission.tAdmissionFormReference AFR ON AFR.AdmissionFormId=AF.Id
				
 WHERE 	
  AF.Id = @rId

				
END
GO
PRINT N'Creating [sAdmission].[pRptAdmissionFormSiblingSubGet]...';


GO


CREATE  PROCEDURE [sAdmission].[pRptAdmissionFormSiblingSubGet]
	
	@rId bigint

AS
 SET NOCOUNT ON
			 

BEGIN 
	
	select 
	 Convert(nvarchar(20),AF.Id) AS AdmissionFormIdText,
	 AF.Id,
	 isnull(ADS.SiblingName,'') AS SiblingName,
	 ADS.SiblingRelation,
	 ADS.SiblingStandard,
	 ADS.SiblingSchool
	
	      
  FROM  
		    sAdmission.tAdmissionForm AF 
			INNER JOIN sAdmission.tAdmissionFormSibling ADS ON ADS.AdmissionFormId=AF.Id
				
 WHERE 	
  AF.Id = @rId

				
END
GO
PRINT N'Creating [sAdmission].[pRptAdmissionFormStudentAcademicSubGet]...';


GO


CREATE PROCEDURE [sAdmission].[pRptAdmissionFormStudentAcademicSubGet]
	
	@rId bigint

AS
 SET NOCOUNT ON
			 

BEGIN 
	
	select 
	 Convert(nvarchar(20),AF.Id) AS AdmissionFormIdText,
	 AF.Id,
	 SA.AcademicYear,
	 SA.AdmissionClass,
	 SA.InstituteAffiliaton,
	 SA.InstituteCity,
	 SA.InstituteName,
	 SA.Language AS Medium,
	 SA.Result
	 
	
	      
  FROM  
		    sAdmission.tAdmissionForm AF 
			INNER JOIN sAdmission.tAdmissionFormStudentAcademic SA ON SA.AdmissionFormId=AF.Id
				
 WHERE 	
  AF.Id = @rId

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


GO

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

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

   INSERT INTO #tAcademicAttendance
   (AcademicId,PresentCount,AbsentCount)
   	SELECT
   
   	SA.Id,
	   ISNULL((SELECT count(AcademicId) FROM sAttendance.tStudentRegister SR	 
		WHERE		 
		 SR.AttendanceDate >= @rFromAttendanceDate
		AND SR.AttendanceDate <= @rToAttendanceDate
		AND 
		SR.AcademicId = SA.Id
		AND SR.IsPresent = 1
		AND SR.AttendanceTypeId = @rAttendanceTypeId				
		) ,0)
		 AS PresentCount
		 , 
	   ISNULL((SELECT count(AcademicId) FROM sAttendance.tStudentRegister SR	 
		WHERE		 
		 SR.AttendanceDate >= @rFromAttendanceDate
		AND SR.AttendanceDate <= @rToAttendanceDate		
		AND 
		SR.IsPresent = 0
		AND SR.AttendanceTypeId = @rAttendanceTypeId
		AND SR.AcademicId = SA.Id		
		),0)
		 AS AbsentCount 		
  FROM 
		 sStudent.tAcademic SA 
		 INNER JOIN sStudent.tStudentMaster SM ON SM.Id=SA.StudentId
		 --INNER JOIN sAssessment.tExamMaster EM ON SA.BatchId = EM.BatchId AND SA.ClassId = EM.ClassId  AND EM.ExamSubGroupId = 	@rExamSubGroupId
		 --AND EM.BatchId = @rBatchId	 
         WHERE
 
		 ((SA.ClassId=@rClassId) OR (@rClassId=0))
	     AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0)) 
         AND (SA.OrgId = @rOrgId)
         AND (SA.BatchId = @rBatchId)
        AND ((SA.Id =@rStudentId) OR (@rStudentId=0))
        
  
  
    INSERT INTO sStudent.tAcademicDetail
    (AcademicId,PresentDaysAnnual,TotalDaysAnnual,PercentageAttendance)
    SELECT RA.AcademicId,PresentCount,AbsentCount + PresentCount,(RA.PresentCount *100) / (RA.PresentCount + RA.AbsentCount) 
    --,SR.AcademicId,SR.ExamId
    FROM #tAcademicAttendance RA 
	LEFT JOIN sStudent.tAcademicDetail SR ON RA.AcademicId = SR.AcademicId 
	    WHERE SR.AcademicId IS NULL   
    
   
    
    UPDATE SR
    SET PresentDaysAnnual = RA.PresentCount,
         TotalDaysAnnual = RA.PresentCount + RA.AbsentCount,
         PercentageAttendance =(RA.PresentCount *100) / (RA.PresentCount + RA.AbsentCount) 
    FROM sStudent.tAcademicDetail SR INNER JOIN
    #tAcademicAttendance RA 
    ON  SR.AcademicId = RA.AcademicId
    --INNER JOIN sAssessment.tExamMaster EM ON EM.Id = SR.ExamId
    --WHERE EM.ExamSubGroupId = @rExamSubGroupId
 
 SELECT 1 AS RESULT
END
GO
PRINT N'Creating [sCommon].[pMasterDataAdd]...';


GO

CREATE  PROCEDURE [sCommon].[pMasterDataAdd]
	 
        
		@rTitle nvarchar(100)='',
		@rCode nvarchar(50)='',
		@rIsObsolete bit=0,
		@rCreatedUserId bigint,
		@rOrgGroupId smallint,
		@rOrgId int,
		@rTable_Name int=0,
		@rDependId int=0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY

	 DECLARE @lNextNumber BIGINT 
			 
		IF(@rTable_Name=1)
		BEGIN
		
			If Exists(select Id from sFinanceCommon.tBankMaster where Title=@rTitle AND OrgGroupId=@rOrgGroupId)
				BEGIN
				select -103 as Result
				RETURN
	 		END 
	 		EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sFinanceCommon.tBankMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
			INSERT INTO sFinanceCommon.tBankMaster
			(
			
				Id,
				Code,
				Title,
				 IsObsolete,
				 OrgGroupId,
				CreatedUserId,
				UpdateduserId,
				CreatedDateTime,
				UpdatedDateTime 
			)
		VALUES
			(
				@lNextNumber,
				@rCode,
				@rTitle,
				 @rIsObsolete,
				 @rOrgGroupId,
				@rCreatedUserId,
				@rCreatedUserId,
				sCommon.fGetDate() ,
				sCommon.fGetDate() 
			)
			END
			
			IF(@rTable_Name=2)
		BEGIN
		
			If Exists(select Id from sCommon.tReligionMaster where Title=@rTitle AND OrgGroupId=@rOrgGroupId)
				BEGIN
				select -103 as Result
				RETURN
	 		END 
	 		EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sCommon.tReligionMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
			INSERT INTO sCommon.tReligionMaster
			(
			
				Id,
				Code,
				Title,
				 IsObsolete,
				 OrgGroupId,
				CreatedUserId,
				UpdateduserId,
				CreatedDateTime,
				UpdatedDateTime 
			)
		VALUES
			(
				@lNextNumber,
				@rCode,
				@rTitle,
				 @rIsObsolete,
				 @rOrgGroupId,
				@rCreatedUserId,
				@rCreatedUserId,
				sCommon.fGetDate() ,
				sCommon.fGetDate() 
			)
			END
			
			IF(@rTable_Name=3)
		BEGIN
		
			If Exists(select Id from sCommon.tOccupationMaster where Title=@rTitle AND OrgGroupId=@rOrgGroupId)
				BEGIN
				select -103 as Result
				RETURN
	 		END 
	 		EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sCommon.tOccupationMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
			INSERT INTO sCommon.tOccupationMaster
			(
			
				Id,
				Code,
				Title,
				 IsObsolete,
				 OrgGroupId,
				CreatedUserId,
				UpdateduserId,
				CreatedDateTime,
				UpdatedDateTime 
			)
		VALUES
			(
				@lNextNumber,
				@rCode,
				@rTitle,
				 @rIsObsolete,
				 @rOrgGroupId,
				@rCreatedUserId,
				@rCreatedUserId,
				sCommon.fGetDate() ,
				sCommon.fGetDate() 
			)
			END
			
			
			IF(@rTable_Name=4)
		BEGIN
		
			If Exists(select Id from sCommon.tMotherTongueMaster where Title=@rTitle AND OrgGroupId=@rOrgGroupId)
				BEGIN
				select -103 as Result
				RETURN
	 		END 
	 		EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sCommon.tMotherTongueMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
			INSERT INTO sCommon.tMotherTongueMaster
			(
			
				Id,
				Code,
				Title,
				 IsObsolete,
				 OrgGroupId,
				CreatedUserId,
				UpdateduserId,
				CreatedDateTime,
				UpdatedDateTime 
			)
		VALUES
			(
				@lNextNumber,
				@rCode,
				@rTitle,
				 @rIsObsolete,
				 @rOrgGroupId,
				@rCreatedUserId,
				@rCreatedUserId,
				sCommon.fGetDate() ,
				sCommon.fGetDate() 
			)
			END
			
		IF(@rTable_Name=5)
		BEGIN
		
			If Exists(select Id from sCommon.tPreviousSchoolMaster where Title=@rTitle AND OrgGroupId=@rOrgGroupId)
				BEGIN
				select -103 as Result
				RETURN
	 		END 
	 		EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sCommon.tPreviousSchoolMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
			INSERT INTO sCommon.tPreviousSchoolMaster
			(
			
				Id,
				Code,
				Title,
				 IsObsolete,
				 OrgGroupId,
				CreatedUserId,
				UpdateduserId,
				CreatedDateTime,
				UpdatedDateTime 
			)
		VALUES
			(
				@lNextNumber,
				@rCode,
				@rTitle,
				 @rIsObsolete,
				 @rOrgGroupId,
				@rCreatedUserId,
				@rCreatedUserId,
				sCommon.fGetDate() ,
				sCommon.fGetDate() 
			)
			END
			
			IF(@rTable_Name=6)
		BEGIN
		
			If Exists(select Id from sHrm.tQualificationMaster where Title=@rTitle AND OrgGroupId=@rOrgGroupId)
				BEGIN
				select -103 as Result
				RETURN
	 		END 
	 		EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sHrm.tQualificationMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
			INSERT INTO sHrm.tQualificationMaster
			(
			
				Id,
				Code,
				Title,
				 IsObsolete,
				 OrgGroupId,
				CreatedUserId,
				UpdateduserId,
				CreatedDateTime,
				UpdatedDateTime 
			)
		VALUES
			(
				@lNextNumber,
				@rCode,
				@rTitle,
				 @rIsObsolete,
				 @rOrgGroupId,
				@rCreatedUserId,
				@rCreatedUserId,
				sCommon.fGetDate() ,
				sCommon.fGetDate() 
			)
			END
			
				IF(@rTable_Name=7)
		BEGIN
		
			If Exists(select Id from sCommon.tCountryMaster where Title=@rTitle AND OrgGroupId=@rOrgGroupId)
				BEGIN
				select -103 as Result
				RETURN
	 		END 
	 		EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sCommon.tCountryMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
			INSERT INTO sCommon.tCountryMaster
			(
			
				Id,
				Title,
				Nationality,
			
				 IsObsolete,
				 OrgGroupId,
				CreatedUserId,
				UpdateduserId,
				CreatedDateTime,
				UpdatedDateTime ,
				IsShow
			)
		VALUES
			(
				@lNextNumber,
				
				@rTitle,
				@rCode,
				 @rIsObsolete,
				 @rOrgGroupId,
				@rCreatedUserId,
				@rCreatedUserId,
				sCommon.fGetDate() ,
				sCommon.fGetDate() ,
				1
			)
			END
			
				IF(@rTable_Name=8)
		BEGIN
			If Exists(select Id from sCommon.tStateMaster where Title=@rTitle AND CountryId=@rDependId AND OrgGroupId=@rOrgGroupId)
				BEGIN
				select -103 as Result
				RETURN
	 		END 
	 		EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sCommon.tStateMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
			INSERT INTO sCommon.tStateMaster
			(
			
				Id,
				Title,
				CountryId,
			
				 IsObsolete,
				 OrgGroupId,
				CreatedUserId,
				UpdateduserId,
				CreatedDateTime,
				UpdatedDateTime ,
				IsShow
			)
		VALUES
			(
				@lNextNumber,
				
				@rTitle,
				@rDependId,
				 @rIsObsolete,
				 @rOrgGroupId,
				@rCreatedUserId,
				@rCreatedUserId,
				sCommon.fGetDate() ,
				sCommon.fGetDate() ,
				1
			)
			END
			
			
				IF(@rTable_Name=9)
		BEGIN
				If Exists(select Id from sCommon.tCityMaster where Title=@rTitle AND StateId =@rDependId AND OrgGroupId=@rOrgGroupId)
				BEGIN
				select -103 as Result
				RETURN
	 		END 
	 		EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sCommon.tCityMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
			INSERT INTO sCommon.tCityMaster
			(
			
				Id,
				Title,
				StateId,
			
				 IsObsolete,
				 OrgGroupId,
				CreatedUserId,
				UpdateduserId,
				CreatedDateTime,
				UpdatedDateTime ,
				IsShow
			)
		VALUES
			(
				@lNextNumber,
				
				@rTitle,
				@rDependId,
				 @rIsObsolete,
				 @rOrgGroupId,
				@rCreatedUserId,
				@rCreatedUserId,
				sCommon.fGetDate() ,
				sCommon.fGetDate() ,
				1
			)
			END
			
				IF(@rTable_Name=10)
		BEGIN
				If Exists(select Id from sCommon.tHobbyMaster where Title=@rTitle AND OrgGroupId=@rOrgGroupId)
				BEGIN
				select -103 as Result
				RETURN
	 		END 
	 		EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sCommon.tHobbyMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
			INSERT INTO sCommon.tHobbyMaster
			(
			
				Id,
				Title,
				Code,
				 IsObsolete,
				 OrgGroupId,
				CreatedUserId,
				UpdateduserId,
				CreatedDateTime,
				UpdatedDateTime 
			 
			)
		VALUES
			(
				@lNextNumber,
				
				@rTitle,
				@rCode,
				 @rIsObsolete,
				 @rOrgGroupId,
				@rCreatedUserId,
				@rCreatedUserId,
				sCommon.fGetDate() ,
				sCommon.fGetDate() 
				 
			)
			END
			
		 IF(@rTable_Name=11)
		BEGIN
				If Exists(select Id from sCommon.tHostelMaster where Title=@rTitle AND OrgGroupId=@rOrgGroupId)
				BEGIN
				select -103 as Result
				RETURN
	 		END 
	 		EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sCommon.tHostelMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
			INSERT INTO sCommon.tHostelMaster
			(
			
				Id,
				Title,
				Code,
				 IsObsolete,
				 OrgGroupId,
				CreatedUserId,
				UpdateduserId,
				CreatedDateTime,
				UpdatedDateTime 
			 
			)
		VALUES
			(
				@lNextNumber,
				
				@rTitle,
				@rCode,
				 @rIsObsolete,
				 @rOrgGroupId,
				@rCreatedUserId,
				@rCreatedUserId,
				sCommon.fGetDate() ,
				sCommon.fGetDate() 
				 
			)
			END
		 
		 	
		 IF(@rTable_Name=12)
		BEGIN
				If Exists(select Id from sCommon.tAreaMaster where Title=@rTitle AND CityId =@rDependId AND OrgGroupId=@rOrgGroupId)
				BEGIN
				select -103 as Result
				RETURN
	 		END 
	 		EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sCommon.tAreaMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
			INSERT INTO sCommon.tAreaMaster
			(
			
				Id,
				Title,
				CityId,
				 IsObsolete,
				 OrgGroupId,
				CreatedUserId,
				UpdateduserId,
				CreatedDateTime,
				UpdatedDateTime,
				IsShow
			 
			)
		VALUES
			(
				@lNextNumber,
				
				@rTitle,
				@rDependId,
				 @rIsObsolete,
				 @rOrgGroupId,
				@rCreatedUserId,
				@rCreatedUserId,
				sCommon.fGetDate() ,
				sCommon.fGetDate() ,
				1
				
				 
			)
			END
		 
			SELECT 1 AS Result
			
			
		 
 
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Creating [sConfig].[pConfigurationDirectValueGet]...';


GO
CREATE PROCEDURE [sConfig].[pConfigurationDirectValueGet] 
            @rOrgGroupId int,
            @rOrgId int,            
			@rUserId bigint,			
			@rKey nvarchar(100)
		
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 SELECT CM.ItemKey AS ItemKey,ISNULL(CS.ItemValue,CM.ItemValue) AS ItemValue
	   FROM sConfig.tConfigurationMaster CM LEFT JOIN sConfig.tConfigurationSetup CS ON CS.ConfigurationId = CM.Id AND CS.SourceTypeId=1016 AND SourceId = @rOrgId 
	   Where CM.ConfigurationLevelId = 1 AND CM.ItemKey = @rKey
	
	--UNION ALL
	
	--   SELECT CM.ItemKey,ISNULL(CS.ItemValue,CM.ItemValue)  FROM sConfig.tConfigurationMaster CM LEFT JOIN sConfig.tConfigurationSetup CS 
	--   ON CS.ConfigurationId = CM.Id AND SourceId = @rLocationId  Where CM.ConfigurationLevelId = 2 AND CM.ItemKey = @rKey
	   
	--UNION ALL
	
	--   SELECT CM.ItemKey,ISNULL(CS.ItemValue,CM.ItemValue)  FROM sConfig.tConfigurationMaster CM LEFT JOIN sConfig.tConfigurationSetup CS 
	--   ON CS.ConfigurationId = CM.Id AND SourceId = @rStoreLocationId  Where CM.ConfigurationLevelId = 3 AND CM.ItemKey = @rKey
	
	UNION ALL
	
	   SELECT CM.ItemKey,ISNULL(CS.ItemValue,CM.ItemValue)  FROM sConfig.tConfigurationMaster CM LEFT JOIN sConfig.tConfigurationSetup CS 
	   ON CS.ConfigurationId = CM.Id AND CS.SourceTypeId=95 AND SourceId = @rUserId  Where CM.ConfigurationLevelId = 4 AND CM.ItemKey = @rKey
	   
	UNION ALL
	
	   SELECT CM.ItemKey,ISNULL(CS.ItemValue,CM.ItemValue)  FROM sConfig.tConfigurationMaster CM LEFT JOIN sConfig.tConfigurationSetup CS 
	   ON CS.ConfigurationId = CM.Id AND CS.SourceTypeId=2010 AND SourceId = @rOrgGroupId  Where CM.ConfigurationLevelId = 5 AND CM.ItemKey = @rKey
	  		
END
GO
PRINT N'Creating [sFee].[pFeeRefundDelete]...';


GO


CREATE PROCEDURE [sFee].[pFeeRefundDelete]
	 
		@rId bigint
		
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 

	BEGIN TRY
		BEGIN TRANSACTION		
	BEGIN
		
		DELETE  RRD
		FROM sFee.tReceiptRefundDetail RRD
		INNER JOIN sFee.tReceiptRefund RR ON RR.Id = RRD.ReceiptRefundId
		WHERE RRD.ReceiptRefundId=@rId
	
		DELETE  RR
		FROM sFee.tReceiptRefund RR
		WHERE RR.Id=@rId
		
		SELECT 1 AS Result
	END		
COMMIT TRANSACTION	
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH			
END
GO
PRINT N'Creating [sFee].[pFeeRefundDetail]...';


GO
CREATE PROCEDURE [sFee].[pFeeRefundDetail]
	 
		@rReceiptRefundId bigint
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 		
	SELECT 
			0 AS Id,
			0 AS ReceiptBookId,
			FM.Id AS FeeId,
			FM.OrderIndex,
			FM.Title AS FeeName,
			FRD.Amount AS PaidAmount,
			FS.Id AS FeeSetupId,
			ISNULL(RRD.Amount,0) AS FeeRefundAmount
    FROM 
		sFee.tFeeMaster FM
		INNER JOIN sFee.tFeeSetup FS
			ON FS.FeeId=FM.Id
		INNER JOIN sFee.tReceiptDetail FRD
			ON FRD.FeeSetupId=FS.Id
		INNER JOIN sFee.tReceipt FR
			ON FR.Id=FRD.ReceiptId
		INNER JOIN sFee.tReceiptRefund RR 
			ON RR.ReceiptId=FR.Id AND RR.SourceId=FR.SourceId
		INNER JOIN sFee.tReceiptRefundDetail RRD 
			ON RRD.ReceiptRefundId=RR.Id AND RRD.FeeSetupId = FRD.FeeSetupId
		WHERE 
		RRD.ReceiptRefundId=@rReceiptRefundId
		ORDER BY FS.StartDate,FM.OrderIndex ASC
END
GO
PRINT N'Creating [sFee].[pFeeRefundListGet]...';


GO

CREATE PROCEDURE [sFee].[pFeeRefundListGet]
		
		@rOrgGroupBatchId int,
		@rAdmissionCategoryId int,
		@rClassId int,
		@rDivisionId int,
		@rIdNo nvarchar(20)='',
		@rFirstName nvarchar(100)='',
		@rFromReceiptNumber int=0,
		@rToReceiptNumber int=0,
		@rReceiptBookId int=0,
		@rSourceTypeId int=0,
		@rPayTypeId tinyint=0,
		@rChequeNo nvarchar(20)='',
		@rFromDate date='',
		@rToDate date='',
		@rOrgId smallint,
		@rBatchId int,
		@rOrgGroupId smallint,
		@rCreatedUserName nvarchar(100),
		@rCreatedUserId bigint
		
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
			 BEGIN
				SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
				SET @rCreatedUserName = sCommon.fSearchStringGet(@rCreatedUserName)
			 END
BEGIN 		
	
	SELECT
		--RR.Id AS FeeRefundId,
		R.Id AS MReceiptId,
		RR.Id AS ReceiptId,
		RR.SourceTypeId AS SourceTypeId,
		CASE WHEN RR.SourceTypeId=2001 THEN 'Student'
		ELSE  'Employee' END AS SourceType,
		--STM.Title 
		A.AcademicId,
		A.RollNo,
		SM.Code AS Code,
		SM.FirstName+' '+SM.LastName AS Name,
		R.ReceiptNumber,
		R.ReceiptDate,
		RR.RefundDate,
		ISNULL(RR.RefundAmount,0)AS RefundAmount,
		ISNULL(R.TotalReceiptAmount,0)AS TotalReceiptAmount,
		ISNULL(R.DiscountAmount,0)AS DiscountAmount,
		RR.PayTypeId,
		PTM.Title AS PayType,
		RR.ChequeNo,
		RR.BankName,
		R.ReceiptBookId,
		RBM.Title AS ReceiptBook,
		RR.IsObsolete,
		A.OrgId,
		OM.DisplayTitle AS Organization,
		RR.BatchId,
		BM.Title AS Batch,
		RR.Remark,
		ISNULL(R.IsChequeCleared,0) AS IsChequeCleared,
		ISNULL(R.ChequeClearDate,'') AS ChequeClearDate,
		ISNULL(R.ChequeDate,'') AS ChequeDate,
		A.ClassName+' - '+A.DivisionName AS ClassName
  FROM 
		sFee.tReceiptRefund RR
		INNER JOIN sFee.tReceipt R ON RR.ReceiptId = R.Id
		INNER JOIN sStudent.vStudentAcademic A
			ON A.AcademicId=R.SourceId	
			AND (A.ClassId=@rClassId OR @rClassId=0) AND (A.DivisionId=@rDivisionId OR @rDivisionId=0)
		INNER JOIN sStudent.tStudentMaster SM
			ON SM.Id=A.StudentId
			AND (SM.AdmissionCategoryId=@rAdmissionCategoryId OR @rAdmissionCategoryId=0)
		INNER JOIN sCommon.tSourceTypeMaster STM
			ON STM.Id=RR.SourceTypeId
		INNER JOIN sFinanceCommon.tPayTypeMaster PTM
			ON PTM.Id=RR.PayTypeId
		INNER JOIN sFee.tReceiptBookMaster RBM
			ON RBM.Id=R.ReceiptBookId
		INNER JOIN sSetup.tOrganizationMaster OM
			ON OM.Id=SM.OrgId
			 AND OM.OrgGroupId=@rOrgGroupId
		INNER JOIN sSetup.tBatchMaster BM
			ON BM.Id=RR.BatchId 
			AND BM.OrgGroupBatchId=@rOrgGroupBatchId
		LEFT JOIN sSecurity.tUser U ON U.Id=RR.CreatedUserId
		INNER JOIN sFee.vUserReceiptBook URB ON URB.Id=RBM.Id AND URB.UserId=@rCreatedUserId
WHERE 
	((SM.Code like @rIdNo) OR (ISNULL(@rIdNo,'')=''))
	AND 
	(RR.SourceTypeId=2001)
	AND ((SM.FirstName like @rFirstName) OR(ISNULL(@rFirstName,'')=''))
	AND ((R.ReceiptNumber>=@rFromReceiptNumber)OR(@rFromReceiptNumber=0))
	AND ((R.ReceiptNumber<=@rToReceiptNumber)OR(@rToReceiptNumber=0))
	AND ((R.ReceiptBookId=@rReceiptBookId)OR(@rReceiptBookId=0))
	AND ((RR.PayTypeId=@rPayTypeId)OR(@rPayTypeId=0))
	AND ((RR.ChequeNo like @rChequeNo) OR(ISNULL(@rChequeNo,'')=''))
	AND ((STM.Id=@rSourceTypeId)OR(@rSourceTypeId=0))
	AND ((RR.RefundDate>=@rFromDate)OR(ISNULL(@rFromDate,'')=''))
	AND ((RR.RefundDate<=@rToDate)OR(ISNULL(@rToDate,'')=''))
	AND ((SM.OrgId=@rOrgId) OR (@rOrgId=0))
	AND ((RR.BatchId=@rBatchId) OR (@rBatchId=0))
	AND ((ISNULL(U.DisplayTitle,'') like @rCreatedUserName) OR (ISNULL(@rCreatedUserName,'')=''))
	ORDER BY R.ReceiptNumber DESC
END
GO
PRINT N'Creating [sFee].[pOnlineFeeAdd]...';


GO

CREATE PROCEDURE [sFee].[pOnlineFeeAdd]
	
			@rId bigint=0,
			@rSourceTypeId smallint,
			@rSourceId bigint,
			@rFeeAmount decimal(12, 2),
			@rPenaltyAmount decimal(12, 2),
			@rNetAmount decimal(12, 2),
			@rOnlineFeeDetailXml [nvarchar](max),
			@rOrgId int,
			@rReceiptBookId int

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rOnlineFeeDetailXml

BEGIN
		BEGIN TRY
		BEGIN TRANSACTION	
	 
	DECLARE @lNextNumber BIGINT     
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sFee.tOnlineFee', 0, 1, 1,@outNextNumber = @lNextNumber output

		INSERT INTO sFee.tOnlineFee
			(
				Id,
				SourceTypeId,
				SourceId,
				PayDateTime,
				FeeAmount,
				PenaltyAmount,
				NetAmount,
				ReceiptBookId
			)
		VALUES
			(
				@lNextNumber,
				@rSourceTypeId,
				@rSourceId,
				sCommon.fGetDate(),
				@rFeeAmount,
				@rPenaltyAmount,
				@rNetAmount,
				@rReceiptBookId
			)
		
		INSERT INTO sFee.tOnlineFeeDetail
			(
				OnlineFeeId,
				FeeSetupId,
				Amount
			)
		SELECT  	
			@lNextNumber,
			FeeSetupId,
			Amount
		FROM OPENXML (@loDoc, '/Table/OnlineFeeDetail', 1)
		WITH ( 
				FeeSetupId int,
				Amount decimal(12,2)
			  ) 

	SELECT @lNextNumber AS Result
	
	EXEC sp_xml_removedocument @loDoc
	
	COMMIT TRANSACTION
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END
GO
PRINT N'Creating [sFee].[pReceiptRefundAdd]...';


GO

CREATE PROCEDURE [sFee].[pReceiptRefundAdd]
	
		   @rId bigint,
		   @rSourceTypeId smallint,
		   @rSourceId bigint,
		   @rReceiptId bigint,
		   @rRefundDate date,
		   @rRefundAmount decimal(12,2),
		   @rPayTypeId tinyint,
		   @rChequeNo nvarchar(20),
		   @rBankName nvarchar(200),
		   @rRemark nvarchar(200),
		   @rIsObsolete bit,
		   @rBatchId int,
		   @rOrgGroupBatchId int,
		   @rCreatedUserId bigint,
		   @rOrgId int,
		   @rReceiptRefundDetailXml [nvarchar](max)

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rReceiptRefundDetailXml

BEGIN
	 BEGIN TRY
	 BEGIN TRANSACTION	
IF(@rId = 0)	
BEGIN
	DECLARE @lNextNumber BIGINT     
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sFee.tReceiptRefund', 0, 1, 1,@outNextNumber = @lNextNumber output
	INSERT INTO sFee.tReceiptRefund
		(
		   Id,
		   SourceTypeId,
		   SourceId,
		   ReceiptId,
		   RefundDate,
		   RefundAmount,
		   PayTypeId,
		   ChequeNo,
		   BankName,
		   Remark,
		   IsObsolete,
		   BatchId,
		   OrgGroupBatchId,
		   CreatedUserId,
		   CreatedDateTime
        )
	VALUES
		(
		   @lNextNumber,
		   @rSourceTypeId,
		   @rSourceId,
		   @rReceiptId,
		   @rRefundDate,
		   @rRefundAmount,
		   @rPayTypeId,
		   @rChequeNo,
		   @rBankName,
		   @rRemark,
		   @rIsObsolete,
		   @rBatchId,
		   @rOrgGroupBatchId,
		   @rCreatedUserId,
		   sCommon.fGetDate()
		)
		
		INSERT INTO sFee.tReceiptRefundDetail
		(
		   ReceiptRefundId,
		   FeeSetupId,
		   Amount
        )
        SELECT  	
		  @lNextNumber,
		  FeeSetupId,
		  Amount
		
	FROM OPENXML (@loDoc, '/Table/ReceiptRefundDetail', 1)
		WITH ( 
				FeeSetupId int,
				Amount decimal(12,2)
			  ) 
		
		SELECT 1,@lNextNumber AS Result
		
		EXEC sp_xml_removedocument @loDoc
 END
 
 ELSE
	BEGIN
		UPDATE sFee.tReceiptRefund 
		SET
			RefundAmount=@rRefundAmount,
			RefundDate=@rRefundDate,
			PayTypeId=@rPayTypeId,
		    ChequeNo=@rChequeNo,
		    BankName=@rBankName,
		    Remark=@rRemark
		WHERE Id=@rId
		
		DELETE FROM sFee.tReceiptRefundDetail WHERE ReceiptRefundId=@rId
		
		INSERT INTO sFee.tReceiptRefundDetail
		(
		   ReceiptRefundId,
		   FeeSetupId,
		   Amount
        )
        SELECT  	
		  @rId,
		  FeeSetupId,
		  Amount
		
		FROM OPENXML (@loDoc, '/Table/ReceiptRefundDetail', 1)
		WITH ( 
				FeeSetupId int,
				Amount decimal(12,2)
			  ) 
		SELECT 11 AS Result
	END 
 
	COMMIT TRANSACTION
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
END
GO
PRINT N'Creating [sFee].[pRptFeeRefundDetailsGet]...';


GO
CREATE PROCEDURE [sFee].[pRptFeeRefundDetailsGet]

			@rReceiptRefundId bigint = 0
			
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 	
	SELECT 
			RR.Id AS ReceiptRefundId,
			RR.ReceiptId,
			FR.ReceiptNumber,
			RR.RefundDate,
			SA.AcademicId,
			SA.FirstName+' '+SA.MiddleName+' '+SA.LastName AS Name,
			SA.Code,
			SA.RollNo,
			SA.ClassId,
			SA.DivisionId,
			SA.ClassName,
			SA.DivisionName,
			SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
			FM.FeeHeadId,
			FHM.Title AS FeeHead,
			FM.Id AS FeeId,
			FM.Title AS FeeName,
			RRD.Amount AS PaidAmount,
			PTM.Title AS PayType,
			ISNULL(RR.ChequeNo,'') AS ChequeNo,
			ISNULL(RR.BankName,'') AS BankName,
			ISNULL(RBM.Address1,'') AS Address1,
			ISNULL(RBM.Address2,'') AS Address2,
			ISNULL(RBM.FullTitle,'') AS FullTitle,
			ISNULL(RR.RefundAmount,0.00) AS TotalRefundAmount,
			ISNULL(FR.ReceiptAmount,0.00) AS ReceiptAmount,
			sFinanceCommon.fNumberToWordsWithDecimal(ISNULL(RR.RefundAmount,0.00),1,2,OM.OrgGroupId) AS RefundAmountInWords,
			ISNULL(FR.DiscountAmount,0.00) AS DiscountAmount,
			RR.Remark,
			ISNULL(U.DisplayTitle,'') AS UserName,
			OM.OrgLogo,
			RBM.Remark1,
			RBM.Remark2,			 
			ISNULL(RBM.IsOnPrePrinted,0) AS IsOnPrePrinted,
			ISNULL(RBM.IsSupressLogo,0) AS IsSupressLogo,
			ISNULL(RBM.IsDisplaySchoolName,0) AS IsDisplaySchoolName,
			RBM.ReportId,
			OM.Title AS OrganizationName,
			DM.Title AS DepartmentName,
			FM.OrderIndex AS FeeOrderIndex,
			FHM.OrderIndex AS FeeHeadOrderIndex,
			FR.IsObsolete AS IsCancelReceipt
	FROM 
			sFee.tReceipt FR				
			INNER JOIN sFee.tReceiptDetail FRD
				ON FR.Id=FRD.ReceiptId AND FR.SourceTypeId=2001				
			INNER JOIN sFee.tReceiptRefund RR 
				ON RR.ReceiptId=FR.Id AND RR.SourceId=FR.SourceId
			INNER JOIN sFee.tReceiptRefundDetail RRD 
				ON RRD.ReceiptRefundId=RR.Id AND RRD.FeeSetupId = FRD.FeeSetupId	
			INNER JOIN sFee.tFeeSetup FS
				ON FRD.FeeSetupId = FS.Id				
			INNER JOIN sFee.tFeeMaster FM
				ON FS.FeeId=FM.Id						
			INNER JOIN sFee.tFeeHeadMaster FHM
				ON FHM.Id=FM.FeeHeadId
			INNER JOIN sStudent.vStudentAcademic SA
				ON SA.AcademicId = RR.SourceId
			INNER JOIn sFinanceCommon.tPayTypeMaster PTM
				ON PTM.Id=RR.PayTypeId
			INNER JOIN sFee.tReceiptBookMaster RBM 
				ON RBM.Id=FR.ReceiptBookId
			LEFT JOIN sSecurity.tUser U
				ON U.Id=RR.CreatedUserId
			INNER JOIN sSetup.tDepartmentMaster DM
				ON SA.DepartmentId =DM.Id
			LEFT JOIN sSetup.tOrganizationMaster OM
				ON OM.Id=DM.OrgId
	WHERE 
	 RR.Id=@rReceiptRefundId 
ORDER BY FS.StartDate,FM.OrderIndex ASC
END
GO
PRINT N'Creating [sHrm].[pEmployeeDelete]...';


GO

CREATE PROCEDURE [sHrm].[pEmployeeDelete]
	 
           @rId bigint,
           @rOrgId smallint 
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	 BEGIN TRY 
	 BEGIN TRANSACTION	
		delete D from  sHrm.tEmployeeJobDetail D
		 INNER JOIN sHrm.tEmployeeMaster E  ON D.EmployeeId = E.Id
		 WHERE E.OrgId = @rOrgId AND D.EmployeeId = @rId
		 
		 
		 delete D from   sHrm.tEmployeeImages D
		 INNER JOIN sHrm.tEmployeeMaster E  ON D.EmployeeId = E.Id
		 WHERE E.OrgId = @rOrgId AND D.EmployeeId =@rId
		 
		 
		  delete D from   sHrm.tEmployeeFamilyDetails D
		 INNER JOIN sHrm.tEmployeeMaster E  ON D.EmployeeId = E.Id
		 WHERE E.OrgId = @rOrgId  AND D.EmployeeId = @rId
		 
		 
		   delete D from   sHrm.tEmployeeCommunications D
		 INNER JOIN sHrm.tEmployeeMaster E  ON D.EmployeeId = E.Id
		 WHERE E.OrgId = @rOrgId AND D.EmployeeId =@rId
		 
		 
		 
			delete D from   sHrm.tEmployeePersonalDetail D
		 INNER JOIN sHrm.tEmployeeMaster E  ON D.EmployeeId = E.Id
		 WHERE E.OrgId = @rOrgId  AND D.EmployeeId=@rId
		 
		 
		   delete D from   sHrm.tEmployeePreviousEmployment D
		 INNER JOIN sHrm.tEmployeeMaster E  ON D.EmployeeId = E.Id
		 WHERE E.OrgId = @rOrgId  AND D.EmployeeId =@rId
		 
		 
			delete D from   sHrm.tEmployeeQualification D
		 INNER JOIN sHrm.tEmployeeMaster E  ON D.EmployeeId = E.Id
		 WHERE E.OrgId = @rOrgId AND D.EmployeeId=@rId
		 
		   delete D from    sHrm.tEmployeeStatutoryAndOther D
		 INNER JOIN sHrm.tEmployeeMaster E  ON D.EmployeeId = E.Id
		 WHERE E.OrgId = @rOrgId AND D.EmployeeId =@rId
 
DELETE E FROM sHrm.temployeeMaster E WHERE E.OrgID = @rOrgId AND E.Id =@rId

Select 1 As Result
 
	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Creating [sIp].[pUniformItemAdd]...';


GO

CREATE PROCEDURE [sIp].[pUniformItemAdd]
	 
        @rId int,
		@rCode nvarchar(100),
		@rTitle nvarchar(100),
		@rIsObsolete bit,
		@rCreatedUserId bigint,
		@rOrgGroupId int,
		@rOrgId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	IF(@rId = 0)	
	BEGIN
	
		If Exists(select Id from sIp.tUniformItem where Title=@rTitle AND OrgGroupId=@rOrgGroupId)
			BEGIN
			select -103 as Result
			RETURN
		END 
	END
	 
	
	
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

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

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sIp.tUniformItem
	    SET
			Code = @rCode,
			Title=@rTitle,
			IsObsolete=@rIsObsolete,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate() ,
			 OrgGroupId = @rOrgGroupId
	      
	      
	      WHERE Id = @rId
	      SELECT 101 AS Result
	
		--COMMIT TRANSACTION
	 END  	

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


GO
CREATE PROCEDURE [sIp].[pUniformMasterGet]
	
	@rId int=0,
	@rCode nvarchar(100) ,
	@rTitle nvarchar(100),
	@rOrgGroupId int 

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
		 
	SELECT
			Id,
			Code,
			Title,
			IsObsolete,
			OrgGroupId
			 
	from sIp.tUniformItem
	   
	  WHERE  
			((Id = @rId) OR (@rId =0))
		 AND ((Title Like @rTitle + '%') OR (ISNULL(@rTitle,'')=''))
		AND ((Code = @rCode) OR (ISNULL(@rCode,'')='')) 
		AND OrgGroupId = @rOrgGroupId
	  
	 
END
GO
PRINT N'Creating [sSetup].[pOrgImageAdd]...';


GO
CREATE PROCEDURE [sSetup].[pOrgImageAdd]
	 
	@rOrgId smallint,
	@rOrganizationHead varbinary(max),
  
	@rDeleteOption nvarchar(20) = '',
	@rMarksheetHead varbinary(max)=null
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	SET @rDeleteOption = ISNULL(@rDeleteOption,'')
	BEGIN TRANSACTION
	
	IF (@rDeleteOption = '')
	BEGIN
		IF Exists (Select 1 from sSetup.tOrgImages where OrgId=@rOrgId)
		BEGIN
			UPDATE  sSetup.tOrgImages
			SET
				CertificateHeaderA4 = @rOrganizationHead
				--,
				--ICardBackground = @rIcardBg,
				--ICardBackBackground = @rIcardBackBg
				
			WHERE OrgId = @rOrgId 
		END
		ELSE 
		BEGIN
			INSERT INTO  sSetup.tOrgImages 
			(
				OrgId,
				CertificateHeaderA4,
				MarksheetHeaderA4
			)
			Values
			(
				@rOrgId,
				@rOrganizationHead,
				@rMarksheetHead
			)
		END
	END
	
 
	ELSE IF (@rDeleteOption = 'OrganizationHead') 
	BEGIN
		UPDATE  sSetup.tOrgImages
	SET
		CertificateHeaderA4=NULL 
	WHERE OrgId = @rOrgId 
	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].[pChangeBatchStatusAdd]...';


GO

CREATE PROCEDURE [sStudent].[pChangeBatchStatusAdd]
	 
	       
            @rAcademicId bigint
           ,@rStatusDate date
		   ,@rRemark nvarchar(200),
		   @rBatchStatusId smallint,
		    @rCreatedUserId bigint
		   ,@rOrgId int	
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 
--IF(@rAcademicId = 0)	
--BEGIN
	--EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sStudent.tStudentBatchStatus', 0, 1, 1,@outNextNumber = @lNextNumber output
	INSERT INTO sStudent.tStudentBatchStatus
			   (
			    AcademicId
			   ,StatusDate
			   --,[Code]
			   ,Remark 
			   ,BatchStatusId
			   ,CreatedUserId
			   ,CreatedDateTime			 
			    
			   )
		 VALUES
			   (
				@rAcademicId
			   ,@rStatusDate  
			   ,@rRemark
			   
			   ,@rBatchStatusId
			   ,@rCreatedUserId
			   ,sCommon.fGetDate()
			   
			   )
		    SELECT 1 AS Result
	
		--COMMIT TRANSACTION         
	--END	 
	-- ELSE
	-- BEGIN
	-- SET @lNextNumber = @rAcademicId
	--    UPDATE  sStudent.tStudentBatchStatus
	--    SET
			 
	--          StatusDate=@rStatusDate
	--          ,Remark = @rRemark
	--        ,BatchStatusId=@rBatchStatusId	  
	--		 ,UpdatedUserId =@rCreatedUserId
	--		 ,UpdatedDateTime=sCommon.fGetDate()
	--      WHERE AcademicId = @rAcademicId 	   
	--      SELECT @lNextNumber AS Result
	
	--	--COMMIT TRANSACTION
	-- END  
		
	--END
--END	
COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Creating [sStudent].[pChangeBatchStatusDelete]...';


GO
CREATE PROCEDURE [sStudent].[pChangeBatchStatusDelete]
	 @rAcademicId bigint
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	BEGIN TRY
		BEGIN TRANSACTION SD			 
			--Delete from sSecurity.tUserAccess where SourceId=@rId AND SourceTypeId = 2019
			Delete from sStudent.tStudentBatchStatus where AcademicId = @rAcademicId
		 Select 1 AS Result
		COMMIT TRANSACTION	SD
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION SD
		select -1 as Result
	END CATCH	
END
GO
PRINT N'Creating [sStudent].[pChangeBatchStatusGet]...';


GO
CREATE PROCEDURE [sStudent].[pChangeBatchStatusGet]
	 @rAcademicId bigint = 0,
	 @rStatus smallint=0 , 
	  @rBatchId int=0,
	  @rOrgId int=0,
	  @rDepartmentId int=0,
	  @rClassId int=0,
	  @rDivisionId int=0
	  
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 
	SELECT 
		SBS.AcademicId,
		SBS.BatchStatusId,
		SBS.Remark,
		SM.FIrstName + ' ' + SM.LastName As Name,
		BSM.Title AS BatchStatus,
		ISNULL(SBS.StatusDate,'') AS StatusDate,
		A.RollNo,
		A.Code,
		A.ClassName,
		A.DivisionName,
		A.DivisionId,
		A.BatchId,
		A.ClassId,
		A.OrgId,
		A.DepartmentId,
		OM.DisplayTitle AS Organization,
		Dm.Title AS Department,
		BM.Title AS Batch
		
		
			 
			
			
  FROM 
           sStudent.tStudentBatchStatus SBS
           INNER JOIN sStudent.vStudentFull A ON A.AcademicId = SBS.AcademicId 
            
           INNER JOIN sStudent.tStudentMaster Sm On Sm.Id = A.StudentId	
           
           INNER JOIN sStudent.tBatchStatusMaster BSM ON BSM.Id =SBS.BatchStatusId
           INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId
           INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
           INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id = A.DepartmentId
  WHERE 
		((SBS.AcademicId = @rAcademicId) OR (@rAcademicId =0))
		AND((SBS.BatchStatusId=@rStatus) OR (@rStatus=0)) 
		AND ((A.OrgId = @rOrgId) OR (@rOrgId=0))
		AND ((A.BatchId = @rBatchId) OR (@rbatchId)=0)
		AND ((A.DepartmentId = @rDepartmentId) or (@rDepartmentId=0))
		AND((A.ClassId = @rClassId) OR (@rClassId =0))
		AND ((A.DivisionId =@rDivisionId) OR (@rDivisionId=0))
END
GO
PRINT N'Creating [sStudent].[pImportAdmissionInquiry]...';


GO
CREATE PROCEDURE [sStudent].[pImportAdmissionInquiry]
    
    @rOrgGroupId smallint,
    @rOrgId smallint,
	@rXmldoc [nvarchar](max),
	@rUserId bigint,
	@rBatchId int

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
BEGIN TRY

DECLARE @lCount INT
DECLARE @lInterrorCode INT,
			@intDoc INT,
			@lFirstName nvarchar(100),
			@lMiddleName nvarchar(100),
			@lLastName nvarchar(100),
			@lClassId int,
			@lClass nvarchar(50),
			@lDOB date,
			@lStatusId int,
			--@lStatus nvarchar(20),
			@lPresentStreetOne nvarchar(150),
			@lPresentStreetTwo nvarchar(150),
			@lPresentStreetThree nvarchar(150),
			@lPresentCountry nvarchar(50),
			@lPresentState nvarchar(50),
			
			@lPresentCity nvarchar(50),
			@lPresentZipCode nvarchar(20),
			@lParentContactNo nvarchar(20),
			@lParentEmail nvarchar(50),
			@lRemark nvarchar(200),
			@lInquiryModeId smallint,
			@lInquiryMode nvarchar(50),
			@lInquiryReferenceId int,
			@lInquiryReference nvarchar(50),
			@lAdmissionCategoryId int,
			@lAdmissionCategory nvarchar(100),
			@lPreviousSchool nvarchar(200),
			@lMeritMarks decimal(10,2),
			@lMeritGrade nvarchar(20),
			@lMeritMarksBreakup nvarchar(100),
			@lGenderId int,
			@lGender nvarchar(10),
			 @lFollowupDate date,
			@lFollowupRemark nvarchar(150),
			@lInquiryDate date,
			--@lCode nvarchar(20),
			@lNumber bigint,
			@lHandledBy nvarchar(100),
			@lInquiryStatusId int,
			@lInquiryStatus nvarchar(50) 
		 
			 
			 
			
 		
--DECLARE @OutClassId int
--DECLARE @OutDivisionId int
DECLARE @OutStudentId bigint 
--DECLARE @OutAdmissionStandardId int
--DECLARE @OutReligionId int
--DECLARE @OutAdmissionCategoryId int		
SET @lAdmissionCategoryId=sCommon.fGetIntIdForOrg(1,@rOrgGroupId)	
				 
EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc
	 
	CREATE TABLE #tTable  
	(
		Id bigint identity,	 
		FirstName nvarchar(100),
		MiddleName nvarchar(100),
		LastName nvarchar(100),
		ClassId int  ,
		Class nvarchar(100),
		DOB date,
		StatusId smallint,
		--Status nvarchar(20),
		PresentStreetOne nvarchar(150),
		PresentStreetTwo nvarchar(150),
		PresentStreetThree nvarchar(150),
		PresentCountry nvarchar(50),
		PresentState nvarchar(50),
		PresentCity nvarchar(50),
		PresentZipCode nvarchar(20),
		ParentContactNo nvarchar(20),
		ParentEmail nvarchar(50),
		Remark nvarchar(200),
		InquiryModeId smallint,
		InquiryMode nvarchar(50),
		InquiryReferenceId int,
		InquiryReference nvarchar(50),
		AdmissionCategoryId int,
		AdmissionCategory nvarchar(100),
		PreviousSchool nvarchar(200),
		MeritMarks decimal(10,2),
		MeritGrade nvarchar(20),
		MeritMarksBreakup nvarchar(100),
		GenderId int,
		Gender nvarchar(10),
		 FollowupDate date,
		FollowupRemark nvarchar(150),
		CreatedUserId bigint,
		InquiryDate date,
		Number bigint,
		HandledBy nvarchar(100),
		InquiryStatusId int,
		InquiryStatus nvarchar(50) 
		 
		 
	)
	
	INSERT INTO #tTable
	(
		 
		FirstName,
		MiddleName,
		LastName,
		ClassId,
		Class,
		DOB,
		StatusId,
		--Status,
		PresentStreetOne,
		PresentStreetTwo,
		PresentStreetThree,
		PresentCountry,
		PresentState,
		PresentCity,
		PresentZipCode,
		ParentContactNo,
		ParentEmail,
		Remark,
		InquiryModeId,
		InquiryMode,
		InquiryReferenceId,
		InquiryReference,
		AdmissionCategoryId,
		AdmissionCategory,
		PreviousSchool,
		MeritMarks,
		MeritGrade,
		MeritMarksBreakup,
		GenderId,
		Gender,
		 FollowupDate,
		FollowupRemark,
		CreatedUserId,
		InquiryDate,
		Number,
		HandledBy,
		InquiryStatusId,
		InquiryStatus  
		
		
		 
	)
	
	SELECT
	 
		FirstName,
		MiddleName,
		LastName,
		0,
		Class,
		DOB,
		0,
	   -- Status,
	    PresentStreetOne,
		PresentStreetTwo,
		PresentStreetThree,
		PresentCountry,
		PresentState,
		PresentCity,
		PresentZipCode,
		ParentContactNo,
		ParentEmail,
		Remark,
		0,
		InquiryMode,
		0,
		InquiryReference,
		0,
		AdmissionCategory,
		PreviousSchool,
		MeritMarks,
		MeritGrade,
		MeritMarksBreakup,
		0,
		Gender,
		 FollowupDate,
		FollowupRemark,
		CreatedUserId,
		InquiryDate,
		Number,
		HandledBy,
		0,
		InquiryStatus  
		
		
			
	FROM OPENXML (@intDoc, '/Table/ImportStudent', 1)
	WITH
	( 
		  
		FirstName nvarchar(100) '@FirstName',
		MiddleName nvarchar(100) '@MiddleName',
		LastName nvarchar(100) '@LastName',
		Class nvarchar(100) '@Class',
		DOB DATE '@DOB',
		--Status nvarchar(20) '@Status',
		 PresentStreetOne nvarchar(150) '@PresentStreetOne',
		PresentStreetTwo nvarchar(150) '@PresentStreetTwo',
		PresentStreetThree nvarchar(150) '@PresentStreetThree',
		PresentCountry nvarchar(50) '@PresentCountry',
		PresentState nvarchar(50) '@PresentState',
		PresentCity nvarchar(50) '@PresentCity',
		PresentZipCode nvarchar(20) '@PresentZipCode',
		ParentContactNo nvarchar(20) '@ParentContactNo',
		ParentEmail nvarchar(50) '@ParentEmail',
		Remark nvarchar(200) '@Remark',
		InquiryMode  nvarchar(50) '@rInquiryMode',
		InquiryReference nvarchar(50) '@InquiryReference',
		AdmissionCategory nvarchar(100) '@AdmissionCategory',
		PreviousSchool nvarchar(200) '@PreviousSchool',
		MeritMarks decimal(10,2) '@MeritMarks',
		MeritGrade nvarchar(20) '@MeritGrade',
		MeritMarksBreakup nvarchar(100) '@MeritMarksBreakup',
		Gender nvarchar(10) '@Gender',
		 FollowupDate date '@FollowupDate',
		FollowupRemark nvarchar(150) '@FollowupRemark',
		CreatedUserId bigint '@CreatedUserId' ,
		InquiryDate date '@InquiryDate',
		Number bigint '@Number',
		HandledBy nvarchar(100) '@HandledBy',
		InquiryStatus nvarchar(50) '@InquiryStatus'
		 
		
	)
	
	 --print 'check'
 
 
EXEC sp_xml_removedocument @intDoc
			
SELECT @lCount =  COUNT(Id) FROM #tTable

WHILE @lCount > 0 

BEGIN
		 
		SET @lFirstName = ''
		SET @lMiddleName = ''
		SET @lLastName = ''
		SET @lClassId = null
		SET @lClass = ''
		
		SET @lDOB  = ''
		SET @lStatusId =null
		--SET @lStatus  = ''
		SET @lPresentStreetOne = ''
		SET @lPresentStreetTwo = ''
		SET @lPresentStreetThree = ''
		SET @lPresentCountry = ''
		SET @lPresentState = ''
		SET @lPresentCity = ''
		SET @lPresentZipCode = ''
		SET @lParentContactNo = ''
		SET @lParentEmail = ''	
		SEt @lRemark = ''
		SEt @lInquiryModeId =null
		SET @lInquiryMode =''
		SET @lInquiryReferenceId =null
		SET @lInquiryReference =''
		SET @lAdmissionCategoryId =null
		SEt @lAdmissionCategory =''
		SEt @lPreviousSchool =''
		SEt @lMeritMarks =null
		SEt @lMeritGrade  =''
		SET @lMeritMarksBreakup =''
		SEt @lGenderId  =null
		SEt @lGender=''
		SEt @lFollowupDate =''
		SET @lFollowupRemark =''
		SEt @lInquiryDate =''
		SEt @lNumber =null
		SET @lHandledBy =''
		SET @lInquiryStatusId  =null
		SET @lInquiryStatus =''
		
	 
		--SET @OutStudentId = null

		
SELECT		
		 
		@lFirstName = FirstName,
		@lMiddleName = MiddleName,
		@lLastName = LastName,
		@lClass = Class,
		@lDOB = CASE WHEN DOB = '' THEN  NULL ELSE DOB END,
		--@lStatus = Status,
		@lPresentStreetOne = PresentStreetOne,
		@lPresentStreetTwo = PresentStreetTwo,
		@lPresentStreetThree = PresentStreetThree,
		@lPresentCountry = PresentCountry,
		@lPresentState = PresentState,
		@lPresentCity = PresentCity,
		@lPresentZipCode = PresentZipCode,
		@lParentContactNo = ParentContactNo,
		@lParentEmail = ParentEmail,
		@lRemark = Remark,
		@lInquiryMode =InquiryMode,
		@lInquiryReference = InquiryReference,
		@lAdmissionCategory  =AdmissionCategory,
		@lPreviousSchool  = PreviousSchool,
		@lMeritMarks = MeritMarks,
		@lMeritGrade  =MeritGrade,
		@lMeritMarksBreakup  =MeritMarksBreakup,
		@lGender  =Gender,
		@lFollowupDate =CASE WHEN FollowupDate = '' THEN  NULL ELSE FollowupDate END,
		@lFollowupRemark  =FollowupRemark,
		@lInquiryDate  =  CASE WHEN InquiryDate = '' THEN  NULL ELSE InquiryDate END,
		@lNumber =Number,
		@lHandledBy =HandledBy,
		@lInquiryStatus =InquiryStatus 
		
		 
											 	 
FROM #tTable WHERE Id = @lCount  

	SELECT	@lGenderId = ID FROM sCommon.tGenderMaster WHERE Title = @lGender
	SELECT	@lClassId  = ID FROM sSetup.tClassMaster WHERE Title = @lClass AND OrgId = @rOrgId
	SELECT  @lInquiryModeId = ID from sAdmission.tInquiryModeMaster WHERE Title = @lInquiryMode 
	SELECT @lInquiryReferenceId =ID from sAdmission.tInquiryReferenceMaster Where Title = @lInquiryReference AND OrgGroupId = @rOrgGroupId
	Select @lInquiryStatusId = ID from sAdmission.tInquiryStatusMaster WHERE Title =@lInquiryStatus  AND  OrgGroupId =@rOrgGroupId
	Select @lStatusId = StatusId from sAdmission.tInquiryStatusMaster WHERE Id = @lInquiryStatusId
	
	SELECT	@lAdmissionCategoryId  = ID FROM tAdmissionCategoryMaster WHERE Title = @lAdmissionCategory AND OrgGroupId = @rOrgGroupId
	--SELECT	@lCastCategoryId  = ID FROM sCommon.tCastCategoryMaster WHERE Title = @lCastCategory AND OrgGroupId = @rOrgGroupId	
 
	
	IF(@lClassId IS NULL)
		SET @lClassId = 0
	IF(@lGenderId IS NULL)
		SET @lGenderId = 0
 
	IF(@lAdmissionCategoryId IS NULL)
		SET	@lAdmissionCategoryId = 0
	 
	 IF (@lInquiryModeId IS NULL)
		SET @lInquiryModeId=0
	IF (@lInquiryReferenceId IS Null)
		SET @lInquiryReferenceId=0
	IF (@lMeritMarks IS Null   )
		SET @lMeritMarks=0
	IF (@lNumber IS Null   )
		SET @lNumber=0 
		
 BEGIN TRANSACTION

 EXEC sAdmission.pAdmissionInquiryAdd 0,@lFirstName,@lMiddleName,@lLastName,@lClassId,@rBatchId,@lDOB,@rOrgId, @lInquiryStatusId,
									 @lPresentStreetOne,@lPresentStreetTwo,@lPresentStreetTwo,@lPresentCountry,@lPresentState,@lPresentCity,
									 @lPresentZipCode,@lParentContactNo,@lParentEmail,@lRemark,@lInquiryModeId,@lInquiryReferenceId,
									  @lAdmissionCategoryId,@lPreviousSchool,@lMeritMarks,@lMeritGrade,@lMeritMarksBreakup,
									  @lGenderId,@lFollowupDate,@lFollowupRemark,@rUserId,@lInquiryDate,@lNumber,@lHandledBy,@rOrgGroupId
	
		SET @lCount = @lCount - 1	
 
		 COMMIT TRANSACTION		
 
 
END
 

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


GO
CREATE PROCEDURE [sStudent].[pValidateImportAdmissionInquiry]

	@rOrgGroupId int,
    @rOrgId int,
	@rXmldoc [nvarchar](max)
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
DECLARE @lCount INT
DECLARE @lInterrorCode INT,
		@intDoc INT,
        
        @lClass nvarchar(100),
        @lInquiryDate nvarchar(15),
		@lInquiryStatus nvarchar(50),
        @lDOB nvarchar(15),             
        @1ReturnCode int = 1,
        @1ValidInquiryDate nvarchar(max)='',
        @1ValidDOB nvarchar(max) = '' 
       
       
EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc
 
CREATE TABLE #tTable1 
 (
		Id bigint identity,
        FirstName nvarchar(100),
        MiddleName nvarchar(100),
        LastName nvarchar(100),
		Class nvarchar(100),
		
		InquiryDate nvarchar(15), 
        InquiryStatus nvarchar(50),
        DOB nvarchar(15),
        Gender nvarchar(10)  
	 
 
  )
  INSERT INTO #tTable1
	(
	    
	    FirstName,
	    MiddleName,
	    LastName,
	    Class,
	    InquiryDate,
	    InquiryStatus,
	    DOB,
	    Gender 
	    
    ) 
   SELECT
       
	    FirstName,
	    MiddleName,
	    LastName,
	    Class,
	    InquiryDate,
	    InquiryStatus,
	    DOB,
	    Gender 
	  
   
   FROM OPENXML (@intDoc, '/Table/ImportStudent', 1)
   With
   (
        
        FirstName nvarchar(100) '@FirstName',
        MiddleName  nvarchar(100) '@MiddleName',
        LastName nvarchar(100) '@LastName',
		Class nvarchar(100) '@Class',
		 InquiryDate nvarchar(15) '@InquiryDate',
		 InquiryStatus nvarchar(50) '@InquiryStatus',
		DOB nvarchar(15) '@DOB',
		Gender nvarchar(10) '@Gender' 
   )   
EXEC sp_xml_removedocument @intDoc
		
SELECT @lCount =  COUNT(Id) FROM #tTable1
 
WHILE @lCount > 0 
  BEGIN
  
    IF(ISDATE(@lInquiryDate) = 0 AND @lInquiryDate!='')
	BEGIN    
		SET @1ValidInquiryDate = @1ValidInquiryDate + @lInquiryDate+','
	END
	IF(ISDATE(@lDOB) = 0 AND @lDOB!='')
	BEGIN
		SET @1ValidDOB=@1ValidDOB +   @lDOB+','
	END
     SET @lCount = @lCount - 1	
   END	
    
   
   SELECT @lCount =  COUNT(Id) FROM #tTable1
 
	WHILE @lCount > 0 
		BEGIN
			SELECT         
         
			 @lClass = Class 
			FROM #tTable1 WHERE Id = @lCount
			
			IF NOT EXISTS (SELECT 1 FROM  
					 sSetup.tClassMaster CM  
						WHERE CM.Title=@lClass   )	
			BEGIN
				
				SELECT 'Enter proper value for Class ' + @lClass   AS StudentCode
				RETURN
			END
			SET @lCount = @lCount - 1	
		END
   	
		   
		 
		  IF EXISTS(SELECT 1 FROM #tTable1 WHERE LastName IS NULL OR LastName='')
		BEGIN
			SELECT 'Surname Should not be empty' AS StudentCode
		END
		ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE FirstName IS NULL OR FirstName='')
		BEGIN
			SELECT 'First Name Should not be empty' AS StudentCode
		END
		ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE MiddleName IS NULL OR MiddleName='')
		BEGIN
			SELECT 'Middle Name Should not be empty' AS StudentCode
		END
		ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE Class IS NULL OR Class='')
		BEGIN
			SELECT 'Class 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 Class 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 Gender!='' AND Gender 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 AdmissionCategory!='' AND AdmissionCategory NOT IN(SELECT Title FROM sStudent.tAdmissionCategoryMaster))
		--BEGIN
		--	SELECT 'Enter proper value for Cast Category (Indian,NRI,General)' AS StudentCode
		--END
			 
		Else if Exists(Select 1 from #tTable1 where InquiryStatus!='' AND InquiryStatus NOT IN (Select Title from sAdmission.tInquiryStatusMaster))
		Begin
			Select 'Enter proper Value or check Spelling for Inquiry Status' AS StudentCode
		End
		ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE InquiryStatus IS NULL OR InquiryStatus='')
		BEGIN
			SELECT 'Inquiry Status Should not be empty ' AS StudentCode
		END
		ELSE
			
		BEGIN
			IF((@1ValidInquiryDate IS NULL OR @1ValidInquiryDate = '') AND (@1ValidDOB IS NULL OR @1ValidDOB = ''))
		BEGIN
			SELECT '' AS StudentCode
		END
		
		 ELSE IF (@1ValidDOB IS NOT NULL AND @1ValidDOB != '')
		BEGIN
			SET @1ValidDOB = 'Wrong DOB ' + @1ValidDOB
			Select @1ValidDOB AS StudentCode
		END
		
		END
		 
END
GO
PRINT N'Creating [sStudent].[pValidateImportCommunicationDetails]...';


GO
CREATE PROCEDURE [sStudent].[pValidateImportCommunicationDetails]

	@rOrgGroupId int,
    @rOrgId int,
	@rXmldoc [nvarchar](max)
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
DECLARE @lCount INT
DECLARE @lInterrorCode INT,
		@intDoc INT,
        @lCode nvarchar(50),
        @1ExistStudentCode nvarchar(max) = '',
        @1DuplicateStudentCode nvarchar(max) = '' 
        
       
EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc
 
CREATE TABLE #tTable1 
 (
		Id bigint identity,
        Code nvarchar(50) 
  )
  INSERT INTO #tTable1
	(
	    Code 
    ) 
   SELECT
        Code 
   
   FROM OPENXML (@intDoc, '/Table/ImportStudent', 1)
   With
   (
        Code nvarchar(50) '@Code' 
   )   
EXEC sp_xml_removedocument @intDoc
		
 IF EXISTS(SELECT 1 fROM #tTable1 WHERE Code IS NULL OR Code='')
		BEGIN
			SELECT 'ID No Should not be empty' AS StudentCode
			 Return 
		END
		 

		SELECT @1DuplicateStudentCode=COALESCE(@1DuplicateStudentCode ,'') 
				+ Code + ',' FROM #tTable1 GROUP BY Code HAVING ( COUNT(Code) > 1 )	
				
		IF(@1DuplicateStudentCode IS NOT NULL AND @1DuplicateStudentCode != '')
		BEGIN
			SET @1DuplicateStudentCode = 'Duplicate Code ' + @1DuplicateStudentCode
			SELECT @1DuplicateStudentCode AS StudentCode			
		END	
		ELSE
			SELECT '' AS StudentCode
END
GO
PRINT N'Creating [sStudent].[pValidateImportFamilyDetails]...';


GO
CREATE PROCEDURE [sStudent].[pValidateImportFamilyDetails]

	@rOrgGroupId int,
    @rOrgId int,
	@rXmldoc [nvarchar](max)
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
DECLARE @lCount INT
DECLARE @lInterrorCode INT,
		@intDoc INT,
        @lCode nvarchar(50),
        @1ExistStudentCode nvarchar(max) = '',
        @1DuplicateStudentCode nvarchar(max) = '' 
        
       
EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc
 
CREATE TABLE #tTable1 
 (
		Id bigint identity,
        Code nvarchar(50) 
  )
  
  
  INSERT INTO #tTable1
	(
	    Code 
    ) 
   SELECT
        Code 
   
   FROM OPENXML (@intDoc, '/Table/ImportStudent', 1)
   With
   (	
        Code nvarchar(50) '@Code' 
   )   
EXEC sp_xml_removedocument @intDoc
 
	
 	IF EXISTS(SELECT 1 fROM #tTable1 WHERE Code IS NULL OR Code='')
		BEGIN
			SELECT 'ID No Should not be empty' AS StudentCode
			 Return 
		END
		 

		SELECT @1DuplicateStudentCode=COALESCE(@1DuplicateStudentCode ,'') 
				+ Code + ',' FROM #tTable1 GROUP BY Code HAVING ( COUNT(Code) > 1 )	
				
		IF(@1DuplicateStudentCode IS NOT NULL AND @1DuplicateStudentCode != '')
		BEGIN
			SET @1DuplicateStudentCode = 'Duplicate Code ' + @1DuplicateStudentCode
			SELECT @1DuplicateStudentCode AS StudentCode			
		END	
		ELSE
			SELECT '' AS StudentCode
		

--SELECT @lCount =  COUNT(Id) FROM #tTable1
 
--WHILE @lCount > 0 
--  BEGIN
  
--       SELECT         
         
--         @lCode = Code 
         
--        FROM #tTable1 WHERE Id = @lCount 
     
--    IF Exists ((select 1 from sStudent.tStudentMaster where Code = @lCode AND OrgId = @rOrgId))         
--          BEGIN
--  			    SET @1ExistStudentCode = @1ExistStudentCode + @lCode + ','
--	       END	  
 
--     SET @lCount = @lCount - 1	
--   END	
   
--   SELECT @lCount =  COUNT(Id) FROM #tTable1
 
	 
		 
   	
--		IF EXISTS(SELECT 1 fROM #tTable1 WHERE Code IS NULL OR Code='')
--		BEGIN
--			SELECT 'ID No Should not be empty' AS StudentCode
--		END
		 
--		ELSE
--		BEGIN
--		SELECT @1DuplicateStudentCode=COALESCE(@1DuplicateStudentCode ,'') 
--		+ Code + ',' FROM #tTable1 GROUP BY Code HAVING ( COUNT(Code) > 1 )	
--		IF(@1DuplicateStudentCode IS NOT NULL AND @1DuplicateStudentCode != '')
--		BEGIN
--			SET @1DuplicateStudentCode = 'Duplicate Code ' + @1DuplicateStudentCode
--			SELECT @1DuplicateStudentCode AS StudentCode
--		END
--		ELSE
--		BEGIN
		 
--		IF((@1ExistStudentCode IS NULL OR @1ExistStudentCode = ''))
--		BEGIN
--			SELECT '' AS StudentCode
--		END
--		ELSE IF (@1ExistStudentCode IS NOT NULL AND @1ExistStudentCode != '')
--		BEGIN
--			SET @1ExistStudentCode = 'Exist Code ' + @1ExistStudentCode
--			Select @1ExistStudentCode AS StudentCode
--		END
		 
--		END
--		END
END
GO
PRINT N'Creating [sTimetable].[pAssignedClassRoomGet]...';


GO

CREATE PROCEDURE [sTimetable].[pAssignedClassRoomGet]
	 
	@rId int 
	
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 
	SELECT
				--AO.TimeTableSchemaId AS Id,
				CR.Id AS ClassRoomId,
				CR.Title AS Title ,
				CR.Code ,
				  
				 CASE WHEN AC.TimeTableSchemaId IS NULL THEN 'False' ELSE 'True' END AS IsObsolete
	FROM
			 sTimetable.tClassRoom CR 
			INNER JOIN sTimetable.tAssignClassRoom AC ON AC.ClassRoomId=CR.Id  
	WHERE AC.TimeTableSchemaId = @rId
	 
END
GO
PRINT N'Creating [sTimetable].[pClassRoomTimeOffAdd]...';


GO
 CREATE  PROCEDURE  [sTimetable].[pClassRoomTimeOffAdd]
	 
        @rClassRoomTimeOffXml [nvarchar](max),
		@rTimeTableSchemaId	int	,
		@rClassRoomId	int	
		WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rClassRoomTimeOffXml	
BEGIN 
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	 BEGIN
		
		 DELETE  FROM sTimetable.tClassRoomTimeOff   WHERE TimeTableSchemaId=@rTimeTableSchemaId AND ClassRoomId =@rClassRoomId
		  
		 
		INSERT INTO sTimetable.tClassRoomTimeOff
		(
			TimeTableSchemaId,
			ClassRoomId,
			DayId,
			LectureNumber
		)
		SELECT
		
		    TimeTableSchemaId,
			ClassRoomId,
			DayId,
			LectureNumber
		FROM OPENXML (@loDoc, '/Table/ClassRoomTimeOff', 1)
		WITH ( 
				TimeTableSchemaId int,
				ClassRoomId int,
				DayId tinyint,
				LectureNumber tinyint
				
			  ) 
	END
	SELECT 1 AS Result
	
	COMMIT TRANSACTION
	
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
END
GO
PRINT N'Creating [sTimetable].[pClassRoomTimeoffGet]...';


GO

CREATE PROCEDURE [sTimetable].[pClassRoomTimeoffGet]
	 
	@rTimeTableSchemaId int	,
	@rClassRoomId int
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 
	SELECT
		
		
		 isnull(LectureNumber,0) AS LectureNumber,
		 isnull(DayId,0) AS DayId 
	FROM 
	       sTimetable.tClassRoomTimeOff 
	       where  TimeTableSchemaId=@rTimeTableSchemaId AND ClassRoomId=@rClassRoomId

END
GO
PRINT N'Creating [sTimetable].[pDivisionTimeOffAdd]...';


GO
 CREATE  PROCEDURE  [sTimetable].[pDivisionTimeOffAdd]
	 
        @rDivisionTimeOffXml [nvarchar](max),
		@rTimeTableSchemaId	int	,
		@rDivisionId	int	
		WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rDivisionTimeOffXml	
BEGIN 
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	 BEGIN
		
		 DELETE  FROM sTimetable.tDivisionTimeOff   WHERE TimeTableSchemaId=@rTimeTableSchemaId AND DivisionId =@rDivisionId
		  
		 
		INSERT INTO sTimetable.tDivisionTimeOff
		(
			TimeTableSchemaId,
			DivisionId,
			DayId,
			LectureNumber
		)
		SELECT
		
		    TimeTableSchemaId,
			DivisionId,
			DayId,
			LectureNumber
		FROM OPENXML (@loDoc, '/Table/DivisionTimeOff', 1)
		WITH ( 
				TimeTableSchemaId int,
				DivisionId int,
				DayId tinyint,
				LectureNumber tinyint
				
			  ) 
	END
	SELECT 1 AS Result
	
	COMMIT TRANSACTION
	
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
END
GO
PRINT N'Creating [sTimetable].[pDivisionTimeoffGet]...';


GO

CREATE PROCEDURE [sTimetable].[pDivisionTimeoffGet]
	 
	@rTimeTableSchemaId int	,
	@rDivisionId int
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 
	SELECT
		
		 CASE WHEN DayId IS NULL THEN 'False' ELSE 'True' END AS IsObsolete,
		 isnull(LectureNumber,0) AS LectureNumber,
		 isnull(DayId,0) AS DayId 
	FROM 
	      sTimetable.tDivisionTimeOff 
	       where  TimeTableSchemaId=@rTimeTableSchemaId AND DivisionId=@rDivisionId

END
GO
PRINT N'Creating [sTimetable].[pSubjectTimeoffGet]...';


GO

CREATE PROCEDURE [sTimetable].[pSubjectTimeoffGet]
	 
	@rTimeTableSchemaId int	,
	@rSubjectId int
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 
	SELECT
		
		 CASE WHEN DayId IS NULL THEN 'False' ELSE 'True' END AS IsObsolete,
		 isnull(LectureNumber,0) AS LectureNumber,
		 isnull(DayId,0) AS DayId 
	FROM 
	      sTimetable.tSubjectTimeOff 
	       where  TimeTableSchemaId=@rTimeTableSchemaId AND SubjectId=@rSubjectId

END
GO
PRINT N'Creating [sTimetable].[pSynchAssignClassRoomGet]...';


GO

CREATE PROCEDURE [sTimetable].[pSynchAssignClassRoomGet]
	 
	@rTimeTableSchemaId int
	
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 
	SELECT
		*
	FROM		
		sTimetable.tAssignClassRoom 
	WHERE 
		TimeTableSchemaId = @rTimeTableSchemaId
END
GO
PRINT N'Creating [sTimetable].[pSynchAssignOrganizationGet]...';


GO

CREATE PROCEDURE [sTimetable].[pSynchAssignOrganizationGet]
	 
	@rTimeTableSchemaId int
	
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 
	SELECT
		*
	FROM		
		sTimetable.tAssignOrg
	WHERE 
		TimeTableSchemaId = @rTimeTableSchemaId
END
GO
PRINT N'Creating [sTimetable].[pSynchBatchMasterGet]...';


GO

CREATE PROCEDURE [sTimetable].[pSynchBatchMasterGet]
	 
	@rOrgGroupId int
	
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 
	SELECT
		BM.Id,
		BM.Code,
		BM.Title,
		BM.OrgId,
		OM.OrgGroupId
	FROM		
		sSetup.tBatchMaster BM
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
	WHERE 
		OM.OrgGroupId = @rOrgGroupId
END
GO
PRINT N'Creating [sTimetable].[pSynchClassMasterGet]...';


GO

CREATE PROCEDURE [sTimetable].[pSynchClassMasterGet]
	 
	@rOrgGroupId int
	
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 
	SELECT
		CM.Id,
		CM.Code,
		CM.Title,
		CM.OrderIndex,
		CM.IsObsolete,
		CM.OrgId,
		OM.OrgGroupId
	FROM		
		sSetup.tClassMaster CM
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = CM.OrgId
	WHERE 
		OM.OrgGroupId = @rOrgGroupId
END
GO
PRINT N'Creating [sTimetable].[pSynchClassRoomGet]...';


GO

CREATE PROCEDURE [sTimetable].[pSynchClassRoomGet]
	 

	
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 
	SELECT
		*
	FROM		
		sTimeTable.tClassRoom
	
END
GO
PRINT N'Creating [sTimetable].[pSynchClassRoomTimeOffGet]...';


GO

CREATE PROCEDURE [sTimetable].[pSynchClassRoomTimeOffGet]
	 
	@rTimeTableSchemaId int
	
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 
	SELECT
		*
	FROM		
		sTimetable.tClassRoomTimeOff
	WHERE 
		TimeTableSchemaId = @rTimeTableSchemaId
END
GO
PRINT N'Creating [sTimetable].[pSynchClassSubjectGet]...';


GO

CREATE PROCEDURE [sTimetable].[pSynchClassSubjectGet]
	 
	@rOrgGroupId int
	
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 
	SELECT
		CS.Id,
		CS.OrgId,
		CS.ClassId,
		CS.SubjectId,		
		OM.OrgGroupId
	FROM		
		sSetup.tClassSubject CS
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = CS.OrgId
	WHERE 
		OM.OrgGroupId = @rOrgGroupId
END
GO
PRINT N'Creating [sTimetable].[pSynchDivisionClassRoomGet]...';


GO

CREATE PROCEDURE [sTimetable].[pSynchDivisionClassRoomGet]
	 
	@rTimeTableSchemaId int
	
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 
	SELECT
		*
	FROM		
		sTimetable.tDivisionClassRoom
	WHERE 
		TimeTableSchemaId = @rTimeTableSchemaId
END
GO
PRINT N'Creating [sTimetable].[pSynchDivisionGet]...';


GO

CREATE PROCEDURE [sTimetable].[pSynchDivisionGet]
	 
	@rOrgGroupId int
	
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 
	SELECT
		DM.Id,
		DM.Code,
		DM.Title,
		DM.DisplayTitle,
		DM.InchargeEmployeeId AS ClassTeacherId,
		DM.OrgId,	
		DM.OrderIndex,
		DM.CreatedUserId,
		DM.CreatedDateTime,
		DM.ClassId,
		OM.OrgGroupId	
	FROM		
		sSetup.tDivisionMaster DM
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = DM.OrgId
	WHERE 
		OM.OrgGroupId = @rOrgGroupId
END
GO
PRINT N'Creating [sTimetable].[pSynchdivisionTimeOffGet]...';


GO

CREATE PROCEDURE [sTimetable].[pSynchdivisionTimeOffGet]
	 
	@rTimeTableSchemaId int
	
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 
	SELECT
		*
	FROM		
		sTimetable.tDivisionTimeOff
	WHERE 
		TimeTableSchemaId = @rTimeTableSchemaId
END
GO
PRINT N'Creating [sTimetable].[pSynchDivisionWorkLoadGet]...';


GO

CREATE PROCEDURE [sTimetable].[pSynchDivisionWorkLoadGet]
	 
	@rTimeTableSchemaId int
	
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 
	SELECT
		*
	FROM		
		sTimetable.tDivisionWorkLoad
	WHERE 
		TimeTableSchemaId = @rTimeTableSchemaId
END
GO
PRINT N'Creating [sTimetable].[pSynchOrganizationMasterGet]...';


GO

CREATE PROCEDURE [sTimetable].[pSynchOrganizationMasterGet]
	 
	@rOrgGroupId int
	
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 
	SELECT
		OM.Id,
		OM.Code,
		OM.Title,
		OM.OrgGroupId
	FROM		
		sSetup.tOrganizationMaster OM 
	WHERE 
		OM.OrgGroupId = @rOrgGroupId
END
GO
PRINT N'Creating [sTimetable].[pSynchProxySettingGet]...';


GO

CREATE PROCEDURE [sTimetable].[pSynchProxySettingGet]
	 
	@rTimeTableSchemaId int
	
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 
	SELECT
		*
	FROM		
		sTimetable.tProxysetting
	WHERE 
		TimeTableSchemaId = @rTimeTableSchemaId
END
GO
PRINT N'Creating [sTimetable].[pSynchSchoolBuildingGet]...';


GO

CREATE PROCEDURE [sTimetable].[pSynchSchoolBuildingGet]
	 
--	@rTimeTableSchemaId int
	
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 
	SELECT
		*
	FROM		
		sTimetable.tSchoolBuilding
--	WHERE 
--		TimeTableSchemaId = @rTimeTableSchemaId
END
GO
PRINT N'Creating [sTimetable].[pSynchSubjectClassRoomGet]...';


GO

CREATE PROCEDURE [sTimetable].[pSynchSubjectClassRoomGet]
	 
	@rTimeTableSchemaId int
	
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 
	SELECT
		*
	FROM		
		sTimetable.tSubjectClassRoom
	WHERE 
		TimeTableSchemaId = @rTimeTableSchemaId
END
GO
PRINT N'Creating [sTimetable].[pSynchSubjectGet]...';


GO

CREATE PROCEDURE [sTimetable].[pSynchSubjectGet]
	 
	@rOrgGroupId int
	
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 
	SELECT
		SM.Id,
		SM.Code,
		SM.Number,
		SM.Title,
		SM.OrgId,
		SM.OrderIndex,
		SM.CreatedUserId,
		SM.CreatedDateTime,
		OM.OrgGroupId
	FROM		
		sSetup.tSubjectMaster SM 
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SM.OrgId
	WHERE 
		OM.OrgGroupId = @rOrgGroupId
END
GO
PRINT N'Creating [sTimetable].[pSynchSubjectTimeOffGet]...';


GO

CREATE PROCEDURE [sTimetable].[pSynchSubjectTimeOffGet]
	 
	@rTimeTableSchemaId int
	
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 
	SELECT
		*
	FROM		
		sTimetable.tSubjectTimeOff
	WHERE 
		TimeTableSchemaId = @rTimeTableSchemaId
END
GO
PRINT N'Creating [sTimetable].[pSynchTeacherGet]...';


GO

CREATE PROCEDURE [sTimetable].[pSynchTeacherGet]
	 
	@rOrgGroupId int
	
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 
	SELECT
		EM.Id,
		EM.Code,
		ISNULL(EM.FirstName,'') + ' ' + ISNULL(EM.MiddleName,'') + ' ' + ISNULL(EM.LastName,'') AS Title,
		EM.OrgId,
		EM.CreatedUserId,
		EM.CreatedDateTime,
		OM.OrgGroupId
	FROM		
		sHrm.tEmployeeMaster EM 
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgId
	WHERE 
		OM.OrgGroupId = @rOrgGroupId
END
GO
PRINT N'Creating [sTimetable].[pSynchTeacherTimeOffGet]...';


GO

CREATE PROCEDURE [sTimetable].[pSynchTeacherTimeOffGet]
	 
	@rTimeTableSchemaId int
	
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 
	SELECT
		*
	FROM		
		sTimetable.tTeacherTimeOff
	WHERE 
		TimeTableSchemaId = @rTimeTableSchemaId
END
GO
PRINT N'Creating [sTimetable].[pSynchTeacherWorkLoadGet]...';


GO

CREATE PROCEDURE [sTimetable].[pSynchTeacherWorkLoadGet]
	 
	@rTimeTableSchemaId int
	
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 
	SELECT
		*
	FROM		
		sTimetable.tTeacherWorkLoad
	WHERE 
		TimeTableSchemaId = @rTimeTableSchemaId
END
GO
PRINT N'Creating [sTimetable].[pSynchTimeSetupGet]...';


GO

CREATE PROCEDURE [sTimetable].[pSynchTimeSetupGet]
	 
	@rTimeTableSchemaId int
	
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 
	SELECT
		*
	FROM		
		sTimetable.tTimeSetup
	WHERE 
		TimeTableSchemaId = @rTimeTableSchemaId
END
GO
PRINT N'Creating [sTimetable].[pSynchTimeTableSchemaGet]...';


GO

CREATE PROCEDURE [sTimetable].[pSynchTimeTableSchemaGet]
	 
	--@rTimeTableSchemaId int
	
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 
	SELECT
		*
	FROM		
		sTimetable.tTimeTableSchema
	--WHERE 
	--	TimeTableSchemaId = @rTimeTableSchemaId
END
GO
PRINT N'Creating [sTimetable].[pTeacherTimeOffAdd]...';


GO
 CREATE  PROCEDURE  [sTimetable].[pTeacherTimeOffAdd]
	 
        @rTeacherTimeOffXml [nvarchar](max),
		@rTimeTableSchemaId	int	,
		@rEmployeeId	bigint	
		WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rTeacherTimeOffXml	
BEGIN 
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	 BEGIN
		
		 DELETE  FROM sTimetable.tTeacherTimeOff   WHERE TimeTableSchemaId=@rTimeTableSchemaId AND EmployeeId =@rEmployeeId
		  
		 
		INSERT INTO sTimetable.tTeacherTimeOff
		(
			TimeTableSchemaId,
			EmployeeId,
			DayId,
			LectureNumber
		)
		SELECT
		
		    TimeTableSchemaId,
			EmployeeId,
			DayId,
			LectureNumber
		FROM OPENXML (@loDoc, '/Table/TeacherTimeOff', 1)
		WITH ( 
				TimeTableSchemaId int,
				EmployeeId bigint,
				DayId tinyint,
				LectureNumber tinyint
				
			  ) 
	END
	SELECT 1 AS Result
	
	COMMIT TRANSACTION
	
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
END
GO
PRINT N'Creating [sTimetable].[pTeacherTimeoffGet]...';


GO

CREATE PROCEDURE [sTimetable].[pTeacherTimeoffGet]
	 
	@rTimeTableSchemaId int	,
	@rEmployeeId bigint
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 
	SELECT
		
		
		 isnull(LectureNumber,0) AS LectureNumber,
		 isnull(DayId,0) AS DayId 
	FROM 
	       sTimetable.tTeacherTimeOff
	       where  TimeTableSchemaId=@rTimeTableSchemaId AND EmployeeId=@rEmployeeId

END
GO
PRINT N'Creating [sTimetable].[pTimeTableAssignedTeacherGet]...';


GO

CREATE PROCEDURE [sTimetable].[pTimeTableAssignedTeacherGet]
	 
	@rId int	 
   -- @rOrgGroupId  smallint
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 
	SELECT
				
				EMP.CODE,
				EMP.FIRSTNAME + ' ' + isnull(EMP.MIDDLENAME,'')+ ' ' + EMP.LASTNAME  AS NAME,
				EMP.ID AS EMPLOYEEID ,
				 OM.DisplayTitle AS Organization,
				
				 CASE WHEN AT.TimeTableSchemaId IS NULL THEN 'False' ELSE 'True' END AS IsObsolete
	FROM
			sHrm.tEmployeeMaster EMP
			 INNER JOIN sTimetable.tAssignTeacher AT ON AT.EMPLOYEEID = EMP.ID AND AT.TimeTableSchemaId=@rId
			 LEFT JOIN  sSetup.tOrganizationMaster OM ON OM.Id = EMP.OrgID 
	 
	ORDER BY  EMP.Code
END
GO
PRINT N'Creating [sTimetable].[pTimeTableDetailGet]...';


GO

CREATE PROCEDURE [sTimetable].[pTimeTableDetailGet]
	 
	--@rTimeTableSchemaId int
	
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 
	SELECT
		*
	FROM		
		sTimetable.tTimeTableDetail
	--WHERE 
	--	TimeTableSchemaId = @rTimeTableSchemaId
END
GO
PRINT N'Creating [sTimetable].[pTimeTableGet]...';


GO

CREATE PROCEDURE [sTimetable].[pTimeTableGet]
	 
	@rTimeTableSchemaId int
	
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 
	SELECT
		*
	FROM		
		sTimetable.tTimeTable
	WHERE 
		TimeTableSchemaId = @rTimeTableSchemaId
END
GO


 
 
