


 
 /*
Deployment script for NetVidyalayaVirani
*/

GO
SET ANSI_NULLS, ANSI_PADDING, ANSI_WARNINGS, ARITHABORT, CONCAT_NULL_YIELDS_NULL, QUOTED_IDENTIFIER ON;

SET NUMERIC_ROUNDABORT OFF;


--GO
--:setvar DatabaseName "NetVidyalayaVirani"
--:setvar DefaultDataPath "c:\Program Files\Microsoft SQL Server\MSSQL10_50.SQLEXPRESS\MSSQL\DATA\"
--:setvar DefaultLogPath "c:\Program Files\Microsoft SQL Server\MSSQL10_50.SQLEXPRESS\MSSQL\DATA\"

--GO
--:on error exit
--GO
--USE [master]
--GO
--IF EXISTS (SELECT 1
--           FROM   [master].[dbo].[sysdatabases]
--           WHERE  [name] = N'$(DatabaseName)')
--    BEGIN
--        ALTER DATABASE [$(DatabaseName)]
--            SET AUTO_CLOSE OFF 
--            WITH ROLLBACK IMMEDIATE;
--    END


--GO
--USE [$(DatabaseName)]
--GO
PRINT N'Dropping [sCommunication].[tPhotoMaster]...';


GO
DROP TABLE [sCommunication].[tPhotoMaster];


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


GO
DROP TABLE [sHrm].[tMedicalCoverageMaster];


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


GO
DROP TABLE [sHrm].[tParticipantTypeMaster];


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


GO
DROP VIEW [sHrm].[vExtEmployeeJobTitleMaster];


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


GO
DROP VIEW [sHrm].[vExtEmployeePersonalDetail];


GO
PRINT N'Dropping [sCommunication].[pBehaviorTypeMasterGet]...';


GO
DROP PROCEDURE [sCommunication].[pBehaviorTypeMasterGet];


GO
PRINT N'Dropping [sCommunication].[pPhotoMasterAdd]...';


GO
DROP PROCEDURE [sCommunication].[pPhotoMasterAdd];


GO
PRINT N'Dropping [sCommunication].[pPhotoMasterGet]...';


GO
DROP PROCEDURE [sCommunication].[pPhotoMasterGet];


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


GO
DROP PROCEDURE [sHrm].[pChangeLocationAdd];


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


GO
DROP PROCEDURE [sHrm].[pChangeLocationGet];


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


GO
DROP PROCEDURE [sHrm].[pCsrBenifitAdd];


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


GO
DROP PROCEDURE [sHrm].[pEmployeeBranchAndDepartmentGet];


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


GO
DROP PROCEDURE [sHrm].[pEmployeeCommunicationDelete];


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


GO
DROP PROCEDURE [sHrm].[pEmployeeContactAdd];


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


GO
DROP PROCEDURE [sHrm].[pEmployeeContactGet];


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


GO
DROP PROCEDURE [sHrm].[pEmployeeContactModify];


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


GO
DROP PROCEDURE [sHrm].[pEmployeeCsrBenifitGet];


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


GO
DROP PROCEDURE [sHrm].[pEmployeeCsrBenifitListGet];


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


GO
DROP PROCEDURE [sHrm].[pEmployeeDesignationMasterRemove];


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


GO
DROP PROCEDURE [sHrm].[pEmployeeFamilyNameRelationGet];


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


GO
DROP PROCEDURE [sHrm].[pEmployeeImagesDelete];


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


GO
DROP PROCEDURE [sHrm].[pEmployeeMasterRemove];


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


GO
DROP PROCEDURE [sHrm].[pEmployeePreviousEmploymentModify];


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


GO
DROP PROCEDURE [sHrm].[pImportExamination];


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


GO
DROP PROCEDURE [sHrm].[pQualificationMasterRemove];


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


GO
DROP PROCEDURE [sHrm].[pRptEmployeeDependantList];


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


GO
DROP PROCEDURE [sHrm].[pRptEmployeeQualification];


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


GO
DROP PROCEDURE [sHrm].[pRptEmployeeStatus];


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


GO
DROP PROCEDURE [sHrm].[pValidateImportEmployee_OLD];


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


GO
DROP PROCEDURE [sHrm].[pXMLEmployeeMasterAdd];


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


GO
DROP PROCEDURE [sHrm].[pXMLEmployeeMasterUpdate];


GO
PRINT N'Dropping [sSecurity].[pUserWithEmployeeDetailByEmployeeId]...';


GO
DROP PROCEDURE [sSecurity].[pUserWithEmployeeDetailByEmployeeId];


GO
PRINT N'Dropping [sSecurity].[pUserWithEmployeeDetailByRoleId]...';


GO
DROP PROCEDURE [sSecurity].[pUserWithEmployeeDetailByRoleId];


GO
PRINT N'Dropping [sSecurity].[pUserWithEmployeeDetailByUserId]...';


GO
DROP PROCEDURE [sSecurity].[pUserWithEmployeeDetailByUserId];


GO
PRINT N'Altering [sBiometric].[tPunchMaster]...';


GO
ALTER TABLE [sBiometric].[tPunchMaster] DROP COLUMN [OrgId];


GO
ALTER TABLE [sBiometric].[tPunchMaster]
    ADD [OrgGroupId]      SMALLINT NOT NULL,
        [CreatedUserId]   BIGINT   NOT NULL,
        [CreatedDateTime] DATETIME NOT NULL,
        [UpdatedUserId]   BIGINT   NULL,
        [UpdatedDateTime] DATETIME NULL;


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


GO
ALTER TABLE [sCommon].[tReport]
    ADD [ReportTypeId] TINYINT NULL;


GO
PRINT N'Starting rebuilding table [sCommon].[tReportFormatGroupOrg]...';


GO
/*
The column [sCommon].[tReportFormatGroupOrg].[ReportId] on table [sCommon].[tReportFormatGroupOrg] must be added, but the column has no default value and does not allow NULL values. If the table contains data, the ALTER script will not work. To avoid this issue, you must add a default value to the column or mark it as allowing NULL values.
*/
GO
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;

SET XACT_ABORT ON;

BEGIN TRANSACTION;

CREATE TABLE [sCommon].[tmp_ms_xx_tReportFormatGroupOrg] (
    [OrgId]               SMALLINT NOT NULL,
    [ReportId]            SMALLINT NOT NULL,
    [ReportFormatGroupId] SMALLINT NOT NULL
);

IF EXISTS (SELECT TOP 1 1
           FROM   [sCommon].[tReportFormatGroupOrg])
    BEGIN
        INSERT INTO [sCommon].[tmp_ms_xx_tReportFormatGroupOrg] ([OrgId], [ReportFormatGroupId])
        SELECT [OrgId],
               [ReportFormatGroupId]
        FROM   [sCommon].[tReportFormatGroupOrg];
    END

DROP TABLE [sCommon].[tReportFormatGroupOrg];

EXECUTE sp_rename N'[sCommon].[tmp_ms_xx_tReportFormatGroupOrg]', N'tReportFormatGroupOrg';

COMMIT TRANSACTION;

SET TRANSACTION ISOLATION LEVEL READ COMMITTED;


GO
PRINT N'Starting rebuilding table [sCommunication].[tBehaviourTypeMaster]...';


GO
/*
The column [sCommunication].[tBehaviourTypeMaster].[OrgId] is being dropped, data loss could occur.

The column [sCommunication].[tBehaviourTypeMaster].[OrgGroupId] on table [sCommunication].[tBehaviourTypeMaster] must be added, but the column has no default value and does not allow NULL values. If the table contains data, the ALTER script will not work. To avoid this issue, you must add a default value to the column or mark it as allowing NULL values.
*/
GO
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;

SET XACT_ABORT ON;

BEGIN TRANSACTION;

CREATE TABLE [sCommunication].[tmp_ms_xx_tBehaviourTypeMaster] (
    [Id]                   INT            NOT NULL,
    [Title]                NVARCHAR (100) NOT NULL,
    [Remark]               NVARCHAR (200) NOT NULL,
    [BehaviourIndicatorId] TINYINT        NOT NULL,
    [OrgGroupId]           SMALLINT       NOT NULL,
    [IsObsolete]           BIT            NOT NULL,
    [CreatedUserId]        BIGINT         NOT NULL,
    [CreatedDateTime]      DATETIME       NOT NULL,
    [UpdatedUserId]        BIGINT         NULL,
    [UpdatedDateTime]      DATETIME       NULL
);

IF EXISTS (SELECT TOP 1 1
           FROM   [sCommunication].[tBehaviourTypeMaster])
    BEGIN
        INSERT INTO [sCommunication].[tmp_ms_xx_tBehaviourTypeMaster] ([Id], [Title], [Remark], [BehaviourIndicatorId], [IsObsolete], [CreatedUserId], [CreatedDateTime], [UpdatedUserId], [UpdatedDateTime])
        SELECT [Id],
               [Title],
               [Remark],
               [BehaviourIndicatorId],
               [IsObsolete],
               [CreatedUserId],
               [CreatedDateTime],
               [UpdatedUserId],
               [UpdatedDateTime]
        FROM   [sCommunication].[tBehaviourTypeMaster];
    END

DROP TABLE [sCommunication].[tBehaviourTypeMaster];

EXECUTE sp_rename N'[sCommunication].[tmp_ms_xx_tBehaviourTypeMaster]', N'tBehaviourTypeMaster';

COMMIT TRANSACTION;

SET TRANSACTION ISOLATION LEVEL READ COMMITTED;


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


GO
ALTER TABLE [sCommunication].[tPhotoCategoryMaster] DROP COLUMN [OrgId];


GO
ALTER TABLE [sCommunication].[tPhotoCategoryMaster]
    ADD [OrgGroupId] SMALLINT NOT NULL;


GO
PRINT N'Starting rebuilding table [sCommunication].[tPoll]...';


GO
/*
The column [sCommunication].[tPoll].[BatchId] is being dropped, data loss could occur.

The column [sCommunication].[tPoll].[OrgGroupBatchId] on table [sCommunication].[tPoll] must be added, but the column has no default value and does not allow NULL values. If the table contains data, the ALTER script will not work. To avoid this issue, you must add a default value to the column or mark it as allowing NULL values.

The column [sCommunication].[tPoll].[OrgGroupId] on table [sCommunication].[tPoll] must be added, but the column has no default value and does not allow NULL values. If the table contains data, the ALTER script will not work. To avoid this issue, you must add a default value to the column or mark it as allowing NULL values.
*/
GO
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;

SET XACT_ABORT ON;

BEGIN TRANSACTION;

CREATE TABLE [sCommunication].[tmp_ms_xx_tPoll] (
    [Id]              BIGINT         NOT NULL,
    [Title]           NVARCHAR (200) NOT NULL,
    [Remark]          NVARCHAR (500) NULL,
    [IsOwnAnswer]     BIT            NULL,
    [IsOpen]          BIT            NULL,
    [OrgGroupId]      SMALLINT       NOT NULL,
    [OrgGroupBatchId] INT            NOT NULL,
    [CreatedUserId]   BIGINT         NOT NULL,
    [CreatedDateTime] DATETIME       NOT NULL,
    [UpdatedUserId]   BIGINT         NULL,
    [UpdatedDateTime] DATETIME       NULL
);

IF EXISTS (SELECT TOP 1 1
           FROM   [sCommunication].[tPoll])
    BEGIN
        INSERT INTO [sCommunication].[tmp_ms_xx_tPoll] ([Id], [Title], [Remark], [IsOwnAnswer], [IsOpen], [CreatedUserId], [CreatedDateTime], [UpdatedUserId], [UpdatedDateTime])
        SELECT [Id],
               [Title],
               [Remark],
               [IsOwnAnswer],
               [IsOpen],
               [CreatedUserId],
               [CreatedDateTime],
               [UpdatedUserId],
               [UpdatedDateTime]
        FROM   [sCommunication].[tPoll];
    END

DROP TABLE [sCommunication].[tPoll];

EXECUTE sp_rename N'[sCommunication].[tmp_ms_xx_tPoll]', N'tPoll';

COMMIT TRANSACTION;

SET TRANSACTION ISOLATION LEVEL READ COMMITTED;


GO
PRINT N'Starting rebuilding table [sCommunication].[tQuery]...';


GO
/*
The column [sCommunication].[tQuery].[BatchId] is being dropped, data loss could occur.

The column [sCommunication].[tQuery].[OrgGroupBatchId] on table [sCommunication].[tQuery] must be added, but the column has no default value and does not allow NULL values. If the table contains data, the ALTER script will not work. To avoid this issue, you must add a default value to the column or mark it as allowing NULL values.

The column [sCommunication].[tQuery].[OrgGroupId] on table [sCommunication].[tQuery] must be added, but the column has no default value and does not allow NULL values. If the table contains data, the ALTER script will not work. To avoid this issue, you must add a default value to the column or mark it as allowing NULL values.
*/
GO
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;

SET XACT_ABORT ON;

BEGIN TRANSACTION;

CREATE TABLE [sCommunication].[tmp_ms_xx_tQuery] (
    [OrgGroupId]      SMALLINT       NOT NULL,
    [OrgGroupBatchId] INT            NOT NULL,
    [QueryCategoryId] INT            NOT NULL,
    [Id]              BIGINT         NOT NULL,
    [Title]           NVARCHAR (100) NOT NULL,
    [Remark]          NVARCHAR (200) NOT NULL,
    [IsUserView]      BIT            NOT NULL,
    [IsAssigneeView]  BIT            NOT NULL,
    [StatusId]        TINYINT        NOT NULL,
    [CreatedUserId]   BIGINT         NOT NULL,
    [CreatedDateTime] DATETIME       NOT NULL
);

IF EXISTS (SELECT TOP 1 1
           FROM   [sCommunication].[tQuery])
    BEGIN
        INSERT INTO [sCommunication].[tmp_ms_xx_tQuery] ([QueryCategoryId], [Id], [Title], [Remark], [IsUserView], [IsAssigneeView], [StatusId], [CreatedUserId], [CreatedDateTime])
        SELECT [QueryCategoryId],
               [Id],
               [Title],
               [Remark],
               [IsUserView],
               [IsAssigneeView],
               [StatusId],
               [CreatedUserId],
               [CreatedDateTime]
        FROM   [sCommunication].[tQuery];
    END

DROP TABLE [sCommunication].[tQuery];

EXECUTE sp_rename N'[sCommunication].[tmp_ms_xx_tQuery]', N'tQuery';

COMMIT TRANSACTION;

SET TRANSACTION ISOLATION LEVEL READ COMMITTED;


GO
PRINT N'Starting rebuilding table [sCommunication].[tQueryCategoryMaster]...';


GO
/*
The column [sCommunication].[tQueryCategoryMaster].[InchargeEmployeeId] is being dropped, data loss could occur.

The column [sCommunication].[tQueryCategoryMaster].[InchargeRoleId] is being dropped, data loss could occur.

The column [sCommunication].[tQueryCategoryMaster].[OrgId] is being dropped, data loss could occur.

The column [sCommunication].[tQueryCategoryMaster].[OrgGroupId] on table [sCommunication].[tQueryCategoryMaster] must be added, but the column has no default value and does not allow NULL values. If the table contains data, the ALTER script will not work. To avoid this issue, you must add a default value to the column or mark it as allowing NULL values.
*/
GO
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;

SET XACT_ABORT ON;

BEGIN TRANSACTION;

CREATE TABLE [sCommunication].[tmp_ms_xx_tQueryCategoryMaster] (
    [Id]              INT            NOT NULL,
    [Title]           NVARCHAR (100) NOT NULL,
    [Remark]          NVARCHAR (200) NOT NULL,
    [OrgGroupId]      SMALLINT       NOT NULL,
    [IsObsolete]      BIT            NOT NULL,
    [CreatedUserId]   BIGINT         NOT NULL,
    [CreatedDateTime] DATETIME       NOT NULL,
    [UpdatedUserId]   BIGINT         NULL,
    [UpdatedDateTime] DATETIME       NULL
);

IF EXISTS (SELECT TOP 1 1
           FROM   [sCommunication].[tQueryCategoryMaster])
    BEGIN
        INSERT INTO [sCommunication].[tmp_ms_xx_tQueryCategoryMaster] ([Id], [Title], [Remark], [IsObsolete], [CreatedUserId], [CreatedDateTime], [UpdatedUserId], [UpdatedDateTime])
        SELECT [Id],
               [Title],
               [Remark],
               [IsObsolete],
               [CreatedUserId],
               [CreatedDateTime],
               [UpdatedUserId],
               [UpdatedDateTime]
        FROM   [sCommunication].[tQueryCategoryMaster];
    END

DROP TABLE [sCommunication].[tQueryCategoryMaster];

EXECUTE sp_rename N'[sCommunication].[tmp_ms_xx_tQueryCategoryMaster]', N'tQueryCategoryMaster';

COMMIT TRANSACTION;

SET TRANSACTION ISOLATION LEVEL READ COMMITTED;


GO
PRINT N'Altering [sEExam].[tTestMaster]...';


GO
ALTER TABLE [sEExam].[tTestMaster]
    ADD [IsTestLock]   BIT NULL,
        [TestQuestion] INT NULL;


GO
PRINT N'Starting rebuilding table [sEExam].[tTestParticipant]...';


GO
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;

SET XACT_ABORT ON;

BEGIN TRANSACTION;

CREATE TABLE [sEExam].[tmp_ms_xx_tTestParticipant] (
    [TestId]                INT            NOT NULL,
    [SourceTypeId]          SMALLINT       NULL,
    [SourceId]              BIGINT         NULL,
    [TestDate]              DATE           NULL,
    [StartTime]             TIME (7)       NULL,
    [EndTime]               TIME (7)       NULL,
    [TestStatusId]          SMALLINT       NULL,
    [TotalMarks]            DECIMAL (6, 2) NULL,
    [ScoredMarks]           DECIMAL (6, 2) NULL,
    [TotalQuestions]        INT            NULL,
    [RightQuestions]        INT            NULL,
    [WrongQuestions]        INT            NULL,
    [SkippQuestions]        INT            NULL,
    [NotAttemptedQuestions] INT            NULL,
    [Id]                    BIGINT         NULL
);

IF EXISTS (SELECT TOP 1 1
           FROM   [sEExam].[tTestParticipant])
    BEGIN
        INSERT INTO [sEExam].[tmp_ms_xx_tTestParticipant] ([TestId], [SourceTypeId], [SourceId], [TestDate], [StartTime], [EndTime], [TestStatusId], [TotalMarks], [ScoredMarks], [TotalQuestions], [RightQuestions], [WrongQuestions], [NotAttemptedQuestions], [Id])
        SELECT [TestId],
               [SourceTypeId],
               [SourceId],
               [TestDate],
               [StartTime],
               [EndTime],
               [TestStatusId],
               [TotalMarks],
               [ScoredMarks],
               [TotalQuestions],
               [RightQuestions],
               [WrongQuestions],
               [NotAttemptedQuestions],
               [Id]
        FROM   [sEExam].[tTestParticipant];
    END

DROP TABLE [sEExam].[tTestParticipant];

EXECUTE sp_rename N'[sEExam].[tmp_ms_xx_tTestParticipant]', N'tTestParticipant';

COMMIT TRANSACTION;

SET TRANSACTION ISOLATION LEVEL READ COMMITTED;


GO
PRINT N'Altering [sEExam].[tTestQuestion]...';


GO
ALTER TABLE [sEExam].[tTestQuestion]
    ADD [OrderIndex] INT NULL;


GO
PRINT N'Starting rebuilding table [sFee].[tFeeCustomSearch]...';


GO
/*
The column [sFee].[tFeeCustomSearch].[OrgGroupBatchId] on table [sFee].[tFeeCustomSearch] must be added, but the column has no default value and does not allow NULL values. If the table contains data, the ALTER script will not work. To avoid this issue, you must add a default value to the column or mark it as allowing NULL values.

The column [sFee].[tFeeCustomSearch].[UserId] on table [sFee].[tFeeCustomSearch] must be added, but the column has no default value and does not allow NULL values. If the table contains data, the ALTER script will not work. To avoid this issue, you must add a default value to the column or mark it as allowing NULL values.
*/
GO
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;

SET XACT_ABORT ON;

BEGIN TRANSACTION;

CREATE TABLE [sFee].[tmp_ms_xx_tFeeCustomSearch] (
    [Id]              BIGINT         NOT NULL,
    [Title]           NVARCHAR (50)  NOT NULL,
    [ColumnName]      NVARCHAR (MAX) NOT NULL,
    [OrderBy]         NVARCHAR (MAX) NOT NULL,
    [OrgGroupBatchId] INT            NOT NULL,
    [OrgId]           SMALLINT       NOT NULL,
    [BatchId]         INT            NOT NULL,
    [Code]            NVARCHAR (20)  NOT NULL,
    [FirstName]       NVARCHAR (50)  NOT NULL,
    [LastName]        NVARCHAR (50)  NOT NULL,
    [DivisionId]      NVARCHAR (MAX) NOT NULL,
    [ReceiptBookId]   NVARCHAR (MAX) NOT NULL,
    [FromReceiptDate] DATE           NOT NULL,
    [ToReceiptDate]   DATE           NOT NULL,
    [FromReceiptNo]   INT            NOT NULL,
    [ToReceiptNo]     INT            NOT NULL,
    [IsObsolete]      BIT            NOT NULL,
    [IsCommon]        BIT            NOT NULL,
    [UserId]          BIGINT         NOT NULL,
    [CreatedUserId]   BIGINT         NOT NULL,
    [CreatedDateTime] DATETIME       NOT NULL,
    [UpdatedUserId]   BIGINT         NULL,
    [UpdatedDateTime] DATETIME       NULL
);

IF EXISTS (SELECT TOP 1 1
           FROM   [sFee].[tFeeCustomSearch])
    BEGIN
        INSERT INTO [sFee].[tmp_ms_xx_tFeeCustomSearch] ([Id], [Title], [ColumnName], [OrderBy], [OrgId], [BatchId], [Code], [FirstName], [LastName], [DivisionId], [ReceiptBookId], [FromReceiptDate], [ToReceiptDate], [FromReceiptNo], [ToReceiptNo], [IsObsolete], [IsCommon], [CreatedUserId], [CreatedDateTime], [UpdatedUserId], [UpdatedDateTime])
        SELECT [Id],
               [Title],
               [ColumnName],
               [OrderBy],
               [OrgId],
               [BatchId],
               [Code],
               [FirstName],
               [LastName],
               [DivisionId],
               [ReceiptBookId],
               [FromReceiptDate],
               [ToReceiptDate],
               [FromReceiptNo],
               [ToReceiptNo],
               [IsObsolete],
               [IsCommon],
               [CreatedUserId],
               [CreatedDateTime],
               [UpdatedUserId],
               [UpdatedDateTime]
        FROM   [sFee].[tFeeCustomSearch];
    END

DROP TABLE [sFee].[tFeeCustomSearch];

EXECUTE sp_rename N'[sFee].[tmp_ms_xx_tFeeCustomSearch]', N'tFeeCustomSearch';

COMMIT TRANSACTION;

SET TRANSACTION ISOLATION LEVEL READ COMMITTED;


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


GO
ALTER TABLE [sFee].[tReceiptBookMaster]
    ADD [Remark1] NVARCHAR (200) NULL,
        [Remark2] NVARCHAR (200) NULL;


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


GO
ALTER TABLE [sHrm].[tEmployeeCustomSearch] DROP COLUMN [EmployeeJobTitleId];


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


GO
ALTER TABLE [sHrm].[tEmployeeTypeMaster] ALTER COLUMN [OrgId] SMALLINT NULL;


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


GO
ALTER TABLE [sHrm].[tLeave] ALTER COLUMN [NoOfLeave] DECIMAL (5, 2) NOT NULL;


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


GO
ALTER TABLE [sLibrary].[tBookMaster] ALTER COLUMN [LibraryId] INT NOT NULL;


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


GO
ALTER TABLE [sSetup].[tOrganizationMaster]
    ADD [EmployeeId] BIGINT NULL,
        [OrderIndex] INT    NULL;


GO
PRINT N'Altering [sTransport].[tAssignRoute]...';


GO
ALTER TABLE [sTransport].[tAssignRoute]
    ADD [DropDestinationId] INT NULL;


GO
PRINT N'Starting rebuilding table [sTransport].[tBusRouteMaster]...';


GO
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;

SET XACT_ABORT ON;

BEGIN TRANSACTION;

CREATE TABLE [sTransport].[tmp_ms_xx_tBusRouteMaster] (
    [Id]                INT            NOT NULL,
    [Title]             NVARCHAR (100) NOT NULL,
    [Remark]            NVARCHAR (100) NULL,
    [DriverName]        NVARCHAR (50)  NULL,
    [DriverMobileNo]    NVARCHAR (20)  NULL,
    [ConductorName]     NVARCHAR (50)  NULL,
    [ConductorMobileNo] NVARCHAR (20)  NULL,
    [VehicleId]         INT            NULL,
    [OrderIndex]        SMALLINT       NOT NULL,
    [IsObsolete]        BIT            NOT NULL,
    [CreatedUserId]     BIGINT         NOT NULL,
    [CreatedDateTime]   DATETIME       NOT NULL,
    [UpdatedUserId]     BIGINT         NULL,
    [UpdatedDateTime]   DATETIME       NULL,
    [OrgGroupBatchId]   INT            NOT NULL,
    [OrgGroupId]        INT            NULL
);

IF EXISTS (SELECT TOP 1 1
           FROM   [sTransport].[tBusRouteMaster])
    BEGIN
        INSERT INTO [sTransport].[tmp_ms_xx_tBusRouteMaster] ([Id], [Title], [Remark], [VehicleId], [OrderIndex], [IsObsolete], [CreatedUserId], [CreatedDateTime], [UpdatedUserId], [UpdatedDateTime], [OrgGroupBatchId], [OrgGroupId])
        SELECT [Id],
               [Title],
               [Remark],
               [VehicleId],
               [OrderIndex],
               [IsObsolete],
               [CreatedUserId],
               [CreatedDateTime],
               [UpdatedUserId],
               [UpdatedDateTime],
               [OrgGroupBatchId],
               [OrgGroupId]
        FROM   [sTransport].[tBusRouteMaster];
    END

DROP TABLE [sTransport].[tBusRouteMaster];

EXECUTE sp_rename N'[sTransport].[tmp_ms_xx_tBusRouteMaster]', N'tBusRouteMaster';

COMMIT TRANSACTION;

SET TRANSACTION ISOLATION LEVEL READ COMMITTED;


GO
PRINT N'Creating [sBiometric].[tDeviceMaster]...';


GO
CREATE TABLE [sBiometric].[tDeviceMaster] (
    [DeviceId]                     INT          NULL,
    [DeviceCode]                   VARCHAR (50) NULL,
    [DeviceIP]                     VARCHAR (50) NULL,
    [DevicePort]                   BIGINT       NULL,
    [DevicePassword]               VARCHAR (50) NULL,
    [DeviceName]                   VARCHAR (50) NULL,
    [Mode]                         VARCHAR (50) NULL,
    [OrgGroupId]                   INT          NULL,
    [DeviceLastAccessTime]         DATETIME     NULL,
    [DeviceLastDownloadRecordTime] DATETIME     NULL,
    [CreatedUserId]                BIGINT       NOT NULL,
    [CreatedDateTime]              DATETIME     NOT NULL,
    [UpdatedUserId]                BIGINT       NULL,
    [UpdatedDateTime]              DATETIME     NULL
);


GO
PRINT N'Creating [sBiometric].[tHolidayMaster]...';


GO
CREATE TABLE [sBiometric].[tHolidayMaster] (
    [Id]              INT          NULL,
    [HolidayName]     VARCHAR (50) NULL,
    [HolidayFromDate] DATETIME     NULL,
    [HolidayToDate]   DATETIME     NULL,
    [OrgGroupId]      INT          NULL,
    [OrgId]           INT          NULL,
    [CreatedUserId]   BIGINT       NOT NULL,
    [CreatedDateTime] DATETIME     NOT NULL,
    [UpdatedUserId]   BIGINT       NULL,
    [UpdatedDateTime] DATETIME     NULL
);


GO
PRINT N'Creating [sBiometric].[tScheduleMaster]...';


GO
CREATE TABLE [sBiometric].[tScheduleMaster] (
    [Id]                   INT           NOT NULL,
    [SchedulerName]        NVARCHAR (50) NOT NULL,
    [Durat_SDate]          DATETIME      NULL,
    [Durat_EDate]          DATETIME      NULL,
    [DFrq_OccursEry_Times] INT           NULL,
    [DFrq_OccursEry_Type]  NVARCHAR (50) NULL,
    [CreatedUserId]        BIGINT        NOT NULL,
    [CreatedDateTime]      DATETIME      NOT NULL,
    [UpdatedUserId]        BIGINT        NULL,
    [UpdatedDateTime]      DATETIME      NULL
);


GO
PRINT N'Creating PK_tScheduleMaster...';


GO
ALTER TABLE [sBiometric].[tScheduleMaster]
    ADD CONSTRAINT [PK_tScheduleMaster] 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 [sBiometric].[tShiftAllocation]...';


GO
CREATE TABLE [sBiometric].[tShiftAllocation] (
    [PunchId]         NVARCHAR (50) NULL,
    [ShiftId]         INT           NULL,
    [ShiftDay]        TINYINT       NULL,
    [FromShiftDate]   DATETIME      NULL,
    [ToShiftDate]     DATETIME      NULL,
    [CreatedUserId]   BIGINT        NOT NULL,
    [CreatedDateTime] DATETIME      NOT NULL,
    [UpdatedUserId]   BIGINT        NULL,
    [UpdatedDateTime] DATETIME      NULL
);


GO
PRINT N'Creating [sBiometric].[tShiftMaster]...';


GO
CREATE TABLE [sBiometric].[tShiftMaster] (
    [ShiftId]         INT          NULL,
    [ShiftName]       VARCHAR (50) NULL,
    [StartTime]       DATETIME     NULL,
    [EndTime]         DATETIME     NULL,
    [GraceBefore]     INT          NULL,
    [GraceAfter]      INT          NULL,
    [ShiftDur]        VARCHAR (50) NULL,
    [MinHrsHalfDay]   TEXT         NULL,
    [MinHrsFullDay]   TEXT         NULL,
    [AlertAfter]      INT          NULL,
    [OrgGroupId]      INT          NULL,
    [CreatedUserId]   BIGINT       NOT NULL,
    [CreatedDateTime] DATETIME     NOT NULL,
    [UpdatedUserId]   BIGINT       NULL,
    [UpdatedDateTime] DATETIME     NULL
);


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


GO
CREATE TABLE [sCommon].[tReportTypeMaster] (
    [Id]         SMALLINT       NOT NULL,
    [Code]       NVARCHAR (10)  NOT NULL,
    [Title]      NVARCHAR (100) NOT NULL,
    [IsObsolete] BIT            NOT NULL
);


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


GO
CREATE TABLE [sCommon].[tSurnameMaster] (
    [Id]              INT            NOT NULL,
    [Surname]         NVARCHAR (100) NULL,
    [ReligionId]      NVARCHAR (100) NULL,
    [FamiliyCast]     NVARCHAR (100) NULL,
    [FamiliySubCast]  NVARCHAR (100) NULL,
    [CastCategoryId]  SMALLINT       NULL,
    [IsObsolete]      BIT            NOT NULL,
    [CreatedUserId]   BIGINT         NOT NULL,
    [CreatedDateTime] DATETIME       NOT NULL,
    [UpdatedUserId]   BIGINT         NULL,
    [UpdatedDateTime] DATETIME       NULL,
    [OrgGroupId]      SMALLINT       NOT NULL
);


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


GO
CREATE TABLE [sCommunication].[tPhotoCategoryOrg] (
    [OrgId]           SMALLINT NOT NULL,
    [PhotoCategoryId] INT      NOT NULL
);


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


GO
CREATE TABLE [sCommunication].[tQueryCategoryAssignedTo] (
    [SourceTypeId]    SMALLINT NOT NULL,
    [SourceId]        BIGINT   NOT NULL,
    [QueryCategoryId] INT      NOT NULL
);


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


GO
CREATE TABLE [sCommunication].[tQueryCategoryOrg] (
    [OrgId]           INT NOT NULL,
    [QueryCategoryId] INT NOT NULL
);


GO
PRINT N'Creating [sLibrary].[tBookLocationMaster]...';


GO
CREATE TABLE [sLibrary].[tBookLocationMaster] (
    [LibraryId]       INT            NOT NULL,
    [Id]              INT            NOT NULL,
    [Code]            NVARCHAR (20)  NOT NULL,
    [Title]           NVARCHAR (100) NOT NULL,
    [IsObsolete]      BIT            NOT NULL,
    [CreatedUserId]   BIGINT         NOT NULL,
    [CreatedDateTime] DATETIME       NOT NULL,
    [UpdatedUserId]   BIGINT         NULL,
    [UpdatedDateTime] DATETIME       NULL
);


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


GO
CREATE TABLE [sStudent].[tAcademicDetail] (
    [AcademicId] BIGINT        NOT NULL,
    [ExamSeatNo] NVARCHAR (20) NULL
);


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


GO




ALTER PROCEDURE [sAccounting].[pAccountingYearMasterAdd]
	 
	@rId int,
	@rCode nvarchar(20),
	@rTitle nvarchar(100),
	@rFromDate date,
	@rToDate date,
	@rCreatedUserId bigint,
	@rUpdatedUserId bigint,
	@rOrgGroupId int,
	@rAccountId int 
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	BEGIN TRANSACTION	
	
	CREATE TABLE #TempLedgerGroupMaster
	(
		Id bigint identity,	 
	    LedgerGroupName nvarchar(100),
	    LedgerId int,
	    LedgerGroupId int
	)
	
 IF(@rId = 0)	
BEGIN
	IF Exists(select Id from sAccounting.tAccountingYearMaster where (Title=@rTitle AND AccountId = @rAccountId) OR Code = @rCode)
			BEGIN
			select -103 as Result
			RETURN
		END 
    
	DECLARE @lNextNumber INT     
	DECLARE @1CurruntAccountingYearId INT
	DECLARE @1MaxLedgerGroupId INT	
	DECLARE @1MaxLedgerId int 
	DECLARE @1Count int
	DECLARE @1LedgerGroupId int
	DECLARE @1LedgerGroupName nvarchar(200)
	DECLARE @1LedgerId int
	
	Select @1CurruntAccountingYearId = MAX(Id) from sAccounting.tAccountingYearMaster Where OrgGroupId = @rOrgGroupId
	
	IF NOT Exists (select 1 from sAccounting.tLedgerGroupMaster where AccountingYearId = @1CurruntAccountingYearId)	
	BEGIN
		SET @1CurruntAccountingYearId = 1
	  --SELECT @1MaxLedgerGroupId = MAX(Id)  from sAccounting.tLedgerGroupMaster Where AccountingYearId = @1CurruntAccountingYearId 
	  --SELECT @1MaxLedgerId = MAX(Id)  from sAccounting.tLedgerMaster Where AccountingYearId = @1CurruntAccountingYearId 
	END 
	
	   --SELECT @1MaxLedgerGroupId =  sCommon.fGetIntIdForOrg(101,@rOrgGroupId)
	   --SELECT @1MaxLedgerId = sCommon.fGetIntIdForOrg(101,@rOrgGroupId) 
	   
 
	
	
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sAccounting.tAccountingYearMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	--EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sAccounting.tAccountingYearMaster',@lNextNumber = @lNextNumber output
 
	INSERT INTO sAccounting.tAccountingYearMaster
		(
			Id,
			Code,
			Title,
			FromDate,
			ToDate,
			CreatedUserId,
			CreatedDateTime,
			AccountId,
			OrgGroupId
		)
	VALUES
		(
			@lNextNumber,
			@rCode,
			@rTitle,
			@rFromDate,
			@rToDate,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rAccountId,
			@rOrgGroupId
		) 
		INSERT INTO sAccounting.tLedgerGroupMaster
		SELECT  CASE WHEN  @1CurruntAccountingYearId = 1 then sCommon.fGetIntIdForOrg(Id,@rOrgGroupId)
		ELSE Id END ,Code,Title,IsObsolete,LedgerMainGroupId,@lNextNumber,
		@rCreatedUserId,sCommon.fGetDate(),@rCreatedUserId,sCommon.fGetDate(),@rAccountId,@rOrgGroupId		
		from sAccounting.tLedgerGroupMaster  where AccountingYearId = @1CurruntAccountingYearId
		--SELECT @1MaxLedgerGroupId = MAX(Id)  from sAccounting.tLedgerGroupMaster Where AccountingYearId = @lNextNumber
				  
		INSERT INTO #TempLedgerGroupMaster
		SELECT LGM.Title,l.Id,LedgerGroupId AS LedgerGroup FROM sAccounting.tLedgerMaster l 
		INNER JOIN sAccounting.tLedgerGroupMaster LGM 
		ON LGM.Id = l.LedgerGroupId  AND lgm.AccountingYearId = @1CurruntAccountingYearId
		WHERE l.AccountingYearId = @1CurruntAccountingYearId order by l.Id DESC
				 
		SELECT @1Count = COUNT(*) FROM #TempLedgerGroupMaster
		
		WHILE(@1Count > 0)
		 BEGIN		   		   
		   SELECT @1LedgerGroupName = LedgerGroupName,@1LedgerId = LedgerId  FROM #TempLedgerGroupMaster WHere Id = @1Count
		   SELECT @1LedgerGroupId = Id FROM sAccounting.tLedgerGroupMaster WHERE Title = @1LedgerGroupName AND AccountingYearId = @lNextNumber
		   	
		   INSERT INTO sAccounting.tLedgerMaster
		   SELECT CASE WHEN  @1CurruntAccountingYearId = 1 then sCommon.fGetIntIdForOrg(Id,@rOrgGroupId) ELSE Id END 
		   --@1MaxLedgerId + ROW_NUMBER() over(Order by Id asc)
		   ,Code,Title,IsObsolete,
		   @1LedgerGroupId,
		   0.00,LedgerTypeId,
		   @lNextNumber,@rCreatedUserId,sCommon.fGetDate(),@rCreatedUserId,sCommon.fGetDate(),@rOrgGroupId 
		   FROM sAccounting.tLedgerMaster 
		   WHERE AccountingYearId = @1CurruntAccountingYearId	 AND Id = @1LedgerId		   
		   SET @1Count = @1Count - 1;		    
		 END
		 		 
		SELECT 1 AS RESULT            
		
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE sAccounting.tAccountingYearMaster
	    SET
			  Code=@rCode,
			  Title=@rTitle,
			  FromDate=@rFromDate,
			  AccountId = @rAccountId,
			  ToDate=@rToDate,
			  UpdatedUserId=@rUpdatedUserId,
			  UpdatedDateTime= sCommon.fGetDate() 
	      
	      WHERE Id = @rId 	   
	 END  
		  SELECT @lNextNumber AS Result
	
		  COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sAccounting].[pBalanceSheet]...';


GO
ALTER PROCEDURE [sAccounting].[pBalanceSheet]

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

BEGIN

  --SELECT '' AS Builder1,
	 --    '' AS Builder2,
  --       '' AS IncomeGroup,
	 --    '' AS IncomeLedger,
	 --    '' AS Income,
	 --    '' AS ClosingBalance,
	 --    '' AS ExpenseGroup,
	 --    '' AS ExpenseLedger,
	 --    '' AS Expense,
	 --    '' AS OpeningBalance

Declare @lLedgerId int 
Declare @lOpeningBalance Decimal (12,2)
Declare @ltIncome Decimal (12,2)
Declare @ltExpense Decimal (12,2)
Declare @lInIncome Decimal(12,2)
Declare @lInClosing Decimal(12,2)
Declare @lExOpening Decimal(12,2)
Declare @lExExpense Decimal(12,2)
Declare @lGrossProfit Decimal(12,2)
Declare @lGrossLoss Decimal(12,2)
Declare @lCount int
Declare @lLedgerName Nvarchar(150)
Declare @lLedgerGroupName Nvarchar(150)
Declare @lLedgerMainGroupName Nvarchar(150)
DECLARE @1ExpenceCount int
DECLARE @1IncomeCount int

	
        CREATE TABLE #tempUpdateClosingBalance
 		(	Id INT IDENTITY (1, 1),
 			LedgerId int,
 			Temp_Op_Balance decimal(12,2),
 			Closing_Balance decimal(12,2),
 		    Transaction_Balance decimal(12,2)
 		)
 		  	
 		INSERT INTO #tempUpdateClosingBalance (LedgerId,Temp_Op_Balance,Closing_Balance,Transaction_Balance)
		EXEC [sAccounting].[pUpdateClosingBalance] @rStartDate,@rEndDate,@rOrgGroupId,@rAccountingYearId,'',''
				
		CREATE TABLE #TempExpenseGroup
		(
		   Id INT IDENTITY(1,1),
		   ExpenseGroup nvarchar(200),
		   ExpenseLedger nvarchar(200),
		   Expense decimal(22,2),
		   OpeningBalance decimal(22,2)		 
		)
		
		CREATE TABLE #TempIncomeGroup
		(
		   Id INT IDENTITY(1,1),
		   IncomeGroup nvarchar(200),
		   IncomeLedger nvarchar(200),
		   Income decimal(22,2),
		   ClosingBalance decimal		 
		)
		
		INSERT INTO #TempIncomeGroup
		SELECT 
		ISNULL(LG.Title,'') AS ExpenseGroup,
		ISNULL(L.Title,'') AS ExpenseLedger,	
		ISNULL(SUM(UC.Closing_Balance),0) AS Expense,
	    ISNULL(SUM(L.OpeningBalance),0) AS OpeningBalance
	    
	    FROM sAccounting.tLedgerMaster L
		INNER JOIN sAccounting.tLedgerGroupMaster LG ON L.LedgerGroupId = LG.Id
		INNER JOIN sAccounting.tLedgerMainGroupMaster LMG ON LG.LedgerMainGroupId = LMG.Id
		INNER JOIN #tempUpdateClosingBalance UC ON L.Id=UC.LedgerId
		WHERE LMG.ID  = 2 AND L.AccountingYearId = @rAccountingYearId AND LG.AccountingYearId = @rAccountingYearId
		GROUP BY LG.Title,LMG.ID,L.Title	
		Order By LMG.Id	
		
		
		INSERT INTO #TempExpenseGroup
        SELECT  		
		ISNULL(LG.Title,'') AS IncomeGroup,
		ISNULL(L.Title,'') AS IncomeLedger,
		ISNULL(SUM(UC.Closing_Balance),0) AS Income,
		ISNULL(SUM(UC.Closing_Balance),0) AS ClosingBalance
		FROM sAccounting.tLedgerMaster L 
		INNER JOIN sAccounting.tLedgerGroupMaster LG ON L.LedgerGroupId = LG.Id
		INNER JOIN sAccounting.tLedgerMainGroupMaster LMG ON LG.LedgerMainGroupId = LMG.Id
		INNER JOIN #tempUpdateClosingBalance UC ON L.Id=UC.LedgerId
		WHERE LMG.ID = 1 AND L.AccountingYearId = @rAccountingYearId AND LG.AccountingYearId = @rAccountingYearId
		GROUP BY LG.Title,LMG.ID,L.Title	
		Order By LMG.Id	
		
	     
	   SELECT @1ExpenceCount = count(Id) From #TempExpenseGroup
	   SELECT @1IncomeCount = Count(Id) From #TempIncomeGroup
	   
	   
		
	   If(@1InComeCount > @1ExpenceCount)
	     BEGIN	          
	           SELECT 
	             @rBuilder1 AS Builder1
				,@rBuilder2 AS Builder2, 
	               IncomeGroup, 
	               IncomeLedger,
	               ClosingBalance,
	               Income,
	               ISNULL(ExpenseGroup,'') AS ExpenseGroup,
	               ISNULL(ExpenseLedger,'') AS ExpenseLedger,
				   ISNULL(OpeningBalance,0) AS OpeningBalance,	          
				   ISNULL(Expense,0.00) AS Expense
	           FROM #TempIncomeGroup IG LEFT JOIN #TempExpenseGroup EG ON EG.Id = IG.Id	         
	     END
	     ELSE
	     BEGIN
	         SELECT 
					 @rBuilder1 AS Builder1
					,@rBuilder2 AS Builder2, 
	               ISNULL(IncomeGroup,'') AS IncomeGroup, 
	               ISNULL(IncomeLedger,'') AS IncomeLedger,
	               ISNULL(ClosingBalance,0) AS ClosingBalance,
	               ISNULL(Income,0) AS Income,
	               ExpenseGroup AS ExpenseGroup,
	               ExpenseLedger,
				   OpeningBalance,
				   Expense       
	           FROM  #TempExpenseGroup EG   LEFT JOIN #TempIncomeGroup IG ON EG.Id = IG.Id		        
	     END	
	     
	     DROP TABLE #TempExpenseGroup
	     DROP TABLE #TempIncomeGroup
		
		
		
--SELECT  
		
--		ISNULL(CASE WHEN LMG.ID=2 THEN LG.Title END,'') AS IncomeGroup,
--		ISNULL(CASE WHEN LMG.ID=2 THEN L.Title END,'') AS IncomeLedger,
--		ISNULL(SUM(L.OpeningBalance),0) AS OpeningBalance,
--		ISNULL(CASE WHEN LMG.ID=2 THEN SUM(UC.Closing_Balance) END,0) AS Income,
--		ISNULL(CASE WHEN LMG.ID=1  THEN LG.Title END,'') AS ExpenseGroup,
--		ISNULL(CASE WHEN LMG.ID=1  THEN L.Title END,'') AS ExpenseLedger,
--		ISNULL(CASE WHEN LMG.ID=1 THEN SUM(UC.Closing_Balance) END,0) AS Expense,
--		ISNULL(SUM(UC.Closing_Balance),0) AS ClosingBalance
--		FROM sAccounting.tLedgerMaster L 
--		INNER JOIN #tempUpdateClosingBalance UC ON L.Id=UC.LedgerId
--		INNER JOIN sAccounting.tLedgerGroupMaster LG ON L.LedgerGroupId = LG.Id 
--		INNER JOIN sAccounting.tLedgerMainGroupMaster LMG ON LG.LedgerMainGroupId = LMG.Id AND LMG.Id in (1,2)		
--		GROUP BY LG.Title,LMG.ID
--		,L.Title	
--		Order By LMG.Id	
END
GO
PRINT N'Altering [sAccounting].[pCashBankBook]...';


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

BEGIN



Declare @LedgerId int 
Declare @LOpeningBalance Decimal (12,2)
Declare @OpeningBalance Decimal (12,2)
Declare @lClOsingBalance Decimal (12,2)
Declare @CreditBalance Decimal (12,2)
Declare @DebitBalance Decimal (12,2)
Declare @lCount int
Declare @lLedgerTypeId int
Declare @LedgerName Nvarchar(150)
Declare @LedgerGroupId int
	
	
	--EXEC [sAccounting].[pUpdateClosingBalance] @rStartDate,@rEndDate,@rOrgGroupId,@rAccountingYearId,@rLedgerId,@rLedgerMainGroupId,@rISProfitLoss
  
   CREATE TABLE #tempUpdateClosingBalance
	(	
	    Id INT IDENTITY (1, 1),
		LedgerId int,
		Temp_Op_Balance decimal(12,2),
		Closing_Balance decimal(12,2),
		Transaction_Balance decimal(12,2)
	) 
 	
	CREATE TABLE #tCashBankBookTemp
 		(	Id INT IDENTITY (1, 1),
 			LedgerId int,
 			LedgerName nvarchar(150),
 			OpBalance Decimal(12,2),
 			CrBalance Decimal(12,2),
 			DrBalance Decimal(12,2),
 			ClBalance Decimal(12,2),
 			LedgerGroupId int
 		) 
	
	CREATE TABLE #tCashBankBook
 		(	Id INT IDENTITY (1, 1),
 			LedgerId int,
 			LedgerName nvarchar(150),
 			OpBalance Decimal(12,2),
 			LedgerTypeId int,
 			LedgerGroupId int
 		) 
 	INSERT INTO #tCashBankBook
	select L.Id,L.Title,L.OpeningBalance,LedgerTypeId,L.LedgerGroupId from sAccounting.tLedgerMaster L INNER JOIN 
	sAccounting.tLedgerGroupMaster LG ON L.LedgerGroupId = LG.Id
	where (LedgerMainGroupId=@rLedgerMainGroupId OR @rLedgerMainGroupId = 0)
	AND (L.ID = @rLedgerId or @rLedgerId =0)
	AND LG.OrgGroupId = @rOrgGroupId and L.AccountingYearId = @rAccountingYearId AND LG.AccountingYearId = @rAccountingYearId
	AND (L.LedgerGroupId = @rLedgerGroupId OR @rLedgerGroupId=0)
	ORDER BY L.Id Asc
	
	
	SELECT @lCount =  COUNT(Id) FROM #tCashBankBook
	WHILE (@lCount > 0)
	BEGIN		
		SELECT @LedgerId =LedgerId,@LedgerName= LedgerName,@OpeningBalance=ISNULL(OpBalance,0),@LedgerGroupId = LedgerGroupId, 
		@lLedgerTypeId=LedgerTypeId FROM #tCashBankBook WHERE Id = @lCount				
		
		-- Update Closing Balance
		INSERT INTO #tempUpdateClosingBalance (LedgerId,Temp_Op_Balance,Closing_Balance,Transaction_Balance)
		EXEC [sAccounting].[pUpdateClosingBalance] @rStartDate,@rEndDate,@rOrgGroupId,@rAccountingYearId,@LedgerId,''

		 SELECT @LOpeningBalance=ISNULL(Sum(TD.Amount) ,0)
		 FROM  sAccounting.tTransaction T INNER JOIN sAccounting.tTransactionDetail TD
		 ON T.Id=TD.TransactionId And TD.LedgerId=@LedgerId
			AND T.AccountingYearId = @rAccountingYearId 
			AND T.TransactionDate < @rStartDate


		 SELECT @CreditBalance= -1 * ISNULL(Sum(TD.Amount) ,0)
		 FROM  sAccounting.tTransaction T INNER JOIN sAccounting.tTransactionDetail TD
		 ON T.Id=TD.TransactionId 		 
			AND T.AccountingYearId = @rAccountingYearId 
			AND T.TransactionDate >= @rStartDate AND T.TransactionDate <= @rEndDate
			AND TD.TransactionTypeId = 1 And TD.LedgerId=@LedgerId

		 SELECT @DebitBalance=  ISNULL(Sum(TD.Amount) ,0)
		 FROM  sAccounting.tTransaction T INNER JOIN sAccounting.tTransactionDetail TD
		 ON T.Id=TD.TransactionId 
		 --INNER JOIN sAccounting.tLedgerMaster L ON L.ID = TD.LedgerId
			AND T.AccountingYearId = @rAccountingYearId 
			AND T.TransactionDate >= @rStartDate AND T.TransactionDate <= @rEndDate
			AND TD.TransactionTypeId = 2 And TD.LedgerId=@LedgerId

			SET @LOpeningBalance = @LOpeningBalance  +  @OpeningBalance          
			
			SELECT  @lClOsingBalance = Closing_Balance FROM #tempUpdateClosingBalance WHERE LedgerId=@LedgerId
			
			--IF @lLedgerTypeId =1 
			--	BEGIN
			--		SET @lClOsingBalance = @LOpeningBalance  + @DebitBalance - @CreditBalance
			--	END
			--ELSE
			--	BEGIN
			--		SET @lClOsingBalance = @LOpeningBalance  - @DebitBalance + @CreditBalance
			--	END
							
			INSERT INTO #tCashBankBookTemp  (LedgerId,LedgerName,OpBalance,CrBalance,DrBalance,ClBalance,LedgerGroupId)
			VALUES 	(@LedgerId,@LedgerName,@LOpeningBalance,@CreditBalance,@DebitBalance,@lClOsingBalance,@LedgerGroupId)
			
			--Select * from #tCashBankBookTemp
			
			SET @lCount = @lCount - 1
		END	
	SELECT @rBuilder1 AS Builder1
		  ,@rBuilder2 AS Builder2,Id,LedgerId,LedgerName,OpBalance,CrBalance,DrBalance,ClBalance,LedgerGroupId FROM #tCashBankBookTemp	
	DROP TABLE #tCashBankBook
	DROP TABLE #tCashBankBookTemp
	
	
	 
	
END
GO
PRINT N'Altering [sAccounting].[pDayBook]...';


GO
ALTER PROCEDURE [sAccounting].[pDayBook]

	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='', 
	@rStartDate Date,
	@rEndDate Date,
	@rOrgGroupId int = 0,
	@rAccountingYearId [int],
	@rLedgerId [int]
	

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN  
   
    DECLARE @1OpeningBalance DECIMAL(22,2)
    DECLARE @1ClosingBalance DECIMAl(22,2)
   
   IF(@rLedgerId > 0)
    BEGIN   
    
    CREATE TABLE #tempUpdateClosingBalance
	(	
	    Id INT IDENTITY (1, 1),
		LedgerId int,
		Temp_Op_Balance decimal(12,2),
		Closing_Balance decimal(12,2),
		Transaction_Balance decimal(12,2)
	) 
	
	INSERT INTO #tempUpdateClosingBalance (LedgerId,Temp_Op_Balance,Closing_Balance,Transaction_Balance)
		EXEC [sAccounting].[pUpdateClosingBalance] @rStartDate,@rEndDate,@rOrgGroupId,@rAccountingYearId,@rLedgerId,''
		
	SELECT @1OpeningBalance = Temp_Op_Balance,@1ClosingBalance = Closing_Balance FROM #tempUpdateClosingBalance WHERE LedgerId = @rLedgerId
    
    END
    	

	SELECT 
	@rBuilder1 AS Builder1
	,@rBuilder2 AS Builder2,
	T.Id AS TransactionId,
	T.TransactionDate,
	T.VoucherNumber,
	L.TITLE,
	VTM.Title As VoucherType,
	T.Narration,
	ISNULL(CASE WHEN TD.TransactionTypeId = 1 THEN -1 * ISNULL(SUM(TD.AMOUNT),0) END,0) AS CREDIT,
	ISNULL(CASE WHEN TD.TransactionTypeId = 2 THEN ISNULL(SUM(TD.AMOUNT),0) END,0) AS DEBIT,
	CASE WHEN TD.TransactionTypeId = 1 THEN 'CREDIT' ELSE 'DEBIT' END AS TOBY,
	ISNULL(@1OpeningBalance,0) AS OpeningBalance,
	ISNULL(@1ClosingBalance,0) AS ClosingBalance
	
	from sAccounting.tTransaction T 
	INNER JOIN sAccounting.tTransactionDetail TD ON TD.TransactionId=T.Id 
	INNER JOIN sAccounting.tLedgerMaster L ON L.Id=TD.LedgerId
	INNER JOIN sAccounting.tVoucherTypeMaster VTM ON VTM.Id=T.VoucherTypeId
	INNER JOIN sAccounting.tLedgerGroupMaster LGM ON LGM.Id = L.LedgerGroupId
	
	WHERE (T.TransactionDate >= @rStartDate)  AND
	(T.TransactionDate <= @rEndDate) AND 
	(LGM.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=0) AND
	(LGM.AccountingYearId=@rAccountingYearId or @rAccountingYearId=0) AND	
	(TD.LedgerId =  @rLedgerId  OR @rLedgerId  =0) AND
	T.AccountingYearID=@rAccountingYearId AND
	 L.AccountingYearId = @rAccountingYearId
	
	 
	GROUP BY 	T.TransactionDate,T.VoucherNumber,T.Id,
				TD.TransactionTypeId,L.Title,VTM.Title,T.Narration
END
GO
PRINT N'Altering [sAccounting].[pLedgerBook]...';


GO
ALTER PROCEDURE [sAccounting].[pLedgerBook]
	
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	@rStartDate Date,
	@rEndDate Date,
	@rOrgGroupId int = 0,
	@rAccountingYearId [int],
	@rLedgerId [int],
	@rLedgerGroupId [int]
	

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON 
BEGIN

    --  SELECT '' AS Builder1,
			 --'' AS Builder2,
    --         '' AS TransactionId,
			 --'' AS CREDIT,
			 --'' AS DEBIT,
			 --'' AS LedgerId,
			 --'' AS TransactionDate,
			 --'' AS VoucherNumber,
			 --'' AS Narration,
			 --'' AS VoucherType,
			 --'' AS TITLE,
			 --'' AS OpeningBalance,
			 --'' AS ClosingBalance
      
    
    DECLARE @1OpeningBalance DECIMAL(22,2)
    DECLARE @1ClosingBalance DECIMAl(22,2)
     
	CREATE TABLE #tempUpdateClosingBalance
	(	
	    Id INT IDENTITY (1, 1),
		LedgerId int,
		Temp_Op_Balance decimal(12,2),
		Closing_Balance decimal(12,2),
		Transaction_Balance decimal(12,2)	    
	) 
	
	INSERT INTO #tempUpdateClosingBalance (LedgerId,Temp_Op_Balance,Closing_Balance,Transaction_Balance)
	EXEC [sAccounting].[pUpdateClosingBalance] @rStartDate,@rEndDate,@rOrgGroupId,@rAccountingYearId,@rLedgerId,''
		
	SELECT @1OpeningBalance = Temp_Op_Balance,@1ClosingBalance = Closing_Balance
	FROM #tempUpdateClosingBalance WHERE LedgerId = @rLedgerId

	SELECT 
	 @rBuilder1 AS Builder1
	,@rBuilder2 AS Builder2,
	T.Id AS TransactionId,
	ISNULL(CASE WHEN TD.TransactionTypeId = 1 THEN -1 * SUM(TD.AMOUNT) END,0) AS CREDIT,
	ISNULL(CASE WHEN TD.TransactionTypeId = 2 THEN SUM(TD.AMOUNT) END,0) AS DEBIT,
	TD.LedgerId,T.TransactionDate,T.VoucherNumber,T.Narration,
	VTM.Title As VoucherType,
	T.VoucherTypeId,
	--LEFT(VTM.Title,2) As VoucherType
	L.TITLE,
	ISNULL(@1OpeningBalance,0) AS OpeningBalance,
	ISNULL(@1ClosingBalance,0) AS ClosingBalance
	from sAccounting.tTransaction T 
	INNER JOIN sAccounting.tTransactionDetail TD ON TD.TransactionId=T.Id AND (TD.LedgerId <> @rLedgerId)
	INNER JOIN sAccounting.tLedgerMaster L ON L.Id=TD.LedgerId
	INNER JOIN sAccounting.tVoucherTypeMaster VTM ON VTM.Id=T.VoucherTypeId
	INNER JOIN sAccounting.tLedgerGroupMaster LGM ON LGM.Id = L.LedgerGroupId
	
	WHERE (T.TransactionDate >= @rStartDate)  AND
	(T.TransactionDate <= @rEndDate) AND 
	(LGM.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=0) AND
	(LGM.AccountingYearId=@rAccountingYearId or @rAccountingYearId=0) AND	
	(T.AccountingYearId=@rAccountingYearId OR @rAccountingYearId = 0) AND
	(L.LedgerGroupId = @rLedgerGroupId or @rLedgerGroupId = 0) AND L.AccountingYearId=@rAccountingYearId
	AND @rLedgerId IN (SELECT LedgerId FROM sAccounting.tTransactionDetail TD1 WHERE TD1.TRANSACTIONID=T.ID)

	GROUP BY 	TD.LedgerId,T.TransactionDate,T.VoucherNumber,T.Id,
				TD.TransactionTypeId,L.Title,T.VoucherTypeId,VTM.Title,T.Narration
				
				
   order by T.VoucherTypeId,T.TransactionDate,T.VoucherNumber,Credit,Debit
END
GO
PRINT N'Altering [sAccounting].[pLedgerGroupMasterAdd]...';


GO

ALTER PROCEDURE [sAccounting].[pLedgerGroupMasterAdd]
	 
	@rId int,
	@rCode nvarchar(20),
	@rTitle nvarchar(100),
	@rLedgerMainGroupId int,
	@rAccountingYearId int,
	@rCreatedUserId bigint,
	@rUpdatedUserId bigint,
	@rIsObsolete bit,
	@rOrgGroupId int,
	@rAccountId int	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	 
  SELECT @rAccountId = AccountId FROM sAccounting.tAccountingYearMaster WHERE Id = @rAccountingYearId
  IF(@rId = 0)	
	BEGIN
		If Exists(SELECT 1 FROM sAccounting.tLedgerGroupMaster where (code = @rCode OR Title = @rTitle) AND AccountingYearId = @rAccountingYearId)
			BEGIN
			select -103 as Result
			RETURN
		END 
	 END
	--END
	--ELSE
	--BEGIN
 
	--	If  Exists(select Id from sEExam.tDataSubjectMaster where Code=@rCode AND Id<>@rId)
	--	Begin
	--		select -103 as Result
	--		RETURN
	--	End

	--END
	
	
	
	
	 BEGIN TRANSACTION	
 IF (@rId = 0)	
BEGIN

	DECLARE @lNextNumber INT     
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sAccounting.tLedgerGroupMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
 
	--EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sAccounting.tLedgerGroupMaster',@lNextNumber = @lNextNumber output

	INSERT INTO sAccounting.tLedgerGroupMaster
		(
			Id,
			Code,
			Title,
			LedgerMainGroupId,
			AccountingYearId,
			CreatedUserId,
			CreatedDateTime,
			IsObsolete,
			OrgGroupId,
			AccountId
			
		)
	VALUES
		(
			@lNextNumber,
			@rCode,
			@rTitle,
			@rLedgerMainGroupId,
			@rAccountingYearId,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rIsObsolete,
			@rOrgGroupId,
			@rAccountId
		)
		 SELECT 1 AS RESULT            
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	 UPDATE sAccounting.tLedgerGroupMaster
	    SET
	      --Code=@rCode,
	      --Title=@rTitle,
	      LedgerMainGroupId=@rLedgerMainGroupId,
	      AccountingYearId=@rAccountingYearId,
	      IsObsolete=@rIsObsolete,
	      UpdatedUserId=@rUpdatedUserId,
	      UpdatedDateTime= sCommon.fGetDate()  
	      WHERE Id = @rId 	   
	 END  
		SELECT @lNextNumber AS Result
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sAccounting].[pLedgerMasterAdd]...';


GO

ALTER PROCEDURE [sAccounting].[pLedgerMasterAdd]
	 
	@rId int,
	@rCode nvarchar(100),
	@rTitle nvarchar(100),
	@rLedgerGroupId int,
	@rAccountingYearId int,
	@rCreatedUserId bigint,
	@rUpdatedUserId bigint,
	@rOpeningBalance decimal(12,2),
	@rLedgerTypeId int,
	@rIsObsolete bit,
	@rOrgGroupId int 
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY 
		IF(@rId = 0)	
	BEGIN
		IF Exists(select 1 from sAccounting.tLedgerMaster where Code=@rCode OR Title = @rTitle AND AccountingYearId = @rAccountingYearId)
			BEGIN
			SELECT -103 AS Result
			RETURN
		END  
	END
	--ELSE
	--BEGIN
 
	--	If  Exists(select 1 from sAccounting.tLedgerMaster where Code=@rCode AND Id<>@rId)
	--	Begin
	--		select -103 as Result
	--		RETURN
	--	End

	--END 
	 BEGIN TRANSACTION	
 IF(@rId = 0)	
 BEGIN 
	DECLARE @lNextNumber INT
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sAccounting.tLedgerMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	--EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sAccounting.tLedgerMaster',@lNextNumber = @lNextNumber output

	INSERT INTO sAccounting.tLedgerMaster
		(
			Id,
			Code,
			Title,
			LedgerGroupId,
			AccountingYearId,
			CreatedUserId,
			CreatedDateTime,
			OpeningBalance,
			LedgerTypeId,
		    IsObsolete,
		    OrgGroupId			
		)
	VALUES
		(
			@lNextNumber,
			@rCode,
			@rTitle,
			@rLedgerGroupId,
			@rAccountingYearId,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rOpeningBalance,
			@rLedgerTypeId,
			@rIsObsolete,
			@rOrgGroupId			
		)
		 SELECT 1 AS RESULT            
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE sAccounting.tLedgerMaster
	    SET
	      --Code=@rCode,
	      --Title=@rTitle,
	      LedgerGroupId=@rLedgerGroupId,	    
	      IsObsolete=@rIsObsolete,
	      UpdatedUserId=@rUpdatedUserId,
	      UpdatedDateTime= sCommon.fGetDate(),
	      OpeningBalance=@rOpeningBalance,
	      LedgerTypeId=@rLedgerTypeId 
	      WHERE Id = @rId 	AND AccountingYearId = @rAccountingYearId   
	 END  
		SELECT @lNextNumber AS Result
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sAccounting].[pLedgerMasterGet]...';


GO
 

ALTER PROCEDURE [sAccounting].[pLedgerMasterGet]

     @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rId int = 0,
	 --@rAffiliationId int,
	 @rTitle nvarchar(100),
	 @rCode nvarchar(20),
	 @rLedgerGroupId int,
	 @rAccountingYearId int,
	 @rOrgGroupId int
	 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
      Declare @1AccountId int
      
	  BEGIN
			select @1AccountId = AccountId from sAccounting.tAccountingYearMaster Where Id = @rAccountingYearId
			
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
			SET @rCode = sCommon.fSearchStringGet(@rCode)
	  END
	 
	  SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2, 
		LM.Id,
		LM.Code,
		LM.Title,
		LM.OpeningBalance,
		LM.IsObsolete,
		LGM.Id AS LedgerGroupId,
		LTM.Id AS LedgerTypeId,
		LGM.Title AS LedgerGroupTitle,
		LTM.Title AS LedgerTypeTitle 
	      
	  FROM 
		   sAccounting.tLedgerMaster LM
			INNER JOIN sAccounting.tLedgerTypeMaster LTM
			ON LM.LedgerTypeId= LTM.Id
			 INNER JOIN sAccounting.tLedgerGroupMaster LGM
			ON LM.LedgerGroupId= LGM.Id 
        
  WHERE  
        ((LM.Id = @rId) OR (@rId = 0))
        AND  ((LM.Title like @rTitle) OR (ISNULL(@rTitle,'') = '')) 
        AND  ((LM.Code like @rCode) OR (ISNULL(@rCode,'') = '')) 
        AND  ((LM.LedgerGroupId = @rLedgerGroupId) OR (@rLedgerGroupId = 0))
        AND ((LM.AccountingYearId =  @rAccountingYearId))
        AND ((LGM.AccountingYearId = @rAccountingYearId))
        And LGM.AccountId = @1AccountId AND LM.OrgGroupId = @rOrgGroupId
        --AND ((LGM.OrgGroupId=@rOrgGroupId))
        
        --Do not Change Order By 
        order by LM.Id asc
		
END
GO
PRINT N'Altering [sAccounting].[pMonthlySummaryMonthwiseGet]...';


GO
ALTER PROCEDURE [sAccounting].[pMonthlySummaryMonthwiseGet]
	 
	@rOrgGroupId int = 0,
	@rAccountingYearId [int],
	@rLedgerId [int] 
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

        DECLARE @AccOpBalance decimal(12,2) = 0
		SELECT @AccOpBalance = OpeningBalance FROM sAccounting.tLedgerMaster  WHERE AccountingYearId=@rAccountingYearId AND Id = @rLedgerId
		 
		SELECT @AccOpBalance AS OpeningBalance,CR.MonthName AS Region,ISNULL(Credit,0) AS Credit,ISNULL(Debit,0) AS Debit,@AccOpBalance + ISNULL(Debit,0) - ISNULL(Credit,0) AS ClosingBalance
		,DATEADD(month,CR.MonthN-1,DATEADD(year,CR.YearCr-1900,0)) AS TransactionFromDate,DATEADD(day,-1,DATEADD(month,CR.MonthN,DATEADD(year,CR.YearCr-1900,0))) AS TransactionToDate
		 
		FROM (
		 
		SELECT  -1 * ISNULL(Sum(TD.Amount) ,0) AS Credit ,DATEPART(MONTH,T.TransactionDate) AS MonthN,datename(month,T.TransactionDate) AS MonthName
				 ,DATEPART(Year,T.TransactionDate) AS YearCr FROM  sAccounting.tTransaction T INNER JOIN sAccounting.tTransactionDetail TD
				 ON T.Id=TD.TransactionId 		 
					AND T.AccountingYearId = @rAccountingYearId 			 
					AND TD.TransactionTypeId = 1 And TD.LedgerId=@rLedgerId
				GROUP BY DATEPART(MONTH,T.TransactionDate),datename(month,T.TransactionDate),DATEPART(Year,T.TransactionDate)
	     )   CR  FULL  OUTER JOIN 
	    (
				 SELECT  ISNULL(Sum(TD.Amount) ,0) AS Debit,DATEPART(MONTH,T.TransactionDate) AS MonthN,datename(month,T.TransactionDate) AS MonthName
				,DATEPART(Year,T.TransactionDate) AS YearDR FROM  sAccounting.tTransaction T INNER JOIN sAccounting.tTransactionDetail TD
				 ON T.Id=TD.TransactionId 
				 --INNER JOIN sAccounting.tLedgerMaster L ON L.ID = TD.LedgerId
					AND T.AccountingYearId = @rAccountingYearId 			 
					AND TD.TransactionTypeId = 2 And TD.LedgerId=@rLedgerId
				GROUP BY DATEPART(MONTH,T.TransactionDate),datename(month,T.TransactionDate),DATEPART(Year,T.TransactionDate)   
		)   DR ON DR.MonthN = CR.MonthN

	 
	
END
GO
PRINT N'Altering [sAccounting].[pProfitAndLoss]...';


GO
ALTER PROCEDURE [sAccounting].[pProfitAndLoss]

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

BEGIN
--SELECT '' AS Builder1,
--	   '' AS Builder2,
--         '' AS IncomeGroup,
--	     '' AS IncomeLedger,
--	     '' AS Income,
--	     '' AS ClosingBalance,
--	     '' AS ExpenseGroup,
--	     '' AS ExpenseLedger,
--	     '' AS Expense,
--	     '' AS OpeningBalance
	    

Declare @lLedgerId int 
Declare @lOpeningBalance Decimal (12,2)
Declare @ltIncome Decimal (12,2)
Declare @ltExpense Decimal (12,2)
Declare @lInIncome Decimal(12,2)
Declare @lInClosing Decimal(12,2)
Declare @lExOpening Decimal(12,2)
Declare @lExExpense Decimal(12,2)
Declare @lGrossProfit Decimal(12,2)
Declare @lGrossLoss Decimal(12,2)
Declare @lCount int
Declare @lLedgerName Nvarchar(150)
Declare @lLedgerGroupName Nvarchar(150)
Declare @lLedgerMainGroupName Nvarchar(150) 
DECLARE @1ExpenceCount int
DECLARE @1IncomeCount int

	
    CREATE TABLE #tempUpdateClosingBalance
 		(	Id INT IDENTITY (1, 1),
 			LedgerId int,
 			Temp_Op_Balance decimal(12,2),
 			Closing_Balance decimal(12,2),
 		    Transaction_Balance decimal(12,2)
 		)  	
 		INSERT INTO #tempUpdateClosingBalance (LedgerId,Temp_Op_Balance,Closing_Balance,Transaction_Balance)
		EXEC [sAccounting].[pUpdateClosingBalance] @rStartDate,@rEndDate,@rOrgGroupId,@rAccountingYearId,'',''
		
		
		CREATE TABLE #TempExpenseGroup
		(
		   Id INT IDENTITY(1,1),
		   ExpenseGroup nvarchar(200),
		   ExpenseLedger nvarchar(200),
		   Expense decimal(22,2),
		   OpeningBalance decimal(22,2)		 
		)
		
		CREATE TABLE #TempIncomeGroup
		(
		   Id INT IDENTITY(1,1),
		   IncomeGroup nvarchar(200),
		   IncomeLedger nvarchar(200),
		   Income decimal(22,2),
		   ClosingBalance decimal		 
		)
		
		INSERT INTO #TempExpenseGroup
		SELECT 
		ISNULL(LG.Title,'') AS ExpenseGroup,
		ISNULL(L.Title,'') AS ExpenseLedger,	
		ISNULL(SUM(UC.Closing_Balance),0) AS Expense,
	    ISNULL(SUM(L.OpeningBalance),0) AS OpeningBalance
 
	    FROM sAccounting.tLedgerMaster L
		INNER JOIN sAccounting.tLedgerGroupMaster LG ON L.LedgerGroupId = LG.Id
		INNER JOIN sAccounting.tLedgerMainGroupMaster LMG ON LG.LedgerMainGroupId = LMG.Id
		INNER JOIN #tempUpdateClosingBalance UC ON L.Id=UC.LedgerId
		WHERE LMG.ID  = 4 AND L.AccountingYearId = @rAccountingYearId AND LG.AccountingYearId = @rAccountingYearId
		GROUP BY LG.Title,LMG.ID,L.Title	
		Order By LMG.Id	
		
		
		INSERT INTO #TempIncomeGroup
        SELECT  		
		ISNULL(LG.Title,'') AS IncomeGroup,
		ISNULL(L.Title,'') AS IncomeLedger,
		ISNULL(SUM(UC.Closing_Balance),0) AS Income,
		ISNULL(SUM(UC.Closing_Balance),0) AS ClosingBalance
		FROM sAccounting.tLedgerMaster L 
		INNER JOIN sAccounting.tLedgerGroupMaster LG ON L.LedgerGroupId = LG.Id
		INNER JOIN sAccounting.tLedgerMainGroupMaster LMG ON LG.LedgerMainGroupId = LMG.Id
		INNER JOIN #tempUpdateClosingBalance UC ON L.Id=UC.LedgerId
		WHERE LMG.ID = 3 AND L.AccountingYearId = @rAccountingYearId AND LG.AccountingYearId = @rAccountingYearId
		GROUP BY LG.Title,LMG.ID,L.Title	
		Order By LMG.Id			
	     
	   SELECT @1ExpenceCount = count(Id) From #TempExpenseGroup
	   SELECT @1IncomeCount = Count(Id) From #TempIncomeGroup
	   
	   If(@1InComeCount > @1ExpenceCount)
	     BEGIN	          
	           SELECT 
	             @rBuilder1 AS Builder1
				,@rBuilder2 AS Builder2,
	               IncomeGroup, 
	               IncomeLedger,
	               ClosingBalance,
	               Income,
	               ISNULL(ExpenseGroup,'') AS ExpenseGroup,
	               ISNULL(ExpenseLedger,'') AS ExpenseLedger,
				   ISNULL(OpeningBalance,0) AS OpeningBalance,	          
				   ISNULL(Expense,0.00) AS Expense
	           FROM #TempIncomeGroup IG LEFT JOIN #TempExpenseGroup EG ON EG.Id = IG.Id	         
	     END
	     ELSE
	     BEGIN
	         SELECT
				 @rBuilder1 AS Builder1
				,@rBuilder2 AS Builder2, 
	               ISNULL(IncomeGroup,'') AS IncomeGroup, 
	               ISNULL(IncomeLedger,'') AS IncomeLedger,
	               ISNULL(ClosingBalance,0) AS ClosingBalance,
	               ISNULL(Income,0) AS Income,
	               ExpenseGroup AS ExpenseGroup,
	               ExpenseLedger,
				   OpeningBalance,
				   Expense       
	           FROM  #TempExpenseGroup EG   LEFT JOIN #TempIncomeGroup IG ON EG.Id = IG.Id		        
	     END	
	     
	     DROP TABLE #TempExpenseGroup
	     DROP TABLE #TempIncomeGroup
		
END
GO
PRINT N'Altering [sAccounting].[pRptVoucherEntryGet]...';


GO



ALTER PROCEDURE [sAccounting].[pRptVoucherEntryGet]
	
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rTransactionId bigint,
	 @rAccountingYearId int,
	 @rTransactionDate date,
	 @rOrgGroupId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN  
	 
  SELECT    @rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			T.Id AS TransactionId,
			T.Narration,
			T.TransactionDate,
			T.VoucherNumber,
			TD.Amount,
			TD.Id as TransactionDetailId,
			LM.Title AS Ledger,
			VTM.Title AS VoucherType,
			TD.TransactionTypeId    
  FROM 
       sAccounting.tTransaction T
       INNER JOIN sAccounting.tTransactionDetail TD ON T.Id=TD.TransactionId
       LEFT JOIN sAccounting.tLedgerMaster LM On LM.Id=TD.LedgerId
       LEFT JOIN sAccounting.tVoucherTypeMaster VTM ON VTM.Id=T.VoucherTypeId
      
      
  WHERE 
			(T.Id=@rTransactionId OR @rTransactionId = 0 )  
			AND (T.AccountingYearId=@rAccountingYearId)  AND LM.AccountingYearId = @rAccountingYearId
			ANd (T.TransactionDate=@rTransactionDate OR ISNULL(@rTransactionDate,'')='1900-01-01')     
			AND (T.OrgGroupId=@rOrgGroupId)
   Order By T.VoucherTypeId,T.VoucherNumber
END
GO
PRINT N'Altering [sAccounting].[pTarij]...';


GO
ALTER PROCEDURE [sAccounting].[pTarij]

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

BEGIN

   --SELECT '' AS Builder1,
	  --    '' AS Builder2,
   --       '' As Id,
		 -- '' As CreditBalance,
		 -- '' AS DebitBalance,
		 -- '' As CashOpBalance,
		 -- '' AS LedgerId,
		 -- '' AS LedgerName,
		 -- '' As LedgerTypeId,
		 -- '' AS OpeningBalance,
		 -- '' AS LedgerGroup,
		 -- '' AS LedgerMainGroup

Declare @lLedgerId int 
Declare @lCashOpBalance Decimal (12,2)
Declare @lOpeningBalance Decimal (12,2)
Declare @lCreditBalance Decimal (12,2)
Declare @lDebitBalance Decimal (12,2)
Declare @lLOpeningBalance Decimal(12,2)
Declare @lCount int
Declare @lLedgerTypeId int
Declare @lLedgerName Nvarchar(150)
Declare @lLedgerGroupName Nvarchar(150)
Declare @lLedgerMainGroupName Nvarchar(150)
	
	
	--EXEC [sAccounting].[pUpdateClosingBalance] @rStartDate,@rEndDate,@rOrgGroupId,@rAccountingYearId,@rLedgerId,@rLedgerMainGroupId,@rISProfitLoss
	
	SELECT @lLOpeningBalance = Sum(OpeningBalance) From sAccounting.tLedgerMaster L
	INNER JOIN sAccounting.tLedgerGroupMaster LG ON L.LedgerGroupId=LG.Id AND LG.LedgerMainGroupId = 2 and L.AccountingYearId=@rAccountingYearId And LG.OrgGroupId = @rOrgGroupId
    
	CREATE TABLE #tTarij
 		(	Id INT IDENTITY (1,1),
 			CreditBalance decimal(12,2),
 			DebitBalance decimal(12,2),
 			CashOpBalance Decimal(12,2),
 			LedgerId int,
 			LedgerName varchar(100),
 			LedgerTypeId int,
 			OpeningBalance decimal(12,2),
 			LedgerGroup varchar(100),
			LedgerMainGroup Varchar(100) 			
 		) 
 	IF @rTarij =1 
 	BEGIN	
 		INSERT INTO #tTarij    
		SELECT 
		(Select ISNULL(Sum(Amount),0) From sAccounting.tTransaction T INNER JOIN sAccounting.tTransactionDetail TD ON T.Id= TD.TransactionId And TD.LedgerId = L.Id And TD.TransactionTypeId= 1 And T.TransactionDate>=@rStartDate And T.TransactionDate <=@rEndDate AND T.AccountingYearID=@rAccountingYearId) as CreditBalance, 
		(Select ISNULL(Sum(Amount),0) From sAccounting.tTransaction T INNER JOIN sAccounting.tTransactionDetail TD ON T.Id= TD.TransactionId And TD.LedgerId = L.Id And TD.TransactionTypeId= 2 And T.TransactionDate>=@rStartDate And T.TransactionDate <=@rEndDate AND T.AccountingYearID=@rAccountingYearId) as DebitBalance, 
		(Select ISNULL(Sum(OpeningBalance),0) From sAccounting.tLedgerMaster L1 INNER JOIN sAccounting.tLedgerGroupMaster LG ON LG.Id=L1.LedgerGroupId AND LG.OrgGroupId=@rOrgGroupId AND L1.AccountingYearId=@rAccountingYearId) as CashOpBalance, 
		L.Id, L.Title, L.LedgerTypeId,L.OpeningBalance, 
		LG.Title AS GName, LGM.Title AS MGName 
		FROM sAccounting.tLedgerMaster L INNER JOIN sAccounting.tLedgerGroupMaster LG on LG.Id=L.LedgerGroupId
		INNER JOIN sAccounting.tLedgerMainGroupMaster LGM ON LGM.Id = LG.LEDGERMAINGROUPID
		And LG.OrgGroupId= @rOrgGroupId AND L.AccountingYearId=@rAccountingYearId AND LG.AccountingYearId = @rAccountingYearId
		AND LG.LedgerMainGroupID <> 2
    END
    
    ELSE
    
    BEGIN
 		INSERT INTO #tTarij    
		SELECT 
		(Select ISNULL(Sum(Amount),0) From sAccounting.tTransaction T INNER JOIN sAccounting.tTransactionDetail TD ON T.Id= TD.TransactionId And TD.LedgerId = L.Id And TD.TransactionTypeId= 1 And T.TransactionDate>=@rStartDate And T.TransactionDate <=@rEndDate AND T.AccountingYearID=@rAccountingYearId) as CreditBalance, 
		(Select ISNULL(Sum(Amount),0) From sAccounting.tTransaction T INNER JOIN sAccounting.tTransactionDetail TD ON T.Id= TD.TransactionId And TD.LedgerId = L.Id And TD.TransactionTypeId= 2 And T.TransactionDate>=@rStartDate And T.TransactionDate <=@rEndDate AND T.AccountingYearID=@rAccountingYearId) as DebitBalance, 
		(Select ISNULL(Sum(OpeningBalance),0) From sAccounting.tLedgerMaster L1 INNER JOIN sAccounting.tLedgerGroupMaster LG ON LG.Id=L1.LedgerGroupId AND LG.OrgGroupId=@rOrgGroupId AND L1.AccountingYearId=@rAccountingYearId) as CashOpBalance, 
		L.Id, L.Title, L.LedgerTypeId,L.OpeningBalance, 
		LG.Title AS GName, LGM.Title AS MGName 
		FROM sAccounting.tLedgerMaster L INNER JOIN sAccounting.tLedgerGroupMaster LG on LG.Id=L.LedgerGroupId
		INNER JOIN sAccounting.tLedgerMainGroupMaster LGM ON LGM.Id = LG.LEDGERMAINGROUPID
		And LG.OrgGroupId= @rOrgGroupId AND L.AccountingYearId=@rAccountingYearId AND LG.AccountingYearId = @rAccountingYearId    
    END
		
	

	SELECT @lCount =  COUNT(Id) FROM #tTarij
	WHILE (@lCount > 0)
	BEGIN
		SELECT @lLedgerId=LedgerId,@lCreditBalance=CreditBalance,@lDebitBalance=DebitBalance,@lCashOpBalance=CashOpBalance,
		@lLedgerName=LedgerName,@lLedgerTypeId=LedgerTypeId,@lOpeningBalance=OpeningBalance,@lLedgerGroupName=LedgerGroup,
		@lLedgerMainGroupName=LedgerMainGroup	FROM #tTarij WHERE Id= @lCount
		if @rTarij=1 
		BEGIN
				SET @lCreditBalance = @lCreditBalance + @lLOpeningBalance
		END
		ELSE
		BEGIN
				SET @lCreditBalance = @lLOpeningBalance
		END
		
		SET @lCreditBalance = @lCreditBalance + (-1) * @lCreditBalance
		SET @lDebitBalance = @lDebitBalance + (-1) * @lDebitBalance
		SET @lCount = @lCount - 1
	END	
	
	Update #tTarij Set CreditBalance = -1 * CreditBalance Where CreditBalance < 0
	 
		
	IF @rOrderBy = 1 
	BEGIN
	  
	    
		
		SELECT @rBuilder1 AS Builder1
	,@rBuilder2 AS Builder2,* FROM #tTarij ORDER BY LEDGERMAINGROUP
	END
	
	ELSE
	BEGIN
		SELECT @rBuilder1 AS Builder1
	,@rBuilder2 AS Builder2,* FROM #tTarij ORDER BY 	LEDGERNAME
	END
END
GO
PRINT N'Altering [sAccounting].[pTransactionAdd]...';


GO

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

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

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


GO
ALTER PROCEDURE [sAccounting].[pTrialBalance]

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

BEGIN

--SELECT '' AS Builder1,
--	   '' AS Builder2,
--       '' As Id,
--	   '' As LedgerId,
--	   '' As LedgerName,
--	   '' As LedgerGroup,
--	   '' As LedgerMainGroup,
--	   '' As LedgerTypeId,
--	   '' As CreditBalance,
--	   '' As DebitBalance,
--	   '' As OpeningBalance,
--	   '' As ClosingBalance

Declare @lLedgerId int 
Declare @lCashOpBalance Decimal (12,2)
Declare @lOpeningBalance Decimal (12,2)
Declare @lCreditBalance Decimal (12,2)
Declare @lDebitBalance Decimal (12,2)
Declare @lLOpeningBalance Decimal(12,2)
Declare @lCount int
Declare @lLedgerTypeId int
Declare @lLedgerName Nvarchar(150)
Declare @lLedgerGroupName Nvarchar(150)
Declare @lLedgerMainGroupName Nvarchar(150)
	
	
	
    CREATE TABLE #tempUpdateClosingBalance
 		(	Id INT IDENTITY (1, 1),
 			LedgerId int,
 			Temp_Op_Balance decimal(12,2),
 			Closing_Balance decimal(12,2),
 			Transaction_Balance decimal(12,2) 			
 		)
 		
	   CREATE TABLE #tTempTrialBalance
 		(	Id INT IDENTITY (1,1),
 			LedgerId int,
 			LedgerName varchar(100),
 			LedgerGroup varchar(100),
			LedgerMainGroup Varchar(100), 			
 			LedgerTypeId int,
 			CreditBalance decimal(12,2),
 			DebitBalance decimal(12,2),
 			OpeningBalance decimal(12,2),
 			ClosingBalance Decimal(12,2)
 		) 
 		INSERT INTO #tTempTrialBalance    
		SELECT L.Id, L.Title,LG.Title AS GName, LGM.Title AS MGName ,L.LedgerTypeId,0,0,L.OpeningBalance,0		
		FROM sAccounting.tLedgerMaster L INNER JOIN sAccounting.tLedgerGroupMaster LG on LG.Id=L.LedgerGroupId
		INNER JOIN sAccounting.tLedgerMainGroupMaster LGM ON LGM.Id = LG.LEDGERMAINGROUPID
		And LG.OrgGroupId= @rOrgGroupId AND L.AccountingYearId=@rAccountingYearId AND LG.AccountingYearId = @rAccountingYearId
	  
	--select * from #tTemptrialBalance
	 
	SELECT @lCount =  COUNT(Id) FROM #tTempTrialBalance
	WHILE (@lCount > 0)
	BEGIN
		SELECT @lLedgerId=LedgerId,@lCreditBalance=CreditBalance,@lDebitBalance=DebitBalance,
		@lLedgerName=LedgerName,@lLedgerTypeId=LedgerTypeId,@lOpeningBalance=OpeningBalance,@lLedgerGroupName=LedgerGroup,
		@lLedgerMainGroupName=LedgerMainGroup	FROM #tTempTrialBalance WHERE Id= @lCount
	
		INSERT INTO #tempUpdateClosingBalance (LedgerId,Temp_Op_Balance,Closing_Balance,Transaction_Balance)
		EXEC [sAccounting].[pUpdateClosingBalance] @rStartDate,@rEndDate,@rOrgGroupId,@rAccountingYearId,@lLedgerId,''
		SET @lCount = @lCount - 1
	END	
	
	--select UC.LedgerId,TB.LedgerName,Temp_Op_Balance,Closing_Balance from #tempUpdateClosingBalance UC INNER JOIN #tTemptrialBalance TB ON TB.LedgerId = UC.LedgerId
	
	IF @rOrderBy = 0 
	BEGIN
		SELECT @rBuilder1 AS Builder1
	    ,@rBuilder2 AS Builder2,TB.LedgerId,TB.LedgerName,TB.LedgerGroup,TB.LedgerMainGroup,T.Temp_Op_Balance AS OpeningBalance,
		ISNULL(CASE WHEN T.Transaction_Balance < 0 THEN -1 * T.Transaction_Balance END,0) AS CreditBalance,
		ISNULL(CASE WHEN T.Transaction_Balance >= 0 THEN T.Transaction_Balance ENd,0) AS DebitBalance,
		
		--ISNULL(CASE WHEN T.Temp_Op_Balance < 0 THEN (-1) * T.Temp_Op_Balance END,0) AS CreditBalance,
		--ISNULL(CASE WHEN T.Temp_Op_Balance >= 0 THEN T.Temp_Op_Balance ENd,0) AS DebitBalance,
		
		T.Closing_Balance AS ClosingBalance
		FROM #tempUpdateClosingBalance T 
		INNER JOIN #tTempTrialBalance TB on T.LedgerId=TB.LedgerId ORDER BY TB.LedgerName
	END
	ELSE
	BEGIN
		SELECT @rBuilder1 AS Builder1
	    ,@rBuilder2 AS Builder2,TB.LedgerId,TB.LedgerName,TB.LedgerGroup,TB.LedgerMainGroup,T.Temp_Op_Balance AS OpeningBalance,
	    ISNULL(CASE WHEN T.Transaction_Balance < 0 THEN -1 * T.Transaction_Balance END,0) AS CreditBalance,
		ISNULL(CASE WHEN T.Transaction_Balance >= 0 THEN T.Transaction_Balance ENd,0) AS DebitBalance,
		--ISNULL(CASE WHEN TB.LedgerTypeId =1 THEN T.Transation_Balance END,0) AS CreditBalance,
		--ISNULL(CASE WHEN TB.LedgerTypeId =2 THEN T.Transation_Balance ENd,0) AS DebitBalance,
		T.Closing_Balance AS ClosingBalance
		FROM #tempUpdateClosingBalance T inner join #tTempTrialBalance TB on T.LedgerId=TB.LedgerId ORDER BY TB.LedgerMainGroup
	END
	
	DROP Table #tempUpdateClosingBalance
	
END
GO
PRINT N'Altering [sAccounting].[pUpdateClosingBalance]...';


GO
ALTER PROCEDURE [sAccounting].[pUpdateClosingBalance]
	
	@rStartDate Date,
	@rEndDate Date,
	@rOrgGroupId int = 0,
	@rAccountingYearId [int],
	@rLedgerId [int],
	@rISProfitLoss [smallint]

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

Declare @OpeningBalance decimal(12,2)
Declare @AccOpBalance decimal(12,2) = 0
Declare @ClosingBalance decimal(12,2)
Declare @TransactionBalance decimal(12,2) 
Declare @LedgerId int 
Declare @lCount int
Declare @LedgerTypeId int
	
	
	CREATE TABLE #tempUpdateClosingBalance123
 		(	
 		    Id INT IDENTITY (1, 1),
 			LedgerId int,
 			Temp_Op_Balance decimal(12,2),
 			Closing_Balance decimal(12,2),
 			Trasaction_Balance decimal(12,2) not null
  		) 
	
	CREATE TABLE #tempLedgerMaster
 	    (
 	        Id INT IDENTITY (1, 1),
 			LedgerId int,
 			AccOpBalance decimal(12,2),
 			LedgerTypeId int				 
 		) 
 	INSERT INTO #tempLedgerMaster
	SELECT Id,OpeningBalance,LedgerTypeId FROM sAccounting.tLedgerMaster  
	WHERE AccountingYearId=@rAccountingYearId AND (ID=@rLedgerId OR @rLedgerId=0)
	ORDER BY Id Asc
	
	SELECT @lCount =  COUNT(Id) FROM #tempLedgerMaster
	WHILE (@lCount > 0)
	BEGIN
			SELECT @AccOpBalance =AccOpBalance,@LedgerTypeId= LedgerTypeId,
			@LedgerId =LedgerId FROM #tempLedgerMaster WHERE Id = @lCount	
	 -- Opening Balance Calulation
				IF @rISProfitLoss = 1 
				  BEGIN
					SELECT @OpeningBalance = ISNULL(SUM(AMOUNT),0) FROM sAccounting.tTransactionDetail TD
					INNER JOIN sAccounting.tTransaction T ON T.ID = TD.TransactionId
					WHERE T.OrgGroupId = @rOrgGroupId AND T.AccountingYearId = @rAccountingYearId
					AND T.TransactionDate < @rStartDate AND TD.LedgerId=@LedgerId AND
					(TD.LedgerId = @rLedgerId OR @rLedgerId = 0) AND T.IsProfitAndLoss <> 1
				  END
				ELSE
				  BEGIN
					SELECT @OpeningBalance = ISNULL(SUM(AMOUNT),0) FROM sAccounting.tTransactionDetail TD
					INNER JOIN sAccounting.tTransaction T ON T.ID = TD.TransactionId
					WHERE T.OrgGroupId = @rOrgGroupId AND T.AccountingYearId = @rAccountingYearId
					AND T.TransactionDate < @rStartDate AND TD.LedgerId=@LedgerId AND
				    (TD.LedgerId = @rLedgerId OR @rLedgerId = 0)
				  END				
   -- Transaction Balance
   				IF @rISProfitLoss = 1 
				  BEGIN
					SELECT @TransactionBalance = ISNULL(SUM(AMOUNT),0) FROM sAccounting.tTransactionDetail TD
					INNER JOIN sAccounting.tTransaction T ON T.ID = TD.TransactionId
					WHERE T.OrgGroupId = @rOrgGroupId AND T.AccountingYearId = @rAccountingYearId
					AND T.TransactionDate >= @rStartDate  AND T.TransactionDate <= @rEndDate 
					AND TD.LedgerId=@LedgerId AND
					(TD.LedgerId = @rLedgerId OR @rLedgerId = 0) AND T.IsProfitAndLoss <> 1
				  END
				ELSE
				  BEGIN
					SELECT @TransactionBalance = ISNULL(SUM(AMOUNT),0) FROM sAccounting.tTransactionDetail TD
					INNER JOIN sAccounting.tTransaction T ON T.ID = TD.TransactionId
					WHERE T.OrgGroupId = @rOrgGroupId AND T.AccountingYearId = @rAccountingYearId
					AND T.TransactionDate >= @rStartDate  AND T.TransactionDate <= @rEndDate 
					AND TD.LedgerId=@LedgerId AND (TD.LedgerId = @rLedgerId OR @rLedgerId = 0)
				  END				
	--
				IF @LedgerTypeId = 1 
				BEGIN
					SET @TransactionBalance = -1 * @TransactionBalance
					SET @OpeningBalance = -1 * @OpeningBalance
				END
				ELSE
				BEGIN
					SET @TransactionBalance = @TransactionBalance
					SET @OpeningBalance = @OpeningBalance
				END
								    
				    SET @OpeningBalance = @OpeningBalance + @AccOpBalance				
					SET @ClosingBalance = @OpeningBalance + @TransactionBalance				
				    --Select @OpeningBalance AS OPBal ,@ClosingBalance AS CloseIng				
				
				INSERT INTO #tempUpdateClosingBalance123 (LedgerId ,Temp_Op_Balance ,Closing_Balance,Trasaction_Balance)
				VALUES (@LedgerId,@OpeningBalance,@ClosingBalance,@TransactionBalance)

				SET @lCount = @lCount - 1
	END	
		SELECT LedgerId,Temp_Op_Balance,Closing_Balance,Trasaction_Balance FROM #tempUpdateClosingBalance123 ORDER BY LedgerId
		TRUNCATE TABLE #tempUpdateClosingBalance123
END
GO
PRINT N'Altering [sAccounting].[pVoucherListGet]...';


GO

ALTER PROCEDURE [sAccounting].[pVoucherListGet]

	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rVoucherTypeId int = 0,
	 @rTransactionDate Date,
	 @rTransactionDateTo Date,
	 @rVoucherNumber int,
	 @rVoucherNumberTo int,
	 @rLedgerId int,
	 @rNarration nvarchar(100),
	 @rAmount int,
	 @rAccountingYearId int = 0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

	  BEGIN
			SET @rNarration = sCommon.fSearchStringGet(@rNarration)
	  END
	 
  SELECT   @rBuilder1 AS Builder1
		  ,@rBuilder2 AS Builder2
		  ,T.Id
		  ,VTM.Title AS VoucherType
		  ,T.VoucherNumber AS VoucherNo
		  ,T.TransactionDate AS VoucherDate
		  ,LM.Title AS Ledger
		  ,CASE WHEN ISNULL(TD.Amount,0) < 0 THEN ISNULL(TD.Amount,0) * -1 ELSE 0 END AS Credit
		  ,CASE WHEN ISNULL(TD.Amount,0) > 0 THEN ISNULL(TD.Amount,0) ELSE 0 END AS Debit
		  ,T.Narration AS Narration	  	      
  FROM 
          sAccounting.tTransaction T
          INNER JOIN sAccounting.tTransactionDetail TD ON T.Id=TD.TransactionId
          INNER JOIN sAccounting.tVoucherTypeMaster VTM ON VTM.Id = T.VoucherTypeId
          INNER JOIN sAccounting.tLedgerMaster LM ON LM.Id=TD.LedgerId             
  WHERE 
				(T.VoucherTypeId=@rVoucherTypeId OR @rVoucherTypeId = 0) 
			AND ((T.Narration like @rNarration) OR (ISNULL(@rNarration,'') = '')) 		
			AND (T.TransactionDate >= @rTransactionDate OR ISNULL(@rTransactionDate,'') = '') 
			And (T.TransactionDate <= @rTransactionDateTo OR ISNULL(@rTransactionDateTo,'') = '')
			AND (T.VoucherNumber >= @rVoucherNumber OR @rVoucherNumber=0) 
			AND (T.VoucherNumber <=@rVoucherNumberTo OR @rVoucherNumberTo=0)
			AND (TD.LedgerId = @rLedgerId OR @rLedgerId=0)
			AND (TD.Amount = @rAmount OR ISNULL(@rAmount,0) = 0)
			AND LM.AccountingYearId = @rAccountingYearId
			AND T.AccountingYearId = @rAccountingYearId
        
            Order By T.VoucherTypeId,T.TransactionDate,T.VoucherNumber,Credit,Debit
END
GO
PRINT N'Altering [sAdmission].[pAdmissionFormGet]...';


GO
ALTER PROCEDURE [sAdmission].[pAdmissionFormGet]
	 @rAdmissionFormId bigint = 0,
	 @rFormNo int,
	 @rForClassId int,
	 @rStatusId smallint,
	 @rOrgId int,
	 @rFirstName nvarchar(100),
	 @rLastName nvarchar(100),
	 @rMeritMarks decimal(10,2)
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 --IF @rIsSearch = 1
		BEGIN
			SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
			SET @rLastName = sCommon.fSearchStringGet(@rLastName)
		END
	
	SELECT 
			 AF.Id
			,AF.FormNo
			,AF.FirstName
			,AF.MiddleName
			,AF.LastName
			,AF.FirstName+' '+AF.LastName as Name
			,AF.ForClassId
			,CM.Title AS ClassName
			,AF.ForBatch
			,ISNULL(AF.DateOfBirth,'') AS DateOfBirth
			,AF.DateOfBirthInWord
			,AF.StatusId
			,SM.Title as StatusName
			,AF.StreetOne
			,AF.StreetTwo
			,AF.StreetThree
			,AF.Country
			,AF.State
			,AF.City
			,AF.ZipCode
			,AF.ContactNo
			,AF.ContactEmail
			,AF.Remark
			,AF.PreviousSchool
			,AF.MeritMarks
			,AF.MeritGrade
			,AF.GenderId
			,GM.Title AS Gender
			,ISNULL(AF.ReligionId,0) AS ReligionId
			,AF.FamilyCast
			,AF.FamilySubCast
			,ISNULL(AF.CastCategoryId,0) AS CastCategoryId
      
  FROM 
            sAdmission.tAdmissionForm AF
			INNER JOIN sCommon.tStatusMaster SM ON SM.Id=AF.StatusId
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=AF.ForClassId
			INNER JOIN sCommon.tGenderMaster GM ON GM.Id=AF.GenderId
  WHERE 
  
      ((AF.Id = @rAdmissionFormId) OR (@rAdmissionFormId = 0))
    AND ((AF.FormNo=@rFormNo) OR (@rFormNo=''))
    --AND ((AF.FirstName=@rFirstName) OR (@rFirstName=''))
    --AND ((AF.LastName=@rLastName) OR (@rLastName=''))
    AND ((AF.StatusId=@rStatusId) OR (@rStatusId=0))
	AND ((AF.ForClassId=@rForClassId) OR (@rForClassId=0)) 
	--AND ((AF.MeritMarks=@rMeritMarks) OR (@rMeritMarks=0))
	AND AF.OrgId=@rOrgId
END
GO
PRINT N'Altering [sAssessment].[pCCEResultAdd]...';


GO


ALTER PROCEDURE [sAssessment].[pCCEResultAdd] 
	        @rAcademicId bigint
		   ,@rUpdatedUserId bigint
		   ,@rOrgId int
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 
	 DECLARE @lCCEResultId  BIGINT

SELECT @lCCEResultId = ISNULL(AcademicId,0) FROM sAssessment.tCCEResult WHERE AcademicId=@rAcademicId	 

IF(ISNULL(@lCCEResultId,0) = 0)	
BEGIN
	--EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAssessment.tCCEResult', 0, 1, 1,@outNextNumber = @lNextNumber output
	INSERT INTO [sAssessment].[tCCEResult]
			   (
			  [AcademicId]
			   ,[UpdatedUserId]
			   ,[UpdatedDateTime]
			   )
		 VALUES
			   (
				@rAcademicId
			   ,@rUpdatedUserId		   
			   ,sCommon.fGetDate()
			   )
		    SELECT 1 AS Result
	
		--COMMIT TRANSACTION         
	END	 
ELSE
	 BEGIN
	 SET @lNextNumber = @lCCEResultId
	    UPDATE  [sAssessment].[tCCEResult]
	    SET		 
				UpdatedUserId =@rUpdatedUserId
			 ,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'Altering [sAssessment].[pCCEResultDetailAdd]...';


GO


ALTER PROCEDURE [sAssessment].[pCCEResultDetailAdd]
	 
	     
            @rAcademicId bigint
		   ,@rClassSubjectId int
		   ,@rObtain decimal(6,2)		
		   ,@rExamOrder int
		   ,@rCCEExamId INT
		   ,@rOrgId int
		 
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 
	 DECLARE @lCCEResultDetailId BIGINT
SELECT @lCCEResultDetailId= ISNULL(AcademicId,0) From sAssessment.tCCEResultDetail Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId

IF ISNULL(@lCCEResultDetailId,0) = 0
	 BEGIN

	--EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAssessment.tCCEResultDetail', 0, 1, 1,@outNextNumber = @lNextNumber output	
	 
	INSERT INTO [sAssessment].[tCCEResultDetail]
			   (
				[AcademicId] 
			   ,[ClassSubjectId]
			   ,[GradePointFA1]
			   ,[GradePointFA2]
			   ,[GradePointSA1]
			   ,[GradePointFA3]
			   ,[GradePointFA4]
			   ,[GradePointSA2]
			   ,[UpdatedUserId]
			   ,[UpdatedDateTime]
			   )
		 VALUES
			   (
			    @rAcademicId
			   ,@rClassSubjectId
			   ,0.00
			   ,0.00
			   ,0.00
			   ,0.00
			   ,0.00
			   ,0.00
			   ,0
			   ,sCommon.fGetDate()
			   )
			   
			IF(@rExamOrder=1) UPDATE [sAssessment].[tCCEResultDetail] SET [GradePointFA1]=@rObtain Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
			ELSE IF(@rExamOrder=2) UPDATE [sAssessment].[tCCEResultDetail] SET [GradePointFA2]=@rObtain Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
			ELSE IF(@rExamOrder=3) UPDATE [sAssessment].[tCCEResultDetail] SET [GradePointSA1]=@rObtain Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
			ELSE IF(@rExamOrder=4) UPDATE [sAssessment].[tCCEResultDetail] SET [GradePointFA3]=@rObtain  Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
			ELSE IF(@rExamOrder=5) UPDATE [sAssessment].[tCCEResultDetail] SET [GradePointFA4]=@rObtain Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
			ELSE UPDATE [sAssessment].[tCCEResultDetail] SET [GradePointSA2]=@rObtain Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
		    SELECT @rAcademicId AS Result
	
		--COMMIT TRANSACTION         
	END	 
ELSE
	 BEGIN
	
	    UPDATE  [sAssessment].[tCCEResultDetail]
	    SET  
	         [UpdatedDateTime]=sCommon.fGetDate()
	      WHERE [AcademicId] =@rAcademicId
	     
	    
	        IF(@rExamOrder=1) UPDATE [sAssessment].[tCCEResultDetail] SET [GradePointFA1]=@rObtain Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
			ELSE IF(@rExamOrder=2) UPDATE [sAssessment].[tCCEResultDetail] SET [GradePointFA2]=@rObtain Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
			ELSE IF(@rExamOrder=3) UPDATE [sAssessment].[tCCEResultDetail] SET [GradePointSA1]=@rObtain Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
			ELSE IF(@rExamOrder=4) UPDATE [sAssessment].[tCCEResultDetail] SET [GradePointFA3]=@rObtain  Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
			ELSE IF(@rExamOrder=5)UPDATE [sAssessment].[tCCEResultDetail] SET [GradePointFA4]=@rObtain Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
			ELSE UPDATE [sAssessment].[tCCEResultDetail] SET [GradePointSA2]=@rObtain Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
			
			SELECT @rAcademicId AS Result
	
	 END  
		
--Grade Evaluation
DECLARE @MinimumScore decimal(5,2)
DECLARE @GradeTitle nvarchar(10)
DECLARE @GradePoint decimal(6,2)
DECLARE @lCount int
DECLARE @lDataSetID INT

SELECT @lDataSetID=GradeSetId FROM sAssessment.tExamDetail WHERE ExamId = @rCCEExamId AND ClassSubjectId = @rClassSubjectId

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

SELECT @lCount =  COUNT(Id) FROM #tempGradeSetDetail
DECLARE @lloopCount int
--set @lloopCount=1
while ( @lCount > 0 )
BEGIN
		SELECT @MinimumScore =MinimumScore,@GradeTitle=GradeTitle,@GradePoint=GradePoint
		FROM #tempGradeSetDetail WHERE Id = @lCount
		
		IF @rExamOrder = 1 
		BEGIN				
			Update sAssessment.tCCEResultDetail  Set GradeFA1 = @GradeTitle WHERE GradePointFA1 >= @MinimumScore 
		END
		IF @rExamOrder = 2 
		BEGIN							
			Update sAssessment.tCCEResultDetail  Set GradeFA2 = @GradeTitle WHERE GradePointFA2 >= @MinimumScore 
		END
		IF @rExamOrder = 3 
		BEGIN				
			Update sAssessment.tCCEResultDetail  Set GradeSA1 = @GradeTitle WHERE GradePointSA1 >= @MinimumScore 
		END
		IF @rExamOrder = 4 
		BEGIN				
			Update sAssessment.tCCEResultDetail  Set GradeFA3 = @GradeTitle WHERE GradePointFA3 >= @MinimumScore 
		END
		IF @rExamOrder = 5 
		BEGIN				
			Update sAssessment.tCCEResultDetail  Set GradeFA4 = @GradeTitle WHERE GradePointFA4 >= @MinimumScore 
		END
		IF @rExamOrder = 6 
		BEGIN		
			Update sAssessment.tCCEResultDetail  Set GradeSA2 = @GradeTitle WHERE GradePointSA2 >= @MinimumScore 
		END
		
		SET @lCount = @lCount - 1
 END
	--End Grade Evaluation	
--END	
COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sAssessment].[pCCERptFAIndicatiorListGet]...';


GO



ALTER PROCEDURE [sAssessment].[pCCERptFAIndicatiorListGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 --@rOrgId smallint,
	 --@rBatchId int,
	 @rOrgId int,
	 @rFAGrpId int,
	 @rFAMasterId int
	 --@rClassSubjectId int
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			FAIM.Title AS IndicatorName,
			FAIM.Id AS IndicatorId,
			FAIM.Remark AS IndicatiorRemark,
			FA.Title AS FAMasterName,
			FA.Id As FAMasterId,
			FA.Remark AS FAMasterRemark,
			FAGM.Title AS FAGrpName,
			FAGM.Number AS FAGrpNumber,
			FAGM.Code AS FAGrpCode
			
			
			
			
      
	FROM 
			sAssessment.tCCEFAIndicatorMaster FAIM
			INNER JOIN sAssessment.tCCEFAMaster FA ON FA.Id=FAIM.CCEFAId
			INNER JOIN sAssessment.tCCEFAGroupMaster FAGM ON FAGM.Id=FA.CCEFAGroupId
			
			
			
	WHERE 
			
		   -- (FAIM.OrgId=@rOrgId) AND
		     (FAIM.IsObsolete=0)
		    AND ((FA.Id=@rFAMasterId) OR (@rFAMasterId=0))
		    AND ((FAGM.Id=@rFAGrpId) OR (@rFAGrpId=0))
		    
		
	
		
		
END
GO
PRINT N'Altering [sAssessment].[pCCERptFirstTermResultGet]...';


GO


ALTER PROCEDURE [sAssessment].[pCCERptFirstTermResultGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 --@rOrgId smallint,
	 @rBatchId int,
	 @rClassId int,
	 @rDivisionId int,
	 @rClassSubjectId int
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 



	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			SM.Code,
			ISNULL(SM.FirstName,'')+' '+ISNULL(SM.LastName,'') AS Name,
			A.RollNo,
			CCER.AcademicId,
			ISNULL(SC.ParentContactNo,'') AS ContactNo,
			ISNULL(SC.PresentStreetThree,'')+' '+ISNULL(SC.PresentStreetTwo,'')+' '+ISNULL(SC.PresentStreetThree,'')+' '+ISNULL(SC.PresentCity,'')+' '+ISNULL(SC.PresentState,'') AS PresentAddress,
			SO.DateOfBirth,
			CM.DisplayTitle AS Class,
			DM.DisplayTitle AS Division,
			ISNULL(HM.Title,'') AS House,
			ISNULL(CCERD.GradeFA1,'') AS GradeFA1,
			ISNULL(CCERD.GradeFA2,'') AS GradeFA2,
			ISNULL(CCERD.GradeFA3,'')AS GradeFA3,
			ISNULL(CCERD.GradeFA4,'') AS GradeFA4,
			ISNULL(CCERD.GradeSA1,'') AS GradeSA1,
			ISNULL(CCERD.GradeSA2,'') AS GradeSA2,
			ISNULL(CCERD.FAGrade,'') AS FAGrade,
			ISNULL(CCERD.SAGrade,'') AS SAGrade,
			ISNULL(CCERD.GradePoint,0) AS OverallGrade,
			ISNULL(CCERD.Grade,'') AS Grade,
			ISNULL(CCER.AttendanceTerm1,0) AS AttendanceTerm1,
			ISNULL(CCER.AttendanceTerm2,0) AS AttendanceTerm2,
			ISNULL(CCER.WorkingDaysTerm1,0) AS WorkingDaysTerm1,
			ISNULL(CCER.WorkingDaysTerm2,0) AS WorkingDaysTerm2,
			ISNULL(CCER.Height,0) AS Height,
			ISNULL(CCER.Weight,0) AS Weight,
			ISNULL(CCER.VisionLeft,'') AS VisionLeft,
			ISNULL(CCER.VisionRight,'') AS VisionRight,
			ISNULL(CCER.DentalHygiene,'') AS DentalHygiene,
			SubM.Title As ClassSubject,
			ISNULL(BGM.Title,'') AS BloodGroup,
			ISNULL(CCERD.Term1GradePoint,0) AS Term1GradePoint,
			ISNULL(CCERD.Term1Grade,'') AS Term1Grade,
			ISNULL(CCERD.Term2GradePoint,0) AS Term2GradePoint,
			ISNULL(CCERD.Term2Grade,'') AS Term2Grade
			--ISNULL(SI.StudentPhoto,CONVERT(varbinary(max),SI.StudentPhoto,1)) AS StudentPhoto
			--SI.StudentPhoto AS StudentPhoto 

			
			
      
	FROM 
	
			sAssessment.tCCEResultDetail CCERD
			
			INNER JOIN sAssessment.tCCEResult CCER  ON CCERD.AcademicId=CCER.AcademicId
			INNER JOIN sStudent.tAcademic A ON CCER.AcademicId=A.Id
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId
			LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=A.StudentId
			LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
			LEFT JOIN sActivity.tHouseMaster HM ON HM.Id=SO.HouseId
			LEFT JOIN sSetup.tClassSubject CS ON CS.Id=CCERD.ClassSubjectId
			INNER JOIN sSetup.tSubjectMaster SubM ON SubM.Id=CS.SubjectId
			LEFT JOIN sCommon.tBloodGroupMaster BGM ON BGM.Id=SO.BloodGroupId
			LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=A.StudentId
			
			
	WHERE 
			
    A.BatchId = @rBatchId 
		
	AND (A.DivisionId=@rDivisionId OR @rDivisionId=0)
	AND (A.ClassId=@rClassId OR @rClassId=0) 
	AND (CCERD.ClassSubjectId=@rClassSubjectId OR @rClassSubjectId=0)
	--AND a.Id = 1001000000084
		
	ORDER BY A.RollNo,CS.OrderIndex	
END
GO
PRINT N'Altering [sAssessment].[pCSClassGet]...';


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

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


GO
ALTER PROCEDURE [sAssessment].[pGradeSetMasterDelete]
@rId bigint
AS
BEGIN
BEGIN TRY
	IF NOT EXISTS (SELECT Id FROM sAssessment.tExamMaster WHERE GradeSetId= @rId)	OR
	   Not Exists (Select 1 From sAssessment.tCCECSGroupMaster Where GradeSetId = @rId)
	  BEGIN
		DELETE FROM sAssessment.tGradeSetDetail WHERE GradeSetId IN (SELECT ID FROM sAssessment.tGradeSetMaster WHERE ID=@rId)
		DELETE	FROM sAssessment.tGradeSetMaster WHERE Id=@rId		
		SELECT 1 AS RESULT
	   END
	ELSE
		BEGIN
			SELECT -101 AS RESULT
		END
END TRY
BEGIN CATCH
		SELECT -1 AS RESULT
END CATCH
END
GO
PRINT N'Altering [sAssessment].[pMarkEntryAllSubjectGet]...';


GO
ALTER PROCEDURE [sAssessment].[pMarkEntryAllSubjectGet]
	 @rClassId int,
	 @rDivisionId int,
	 @rExamId 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,Number, ' + @cols + '
FROM
(
Select ISNULL(RD.Obtain,0) AS Obtain,ED.Id AS ExamDetailId,A.AcademicId,ED.ExamId,A.Name,A.RollNo,
A.Number,ISNULL(R.Id,0) AS ResultId
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.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,Number,Academicid'
--print (@query)
execute(@query)
		
END
GO
PRINT N'Altering [sAssessment].[pMarkEntryDetailAdd]...';


GO

ALTER PROCEDURE [sAssessment].[pMarkEntryDetailAdd]
	 
	        @rId bigint
           ,@rResultId bigint
		   ,@rExamDetailId int
		   ,@rObtain Decimal(6,2)
		   ,@rIsPresent bit
		   ,@rExamId int
		   ,@rAcademicId bigint
		   ,@rOrgId int
		  	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 
	 DECLARE @lMarkInDecimal bit
	 
Select @lMarkInDecimal=IsMarksInDecimal from sAssessment.tExamMaster Where Id = @rExamId And ClassId IN (SELECT ClassId FROM sStudent.tAcademic WHERE ID=@rAcademicId)
IF @lMarkInDecimal = 0
	BEGIN
		SET @rObtain = ROUND(@rObtain,0)
	END
IF NOT EXISTS(SELECT Id From sAssessment.tResultDetail Where ResultId IN (SELECT ID from sAssessment.tResult Where AcademicId=@rAcademicId AND ExamId=@rExamId) AND ExamDetailId=@rExamDetailId)	
BEGIN

	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAssessment.tResultDetail', 0, 1, 1,@outNextNumber = @lNextNumber output	
	 
	INSERT INTO [sAssessment].[tResultDetail]
			   (
			    [Id]
			   ,[ResultId] 
			   ,[ExamDetailId]
			   ,[Obtain]
			   ,[IsPresent]
			   )
		 VALUES
			   (
				@lNextNumber
			   ,@rResultId
			   ,@rExamDetailId
			   ,@rObtain
			   ,@rIsPresent
			   )
			  
		    SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION         
	END	 
	 ELSE
	 BEGIN
	 
	 Select @rId = Id From sAssessment.tResultDetail Where ResultId IN (SELECT ID from sAssessment.tResult Where AcademicId=@rAcademicId AND ExamId=@rExamId) AND ExamDetailId=@rExamDetailId
	
	    UPDATE  [sAssessment].[tResultDetail]
	    SET
	          ResultId=@rResultId
	         ,ExamDetailId=@rExamDetailId
			 ,Obtain=@rObtain
			 ,IsPresent=@rIsPresent
	      WHERE Id = @rId 	   
	      SELECT @rId 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].[pMarkEntryDetailAllSubjectAdd]...';


GO


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

DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml
BEGIN
	BEGIN TRY
	 BEGIN	
	 DECLARE @lNextNumber BIGINT 
	 DECLARE @lResultId BIGINT
	 DECLARE @lCount INT
	 DECLARE @lMarkInDecimal bit
	 Declare @lExamId BigInt
	 

	 
	 
		IF EXISTS (SELECT ResultDetailId FROM OPENXML (@loDoc, '/Table/ResultDetail', 1)
			WITH (ResultDetailId bigint) WHERE ResultDetailId = 0 )
		BEGIN
			EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAssessment.tResultDetail', 0, 1, 1,@outNextNumber = @lNextNumber output	
		END
		
		INSERT INTO sAssessment.tResultDetail
			( Id,ResultId,ExamDetailId,Obtain,IsPresent )
			SELECT		
				@lNextNumber + ROW_NUMBER() OVER(ORDER BY ExamDetailId) AS Id,
				sAssessment.fGetResultId(AcademicId,ExamId)AS ResultId,ExamDetailId,Obtain,IsPresent					
			FROM OPENXML (@loDoc, '/Table/ResultDetail', 1)
			WITH ( 					
					ExamDetailId int,Obtain decimal(5,2),IsPresent bit,ResultDetailId bigint,ResultId bigint,
					AcademicId bigint,ExamId int			
				  ) 
			 WHERE ResultId = 0 
				 
		SELECT @lCount = COUNT(1) FROM OPENXML (@loDoc, '/Table/ResultDetail', 1)
				 WITH ( Id int )
		SET @lNextNumber  = @lCount + @lNextNumber 
		
		EXECUTE sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sAssessment.tResultDetail', @rCurrentNumber = @lNextNumber 
		
		


		--- UPDATE RESULTDETAIL IF RESULTDETAILID EXIST
			UPDATE  sAssessment.tResultDetail
			SET
				ExamDetailId = A.ExamDetailId,
				Obtain = A.Obtain,
				IsPresent = A.IsPresent
			FROM
			(
			SELECT ExamDetailId,Obtain,IsPresent,ResultDetailId,ResultId 
			FROM OPENXML (@loDoc, '/Table/ResultDetail', 1)
			WITH ( 
					ExamDetailId int,
					Obtain Decimal(5,2),
					IsPresent bit,
					ResultDetailId bigint,
					ResultId Bigint		
				  )) A
			WHERE sAssessment.tResultDetail.ResultId = A.ResultId AND  sAssessment.tResultDetail.ExamDetailId = A.ExamDetailId
				
		Select Distinct @lExamId =  ExamId FROM OPENXML (@loDoc, '/Table/ResultDetail', 1) WITH (ExamId bigint)
		Select @lMarkInDecimal=IsMarksInDecimal from sAssessment.tExamMaster E WHERE E.Id = @lExamId
		
		IF @lMarkInDecimal = 0
		BEGIN		
			
		UPDATE  sAssessment.tResultDetail
			SET				
				Obtain = ROUND(A.Obtain,0)
			FROM
			(
			SELECT ExamDetailId,Obtain,ResultId 
			FROM OPENXML (@loDoc, '/Table/ResultDetail', 1)
			WITH ( 
					ExamDetailId int,
					Obtain Decimal(5,2),
					ResultId Bigint		
				  )) A
			WHERE sAssessment.tResultDetail.ResultId = A.ResultId AND  sAssessment.tResultDetail.ExamDetailId = A.ExamDetailId
		END		
		SELECT 1 AS Result	
	 END	
	
	END TRY
	
	BEGIN CATCH 
		
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sAssessment].[pMarkEntryMasterUpdate]...';


GO

ALTER PROCEDURE [sAssessment].[pMarkEntryMasterUpdate]	 
           @rExamId int,
           @rDivisionId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	
	UPDATE sAssessment.tResult SET TotalMarks= A.Maximum, 
	TotalObtain=A.Obtain,
	Percentage = (A.Obtain/A.Maximum)*100
	FROM 
	(SELECT  round(SUM(Obtain),0) AS Obtain,SUM(Maximum) AS Maximum,R.Id 
	FROM sAssessment.tResultDetail RD
	INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId AND RD.IsPresent =1
	INNER JOIN sAssessment.tExamMaster EM ON EM.Id = R.ExamId
	INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id AND ED.Id=RD.ExamDetailId
	INNER JOIN sStudent.vStudentAcademic SA ON SA.ClassId = EM.ClassId AND R.AcademicId=SA.AcademicId
	WHERE (R.ExamId = @rExamId OR @rExamId = 0) AND (SA.DivisionId=@rDivisionId or @rDivisionId=0) AND ED.IsIncludeInTotal=1
	GROUP BY R.Id ) AS A 	
	WHERE (ExamId = @rExamId OR @rExamId = 0) AND A.Id=sAssessment.tResult.Id
	
	--- Update Result Status
	
	UPDATE sAssessment.tResult SET ResultStatus='FAIL' WHERE ID IN (
	SELECT R.ID FROM sAssessment.tResultDetail RD 
	INNER JOIN sAssessment.tExamDetail ED ON RD.ExamDetailId = ED.Id
	INNER JOIN sAssessment.tResult R ON R.Id =RD.ResultId 
	INNER JOIN sStudent.tAcademic A ON R.AcademicId=A.Id
	AND R.ExamId = @rExamId AND A.DivisionId =@rDivisionId 	WHERE Obtain < Minimum)
	
	UPDATE sAssessment.tResult SET ResultStatus='PASS' WHERE ResultStatus <> 'FAIL'
	---
	
	SELECT 1 AS RESULT 
	
	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sAssessment].[pRptProgressCardGet]...';


GO

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

BEGIN 

	--SELECT 
	--	'' AS ACADEMICID,
	--	'' AS ExamDate,
	--	0 AS Maximum,
	--	0 AS Obtain,
	--	0 AS Percentage,
	--	'' AS ExamTopic,
	--	'' AS SubjectName,
	--	'' AS ExamGroup,
	--	'' AS StudentPhoto,
	--	'' AS ClassName,
	--	'' AS DivisionName,
	--	'' AS StudentName,
	--	'' AS RollNo,
	--  '' AS IsMarksInDecimal
		



	CREATE TABLE #tempProgressCard
	(
		Id int Identity,
		AcademicId Bigint,
		ClassSubjectId bigint,
		ExamDate Date,
		Obtain Decimal(6,2),
		Maximum Decimal(6,2),
		Percentage Decimal(6,2),
		ExamId int
	)
 
 DECLARE @query  AS NVARCHAR(MAX)
 set @query = 'INSERT INTO #tempProgressCard 
 SELECT	R.AcademicId,ED.ClassSubjectId,ED.ExamDate ,SUM(RD.Obtain) AS Obtain,SUM(ED.Maximum) AS Maximum,
 (SUM(RD.Obtain)/SUM(ED.Maximum))*100 AS PERCENTAGE,ED.ExamId
FROM sAssessment.tExamMaster EM INNER JOIN sAssessment.tResult R ON R.ExamId = EM.Id
INNER JOIN sAssessment.tResultDetail RD ON RD.ResultId = R.Id
INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId = EM.Id AND ED.Id = RD.ExamDetailId
INNER JOIN sAssessment.tExamGroupMaster EGM ON EGM.Id = EM.ExamGroupId
INNER JOIN sStudent.tAcademic AM ON AM.Id = R.AcademicId
WHERE RD.ISPRESENT = 1 AND EM.ClassId =' + CONVERT(NVARCHAR,@rClassId) + '
AND AM.DivisionId = ' + CONVERT(NVARCHAR(500),@rDivisionId) + '
AND EM.ExamGroupId IN (' + CONVERT(NVARCHAR(500),@rExamGroupIdStr) + ')
AND ED.ClassSubjectId IN (' + CONVERT(NVARCHAR(500),@rClassSubjectIdStr) + ')
AND ED.EXAMDATE >= ''' + CONVERT(NVARCHAR,@rFromDate) + ''' AND ED.EXAMDATE <= ''' + CONVERT(NVARCHAR,@rToDate) + '''
GROUP BY R.AcademicId,ED.ClassSubjectId,ED.ExamDate,ED.ExamId'
print @query
execute(@query)

SELECT
T.AcademicId,
T.ExamDate,
T.Maximum,T.Obtain,T.Percentage,
CASE WHEN ED.ExamTopic = '0' THEN '' ELSE ED.ExamTopic  END AS ExamTopic,
CS.SubjectCode AS SubjectName,
EGM.Title AS ExamGroup,
'' as StudentPhoto , 
SF.ClassName,
SF.DivisionName,
SF.Name AS StudentName,SF.RollNo,
EM.IsMarksInDecimal
FROM #tempProgressCard T 
INNER JOIN sAssessment.tExamMaster EM on EM.Id=T.ExamId
INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId = T.ExamId AND EM.Id=ED.ExamId AND T.ExamDate = ED.ExamDate
INNER JOIN sAssessment.tExamGroupMaster EGM ON EGM.Id = EM.ExamGroupId
INNER JOIN sSetup.vClassSubject CS ON CS.ClassSubjectId = ED.ClassSubjectId AND CS.ClassSubjectId=T.ClassSubjectId 
INNER JOIN sStudent.vStudentFull SF ON SF.AcademicId	= T.AcademicId AND SF.StatusId=1
Order By SF.RollNo,CS.OrderIndex,T.ExamDate Desc
DROP TABLE #tempProgressCard

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


GO

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

BEGIN 
	--SELECT 
	--    '' AS Builder1,
	--    '' AS Builder2,
	--	'' AS AcademicId ,
	--	'' AS ExamName ,
	--	'' AS StudCode ,
	--	'' AS StudentName ,
	--	'' AS RollNo ,
	--	'' AS ResultStatus ,
	--	'' AS ClassName ,		
	--	'' AS Division ,
	--	'' AS TotalMark ,
	--	'' AS TotalObtain ,
	--	'' AS Percentage ,
	--	'' AS RankNumber ,
	--	'' AS ResultGrade ,
	--	'' AS SubjectName ,
	--	'' AS SubjectCode ,
	--	'' AS ClassSubjectID ,
	--	'' AS SubjectGrade,
	--	'' AS MaximumMark1 ,
	--	'' AS Exam1Name ,
	--	'' AS SubjectGrade1 ,
	--	'' AS Obtain1 ,
	--	'' AS MaximumMark2 ,
	--	'' AS Exam2Name ,
	--	'' AS SubjectGrade2 ,
	--	'' AS Obtain2 ,
		
	--	'' AS MaximumMark3 ,
	--	'' AS Exam3Name ,
	--	'' AS SubjectGrade3 ,
	--	'' AS Obtain3 ,
		
	--	'' AS MaximumMark4 ,
	--	'' AS Exam4Name ,
	--	'' AS SubjectGrade4 ,
	--	'' AS Obtain4 ,
		
	--	'' AS MaximumMark5 ,
	--	'' AS Exam5Name ,
	--	'' AS SubjectGrade5 ,
	--	'' AS Obtain5 ,
		
	--	'' AS MaximumMark6 ,
	--	'' AS Exam6Name ,
	--	'' AS SubjectGrade6 ,
	--	'' AS Obtain6 ,

	--	'' AS column_visible,
	--  '' AS IsMarksInDecimal

	CREATE TABLE #TempAllExam
	(
		AcademicId bigint,
		ExamName varchar(50),
		StudCode Varchar(10),
		StudentName varchar(50),
		RollNo int,
		ResultStatus varchar(10),
		ClassName Varchar(10),		
		Division Varchar(10),
		TotalMark decimal(6,2),
		TotalObtain decimal(6,2),
		Percentage decimal(6,2),
		RankNumber int,
		ResultGrade Varchar(5),
		SubjectName Varchar(30),
		SubjectCode varchar(10),
		ClassSubjectID int,
		SubjectGrade Varchar(10),
		
		MaximumMark1 decimal(6,2),
		Exam1Name nvarchar(50),
		SubjectGrade1 Varchar(10),
		Obtain1 decimal(6,2),
		
		MaximumMark2 decimal(6,2),
		Exam2Name nvarchar(50),
		SubjectGrade2 Varchar(10),
		Obtain2 decimal(6,2),
		
		MaximumMark3 decimal(6,2),
		Exam3Name nvarchar(50),
		SubjectGrade3 Varchar(10),
		Obtain3 decimal(6,2),
		
		MaximumMark4 decimal(6,2),
		Exam4Name nvarchar(50),
		SubjectGrade4 Varchar(10),
		Obtain4 decimal(6,2),
		
		MaximumMark5 decimal(6,2),
		Exam5Name nvarchar(50),
		SubjectGrade5 Varchar(10),
		Obtain5 decimal(6,2),
		
		MaximumMark6 decimal(6,2),
		Exam6Name nvarchar(50),
		SubjectGrade6 Varchar(10),
		Obtain6 decimal(6,2),
		IsMarksInDecimal bit
	)	    	
	INSERT INTO  #TempAllExam 
	(
	AcademicId,ExamName,StudCode ,StudentName ,RollNo ,ResultStatus ,ClassName ,Division ,
	TotalMark ,TotalObtain ,Percentage ,RankNumber ,ResultGrade ,
	SubjectName ,SubjectCode,ClassSubjectID,SubjectGrade,IsMarksInDecimal )
	SELECT 
	A.Id,EM.Name AS EXAMNAME,
	StuM.Code AS StudCode,StuM.FirstName + ' ' + 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,
	SM.Title AS SubjectName,SM.Code AS SubjectCode,ED.ClassSubjectId,RD.SubjectGrade,
	EM.IsMarksInDecimal
FROM 
	sAssessment.tResultDetail RD
	INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
	INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId			
	INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
	INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId					 
	INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
	INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
	INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
	INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
	WHERE EM.ClassId=@rClassId And  EM.Id = @rExamId 
	Order By ED.DisplayOrder

	create TABLE #tempcombineExam
	(	Id int IDENTITY,
		ExamID int)
	INSERT INTO #tempcombineExam (ExamID) 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
	
	while (@lCount > 0)
	begin
		select @lSubExamId = ExamID from #tempcombineExam Where Id = @lCount
			
		set @query ='update T set MaximumMark' + convert(nvarchar(15),@lCount)+ '=ED.Maximum,
					Exam' + convert(nvarchar(15),@lCount)+ 'Name=EM.Name,
					SubjectGrade' + convert(nvarchar(15),@lCount)+ '=RD.SubjectGrade,
					Obtain' + convert(nvarchar(15),@lCount)+'=RD.Obtain From
						sAssessment.tResultDetail RD
						INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						INNER JOIN sAssessment.tExamCombine EC ON EC.SubExamId = EM.Id
						INNER JOIN 	#TempAllExam  T ON T.ClassSubjectID=ED.ClassSubjectId
						WHERE EM.ClassId=' + convert(nvarchar(15), @rClassId) +' And T.AcademicId = R.AcademicId
						AND EC.SubExamId =' + convert(nvarchar(15), @lSubExamId)  
		execute(@query)
--		print (@query)
		set @lCount = @lCount -1
	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(15),@lCount1)+ 'Name'
		execute(@query)
		set @query ='ALTER TABLE #TempAllExam DROP COLUMN SubjectGrade' + convert(nvarchar(15),@lCount1)
		execute(@query)		
		set @query ='ALTER TABLE #TempAllExam DROP COLUMN Obtain' + convert(nvarchar(15),@lCount1)
		execute(@query)
		SET @lCount1 = @lCount1 + 1
	END
	
	SELECT @rBuilder1,@rBuilder2,1 AS column_visible ,* 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
GO
PRINT N'Altering [sAssessment].[pRptResultWithSubjectListGet]...';


GO


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

BEGIN 

	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			EM.Name AS Exam,
			StuM.Code,
			StuM.FirstName+' '+StuM.LastName AS Name,
			A.RollNo,
			R.AcademicId,
			RD.Obtain,
			R.ResultStatus,
			CM.DisplayTitle AS Class,
			DM.DisplayTitle AS Division,
			R.TotalMarks,
			R.TotalObtain,
			R.Percentage,
			R.RankNumber,
			R.ResultGrade,
			SM.Title AS ClassSubject,
			RD.Id AS ResultDetailId,
			R.Id AS ResultId,
			CS.Id AS SubjectId,
			ED.Maximum,
			RD.SubjectGrade,
			EM.IsMarksInDecimal,
			--SM.OrderIndex AS SubjectCode,
			SM.Code AS SubjectCode,
			SM.OrderIndex AS SubjectOrderIndex
			
      
	FROM 
			sAssessment.tResultDetail RD
			INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
			INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
			INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId			
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId					 
			INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
			INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
			
	WHERE 
			
		EM.BatchId = @rBatchId 
		AND (A.ClassId=@rClassId OR @rClassId=0) 
		AND ((SM.Id=@rSubjectId) OR (@rSubjectId=0))
		AND (A.DivisionId=@rDivisionId OR @rDivisionId=0)
		AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((R.RankNumber >= @rFromRank) OR (@rFromRank=0))
		AND ((R.RankNumber <= @rToRank) OR (@rToRank=0))
		AND ((R.ResultGrade = @rGrade) OR (@rGrade=''))
		
		AND (R.ExamId = @rExamId)
		AND ((StuM.Code=@rCode) OR (@rCode=''))
		
		order by A.RollNo,CS.OrderIndex 
		--AND A.id = 1005000000007
		
END
GO
PRINT N'Altering [sAssessment].[pViewResultGet]...';


GO
ALTER PROCEDURE [sAssessment].[pViewResultGet]
	 @rClassId int,
	 @rDivisionId int,
	 @rExamId 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,Number,
TotalMarks,TotalObtain,ResultStatus,ResultGrade,RankNumber,Percentage,Percentile,
IsRankNo,IsGrade,IsPercentage,IsPercentile,
 ' + @cols + '
FROM
(
Select ISNULL(RD.Obtain,0) AS Obtain,ED.Id AS ExamDetailId,A.AcademicId,ED.ExamId,A.Name,A.RollNo,
A.Number,ISNULL(R.Id,0) AS ResultId,
ISNULL(R.TotalMarks,0) AS TotalMarks,ISNULL(R.TotalObtain,0) AS TotalObtain,ISNULL(R.ResultStatus,'''') AS ResultStatus,
ISNULL(R.ResultGrade,'''') AS ResultGrade,ISNULL(R.RankNumber,0) AS RankNumber,ISNULL(R.Percentage,0) AS Percentage,ISNULL(R.Percentile,0) AS Percentile,
IsRankNo,IsGrade,IsPercentage,IsPercentile
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.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,Number,Academicid'
--print (@query)
execute(@query)
		
END
GO
PRINT N'Altering [sAttendance].[pRptStudentMonthlyRegisterGet]...';


GO

ALTER PROCEDURE [sAttendance].[pRptStudentMonthlyRegisterGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rOrgId smallint,
	 @rBatchId int,
	 @rClassId int,
	 @rDivisionId int,
	 @rAttendanceTypeId tinyint,
	 @rSubjectId int,
	 @rForYear smallint,
	 @rForMonth tinyint
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			SA.AcademicId,
			SA.ClassId,
			SA.DivisionId,
			SA.ClassName,
			SA.DivisionName,
			SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
			SA.Code,
			SA.RollNo,			
			SA.Name,
			MR.ForMonth,
			MR.ForYear,
			DateName( month , DateAdd( month , MR.ForMonth , -1 ))+' - '+Convert(nvarchar(4),MR.ForYear) AS ForMonthYear,
			MR.TotalCount,
			MR.PresentCount,
			MR.AbsentCount,
			MR.AveragePresence,
			MR.AbsentDays,
			ISNULL(SO.DateOfBirth,NULL) AS DateOfBirth,
			SM.Title AS SubjectName,
			SA.DivisionOrder
			 
			
	FROM 
			sStudent.vStudentAcademic SA
        INNER JOIN sStudent.tStudentOther SO ON SA.StudentId = SO.StudentId 			
		INNER JOIN sAttendance.tMonthlyRegister MR ON MR.AcademicId=SA.AcademicId
		LEFT JOIN sSetup.tSubjectMaster SM ON SM.Id=MR.SubjectId
	WHERE 
			(SA.OrgId=@rOrgId)
		AND	(SA.BatchId = @rBatchId) 
		AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		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))
		AND (SA.StatusId != 3)
END
GO
PRINT N'Altering [sAttendance].[pRptStudentwiseAbsentDaysGet]...';


GO

ALTER PROCEDURE [sAttendance].[pRptStudentwiseAbsentDaysGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rOrgId smallint,
	 @rBatchId int,
	 @rClassId int,
	 @rDivisionId int,
	 @rAttendanceTypeId tinyint,
	 @rSubjectId int,
	 @rFromDate date,
	 @rToDate date
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

	SELECT 
			DISTINCT(SA.AcademicId),
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			SA.ClassId,
			SA.DivisionId,
			SA.ClassName,
			SA.DivisionName,
			SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
			SA.Code,
			SA.RollNo,			
			SA.Name,		
			sAttendance.fAttendanceGet(SA.AcademicId,@rAttendanceTypeId,@rSubjectId,@rFromDate,@rToDate) AS AttendanceDate,
			AbsentCount=(SELECT COUNT(1) FROM sAttendance.tStudentRegister SR1 
				WHERE SR1.AcademicId=SA.AcademicId 
				AND ((SR1.AttendanceTypeId=@rAttendanceTypeId) OR (@rAttendanceTypeId=0))
				AND ((SR1.SubjectId=@rSubjectId) OR (@rSubjectId=0))
				AND ((SR1.AttendanceDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
				AND ((SR1.AttendanceDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
				AND SR1.IsPresent=0),
		   SA.DivisionOrder
	FROM 
			sStudent.vStudentAcademic SA
		INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.AcademicId
	WHERE 
			(SA.OrgId=@rOrgId)
		AND	(SA.BatchId = @rBatchId) 
		AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((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 = 0)
		AND (SA.StatusId != 3)
		GROUP BY SA.AcademicId,SA.ClassId,SA.DivisionId,SA.ClassName,SA.DivisionName,SA.Code,SA.RollNo,SA.Name,SA.DivisionOrder
END
GO
PRINT N'Altering [sCertificate].[pBonafideAdd]...';


GO

ALTER PROCEDURE [sCertificate].[pBonafideAdd]
			@rId bigint
	       ,@rAcademicId bigint
	       ,@rNumber int
	       ,@rBonafideDate date
	       ,@rCreatedUserId bigint
	       ,@rOrgId int
           	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

		--BEGIN TRY
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT
			
		--IF(@rId = 0)	
		--BEGIN
		--If Exists(select Id from sCertificate.tBonafide where AcademicId=@rAcademicId)
		--	BEGIN
		--	select -103 as Result
		--	RETURN
		--END
		
		--EXECUTE sCommon.pPrefixSetupNextNumberGet @rOrgId = @rOrgId, @rPrefixFunctionalityId = 2003,@rStoreLocationId = 0, @rNextNumber  = @rNumber OUTPUT

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

		--IF @rNumber = '-300'
	 -- BEGIN
		--SELECT -300 AS Result, '' AS Number, 0 AS Id 
		--RETURN
	 -- END
	  --END
	  IF(@rId = 0)	
		BEGIN
			SELECT @rNumber = ISNULL(MAX(Number),0) + 1 FROM sCertificate.tBonafide WHERE OrgId=@rOrgId
			EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sCertificate.tBonafide', 0, 1, 1,@outNextNumber = @lNextNumber output
			
			INSERT INTO sCertificate.tBonafide
			(
				Id
			   ,AcademicId
			   ,Number
			   ,BonafideDate
			   ,OrgId
			   ,CreatedUserId
			   ,CreatedDateTime
			)
			VALUES
			(	@lNextNumber
			   ,@rAcademicId
			   ,@rNumber
			   ,@rBonafideDate
			   ,@rOrgId
			   ,@rCreatedUserId
			   ,sCommon.fGetDate() 
			)
		END
		
		ELSE
		 BEGIN
		-- If  Exists(select Id from sCertificate.tBonafide where AcademicId=@rAcademicId AND Id<>@rId)
		--Begin
		--	select -103 as Result
		--	RETURN
		--End
		 SET @lNextNumber = @rId
			UPDATE  sCertificate.tBonafide
			SET
				AcademicId=@rAcademicId,
				BonafideDate=@rBonafideDate,
				UpdatedUserId=@rCreatedUserId,
				UpdatedDateTime=sCommon.fGetDate()
		      
		      
			  WHERE Id = @rId
			  
		 END  	
	SELECT @lNextNumber AS Result
	COMMIT TRANSACTION
	--END TRY
	
	--BEGIN CATCH 
	--	ROLLBACK TRANSACTION
	--	SELECT -1 AS Result
	--END CATCH	
	
END
GO
PRINT N'Altering [sCertificate].[pRptBonafiedCertificateGet]...';


GO


ALTER PROCEDURE [sCertificate].[pRptBonafiedCertificateGet]
	 
	 @rOrgId smallint,
	 @rBatchId int,
	 @rFromNo nvarchar(20),
	 @rToNo nvarchar(20),
	 @rNumber nvarchar(20),
	 @rAcademicId bigint,
	 @rClassId int,
	 @rDivisionId int,
	 @rBonafiedDate datetime
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 

	SELECT 
			B.Id,
			B.Number,
			B.AcademicId,
			SM.Code,
			SM.FirstName+' '+SM.MiddleName+' '+SM.LastName AS Name,
			CM.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
	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
			
	WHERE 
			A.OrgId=@rOrgId
		AND	A.BatchId = @rBatchId 
		AND ((A.ClassId=@rClassId) OR (@rClassId=0))
		AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		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.AcademicId=@rAcademicId) OR (@rAcademicId=0))
		--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]
	 
	 @rOrgId smallint,
	 @rBatchId int,
	 @rFromNo nvarchar(20),
	 @rToNo nvarchar(20),
	 @rNumber nvarchar(20),
	 @rAcademicId bigint,
	 @rClassId int,
	 @rDivisionId int,
	 @rCharacterDate datetime
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 

	SELECT 
			C.Id,
			C.AcademicId,
			SM.Code,
			SM.FirstName+' '+SM.MiddleName+' '+SM.LastName AS Name,
			CM.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
	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
	WHERE 
			A.OrgId=@rOrgId
		AND	A.BatchId = @rBatchId 
		AND ((A.ClassId=@rClassId) OR (@rClassId=0))
		AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((C.characterDate=@rCharacterDate) OR (ISNULL(@rCharacterDate,'')=''))
		AND ((C.Number=@rNumber) OR (@rNumber=''))
		AND ((C.Number >= @rFromNo) OR (@rFromNo=''))
		AND ((C.Number <= @rToNo) OR (@rToNo=''))
		AND ((C.AcademicId=@rAcademicId) OR (@rAcademicId=0))
		--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]
	 
	 @rOrgId smallint,
	 @rBatchId int,
	 --@rNumber nvarchar(20),
	 @rFromNo nvarchar(20),
	 @rToNo nvarchar(20),
	 @rAcademicId bigint,
	 @rClassId int,
	 @rDivisionId int,
	 @rFromDate date,
	 @rToDate date
	 --@rExamYear nvarchar(20),
	 --@rExamCentre nvarchar(100),
	 --@rFirstTrialDate datetime,
	 --@rTrial nvarchar(100)
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 

	SELECT 
			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
	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 
	WHERE 
			A.OrgId=@rOrgId
		AND	A.BatchId = @rBatchId 
		AND ((A.ClassId=@rClassId) OR (@rClassId=0))
		AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((FT.FirstTrialDate>=@rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((FT.FirstTrialDate<=@rToDate) OR (ISNULL(@rToDate,'')=''))
		AND ((FT.Number >= @rFromNo) OR (@rFromNo=''))
		AND ((FT.Number <= @rToNo) OR (@rToNo=''))
		AND ((FT.AcademicId=@rAcademicId) OR (@rAcademicId=0))
		--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]
	 
	 @rOrgId int,
	 @rBatchId int,
	 @rFromNo int,
	 @rToNo int,
	 @rAcademicId bigint,
	 --@rNumber nvarchar(20),
	 @rClassId int,
	 @rDivisionId int
	 --@rIsTransferCerti bit
	 --@rLCDate datetime,
	 --@rLeftDate datetime,
	 --@rLCCopy tinyint,
	 --@rLCBookNumber nvarchar(20)
	 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 

	SELECT 
			--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,
			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(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,
			A.RollNo,
			DM.OrderIndex AS DivisionOrder
			--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.tAcademic A ON L.AcademicId=A.Id
			LEFT JOIN sStudent.tStudentAdmission SA ON SA.StudentId=A.StudentId
			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 
			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 A.DivisionId = DM.Id  
			INNER JOIN sSetup.tClassMaster CMS ON CMS.Id= DM.ClassId 
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId=A.StudentId
			LEFT JOIN sCommon.tNationalityMaster NM ON NM.Id=SO.NationalityId
			--LEFT JOIN sSetup.tClassSubject CS ON CS.ClassId=A.ClassId
			--LEFT JOIN sSetup.tSubjectMaster SubM ON SM.Id=CS.SubjectId
	WHERE 
		L.OrgId=@rOrgId
		AND	A.BatchId = @rBatchId 
		--AND ((L.LCNumber=@rNumber) OR (@rNumber=''))
		AND ((L.LCNumber >= @rFromNo) OR (@rFromNo=0))
		AND ((L.LCNumber <= @rToNo) OR (@rToNo=0))
		AND ((L.AcademicId=@rAcademicId) OR (@rAcademicId=0))
		--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 ((A.ClassId=@rClassId) OR(@rClassId=0))
		AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		--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].[pOrganizationSetupAdd]...';


GO
ALTER PROCEDURE [sCommon].[pOrganizationSetupAdd]
    @rOrgId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

SET @rOrgId = @rOrgId
DECLARE @lCreatedDateTime DATETIME
SET @lCreatedDateTime =  GETDATE()

DECLARE @lCreatedUserId Int
SET @lCreatedUserId = 1
DECLARE @lOrgGroupId smallint
DECLARE @lOrgGroupBatchId int 
BEGIN TRY
BEGIN TRANSACTION


 SELECT @lOrgGroupId=OrgGroupId from sSetup.tOrganizationMaster where Id=@rOrgId
 
 SELECT @lOrgGroupBatchId=ISNULL(MIN(Id),(Convert(nvarchar(10),Convert(nvarchar(10),@lOrgGroupId))+'00000')+1) 
	FROM sSetup.tOrgGroupBatchMaster WHERE OrgGroupId=@lOrgGroupId
 
 
 INSERT INTO [sCommon].[tTableRowId]
           ([OrgId]
           ,[TableTitle]
           ,[CurrentNumber]
           ,[Seed]
           ,[Increment])
SELECT
		   @rOrgId
		  ,[TableTitle]
		  
		  ,CASE 
      WHEN IdDataType = 'int' THEN sCommon.fGetIntIdForOrg(CurrentNumber,@rOrgId) 
      WHEN IdDataType = 'bigint' THEN sCommon.fGetbigIntIdForOrg(CurrentNumber,@rOrgId )
		END 
		
		  ,CASE 
      WHEN IdDataType = 'int' THEN sCommon.fGetIntIdForOrg(CurrentNumber,@rOrgId) 
      WHEN IdDataType = 'bigint' THEN sCommon.fGetbigIntIdForOrg(CurrentNumber,@rOrgId )
		END  
		   ,1
	  FROM [sCommon].[tTableRowIdMaster] where 
	  (tableType = 'Non Static' or tableType = '100Static' )
	  AND iddatatype <> '' AND IdScope <> 'OrgGroup'
	  
	
--	INSERT INTO [sCommon].[tTableRowId]
--           ([OrgId]
--           ,[TableTitle]
--           ,[CurrentNumber]
--           ,[Seed]
--           ,[Increment])
--SELECT
--		   0
--		  ,[TableTitle]		  
--		  ,CurrentNumber		
--		  ,CurrentNumber
--		  ,1
--	  FROM [sCommon].[tTableRowIdMaster] where 
--	  (tableType =   '100StaticCommon') 
--	   AND IdScope <> 'OrgGroup'  
 
 INSERT INTO [sSetup].[tBatchMaster]
           ([Id]
           ,[Code]
           ,[Title]
           ,[OrgId]
           ,[IsHistory]
           ,[IsActive]
           ,[IsObsolete]
           ,[OrderIndex]
           ,[FromDate]
           ,[ToDate]
           ,[OrgGroupBatchId]
           ,[CreatedUserId]
           ,[CreatedDateTime]
           ,[UpdatedUserId]
           ,[UpdatedDateTime])
     
      SELECT sCommon.fGetIntIdForOrg(1,@rOrgId)
           ,Code
           ,Title
           ,@rOrgId
           ,0
           ,1
           ,0
           ,1
           ,FromDate
           ,ToDate
           ,@lOrgGroupBatchId
		  ,@lCreatedUserId
		  ,@lCreatedDateTime
		  ,@lCreatedUserId
		  ,@lCreatedDateTime
           FROM [sSetup].[tOrgGroupBatchMaster] WHERE  Id =  @lOrgGroupBatchId
 
  


 --INSERT INTO [sIp].[tStoreLocationMaster]
 --         ([OrgId]
 --          ,[Id]
 --          ,[Code]
 --          ,[Title]
 --          ,[IsObsolete]
 --          ,[CreatedUserId]
 --          ,[CreatedDateTime]
 --          ,[UpdatedUserId]
 --          ,[UpdatedDateTime]
 --          ,[LocationId]
 --          ,[IsShowDependent])
	--SELECT
	--   @rOrgId
 --     ,sCommon.fGetIntIdForOrg(Id,@rOrgId)
 --     ,[Code]
 --     ,[Title]
 --     ,[IsObsolete]
 --     ,@lCreatedUserId
	--  ,@lCreatedDateTime
	--  ,@lCreatedUserId
	--  ,@lCreatedDateTime
 --     ,sCommon.fGetIntIdForOrg(LocationId,@rOrgId)
 --     ,[IsShowDependent]
 -- FROM [sIp].[tStoreLocationMaster] WHERE OrgId =1
  
  
  
--  INSERT INTO  [sCommon].[tCountryMaster]
--           ([OrgId]
--           ,[Title]
--           ,[Nationality]
--           ,[IsObsolete]
--           ,[CreatedUserId]
--           ,[CreatedDateTime]
--           ,[UpdatedUserId]
--           ,[UpdatedDateTime]
--           ,[Id]
--           ,[IsShow])
--     SELECT
--            @rOrgId
--           ,[Title]
--           ,[Nationality]
--           ,[IsObsolete]
--		  ,@lCreatedUserId
--		  ,@lCreatedDateTime
--		  ,@lCreatedUserId
--		  ,@lCreatedDateTime
--           ,sCommon.fGetIntIdForOrg(Id,@rOrgId)
--           ,[IsShow]
--FROM [sCommon].[tCountryMaster] WHERE  OrgId = 1



 --INSERT INTO [sCommon].[tLocationMaster]
 --          ([Id]
 --          ,[OrgId]
 --          ,[Code]
 --          ,[Title]
 --          ,[StreetOne]
 --          ,[StreetTwo]
 --          ,[StreetThree]
 --          ,[CityName]
 --          ,[StateName]
 --          ,[CountryName]
 --          ,[ZipCode]
 --          ,[PhoneNo]
 --          ,[FaxNo]
 --          ,[NameOfOccupier]
 --          ,[AddressOfOccupier]
 --          ,[SmallAddress1]
 --          ,[SmallAddress2]
 --          ,[RegistrationNumber]
 --          ,[LicenceNumber]
 --          ,[EsicNumber]
 --          ,[EsicAddress1]
 --          ,[EsicAddress2]
 --          ,[NatureOfIndustry]
 --          ,[ByProduct]
 --          ,[DangerousOperation]
 --          ,[NatureOfTest]
 --          ,[NatureOfTestNonHazardous]
 --          ,[RowMaterialUsed]
 --          ,[HazardousProcess]
 --          ,[Cmo]
 --          ,[NicNumber]
 --          ,[IsObsolete]
 --          ,[CreatedUserId]
 --          ,[CreatedDateTime]
 --          ,[UpdatedUserId]
 --          ,[UpdatedDateTime]
 --          ,[CountryId]
 --          ,[StateId])
           
 -- SELECT sCommon.fGetIntIdForOrg(Id,@rOrgId)
 --     ,@rOrgId
 --     ,[Code]
 --     ,[Title]
 --     ,[StreetOne]
 --     ,[StreetTwo]
 --     ,[StreetThree]
 --     ,[CityName]
 --     ,[StateName]
 --     ,[CountryName]
 --     ,[ZipCode]
 --     ,[PhoneNo]
 --     ,[FaxNo]
 --     ,[NameOfOccupier]
 --     ,[AddressOfOccupier]
 --     ,[SmallAddress1]
 --     ,[SmallAddress2]
 --     ,[RegistrationNumber]
 --     ,[LicenceNumber]
 --     ,[EsicNumber]
 --     ,[EsicAddress1]
 --     ,[EsicAddress2]
 --     ,[NatureOfIndustry]
 --     ,[ByProduct]
 --     ,[DangerousOperation]
 --     ,[NatureOfTest]
 --     ,[NatureOfTestNonHazardous]
 --     ,[RowMaterialUsed]
 --     ,[HazardousProcess]
 --     ,[Cmo]
 --     ,[NicNumber]
 --     ,[IsObsolete]
 --   ,@lCreatedUserId
 -- ,@lCreatedDateTime
 -- ,@lCreatedUserId
 -- ,@lCreatedDateTime
 --     ,sCommon.fGetIntIdForOrg(CountryId,@rOrgId) 
 --     ,sCommon.fGetIntIdForOrg(StateId,@rOrgId) 
 -- FROM [sCommon].[tLocationMaster]  where OrgId=1   	




--INSERT INTO  [sCommon].[tStateMaster]
--           ([OrgId]
--           ,[CountryId]
--           ,[Title]
--           ,[CreatedUserId]
--           ,[CreatedDateTime]
--           ,[UpdatedUserId]
--           ,[UpdatedDateTime]
--           ,[IsObsolete]
--           ,[Id]
--           ,[IsShow])
--     sELECT
--			@rOrgId
--           ,sCommon.fGetIntIdForOrg(CountryId,@rOrgId)
--           ,[Title]
--		   ,@lCreatedUserId
--		   ,@lCreatedDateTime
--		   ,@lCreatedUserId
--		   ,@lCreatedDateTime
--           ,[IsObsolete]
--           ,sCommon.fGetIntIdForOrg(Id,@rOrgId)
--           ,[IsShow] 
--FROM [sCommon].[tStateMaster] wHERe OrgId = 1

--INSERT INTO sSecurity.tModulePermission
--           ([OrgId]
--           ,[ModuleId]
--			)
--			Values
--			(
--		   @rOrgId
--		   ,1
--		   )
 
 --INSERT INTO [sSecurity].[tPermission]
 --          ([TaskId]
 --          ,[RoleId]
 --          ,[Permission]
 --          ,[CreatedUserId]
 --          ,[CreatedDateTime]
 --          ,[UpdatedUserId]
 --          ,[UpdatedDateTime]
 --          ,[IsObsolete]
 --          ,[OrgId])
	--SELECT
	--      [TaskId]
 --          ,sCommon.fGetIntIdForOrg(RoleId,@rOrgId)
 --          ,[Permission]
 --          ,@lCreatedUserId
	--	   ,@lCreatedDateTime
	--	   ,@lCreatedUserId
	--       ,@lCreatedDateTime
 --          ,[IsObsolete]
 --          ,@rOrgId
	--  FROM [sSecurity].[tPermission] WHERE RoleId = 2 AND OrgId = 1
  
 
 IF (  @lOrgGroupId = @rOrgId)
 BEGIN
	  INSERT INTO sSecurity.tUser 
		   ([Id]
           ,[DisplayTitle]
           ,[LoginTitle]
           ,[LoginPassword]
           ,[LastLockOutDate]
           ,[NumberOfLogonAttempt]
           ,[IsObsolete]
           ,[CreatedUserId]
           ,[CreatedDateTime]
           ,[UpdatedUserId]
           ,[UpdatedDateTime]
           --,[EmployeeId]
           ,[SessionId]
           ,[OrgId]
           ,[IsCommon])		  
	SELECT 
		   sCommon.fGetBigIntIdForOrg(Id,@rOrgId)
		  ,[DisplayTitle]
		  ,[LoginTitle]
		  ,[LoginPassword]
		  ,@lCreatedDateTime
		  ,[NumberOfLogonAttempt]
		  ,[IsObsolete]
		  ,@lCreatedUserId
		  ,@lCreatedDateTime
		  ,@lCreatedUserId
		  ,@lCreatedDateTime
		  --,sCommon.fGetIntIdForOrg(1,@rOrgId)
		  ,[SessionId]
		  ,@rOrgId
		  ,1
	  FROM [sSecurity].[tUser] WHERE Id < 4 AND OrgId=1
	  
	  
	  --OrgId is not used
INSERT INTO [sSecurity].[tUserRole]
           (
            [RoleId]
           ,[UserId]
           ,[IsObsolete]
           ,[IsPrimary]
           ,[CreatedUserId]
           ,[CreatedDateTime]
           ,[UpdatedUserId]
           ,[UpdatedDateTime]
           )
SELECT 
		   sCommon.fGetIntIdForOrg(2,@lOrgGroupId)
		  ,sCommon.fGetBigIntIdForOrg(3,@lOrgGroupId)
		  ,0
		  ,1
		  ,@lCreatedUserId
		  ,@lCreatedDateTime
		  ,@lCreatedUserId
		  ,@lCreatedDateTime
	  
END
  
 --INSERT INTO [sSecurity].[tUserLocation]
 --          ([StoreLocationId]
 --          ,[UserId]
 --          ,[CreatedUserId]
 --          ,[CreatedDateTime])
           
 --  select 
	--sCommon.fGetIntIdForOrg(Id,@rOrgId),
	--sCommon.fGetBigIntIdForOrg(3,@rOrgId)
	--,@lCreatedUserId
	--,@lCreatedDateTime
 --from sIp.tStoreLocationMaster where OrgId=1   	
 
 

	  --OrgId is not used
INSERT INTO sSecurity.tUserOrganization
           (
            [OrgId]
           ,[UserId]
           
           )
SELECT 
		   @rOrgId
		  ,sCommon.fGetBigIntIdForOrg(3,@lOrgGroupId)
		   


INSERT INTO [sConfig].[tColorLegendDetail]
           ([OrgId]
           ,[Id]
           ,[Title]
           ,[ColorLegendId]
           ,[configSettingId])
	SELECT
		   @rOrgId
		  ,sCommon.fGetIntIdForOrg(Id,@rOrgId)
		  ,[Title]
		  ,[ColorLegendId]
		  ,[configSettingId]
	  FROM [sConfig].[tColorLegendDetail] WHERE OrgId=1
	  
	  
 
--INSERT INTO [sCommon].[tReligionMaster]
--           ([Id]
--           ,[Code]
--           ,[Title]
--           ,[IsObsolete]
--           ,[CreatedUserId]
--           ,[CreatedDateTime]
--           ,[UpdatedUserId]
--           ,[UpdatedDateTime]
--           ,[OrgGroupId])
--     SELECT      
--			 sCommon.fGetIntIdForOrg(Id,@rOrgId)
--			,[Code]
--			,[Title]
--            ,[IsObsolete]
--			,@lCreatedUserId
--		    ,@lCreatedDateTime
--		    ,@lCreatedUserId
--		    ,@lCreatedDateTime
--		    ,@rOrgId
--     FROM [sCommon].[tReligionMaster] WHERE OrgId=1






INSERT INTO [sHrm].[tEmployeeTypeMaster]
           ([OrgId]
           ,[Id]
           ,[Code]
           ,[Title]
           ,[IsObsolete]
           ,[CreatedUserId]
           ,[CreatedDateTime]
           ,[UpdatedUserId]
           ,[UpdatedDateTime])			
	 SELECT
			@rOrgId
		   ,sCommon.fGetIntIdForOrg(Id,@rOrgId)
		   ,[Code]
		   ,[Title]
           ,[IsObsolete]
		   ,@lCreatedUserId
		   ,@lCreatedDateTime
		   ,@lCreatedUserId
		   ,@lCreatedDateTime
     FROM [sHrm].[tEmployeeTypeMaster] WHERE OrgId=1
     
--INSERT INTO sAccounting.tLedgerGroupMaster
--           (Id,
--           Code,
--           Title,
--           IsObsolete,
--           LedgerMainGroupId,
--           AccountingYearId,
--           CreatedUserId,
--           CreatedDateTime,
--           UpdatedUserId,
--           UpdatedDateTime,
--           OrgId
--           )
--	SELECT
--		   sCommon.fGetIntIdForOrg(Id,@rOrgId),
--		   Code,
--		   Title,
--		   IsObsolete,
--		   sCommon.fGetIntIdForOrg(LedgerMainGroupId,@rOrgId),
--		   sCommon.fGetIntIdForOrg(AccountingYearId,@rOrgId),
--		   @lCreatedUserId,
--		   @lCreatedDateTime,
--		   @lCreatedUserId,
--		   @lCreatedDateTime,
--		   @rOrgId
--	  FROM [sAccounting].[tLedgerGroupMaster] WHERE AccountingYearId=sCommon.fGetIntIdForOrg(AccountingYearId,@rOrgId)  
    
--INSERT INTO sAccounting.tLedgerMaster
--           (Id,
--           Code,
--           Title,
--           IsObsolete,
--           LedgerGroupId,
--           OpeningBalance,
--           LedgerTypeId,
--           AccountingYearId,
--           CreatedUserId,
--           CreatedDateTime,
--           UpdatedUserId,
--           UpdatedDateTime
--           )
--	SELECT
--		   sCommon.fGetIntIdForOrg(Id,@rOrgId),
--		   Code,
--		   Title,
--		   IsObsolete,
--		   sCommon.fGetIntIdForOrg(LedgerGroupId,@rOrgId),
--		   OpeningBalance,
--		   sCommon.fGetIntIdForOrg(LedgerTypeId,@rOrgId),
--		   sCommon.fGetIntIdForOrg(AccountingYearId,@rOrgId),
--		   @lCreatedUserId,
--		   @lCreatedDateTime,
--		   @lCreatedUserId,
--		   @lCreatedDateTime
--	  FROM [sAccounting].[tLedgerMaster] WHERE AccountingYearId=sCommon.fGetIntIdForOrg(AccountingYearId,@rOrgId)
	  
--INSERT INTO [sCommon].[tFilePath]
--           ([Id]
--           ,[SourceTypeId]
--           ,[FilePath]
--           ,[OrgId])
-- SELECT sCommon.fGetIntIdForOrg(Id,@rOrgId)
--      ,[SourceTypeId]
--      ,[FilePath]
--      ,@rOrgId
--  FROM [sCommon].[tFilePath] WHERE OrgId =1   
           
--      UPDATE [sCommon].[tFilePath] SET FilePath = REPLACE (Filepath, '/1/', '/'+CONVERT(Nvarchar(100),@rOrgId)+'/') where OrgId = @rOrgId 

--INSERT INTO sConfig.tCultureConfiguration
--           (
--			OrgId,
--			DateSeparator,
--			Culture,
--			LongDatePattern,
--			LongTimePattern,
--			NumberGroupSeparator,
--			NumberNegativePattern,
--			ShortDatePattern,
--			ShortTimePattern,
--			NumberGroupSizes,
--			UpdatedUserId,
--			UpdatedDateTime
--           )
     
--      SELECT 
--            @rOrgId,
--            DateSeparator,
--			Culture,
--			LongDatePattern,
--			LongTimePattern,
--			NumberGroupSeparator,
--			NumberNegativePattern,
--			ShortDatePattern,
--			ShortTimePattern,
--			NumberGroupSizes,
--		    @lCreatedUserId,
--		    @lCreatedDateTime
--           FROM sConfig.tCultureConfiguration WHERE  OrgId =  1
           
   INSERT INTO [sPayroll].[tPayElement]
           (
					[ID]
				   ,[Code]
				   ,[Title]
				   ,[PayElementTypeId]
				   ,[PaidCategoryId]
				   ,[IsLwp]
				   ,[IsEmployeeSpecific]
				   ,[IsDepend]
				   ,[IsAvailDuringProbation]
				   ,[IsIncludeInPaySlip]
				   ,[SortOrder]
				   ,[IsObsolete]
				   ,[OrgId]
				   ,[CreatedUserId]
				   ,[CreatedDateTime]
				   ,[UpdatedUserId]
				   ,[UpdatedDateTime]
           )     
           SELECT  sCommon.fGetIntIdForOrg(ID,@rOrgId)
				  ,[Code]
				  ,[Title]
				  ,[PayElementTypeId]
				  ,[PaidCategoryId]
				  ,[IsLwp]
				  ,[IsEmployeeSpecific]
				  ,[IsDepend]
				  ,[IsAvailDuringProbation]
				  ,[IsIncludeInPaySlip]
				  ,[SortOrder]
				  ,[IsObsolete]
				  ,@rOrgId
				  ,@lCreatedUserId
				  ,@lCreatedDateTime
				  ,@lCreatedUserId
				  ,@lCreatedDateTime
    
  FROM  [sPayroll].[tPayElement] Where OrgId = 1 
  --AND Id < 101
           
  INSERT INTO [sSetup].[tDepartmentMaster]
           (
					[ID]
				   ,[Code]
				   ,[Title]
				   ,[DisplayTitle]
				   ,[OrgId]
				   ,[IsObsolete]
				   ,[CreatedUserId]
				   ,[CreatedDateTime]
				   ,[UpdatedUserId]
				   ,[UpdatedDateTime]
           )     
           SELECT  sCommon.fGetIntIdForOrg(1,@rOrgId)
				  ,'Common'
				  ,'Common'
				  ,'Common'
				  ,@rOrgId
				  ,0
				  ,@lCreatedUserId
				  ,@lCreatedDateTime
				  ,@lCreatedUserId
				  ,@lCreatedDateTime
    
  --FROM  [sSetup].[tDepartmentMaster] Where OrgId = 1 

COMMIT TRANSACTION	 
END TRY
BEGIN CATCH
ROLLBACK TRANSACTION
SELECT ERROR_MESSAGE()
END CATCH
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.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.tCCECSIndicatorGrade WHERE CAST(LEFT(CCECSId, 4) AS INT) = @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.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.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 sCommon.tTableRowId WHERE OrgId = @rOrgId AND TableTitle in (select TableTitle from sCommon.tTableRowIdMaster where IdScope = 'Org')
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(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sCommunication.tBehaviourTypeMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sCommunication.tBlog WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sCommunication.tBlogComment WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sCommunication.tBlogFavorite WHERE CAST(LEFT(BlogId, 4) AS BIGINT) = @rOrgId
DELETE FROM sCommunication.tCircular WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sCommunication.tCircularScope WHERE CAST(LEFT(CircularId, 4) AS BIGINT) = @rOrgId
DELETE FROM sCommunication.tCircularView WHERE CAST(LEFT(CircularId, 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.tNews WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sCommunication.tNewsComment WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sCommunication.tPhotoCategoryMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sCommunication.tPoll WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sCommunication.tPollAnswer WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sCommunication.tPollMember WHERE CAST(LEFT(PollId, 4) AS BIGINT) = @rOrgId
DELETE FROM sCommunication.tPollResult WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sCommunication.tQuery WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sCommunication.tQueryCategoryMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sCommunication.tQueryComment WHERE CAST(LEFT(Id, 4) AS BIGINT) = @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.tQuestionMaster WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sEExam.tQuestionOption WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sEExam.tQuestionParagraph WHERE CAST(LEFT(Id, 4) AS BIGINT) = @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 sMro.tScannedImages WHERE CAST(LEFT(Id, 4) AS INT) = @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  sPayroll.tEsiProcess WHERE CAST(LEFT(PayProcessElementId, 4) AS BIGINT) = @rOrgId
DELETE FROM sPayroll.tEsiSetup WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sPayroll.tPayElement WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM  sPayroll.tPayProcess WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sPayroll.tPayProcessElement WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sPayroll.tPayProcessEmployee WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM  sPayroll.tPaySetup WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM  sPayroll.tPaySetupDependent WHERE CAST(LEFT(PaySetupId, 4) AS INT) = @rOrgId
DELETE FROM  sPayroll.tPfProcess WHERE CAST(LEFT(PayProcessElementId, 4) AS BIGINT) = @rOrgId
DELETE FROM  sPayroll.tPfProcessCharge WHERE CAST(LEFT(PayProcessElementId, 4) AS BIGINT) = @rOrgId
DELETE FROM sPayroll.tPfSetup WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sPayroll.tProfessionalTaxRange 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.tOrganizationMaster WHERE Id = @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.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 sCommunication.tPhotoCategoryOrg WHERE OrgId = @rOrgId
DELETE FROM sCommunication.tQueryCategoryOrg WHERE OrgId = @rOrgId
DELETE FROM sStudent.tAcademicDetail WHERE CAST(LEFT(AcademicId, 4) AS BIGINT) = @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 -1 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 sAssessment.tCCECSGroupMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sAssessment.tCCECSIndicatorMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sAssessment.tCCECSMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sAssessment.tCCEFAGroupMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sAssessment.tCCEFAIndicatorMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sAssessment.tCCEFAMaster 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 sCommunication.tBlogScope WHERE CAST(LEFT(BlogId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sCommunication.tNewsScope WHERE CAST(LEFT(NewsId, 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.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 OrgGroupId = @rOrgGroupId
DELETE FROM  sIp.tItemSubGroupMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM  sIp.tStockItemCategoryMaster WHERE OrgGroupId = @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.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  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 sSetup.tOrgGroupBatchMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sSetup.tOrgGroupMaster WHERE Id=@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 sCommunication.tQueryCategoryAssignedTo WHERE CAST(LEFT(QueryCategoryId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sLibrary.tBookLocationMaster WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sCommon.tSurnameMaster WHERE OrgGroupId = @rOrgGroupId



 
		
		
		
		
		
		-- special case will come orgwise and orggroupwise
		
		DELETE FROM sCommon.tTableRowId WHERE OrgId = @rOrgGroupId 
		DELETE FROM sConfig.tConfigurationSetup WHERE SourceTypeId = 2010 AND SourceId = @rOrgGroupId
		
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].[pReasonMasterAdd]...';


GO
ALTER PROCEDURE [sCommon].[pReasonMasterAdd]
	@rTitle [nvarchar](100),
	@rCreatedUserId [bigint],
	@rIsObsolete [bit],
	@rRemark [nvarchar](100),
	@rReasonCategoryId [tinyint],
	@rOrgGroupId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

IF NOT EXISTS (SELECT 1 FROM sCommon.tReasonMaster WHERE UPPER(Title) = UPPER(@rTitle) AND ReasonCategoryId = @rReasonCategoryId AND OrgGroupId = @rOrgGroupId )

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

	INSERT INTO sCommon.tReasonMaster
		(
			Id,
			Title,
			CreatedUserId,
			CreatedDateTime,
			IsObsolete,
			UpdatedUserId,
			UpdatedDateTime,
			Remark,
			ReasonCategoryId,
			OrgGroupId
		)
	VALUES
		(
			@lNextNumber,
			@rTitle,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rIsObsolete,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rRemark,
			@rReasonCategoryId,
			@rOrgGroupId
		)
	SELECT 1 AS RESULT
END
ELSE
 BEGIN
 SELECT -100 AS RESULT
 END
END
GO
PRINT N'Altering [sCommon].[pReasonMasterGet]...';


GO
ALTER PROCEDURE [sCommon].[pReasonMasterGet]
	@rId [int] = 0,
	@rTitle [nvarchar](20) = '',
	@rRemark [nvarchar](100) = '',
	@rReasonCategoryId [int] = 0,
	@rOrgGroupId int,
	@rIsWildCardSearch [bit] = 1

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

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


	 SELECT M.Id,
			M.Title,
			M.CreatedUserId,
			M.CreatedDateTime,
			M.IsObsolete,
			M.UpdatedUserId,
			M.UpdatedDateTime,
			M.Remark,
			M.ReasonCategoryId,
			C.Title AS ReasonCategory
	   FROM sCommon.tReasonMaster M INNER JOIN sCommon.tReasonCategoryMaster C
	   ON M.ReasonCategoryId = c.Id
	  WHERE ((M.Id = @rId) OR (@rId = 0))
	   AND ((M.Title LIKE @rTitle) OR (ISNULL(@rTitle, '') = ''))
	   AND ((M.Remark LIKE @rRemark ) OR (ISNULL(@rRemark, '') = ''))
	   AND ((M.ReasonCategoryId = @rReasonCategoryId) OR (@rReasonCategoryId = 0))
	   AND 	M.OrgGroupId = 	@rOrgGroupId
END
GO
PRINT N'Altering [sCommon].[pReasonMasterModify]...';


GO
ALTER PROCEDURE [sCommon].[pReasonMasterModify]
	@rId [int],
	@rTitle [nvarchar](100),
	@rIsObsolete [bit],
	@rUpdatedUserId [bigint],
	@rRemark [nvarchar](100),
	@rReasonCategoryId [tinyint],
	@rOrgGroupId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
IF NOT EXISTS (SELECT 1 FROM sCommon.tReasonMaster WHERE UPPER(Title) = UPPER(@rTitle) AND ReasonCategoryId = @rReasonCategoryId AND Id  <> @rId AND OrgGroupId = @rOrgGroupId )
BEGIN

	 UPDATE sCommon.tReasonMaster
		SET 
			Title = @rTitle,
			IsObsolete = @rIsObsolete,
			UpdatedUserId = @rUpdatedUserId,
			UpdatedDateTime = sCommon.fGetDate(),
			Remark = @rRemark,
			ReasonCategoryId = @rReasonCategoryId
	  WHERE Id = @rId AND OrgGroupId = @rOrgGroupId
	  
	  
SELECT 1 AS RESULT
END

ELSE

 BEGIN
	 SELECT -100 AS RESULT
 END
 
END
GO
PRINT N'Altering [sCommon].[pReportGet]...';


GO
ALTER PROCEDURE [sCommon].[pReportGet]
	@rId [int] = 0,
	@rOrgId int = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 SELECT Id,
			
			--R.Title,
			R.ReportName AS Title,
			R.ReportPath,			
			R.IsElectronicSignatureRequired,
			ISNULL(s.IsDirectPrint,0) AS IsDirectPrint ,
			ISNULL(s.NoOfCopies,1) AS NoOfCopies
	   FROM sCommon.tReport R
	   LEFT JOIN sSetup.tReportSetting S
	   ON R.Id = s.ReportId AND S.OrgId = @rOrgId
	  WHERE ((R.Id = @rId) OR (@rId = 0))
END
GO
PRINT N'Altering [sCommunication].[pAssignmentAdd]...';


GO

ALTER PROCEDURE [sCommunication].[pAssignmentAdd]
	 
        @rId bigint,
        @rSubjectId int,
		@rTitle nvarchar(100),
		@rRemark nvarchar(max),
		@rStartDate date,
		@rEndDate date,
		@rCreatedUserId bigint,
		@rBatchId int,
		@rOrgId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	IF(@rId = 0)	
	BEGIN
		--If Exists(select Id from sCommunication.tAssignment where Code=@rCode AND BatchId=@rBatchId)
		--	BEGIN
		--	select -102 as Result
		--	RETURN
		--END 
	
		If Exists(select Id from sCommunication.tAssignment where Title=@rTitle AND BatchId=@rBatchId)
			BEGIN
			select -103 as Result
			RETURN
		END 
	END
	ELSE
	BEGIN
		--If Exists(select Id from sCommunication.tAssignment where Code=@rCode AND BatchId=@rBatchId AND Id<>@rId)
		--Begin
		--	select -102 as Result
		--	RETURN
		--End
		If  Exists(select Id from sCommunication.tAssignment where Title=@rTitle AND BatchId=@rBatchId AND Id<>@rId)
		Begin
			select -103 as Result
			RETURN
		End

	END
	
	
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sCommunication.tAssignment', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sCommunication.tAssignment
		(
			Id,
			SubjectId,
			Title,
			Remark,
			StartDate,
			EndDate,
			CreatedUserId,
			CreatedDateTime,
			BatchId
		)
	VALUES
		(
			@lNextNumber,
			@rSubjectId,
			@rTitle,
			@rRemark,
			@rStartDate,
			@rEndDate,
			@rCreatedUserId,
			sCommon.fGetDate(), 
			@rBatchId
		)
		    SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION         
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE sCommunication.tAssignment
	    SET
			SubjectId=@rSubjectId,
			Title=@rTitle,
			StartDate=@rStartDate,
			EndDate=@rEndDate,
			Remark=@rRemark,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate()
	      
	      WHERE Id = @rId
	      
	      DELETE FROM sCommunication.tAssignmentView WHERE AssignmentId=@rId
	      
	      SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION
	 END  	

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


GO
ALTER PROCEDURE [sCommunication].[pAssignTaskGet]
	 
	 @rId bigint,
	 @rOrgId int,
	 @rCreatedUserId bigint,
	 @rIsAssignTaskToMe bit,
	 @rStatus tinyint,
	 @rIsSearch bit
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 
IF(@rIsAssignTaskToMe = 1)
BEGIN
	SELECT 
			AT.Id,
			AT.AssignedToSourceTypeId,
			AT.AssignedToSourceId,
			CASE WHEN @rIsSearch = 1 THEN EM1.Code ELSE EM.Code END AS SourceCode,
			CASE WHEN @rIsSearch = 1 THEN EM1.EmployeeName ELSE EM.EmployeeName END AS SourceName,
			AT.AssignedDate,
			AT.DueDate,
			AT.Remark,
			AT.IsCompleted,
			AT.IsClosed
	FROM 
			sCommunication.tAssignTask AT
		INNER JOIN sHrm.vExtEmployeeMaster EM ON EM.Id=AT.AssignedToSourceId AND AT.AssignedToSourceTypeId=95
		INNER JOIN sSecurity.tUser U ON U.Id=AT.CreatedUserId
		LEFT JOIN sHrm.vExtEmployeeMaster EM1 ON EM1.Id=U.SourceId
	WHERE 
			((AT.Id=@rId) OR (@rId=0))
		AND (AT.AssignedToSourceId=(Select SourceId From sSecurity.tUser where Id=@rCreatedUserId))
		AND AT.IsCompleted=(CASE 
			WHEN @rStatus=0 THEN 0
			WHEN @rStatus=1 THEN 1
			WHEN @rStatus=2 THEN 0
		END)
		AND AT.IsClosed=(CASE 
			WHEN @rStatus=2 THEN 1
			WHEN @rStatus=1 THEN 0
			WHEN @rStatus=0 THEN 0
		END)
		AND AT.OrgId=@rOrgId
			
	UNION ALL
	
	SELECT 
			AT.Id,
			AT.AssignedToSourceTypeId,
			AT.AssignedToSourceId,
			CASE WHEN @rIsSearch = 0 THEN SN.Code WHEN SN1.StudentId IS NOT NULL THEN SN1.Code ELSE EM1.Code END AS SourceCode,
			CASE WHEN @rIsSearch = 0 THEN SN.Name WHEN SN1.StudentId IS NOT NULL THEN SN1.Name ELSE EM1.EmployeeName END AS SourceName,
			AT.AssignedDate,
			AT.DueDate,
			AT.Remark,
			AT.IsCompleted,
			AT.IsClosed
	FROM 
			sCommunication.tAssignTask AT
		INNER JOIN sStudent.vStudentName SN ON SN.StudentId=AT.AssignedToSourceId AND AT.AssignedToSourceTypeId=2003
		INNER JOIN sSecurity.tUser U ON U.Id=AT.CreatedUserId
		LEFT JOIN sStudent.vStudentName SN1 ON SN1.StudentId=U.SourceId AND U.SourceTypeId=2003
		LEFT JOIN sHrm.vExtEmployeeMaster EM1 ON EM1.EmployeeId=U.SourceId AND U.SourceTypeId=95
	WHERE 
			((AT.Id=@rId) OR (@rId=0))
		AND (AT.AssignedToSourceId=(Select SourceId From sSecurity.tUser where Id=@rCreatedUserId))
		AND AT.IsCompleted=(CASE 
			WHEN @rStatus=0 THEN 0
			WHEN @rStatus=1 THEN 1
			WHEN @rStatus=2 THEN 0
		END)
		AND AT.IsClosed=(CASE 
			WHEN @rStatus=2 THEN 1
			WHEN @rStatus=1 THEN 0
			WHEN @rStatus=0 THEN 0
		END)
		AND AT.OrgId=@rOrgId
END
ELSE
BEGIN
	SELECT 
			AT.Id,
			AT.AssignedToSourceTypeId,
			AT.AssignedToSourceId,
			EM1.Code AS SourceCode,
			EM1.EmployeeName AS SourceName,
			AT.AssignedDate,
			AT.DueDate,
			AT.Remark,
			AT.IsCompleted,
			AT.IsClosed
	FROM 
			sCommunication.tAssignTask AT
		INNER JOIN sSecurity.tUser U ON U.Id=AT.CreatedUserId
		INNER JOIN sHrm.vExtEmployeeMaster EM1 ON EM1.Id=AT.AssignedToSourceId AND AT.AssignedToSourceTypeId=95
	WHERE 
			((AT.Id=@rId) OR (@rId=0))
		AND (AT.CreatedUserId=@rCreatedUserId)
		AND AT.IsCompleted=(CASE 
			WHEN @rStatus=0 THEN 0
			WHEN @rStatus=1 THEN 1
			WHEN @rStatus=2 THEN 0
		END)
		AND AT.IsClosed=(CASE 
			WHEN @rStatus=2 THEN 1
			WHEN @rStatus=1 THEN 0
			WHEN @rStatus=0 THEN 0
		END)
		AND AT.OrgId=@rOrgId
			
	UNION ALL
	
	SELECT 
			AT.Id,
			AT.AssignedToSourceTypeId,
			AT.AssignedToSourceId,
			SN1.Code AS SourceCode,
			SN1.Name AS SourceName,
			AT.AssignedDate,
			AT.DueDate,
			AT.Remark,
			AT.IsCompleted,
			AT.IsClosed
	FROM 
			sCommunication.tAssignTask AT
		INNER JOIN sSecurity.tUser U ON U.Id=AT.CreatedUserId
		INNER JOIN sStudent.vStudentName SN1 ON SN1.StudentId=AT.AssignedToSourceId AND AT.AssignedToSourceTypeId=2003
	WHERE 
			((AT.Id=@rId) OR (@rId=0))
		AND (AT.CreatedUserId=@rCreatedUserId)
		AND AT.IsCompleted=(CASE 
			WHEN @rStatus=0 THEN 0
			WHEN @rStatus=1 THEN 1
			WHEN @rStatus=2 THEN 0
		END)
		AND AT.IsClosed=(CASE 
			WHEN @rStatus=2 THEN 1
			WHEN @rStatus=1 THEN 0
			WHEN @rStatus=0 THEN 0
		END)
		AND AT.OrgId=@rOrgId
END
END
GO
PRINT N'Altering [sCommunication].[pBehaviourEntryAdd]...';


GO

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

IF(@rId = 0)

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

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

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


GO

ALTER PROCEDURE [sCommunication].[pBehaviourGet]
		
		@rBehaviourTypeId int,
		@rOrgGroupBatchId int,
		@rCode nvarchar(20),
		@rTitle nvarchar(100)
		
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
		
BEGIN 
	  --BEGIN
	  
			--SET @rTitle = sCommon.fSearchStringGet(@rTitle)
	  --END
	SELECT 
	B.Id,
	B.BehaviourDate,
	B.Title,
	BTM.Title AS BehaviourType,
	SA.FirstName+' '+SA.LastName AS Name,
	SA.ClassName+'-'+SA.DivisionName AS ClassDiv,
	SA.Code,
	B.Remark,
	B.BehaviourTypeId,
	B.AcademicId
  FROM 
        sCommunication.tBehaviour B
         INNER JOIN sCommunication.tBehaviourTypeMaster BTM
         ON B.BehaviourTypeId=BTM.Id
         INNER JOIN sStudent.vStudentAcademic SA
         ON SA.AcademicId=B.AcademicId
         --INNER JOIN sStudent.tStudentMaster SM
         --ON SM.Id=B.AcademicId
  WHERE 
        ((B.BehaviourTypeId= @rBehaviourTypeId) OR (ISNULL(@rBehaviourTypeId,0) = 0)) 
     AND ((SA.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	AND ((SA.Code=@rCode) OR (ISNULL(@rCode,'') = '')) 
	AND ((B.Title=@rTitle) OR (ISNULL(@rTitle,'') = '')) 
END
GO
PRINT N'Altering [sCommunication].[pBehaviourListGet]...';


GO

ALTER PROCEDURE [sCommunication].[pBehaviourListGet]
		
		@rOrgGroupBatchId int,
		@rStudentId bigint,
		@rBehaviourTypeId int,
		@rBehaviourIndicatorId int
		
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
		
BEGIN 
	  --BEGIN
	  
			--SET @rTitle = sCommon.fSearchStringGet(@rTitle)
	  --END
	 
	SELECT 
	--B.Id,
	B.BehaviourDate,
	B.Title,
	BTM.Title AS BehaviourType,
	--SA.FirstName+' '+SA.LastName AS Name,
	--SA.ClassName+'-'+SA.DivisionName AS ClassDiv,
	--SA.Code,
	B.Remark
	--B.BehaviourTypeId,
	--B.AcademicId
	
  FROM 
        sCommunication.tBehaviour B
         INNER JOIN sCommunication.tBehaviourTypeMaster BTM
         ON B.BehaviourTypeId=BTM.Id
         INNER JOIN sStudent.vStudentAcademic  SA
         ON SA.AcademicId=B.AcademicId AND SA.StudentId = @rStudentId AND SA.OrgGroupBatchId = @rOrgGroupBatchId
WHERE
         ((B.BehaviourTypeId= @rBehaviourTypeId) OR (ISNULL(@rBehaviourTypeId,0) = 0))  
         AND ((BTM.BehaviourIndicatorId=@rBehaviourIndicatorId) OR (ISNULL(@rBehaviourIndicatorId,0)=0)) 
END
GO
PRINT N'Altering [sCommunication].[pBehaviourTypeMasterAdd]...';


GO

ALTER PROCEDURE [sCommunication].[pBehaviourTypeMasterAdd]
	 
	@rId int,
	--@rCode nvarchar(25),
	@rTitle nvarchar(100),
	@rRemark nvarchar(200),
	@rBehaviourIndicatorId int,
	@rIsObsolete bit,
	@rOrgGroupId smallint,
	@rCreatedUserId bigint,
	@rUpdatedUserId bigint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
		--IF(@rId = 0)	
--	IF Exists(Select @rCode from	sLibrary.tBookMaster where Code=@rCode)
--BEGIN
--Select -103 AS Result
--RETURN
--END
		
BEGIN TRANSACTION

IF(@rId = 0)

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

	INSERT INTO sCommunication.tBehaviourTypeMaster
		(
			Id,
			Title,
			Remark,
			BehaviourIndicatorId,
			OrgGroupId,
			IsObsolete,
			CreatedUserId,
			CreatedDateTime
		)
	VALUES
		(
			@lNextNumber,
			@rTitle,
			@rRemark,
			@rBehaviourIndicatorId,
			@rOrgGroupId,
			@rIsObsolete,
		    @rCreatedUserId,
			sCommon.fGetDate()
		)
		   Select @lNextNumber AS Result
	END
	ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sCommunication.tBehaviourTypeMaster
	    SET
			Title=@rTitle,
			Remark=@rRemark,
			BehaviourIndicatorId=@rBehaviourIndicatorId,
			IsObsolete=@rIsObsolete,
			UpdatedUserId=@rUpdatedUserId,
			UpdatedDateTime= sCommon.fGetDate()
	      WHERE Id = @rId 
     SELECT @lNextNumber AS Result
END	
	
	COMMIT TRANSACTION
END TRY
	
	BEGIN CATCH
	    ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH  
END
GO
PRINT N'Altering [sCommunication].[pBlogScopeGet]...';


GO
ALTER PROCEDURE [sCommunication].[pBlogScopeGet]
	 
	 @rBlogId bigint,
	 @rOrgGroupId smallint,
	 @rUserId bigint
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 		
		
	SELECT 
			OM.Id  as SourceId,
			OM.DisplayTitle as Organization,
			1016 as SourceTypeId,
			CASE WHEN BS.SourceId IS NULL OR BS.BlogId!=@rBlogId THEN 0 ELSE 1 END AS IsObsolete
  FROM 
			sSetup.tOrganizationMaster OM
			INNER JOIN sSetup.vUserOrganization UO ON UO.Id=OM.Id AND UO.OrgGroupId=@rOrgGroupId AND UO.UserId=@rUserId
			LEFT JOIN sCommunication.tBlogScope BS ON BS.SourceId=OM.Id AND BS.SourceTypeId=1016 AND BS.BlogId=@rBlogId
	Order BY OM.OrderIndex
END
GO
PRINT N'Altering [sCommunication].[pCircularAdd]...';


GO

ALTER PROCEDURE [sCommunication].[pCircularAdd]
	 
        @rId bigint,
		@rTitle nvarchar(100),
		@rRemark nvarchar(200),
		@rStartDate date,
		@rCreatedUserId bigint,
        @rOrgGroupId smallint,
        @rOrgGroupBatchId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	IF(@rId = 0)	
	BEGIN
		--If Exists(select Id from sCommunication.tCircular where Code=@rCode AND OrgGroupBatchId=@rOrgGroupBatchId)
		--	BEGIN
		--	select -102 as Result
		--	RETURN
		--END 
	
		If Exists(select Id from sCommunication.tCircular where Title=@rTitle AND OrgGroupBatchId=@rOrgGroupBatchId)
			BEGIN
			select -103 as Result
			RETURN
		END 
	END
	ELSE
	BEGIN
		--If Exists(select Id from sCommunication.tCircular where Code=@rCode AND OrgGroupBatchId=@rOrgGroupBatchId AND Id<>@rId)
		--Begin
		--	select -102 as Result
		--	RETURN
		--End
		If  Exists(select Id from sCommunication.tCircular where Title=@rTitle AND OrgGroupBatchId=@rOrgGroupBatchId AND Id<>@rId)
		Begin
			select -103 as Result
			RETURN
		End

	END
	
	
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sCommunication.tCircular', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sCommunication.tCircular
		(
			Id,
			Title,
			Remark,
			StartDate,
			CreatedUserId,
			CreatedDateTime,
			OrgGroupId,
			OrgGroupBatchId
		)
	VALUES
		(
			@lNextNumber,
			@rTitle,
			@rRemark,
			@rStartDate,
			@rCreatedUserId,
			sCommon.fGetDate(), 
			@rOrgGroupId,
			@rOrgGroupBatchId
		)
		    SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION         
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE sCommunication.tCircular
	    SET
			Title=@rTitle,
			StartDate=@rStartDate,
			Remark=@rRemark,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate()
	      
	      WHERE Id = @rId
	      
	      DELETE FROM sCommunication.tCircularView WHERE CircularId=@rId
	      
	      SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION
	 END  	

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


GO
ALTER PROCEDURE [sCommunication].[pNewsScopeGet]
	 @rNewsId bigint,
	 @rOrgGroupId smallint,
	 @rUserId bigint
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 		
		
	SELECT 
			OM.Id  as SourceId,
			OM.DisplayTitle as Organization,
			1016 as SourceTypeId,
			CASE WHEN NS.SourceId IS NULL OR NS.NewsId!=@rNewsId THEN 0 ELSE 1 END AS IsObsolete
  FROM 
			sSetup.tOrganizationMaster OM
			INNER JOIN sSetup.vUserOrganization UO ON UO.Id=OM.Id AND UO.OrgGroupId=@rOrgGroupId AND UO.UserId=@rUserId
			LEFT JOIN sCommunication.tNewsScope NS ON NS.SourceId=OM.Id AND NS.SourceTypeId=1016 AND NS.NewsId=@rNewsId
	Order BY OM.OrderIndex
END
GO
PRINT N'Altering [sCommunication].[pPhotoCategoryMasterAdd]...';


GO
ALTER PROCEDURE [sCommunication].[pPhotoCategoryMasterAdd]
	 
	 @rId int,
	 @rOrgGroupId int,
	 @rTitle nvarchar(100),
	 @rIsObsolete bit,
	 @rCreatedUserId bigint
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
IF(@rId = 0)	
BEGIN
	IF EXISTS(Select 1 FROM sCommunication.tPhotoCategoryMaster Where Title = @rTitle AND OrgGroupId=@rOrgGroupId)
	BEGIN 
		SELECT -101 AS Result
		RETURN
	END 
END
ELSE 
BEGIN 
	IF EXISTS(Select 1 FROM sCommunication.tPhotoCategoryMaster Where Title = @rTitle AND OrgGroupId=@rOrgGroupId AND Id!=@rId)
	BEGIN 
		SELECT -101 AS Result
		RETURN
	END 
END
	
BEGIN TRY

BEGIN TRANSACTION	
 IF(@rId = 0)	
BEGIN
  
	DECLARE @lNextNumber BIGINT     
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sCommunication.tPhotoCategoryMaster', 0, 1, 1,@outNextNumber = @lNextNumber output

	INSERT INTO [sCommunication].[tPhotoCategoryMaster]
           (
            [Id]
           ,[Title]
           ,[IsObsolete]
           ,[CreatedUserId]
           ,[CreatedDateTime]
           ,[UpdatedUserId]
           ,[UpdatedDateTime]
           ,[OrgGroupId])
     VALUES
		(
			@lNextNumber,
			@rTitle,
			@rIsObsolete,
			@rCreatedUserId,
		    sCommon.fGetDate(),
			@rCreatedUserId,	 
			sCommon.fGetDate(),
			@rOrgGroupId
		)
		             
	END	 
	 ELSE
	  BEGIN
	 SET @lNextNumber = @rId
	    UPDATE [sCommunication].[tPhotoCategoryMaster]
	    SET
			Title = @rTitle,
			IsObsolete = @rIsObsolete,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate()
	      
	      WHERE Id = @rId 	 
		END
		SELECT @lNextNumber AS Result	   
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sCommunication].[pPhotoCategoryMasterGet]...';


GO
ALTER PROCEDURE [sCommunication].[pPhotoCategoryMasterGet]
	 
	 @rOrgId int,
	 @rId int = 0	 	 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	
  SELECT   PCM.[Id]
  		  ,PCM.[Title]
          ,PCM.[IsObsolete]
          
  FROM    [sCommunication].[tPhotoCategoryMaster]  PCM
  INNER JOIN sCommunication.tPhotoCategoryOrg PCO ON PCO.PhotoCategoryId=PCM.Id AND PCO.OrgId=@rOrgId
            
  WHERE   
      PCM.IsObsolete = 0
      AND (PCM.Id = @rId OR @rId = 0)
 
END
GO
PRINT N'Altering [sCommunication].[pPollAdd]...';


GO

ALTER PROCEDURE [sCommunication].[pPollAdd]
	 
        @rId bigint,
        @rTitle nvarchar(200),
		@rRemark nvarchar(500),
		@rIsOwnAnswer bit,
		@rIsOpen bit,
		@rCreatedUserId bigint,
		@rOrgGroupId smallint,
		@rOrgGroupBatchId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	IF(@rId = 0)	
	BEGIN
		--If Exists(select Id from sCommunication.tPoll where Code=@rCode AND OrgGroupBatchId=@rOrgGroupBatchId)
		--	BEGIN
		--	select -102 as Result
		--	RETURN
		--END 
	
		If Exists(select Id from sCommunication.tPoll where Title=@rTitle AND OrgGroupBatchId=@rOrgGroupBatchId)
			BEGIN
			select -103 as Result
			RETURN
		END 
	END
	ELSE
	BEGIN
		--If Exists(select Id from sCommunication.tPoll where Code=@rCode AND OrgGroupBatchId=@rOrgGroupBatchId AND Id<>@rId)
		--Begin
		--	select -102 as Result
		--	RETURN
		--End
		If  Exists(select Id from sCommunication.tPoll where Title=@rTitle AND OrgGroupBatchId=@rOrgGroupBatchId AND Id<>@rId)
		Begin
			select -103 as Result
			RETURN
		End

	END
	
	
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sCommunication.tPoll', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sCommunication.tPoll
		(
			Id,
			Title,
			Remark,
			IsOwnAnswer,
			IsOpen,
			CreatedUserId,
			CreatedDateTime,
			OrgGroupId,
			OrgGroupBatchId
		)
	VALUES
		(
			@lNextNumber,
			@rTitle,
			@rRemark,
			@rIsOwnAnswer,
			@rIsOpen,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rOrgGroupId,
			@rOrgGroupBatchId
		)
		    SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION         
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sCommunication.tPoll
	    SET
			Title=@rTitle,
			Remark=@rRemark,
			IsOwnAnswer=@rIsOwnAnswer,
			IsOpen=@rIsOpen,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate()
	      
	      WHERE Id = @rId
	      SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION
	 END  	

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


GO

ALTER PROCEDURE [sCommunication].[pPollAnswerAdd]
	 
        @rId bigint
       ,@rPollId bigint
       ,@rTitle nvarchar(200)
       ,@rIsDeleted bit
       ,@rOrgGroupId smallint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
If(@rIsDeleted=1)
BEGIN
	Delete from sCommunication.tPollAnswer where Id=@rId
	Select @rId as Result
END	
ELSE
BEGIN
	BEGIN TRY
	
	IF(@rId = 0)	
	BEGIN
		--If Exists(select Id from sCommunication.tPollAnswer where Code=@rCode AND PollId=@rPollId)
		--	BEGIN
		--	select -102 as Result
		--	RETURN
		--END 
	
		If Exists(select Id from sCommunication.tPollAnswer where Title=@rTitle AND PollId=@rPollId)
			BEGIN
			select -103 as Result
			RETURN
		END 
	END
	ELSE
	BEGIN
		--If Exists(select Id from sCommunication.tPollAnswer where Code=@rCode AND PollId=@rPollId AND Id<>@rId)
		--Begin
		--	select -102 as Result
		--	RETURN
		--End
		If  Exists(select Id from sCommunication.tPollAnswer where Title=@rTitle AND PollId=@rPollId AND Id<>@rId)
		Begin
			select -103 as Result
			RETURN
		End

	END
	
	
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sCommunication.tPollAnswer', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sCommunication.tPollAnswer
		(
			Id,
			PollId,
			Title
		)
	VALUES
		(
			@lNextNumber,
			@rPollId,
			@rTitle
		)
		    SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION         
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sCommunication.tPollAnswer
	    SET
			PollId=@rPollId,
			Title=@rTitle
	      
	      WHERE Id = @rId
	      SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION
	 END  	

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


GO
ALTER PROCEDURE [sCommunication].[pPollGet]
	 @rId bigint = 0,
	 @rOrgGroupBatchId int,
	 @rCreatedUserId bigint,
	 @rSourceTypeId smallint
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
If(@rSourceTypeId = 95)
BEGIN	 
	SELECT 
	
			P.Id as PollId,
			P.Title AS PollTitle,
			P.Remark AS PollRemark,
			P.IsOwnAnswer,
			P.IsOpen,
			P.CreatedDateTime AS PollCreatedDateTime,
			(SELECT  ISNULL(Count(1),0) FROM sCommunication.tPollResult PR WHERE PR.PollId=P.Id) AS TotalPollVote
  FROM 
            sCommunication.tPoll P
         INNER JOIN sCommunication.tPollMember PM ON PM.PollId=P.Id AND PM.SourceTypeId=2004 
         INNER JOIN sSetup.tDepartmentMaster ODM ON ODM.Id=PM.SourceId
         INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.OrganizationDepartmentId=ODM.Id
         INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id=EJD.EmployeeId
         INNER JOIN sSecurity.tUser U ON U.SourceId=EM.Id AND U.SourceTypeId=@rSourceTypeId AND U.Id=@rCreatedUserId
  WHERE 
  
      ((P.Id = @rId) OR (@rId = 0))
	AND ((P.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	--ORDER BY P.CreatedDateTime DESC
	
	UNION
	
	SELECT 
	
			P.Id as PollId,
			P.Title AS PollTitle,
			P.Remark AS PollRemark,
			P.IsOwnAnswer,
			P.IsOpen,
			P.CreatedDateTime AS PollCreatedDateTime,
			(SELECT  ISNULL(Count(1),0) FROM sCommunication.tPollResult PR WHERE PR.PollId=P.Id) AS TotalPollVote
  FROM 
            sCommunication.tPoll P
  WHERE 
  
      ((P.Id = @rId) OR (@rId = 0))
    AND ((P.CreatedUserId = @rCreatedUserId) OR (@rCreatedUserId = 0))
	AND ((P.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	--ORDER BY P.CreatedDateTime DESC
	
END
ELSE IF(@rSourceTypeId = 2003)
BEGIN
	SELECT 
	
			P.Id as PollId,
			P.Title AS PollTitle,
			P.Remark AS PollRemark,
			P.IsOwnAnswer,
			P.IsOpen,
			P.CreatedDateTime AS PollCreatedDateTime,
			(SELECT  ISNULL(Count(1),0) FROM sCommunication.tPollResult PR WHERE PR.PollId=P.Id) AS TotalPollVote
			--(SELECT  ISNULL(Count(1),0) FROM sCommunication.tPollAnswer PA 
			--INNER JOIN sCommunication.tPollResult PR ON PR.PollAnswerId=PA.Id WHERE PA.PollId = P.Id) AS TotalPollVote
  FROM 
            sCommunication.tPoll P
         INNER JOIN sCommunication.tPollMember PM ON PM.PollId=P.Id AND PM.SourceTypeId=2005
         INNER JOIN sStudent.vStudentAcademic SA ON SA.DivisionId=PM.SourceId
         INNER JOIN sSecurity.tUser U ON U.SourceId=SA.StudentId AND U.SourceTypeId=@rSourceTypeId AND U.Id=@rCreatedUserId
  WHERE 
  
      ((P.Id = @rId) OR (@rId = 0))
	AND ((P.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	--ORDER BY P.CreatedDateTime DESC
	
	UNION
	
	SELECT 
	
			P.Id as PollId,
			P.Title AS PollTitle,
			P.Remark AS PollRemark,
			P.IsOwnAnswer,
			P.IsOpen,
			P.CreatedDateTime AS PollCreatedDateTime,
			(SELECT  ISNULL(Count(1),0) FROM sCommunication.tPollResult PR WHERE PR.PollId=P.Id) AS TotalPollVote
  FROM 
            sCommunication.tPoll P
  WHERE 
  
      ((P.Id = @rId) OR (@rId = 0))
    AND ((P.CreatedUserId = @rCreatedUserId) OR (@rCreatedUserId = 0))
	AND ((P.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	--ORDER BY P.CreatedDateTime DESC
	
END

ELSE 

BEGIN
	SELECT 
	
			P.Id as PollId,
			P.Title AS PollTitle,
			P.Remark AS PollRemark,
			P.IsOwnAnswer,
			P.IsOpen,
			P.CreatedDateTime AS PollCreatedDateTime,
			(SELECT  ISNULL(Count(1),0) FROM sCommunication.tPollResult PR WHERE PR.PollId=P.Id) AS TotalPollVote
			--(SELECT  ISNULL(Count(1),0) FROM sCommunication.tPollAnswer PA 
			--INNER JOIN sCommunication.tPollResult PR ON PR.PollAnswerId=PA.Id WHERE PA.PollId = P.Id) AS TotalPollVote
  FROM 
            sCommunication.tPoll P
         INNER JOIN sCommunication.tPollMember PM ON PM.PollId=P.Id AND PM.SourceTypeId=2005
         INNER JOIN sStudent.vStudentAcademic SA ON SA.DivisionId=PM.SourceId
         INNER JOIN sSecurity.tUser U ON U.SourceId=SA.StudentId AND U.SourceTypeId=@rSourceTypeId AND U.Id=@rCreatedUserId
  WHERE 
  
      ((P.Id = @rId) OR (@rId = 0))
	AND ((P.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	--ORDER BY P.CreatedDateTime DESC
	
	UNION
	
	SELECT 
	
			P.Id as PollId,
			P.Title AS PollTitle,
			P.Remark AS PollRemark,
			P.IsOwnAnswer,
			P.IsOpen,
			P.CreatedDateTime AS PollCreatedDateTime,
			(SELECT  ISNULL(Count(1),0) FROM sCommunication.tPollResult PR WHERE PR.PollId=P.Id) AS TotalPollVote
  FROM 
            sCommunication.tPoll P
  WHERE 
  
      ((P.Id = @rId) OR (@rId = 0))
    AND ((P.CreatedUserId = @rCreatedUserId) OR (@rCreatedUserId = 0))
	AND ((P.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	--ORDER BY P.CreatedDateTime DESC
	
END


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


GO
ALTER PROCEDURE [sCommunication].[pPollMemberGet]
	 
	 @rPollId bigint,
	 @rOrgId smallint,
	 @rOrgGroupId smallint
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 		
		
	SELECT 
			DM.Id  as SourceId,
			CM.Title+'-'+DM.Title as ClassDept,
			2005 as SourceTypeId,
			CASE WHEN PM.SourceId IS NULL OR PM.PollId!=@rPollId THEN 0 ELSE 1 END AS IsObsolete,
			OM.DisplayTitle AS Organization,
			CM.OrderIndex+DM.OrderIndex AS OrderIndex
  FROM 
			sSetup.tDivisionMaster DM
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=DM.ClassId
			LEFT JOIN sCommunication.tPollMember PM ON PM.SourceId=DM.Id AND PM.SourceTypeId=2005 AND PM.PollId=@rPollId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=DM.OrgId AND OM.OrgGroupId=@rOrgGroupId
	 WHERE
		((DM.OrgId=@rOrgId) OR (@rOrgId=0))
		UNION
	SELECT 
			ODM.Id  as SourceId,
			ODM.Title as ClassDept,
			2004 as SourceTypeId,
			CASE WHEN PM.SourceId IS NULL OR PM.PollId!=@rPollId THEN 0 ELSE 1 END AS IsObsolete,
			OM.DisplayTitle AS Organization,
			0 AS OrderIndex
  FROM 
			sSetup.tDepartmentMaster ODM
			LEFT JOIN sCommunication.tPollMember PM ON PM.SourceId=ODM.Id AND PM.SourceTypeId=2004 AND PM.PollId=@rPollId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=ODM.OrgId AND OM.OrgGroupId=@rOrgGroupId
	WHERE
		((ODM.OrgId=@rOrgId) OR (@rOrgId=0))
END
GO
PRINT N'Altering [sCommunication].[pPollResultAdd]...';


GO

ALTER PROCEDURE [sCommunication].[pPollResultAdd]
	 
        @rPollAnswerId bigint,
        @rPollId bigint,
		@rRemark nvarchar(500),
		@rCreatedUserId bigint,
		@rOrgGroupId smallint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sCommunication.tPollResult', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sCommunication.tPollResult
		(
			Id,
			PollId,
			PollAnswerId,
			Remark,
			CreatedUserId,
			CreatedDateTime
		)
	VALUES
		(
			@lNextNumber,
			@rPollId,
			@rPollAnswerId,
			@rRemark,
			@rCreatedUserId,
			sCommon.fGetDate()
		)
		    SELECT @lNextNumber AS Result
	
	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sCommunication].[pQueryAdd]...';


GO

ALTER PROCEDURE [sCommunication].[pQueryAdd]
	 
	@rOrgGroupId smallint,
	@rOrgGroupBatchId int,
	@rQueryCategoryId int,
	@rId AS bigint,
	@rTitle nvarchar(100),
	@rRemark nvarchar(200),
	@rIsUserView bit,
	@rIsAssigneeView bit,
	@rStatusId tinyint,
	@rCreatedUserId bigint,
	@rCreatedDateTime datetime
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	BEGIN TRANSACTION
		IF(@rId = 0)
BEGIN
DECLARE @lNextNumber BIGINT     
	
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sCommunication.tQueryCategoryMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sCommunication.tQuery
		(
			OrgGroupId,
			OrgGroupBatchId,
			QueryCategoryId,
			Id,
			Title,
			Remark,
			IsUserView,
			IsAssigneeView,
			StatusId,
			CreatedUserId,
			CreatedDateTime
		)
	VALUES
		(
			@rOrgGroupId,
			@rOrgGroupBatchId,
			@rQueryCategoryId,
			@lNextNumber,
			@rTitle,
			@rRemark,
			@rIsUserView,
			@rIsAssigneeView,
			@rStatusId,
			@rCreatedUserId,
			sCommon.fGetDate()
		)
		select 1 as result
END
ELSE
BEGIN
		UPDATE sCommunication.tQuery 
		SET IsUserView = @rIsUserView,
		IsAssigneeView=@rIsAssigneeView
		
		 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 [sCommunication].[pQueryCategoryMasterAdd]...';


GO

ALTER PROCEDURE [sCommunication].[pQueryCategoryMasterAdd]
	 
	@rId int,
	@rTitle nvarchar(100),
	@rRemark nvarchar(200),
	@rIsObsolete bit,
	@rCreatedUserId bigint,
	@rUpdatedUserId bigint,
	@rOrgGroupId smallint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	
		IF(@rId = 0)	
	BEGIN
		If Exists(select Id from sCommunication.tQueryCategoryMaster where Title=@rTitle AND OrgGroupId=@rOrgGroupId)
			BEGIN
			select -103 as Result
			RETURN
		END 
 
	END
	ELSE
	BEGIN
 
		If  Exists(select Id from sCommunication.tQueryCategoryMaster where Title=@rTitle AND OrgGroupId =@rOrgGroupId AND Id<>@rId)
		Begin
			select -103 as Result
			RETURN
		End

	END
	
	 BEGIN TRANSACTION	
 IF(@rId = 0)	
BEGIN

	DECLARE @lNextNumber INT     
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sCommunication.tQueryCategoryMaster', 0, 1, 1,@outNextNumber = @lNextNumber output

	INSERT INTO sCommunication.tQueryCategoryMaster
		(
			Id,
			Title,
			Remark,
			OrgGroupId,
			IsObsolete,
			CreatedUserId,
			CreatedDateTime
		)
	VALUES
		(
			@lNextNumber,
			@rTitle,
			@rRemark,
			@rOrgGroupId,
			@rIsObsolete,
			@rCreatedUserId,
			sCommon.fGetDate()
		)        
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sCommunication.tQueryCategoryMaster
	    SET
	      Title=@rTitle,
	      Remark=@rRemark,
	      IsObsolete=@rIsObsolete,
	      UpdatedUserId=@rUpdatedUserId,
	      UpdatedDateTime= sCommon.fGetDate()
	     
	      WHERE Id = @rId 	   
	 END  
		SELECT @lNextNumber AS Result
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sCommunication].[pQueryCategoryMasterGet]...';


GO

ALTER PROCEDURE [sCommunication].[pQueryCategoryMasterGet]
	 
	 @rId int = 0,
	 @rTitle nvarchar(100),
	 @rOrgGroupId smallint
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
		
BEGIN 
  BEGIN
		SET @rTitle = sCommon.fSearchStringGet(@rTitle)
  END
	 
	SELECT 
			QM.Id,
			QM.Title,
			QM.Remark,
			QM.IsObsolete
  FROM 
         sCommunication.tQueryCategoryMaster QM
  WHERE 
			((QM.Id = @rId) OR (@rId = 0))
		AND ((QM.Title like @rTitle) OR (ISNULL(@rTitle,'') = '')) 
		AND (QM.OrgGroupId = @rOrgGroupId)	
END
GO
PRINT N'Altering [sCommunication].[pQueryListGet]...';


GO


ALTER PROCEDURE [sCommunication].[pQueryListGet]
	 
	 @rQueryCategoryId int = 0,
	 --@rTitle nvarchar(100),
	 @rOrgGroupBatchId int,
	 @rId bigint,
	 @rCreatedUserId bigint
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			
BEGIN 
	  --BEGIN
			--SET @rTitle = sCommon.fSearchStringGet(@rTitle)
	  --END
	SELECT 
			QM.Id AS QueryId,
			QCM.Id AS QueryCategoryId,
			ISNULL(QCM.Title,'') AS QueryCategoryMaster,
			QM.Title,
			QM.Remark,
			QM.CreatedDateTime,
			QM.StatusId,
			ISNULL(sm.Title,'') AS StatusMaster,
			QM.IsAssigneeView,
			QM.IsUserView,
			QM.CreatedUserId AS QueryCreatedUserId
  FROM 
			sCommunication.tQuery QM
		INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QM.QueryCategoryId=QCM.Id
        INNER JOIN sCommon.tStatusMaster SM ON SM.Id=QM.StatusId
        INNER JOIN sSecurity.tUser U ON QM.CreatedUserId = U.Id
  WHERE 
			((QCM.Id = @rQueryCategoryId) OR (@rQueryCategoryId = 0))
        AND	(QM.OrgGroupBatchId=@rOrgGroupBatchId) 
        AND ((QM.Id=@rId) OR (@rId=0))
        AND ((QM.CreatedUserId=@rCreatedUserId) OR (@rCreatedUserId=0))
END
GO
PRINT N'Altering [sCommunication].[pQueryQueueGet]...';


GO

ALTER PROCEDURE [sCommunication].[pQueryQueueGet]
	 
	 @rQueryCategoryId int = 0,
	 --@rCreatedUserId bigint,
	 @rOrgGroupBatchId int,
	 @rOrgGroupId smallint,
	 @rQueryId bigint,
	 @rUserSourceId bigint,
	 @rMyList bit
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
		
BEGIN 
IF(@rMyList=0)
BEGIN
	SELECT 
			QCM.Id AS QueryCategoryId,
			ISNULL(QCM.Title,'') AS QueryCategoryMaster,
			QM.Title,
			QM.Remark,
			QM.CreatedDateTime,
			QM.StatusId,
			ISNULL(sm.Title,'') AS StatusMaster,
			QM.Id AS QueryId,
			QM.IsUserView,
			QM.IsAssigneeView,
			ODM.Title AS Department,
			U.DisplayTitle AS SourceName, 
			U.SourceTypeId, 
			'Employee' AS SourceType,
			QM.CreatedUserId AS QueryCreatedUserId
	FROM 
			sCommunication.tQuery QM
		INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QM.QueryCategoryId=QCM.Id
        INNER JOIN sCommon.tStatusMaster SM ON SM.Id=QM.StatusId
        INNER JOIN sSecurity.tUser U ON U.Id=QM.CreatedUserId
        INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = U.SourceId AND U.SourceTypeId = 95
        INNER JOIN sSetup.tDepartmentMaster ODM ON EJD.OrganizationDepartmentId=ODM.Id  
	WHERE 
  
			((QCM.Id = @rQueryCategoryId) OR (@rQueryCategoryId = 0))
		AND ((QM.Id = @rQueryId) OR (@rQueryId = 0)) 
		AND (QCM.OrgGroupId = @rOrgGroupId) 
		AND (QM.OrgGroupBatchId = @rOrgGroupBatchId)
	
	UNION 

	SELECT 
			QCM.Id AS QueryCategoryId,
			ISNULL(QCM.Title,'') AS QueryCategoryMaster,
			QM.Title,
			QM.Remark,
			QM.CreatedDateTime,
			QM.StatusId,
			ISNULL(sm.Title,'') AS StatusMaster,
			QM.Id AS QueryId,
			QM.IsUserView,
			QM.IsAssigneeView,
			SA.ClassName + ' ' + SA.DivisionName  AS Department,
			U.DisplayTitle AS SourceName,
			U.SourceTypeId,
			'Student' AS SourceType,
			QM.CreatedUserId AS QueryCreatedUserId
	FROM 
			sCommunication.tQuery QM
        INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QM.QueryCategoryId=QCM.Id
        INNER JOIN sCommon.tStatusMaster SM ON SM.Id=QM.StatusId
        INNER JOIN sSecurity.tUser U ON U.Id=QM.CreatedUserId
        INNER JOIN sStudent.vStudentAcademic SA ON SA.StudentId = U.SourceId AND U.SourceTypeId = 2003 AND SA.OrgGroupBatchId = @rOrgGroupBatchId
	WHERE 
			((QCM.Id = @rQueryCategoryId) OR (@rQueryCategoryId = 0))
		AND ((QM.Id = @rQueryId) OR (@rQueryId = 0)) 
		AND (QCM.OrgGroupId=@rOrgGroupId)  
		AND (QM.OrgGroupBatchId=@rOrgGroupBatchId)
END
ELSE IF(@rMyList=1)
BEGIN

	SELECT 
			QCM.Id AS QueryCategoryId,
			ISNULL(QCM.Title,'') AS QueryCategoryMaster,
			QM.Title,
			QM.Remark,
			QM.CreatedDateTime,
			QM.StatusId,
			ISNULL(sm.Title,'') AS StatusMaster,
			QM.Id AS QueryId,
			QM.IsUserView,
			QM.IsAssigneeView,
			ODM.Title AS Department,
			U.DisplayTitle AS SourceName, 
			U.SourceTypeId, 
			'Employee' AS SourceType,
			QM.CreatedUserId AS QueryCreatedUserId
	FROM 
			sCommunication.tQuery QM
		INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QM.QueryCategoryId=QCM.Id
        INNER JOIN sCommon.tStatusMaster SM ON SM.Id=QM.StatusId
        INNER JOIN sSecurity.tUser U ON U.Id=QM.CreatedUserId
        INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = U.SourceId AND U.SourceTypeId = 95
        INNER JOIN sSetup.tDepartmentMaster ODM ON EJD.OrganizationDepartmentId=ODM.Id 
	WHERE 
			((QCM.Id = @rQueryCategoryId) OR (@rQueryCategoryId = 0))
		AND ((QM.Id = @rQueryId) OR (@rQueryId = 0)) 
		AND (QCM.OrgGroupId = @rOrgGroupId)
		AND (QM.OrgGroupBatchId = @rOrgGroupBatchId)
	    AND QueryCategoryId IN (select QueryCategoryId FROM sCommunication.tQueryCategoryAssignedTo where  SourceId = @rUserSourceId)
	    
	UNION 

	SELECT 
			QCM.Id AS QueryCategoryId,
			ISNULL(QCM.Title,'') AS QueryCategoryMaster,
			QM.Title,
			QM.Remark,
			QM.CreatedDateTime,
			QM.StatusId,
			ISNULL(sm.Title,'') AS StatusMaster,
			QM.Id AS QueryId,
			QM.IsUserView,
			QM.IsAssigneeView,
			SA.ClassName + ' ' + SA.DivisionName  AS Department,
			U.DisplayTitle AS SourceName,
			U.SourceTypeId,
			'Student' AS SourceType,
			QM.CreatedUserId AS QueryCreatedUserId
	FROM 
		sCommunication.tQuery QM
        INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QM.QueryCategoryId=QCM.Id
        INNER JOIN sCommon.tStatusMaster SM ON SM.Id=QM.StatusId
        INNER JOIN sSecurity.tUser U ON U.Id=QM.CreatedUserId
        INNER JOIN sStudent.vStudentAcademic SA ON SA.StudentId = U.SourceId AND U.SourceTypeId = 2003 AND SA.OrgGroupBatchId = @rOrgGroupBatchId
	WHERE 
			((QCM.Id = @rQueryCategoryId) OR (@rQueryCategoryId = 0))
		AND ((QM.Id = @rQueryId) OR (@rQueryId = 0)) 
		AND (QCM.OrgGroupId=@rOrgGroupId)  
		AND (QM.OrgGroupBatchId=@rOrgGroupBatchId)
		AND QueryCategoryId IN (select QueryCategoryId FROM sCommunication.tQueryCategoryAssignedTo where  SourceId = @rUserSourceId AND SourceTypeId <> 2015)
		
	UNION 

	SELECT 
			QCM.Id AS QueryCategoryId,
			ISNULL(QCM.Title,'') AS QueryCategoryMaster,
			QM.Title,
			QM.Remark,
			QM.CreatedDateTime,
			QM.StatusId,
			ISNULL(sm.Title,'') AS StatusMaster,
			QM.Id AS QueryId,
			QM.IsUserView,
			QM.IsAssigneeView,
			SA.ClassName + ' ' + SA.DivisionName  AS Department,
			U.DisplayTitle AS SourceName,
			U.SourceTypeId,
			'Student' AS SourceType,
			QM.CreatedUserId AS QueryCreatedUserId
	FROM 
		sCommunication.tQuery QM
        INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QM.QueryCategoryId=QCM.Id
        INNER JOIN sCommon.tStatusMaster SM ON SM.Id=QM.StatusId
        INNER JOIN sSecurity.tUser U ON U.Id=QM.CreatedUserId
        INNER JOIN sStudent.vStudentAcademic SA ON SA.StudentId = U.SourceId AND U.SourceTypeId = 2003 AND SA.OrgGroupBatchId = @rOrgGroupBatchId 
					AND SA.DivisionId IN (SELECT Id FROM sSetup.tDivisionMaster WHERE InchargeEmployeeId=@rUserSourceId)
	WHERE 
			((QCM.Id = @rQueryCategoryId) OR (@rQueryCategoryId = 0))
		AND ((QM.Id = @rQueryId) OR (@rQueryId = 0)) 
		AND (QCM.OrgGroupId=@rOrgGroupId)  
		AND (QM.OrgGroupBatchId=@rOrgGroupBatchId)
		AND QueryCategoryId IN (select QueryCategoryId FROM sCommunication.tQueryCategoryAssignedTo where  RIGHT(SourceId,2) = 24 AND SourceTypeId = 2015)
		
	UNION 

	SELECT 
			QCM.Id AS QueryCategoryId,
			ISNULL(QCM.Title,'') AS QueryCategoryMaster,
			QM.Title,
			QM.Remark,
			QM.CreatedDateTime,
			QM.StatusId,
			ISNULL(sm.Title,'') AS StatusMaster,
			QM.Id AS QueryId,
			QM.IsUserView,
			QM.IsAssigneeView,
			SA.ClassName + ' ' + SA.DivisionName  AS Department,
			U.DisplayTitle AS SourceName,
			U.SourceTypeId,
			'Student' AS SourceType,
			QM.CreatedUserId AS QueryCreatedUserId
	FROM 
		sCommunication.tQuery QM
        INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QM.QueryCategoryId=QCM.Id
        INNER JOIN sCommon.tStatusMaster SM ON SM.Id=QM.StatusId
        INNER JOIN sSecurity.tUser U ON U.Id=QM.CreatedUserId
        INNER JOIN sStudent.vStudentAcademic SA ON SA.StudentId = U.SourceId AND U.SourceTypeId = 2003 AND SA.OrgGroupBatchId = @rOrgGroupBatchId 
	WHERE 
			((QCM.Id = @rQueryCategoryId) OR (@rQueryCategoryId = 0))
		AND ((QM.Id = @rQueryId) OR (@rQueryId = 0)) 
		AND (QCM.OrgGroupId=@rOrgGroupId)  
		AND (QM.OrgGroupBatchId=@rOrgGroupBatchId)
		AND QueryCategoryId IN (select QueryCategoryId FROM sCommunication.tQueryCategoryAssignedTo where  RIGHT(SourceId,2) = 25 AND SourceTypeId = 2015)
END
END
GO
PRINT N'Altering [sCommunication].[pQueryRemarkCommentAdd]...';


GO

ALTER PROCEDURE [sCommunication].[pQueryRemarkCommentAdd]
	 
	@rOrgGroupId smallint,
	@rId AS bigint,
	@rQueryId as bigint,
	@rRemark nvarchar(200),
	@rCreatedUserId bigint,
	@rCreatedDateTime datetime,
	@rIsUserView bit
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	 		
BEGIN TRANSACTION
IF(@rId = 0)
DECLARE @lNextNumber BIGINT     
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sCommunication.tQueryComment', 0, 1, 1,@outNextNumber = @lNextNumber output
	
    BEGIN
	
	INSERT INTO sCommunication.tQueryComment
		(
			Id,
			QueryId,
			Remark,
			CreatedUserId,
			CreatedDateTime
		)
	VALUES
		(
			@lNextNumber,
			@rQueryId,
			@rRemark,
		    @rCreatedUserId,
			sCommon.fGetDate()
		)
		   
	END	
	--queue
	if(@rIsUserView = 1) 
	UPDATE sCommunication.tQuery SET IsAssigneeView = 0 WHERE Id = @rQueryId
	else	 
	UPDATE sCommunication.tQuery SET  IsUserView = 0 WHERE Id = @rQueryId
	 
	Select @lNextNumber AS Result
	COMMIT TRANSACTION
END TRY
	
	BEGIN CATCH
	    ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH  
END
GO
PRINT N'Altering [sCommunication].[pViewQueryRemarkGet]...';


GO

ALTER PROCEDURE [sCommunication].[pViewQueryRemarkGet]
	 
	 @rQueryId bigint = 0,
	 --@rTitle nvarchar(100),
	 @rId bigint
	 --@rQueryCategoryId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 
	  --BEGIN
			--SET @rTitle = sCommon.fSearchStringGet(@rTitle)
	  --END
	SELECT 
			QC.Id,
			QC.QueryId,
			QC.Remark,
			U.DisplayTitle AS UserName,
			QC.CreatedDateTime,
			QC.CreatedUserId AS CommentCreatedUserId,
			Q.CreatedUserId AS QueryCreatedUserId
	FROM 
			sCommunication.tQueryComment QC
		INNER JOIN sCommunication.tQuery Q ON Q.Id=QC.QueryId
		INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId
	WHERE 
			((QC.QueryId = @rQueryId) OR (@rQueryId = 0)) 
			order by QC.CreatedDateTime desc
END
GO
PRINT N'Altering [sConfig].[pConfigurationLevelMasterGet]...';


GO
ALTER PROCEDURE [sConfig].[pConfigurationLevelMasterGet] 
  
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 SELECT  4 AS ConfigurationLevelId,'User Configuration' AS LevelName
	 UNION ALL
	 SELECT  1,'Organization Configuration'
	 UNION ALL
	 SELECT  2,'Location Configuration'
	 UNION ALL
	 SELECT  3,'Sub Location Configuration'
	 UNION ALL
	 
	 SELECT  5,'Org Group Configuration'
	  
END
GO
PRINT N'Altering [sConfig].[pConfigurationMasterGet]...';


GO
ALTER PROCEDURE [sConfig].[pConfigurationMasterGet] 
 
	@rConfigurationLevelId [tinyint] = 0,
	@rSourceId bigint,
	@rSourceTypeId int,
	@rOrgGroupId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 SELECT 
	        CM.Id AS ID,
			MM.Title,
			CM.ItemKey,
			CM.ItemValue AS DefaultValue,
			ISNULL(CS.ItemValue,CM.ItemValue) AS ItemValue,
			CM.Remark AS VDescription,
			CM.ValidationTypeId AS ValidationType,
			CM.ConfigurationLevelId	
			--Remark,
			--TypeId,
			--MM.TitleResourceKeyId
			--IsObsolete
	   FROM sCommon.tModuleMaster MM
	   INNER JOIN sConfig.tConfigurationMaster CM ON CM.ModuleId = MM.Id
	   INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId=CM.ModuleId AND MP.OrgGroupId=@rOrgGroupId
	   LEFT JOIN sConfig.tConfigurationSetup CS ON CS.ConfigurationId = CM.Id AND CS.SourceId = @rSourceId AND CS.SourceTypeId = @rSourceTypeId
	   
	  WHERE  
			 (CM.ConfigurationLevelId = @rConfigurationLevelId)
			AND (CM.IsObsolete = 0) 
			
			ORDER BY MM.Title,CM.ItemKey			
END
GO
PRINT N'Altering [sEExam].[pAutoGenerateQuestionGet]...';


GO

ALTER PROCEDURE [sEExam].[pAutoGenerateQuestionGet]
	
	@rTopicId nvarchar(max)
 
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN  
	SELECT Id,Marks,TopicId,DifficultyLevelId,ISNULL(GroupQuestionId,0) AS  GroupQuestionId
	FROM sEExam.tQuestionMaster Where TopicId IN (select item from [sCommon].[fnSplit](@rTopicId,',')) 	 
	--Order By RAND(Id)  
	 --IF(@1Count > @rNoOfQuestions)
	 -- BEGIN
	 --    SET @1Count = @rNoOfQuestions
	 -- END
	
	--While (@1Count > 0)
	--  BEGIN	  
	--        SELECT @1QuestionId = QuestionId,@1Marks = Marks From #temp Where Id = @1Count 
	        
	--        IF NOT EXISTS(Select 1 FROM sEExam.tTestQuestion Where TestId = @rTestId 
	--        AND QuestionId = @1QuestionId) 
	--         BEGIN
	--            INSERT INTO sEExam.tTestQuestion
	--            SELECT @rTestId,@1QuestionId,@1Marks
	--         END   
	--  END		
END
GO
PRINT N'Altering [sEExam].[pAvailableTestsGet]...';


GO


ALTER PROCEDURE [sEExam].[pAvailableTestsGet]

		@rUserSourceTypeId smallint,
		@rUserSourceId bigint,
		@rBatchId int
			
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			
BEGIN  
	SELECT  
		TP.Id AS TestParticipantId,		
		TM.Title AS Test,
		VCS.SubjectName,
		TM.Id AS TestId,
		TM.TotalMarks,
		ISNULL(SM.Title,'')AS TestStatus,
		TP.TestStatusId			
  FROM 
	    sEExam.tTestParticipant TP 
		INNER JOIN sEExam.tTestMaster TM
		ON TM.Id=TP.TestId
		INNER JOIN sSetup.vClassSubject VCS
		ON VCS.ClassSubjectId=TM.ClassSubjectId
		LEFT JOIN sCommon.tStatusMaster SM
		ON SM.Id=TP.TestStatusId
			
WHERE 
		TP.SourceId=@rUserSourceId AND TP.SourceTypeId = @rUserSourceTypeId AND IsTestLock = 1
		
	ORDER BY TP.TestId DESC
		
END
GO
PRINT N'Altering [sEExam].[pDataBankMasterAdd]...';


GO

ALTER PROCEDURE [sEExam].[pDataBankMasterAdd]
	 
	        @rId int
	       ,@rCode nvarchar(50)
           ,@rTitle nvarchar(50)
           ,@rIsObsolete bit
           ,@rCreatedUserId bigint        
           ,@rOrgGroupId smallint
           ,@rAffiliationId smallint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	
	IF(@rId = 0)	
	BEGIN
		If Exists(select Id from sEExam.tDataBankMaster where Code=@rCode)
			BEGIN
			select -103 as Result
			RETURN
		END  
	END
	ELSE
	BEGIN
 
		If  Exists(select Id from sEExam.tDataBankMaster where Code=@rCode AND Id<>@rId)
		Begin
			select -103 as Result
			RETURN
		End

	END
		
	 BEGIN TRANSACTION	
 IF(@rId = 0)	
BEGIN

	DECLARE @lNextNumber INT     
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sEExam.tDataBankMaster', 0, 1, 1,@outNextNumber = @lNextNumber output


	INSERT INTO [sEExam].[tDataBankMaster]
           ([Id]
           ,[Code]
           ,[Title]
           ,[IsObsolete]
           ,[CreatedUserId]
           ,[CreatedDateTime]
           ,[UpdatedUserId]
           ,[UpdatedDateTime]
           ,[OrgGroupId]
           ,[AffiliationId])
     VALUES
           (
            @lNextNumber 
           ,@rCode
           ,@rTitle
           ,@rIsObsolete
           ,@rCreatedUserId
           ,sCommon.fGetDate()
           ,@rCreatedUserId
           ,sCommon.fGetDate()
           ,@rOrgGroupId
           ,@rAffiliationId
           )
		             
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
		UPDATE [sEExam].[tDataBankMaster]
		   SET  
			   [Code] = @rCode 
			  ,[Title] = @rTitle 
			  ,[IsObsolete] = @rIsObsolete  
			  ,[UpdatedUserId] = @rCreatedUserId 
			  ,[UpdatedDateTime] = sCommon.fGetDate()	      
			  ,[AffiliationId] = @rAffiliationId 	      
	      WHERE Id = @rId 	   
	 END  
		SELECT @lNextNumber AS Result
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sEExam].[pDataTopicTypeMasterAdd]...';


GO




ALTER PROCEDURE [sEExam].[pDataTopicTypeMasterAdd]
	 
	@rId int,
	--@rAffiliationId int,	
	@rDataSubjectId int,
	@rCode nvarchar(20),
	@rNumber int,
	@rTitle nvarchar(100),
	@rIsObsolete bit,
	@rOrderIndex int,
	@rCreatedUserId bigint, 
	@rOrgGroupId int,
	@rDataBankId int 
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	IF(@rId = 0)	
	BEGIN
		If Exists(select Id from sEExam.tDataTopicTypeMaster where Code=@rCode)
			BEGIN
			  Select -103 as Result
			RETURN
		END 
	END
	BEGIN TRANSACTION	
 IF(@rId = 0)	
BEGIN

	DECLARE @lNextNumber INT     
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sEExam.tDataTopicTypeMaster', 0, 1, 1,@outNextNumber = @lNextNumber output


	INSERT INTO sEExam.tDataTopicTypeMaster
		(
			Id,
			--AffiliationId,
			Code,
			Number,
			Title,
			DataSubjectId,
			OrgGroupId,
			IsObsolete,
			OrderIndex,
			CreatedUserId,
			CreatedDateTime,
			DataBankId
		)
	VALUES
		(
			@lNextNumber,
			--@rAffiliationId,
			@rCode,
			@rNumber,
			@rTitle,
			@rDataSubjectId,
			@rOrgGroupId,
			@rIsObsolete,
			@rOrderIndex,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rDataBankId
		)
		             
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE sEExam.tDataTopicTypeMaster
	    SET
	      --AffiliationId=@rAffiliationId,
	      --Code=@rCode,
	      Number=@rNumber,
	      Title=@rTitle,
	      DataSubjectId=@rDataSubjectId, 
	      IsObsolete=@rIsObsolete,
	      OrderIndex=@rOrderIndex,
	      UpdatedUserId=@rCreatedUserId,
	      UpdatedDateTime= sCommon.fGetDate() 
	      
	      WHERE Id = @rId 	   
	 END  
		SELECT @lNextNumber AS Result
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sEExam].[pDeleteTestQuestionOption]...';


GO
ALTER PROCEDURE [sEExam].[pDeleteTestQuestionOption]

	 @rId bigint
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON 

BEGIN 
	BEGIN TRY
		BEGIN TRANSACTION	
			
				IF NOT EXISTS(Select 1 FROM sEExam.tTestParticipantAnswer Where QuestionOptionId  = @rId)			 				
				BEGIN	
				      DELETE FROM sEExam.tQuestionOption Where Id = @rId	 
				 	  SELECT 1 AS RESULT		
				END				   
				ELSE
					  SELECT -101 AS RESULT
					  
		COMMIT TRANSACTION	
	END TRY
	
	BEGIN CATCH 
	    SELECT 0 AS RESULT
		ROLLBACK TRANSACTION
	END CATCH	
END
GO
PRINT N'Altering [sEExam].[pQuestionListGet]...';


GO

ALTER PROCEDURE [sEExam].[pQuestionListGet]
	 
	 @rId bigint = 0,
	 @rTopicId int,
	 @rClassSubjectId int,
	 @rClassId int,
	 @rDifficultyLevelId int,
	 @rOrgId int 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON 

BEGIN 	 
	
	SELECT 
		
		QM.Id,
		QM.TopicId,
		DLM.Id AS DifficultyLevelId,
		ISNULL(QM.QuestionParagraphId,0)AS QuestionParagraphId,
		QM.QuestionDescription,
		ISNULL(QM.QuestionDescription2,'')AS QuestionDescription2,
		ISNULL(QP.QuestionParagraphDescription,'') AS QuestionParegraphDescription,	
		ISNULL(QP.QuestionParagraphDescription2,'') AS QuestionParegraphDescription2,												  
		QM.Marks,
		QM.IsObsolete,
		QM.OrderIndex,
		DLM.Title AS DifficultyLevel,
		CM.Title AS Class,
		VCS.Title AS SubjectName,
		TM.Title AS Topic,
		ISNULL(QM.GroupQuestionId,0) AS QuestionGroupId  
		      
	FROM 
			sEExam.tQuestionMaster QM
		INNER JOIN sEExam.tDataTopicMaster TM
			ON QM.TopicId= TM.Id
		INNER JOIN sEExam.tDataSubjectMaster VCS
			ON TM.DataSubjectId=VCS.Id
		INNER JOIN sEExam.tDifficultyLevelMaster DLM
			ON DLM.Id=QM.DifficultyLevelId
		INNER JOIN sSetup.vAffiliationClassGroup CM
			ON CM.Id=TM.ClassGroupId 
		LEFT JOIN sEExam.tQuestionParagraph QP ON Qp.Id = QM.QuestionParagraphId
             
	WHERE  
			((QM.Id = @rId) OR (@rId = 0))
		 AND((QM.OrgId = @rOrgId) OR (@rOrgId = 0))
		 AND((QM.TopicId = @rTopicId) OR (@rTopicId = 0))
         AND((VCS.Id = @rClassSubjectId) OR (@rClassSubjectId = 0)) 
         AND((CM.ClassGroupId = @rClassId) OR (@rClassId = 0)) 
         AND((DLM.Id = @rDifficultyLevelId) OR (@rDifficultyLevelId = 0)) 
         AND CM.AffiliationId = 3
      
        --Order By QuestionGroupId
	
		
END
GO
PRINT N'Altering [sEExam].[pQuestionMasterAdd]...';


GO
ALTER PROCEDURE [sEExam].[pQuestionMasterAdd]
	 
	@rId bigint,
	@rTopicId int,
	@rDifficultyLevelId tinyint,
	@rQuestionParagraphId bigint,
	@rQuestionDescription nvarchar(max),
	@rQuestionDescription2 nvarchar(max),
	@rMarks decimal(6,2),
	@rIsObsolete bit,
	@rOrderIndex smallint,
	@rOrgId int,
	@rCreatedUserId bigint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
BEGIN TRANSACTION	
IF(@rId = 0)	
BEGIN

	DECLARE @lNextNumber BIGINT   
	DECLARE @1NextOrderIndex int  
	
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sEExam.tQuestionMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	IF(@rOrderIndex = 0)
	BEGIN
    Select @rOrderIndex = ISNULL(Max(OrderIndex),0) From sEExam.tQuestionMaster Where TopicId = @rTopicId
    SET @rOrderIndex = @rOrderIndex + 1;
    END
    
	INSERT INTO sEExam.tQuestionMaster
		(
			Id,
			TopicId,
			DifficultyLevelId,
			QuestionParagraphId,
			QuestionDescription,
			QuestionDescription2,
			Marks,
			IsObsolete,
			OrderIndex,
			OrgId,
			CreatedUserId,
			CreatedDateTime
		)
	VALUES
		(
			@lNextNumber,
			@rTopicId,
			@rDifficultyLevelId,
			@rQuestionParagraphId,
			@rQuestionDescription,
			@rQuestionDescription2,
			@rMarks,
			@rIsObsolete,
			@rOrderIndex,
			@rOrgId,
			@rCreatedUserId,
			sCommon.fGetDate()
		)
		   SELECT @lNextNumber AS Result          
	END	 
	 ELSE
	 SET @lNextNumber = @rId 
	 
	    UPDATE  sEExam.tQuestionMaster
	    SET
			TopicId=@rTopicId,
			DifficultyLevelId=@rDifficultyLevelId,
			QuestionParagraphId=@rQuestionParagraphId,
			QuestionDescription=@rQuestionDescription,
			QuestionDescription2=@rQuestionDescription2,
			Marks=@rMarks,
			IsObsolete=@rIsObsolete,
			OrderIndex=@rOrderIndex,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate() 
			 
	      WHERE Id = @rId 	   
	 	 
		  SELECT @lNextNumber AS Result  
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sEExam].[pRptQuestionListGet]...';


GO


ALTER PROCEDURE [sEExam].[pRptQuestionListGet]

	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rTestId int,
	 @rTopicId int,
	 @rClassSubjectId int,
	 @rClassId int,
	 @rDifficultyLevelId int,
	 @rOrgId int,
	 @rDataBankId int,
	 @rAffilationId int 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON 

BEGIN 
	 
	SELECT 
		--@rBuilder1 AS Builder1,
		--@rBuilder2 AS Builder2,
		QM.Id,
		QM.TopicId,
		DLM.Id AS DifficultyLevelId,
		ISNULL(QM.QuestionParagraphId,0)AS QuestionParagraphId,
		QM.QuestionDescription,
		ISNULL(QM.QuestionDescription2,'')AS QuestionDescription2,
		QM.Marks,
		QM.IsObsolete,
		QM.OrderIndex,
		DLM.Title AS DifficultyLevel,
		CM.Title AS Class,
		VCS.Title AS SubjectName,
		TM.Title AS Topic ,
		QO.ChoiceDescription,
		QO.Id AS ChoiceDescriptionId,
		QM.Marks AS QuestionMArks,		 
		TM.Id AS TestId,
		VCS.Title As Subject,
		QO.OrderIndex AS OptNo 
		
	FROM  
			sEExam.tTestQuestion TQ INNER JOIN 
	
			sEExam.tQuestionMaster QM ON TQ.QuestionId = QM.Id AND TQ.TestId = @rTestId 
		INNER JOIN sEExam.tDataTopicMaster TM
			ON QM.TopicId= TM.Id
		INNER JOIN sEExam.tDataSubjectMaster VCS
			ON TM.DataSubjectId=VCS.Id
		INNER JOIN sEExam.tDifficultyLevelMaster DLM
			ON DLM.Id=QM.DifficultyLevelId
		INNER JOIN sSetup.vAffiliationClassGroup CM
			ON CM.Id=TM.ClassGroupId
		INNER JOIN sEExam.tQuestionOption QO 
		ON QO.QuestionId=QM.Id 
			
	
		--	sEExam.tQuestionMaster QM
		--INNER JOIN sEExam.tQuestionOption QO 
		--	ON QO.QuestionId=QM.Id
		--INNER JOIN sEExam.tDataTopicMaster TM
		--	ON QM.TopicId= TM.Id
		
		--INNER JOIN sEExam.tDataSubjectMaster VCS
		--	ON TM.DataSubjectId=VCS.Id
		--INNER JOIN sEExam.tDifficultyLevelMaster DLM
		--	ON DLM.Id=QM.DifficultyLevelId
		--INNER JOIN sSetup.vAffiliationClassGroup CM
		--	ON CM.Id=TM.ClassGroupId 
		----INNER JOIN sEExam.tTestQuestion TQ ON TQ.QuestionId=QM.Id AND (TQ.TestId=@rTestId OR @rTestId=0)
		----INNER JOIN sEExam.tTestMaster TestM ON TestM.Id=TQ.TestId
		--INNER JOIN [sSetup].[vClassSubject] CS ON CS.ClassSubjectId =  TM.DataSubjectId
             
	WHERE  
		 
		  ((QM.OrgId = @rOrgId) OR (@rOrgId = 0))
		 AND((QM.TopicId = @rTopicId) OR (@rTopicId = 0))
         AND((VCS.Id = @rClassSubjectId) OR (@rClassSubjectId = 0)) 
         AND((CM.ClassGroupId = @rClassId) OR (@rClassId = 0)) 
         AND((DLM.Id = @rDifficultyLevelId) OR (@rDifficultyLevelId = 0)) 
         AND CM.AffiliationId = @rAffilationId AND TQ.TestId = @rTestId
         --AND (TQ.TestId=@rTestId OR @rTestId=0) 
		
END
GO
PRINT N'Altering [sEExam].[pTakeTestGet]...';


GO


ALTER PROCEDURE [sEExam].[pTakeTestGet]

	 @rTestParticipantId bigint
           
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
--DECLARE @lScoremark decimal(6,2)
--SET @lScoremark =(SELECT SUM(TPAT.ScoredMark) FROM sEExam.tTestParticipantAnswer TPAT WHERE TPAT.TestParticipantId=9999000000567)
	  
	SELECT 
		
		ISNULL(TPA.TestParticipantId,0) AS TestParticipantId, 
		TPA.TestId,
		TP.SourceId,
		TP.SourceTypeId,
		QM.Id AS QuestionId,
		QO.Id AS QuestionOptionId,
		ISNULL(TPA.QuestionOptionId,0) AS AnweredQuestionOptionId,
		QM.QuestionDescription AS QuestionDescription,
		ISNULL(QM.QuestionDescription2,'') AS QuestionDescription2,
		QO.ChoiceDescription AS ChoiceDescription,
		ISNULL(QO.ChoiceDescription2,'') AS ChoiceDescription2,
		ISNULL(TPA.OrderIndex,0)AS OrderIndex,
		QM.Marks AS QuestionMarks,
		QO.IsKey,
		TPA.AnswerStatusId,
		ISNULL(Qp.QuestionParagraphDescription,'') AS QuestionParagraphDescription 
	    --ISNULL(@lScoremark,0)AS ScoredMarks, 
	 
FROM 
		sEExam.tTestParticipant TP INNER JOIN 
	    sEExam.tTestParticipantAnswer TPA ON TP.Id = TPA.TestParticipantId	  
		INNER JOIN sEExam.tQuestionMaster QM
		ON QM.Id=TPA.QuestionId  
		 INNER JOIN sEExam.tTestQuestion TQ ON TQ.QuestionId = QM.Id AND TQ.TestId = TP.TestId
		INNER JOIN sEExam.tQuestionOption QO
		ON QO.QuestionId=QM.Id 
		LEFT JOIN sEExam.tQuestionParagraph QP ON Qp.Id = QM.QuestionParagraphId
WHERE  

        TP.Id = @rTestParticipantId
		--TPA.TestId=@rTestId AND 
		--SourceId = @rSourceId AND SourceTypeId = @rSourceTypeId 
		
	ORDER BY TQ.OrderIndex ASC,ISNULL(Qp.QuestionParagraphDescription,'') ASC
		
END
GO
PRINT N'Altering [sEExam].[pTestAnalysisGet]...';


GO


ALTER PROCEDURE [sEExam].[pTestAnalysisGet]
			
			@rTestId int
			
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	
Select 
     
     QuestionDescription,
     Topic,
     TopicId,
     QuestionId,
     COUNT(Pvt.[0]) AS Wrong,
     COUNT(Pvt.[1]) AS RightA,
     COUNT(pvt.[2]) AS NotAttempt,
     COUNT(Pvt.[3]) AS SKIP
    
     --Pvt.[0] AS Wrong,
     --Pvt.[1] AS true
     --Pvt.[-1] AS Skip, 
 from
 (
    SELECT  
	TPA.TestId,
	TopicId,
	TPA.TestParticipantId AS  TestParticipantId,
	TPA.QuestionId AS QuestionId,
	TPA.QuestionOptionId AS TPAQuestionOptionId,
	TQM.Marks AS QuestionMarks,
	TPA.ScoredMark AS ScoredMarks,
	TPA.AnswerStatusId,
	TPA.OrderIndex AS OrderIndex,
	CASE When tpa.AnswerStatusId = 533 Then 3
	WHEN tpa.AnswerStatusId = 532 Then 2
	When tpa.AnswerStatusId = 531 AND Qo.IsKey = 1 THEN 1
	ELSE 0 END AS IsKey123,
	
	--CASE WHEN QO.IsKey IS NULL THEN 2
 --   WHEN QO.IsKey =1 THEN 1
	-- WHEN QO.IsKey = 0 THEN 0
	-- END	
	--AS IsKey123,
    TQ.QuestionDescription,
    DTM.Title AS Topic 
	
FROM  
	sEExam.tTestParticipantAnswer TPA
	INNER JOIN sEExam.tTestParticipant TP ON TP.Id = TPA.TestParticipantId
	INNER JOIN sEExam.tTestQuestion TQM ON TQM.QuestionId = TPA.QuestionId AND TP.TestId = TQM.TestId
	INNER JOIN sEExam.tQuestionMaster TQ  ON TPA.QuestionId=TQ.Id AND TQM.QuestionId = TQ.Id
	INNER JOIN sEExam.tDataTopicMaster DTM ON DTM.Id = TQ.TopicId
	LEFT JOIN sEExam.tQuestionOption QO   ON QO.Id=TPA.QuestionOptionId AND QO.QuestionId = TPA.QuestionId	
    where TP.TestId = @rTestId 
    
	
 ) t
 pivot (min(TestId) FOR IsKey123 IN ([3],[2],[1],[0])) AS Pvt
 
 Group By QuestionDescription,QuestionId,Topic,TopicId
		
END
GO
PRINT N'Altering [sEExam].[pTestAssignGet]...';


GO


ALTER PROCEDURE [sEExam].[pTestAssignGet]

			--@rClassId int,
			@rDivisionId int,
			@rTestId int,
			@rBatchId int,			 
			@rSourceTypeID int,
			@rOrgId int,
			@rClassId int
           
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON  
BEGIN    

    SELECT  
			--VSA.AcademicId,
			VSA.RollNo,
			VSA.StudentId AS SourceId,
			VSA.Name AS StudentName,			
			'Student' AS ParticipantType,
			2003 AS SourceTypeId,
			VSA.DivisionId, 
			VSA.Code,	   
			CASE WHEN ISNULL(A.TestId,0) != 0 THEN 1 ELSE 0 END AS IsSelected,
			ISNULL(A.TestStatusId,0) AS TestStatusId,
			VSA.DivisionName AS DivisionName
    
    FROM 
			 sStudent.vStudentAcademic VSA
			 LEFT JOIN sEExam.tTestAssign A ON A.SourceId = VSA.StudentId AND A.SourceTypeId = 2003 AND A.TestId = @rTestId
			 LEFT JOIN sCommon.tStatusMaster SM ON SM.Id = A.TestStatusID
	WHERE 
		--VSA.DivisionId=@rDivisionId
	 --   AND 
	    VSA.BatchId=@rBatchId  
		 
    --ORDER BY VSA.RollNo ASC 
	
UNION ALL
  
      SELECT 
          0 AS RollNo,
          EM.EmployeeId AS  SourceId,
          EM.EmployeeName AS StudentName,
	      'Employee' AS ParticipantType,
		  95 AS SourceTypeId,
		  0 AS DivisionId,
          EM.Code,
		  CASE WHEN ISNULL(A.TestId,0) != 0 THEN 1 ELSE 0 END AS IsSelected,
          ISNULL(A.TestStatusId,0) AS TestStatusId,
          EM.DepartmentName AS DivisionName
         
      FROM sHrm.vEmployeeCommonDetail EM LEFT JOIN sEExam.tTestAssign A ON A.SourceId = EM.EmployeeId AND A.SourceTypeId = 95 AND A.TestId = @rTestId
      LEFT JOIN sCommon.tStatusMaster SM ON SM.Id = A.TestStatusID 
      
      WHERE OrgID = @rOrgId
  
 UNION ALL
     SELECT 
          0 AS RollNo,
          DM.Id AS  SourceId,
          DM.Title AS StudentName,
		  'Division' AS ParticipantType,
		  2005 AS SourceTypeId,
		  DM.Id AS DivisonId, 
          DM.Code,
		  CASE WHEN ISNULL(A.TestId,0) != 0 THEN 1 ELSE 0 END AS IsSelected,
          ISNULL(A.TestStatusId,0) AS TestStatusId,
          DM.Title AS DivisionName    
         
      FROM sSetup.tDivisionMaster DM  LEFT JOIN sEExam.tTestAssign A ON A.SourceId = DM.Id AND A.TestId = @rTestId
      LEFT JOIN sCommon.tStatusMaster SM ON SM.Id = A.TestStatusID 
      
      WHERE 
          ClassId = @rClassId AND DM.IsObsolete = 0 
END
GO
PRINT N'Altering [sEExam].[pTestMasterAdd]...';


GO

ALTER PROCEDURE [sEExam].[pTestMasterAdd]
	 
	@rId int,
	@rCode nvarchar(20),
	@rTitle nvarchar(100),
	@rDataSubjectId int,
	@rDataBankId int,
	@rClassGroupId int,	
	@rTestDate date,
	@rFromTime datetime,
	@rToTime datetime,
	@rIsDisplayResultOnComplete bit,
	@rIsSMSResultOnComplete bit,
	@rIsAllowReview bit,
	@rIsAutoPostResultToExam bit,
	@rTotalMarks decimal(6,2),
	@rIsObsolete bit,
	@rOrderIndex int,
	@rCreatedUserId bigint,
	@rCreatedDateTime datetime,
	@rUpdatedUserId bigint,
	@rUpdatedDateTime datetime,
	@rOrgId int,
	@rClassId int,
	@rClassSubjectId int,
	@rTestTemplateId int,
	@rAssignedSourceTypeId int,
	@rTestDuration int,
	@rIsTestLock bit,
	@rTestQuestion int	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
		IF(@rId = 0)	
	BEGIN
		IF Exists(select Id from sEExam.tTestMaster where Code=@rCode)
			BEGIN
			  Select -103 as Result
			RETURN
		END  
	END
	ELSE
	BEGIN 
		IF  Exists(select Id from sEExam.tTestMaster where Code=@rCode AND Id<>@rId)
		BEGIN
			select -103 as Result
			RETURN
		END

	END
	
	 BEGIN TRANSACTION	
 IF(@rId = 0)	
BEGIN

	DECLARE @lNextNumber INT     
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sEExam.tTestMaster', 0, 1, 1,@outNextNumber = @lNextNumber output

	INSERT INTO sEExam.tTestMaster
		(
			Id,
			Code,
			Title,
			DataSubjectId,
			TestDate,
			FromTime,
			ToTime,
			IsDisplayResultOnComplete,
			IsSMSResultOnComplete,
			IsAllowReview,
			IsAutoPostResultToExam,
			IsObsolete,
			TotalMarks,
			CreatedUserId,
			CreatedDateTime,
			OrgId,
			DataBankId,
			ClassGroupId,
			ClassId,
			ClassSubjectId,
			TestTemplateId,
			AssignedSourceTypeId,
			TestDuration,
			IsTestLock,
			TestQuestion		
		)
	VALUES
		(
			@lNextNumber,
			@rCode,
			@rTitle,
			@rDataSubjectId,
			@rTestDate,
			@rFromTime,
			@rToTime,
			@rIsDisplayResultOnComplete,
			@rIsSMSResultOnComplete,
			@rIsAllowReview,
			@rIsAutoPostResultToExam,
			@rIsObsolete,
			@rTotalMarks,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rOrgId,
			@rDataBankId,
			@rClassGroupId,
			@rClassId,
			@rClassSubjectId,
			@rTestTemplateId,
			@rAssignedSourceTypeId,
			@rTestDuration,
			0,
			@rTestQuestion
		)
		             
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE sEExam.tTestMaster
	    SET
	      Code=@rCode,
	      Title=@rTitle,
	      DataSubjectId=@rDataSubjectId,
	      ClassGroupId = @rClassGroupId,
	      TestDate=@rTestDate,
	      FromTime=@rFromTime,
	      ToTime=@rToTime,
	      IsDisplayResultOnComplete=@rIsDisplayResultOnComplete,
	      IsSMSResultOnComplete=@rIsSMSResultOnComplete,
	      IsAllowReview=@rIsAllowReview,
	      IsAutoPostResultToExam=@rIsAutoPostResultToExam,
	      IsObsolete=@rIsObsolete,
	      TotalMarks =@rTotalMarks,
	      UpdatedUserId=@rUpdatedUserId,
	      UpdatedDateTime= sCommon.fGetDate(),
	      classId = @rClassId,
	      ClassSubjectId = @rClassSubjectId,
	      TestTemplateId = @rTestTemplateId,
	      AssignedSourceTypeId = @rAssignedSourceTypeId,
	      TestDuration = @rTestDuration,
	      IsTestLock = @rIsTestLock,
	      TestQuestion = @rTestQuestion      
	      
	      WHERE Id = @rId 	   
	 END  
		SELECT @lNextNumber AS Result
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sEExam].[pTestMasterGet]...';


GO

ALTER PROCEDURE [sEExam].[pTestMasterGet]
	 
	 @rId int = 0,
	 --@rAffiliationId int,
	 @rTitle nvarchar(100),
	 @rCode nvarchar(20),
	 @rDataSubjectId int,
	 @rClassGroupId int,
	 @rDataBankId int,
	 @rOrgId int,
	 @rClassId int,
	 @rClassSubjectId int,
	 @rTestTemplateId int,
	 @rIsObsolete bit
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON		 

BEGIN 
	  BEGIN	  
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
			SET @rCode = sCommon.fSearchStringGet(@rCode)
	  END
	 
	SELECT 
		TM.Id,
		TM.Code,
		TM.Title,
		TM.TestDate,
		TM.DataSubjectId,
		TM.FromTime,
		TM.ToTime,
		TM.IsDisplayResultOnComplete,
		tm.IsSMSResultOnComplete,
		TM.IsAllowReview,
		TM.IsAutoPostResultToExam,
		TM.IsObsolete,
		TM.TotalMarks,
		DSM.Title AS DataSubjectTitle,
		TM.ClassGroupId,
		CGM.Title AS ClassGroupTitle,
		TM.DataBankId,
		DBM.Title AS DataBank,
		TM.ClassId,
		TM.ClassSubjectId,
		TM.TestTemplateId,
		CM.Title AS ClassName,
		CS.SubjectName AS ClassSubjectName,	
		'' AS TestTemplateName,
		ISNULL(AssignedSourceTypeId,0) AS AssignSourceTypeId,
		ISNULL(TestDuration,0) AS TestDuration,
		ISNULL(IsTestLock,0) AS IsTestLock,
		ISNULL(TestQuestion,0) AS TestQuestion  									   
	    --VBC.ClassName      
  FROM 
        sEExam.tTestMaster TM
        INNER JOIN  sEExam.tDataSubjectMaster DSM
        ON DSM.Id = TM.DataSubjectId
        INNER JOIN sEExam.tDataBankMaster DBM ON DBM.Id = TM.DataBankId
        INNER JOIN sSetup.tClassGroupMaster CGM ON CGM.Id = TM.ClassGroupId
        INNER JOIN sSetup.tClassMaster CM ON CM.Id = TM.ClassId
        INNER JOIN [sSetup].[vClassSubject] CS ON CS.ClassSubjectId = TM.ClassSubjectId  
        
  WHERE  
		   ((TM.Id = @rId) OR (@rId = 0))
      AND  ((TM.OrgId = @rOrgId) OR (@rOrgId = 0))
      AND  ((TM.Title like @rTitle) OR (ISNULL(@rTitle,'') = '')) 
      AND  ((TM.Code like @rCode) OR (ISNULL(@rCode,'') = '')) 
      AND  (TM.ClassGroupId = @rClassGroupId OR @rClassGroupId = 0) 
      AND  (TM.DataSubjectId = @rDataSubjectId OR @rDataSubjectId = 0)
      AND  (TM.ClassId = @rClassId OR @rClassId = 0)
      AND  (TM.ClassSubjectId = @rClassSubjectId OR @rClassSubjectId = 0)
      AND  (TM.TestTemplateId = @rTestTemplateId OR @rTestTemplateId = 0)
      AND  (TM.DataBankId = @rDataBankId OR @rDataBankId = 0)
      AND  (TM.IsObsolete = @rIsObsolete)
      
END
GO
PRINT N'Altering [sEExam].[pTestParticipantAdd]...';


GO
 
ALTER PROCEDURE [sEExam].[pTestParticipantAdd]
	  
	@rId bigint,
	@rTestId int,
	@rSourceId bigint,
	@rSourceTypeId int, 
	@rTestDate date=NULL,
	@rStartTime time(7)=NULL,
	@rEndTime time(7)=NULL,
	@rTestStatusId smallint=NULL,
	@rTotalMarks decimal(6,2)=NULL,
	@rScoredMarks decimal(6,2)=NULL,
	@rTotalQuestions int=NULL,
	@rRightQuestions int=NULL,
	@rWrongQuestions int=NULL,
	@rNotAttemptedQuestions int=NULL,
	@rSkippQuestion int=NULL,
	@rOrgId int,
	@rMode smallint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	 
	IF(@rId = 0)
	BEGIN 
	DECLARE @lNextNumber bigint     
	EXECUTE sCommon.pTableRowIdGet  @rOrgId, 'sEExam.tTestParticipant', 0, 1, 1,@outNextNumber = @lNextNumber output
	END 
 IF(@rSourceTypeId = 2005)
   BEGIN   
		 DELETE TP FROM sEExam.tTestParticipant TP INNER JOIN sStudent.vStudentAcademic VSA 
		 ON TP.SourceId = VSA.StudentId 
		 Where DivisionId = @rSourceId  AND TestId = @rTestId
		 
		    --IF(@rId = 0)
		     BEGIN
			 INSERT INTO sEExam.tTestParticipant
			 SELECT @rTestId,2003,StudentId,@rTestDate,@rStartTime,@rEndTime,543,
			 @rTotalMarks,@rScoredMarks,@rTotalQuestions,@rRightQuestions,@rWrongQuestions,@rNotAttemptedQuestions,@rSkippQuestion,@lNextNumber + ROW_NUMBER() over(order by StudentId desc)
			 FROM sStudent.vStudentAcademic VSA Where DivisionId = @rSourceId  
			  
			 SELECT @lNextNumber = MAX(Id) from sEExam.tTestParticipant where Id like  CONVERT(nvarchar(50),@rOrgId) + '%'
             EXECUTE sCommon.pTableRowIdModify  @rOrgId,'sEExam.tTestParticipant',@lNextNumber,0,0,0,@lNextNumber output 
			  
			 UPDATE  TA 
			 SET TA.TestStatusId = 543
			 FROM sEExam.tTestAssign TA INNER JOIN sStudent.vStudentAcademic VSA 
			 ON TA.SourceId = VSA.StudentId 
			 Where DivisionId = @rSourceId AND TA.TestId = @rTestId
			 END
           
         SELECT 1 AS Result 
   END 
    --EXECUTE sCommon.pTableRowIdModify   @rOrgId,'sEExam.tTestParticipant',@lNextNumber,0,0,0,@lNextNumber output 
   
ELSE
	 
   IF NOT EXISTS(SELECT 1 FROM sEExam.tTestParticipant Where  TestId = @rTestId 
   AND SourceId = @rSourceId AND SourceTypeId = @rSourceTypeId)	
   BEGIN
   
	INSERT INTO sEExam.tTestParticipant
		(
			Id,
			TestId,
			SourceId,
			SourceTypeId,
			TestDate,
			StartTime,
			EndTime,
			TestStatusId,
			TotalMarks,
			ScoredMarks,
			TotalQuestions,
			RightQuestions,
			WrongQuestions,
			NotAttemptedQuestions,
			SkippQuestions			
		)
	VALUES
		(
			@lNextNumber,
			@rTestId,
			@rSourceId,
			@rSourceTypeId,
			@rTestDate,
			CONVERT(CHAR(7),@rStartTime,108),
			--@rStartTime,
			@rEndTime,
			@rTestStatusId,
			@rTotalMarks,
			@rScoredMarks,
			@rTotalQuestions,
			@rRightQuestions,
			@rWrongQuestions,
			@rNotAttemptedQuestions,
			@rSkippQuestion
			
		)    
	--UPDATE sEExam.tTestParticipant SET TestStatusId = 1 WHERE SourceId = @rSourceId AND SourceTypeId = @rSourceTypeId AND TestId = @rTestId
	 --1 For Activated ,0 For Deactivated
	--SELECT 1 AS Result  
	END
	 ELSE
	 BEGIN
	 --SET @lNextNumber = @rId
	 IF(@rMode=1)
	 BEGIN
	  
	    UPDATE sEExam.tTestParticipant
	    SET
	     TestDate=@rTestDate,
	     StartTime=@rStartTime,
	     TestStatusId=@rTestStatusId,
	     TotalMarks=@rTotalMarks
	     WHERE Id = @rId
 	     --TestId = @rTestId AND SourceId = @rSourceId AND SourceTypeId = @rSourceTypeId
	     --SELECT 11 AS Result 	
	 END
	 ELSE IF(@rMode=2)
	 BEGIN
	 
	 UPDATE sEExam.tTestParticipant
	    SET
	     
	     --EndTime=@rEndTime,
	     TestStatusId=@rTestStatusId,
	     ScoredMarks=@rScoredMarks,
	     TotalQuestions=@rTotalQuestions,
	     RightQuestions=@rRightQuestions,
	     WrongQuestions=@rWrongQuestions,
	     NotAttemptedQuestions=@rNotAttemptedQuestions,
	     SkippQuestions = @rSkippQuestion
	      
	     WHERE Id = @rId 
	     --TestId = @rTestId AND SourceId = @rSourceId AND SourceTypeId = @rSourceTypeId
	     --SELECT 11 AS Result 
	  END    
	 END
	 
	 UPDATE sEExam.tTestParticipant SET TestStatusId = @rTestStatusId WHERE SourceId = @rSourceId AND SourceTypeId = @rSourceTypeId AND TestId = @rTestId
	 UPDATE sEExam.tTestAssign SET TestStatusId = @rTestStatusId Where SourceId = @rSourceId AND SourceTypeId = @rSourceTypeId AND TestId = @rTestId
	 SELECT 1 AS Result
	 	
	COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sEExam].[pTestParticipantAnswerGet]...';


GO


ALTER PROCEDURE [sEExam].[pTestParticipantAnswerGet]

		 @rTestParticipantId bigint
			
           
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	
SELECT  
	--0 AS  TestParticipantId,
	TPA.TestParticipantId AS  TestParticipantId,
	ISNULL(TPA.QuestionId,0) AS QuestionId,
	ISNULL(TPA.QuestionOptionId,0) AS QuestionOptionId,
	ISNULL(TQM.Marks,0)AS QuestionMarks,
	ISNULL(TPA.ScoredMark,0)AS ScoredMarks,
	TPA.AnswerStatusId,
	ISNULL(TPA.OrderIndex,0)AS OrderIndex,
	ISNULL(QO.IsKey,0)AS IsKey,
	TPA.TestId
	
FROM  
	sEExam.tTestParticipantAnswer TPA
	INNER JOIN sEExam.tTestParticipant TP ON TP.Id = TPA.TestParticipantId
	INNER JOIN sEExam.tTestQuestion TQM ON TQM.QuestionId = TPA.QuestionId AND TP.TestId = TQM.TestId
	--INNER JOIN sEExam.tQuestionMaster TQ  ON TPA.QuestionId=TQ.Id
	LEFT JOIN sEExam.tQuestionOption  QO  ON QO.Id=TPA.QuestionOptionId AND QO.QuestionId = TPA.QuestionId
	
WHERE 
 
	TPA.TestParticipantId = @rTestParticipantId 
	  
	 --TQ.TestId=@rTestId
	 --AND 
	 --TPA.TestId=@rTestId  AND TP.SourceId = @rSourceId AND TP.SourceTypeId = @rSourceTypeId
	 --AND TPA.QuestionId = @rQuestionId
		
	ORDER BY TPA.OrderIndex ASC
		
END
GO
PRINT N'Altering [sEExam].[pTestParticipantResultGet]...';


GO


ALTER PROCEDURE [sEExam].[pTestParticipantResultGet]
 
			@rTestId int,		 
			@rSourceTypeID int,
			@rSourceId bigint
           
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON  
BEGIN   

DECLARE @1TestAssignStatusId int

 
IF(@rSourceTypeID = 2003)
   BEGIN
	 SELECT  
		 VSA.RollNo,
		 VSA.Name,
		 VSA.Code,
		 P.SourceId,
		 P.SourceTypeId,	
	     ISNULL(P.TotalMarks,0) AS TotalMarks,
		 ISNULL(P.ScoredMarks,0) AS ScoredMarks,
		 ISNULL(P.TotalQuestions,0) AS TotalQuestions,
		 ISNULL(P.RightQuestions,0) AS RightQuestions,
		 ISNULL(P.WrongQuestions,0) AS WrongQuestions,
		 ISNULL(P.NotAttemptedQuestions,0) AS NotAttemptedQuestions,
		 ISNULL(P.SkippQuestions,0) AS SkippQuestions,
		 'Student' AS TypeName,
		 VSA.ClassName+'-'+VSA.DivisionName As ClassName
		 
		 FROM sEExam.tTestParticipant P INNER JOIN sEExam.tTestMaster TM ON TM.Id = P.TestId
		 INNER JOIN sStudent.vStudentAcademic VSA ON VSA.StudentId = P.SourceId  
		 Where SourceTypeId = @rSourceTypeID AND TestId = @rTestId
		 AND TestStatusId != 0 
		
		ORDER BY DivisionId, VSA.RollNo ASC
		END
		ELSE 
		     Select 			
			 ECD.Code AS RollNo,
			 ECD.EmployeeName AS Name,
			 ECD.Code,
			 P.SourceId,
			 P.SourceTypeId,			
			 ISNULL(P.TotalMarks,0) AS TotalMarks,
			 ISNULL(P.ScoredMarks,0) AS ScoredMarks,
			 ISNULL(P.TotalQuestions,0) AS TotalQuestions,
			 ISNULL(P.RightQuestions,0) AS RightQuestions,
			 ISNULL(P.WrongQuestions,0) AS WrongQuestions,
			 ISNULL(P.SkippQuestions,0) AS SkippQuestions,
			 ISNULL(P.NotAttemptedQuestions,0) AS NotAttemptedQuestions,
		     'Employee' AS TypeName,
		     ECD.DepartmentName AS ClassName
			 
			 FROM sEExam.tTestParticipant P INNER JOIN sEExam.tTestMaster TM ON TM.Id = P.TestId
			 INNER JOIN sHrm.vEmployeeCommonDetail ECD ON ECD.EmployeeId = P.SourceId 
			 AND TestStatusId != 0
 
			 Where SourceTypeId = @rSourceTypeID AND TestId = @rTestId   
			  AND TestStatusId != 0  
END
GO
PRINT N'Altering [sEExam].[pTestQuestionAdd]...';


GO
ALTER PROCEDURE [sEExam].[pTestQuestionAdd]
	
	 
	@rTestId bigint,
	@rQuestionId bigint,
	@rMarks decimal(6,2),
	@rOrgId int,
	@rOrderIndex int
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
    
    DECLARE @1LastOrderIndex int

	--DECLARE @lNextNumber BIGINT     
	
	--EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sEExam.tTestQuestion', 0, 1, 1,@outNextNumber = @lNextNumber output
  
IF NOT EXISTS (SELECT 1 FROM sEExam.tTestQuestion Where TestId = @rTestId AND QuestionId = @rQuestionId)
  BEGIN
     
    SELECT @1LastOrderIndex =  ISNULL(MAX(OrderIndex),0) + 1 From sEExam.tTestQuestion where TestId = @rTestId   
  
	INSERT INTO sEExam.tTestQuestion
		(  
			TestId,
			QuestionId,
			Marks,
			OrderIndex
		)
	VALUES
		( 
			@rTestId,
			@rQuestionId,
			@rMarks,
			@1LastOrderIndex
		)		
	END
	ELSE
	BEGIN
		   
	   UPDATE sEExam.tTestQuestion
	   
	   SET   OrderIndex = @rOrderIndex,
	         Marks = @rMarks	
	                  	   
	   Where TestId = @rTestId AND QuestionId = @rQuestionId       
	   
	END	  
		   SELECT 1 AS Result
		   COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sEExam].[pTestQuestionListGet]...';


GO

ALTER PROCEDURE [sEExam].[pTestQuestionListGet]
	 	 
	 @rTopicId int,
	 @rTestId int,
	 @rIsQuestionBank bit
	 	 
     WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON		 

BEGIN 

	IF(@rIsQuestionBank=1)
	BEGIN 
	SELECT 		
		QM.Id AS QuestionId,
		QM.TopicId,
		DLM.Id AS DifficultyLevelId,
		QM.QuestionDescription,
		QM.QuestionDescription2,
		QM.Marks,
		QM.IsObsolete,
		QM.OrderIndex,
		DLM.Title AS DifficultyLevel,
		TM.Title AS Topic,
		ISNULL(Qm.GroupQuestionId,0) AS QuestionGroupId,
		0 AS TestQuestions			 
      
 FROM   sEExam.tQuestionMaster QM
		INNER JOIN sEExam.tDataTopicMaster TM
		ON QM.TopicId= TM.Id
		INNER JOIN sEExam.tDifficultyLevelMaster DLM
		ON DLM.Id=QM.DifficultyLevelId 
	          
 WHERE 		
		((QM.TopicId = @rTopicId) OR (@rTopicId = 0))
		AND (QM.Id not in (SELECT QuestionId from sEExam.tTestQuestion WHERE TestId=@rTestId )OR (@rTestId=0))
		AND QM.IsObsolete = 0
		
ORDER BY QuestionDescription2 ASC

 END	
	ELSE	
BEGIN
	SELECT QM.Id AS QuestionId,
		   QM.TopicId,
		   DLM.Id AS DifficultyLevelId,
		   QM.QuestionDescription,
		   QM.QuestionDescription2,
		   TQ.Marks,
		   QM.IsObsolete,
		   ISNULL(TQ.OrderIndex,0) AS OrderIndex,
		   DLM.Title AS DifficultyLevel,
		   TM.Title AS Topic,
		   ISNULL(Qm.GroupQuestionId,0) AS QuestionGroupId  
	FROM 
			sEExam.tQuestionMaster QM
		    INNER JOIN sEExam.tDataTopicMaster TM
			ON QM.TopicId= TM.Id
		    INNER JOIN sEExam.tDifficultyLevelMaster DLM
			ON DLM.Id=QM.DifficultyLevelId
            INNER JOIN sEExam.tTestQuestion TQ
			ON TQ.QuestionId=QM.Id             
	WHERE 
		
			TQ.TestId=@rTestId
	
	order by QuestionDescription2 desc,TQ.OrderIndex
END
	
		
END
GO
PRINT N'Altering [sEExam].[pTestTemplateQuestionAdd]...';


GO
ALTER PROCEDURE [sEExam].[pTestTemplateQuestionAdd]
	 
	@rTestTemplateId bigint,
	@rQuestionId bigint,
	@rMarks decimal,
	@rOrgGroupId int
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	--BEGIN TRY
	
	-- BEGIN TRANSACTION	
 

	DECLARE @lNextNumber BIGINT     
	
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sEExam.tTestTemplateQuestion', 0, 1, 1,@outNextNumber = @lNextNumber output

	INSERT INTO sEExam.tTestTemplateQuestion
		(
			 
			TestTemplateId,
			QuestionId,
			Marks
		)
	VALUES
		(
		 
			@rTestTemplateId,
			@rQuestionId,
			@rMarks
		)
     
     SELECT 1 AS Result          
	
	
	-- COMMIT TRANSACTION
		
	--END TRY
	
	--BEGIN CATCH 
	--	ROLLBACK TRANSACTION
	--	SELECT -1 AS Result
	--END CATCH	
		
END
GO
PRINT N'Altering [sEExam].[pTestTemplateQuestionListGet]...';


GO

ALTER PROCEDURE [sEExam].[pTestTemplateQuestionListGet]
	 
	 @rTopicId int,
	 @rTestTemplateId int,
	 @rIsQuestionBank bit
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	IF(@rIsQuestionBank=1)
	BEGIN 
	SELECT 
		0 AS TestQuestionId,
		QM.Id AS QuestionId,
		QM.TopicId,
		DLM.Id AS DifficultyLevelId,
		QM.QuestionDescription,
		QM.Marks,
		QM.IsObsolete,
		QM.OrderIndex,
		DLM.Title AS DifficultyLevel,
		TM.Title AS Topic,
		ISNULL(Qm.GroupQuestionId,0) AS QuestionGroupId
      
	FROM 
			sEExam.tQuestionMaster QM
		INNER JOIN sEExam.tDataTopicMaster TM
			ON QM.TopicId= TM.Id
		INNER JOIN sEExam.tDifficultyLevelMaster DLM
			ON DLM.Id=QM.DifficultyLevelId
             
	WHERE 
		
		((QM.TopicId = @rTopicId) OR (@rTopicId = 0))
	AND (QM.Id not in (SELECT QuestionId from sEExam.tTestTemplateQuestion WHERE TestTemplateId=@rTestTemplateId )OR(@rTestTemplateId=0))
	AND Qm.IsObsolete = 0
ORDER BY QM.OrderIndex ASC

 END
	ELSE
BEGIN

SELECT 
		0 AS TestQuestionId,
		QM.Id AS QuestionId,
		QM.TopicId,
		DLM.Id AS DifficultyLevelId,
		QM.QuestionDescription,
		QM.Marks,
		QM.IsObsolete,
		QM.OrderIndex,
		DLM.Title AS DifficultyLevel,
		TM.Title AS Topic,
		ISNULL(Qm.GroupQuestionId,0) AS QuestionGroupId
      
	FROM 
			sEExam.tQuestionMaster QM
		INNER JOIN sEExam.tDataTopicMaster TM
			ON QM.TopicId= TM.Id
		INNER JOIN sEExam.tDifficultyLevelMaster DLM
			ON DLM.Id=QM.DifficultyLevelId
        INNER JOIN sEExam.tTestTemplateQuestion TQ
			ON TQ.QuestionId=QM.Id
             
	WHERE 
		
	TQ.TestTemplateId=@rTestTemplateId


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


GO
ALTER PROCEDURE [sFee].[pFeeCustomReportListGet]
	@rCreatedUserId bigint
	--@rOrgId smallint
AS
SET NOCOUNT ON

BEGIN
		SELECT 
			FCS.Id,
			FCS.Title,
			FCS.ColumnName,
			U.DisplayTitle AS CreatedUserName,
			CASE WHEN FCS.CreatedUserId = @rCreatedUserId THEN 'true' ELSE 'false' END AS IsDelete
		FROM sFee.tFeeCustomSearch FCS
		INNER JOIN sSecurity.tUser U ON U.Id=FCS.CreatedUserId
		WHERE 
			    ((FCS.CreatedUserId = @rCreatedUserId) OR (FCS.IsCommon = 1))
			--AND FCS.OrgId = @rOrgId
END
GO
PRINT N'Altering [sFee].[pFeeCustomSearchGet]...';


GO
ALTER PROCEDURE [sFee].[pFeeCustomSearchGet]
(
	@rOrgGroupBatchId int,
	@rOrgId smallint,
	@rBatchId int,
	@rOrderBy nvarchar(max) = 'ReceiptNumber',
	@rCode [nvarchar](20) = '',
	@rFirstName [nvarchar](50) = '',	
	@rLastName [nvarchar](50) = '',
	--@rClassId nvarchar(max) = '',
	@rDivisionId nvarchar(max) = '',
	@rReceiptBookId nvarchar(max) = '',
	@rFromReceiptDate Date = '0001-01-01',
	@rToReceiptDate Date = '9999-12-31',
	@rFromReceiptNo int,
	@rToReceiptNo int,
	@rCreatedUserId bigint,
	@rIsObsolete bit
 )
AS
SET NOCOUNT ON

BEGIN
		DECLARE @Sql nvarchar(MAX)
		
		IF(@rFromReceiptDate IS NULL)
			SET @rFromReceiptDate='0001-01-01'
		IF(@rToReceiptDate IS NULL)
			SET @rToReceiptDate='9999-12-31'
		
		SET @rCode = sCommon.fSearchStringGet(@rCode)
		SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
		SET @rLastName = sCommon.fSearchStringGet(@rLastName)
		
		SELECT 
				*
		into sFee.tTempFee1
		FROM sFee.vFeeCustomSearch FCS
		WHERE 
				(FCS.OrgGroupBatchId = @rOrgGroupBatchId)
			AND	((FCS.OrgId = @rOrgId) OR (@rOrgId=0))
			AND ((FCS.BatchId = @rBatchId) OR (@rBatchId=0))
			AND ((FCS.Code Like @rCode + '%') OR (@rCode = ''))
			AND ((FCS.FirstName Like @rFirstName  + '%') OR (@rFirstName = ''))	 			 
			AND ((FCS.LastName Like @rLastName + '%')OR(@rLastName = ''))
			AND ((FCS.ReceiptNumber >= @rFromReceiptNo) OR (@rFromReceiptNo=0))
			AND ((FCS.ReceiptNumber <= @rToReceiptNo) OR (@rToReceiptNo=0))
			AND ((ISNULL(FCS.ReceiptDate,'0001-01-01') >= @rFromReceiptDate) OR (ISNULL(@rFromReceiptDate,'') = ''))
			AND ((ISNULL(FCS.ReceiptDate,'9999-12-31') <= @rToReceiptDate) OR (ISNULL(@rToReceiptDate,'') = ''))
			--AND ((ISNULL(FCS.EndDate,'9999-12-31') <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			--AND (FCS.ClassId In( SELECT item FROM  sCommon.fnsplit(@rClassId,','))OR @rClassId=''))
		    
		    AND (FCS.DivisionId In( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionId,','))OR @rDivisionId='')
		         	          
			AND (FCS.FeeReceiptBookId In( SELECT cast(item as int) FROM  sCommon.fnsplit(@rReceiptBookId,','))OR @rReceiptBookId='')	
	        AND ((FCS.CreatedUserId=@rCreatedUserId) OR (@rCreatedUserId=0))
	        AND (FCS.IsObsolete=@rIsObsolete)
	       
	SET @rOrderBy=Replace(@rOrderBy,'ID No','Code') 
		SET @sql=
		'SELECT 
				Code AS Code,
				Name,
				ReceiptNumber,
				ReceiptDate,
				ReceiptAmount,
				PayType,
				ChequeNo,
				BankName,
				ReceiptBookName,
				Remark,
				OrgId,
				BatchId
		FROM sFee.tTempFee1 ORDER BY '+@rOrderBy
		exec(@Sql)
		
		DROP Table sFee.tTempFee1
END
GO
PRINT N'Altering [sFee].[pFeeGenerateReport]...';


GO
ALTER PROCEDURE [sFee].[pFeeGenerateReport]
	
	@rId bigint,
	@rTitle nvarchar(50),
	@rColumnName nvarchar(max) = '',
	@rOrderBy nvarchar(max) = 'ReceiptNumber',
	@rOrgGroupBatchId int,
	@rOrgId smallint,
	@rBatchId int,
	@rCurrentOrgId smallint,
	@rCode [nvarchar](20) = '',
	@rFirstName [nvarchar](50) = '',	
	@rLastName [nvarchar](50) = '',
	--@rClassId nvarchar(max) = '',
	@rDivisionId nvarchar(max) = '',
	@rReceiptBookId nvarchar(max) = '',
	@rFromReceiptDate Date = '0001-01-01',
	@rToReceiptDate Date = '9999-12-31',
	@rFromReceiptNo int,
	@rToReceiptNo int,
	@rIsObsolete bit,
	@rIsCommon bit,
	@rCreatedUserId bigint,
	@rInsertUserId bigint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	
	IF(@rFromReceiptDate IS NULL)
			SET @rFromReceiptDate='0001-01-01'
	IF(@rToReceiptDate IS NULL)
		SET @rToReceiptDate='9999-12-31'
	
	IF(@rTitle != '' AND @rId = 0)
	BEGIN
	DECLARE @lNextNumber BIGINT     
	EXECUTE sCommon.pTableRowIdGet @rCurrentOrgId, 'sFee.tFeeCustomSearch', 0, 1, 1,@outNextNumber = @lNextNumber output

	INSERT INTO sFee.tFeeCustomSearch
		(
			Id,
			Title,
			ColumnName,
			OrderBy,
			OrgGroupBatchId,
			OrgId,
			BatchId,
			Code,
			FirstName,	
			LastName,
			DivisionId,
			ReceiptBookId,
			FromReceiptDate,
			ToReceiptDate,
			FromReceiptNo,
			ToReceiptNo,
			IsObsolete,
			IsCommon,
			UserId,
			CreatedUserId,
			CreatedDateTime
		)
	VALUES
		(
			@lNextNumber,
			@rTitle,
			@rColumnName,
			@rOrderBy,
			@rOrgGroupBatchId,
			@rOrgId,
			@rBatchId,
			@rCode,
			@rFirstName,	
			@rLastName,
			@rDivisionId,
			@rReceiptBookId,
			@rFromReceiptDate,
			@rToReceiptDate,
			@rFromReceiptNo,
			@rToReceiptNo,
			@rIsObsolete,
			@rIsCommon,
			@rCreatedUserId,
			@rInsertUserId,
			sCommon.fGetDate()
		)
		--SELECT @lNextNumber AS Result
	END
	IF(@rId > 0)
	BEGIN
		Select
				@rColumnName=ColumnName,
				@rOrderBy=OrderBy,
				@rOrgGroupBatchId=OrgGroupBatchId,
				@rOrgId=OrgId,
				@rBatchId=BatchId,
				@rCode=Code,
				@rFirstName=FirstName,	
				@rLastName=LastName,
				@rDivisionId=DivisionId,
				@rReceiptBookId=ReceiptBookId,
				@rFromReceiptDate=FromReceiptDate,
				@rToReceiptDate=ToReceiptDate,
				@rFromReceiptNo=FromReceiptNo,
				@rToReceiptNo=ToReceiptNo,
				@rIsObsolete=IsObsolete,
				@rCreatedUserId=UserId
		FROM
			sFee.tFeeCustomSearch
		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)
	
		SELECT 
				*
		into sFee.tTempFee
		FROM sFee.vFeeCustomSearch FCS
		WHERE 
				(FCS.OrgGroupBatchId = @rOrgGroupBatchId)
			AND	((FCS.OrgId = @rOrgId) OR (@rOrgId=0))
			AND ((FCS.BatchId = @rBatchId) OR (@rBatchId=0))
			AND ((FCS.Code Like @rCode + '%') OR (@rCode = ''))
			AND ((FCS.FirstName Like @rFirstName  + '%') OR (@rFirstName = ''))	 			 
			AND ((FCS.LastName Like @rLastName + '%')OR(@rLastName = ''))
			AND ((FCS.ReceiptNumber >= @rFromReceiptNo) OR (@rFromReceiptNo=0))
			AND ((FCS.ReceiptNumber <= @rToReceiptNo) OR (@rToReceiptNo=0))
			AND ((ISNULL(FCS.ReceiptDate,'0001-01-01') >= @rFromReceiptDate) OR (ISNULL(@rFromReceiptDate,'') = ''))
			AND ((ISNULL(FCS.ReceiptDate,'9999-12-31') <= @rToReceiptDate) OR (ISNULL(@rToReceiptDate,'') = ''))
			--AND ((ISNULL(FCS.EndDate,'9999-12-31') <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			--AND (FCS.ClassId In( SELECT item FROM  sCommon.fnsplit(@rClassId,','))OR @rClassId=''))
		    
		    AND (FCS.DivisionId In( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionId,','))OR @rDivisionId='')
		         	          
			AND (FCS.FeeReceiptBookId In( SELECT cast(item as int) FROM  sCommon.fnsplit(@rReceiptBookId,','))OR @rReceiptBookId='')	
	        AND ((FCS.CreatedUserId=@rCreatedUserId) OR (@rCreatedUserId=0))
	        AND (FCS.IsObsolete=@rIsObsolete)
	      
	    SET @rColumnName=Replace(@rColumnName,',Code',',Code AS [ID No]')
		--SET @rOrderBy=Replace(@rOrderBy,',Code',',Code AS [ID No]')    
		SET @sql=
		'SELECT '+
		@rColumnName+' 
		FROM sFee.tTempFee ORDER BY '+@rOrderBy
		SET @sql=Replace(@sql,'SELECT Code','SELECT Code AS [ID No]')
		exec(@Sql)
		
		DROP Table sFee.tTempFee
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		--SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sFee].[pFeeHeadMasterAdd]...';


GO

ALTER PROCEDURE [sFee].[pFeeHeadMasterAdd]
	 
	        @rId int
	       ,@rNumber int
	       ,@rCode nvarchar(20)
           ,@rTitle nvarchar(100)
           ,@rOrderIndex int
           ,@rIsObsolete bit
           ,@rCreatedUserId bigint           
           ,@rOrgGroupId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	IF(@rId = 0)	
	BEGIN
		If Exists(select Id from sFee.tFeeHeadMaster where Code=@rCode AND OrgGroupId=@rOrgGroupId)
			BEGIN
			select -101 as Result
			RETURN
		END 
		If Exists(select Id from sFee.tFeeHeadMaster where Number=@rNumber AND OrgGroupId=@rOrgGroupId)
			BEGIN
			select -102 as Result
			RETURN
		END
		If Exists(select Id from sFee.tFeeHeadMaster where Title=@rTitle AND OrgGroupId=@rOrgGroupId)
			BEGIN
			select -103 as Result
			RETURN
		END 
		If Exists(select Id from sFee.tFeeHeadMaster where OrderIndex=@rOrderIndex AND OrgGroupId=@rOrgGroupId)
			BEGIN
			select -104 as Result
			RETURN
		END 
	END
	ELSE
	BEGIN
		If Exists(select Id from sFee.tFeeHeadMaster where Code=@rCode AND OrgGroupId=@rOrgGroupId AND Id<>@rId)
		Begin
			select -101 as Result
			RETURN
		End 
		If Exists(select Id from sFee.tFeeHeadMaster where Number=@rNumber AND OrgGroupId=@rOrgGroupId AND Id<>@rId)
			BEGIN
			select -102 as Result
			RETURN
		END
		If  Exists(select Id from sFee.tFeeHeadMaster where Title=@rTitle AND OrgGroupId=@rOrgGroupId AND Id<>@rId)
		Begin
			select -103 as Result
			RETURN
		End
		If  Exists(select Id from sFee.tFeeHeadMaster where OrderIndex=@rOrderIndex AND OrgGroupId=@rOrgGroupId AND Id<>@rId)
		Begin
			select -104 as Result
			RETURN
		End
	END
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber INT     
	
IF(@rId = 0)	
BEGIN
	--EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sFee.tFeeHeadMaster',@lNextNumber = @lNextNumber output
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sFee.tFeeHeadMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	INSERT INTO [sFee].[tFeeHeadMaster]
			   (
			    [Id]
			   ,[Number]  
			   ,[Code]
			   ,[Title]
			   ,[OrderIndex]
			   ,[IsObsolete]
			   ,[CreatedUserId]
			   ,[CreatedDateTime]
			   ,[UpdatedUserId]
			   ,[UpdatedDateTime]
			   ,[OrgGroupId]
			   )
		 VALUES
			   (
				@lNextNumber
			   ,@rNumber
			   ,@rCode
			   ,@rTitle
			   ,@rOrderIndex
			   ,@rIsObsolete
			   ,@rCreatedUserId
			   ,sCommon.fGetDate()
			   ,0
			   ,sCommon.fGetDate()
			   ,@rOrgGroupId
			   )
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  [sFee].[tFeeHeadMaster]
	    SET
			  Number=@rNumber
	         ,Code=@rCode
	         ,Title=@rTitle
	         ,OrderIndex=@rOrderIndex
             ,[IsObsolete] = @rIsObsolete                          
             ,[UpdatedUserId] = @rCreatedUserId
             ,[UpdatedDateTime] = sCommon.fGetDate()          
             
	      WHERE Id = @rId 	
	 END  
	      SELECT @lNextNumber AS Result
			COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sFee].[pFeeMasterAdd]...';


GO

ALTER PROCEDURE [sFee].[pFeeMasterAdd]
	 
	        @rId int
	       ,@rNumber int
	       ,@rCode nvarchar(20)
           ,@rTitle nvarchar(100)
           ,@rFeeHeadId int
           ,@rOrderIndex int
           ,@rIsObsolete bit
           ,@rCreatedUserId bigint           
           ,@rOrgGroupId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	IF(@rId = 0)	
	BEGIN
		If Exists(select Id from sFee.tFeeMaster where Code=@rCode AND OrgGroupId=@rOrgGroupId)
			BEGIN
			select -101 as Result
			RETURN
		END 
		If Exists(select Id from sFee.tFeeMaster where Number=@rNumber AND OrgGroupId=@rOrgGroupId)
			BEGIN
			select -102 as Result
			RETURN
		END
		If Exists(select Id from sFee.tFeeMaster where Title=@rTitle AND OrgGroupId=@rOrgGroupId)
			BEGIN
			select -103 as Result
			RETURN
		END 
		If Exists(select Id from sFee.tFeeMaster where OrderIndex=@rOrderIndex AND OrgGroupId=@rOrgGroupId)
			BEGIN
			select -104 as Result
			RETURN
		END 
	END
	ELSE
	BEGIN
		If Exists(select Id from sFee.tFeeMaster where Code=@rCode AND OrgGroupId=@rOrgGroupId AND Id<>@rId)
		Begin
			select -101 as Result
			RETURN
		End 
		If Exists(select Id from sFee.tFeeMaster where Number=@rNumber AND OrgGroupId=@rOrgGroupId AND Id<>@rId)
			BEGIN
			select -102 as Result
			RETURN
		END
		If  Exists(select Id from sFee.tFeeMaster where Title=@rTitle AND OrgGroupId=@rOrgGroupId AND Id<>@rId)
		Begin
			select -103 as Result
			RETURN
		End
		If  Exists(select Id from sFee.tFeeMaster where OrderIndex=@rOrderIndex AND OrgGroupId=@rOrgGroupId AND Id<>@rId)
		Begin
			select -104 as Result
			RETURN
		End


	END
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber INT     
	
IF(@rId = 0)	
BEGIN
	--EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sFee.tFeeMaster',@lNextNumber = @lNextNumber output
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sFee.tFeeMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	
	INSERT INTO [sFee].[tFeeMaster]
			   (
			    [Id]
			   ,[Number]  
			   ,[Code]
			   ,[Title]
			   ,[FeeHeadId]
			   ,[OrderIndex]
			   ,[IsObsolete]
			   ,[CreatedUserId]
			   ,[CreatedDateTime]
			   ,[UpdatedUserId]
			   ,[UpdatedDateTime]
			   ,[OrgGroupId]
			   )
		 VALUES
			   (
				@lNextNumber
			   ,@rNumber
			   ,@rCode
			   ,@rTitle
			   ,@rFeeHeadId
			   ,@rOrderIndex
			   ,@rIsObsolete
			   ,@rCreatedUserId
			   ,sCommon.fGetDate()
			   ,0
			   ,sCommon.fGetDate()
			   ,@rOrgGroupId
			   )
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  [sFee].[tFeeMaster]
	    SET
			  Number=@rNumber
	         ,Code=@rCode
	         ,Title=@rTitle
	         ,FeeHeadId=@rFeeHeadId
	         ,OrderIndex=@rOrderIndex
             ,[IsObsolete] = @rIsObsolete                          
             ,[UpdatedUserId] = @rCreatedUserId
             ,[UpdatedDateTime] = sCommon.fGetDate()          
             
	      WHERE Id = @rId 	
	 END  
	      SELECT @lNextNumber AS Result
			COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sFee].[pFeeReceiptListGet]...';


GO

ALTER PROCEDURE [sFee].[pFeeReceiptListGet]
		
		@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,
		@rIsObsolete bit,
		@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 
		R.Id AS ReceiptId,
		R.SourceTypeId AS SourceTypeId,
		CASE WHEN R.SourceTypeId=2001 THEN 'Student'
		ELSE  'Employee' END AS SourceType,
		--STM.Title 
		SM.Code AS Code,
		SM.FirstName+' '+SM.LastName AS Name,
		R.ReceiptNumber,
		R.ReceiptDate,
		ISNULL(R.ReceiptAmount,0)AS ReceiptAmount,
		ISNULL(R.TotalReceiptAmount,0)AS TotalReceiptAmount,
		ISNULL(R.DiscountAmount,0)AS DiscountAmount,
		R.PayTypeId,
		PTM.Title AS PayType,
		R.ChequeNo,
		R.BankName,
		R.ReceiptBookId,
		RBM.Title AS ReceiptBook,
		R.IsObsolete,
		A.OrgId,
		OM.DisplayTitle AS Organization,
		R.BatchId,
		BM.Title AS Batch,
		R.Remark
  FROM 
			sFee.tReceipt R
		INNER JOIN sStudent.tAcademic A
			ON A.Id=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.StatusId=1
			AND (SM.AdmissionCategoryId=@rAdmissionCategoryId OR @rAdmissionCategoryId=0)
		INNER JOIN sCommon.tSourceTypeMaster STM
			ON STM.Id=R.SourceTypeId
		INNER JOIN sFinanceCommon.tPayTypeMaster PTM
			ON PTM.Id=R.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=R.BatchId 
			AND BM.OrgGroupBatchId=@rOrgGroupBatchId
		INNER JOIN sSecurity.tUser U ON U.Id=R.CreatedUserId
		INNER JOIN sFee.vUserReceiptBook URB ON URB.Id=RBM.Id AND URB.UserId=@rCreatedUserId
WHERE 
		((SM.Code like @rIdNo) OR (ISNULL(@rIdNo,'')=''))
	AND (R.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 ((R.PayTypeId=@rPayTypeId)OR(@rPayTypeId=0))
	AND ((R.ChequeNo like @rChequeNo) OR(ISNULL(@rChequeNo,'')=''))
	AND ((STM.Id=@rSourceTypeId)OR(@rSourceTypeId=0))
	AND ((R.ReceiptDate>=@rFromDate)OR(ISNULL(@rFromDate,'')=''))
	AND ((R.ReceiptDate<=@rToDate)OR(ISNULL(@rToDate,'')=''))
	AND (R.IsObsolete=@rIsObsolete)
	AND ((SM.OrgId=@rOrgId) OR (@rOrgId=0))
	AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
	AND ((U.DisplayTitle like @rCreatedUserName) OR (ISNULL(@rCreatedUserName,'')=''))
	
	ORDER BY R.ReceiptNumber DESC
--UNION All
	
--	SELECT 
--		R.Id AS ReceiptId,
--		R.SourceTypeId AS SourceTypeId,
--		CASE WHEN R.SourceTypeId=2001 THEN 'Student'
--		ELSE  'Employee' END AS SourceType,
--		--STM.Title 
--		EM.Code AS Code,
--		EM.EmployeeName AS Name,
--		R.ReceiptNumber,
--		R.ReceiptDate,
--		ISNULL(R.ReceiptAmount,0)AS ReceiptAmount,
--		R.PayTypeId,
--		PTM.Title AS PayType,
--		R.ChequeNo,
--		R.BankName,
--		R.ReceiptBookId,
--		RBM.Title AS ReceiptBook,
--		R.IsObsolete,
--		EM.OrgId,
--		OM.DisplayTitle AS Organization,
--		R.BatchId,
--		BM.Title AS Batch
				
			
	
--  FROM 
		
--			sFee.tReceipt R
--		INNER JOIN	sHrm.vExtEmployeeMaster EM
--			ON EM.Id=R.SourceId
--		INNER JOIN sCommon.tSourceTypeMaster STM
--			ON STM.Id=R.SourceTypeId
--		INNER JOIN sFinanceCommon.tPayTypeMaster PTM
--			ON PTM.Id=R.PayTypeId
--		INNER JOIN sFee.tReceiptBookMaster RBM
--			ON RBM.Id=R.ReceiptBookId
--		INNER JOIN sSetup.tOrganizationMaster OM
--			ON OM.Id=EM.OrgId
--		INNER JOIN sSetup.tBatchMaster BM
--			ON BM.Id=R.BatchId
			
--WHERE 

--		((EM.Code like @rIdNo) OR (ISNULL(@rIdNo,'')=''))
--	AND (R.SourceTypeId=95)
--	AND ((EM.FirstName like @rFirstName) OR(ISNULL(@rFirstName,'')=''))
--	AND ((R.ReceiptNumber=@rReceiptNumber)OR(@rReceiptNumber=0))
--	AND ((R.ReceiptBookId=@rReceiptBookId)OR(@rReceiptBookId=0))
--	AND ((R.PayTypeId=@rPayTypeId)OR(@rPayTypeId=0))
--	AND ((R.ChequeNo like @rChequeNo) OR(ISNULL(@rChequeNo,'')=''))
--	AND ((STM.Id=@rSourceTypeId)OR(@rSourceTypeId=0))
--	AND ((R.ReceiptDate>=@rFromDate)OR(ISNULL(@rFromDate,'')=''))
--	AND ((R.ReceiptDate<=@rToDate)OR(ISNULL(@rToDate,'')=''))
--	AND (R.IsObsolete=@rIsObsolete)
--	AND ((EM.OrgId=@rOrgId) OR (EM.OrgId IN(SELECT Id FROM sSetup.tOrganizationMaster WHERE OrgGroupId=@rOrgGroupId)))
--	AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
	
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
			--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].[pFeeSetupGet]...';


GO

ALTER PROCEDURE [sFee].[pFeeSetupGet]
				
		   @rBuilder1 nvarchar(max)='',
		   @rBuilder2 nvarchar(max)='', 
		   @rClassId int,
           @rAdmissionCategoryId int,
		   @rBatchId int,
		   @rOrgGroupId int
           
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 
	SELECT 
	
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			ISNULL(FS.Id,0)AS Id,
			ISNULL(FS.ClassId,0)AS ClassId,
			ISNULL(CM.Title,'') AS ClassName,
			ISNULL(FS.AdmissionCategoryId,0) AS AdmissionCategoryId,
			FM.Title AS FeeTitle,
			ISNULL(FS.BatchId,0)AS BatchId,
			ISNULL(FM.Id,0)AS FeeId,
			ISNULL(FS.IsOptional,0)AS IsOptional,
			ISNULL(FS.IsVariable,0)AS IsVariable,
			ISNULL(FS.Amount,0)AS Amount,
			ISNULL(FS.StartDate,'0001-01-01 00:00:00.00')AS StartDate,
			ISNULL(FS.EndDate,'0001-01-01 00:00:00.00')AS EndDate,
			ISNULL(FS.ReceiptBookId,0) AS ReceiptBookId,
			ISNULL(RBM.Title,'') AS ReceiptBookTitle,
			ISNULL(FHM.Id,0) AS FeeHeadId,
			ISNULL(FHM.Title,'') AS FeeHeadName,
			CASE WHEN (SELECT COUNT(*) FROM sFee.tReceiptDetail WHERE FeeSetupId=FS.Id) <= 0 THEN 'True' ELSE 'False' END AS IsReceiptBookChange
  FROM 
			sFee.tFeeMaster FM
		LEFT JOIN sFee.tFeeSetup FS ON FM.Id=FS.FeeId 
			AND (FS.ClassId=@rClassId) AND (FS.AdmissionCategoryId=@rAdmissionCategoryId) AND (FS.BatchId=@rBatchId)
		LEFT JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
		LEFT JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=FS.ReceiptBookId
		LEFT JOIN sSetup.tClassMaster CM ON CM.Id=FS.ClassId
WHERE 
		FM.OrgGroupId=@rOrgGroupId
		ORDER BY FS.StartDate,FHM.OrderIndex,FM.OrderIndex
END
GO
PRINT N'Altering [sFee].[pOptionalFeeGet]...';


GO

ALTER PROCEDURE [sFee].[pOptionalFeeGet]

		   @rClassId int,
           @rAdmissionCategoryId int,
		   @rBatchId int,
		   @rOrgGroupId int,
		   @rSourceTypeId int,
		   @rSourceId bigint
           
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 
	SELECT 
			ISNULL(FS.Id,0)AS Id,
			FM.Title AS FeeTitle,
			ISNULL(FS.Amount,0)AS Amount,
			ISNULL(FS.StartDate,'0001-01-01 00:00:00.00')AS StartDate,
			ISNULL(FS.EndDate,'0001-01-01 00:00:00.00')AS EndDate,
			ISNULL(FHM.Title,'') AS FeeHeadName,
			CASE WHEN ISNULL(FO.SourceId,0) = 0 THEN 'False' ELSE 'True' END AS IsCheck
  FROM 
			sFee.tFeeMaster FM
		INNER JOIN sFee.tFeeSetup FS ON FM.Id=FS.FeeId AND FS.IsOptional=1
			AND (FS.ClassId=@rClassId) AND (FS.AdmissionCategoryId=@rAdmissionCategoryId) AND (FS.BatchId=@rBatchId)
		INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
		LEFT JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS.Id AND FO.SourceTypeId=@rSourceTypeId AND FO.SourceId=@rSourceId
WHERE 
		FM.OrgGroupId=@rOrgGroupId
		ORDER BY FS.StartDate,FM.OrderIndex
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(200)
           ,@rRemark2 nvarchar(200)
           ,@rCreatedUserId bigint           
           ,@rOrgGroupId int
	
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()          
             
	      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]
			   )
		 VALUES
			   (
				@lNextNumber
			   ,@rCode
			   ,@rTitle
			   ,@rFullTitle
			   ,@rAddress1
			   ,@rAddress2
			   ,@rBankAccountNumber
			   ,@rIsObsolete
			   ,@rRemark1
			   ,@rRemark2
			   ,@rCreatedUserId
			   ,sCommon.fGetDate()
			   ,@rOrgGroupId
			   )
		    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()               
             
	      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
     
  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].[pRptFeePendingDetailListGet]...';


GO

ALTER PROCEDURE [sFee].[pRptFeePendingDetailListGet]
		
		@rReceiptBookId int,
		@rAdmissionCategoryId int,
		@rClassId int,
		@rDivisionId int,
		--@rDepartmentId int,
		@rUptoDate date,
		@rBatchId int,
		@rUserId bigint,
		@rBuilder1 nvarchar(max),
		@rBuilder2 nvarchar(max),
		@rIsDetail bit,
		@rOrgId int,
		@rOrgGroupBatchId int,
		@rStatusId int
		
		
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 	
	SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		@rIsDetail AS IsDetail,
		SA.AcademicId,
		SA.RollNo,
		SA.Name,
		SA.Code,
		SA.ClassId,
		SA.DivisionId,
		SA.ClassName,
		SA.DivisionName,
		SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
		FS.Id AS FeeSetupId,
		
		ISNULL(FS.IsVariable,0)AS IsVariable,
		ISNULL(FS.Amount,0)AS Amount,
		ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
		ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
		ISNULL(FA.VariableAmount,0.00)AS FAAmount,
		ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
		ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
		ISNULL(R.PaidAmount,0) AS PaidAmount,
		ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)AS PendingAmount,
		ISNULL(FA.Remark,'') AS Remark,
		FS.ReceiptBookId,
		FS.FeeName
			
  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 ((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 ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.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,
				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.ClassId=@rClassId) OR (@rClassId=0)) 
			AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
		WHERE
					((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=1)
				
		) FS ON FS.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
		LEFT JOIN
		(
		    SELECT 
					ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
		    FROM
					sFee.tReceipt R 
				INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
				INNER JOIN 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 (R.OrgGroupBatchId = @rOrgGroupBatchId)
				AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
					GROUP BY FeeSetupId,R.SourceId
		
		) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
	WHERE	
	
    ((SA.BatchId=@rBatchId) OR (@rBatchId=0)) 
			AND (SA.StatusId = @rStatusId OR @rStatusId=0)
			AND ((FS.EndDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			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)			
			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 [sFee].[pRptFeeReceiptDetailListGet]...';


GO

ALTER PROCEDURE [sFee].[pRptFeeReceiptDetailListGet]
		
		@rReceiptBookId int,
		@rAdmissionCategoryId int,
		@rClassId int,
		@rDivisionId int,
		--@rDepartmentId 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
		
		
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 	
	SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		@rIsCancel AS IsCancel,
		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,
		RD.Amount AS DetailAmount,
		ISNULL(RBM.Title,'') AS ReceiptBookTitle,
		ISNULL(R.ReceiptBookId,'0') As ReceiptBookId,
		ISNULL(FHM.Title,'') AS FeeHead
			
  FROM 
			sFee.tReceipt R
		INNER JOIN sCommon.tSourceTypeMaster STM
			ON STM.Id=R.SourceTypeId AND R.SourceTypeId = 2001
		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
			
			
WHERE 
		((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 (R.OrgGroupBatchId = @rOrgGroupBatchId)
	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)
	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]
	 
		@rReceiptId bigint
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 		
	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,
			sFinanceCommon.fNumberToWordsWithDecimal(ISNULL(FR.ReceiptAmount,0.00),0,2) AS ReceiptAmountInWords,
			ISNULL(FR.DiscountAmount,0.00) AS DiscountAmount,
			FR.Remark,
			U.DisplayTitle AS UserName,
			OM.OrgLogo,
			RBM.Remark1,
			RBM.Remark2
	FROM 
			sFee.tFeeMaster FM
			INNER JOIN sFee.tFeeHeadMaster FHM
				ON FHM.Id=FM.FeeHeadId
			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 AND FR.SourceTypeId=2001
			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=FS.ReceiptBookId
			INNER JOIN sSecurity.tUser U
				ON U.Id=FR.CreatedUserId
			INNER JOIN sSetup.tOrganizationMaster OM
				ON OM.Id=SA.OrgId
				
	where 
			FRD.ReceiptId=@rReceiptId

ORDER BY FS.StartDate,FM.OrderIndex ASC

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


GO

ALTER PROCEDURE [sFee].[pRptFeeReceiptListGet]
		
		@rReceiptBookId int,
		@rAdmissionCategoryId int,
		@rClassId int,
		@rDivisionId int,
		--@rDepartmentId int,
		@rFromDate date,
		@rToDate date,
		@rFromReceiptNo int,
		@rToReceiptNo int,
		@rBatchId int,
		@rUserId bigint,
		@rBuilder1 nvarchar(max),
		@rBuilder2 nvarchar(max),
		@rIsDetail bit,
		@rIsCancel bit,
		@rOrgId int,
		@rOrgGroupBatchId int,
		@rStatusId int,
		@rPaytypeId int
		
		
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 	
	SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		@rIsDetail AS IsDetail,
		@rIsCancel AS IsCancel,
		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,
		PTM.Title AS PayType,
		R.ChequeNo,
		R.BankName,
		R.ReceiptAmount,
		R.ReceiptDate,
		R.CreatedUserId,
		U.DisplayTitle AS UserName,
		ISNULL(RBM.Title,'') AS ReceiptBookTitle,
		ISNULL(R.ReceiptBookId,'0') As ReceiptBookId
			
  FROM 
			sFee.tReceipt R
		INNER JOIN sCommon.tSourceTypeMaster STM
			ON STM.Id=R.SourceTypeId AND R.SourceTypeId = 2001
		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 sSecurity.tUser U
			ON U.Id=R.CreatedUserId
		INNER JOIN sFee.tReceiptBookMaster RBM 
			ON RBM.Id=R.ReceiptBookId
			
WHERE 
		((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 (R.OrgGroupBatchId = @rOrgGroupBatchId)
	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)
	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]
		
		@rReceiptBookId int,
		@rAdmissionCategoryId int,
		@rClassId int,
		@rDivisionId int,
		--@rDepartmentId int,
		@rUptoDate date,
		@rBatchId int,
		@rUserId bigint,
		@rBuilder1 nvarchar(max),
		@rBuilder2 nvarchar(max),
		@rIsDetail bit,
		@rOrgId int,
		@rOrgGroupBatchId int,
		@rIsExemption bit =0,
		@rStatusId int
		
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 	
	SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		@rIsDetail AS IsDetail,
		SA.AcademicId,
		SA.RollNo,
		SA.Name,
		SA.Code,
		SA.ClassId,
		SA.DivisionId,
		SA.ClassName,
		SA.DivisionName,
		SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
		FS.Id AS FeeSetupId,
		
		ISNULL(FS.IsVariable,0)AS IsVariable,
		ISNULL(FS.Amount,0)AS Amount,
		ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
		ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
		ISNULL(FA.VariableAmount,0.00)AS FAAmount,
		ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
		ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
		ISNULL(R.PaidAmount,0) AS PaidAmount,
		ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)AS PendingAmount,
		ISNULL(FA.Remark,'') AS Remark,
		FS.ReceiptBookId,
		FS.FeeName
			
  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 ((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 ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.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,
				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.ClassId=@rClassId) OR (@rClassId=0)) 
			AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
		WHERE
					((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=1)
				
		) FS ON FS.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
		LEFT JOIN
		(
		    SELECT 
					ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
		    FROM
					sFee.tReceipt R 
				INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
				INNER JOIN 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 (R.OrgGroupBatchId = @rOrgGroupBatchId)
				AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
					GROUP BY FeeSetupId,R.SourceId
		
		) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
	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.EndDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			
			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 [sGSEB].[pActivityIndicatorScoreAdd]...';


GO


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

DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml
BEGIN
	BEGIN TRY
	 BEGIN	
	 DECLARE @lNextNumber BIGINT 
	 DECLARE @lCount INT

		IF @rExamId = 1
		BEGIN
			UPDATE AI SET AI.Term1Indicator = 0,AI.Term1IndicatorText='' FROM sGSEB.tActivityIndicatorScore AI
			INNER JOIN OPENXML (@loDoc, '/Table/ActivityIndicatorScore', 1)
				WITH ( 				
						AcademicId Bigint,ActivityTitle NVARCHAR(100)			
					  ) A 	ON AI.AcademicId = A.AcademicId
			INNER JOIN sGSEB.tActivityMaster AM ON AM.Id = AI.ActivityId 
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.OrgGroupId = AM.OrgGroupId AND OM.Id = @rORGId	
			AND AM.Title=A.ActivityTitle			  			
		END
		IF @rExamId = 2
		BEGIN
			UPDATE AI SET AI.Term2Indicator = 0,AI.Term2IndicatorText='' FROM sGSEB.tActivityIndicatorScore AI
			INNER JOIN OPENXML (@loDoc, '/Table/ActivityIndicatorScore', 1)
				WITH ( 				
						AcademicId Bigint,
						ActivityTitle NVARCHAR(100)			
					  ) A 	ON AI.AcademicId = A.AcademicId
			INNER JOIN sGSEB.tActivityMaster AM ON AM.Id = AI.ActivityId 
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.OrgGroupId = AM.OrgGroupId AND OM.Id = @rORGId	
			AND AM.Title=A.ActivityTitle			  
	    END
	    
	    	DELETE AI FROM sGSEB.tActivityIndicatorScore AI
			INNER JOIN OPENXML (@loDoc, '/Table/ActivityIndicatorScore', 1)
				WITH ( 				
						AcademicId Bigint,
						ActivityTitle NVARCHAR(100),
						Term1Indicator nvarchar(20),
						Term2Indicator nvarchar(20)
					  ) A 	ON AI.AcademicId = A.AcademicId
			INNER JOIN sGSEB.tActivityMaster AM ON AM.Id = AI.ActivityId 
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.OrgGroupId = AM.OrgGroupId AND OM.Id = @rORGId	
			AND AM.Title=A.ActivityTitle	AND (A.Term1Indicator='0' OR A.Term1Indicator='')
			AND (A.Term2Indicator='0' OR A.Term2Indicator='') 
		
		INSERT INTO sGSEB.tActivityIndicatorScore
			(AcademicId,ActivityId,Term1Indicator,Term2Indicator)
			
			SELECT		AcademicId,AM.Id,
						Replace(Term1Indicator,',','.'),
						Replace(Term2Indicator,',','.')
			
			FROM OPENXML (@loDoc, '/Table/ActivityIndicatorScore', 1)
			WITH ( 				
					AcademicId Bigint,ActivityTitle NVARCHAR(100),Term1Indicator nvarchar(20),Term2Indicator nvarchar(20)			
				  ) A 	
			INNER JOIN sGSEB.tActivityMaster AM ON AM.TITLE = A.ACTIVITYTITLE 			
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.OrgGroupId = AM.OrgGroupId AND OM.Id = @rORGId
			INNER JOIN sGSEB.tActivityIndicatorMaster AIM ON AIM.ActivityId = AM.Id 
			AND (',' + A.Term1Indicator + ',' like '%,'+ cast(AIM.Number as varchar(255)) + ',%'
			 OR ',' + A.Term2Indicator + ',' like '%,'+ cast(AIM.Number as varchar(255)) + ',%')
	      SELECT 1 AS Result
	 END	
	
	END TRY
	
	BEGIN CATCH 
		
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sGSEB].[pRptAnusuchiCPrimaryGet]...';


GO


ALTER PROCEDURE [sGSEB].[pRptAnusuchiCPrimaryGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rBatchId int,	
	 @rClassId INT,
	 @rDivisionId int
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
		
BEGIN 	
BEGIN TRY
 BEGIN TRANSACTION			 	
	
		--SELECT	@rBuilder1,
		--		@rBuilder2,		
		--		'' AS ClassName,
		--		'' AS DivisionName,
		--		'' AS RollNo,
		--		'' AS Name,
		--		'' AS Number,
		--		'' AS SubjectName,			
		--		'' AS SUB1,
		--		'' AS SUB2,
		--		'' AS SUB3,
		--		'' AS SUB4,
		--		'' AS SUB5,
		--		'' AS SUB6,
		--		'' AS SUB7,			
		--		'' AS SUB8,
		--		'' AS SUB9,
		--		'' AS SUB10,
		--		'' AS SUB11,
		--		'' AS SUB12,
		--		'' AS Id,
		--		'' AS AcademicId,
		--		'' AS PD,
		--		'' AS PDGrade,
		--		'' AS Total,
		--		'' AS Percentage,
		--		'' AS Grade,
		--		'' AS FA11, '' AS  FA21 , '' AS SA11 , '' AS  FA31, '' AS FA41, '' AS SA21,'' AS GRADE1,
		--		'' AS FA12, '' AS  FA22 , '' AS SA12 , '' AS  FA32, '' AS FA42, '' AS SA22,'' AS GRADE2,
		--		'' AS FA13, '' AS  FA23 , '' AS SA13 , '' AS  FA33, '' AS FA43, '' AS SA23,'' AS GRADE3,
		--		'' AS FA14, '' AS  FA24 , '' AS SA14 , '' AS  FA34, '' AS FA44, '' AS SA24,'' AS GRADE4,
		--		'' AS FA15, '' AS  FA25 , '' AS SA15 , '' AS  FA35, '' AS FA45, '' AS SA25,'' AS GRADE5,
		--		'' AS FA16, '' AS  FA26 , '' AS SA16 , '' AS  FA36, '' AS FA46, '' AS SA26,'' AS GRADE6,
		--		'' AS FA17, '' AS  FA27 , '' AS SA17 , '' AS  FA37, '' AS FA47, '' AS SA27,'' AS GRADE7,
		--		'' AS FA18, '' AS  FA28 , '' AS SA18 , '' AS  FA38, '' AS FA48, '' AS SA28,'' AS GRADE8,
		--		'' AS FA19, '' AS  FA29 , '' AS SA19 , '' AS  FA39, '' AS FA49, '' AS SA29,'' AS GRADE9,
		--		'' AS FA110, '' AS  FA210 , '' AS SA110 , '' AS  FA310, '' AS FA410, '' AS SA210,'' AS GRADE10,
		--		'' AS FA111, '' AS  FA211 , '' AS SA111 , '' AS  FA311, '' AS FA411, '' AS SA211,'' AS GRADE11,
		--		'' AS FA112, '' AS  FA212 , '' AS SA112 , '' AS  FA312, '' AS FA412, '' AS SA212,'' AS GRADE12

		
		
DECLARE @query  AS NVARCHAR(MAX)		
BEGIN
			
CREATE TABLE #tempAnusuchiCMaster
(	ID INT IDENTITY,
	ACADEMICID BIGINT,	
	ClassSubjectId1 INT,
	ClassSubjectId2 INT,
	ClassSubjectId3 INT,
	ClassSubjectId4 INT,
	ClassSubjectId5 INT,
	ClassSubjectId6 INT,
	ClassSubjectId7 INT,	
	ClassSubjectId8 INT,	
	ClassSubjectId9 INT,	
	ClassSubjectId10 INT,	
	ClassSubjectId11 INT,	
	ClassSubjectId12 INT,
	PD DECIMAL(5,2),
	PDGrade nvarchar(5),	
	Total DECIMAL(6,2),
	Percentage DECIMAL(6,2),
	Grade	NVARCHAR(5),
	FA11 DECIMAL(5,2),FA21 DECIMAL(5,2),SA11 DECIMAL(5,2),FA31 DECIMAL(5,2),FA41 DECIMAL(5,2),SA21 DECIMAL(5,2),Grade1 Nvarchar(10),
	FA12 DECIMAL(5,2),FA22 DECIMAL(5,2),SA12 DECIMAL(5,2),FA32 DECIMAL(5,2),FA42 DECIMAL(5,2),SA22 DECIMAL(5,2),Grade2 Nvarchar(10),
	FA13 DECIMAL(5,2),FA23 DECIMAL(5,2),SA13 DECIMAL(5,2),FA33 DECIMAL(5,2),FA43 DECIMAL(5,2),SA23 DECIMAL(5,2),Grade3 Nvarchar(10),
	FA14 DECIMAL(5,2),FA24 DECIMAL(5,2),SA14 DECIMAL(5,2),FA34 DECIMAL(5,2),FA44 DECIMAL(5,2),SA24 DECIMAL(5,2),Grade4 Nvarchar(10),
	FA15 DECIMAL(5,2),FA25 DECIMAL(5,2),SA15 DECIMAL(5,2),FA35 DECIMAL(5,2),FA45 DECIMAL(5,2),SA25 DECIMAL(5,2),Grade5 Nvarchar(10),
	FA16 DECIMAL(5,2),FA26 DECIMAL(5,2),SA16 DECIMAL(5,2),FA36 DECIMAL(5,2),FA46 DECIMAL(5,2),SA26 DECIMAL(5,2),Grade6 Nvarchar(10),
	FA17 DECIMAL(5,2),FA27 DECIMAL(5,2),SA17 DECIMAL(5,2),FA37 DECIMAL(5,2),FA47 DECIMAL(5,2),SA27 DECIMAL(5,2),Grade7 Nvarchar(10),
	FA18 DECIMAL(5,2),FA28 DECIMAL(5,2),SA18 DECIMAL(5,2),FA38 DECIMAL(5,2),FA48 DECIMAL(5,2),SA28 DECIMAL(5,2),Grade8 Nvarchar(10),
	FA19 DECIMAL(5,2),FA29 DECIMAL(5,2),SA19 DECIMAL(5,2),FA39 DECIMAL(5,2),FA49 DECIMAL(5,2),SA29 DECIMAL(5,2),Grade9 Nvarchar(10),
	FA110 DECIMAL(5,2),FA210 DECIMAL(5,2),SA110 DECIMAL(5,2),FA310 DECIMAL(5,2),FA410 DECIMAL(5,2),SA210 DECIMAL(5,2),Grade10 Nvarchar(10),
	FA111 DECIMAL(5,2),FA211 DECIMAL(5,2),SA111 DECIMAL(5,2),FA311 DECIMAL(5,2),FA411 DECIMAL(5,2),SA211 DECIMAL(5,2),Grade11 Nvarchar(10),
	FA112 DECIMAL(5,2),FA212 DECIMAL(5,2),SA112 DECIMAL(5,2),FA312 DECIMAL(5,2),FA412 DECIMAL(5,2),SA212 DECIMAL(5,2),Grade12 Nvarchar(10)
)
CREATE TABLE #tempSubject
(Id int Identity,
 ClassSubjectId int)
 INSERT INTO #tempSubject SELECT distinct Id FROM sSetup.tClassSubject CS
 INNER JOIN sGSEB.tAnusuchiB AB ON AB.ClassSubjectId <> CS.Id
 AND CS.ClassId = @rClassId 
 
 INSERT INTO #tempAnusuchiCMaster (ACADEMICID)
 SELECT A.Id FROM sStudent.tAcademic A WHERE A.DivisionId = @rDivisionId  ORDER BY A.Id

DECLARE @lCount int
DECLARE @lSubCount int
DECLARE @lAcademicId BIGINT
DECLARE @lClassSubjectId INT
DECLARE @lColName NVARCHAR(20)
SELECT @lCount = MAX(Id) FROM #tempAnusuchiCMaster

WHILE @lCount > 0
BEGIN
	SELECT @lAcademicId=AcademicId FROM #tempAnusuchiCMaster WHERE ID = @lCount
	SELECT @lSubCount = MAX(Id) FROM #tempSubject
	WHILE @lSubCount > 0
	BEGIN
		SELECT @lClassSubjectId = ClassSubjectId FROM #tempSubject WHERE Id = @lSubCount
		SET @lColName = 'ClassSubjectId' + CONVERT(NVARCHAR,@lSubCount)
		SET @query =N'UPDATE  #tempAnusuchiCMaster  SET  ' + convert(varchar, @lColName) + ' = ' + 
					 CONVERT(NVARCHAR,@lClassSubjectId) + ' WHERE ACADEMICID = ' + CONVERT(NVARCHAR,@lAcademicId)
		EXEC sp_executesql  @query	
		
		SET @query =N'UPDATE  T  SET T.FA1' + CONVERT(NVARCHAR,@lSubCount) + ' = RD.FA1,
					 T.FA2' + CONVERT(NVARCHAR,@lSubCount) + ' = RD.FA2,
					 T.SA1' + CONVERT(NVARCHAR,@lSubCount) + ' = RD.SA1,
					 T.FA3' + CONVERT(NVARCHAR,@lSubCount) + ' = RD.FA3,
					 T.FA4' + CONVERT(NVARCHAR,@lSubCount) + ' = RD.FA4,
					 T.SA2' + CONVERT(NVARCHAR,@lSubCount) + ' = RD.SA2,
					 T.Grade' + CONVERT(NVARCHAR,@lSubCount) + ' = RD.Grade
					 FROM #tempAnusuchiCMaster T 	
					 INNER JOIN SGSEB.TRESULTDETAIL RD ON T.ACADEMICID = ' + CONVERT(NVARCHAR,@lAcademicId)  + ' AND ' +
					 convert(varchar, @lColName) + ' = ' + CONVERT(NVARCHAR,@lClassSubjectId)  + ' AND RD.ClassSubjectId= '+ convert(varchar, @lColName) +''
		execute (@query)	
		SET @lSubCount = @lSubCount - 1

	END
		-- Personality Development
		SET @query =N'UPDATE  T  SET PD = (RD.FA2 + RD.FA4)/2
					 FROM #tempAnusuchiCMaster T 
					 INNER JOIN SGSEB.TRESULTDETAIL RD ON T.ACADEMICID = ' + CONVERT(NVARCHAR,@lAcademicId) + '
					 INNER JOIN sGSEB.tAnusuchiB AB ON AB.ACADEMICID = T.ACADEMICID AND AB.CLASSSUBJECTID = RD.CLASSSUBJECTID'
		EXEC sp_executesql  @query			 

	SET @lCount = @lCount - 1 
END
------ Personality Development Grade Evaluation
DECLARE @MinimumScore decimal(5,2)
DECLARE @Grade nvarchar(10)
DECLARE @GradePoint Decimal(6,2)

	CREATE TABLE #tempGradeSetDetail
 		(
 			Id INT IDENTITY (1, 1),
 			MinimumScore decimal(5,2),
 			Grade nvarchar(10),
 			GradePoint Decimal(6,2)					 
 		) 
 		INSERT INTO #tempGradeSetDetail
 		SELECT MinimumScore,GradeTitle,GradePoint		
		FROM sAssessment.tExamMaster EM 
		INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId = EM.Id
		INNER JOIN sGSEB.tGSEBExamMapping GEM ON EM.Id = GEM.ExamId AND  GSEBExamId = 1 and GEM.ClassId = @rClassId
		INNER JOIN sAssessment.tGradeSetMaster GM ON GM.ID = EM.GradeSetId
		INNER JOIN sAssessment.tGradeSetDetail GD ON GD.GradeSetId=GM.Id
		INNER JOIN sGSEB.tAnusuchiB AB ON AB.ClassSubjectId = ED.ClassSubjectId ORDER BY GD.MinimumScore DESC
		

SELECT @lCount =  COUNT(Id) FROM #tempGradeSetDetail
while (@lCount > 0)
BEGIN
	SELECT
		@MinimumScore =MinimumScore,
		@Grade= Grade,
		@GradePoint = GradePoint
		FROM #tempGradeSetDetail WHERE Id = @lCount
		
	Update #tempAnusuchiCMaster  Set PDGrade = @Grade WHERE PD >= @MinimumScore 
		AND AcademicId IN (SELECT AcademicID from sStudent.vStudentAcademic WHERE DivisionId=@rDivisionId AND StatusId=1)

	SET @lCount = @lCount - 1
 END	
---------- Total And Grade
	UPDATE T SET T.TOTAL=R.Obtain,T.Percentage=R.Percentage,T.Grade=R.Grade  FROM #tempAnusuchiCMaster T
	INNER JOIN sGSEB.tResult R ON R.AcademicId = T.ACADEMICID
 --------------------------------
SELECT 	@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2, 			
			BVC.ClassName,
			BVC.DivisionName,		
			SF.Name,
			SF.Number,
			SF.RollNo, 		
			CS1.SubjectName AS SUB1,
			CS2.SubjectName AS SUB2,
			CS3.SubjectName AS SUB3,
			CS4.SubjectName AS SUB4,
			CS5.SubjectName AS SUB5,
			CS6.SubjectName AS SUB6,
			CS7.SubjectName AS SUB7,			
			CS8.SubjectName AS SUB8,
			CS9.SubjectName AS SUB9,
			CS10.SubjectName AS SUB10,
			CS11.SubjectName AS SUB11,
			CS12.SubjectName AS SUB12,
			AIS.*		 
FROM #tempAnusuchiCMaster AIS		
		LEFT JOIN sGSEB.tResultDetail RD ON RD.AcademicId=AIS.AcademicId AND RD.ClassSubjectId = AIS.ClassSubjectId1		
		LEFT JOIN sSetup.vClassSubject CS1 ON CS1.ClassSubjectId = AIS.ClassSubjectId1		
		LEFT JOIN sSetup.vClassSubject CS2 ON CS2.ClassSubjectId = AIS.ClassSubjectId2		
		LEFT JOIN sSetup.vClassSubject CS3 ON CS3.ClassSubjectId = AIS.ClassSubjectId3		
		LEFT JOIN sSetup.vClassSubject CS4 ON CS4.ClassSubjectId = AIS.ClassSubjectId4		
		LEFT JOIN sSetup.vClassSubject CS5 ON CS5.ClassSubjectId = AIS.ClassSubjectId5		
		LEFT JOIN sSetup.vClassSubject CS6 ON CS6.ClassSubjectId = AIS.ClassSubjectId6		
		LEFT JOIN sSetup.vClassSubject CS7 ON CS7.ClassSubjectId = AIS.ClassSubjectId7		
		LEFT JOIN sSetup.vClassSubject CS8 ON CS8.ClassSubjectId = AIS.ClassSubjectId8		
		LEFT JOIN sSetup.vClassSubject CS9 ON CS9.ClassSubjectId = AIS.ClassSubjectId9		
		LEFT JOIN sSetup.vClassSubject CS10 ON CS10.ClassSubjectId = AIS.ClassSubjectId10		
		LEFT JOIN sSetup.vClassSubject CS11 ON CS11.ClassSubjectId = AIS.ClassSubjectId11		
		LEFT JOIN sSetup.vClassSubject CS12 ON CS12.ClassSubjectId = AIS.ClassSubjectId12		
		INNER JOIN sStudent.vStudentFull SF ON SF.AcademicId=AIS.AcademicId AND SF.StatusId = 1		
		INNER JOIN sSetup.vBatchClassDivision BVC ON BVC.DivisionId = SF.DivisionId
		ORDER BY SF.RollNo


DROP TABLE #tempAnusuchiCMaster
DROP TABLE #tempSubject


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


GO


ALTER PROCEDURE [sGSEB].[pRptFirstTermResultGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rBatchId int,
	 @rClassId int,
	 @rDivisionId int,
	 @rClassSubjectId int
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 



	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			SM.Code,
			ISNULL(SM.FirstName,'')+' '+ISNULL(SM.LastName,'') AS Name,
			A.RollNo,
			R.AcademicId,
			Convert(Nvarchar,R.AcademicId) AS AcademicIdText,
			ISNULL(SC.ParentContactNo,'') AS ContactNo,
			ISNULL(SC.PresentStreetThree,'')+' '+ISNULL(SC.PresentStreetTwo,'')+' '+ISNULL(SC.PresentStreetThree,'')+' '+ISNULL(SC.PresentCity,'')+' '+ISNULL(SC.PresentState,'') AS PresentAddress,
			SO.DateOfBirth,
			CM.DisplayTitle AS Class,
			DM.DisplayTitle AS Division,
			ISNULL(HM.Title,'') AS House,
			
			ISNULL(RD.FA1Grade,'') AS FA1Grade,
			ISNULL(RD.FA2Grade,'') AS FA2Grade,
			ISNULL(RD.FA3Grade,'')AS FA3Grade,
			ISNULL(RD.FA4Grade,'') AS FA4Grade,
			ISNULL(RD.SA1Grade,'') AS SA1Grade,
			ISNULL(RD.SA2Grade,'') AS SA2Grade,
			ISNULL(RD.FA1,0) AS FA1,
			ISNULL(RD.FA2,0) AS FA2,
			ISNULL(RD.FA3,0) AS FA3,
			ISNULL(RD.FA4,0) AS FA4,
			ISNULL(RD.SA1,0) AS SA1,
			ISNULL(RD.SA2,0) AS SA2,			
			ISNULL(RD.Grade,'') AS Grade,
			
			ISNULL(R.AttendanceTerm1,0) AS AttendanceTerm1,
			ISNULL(R.AttendanceTerm2,0) AS AttendanceTerm2,
			ISNULL(R.WorkingDaysTerm1,0) AS WorkingDaysTerm1,
			ISNULL(R.WorkingDaysTerm2,0) AS WorkingDaysTerm2,
	
			SubM.Title As ClassSubject,
			ISNULL(BGM.Title,'') AS BloodGroup,
	
			ISNULL(R.TOTAL1,0) AS TOTAL1,
			ISNULL(R.Obtain1,0) AS Obtain1,
			ISNULL(R.Result1,0) AS Result1,
			ISNULL(R.Percentage1,0) AS Percentage1,
			ISNULL(R.Percentile1,0) AS Percentile1,
			ISNULL(R.Remark1,0) AS Remark1,
			ISNULL(R.AttendanceTerm1,0) AS AttendanceTerm1,
			ISNULL(R.WorkingDaysTerm1,0) AS WorkingDaysTerm1,
			
			ISNULL(R.TOTAL2,0) AS TOTAL2,
			ISNULL(R.Obtain2,0) AS Obtain2,
			ISNULL(R.Result2,0) AS Result2,
			ISNULL(R.Percentage2,0) AS Percentage2,
			ISNULL(R.Percentile2,0) AS Percentile2,
			ISNULL(R.Remark2,0) AS Remark2,
			ISNULL(R.AttendanceTerm2,0) AS AttendanceTerm2,
			ISNULL(R.WorkingDaysTerm2,0) AS WorkingDaysTerm2,
			
			ISNULL(R.TOTAL,0) AS TOTAL,
			ISNULL(R.Obtain,0) AS Obtain,
			ISNULL(R.Result,0) AS Result,
			ISNULL(R.Percentage,0) AS Percentage,
			ISNULL(R.Percentile,0) AS Percentile,
			ISNULL(R.Remark,0) AS Remark,
			ISNULL(R.Grade,'') AS ResultGrade
      
	FROM 
	
			sGSEB.tResultDetail RD			
			INNER JOIN sGSEB.tResult R  ON RD.AcademicId=R.AcademicId
			INNER JOIN sStudent.tAcademic A ON R.AcademicId=A.Id 
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId And SM.StatusId = 1
			LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=A.StudentId
			LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId AND DM.ClassId=CM.Id
			LEFT JOIN sActivity.tHouseMaster HM ON HM.Id=SO.HouseId
			LEFT JOIN sSetup.tClassSubject CS ON CS.Id=RD.ClassSubjectId AND CS.IsOptional=0
			INNER JOIN sSetup.tSubjectMaster SubM ON SubM.Id=CS.SubjectId
			LEFT JOIN sCommon.tBloodGroupMaster BGM ON BGM.Id=SO.BloodGroupId
			--LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=A.StudentId
	WHERE 
			
    A.BatchId = @rBatchId 
		
	AND (A.DivisionId=@rDivisionId OR @rDivisionId=0)
	AND (A.ClassId=@rClassId OR @rClassId=0) 
	AND (RD.ClassSubjectId=@rClassSubjectId OR @rClassSubjectId=0)
	
	
		
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

BEGIN 
       SELECT  
         EM.Code AS EmployeeCode,
         EM.EmployeeName,   
         EM.EmployeeId,      
         ISNULL(WD.TotalDays,MY.NoOfDays) AS TotalDays,
         ISNULL(AT.TotalWorkingDays,ISNULL(WD.WorkingDays,0)) AS WorkingDays, 
         ISNULL(AT.LWP,0) AS LWP,
         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 
		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.tWorkingDays WD ON  EM.EmployeeGradeId = WD.EmployeeGradeId
	    AND WD.ForMonth=@rForMonth AND WD.ForYear=@rForYear AND WD.BatchId = @rBatchId
		--LEFT JOIN sHrm.tLeave L ON L.EmployeeId = EM.EmployeeId  
    	WHERE EM.OrgID = @rOrgId 
END
GO
PRINT N'Altering [sHrm].[pEmployeeCommunicationsGet]...';


GO
ALTER PROCEDURE [sHrm].[pEmployeeCommunicationsGet]
	 
	 @rEmployeeId bigint,
	 @rOrgId int
	 
	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 [EmployeeId]
      ,ISNULL([PresentStreetOne],'') AS [PresentStreetOne]
      ,ISNULL([PresentStreetTwo],'') AS [PresentStreetTwo]
      ,ISNULL([PresentStreetThree],'') AS [PresentStreetThree]
      ,ISNULL([PresentCountry],'') AS [PresentCountry]
      ,ISNULL([PresentState],'') AS [PresentState]
      ,ISNULL([PresentCity],'') AS [PresentCity]
      ,ISNULL([PresentZipCode],'') AS [PresentZipCode]
      ,ISNULL([PresentContactNo],'') AS [PresentContactNo]
      ,ISNULL([PermanentStreetOne],'') AS [PermanentStreetOne]
      ,ISNULL([PermanentStreetTwo],'') AS [PermanentStreetTwo]
      ,ISNULL([PermanentStreetThree],'') AS [PermanentStreetThree]
      ,ISNULL([PermanentCountry],'') AS [PermanentCountry]
      ,ISNULL([PermanentState],'') AS [PermanentState]
      ,ISNULL([PermanentCity],'') AS [PermanentCity]
      ,ISNULL([PermanentZipCode],'') AS [PermanentZipCode]
      ,ISNULL([PermanentContactNo],'') AS [PermanentContactNo]
      ,ISNULL([EmergencyStreetOne],'') AS [EmergencyStreetOne]
      ,ISNULL([EmergencyStreetTwo],'') AS [EmergencyStreetTwo]
      ,ISNULL([EmergencyStreetThree],'') AS [EmergencyStreetThree]
      ,ISNULL([EmergencyCountry],'') AS [EmergencyCountry]
      ,ISNULL([EmergencyState],'') AS [EmergencyState]
      ,ISNULL([EmergencyCity],'') AS [EmergencyCity]
      ,ISNULL([EmergencyZipCode],'') AS [EmergencyZipCode]
      ,ISNULL([EmergencyContactNo],'') AS [EmergencyContactNo]
      ,ISNULL([PhoneNoCompany],'') AS [PhoneNoCompany]
      ,ISNULL([ExtensionNo],'') AS [ExtensionNo]
      ,ISNULL([CompanyEmail],'') AS [CompanyEmail]
      ,ISNULL([PersonalEmail],'') AS [PersonalEmail]
      ,ISNULL([MobileNumber],'') AS [MobileNumber]
    
  FROM  [sHrm].[tEmployeeCommunications]
             
  WHERE 
		EmployeeId = @rEmployeeId 
		--	((SM.Code=@rCode) OR (ISNULL(@rCode,'') = ''))
		--AND(SM.OrgId=@rOrgId)

 --     ((BM.Id = @rId) OR (@rId = 0))
	--AND  ((BM.Code like @rCode) OR (ISNULL(@rCode,'') = '')) 
	--AND  ((BM.Title like @rTitle) OR (ISNULL(@rTitle,'') = '')) 
	--AND(BM.OrgId=@rOrgId)

--ORDER BY BM.OrderIndex ASC
  
		
END
GO
PRINT N'Altering [sHrm].[pEmployeeCustomSearchGet]...';


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

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


GO
ALTER PROCEDURE [sHrm].[pEmployeeDesignationMasterAdd]
	
	@rOrgId smallint,
	@rCode [nvarchar](20),
	@rTitle [nvarchar](100),	 
	@rIsObsolete [bit],
	@rCreatedUserId [bigint],	 
	@OutDesignationId int = null output  
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
BEGIN TRY
BEGIN TRANSACTION
	DECLARE @lNextNumber INT
	EXECUTE  sCommon.pTableRowIdGet @rOrgId, 'sHrm.tEmployeeDesignationMaster', 0, 1, 1,@outNextNumber = @lNextNumber output

	INSERT INTO sHrm.tEmployeeDesignationMaster
		(
			Id,
			Code,
			Title,			 
			IsObsolete,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime,
			OrgId
		)
	VALUES
		(
			@lNextNumber,
			@rCode,
			@rTitle,		 
			@rIsObsolete,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rOrgId
		)
		SET @OutDesignationId = @lNextNumber -- addd for import functionality
	SELECT @lNextNumber AS RESULT
	COMMIT TRANSACTION
	END TRY
	BEGIN CATCH
	ROLLBACK TRANSACTION
	SELECT -1 AS RESULT
	END CATCH						
END
GO
PRINT N'Altering [sHrm].[pEmployeeDetailListGet]...';


GO
ALTER PROCEDURE [sHrm].[pEmployeeDetailListGet]
(
	@rOrgId int,
	@rCode [nvarchar](20) = '',
	@rFirstname [nvarchar](50) = '',		
	@rLastName [nvarchar](50) = '',		
	@rDepartmentId [int] = 0,
	@rDesignationId [int] = 0
 )
AS
SET NOCOUNT ON

BEGIN
 
 		SET @rCode = ISNULL( sCommon.fSearchStringGet(@rCode),'')
		SET @rFirstname = ISNULL( sCommon.fSearchStringGet(@rFirstname),'')
		SET @rLastName = ISNULL( sCommon.fSearchStringGet(@rLastName),'')
		
		SELECT 
				EM.Id AS Id,
				EM.Code AS Code,
				ISNULL(EM.FirstName, '') + ' ' + ISNULL(EM.MiddleName, '') + ' ' + ISNULL(EM.LastName, '') AS NameFull, 
				ISNULL(EM.FirstName, '') + ' ' + ISNULL(EM.LastName, '') AS NameSurname, 
				EJD.OrganizationDepartmentId AS DepartmentId,
				ODM.Title AS Department,
				ISNULL(EJD.EmployeeDesignationId,0) AS DesignationId ,
				ISNULL(EDM.Title,'') AS Designation,
				EJD.EmployeeGradeId			
		FROM 
				sHrm.tEmployeeMaster EM
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id			
			INNER JOIN sSetup.tDepartmentMaster ODM ON ODM.Id = EJD.OrganizationDepartmentId						 			
			LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id = EJD.EmployeeDesignationId		
		WHERE 
				((EM.Code Like '%' +  @rCode + '%' ) OR (@rCode = ''))
			AND ((EM.FirstName Like '%' + @rFirstName  + '%') OR (@rFirstName = ''))	
		    AND ((EM.LastName Like '%' + @rLastName  + '%') OR (@rLastName = ''))
			AND ((EJD.OrganizationDepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))	
			AND ((EJD.EmployeeDesignationId = @rDesignationId) OR (@rDesignationId = 0))	
			AND EM.OrgId = @rOrgId
			ORDER BY EM.Code
END
GO
PRINT N'Altering [sHrm].[pEmployeeDetailRemove]...';


GO
ALTER PROCEDURE [sHrm].[pEmployeeDetailRemove]
 
	@rId bigint
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	BEGIN TRY
		BEGIN TRANSACTION	
				-- SET @1Result = 1
				 
				-- IF EXISTS(Select 1 FROM sPayroll.tPayProcessEmployee Where EmployeeId = @rEmployeeId)
				-- BEGIN
				--   SET @1Result = -101				   
				-- END
				 
				-- IF EXISTS(Select 1 FROM sActivity.tActivityParticipant Where SourceId = @rEmployeeId AND SourceTypeId = 95)
				-- BEGIN
				--   SET @1Result = -101				   
				-- END
				 
				-- ELSE IF EXISTS(Select 1 FROM sHostel.tAssignRoom where SourceId = @rEmployeeId AND SourceTypeId = 95)
				-- BEGIN
				--    SET @1Result = -101
				-- END			 
				 
				-- ELSE IF EXISTS(SELECT 1 FROM sCommunication.tPollMember WHERE SourceId = @rEmployeeId AND SourceTypeId = 95)
				--  BEGIN
				--     SET @1Result = -101
				--  END
				-- ELSE IF EXISTS(SELECT 1 FROM sHrm.tEmployeeAttendance Where EmployeeId = @rEmployeeId)
				-- BEGIN
				--    SET @1Result = -101
				-- END
				 
				-- ELSE IF EXISTS(Select 1 FROM sHostel.tHostelWarden Where EmployeeId = @rEmployeeId)
				-- BEGIN 
				--    SET @1Result = -101
				-- END		
				-- ELSE IF EXISTS(Select 1 FROM sCommunication.tDiscussionGroupMember Where SourceId = @rEmployeeId AND SourceTypeId = 95)
				-- BEGIN 
				--    SET @1Result = -101
				-- END	
				-- ELSE IF EXISTS(Select 1 FROM sHrm.tLeave Where EmployeeId = @rEmployeeId)
				-- BEGIN 
				--    SET @1Result = -101
				-- END				
				--ELSE IF EXISTS(Select 1 FROM sBi.tAction Where AssignedToEmployeeId = @rEmployeeId)
				-- BEGIN 
				--    SET @1Result = -101
				-- END		 
				-- ELSE IF EXISTS(Select 1 FROM sBi.tAudit Where BackupAuditorEmployeeId = @rEmployeeId)
				-- BEGIN 
				--    SET @1Result = -101
				-- END	 
				-- ELSE IF EXISTS(Select 1 FROM sLibrary.tBookLog  Where ReaderSourceId = @rEmployeeId and ReaderSourceTypeId = 95)
				-- BEGIN 
				--    SET @1Result = -101
				-- END			 
				-- ELSE IF EXISTS(Select 1 FROM sFee.tChargeReceipt Where SourceId = @rEmployeeId AND SourceTypeId = 95)
				-- BEGIN 
				--    SET @1Result = -101
				-- END	 
				-- ELSE IF EXISTS(Select 1 FROM sSetup.tDivisionMaster Where InchargeEmployeeId = @rEmployeeId)
				-- BEGIN 
				--    SET @1Result = -101
				-- END
				-- ELSE IF EXISTS(Select 1 FROM sProcurement.tFirstAidEmoloyee Where EmployeeId = @rEmployeeId)
				-- BEGIN 
				--    SET @1Result = -101
				-- END
				-- ELSE IF EXISTS(Select 1 FROM sProcurement.tFirstAidInspection Where EmployeeId = @rEmployeeId)
				-- BEGIN 
				--    SET @1Result = -101
				-- END
				-- ELSE IF EXISTS(Select 1 FROM sOrderEntry.tIssueReturn Where ParticipantSourceId = @rEmployeeId)
				-- BEGIN 
				--    SET @1Result = -101
				-- END
				-- ELSE IF EXISTS(Select 1 FROM sTimetable.tProxySetting Where EmployeeId = @rEmployeeId)
				-- BEGIN 
				--    SET @1Result = -101
				-- END
				-- ELSE IF EXISTS(Select 1 FROM sCommunication.tQueryCategoryMaster Where InchargeEmployeeId = @rEmployeeId)
				-- BEGIN 
				--    SET @1Result = -101
				-- END
				-- ELSE IF EXISTS(Select 1 FROM sAccounting.tReimbursement Where ParticipantSourceId = @rEmployeeId AND ParticipantSourceTypeId = 95 )
				-- BEGIN 
				--    SET @1Result = -101
				-- END
				-- ELSE IF EXISTS(Select 1 FROM sTimetable.tTimeTable Where EmployeeId = @rEmployeeId)
				-- BEGIN 
				--    SET @1Result = -101
				-- END
				-- ELSE IF EXISTS(Select 1 FROM sBi.tAudit Where LeadAuditorEmployeeId = @rEmployeeId)
				-- BEGIN 
				--    SET @1Result = -101
				-- END	 
				-- ELSE 
				--  BEGIN 
				--     SET @1Result = 1 
				     DELETE From sHrm.tEmployeeJobDetail Where EmployeeId = @rId 			
					 DELETE From sHrm.tEmployeePersonalDetail Where EmployeeId = @rId
					 DELETE From sHrm.tEmployeeCommunications Where EmployeeId = @rId
					 DELETE From sHrm.tEmployeeFamilyDetails Where EmployeeId = @rId
					 DELETE From sHrm.tEmployeePreviousEmployment Where EmployeeId = @rId
					 Delete From sHrm.tEmployeeImages where EmployeeId=@rId
					Delete from sSecurity.tDivisionPermission Where UserId IN(SELECT Id FROM sSecurity.tUser Where SourceId=@rId AND SourceTypeId=95)
					Delete from sSecurity.tUserPreference Where UserId IN(SELECT Id FROM sSecurity.tUser Where SourceId=@rId AND SourceTypeId=95)
					Delete from sSecurity.tUserProfile Where UserId IN(SELECT Id FROM sSecurity.tUser Where SourceId=@rId AND SourceTypeId=95)
					Delete from sSecurity.tUserRole Where UserId IN(SELECT Id FROM sSecurity.tUser Where SourceId=@rId AND SourceTypeId=95)
					Delete from sSecurity.tUser Where SourceId=@rId AND SourceTypeId=95
					DELETE FROM sHrm.tEmployeeMaster Where Id = @rId
				  COMMIT TRANSACTION	
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
	END CATCH	
END
GO
PRINT N'Altering [sHrm].[pEmployeeFamilyDelete]...';


GO
ALTER PROCEDURE [sHrm].[pEmployeeFamilyDelete]
			
			@rParticipantId bigint,
		    @rOrgId int
AS
SET NOCOUNT ON
 
BEGIN 
      
   IF EXISTS (SELECT 1 FROM sOrderEntry.tIssueReturn where ParticipantSourceTypeId = 1001 AND ParticipantSourceId = @rParticipantId)
	 SELECT -1 AS RESULT
   ELSE IF EXISTS (SELECT 1 FROM sAccounting.tReimbursement where ParticipantSourceTypeId = 1001 AND ParticipantSourceId = @rParticipantId)
     SELECT -1 AS RESULT
   ELSE 
    BEGIN
     DELETE FROM sHrm.tEmployeeFamilyDetails WHERE Id = @rParticipantId AND OrgId = @rOrgId
      SELECT 1 AS RESULT
    END
         
  
END
GO
PRINT N'Altering [sHrm].[pEmployeeGenerateReport]...';


GO
ALTER PROCEDURE [sHrm].[pEmployeeGenerateReport]
	
	@rId bigint,
	@rTitle nvarchar(50),
	@rColumnName nvarchar(max) = '',
	@rOrgId smallint,
	@rCode [nvarchar](20) = '',
	@rFirstName [nvarchar](50) = '',	
	@rLastName [nvarchar](50) = '',
	@rEmployeeTypeId[nvarchar](50) = '',
	@rStatusId[nvarchar](50) = '',
	@rOrganizationDepartmentId[nvarchar](50) = '',
	@rReligionId[nvarchar](50) = '',
	@rMaritalStatusId[nvarchar](50) = '',
	@rQualification[nvarchar](50) = '',
	@rGenderId[nvarchar](50) = '',
	@rEmployeeDesignationId[nvarchar](50) = '',
	@rBloodGroupId[nvarchar](50) = '',	 
	@rDOBFromDate Date = '0001-01-01',
	@rDOBToDate Date = '9999-12-31',
	@rDOJFromDate Date = '0001-01-01',
	@rDOJToDate Date = '9999-12-31',
	@rIsCommon bit,
	@rCreatedUserId bigint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	
	IF(@rDOBFromDate IS NULL)
		SET @rDOBFromDate='0001-01-01'
	IF(@rDOJFromDate IS NULL)
		SET @rDOJFromDate='0001-01-01'
	IF(@rDOBToDate IS NULL)
		SET @rDOBToDate='9999-12-31'
	IF(@rDOJToDate IS NULL)
		SET @rDOJToDate='9999-12-31'
	
	IF(@rTitle != '' AND @rId = 0)
	BEGIN
	DECLARE @lNextNumber BIGINT     
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sHrm.tEmployeeCustomSearch', 0, 1, 1,@outNextNumber = @lNextNumber output

	INSERT INTO sHrm.tEmployeeCustomSearch
		(
			Id,
			Title,
			ColumnName,
			OrgId,
			Code,
			FirstName,	
			LastName,
			EmployeeTypeId,
			StatusId,
			OrganizationDepartmentId,
			ReligionId,
			MaritalStatusId,
			Qualification,
			GenderId,
			EmployeeDesignationId,
			BloodGroupId,	 
			DOBFromDate,
			DOBToDate,
			DOJFromDate,
			DOJToDate,
			IsCommon,
			CreatedUserId,
			CreatedDateTime
		)
	VALUES
		(
			@lNextNumber,
			@rTitle,
			@rColumnName,
			@rOrgId,
			@rCode,
			@rFirstName,	
			@rLastName,
			@rEmployeeTypeId,
			@rStatusId,
			@rOrganizationDepartmentId,
			@rReligionId,
			@rMaritalStatusId,
			@rQualification,
			@rGenderId,
			@rEmployeeDesignationId,
			@rBloodGroupId,	 
			@rDOBFromDate,
			@rDOBToDate,
			@rDOJFromDate,
			@rDOJToDate,
			@rIsCommon,
			@rCreatedUserId,
			sCommon.fGetDate()
		)
		--SELECT @lNextNumber AS Result
	END
	
	IF(@rId > 0)
	BEGIN
		Select
				@rColumnName=ColumnName,
				@rOrgId=OrgId,
				@rCode=Code,
				@rFirstName=FirstName,	
				@rLastName=LastName,
				@rEmployeeTypeId=EmployeeTypeId,
				@rStatusId=StatusId,
				@rOrganizationDepartmentId=OrganizationDepartmentId,
				@rReligionId=ReligionId,
				@rMaritalStatusId=MaritalStatusId,
				@rQualification=Qualification,
				@rGenderId=GenderId,
				@rEmployeeDesignationId=EmployeeDesignationId,
				@rBloodGroupId=BloodGroupId,	 
				@rDOBFromDate=DOBFromDate,
				@rDOBToDate=DOBToDate,
				@rDOJFromDate=DOJFromDate,
				@rDOJToDate=DOJToDate
		FROM
			sHrm.tEmployeeCustomSearch
		WHERE
			Id=@rId
	END
	
	DECLARE @Sql nvarchar(MAX)
	
	SET @rCode = sCommon.fSearchStringGet(@rCode)
	SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
	SET @rLastName = sCommon.fSearchStringGet(@rLastName)
	SET @rQualification = sCommon.fSearchStringGet(@rQualification)
	
		SELECT 
			* into sHrm.tTempEmployee
		FROM 
			sHrm.vEmployeeCustomSearch ECS
		WHERE 
			ECS.OrgId = @rOrgId 
			AND ((ECS.Code Like @rCode + '%') OR (@rCode = ''))
			AND ((ECS.FirstName Like @rFirstName  + '%') OR (@rFirstName = ''))	 			 
			AND ((ECS.LastName Like @rLastName + '%')OR(@rLastName = ''))
			AND ((ISNULL(ECS.Qualification,'') Like @rQualification + '%')OR(@rQualification = ''))
			AND ((ECS.DateOfBirth >= @rDOBFromDate) OR (ISNULL(@rDOBFromDate,'') = ''))
			AND ((ECS.DateOfBirth <= @rDOBToDate) OR (ISNULL(@rDOBToDate,'') = ''))	
			AND ((ECS.DateOfJoining >= @rDOJFromDate) OR (ISNULL(@rDOJFromDate,'') = ''))
			AND ((ECS.DateOfJoining <= @rDOJToDate) OR (ISNULL(@rDOJToDate,'') = ''))	
			
			AND (ISNULL(ECS.OrganizationDepartmentId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrganizationDepartmentId,','))OR @rOrganizationDepartmentId='') 
			
			AND (ISNULL(ECS.StatusId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rStatusId,','))OR @rStatusId='') 
			
		    AND (ISNULL(ECS.EmployeeTypeId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rEmployeeTypeId,','))OR @rEmployeeTypeId='') 
			
		    AND (ISNULL(ECS.EmployeeDesignationId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rEmployeeDesignationId,','))OR @rEmployeeDesignationId='') 
			
		    AND (ISNULL(ECS.BloodGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rBloodGroupId,','))OR @rBloodGroupId='') 
			   
		    AND (ISNULL(ECS.ReligionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rReligionId,','))OR @rReligionId='') 
			        
		    AND (ISNULL(ECS.MaritalStatusId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rMaritalStatusId,','))OR @rMaritalStatusId='') 
			 
		    AND (ISNULL(ECS.GenderId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rGenderId,','))OR @rGenderId='') 
			   
		SET @sql=
		'SELECT '+
		@rColumnName+' 
		FROM sHrm.tTempEmployee'
		exec(@Sql)
		
		DROP Table sHrm.tTempEmployee
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		--SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sHrm].[pEmployeeJobDetailAdd]...';


GO
ALTER PROCEDURE [sHrm].[pEmployeeJobDetailAdd]
    
    @rOrgId smallint,
	@rEmployeeId [bigint], 
	@rEmployeeDesignationId [int],
	@rOrganizationDepartmentId [int],
	@rDateOfJoining Date,
	@rCreatedUserId [bigint],
	@rEmployeeTypeId int,
	@rEmployeeGradeId int,
	@rEmployeeGroupId int

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

	BEGIN TRY
	BEGIN TRANSACTION
	
			IF (@rEmployeeDesignationId <= 0)
			SET @rEmployeeDesignationId = NULL		
			
			IF(@rEmployeeTypeId <= 0)
			SET @rEmployeeTypeId = NULL			
			
			IF(@rEmployeeGradeId <= 0) 
			SET @rEmployeeGradeId = NULL
			
			IF(@rEmployeeGroupId <= 0)
			SET @rEmployeeGroupId = NULL
			
	INSERT INTO sHrm.tEmployeeJobDetail
		(
			EmployeeId,	
			EmployeeDesignationId,
			OrganizationDepartmentId,
			DateOfJoining,
			UpdatedUserId,
			UpdatedDateTime,
			OrgId,
			EmployeeTypeId,
			EmployeeGradeId,
			EmployeeGroupId
		)
	VALUES
		(
			@rEmployeeId, 			 
			@rEmployeeDesignationId,
			@rOrganizationDepartmentId,
			@rDateOfJoining,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rOrgId,
			@rEmployeeTypeId,
			@rEmployeeGradeId,
			@rEmployeeGroupId
		)
	
	SELECT @rEmployeeId AS Result
	
	COMMIT TRANSACTION
	END TRY
	BEGIN CATCH
	ROLLBACK TRANSACTION
	 RAISERROR ('Error Creating Job Detail', -- Message text.
               16, -- Severity.
               1 -- State.
               );
	--SELECT -1 AS RESULT
	END CATCH	
END
GO
PRINT N'Altering [sHrm].[pEmployeeJobDetailGet]...';


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

BEGIN
	 SELECT 
			JD.EmployeeId,			 
			ISNULL(JD.EmployeeDesignationId,0) AS EmployeeDesignationId,
			ISNULL(DM.Title,'') AS EmployeeDesignation,
			JD.OrganizationDepartmentId,
			ODM.Title AS OrganizationDepartment, 
			ISNULL(JD.DateOfJoining,'0001/01/01') AS DateOfJoining,
			JD.UpdatedUserId,
			JD.UpdatedDateTime,
			ISNULL(JD.EmployeeTypeId,0) AS EmployeeTypeId,
			ISNULL(JD.DateOfleaving,'01-01-0001') AS DateOfLeaving,
			ISNULL(JD.ReasonOfleaving,'') AS ReasonOfLeaving,
			ISNULL(JD.EmployeeGradeId,0) AS EmployeeGradeId,
			ISNULL(JD.EmployeeGroupId,0) AS EmployeeGroupId
			
	   FROM 
			sHrm.tEmployeeJobDetail JD
	   INNER JOIN sSetup.tDepartmentMaster ODM ON ODM.Id = JD.OrganizationDepartmentId	
	   LEFT JOIN sHrm.tEmployeeDesignationMaster DM ON DM.Id  = JD.EmployeeDesignationId
	   WHERE 
			((EmployeeId = @rEmployeeId) OR (@rEmployeeId = 0))
		AND JD.OrgId = @rOrgId
END
GO
PRINT N'Altering [sHrm].[pEmployeeJobDetailModify]...';


GO
ALTER PROCEDURE [sHrm].[pEmployeeJobDetailModify]
 
	@rEmployeeId [bigint], 
	@rEmployeeDesignationId [int],
	@rOrganizationDepartmentId [int],
	@rDateOfJoining Date,
	@rUpdatedUserId [bigint],
	@rEmployeeTypeId int,
	@rDateOfLeaving Date = null,
	@rReasonOfLeaving nvarchar(200) = null,
	@rEmployeeGradeId int,
	@rEmployeeGroupId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	
			IF (@rEmployeeDesignationId <= 0)
			SET @rEmployeeDesignationId = NULL
			
	 UPDATE sHrm.tEmployeeJobDetail
		SET  
			EmployeeDesignationId = @rEmployeeDesignationId,			 
			OrganizationDepartmentId = @rOrganizationDepartmentId,
			DateOfJoining =	@rDateOfJoining,
			UpdatedUserId = @rUpdatedUserId,
			UpdatedDateTime = sCommon.fGetDate(),
			EmployeeTypeId = @rEmployeeTypeId,
			DateOfleaving = @rDateOfLeaving,
			ReasonOfleaving = @rReasonOfLeaving,
			EmployeeGradeId = @rEmployeeGradeId,
			EmployeeGroupId = @rEmployeeGroupId
			
	  WHERE 
			EmployeeId = @rEmployeeId
	
	  SELECT 1 AS JobDetailId From sHrm.tEmployeeJobDetail where EmployeeId = @rEmployeeId
END
GO
PRINT N'Altering [sHrm].[pEmployeeJobTitleMasterGet]...';


GO
ALTER PROCEDURE [sHrm].[pEmployeeJobTitleMasterGet]
	
	@rOrgId smallint,
	@rId [int] = 0,
	@rCode [nvarchar](100) = '',
	@rTitle [nvarchar](20) = '',
	@rEmployeeGradeId [int] = 0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	
	SET @rTitle = sCommon.fSearchStringGet(@rTitle)
	SET @rCode = sCommon.fSearchStringGet(@rCode)
	
	 SELECT 
			JTM.Id,
			JTM.Code,
			JTM.Title,
			JTM.IsObsolete,
			JTM.CreatedUserId,
			JTM.CreatedDateTime,
			JTM.UpdatedUserId,
			JTM.UpdatedDateTime
	   FROM 
			sHrm.tEmployeeJobTitleMaster JTM
	   WHERE 
			((JTM.Id = @rId) OR (@rId = 0))
	   AND ((JTM.Title LIKE @rTitle) OR (@rTitle = ''))
	   AND ((JTM.Code LIKE  @rCode) OR (@rCode = ''))
	   AND JTM.OrgId = @rOrgId
END
GO
PRINT N'Altering [sHrm].[pEmployeeMasterAdd]...';


GO
ALTER PROCEDURE [sHrm].[pEmployeeMasterAdd]
    
    @rOrgId smallint,
	@rCode [nvarchar](100),
	@rFirstName [nvarchar](100),
	@rMiddleName [nvarchar](100),
	@rLastName [nvarchar](100),
    @rEmployeeTypeId int,
	@rDepartmentId int,
	@rDateOfBirth Date,
	@rDateOfJoining Date,
	@rGenderId int,
	@rReligionId int=null,
	@rStatusId [int],
	@rIsObsolete [bit],
	@rCreatedUserId [bigint],
	@OutEmployeeId bigint = null output,
	@rEmployeeDesignationId INT,
	@rBloodGroupId INT = 0,
	@rQualification nvarchar(150) = '',
	@rEmployeeGradeId int,
	@rEmployeeGroupId int,
	@rShortName nvarchar(50)
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

	DECLARE @lNextNumber BIGINT
	
	DECLARE @loEmpNumber Nvarchar(100)
	DECLARE @lEmpPrefixResult Int
    
 --   IF((@rCode = Null) OR (@rCode = ''))
 --   BEGIN
	--	EXECUTE sCommon.pPrefixSetupNextNumberGet @rOrgId = @rOrgId, @rPrefixFunctionalityId = 94,@rStoreLocationId = 0, @rNextNumber = @loEmpNumber OUTPUT	
	--	SET @loEmpNumber = ISNULL(@loEmpNumber, '-300')
	--	SET @lEmpPrefixResult = '-300'	
	--END
	--ELSE
	--  BEGIN
 --       SET	@loEmpNumber = @rCode
 --     END
            		
	--IF (@loEmpNumber <> '-300')
	--BEGIN
	
	BEGIN TRY
 	BEGIN TRANSACTION
	
		EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sHrm.tEmployeeMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
				
		INSERT INTO sHrm.tEmployeeMaster
			(
				Id,
				Code,
				FirstName,
				MiddleName,
				LastName,
				ShortName,
				StatusId,
				IsObsolete,
				CreatedUserId,
				CreatedDateTime,
				UpdatedUserId,
				UpdatedDateTime,
				OrgId
			)
		VALUES
			(
				@lNextNumber,
				@rCode,
				@rFirstName,
				@rMiddleName,
				@rLastName,
				@rShortName,
				@rStatusId,
				@rIsObsolete,
				@rCreatedUserId,
				sCommon.fGetDate(),
				@rCreatedUserId,
				sCommon.fGetDate(),
				@rOrgId
			)
			
		SELECT Id AS RESULT, @loEmpNumber AS EmpCode FROM sHrm.tEmployeeMaster WHERE  Id = @lNextNumber
		SET @OutEmployeeId = @lNextNumber -- added for import employee
		
		BEGIN 
        Execute sHrm.pEmployeeJobDetailAdd  
	       @rOrgId,@lNextNumber,@rEmployeeDesignationId,@rDepartmentId,@rDateOfJoining,@rCreatedUserId,
	       @rEmployeeTypeId,@rEmployeeGradeId,@rEmployeeGroupId
	          
	     Execute sHrm.pEmployeePersonalDetailAdd @rOrgId,@lNextNumber,'',@rDateOfBirth,@rGenderId,@rReligionId,
	     0,'',@rBloodGroupId,@rQualification,@rCreatedUserId
	        
		END	

		COMMIT TRANSACTION
	 
		END TRY
		
		BEGIN CATCH
		ROLLBACK TRANSACTION 
 
			RAISERROR ('Error saving employee Master', -- Message text.
               16, -- Severity.
               1 -- State.
               );           
		----SELECT -1 AS RESULT
 
		END CATCH			
	--END		
	--ELSE
	--BEGIN
	--SELECT @loEmpNumber AS RESULT
	
	--END	
END
GO
PRINT N'Altering [sHrm].[pEmployeeMasterGet]...';


GO
ALTER PROCEDURE [sHrm].[pEmployeeMasterGet]
	 
	 @rOrgId smallint,
	 @rId [bigint] = 0,
	 @rCode nvarchar(50) = ''
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 --  IF @rIsWildCardSearch = 1
		--BEGIN			
		--	SET @rCode = sCommon.fSearchStringGet(@rCode)
		--END
	 SELECT 
				EM.Id,
				EM.Id AS EmployeeId,
				EM.Code,
				EM.FirstName,
				EM.MiddleName,
				EM.LastName,
				EM.ShortName AS EmpShortName,
				EM.StatusId,
				EM.IsObsolete,
				EM.FirstName+' '+EM.LastName As EmployeeFullName,
				EJD.OrganizationDepartmentId AS DepartmentId,
				EJD.DateOfJoining,
				EJD.EmployeeTypeId,
				EPD.DateOfBirth,
				EPD.GenderId,
				EJD.EmployeeDesignationId,
				ISNULL(DM.Title,'') AS EmployeeDesignation,
				EJD.EmployeeGradeId,
				EJD.EmployeeGroupId
	   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 DM	ON DM.Id  = EJD.EmployeeDesignationId
	WHERE 
			    EM.OrgId = @rOrgId
		   AND ((EM.Id = @rId) OR (@rId = 0))
		   AND ((EM.Code Like  @rCode ) OR (@rCode = ''))
END
GO
PRINT N'Altering [sHrm].[pEmployeeMasterListingGet]...';


GO
ALTER PROCEDURE [sHrm].[pEmployeeMasterListingGet]
(
	@rOrgId smallint,
	@rCode [nvarchar](20) = '',
	@rName [nvarchar](50) = '',	
	@rSurName[nvarchar](50) = '',
	@rEmployeeTypeId int = 0,
	@rStatusId int = 0,
	@rDepartmentId int = 0
 )
AS
SET NOCOUNT ON

BEGIN
		SET @rCode = sCommon.fSearchStringGet(@rCode)
		SET @rName = sCommon.fSearchStringGet(@rName)
		SET @rSurName = sCommon.fSearchStringGet(@rSurName)
		
		SELECT 
				EM.Id AS EmployeeId,
				EM.Code AS Code,
				ISNULL(EM.FirstName, '') + ' ' + ISNULL(EM.MiddleName, '') + ' ' + ISNULL(EM.LastName, '') AS Name,
				ISNULL(ETM.Id,0) AS EmployeeTypeId,			
				ISNULL(ETM.Title,'') As EmployeeType,
				ISNULL(SM.Id,0) AS StatusId,
				ISNULL(SM.Title,'') AS Status,
				EJD.OrganizationDepartmentId,
				EJD.EmployeeGradeId,
				ODM.Title AS OrganizationDepartment,
				EM.IsObsolete AS IsObsolete,
				EJD.EmployeeGroupId
		FROM 
				sHrm.tEmployeeMaster EM
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
			INNER JOIN sSetup.tDepartmentMaster ODM ON ODM.Id = EJD.OrganizationDepartmentId
			INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId = EM.Id
			LEFT JOIN sHrm.tEmployeeTypeMaster ETM ON ETM.Id = EJD.EmployeeTypeId
			INNER JOIN sCommon.tStatusMaster SM ON SM.Id = EM.StatusId AND SM.StatusTypeId = 4
		WHERE 
				EM.OrgId = @rOrgId 
			AND ((EM.Code Like @rCode + '%') OR (@rCode = ''))
			AND ((EM.FirstName Like @rName  + '%') OR (@rName = ''))	 			 
			AND ((EM.LastName Like @rSurName + '%')OR(@rSurName = ''))
			AND ((EJD.OrganizationDepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))	
			AND ((EM.StatusId = @rStatusId) OR (@rStatusId = 0))			
			AND ((EJD.EmployeeTypeId = @rEmployeeTypeId) OR (@rEmployeeTypeId = 0))	
			Order By EM.Code	
END
GO
PRINT N'Altering [sHrm].[pEmployeeMasterModify]...';


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

BEGIN 
			
	 UPDATE sHrm.tEmployeeMaster
		SET
		    Code = @rCode, 
			FirstName = @rFirstName,
			MiddleName = @rMiddleName,
			LastName = @rLastName,
			StatusId = @rStatusId,
			ShortName=@rShortName,
			IsObsolete = @rIsObsolete,
			UpdatedUserId = @rUpdatedUserId,
			UpdatedDateTime = sCommon.fGetDate()
	  WHERE 
			Id = @rId
	  
	SELECT @rId AS RESULT
	
	BEGIN 
	UPDATE sHrm.tEmployeeJobDetail
		SET 
			EmployeeDesignationId = @rEmployeeDesignationId,	
			OrganizationDepartmentId = @rDepartmentId,
			DateOfJoining =	@rDateOfJoining,
			UpdatedUserId = @rUpdatedUserId,
			EmployeeTypeId = @rEmployeeTypeId,
			EmployeeGradeId = @rEmployeeGradeId,
			EmployeeGroupId = @rEmployeeGroupId
		WHERE 
			EmployeeId = @rId
	
	UPDATE sHrm.tEmployeePersonalDetail
		SET 
			DateOfBirth	=	@rDateOfBirth,
			GenderId	=	@rGenderId,
			UpdatedUserId = @rUpdatedUserId
		WHERE 
			EmployeeId = @rId	
	  
	  --BEGIN
	  --   Execute sHrm.pEmployeeJobDetailModify 
	  --     0,@rId,0,@rEmployeeDesignationId,@rLocationId,@rDepartmentId,@rDateOfJoining,'','',0,0,@rUpdatedUserId,
	  --     0,0,@rEmployeeTypeId,@rProcessTypeId,NULL,NULL,NULL,0,0
	     --Execute sHrm.pEmployeePersonalDetailModify
	     --  0,@rId,'',@rDateOfBirth,@rGenderId,0,0,'','',0,0,'','','','','',0,'',0,'',0,0,@rUpdatedUserId,@rIsBirthDateUnknown
	     
	  END
END
GO
PRINT N'Altering [sHrm].[pEmployeePersonalDetailAdd]...';


GO
ALTER PROCEDURE [sHrm].[pEmployeePersonalDetailAdd]
	
	@rOrgId smallint,
	@rEmployeeId [bigint],
	@rUIDNumber [nvarchar](50),
	@rDateOfBirth	date,
	@rGenderId	tinyint,
	@rReligionId	int,
	@rMaritalStatusId	tinyint,
	@rIdentificationMark1	nvarchar(100),
	@rBloodGroupId	tinyint,
	@rQualification	nvarchar(150),
	@rCreatedUserId [bigint]
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

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

 		IF (@rReligionId <= 0)
			SET @rReligionId = NULL
			
  		IF (@rMaritalStatusId <= 0)
			SET @rMaritalStatusId = NULL
			
	  	IF (@rBloodGroupId <= 0 OR @rBloodGroupId Is null)
			SET @rBloodGroupId = 9
		
	INSERT INTO sHrm.tEmployeePersonalDetail
		(
			EmployeeId,
			UIDNumber,
			DateOfBirth,
			GenderId,
			ReligionId,
			MaritalStatusId,
			IdentificationMark1,
			BloodGroupId,
			Qualification,
			UpdatedUserId,
			UpdatedDateTime,
			OrgId
		)
	VALUES
		(
			@rEmployeeId,
			@rUIDNumber,
			@rDateOfBirth,
			@rGenderId,
			@rReligionId,
			@rMaritalStatusId,
			@rIdentificationMark1,
			@rBloodGroupId,
			@rQualification,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rOrgId
		)
	SELECT @lNextNumber AS RESULT
	COMMIT TRANSACTION
	END TRY
	BEGIN CATCH
	ROLLBACK TRANSACTION
	SELECT -1 AS RESULT
	END CATCH				
END
GO
PRINT N'Altering [sHrm].[pEmployeePersonalDetailGet]...';


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

BEGIN
	 SELECT 
			EPD.UIDNumber,
			EPD.EmployeeId,			 
			EPD.DateOfBirth,
			EPD.GenderId,			
			ISNULL(EPD.ReligionId,0) AS ReligionId, 
			ISNULL(EPD.MaritalStatusId,0) AS MaritalStatusId, 
			EPD.IdentificationMark1,
			EPD.BloodGroupId, 
			ISNULL(EPD.Qualification,'') AS Qualification,
			EPD.UpdatedUserId,
			EPD.UpdatedDateTime
	FROM 
			sHrm.tEmployeePersonalDetail EPD 
	WHERE 
			((EmployeeId = @rEmployeeId) OR (@rEmployeeId = 0))
		AND EPD.OrgId = @rOrgId
END
GO
PRINT N'Altering [sHrm].[pEmployeePersonalDetailModify]...';


GO
ALTER PROCEDURE [sHrm].[pEmployeePersonalDetailModify]
	 
	@rEmployeeId [bigint],
	@rUIDNumber [nvarchar](50),
	@rDateOfBirth	date,
	@rGenderId	tinyint,
	@rReligionId	int,
	@rMaritalStatusId	tinyint,
	@rIdentificationMark1	nvarchar(100),
	@rBloodGroupId	tinyint,
	@rQualification	nvarchar(150),
	@rUpdatedUserId [bigint]
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
		IF (@rReligionId <= 0)
			SET @rReligionId = NULL			
  		IF (@rMaritalStatusId <= 0)
			SET @rMaritalStatusId = NULL	
	  	IF (@rBloodGroupId <= 0 OR @rBloodGroupId Is null)
			SET @rBloodGroupId = 9			
	
	UPDATE sHrm.tEmployeePersonalDetail
		SET 
				UIDNumber = @rUIDNumber,
				DateOfBirth	=	@rDateOfBirth,
				GenderId	=	@rGenderId,
				ReligionId	=	@rReligionId,
				MaritalStatusId	=	@rMaritalStatusId,
				IdentificationMark1	=	@rIdentificationMark1,		 
				BloodGroupId	=	@rBloodGroupId,
				Qualification	=	@rQualification,
				UpdatedUserId = @rUpdatedUserId,
				UpdatedDateTime = sCommon.fGetDate()
	    WHERE 
				EmployeeId = @rEmployeeId
	       
	  SELECT 1 AS RESULT
END
GO
PRINT N'Altering [sHrm].[pEmployeeSearchGet]...';


GO

ALTER PROCEDURE [sHrm].[pEmployeeSearchGet]
	 
	@rCode nvarchar(20),
	@rBatchId int
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 
	SELECT 
			VEM.Code,
			EB.Id AS EmployeeBatchId,
			VEM.Id AS EmployeeId,
			VEM.EmployeeName AS Name,
			VEM.DepartmentName,
			VEM.DepartmentId
  FROM 
		  sHrm.tEmployeeBatch EB
	   INNER JOIN sHrm.vExtEmployeeMaster VEM ON VEM.Id=EB.EmployeeId
  WHERE 
			((VEM.Code= @rCode) OR (ISNULL(@rCode,'') = '')) 
		AND (EB.BatchId=@rBatchId)
END
GO
PRINT N'Altering [sHrm].[pImportEmployee]...';


GO
ALTER PROCEDURE [sHrm].[pImportEmployee]
	
	@rOrgGroupId int,
    @rOrgId int,
	@rXmldoc [nvarchar](max),
	@rUserId bigint

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
BEGIN TRY

DECLARE @lCount INT
DECLARE @lInterrorCode INT,
			@intDoc INT,
			@lCode nvarchar(20),
			@lShortName nvarchar(50),
			@lFirstName Nvarchar(100),
			@lMiddleName Nvarchar(100),
			@lLastName Nvarchar(100),
			@lGenderId int = 0,
			@lGender nvarchar(10),
			@lEmployeeTypeId int = 0,
			@lEmployeeType nvarchar(100),
			@lEmployeeGroupId int,
			@lEmployeeGroup nvarchar(100),
			@lEmployeeGradeId int,
			@lEmployeeGrade nvarchar(100),
			@lDepartmentId int,
			@lDepartment nvarchar(100),
			@lDesignationId int,
			@lDesignation nvarchar(100),
			@lQualification nvarchar(150),
			@lDOB DATETIME,
			@lDOJ DATETIME,
			@lReligionId int,
			@lReligion nvarchar(100),
			@lCompanyPhoneNo Nvarchar(50),
			@lExtentionNo Nvarchar(10),
			@lCompanyEmailId Nvarchar(100),
			@lPersonalEmailId Nvarchar(100),
			@lMobileNo Nvarchar(20),
			@lPresentStreetOne nvarchar(50),
			@lPresentStreetTwo nvarchar(50),
			@lPresentStreetThree nvarchar(50),
			@lPresentCity nvarchar(50),
			@lPresentZipCode nvarchar(20),
			@lPresentState nvarchar(50),
			@lPresentCountry nvarchar(50),
			@lPresentContactNo nvarchar(20)
			
DECLARE @OutEmployeeId bigint		
			
EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc
	
	CREATE TABLE #tTable  
	(
		Id bigint identity,	 
		Code nvarchar(20),
		ShortName nvarchar(50),
		FirstName Nvarchar(100),
		MiddleName Nvarchar(100) null,
		LastName Nvarchar(100),
		GenderId int null,
		Gender nvarchar(10),
		EmployeeTypeId int null,
		EmployeeType nvarchar(100),
		EmployeeGroupId int null,
		EmployeeGroup nvarchar(100),
		EmployeeGradeId int null,
		EmployeeGrade nvarchar(100),
		DepartmentId int null,
		Department nvarchar(100),
		DesignationId int null,
		Designation nvarchar(100),
		Qualification nvarchar(150),	 
		DOB date,
		DOJ date,
		ReligionId int,
		Religion nvarchar(100),
		CompanyPhoneNo nvarchar(50) null,
		ExtentionNo nvarchar(10) null,
		CompanyEmailId nvarchar(100) null,
		PersonalEmailId nvarchar(100) null,
		MobileNo nvarchar(20) null,
		PresentStreetOne nvarchar(50),
		PresentStreetTwo nvarchar(50),
		PresentStreetThree nvarchar(50),
		PresentCity nvarchar(50),
		PresentZipCode nvarchar(20),
		PresentState nvarchar(50),
		PresentCountry nvarchar(50),
		PresentContactNo nvarchar(20),
		CreatedUserId bigint null
	)
		
	INSERT INTO #tTable
	(
		Code,
		ShortName,
		FirstName,
		MiddleName,
		LastName,
		GenderId,
		Gender,
		EmployeeTypeId,
		EmployeeType,
		EmployeeGroupId,
		EmployeeGroup,
		EmployeeGradeId,
		EmployeeGrade,
		DepartmentId,
		Department,
		DesignationId,
		Designation,
		Qualification,	 
		DOB,
		DOJ,
		ReligionId,
		Religion,
		CompanyPhoneNo,
		ExtentionNo,
		CompanyEmailId,
		PersonalEmailId,
		MobileNo,
		PresentStreetOne,
		PresentStreetTwo,
		PresentStreetThree,
		PresentCity,
		PresentZipCode,
		PresentState,
		PresentCountry,
		PresentContactNo,
		CreatedUserId		
	)
	SELECT
		Code,
		ShortName,
		FirstName,
		MiddleName,
		LastName,
		0,
		Gender,
		0,
		EmployeeType,
		0,
		EmployeeGroup,
		0,
		EmployeeGrade,
		0,
		Department,
		0,
		Designation,
		Qualification,	 
		DOB,
		DOJ,
		0,
		Religion,
		CompanyPhoneNo,
		ExtentionNo,
		CompanyEmailId,
		PersonalEmailId,
		MobileNo,
		PresentStreetOne,
		PresentStreetTwo,
		PresentStreetThree,
		PresentCity,
		PresentZipCode,
		PresentState,
		PresentCountry,
		PresentContactNo,
		CreatedUserId
		
	FROM OPENXML (@intDoc, '/Table/ImportEmployee', 1)
	WITH
	( 
		Code nvarchar(20) '@Code',
		ShortName nvarchar(50) '@ShortName',
		FirstName Nvarchar(100) '@FirstName',
		MiddleName Nvarchar(100) '@MiddleName',
		LastName Nvarchar(100) '@LastName',  			
		Gender nvarchar(10) '@Gender', 			
		EmployeeType nvarchar(100) '@EmployeeType',		
		EmployeeGroup nvarchar(100) '@EmployeeGroup',
		EmployeeGrade nvarchar(100) '@EmployeeGrade',	
		Department nvarchar(100) '@Department', 			
		Designation nvarchar(100) '@Designation',	 		
		Qualification nvarchar(150) '@Qualification',	 			
		DOB nvarchar(15) '@DOB', 			
		DOJ nvarchar(15) '@DOJ',	 			
		Religion nvarchar(100) '@Religion',
		CompanyPhoneNo nvarchar(50) '@CompanyPhoneNo',
		ExtentionNo nvarchar(10) '@ExtentionNo', 	
		CompanyEmailId nvarchar(100) '@CompanyEmailId',
		PersonalEmailId nvarchar(100) '@PersonalEmailId',
		MobileNo nvarchar(20) '@MobileNo',
		PresentStreetOne nvarchar(50) '@PresentStreetOne',
		PresentStreetTwo nvarchar(50) '@PresentStreetTwo',
		PresentStreetThree nvarchar(50) '@PresentStreetThree',
		PresentCity nvarchar(50) '@PresentCity',
		PresentZipCode nvarchar(20) '@PresentZipCode',
		PresentState nvarchar(50) '@PresentState',
		PresentCountry nvarchar(50) '@PresentCountry',
		PresentContactNo nvarchar(20) '@PresentContactNo',		
		CreatedUserId bigint '@CreatedUserId'
	)
	
EXEC sp_xml_removedocument @intDoc
			
SELECT @lCount =  COUNT(Id) FROM #tTable

WHILE @lCount > 0 

BEGIN
		SET	@lCode = ''	
		SET @lShortName = ''
		SET @lFirstName = ''
		SET @lMiddleName = ''
		SET @lLastName = ''	
		SET	@lGenderId = 0
		SET	@lGender = ''
		SET	@lEmployeeTypeId = 0
		SET	@lEmployeeType = ''
		SET	@lEmployeeGroupId = null
		SET	@lEmployeeGroup = ''
		SET	@lEmployeeGradeId = null
		SET	@lEmployeeGrade = ''
		SET	@lDepartmentId = null
		SET	@lDesignationId = null
		SET	@lDepartment = ''
		SET	@lDesignation = ''
		SET @lQualification = ''	
		SET	@lDOB = null
		SET	@lDOJ = null
		SET @lReligionId = null
		SET @lReligion = ''
		SET	@lCompanyPhoneNo = null
		SET	@lExtentionNo = null
		SET	@lCompanyEmailId = null
		SET	@lPersonalEmailId = null
		SET	@lMobileNo = null
		SET @OutEmployeeId = null
		SET @lPresentStreetOne = ''
		SET @lPresentStreetTwo = ''
		SET @lPresentStreetThree = ''
		SET @lPresentCity = ''
		SET @lPresentZipCode = ''
		SET @lPresentState = ''
		SET @lPresentCountry = ''
		SET @lPresentContactNo = ''
		
SELECT		
		@lCode = Code,
		@lShortName = ShortName,
		@lFirstName = FirstName,
		@lMiddleName = MiddleName,
		@lLastName = LastName,	
		@lGender = Gender,
		@lEmployeeType = EmployeeType,	
	    @lEmployeeGroup = EmployeeGroup,
	    @lEmployeeGrade = EmployeeGrade,
		@lDepartment = Department,
		@lDesignation= Designation,	
		@lQualification = Qualification,	
		@lDOB = CASE			
		WHEN DOB = '' THEN  '01/01/1990'
		ELSE DOB  
		--CONVERT(datetime, DOB, 103)
		END,		
		@lDOJ = CASE	
		WHEN DOJ = '' THEN  GETDATE()
		ELSE DOJ 
		END,			
		--@lDOB = convert(datetime, DOB, 103),
		--@lDOJ = convert(datetime, DOJ, 103),
		@lReligion = Religion,
	    @lCompanyPhoneNo = CompanyPhoneNo,
	    @lExtentionNo = ExtentionNo,
	    @lCompanyEmailId = CompanyEmailId,
		@lPersonalEmailId = PersonalEmailId,
		@lMobileNo = MobileNo,
		@lPresentStreetOne = PresentStreetOne,
		@lPresentStreetTwo = PresentStreetTwo,
		@lPresentStreetThree = PresentStreetThree,
		@lPresentCountry = PresentCountry,
		@lPresentState = PresentState,
		@lPresentCity = PresentCity,
		@lPresentZipCode = PresentZipCode,
		@lPresentContactNo = PresentContactNo
											 	 
FROM #tTable WHERE Id = @lCount  

--select * from #tTable

	SELECT	@lGenderId = ID FROM sCommon.tGenderMaster WHERE Title = @lGender
	SELECT	@lEmployeeTypeId = ID FROM sHrm.tEmployeeTypeMaster WHERE Title = @lEmployeeType AND OrgId = @rOrgId
	SELECT	@lEmployeeGroupId  = ID FROM sHrm.tEmployeeGroupMaster WHERE Title = @lEmployeeGroup
	SELECT	@lEmployeeGradeId  = ID FROM sHrm.tEmployeeGradeMaster WHERE Title = @lEmployeeGrade AND OrgId = @rOrgId
	SELECT	@lDepartmentId  = ID FROM sSetup.tDepartmentMaster WHERE Title = @lDepartment AND OrgId = @rOrgId
	SELECT	@lDesignationId  = ID FROM sHrm.tEmployeeDesignationMaster WHERE Title = @lDesignation AND OrgId = @rOrgId
	SELECT	@lReligionId  = ID FROM sCommon.tReligionMaster WHERE Title = @lReligion AND OrgGroupId = @rOrgGroupId
	
	IF(@lGenderId IS NULL)
		SET @lGenderId = 0
	IF(@lEmployeeGroupId IS NULL)
		SET @lEmployeeGroupId = 0
	IF(@lEmployeeGradeId IS NULL)
		SET @lEmployeeGradeId = 0
	
 BEGIN TRANSACTION
    --Default Group Id = 1
--IF 	@lDepartmentId IS NULL  AND @lDepartment != ''
--BEGIN
--DECLARE @1DepartmentGroupId  int 
-- SET @1DepartmentGroupId = sCommon.fGetIntIdForOrg(1,@rOrgId) 
-- EXEC [sCommon].[pOrganizationDepartmentMasterAdd] @rOrgId,@lDepartment,@lDepartment,0,@rUserId,@OutDepartmentId OUTPUT
--END
--ELSE
--SET @OutDepartmentId = @lDepartmentId

--IF 	@lEmployeeGradeId IS NULL  AND @lEmployeeGrade != ''
--BEGIN
--DECLARE @1EmployeeGradeGroupId  int 
-- EXEC [sHrm].[pEmployeeGradeMasterAdd] @rOrgId,@lEmployeeGrade,@lEmployeeGrade,0,@rUserId,@OutEmployeeGradeId OUTPUT
--END
--ELSE
--SET @OutEmployeeGradeId = @lEmployeeGradeId

--IF 	@lDesignationId IS NULL  AND @lDesignation != ''
--BEGIN
-- DECLARE @1GroupId  int 
-- SET @1GroupId = sCommon.fGetIntIdForOrg(1,@rOrgId) 
-- EXEC [sHrm].[pEmployeeDesignationMasterAdd] @rOrgId,@lDesignation,@lDesignation,0,@rUserId,@1GroupId,@OutDesignationId = @OutDesignationId OUTPUT
--END
--ELSE
--SET @OutDesignationId = @lDesignationId

--UPDATE #tTable SET
--		GenderId = @lGenderId ,
--		EmpTypeId = @lEmpTypeId,
--		DepartmentId = @OutDepartmentId,
--		DesignationId = @lDesignationId,
--		ContractorId = @OutContractorId,
--		BloodGroupId = @lBloodGroupId WHERE Id = @lCount
 	
	
 
EXEC [sHrm].[pEmployeeMasterAdd] @rOrgId,@lCode,@lFirstName,@lMiddleName,@lLastName,@lEmployeeTypeId,
@lDepartmentId,@lDOB,@lDOJ,@lGenderId,@lReligionId,7,0,@rUserId,@OutEmployeeId OUTPUT,
@lDesignationId,NULL,@lQualification,@lEmployeeGradeId,@lEmployeeGroupId,@lShortName
 
EXEC [sHrm].[pEmployeeCommunicationsAdd] @OutEmployeeId,@lPresentStreetOne,@lPresentStreetTwo,@lPresentStreetThree,
@lPresentCountry,@lPresentState,@lPresentCity,@lPresentZipCode,@lPresentContactNo,NULL,Null,Null,NULL,NULL,NULL,NULL,Null,
Null,NULL,NULL,NULL,NULL,NULL,NULL,NULL,@lCompanyPhoneNo,@lExtentionNo,@lCompanyEmailId,@lPersonalEmailId,@lMobileNo,@rUserId
		
		SET @lCount = @lCount - 1	
		COMMIT TRANSACTION	
END
		SELECT 1		
	END TRY
	BEGIN CATCH
	
	SELECT ERROR_MESSAGE(), ERROR_LINE()
	END CATCH
	
END
GO
PRINT N'Altering [sHrm].[pLeaveAdd]...';


GO
ALTER PROCEDURE [sHrm].[pLeaveAdd]
           
        @rId bigint,
        @rEmployeeId bigint,
        @rReportDate date,
        @rFromDate date,
        @rToDate date,
        @rLeavePeriodId tinyint,
        @rLeaveTypeId int,
        @rLeaveReson nvarchar(200),
        @rNoOfLeave decimal(5,2),
        @rBatchId int,
        @rOrgId int,
        @rUserId bigint 
        
AS
SET NOCOUNT ON

BEGIN
     
    DECLARE @1Leave int

	BEGIN TRY
	
	BEGIN TRANSACTION

	DECLARE @lNextNumber bigint
	 
    IF (@rId = 0)
     BEGIN
       
       IF(@rLeavePeriodId = 2) --For Half Leave	  	
       SELECT @1Leave = SUM(NoOfLeave) from sHrm.tLeave where EmployeeId = @rEmployeeId AND OrgId = @rOrgId AND FromDate = @rFromDate 
       ELSE
         SET @1Leave = 1
     		
	   IF NOT EXISTS(SELECT 1 FROM sHrm.tLeave WHERE EmployeeId = @rEmployeeId 
	   AND(( FromDate  BETWEEN @rFromDate AND @rToDate) OR (ToDate BETWEEN @rFromDate AND @rToDate)
	   OR (@rFromDate  BETWEEN FromDate AND ToDate) OR (@rToDate BETWEEN FromDate AND ToDate)) AND OrgId = @rOrgId AND BatchId = @rBatchId ) OR @1Leave != 1
	   BEGIN
	    EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sHrm.tLeave', 0, 1, 1,@outNextNumber = @lNextNumber output	
	    
		  INSERT INTO [sHrm].[tLeave]
           (
            [Id]
           ,[EmployeeId]
           ,[ReportDate]
           ,[FromDate]
           ,[ToDate]
           ,[LeavePeriodId]
           ,[LeaveTypeId]
           ,[LeaveReason]
           ,NoOfLeave
           ,BatchId
           ,[OrgId]           
           ,[CreatedUserId]
           ,[CreatedDateTime]
           ,[UpdatedUserId]
           ,[UpdatedDateTime]
           )
     VALUES
           (
            @lNextNumber
           ,@rEmployeeId 
           ,@rReportDate 
           ,@rFromDate 
           ,@rToDate 
           ,@rLeavePeriodId 
           ,@rLeaveTypeId 
           ,@rLeaveReson 
           ,@rNoOfLeave
           ,@rBatchId
           ,@rOrgId 
           ,@rUserId 
           ,sCommon.fGetDate()
           ,@rUserId 
           ,sCommon.fGetDate()             
           )
            END
          ELSE
            SET @lNextNumber = -101            
          END
	ELSE
	BEGIN
	SET @lNextNumber = @rId
		UPDATE sHrm.tLeave
		SET 	 
		   [EmployeeId]= @rEmployeeId 
		  ,[ReportDate]= @rReportDate 
		  ,[FromDate]= @rFromDate 
		  ,[ToDate]= @rToDate 
		  ,[LeavePeriodId]= @rLeavePeriodId 
		  ,[LeaveTypeId]= @rLeaveTypeId 
		  ,[LeaveReason]= @rLeaveReson 
		  ,NoOfLeave = @rNoOfLeave
		  ,[OrgId]= @rOrgId        
		  ,[UpdatedUserId]= @rUserId
		  ,[UpdatedDateTime]= sCommon.fGetDate()                     
		WHERE Id = @rId
	 END 
	   SELECT @lNextNumber AS Result	   
	   COMMIT TRANSACTION
	   		
	END TRY	
	BEGIN CATCH
		ROLLBACK TRANSACTION
		SELECT -1 AS RESULT
	END CATCH
	
END
GO
PRINT N'Altering [sHrm].[pQualificationMasterAdd]...';


GO
ALTER PROCEDURE [sHrm].[pQualificationMasterAdd]
	
	@rOrgGroupId smallint,
	@rCode [nvarchar](20),
	@rTitle [nvarchar](100),
	@rIsObsolete [bit],
	@rCreatedUserId [bigint]
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

	DECLARE @lNextNumber INT
	EXECUTE  sCommon.pTableRowIdGet @rOrgGroupId, 'sHrm.tQualificationMaster', 0, 1, 1,@outNextNumber = @lNextNumber output

	INSERT INTO sHrm.tQualificationMaster
		(
			Id,
			Code,
			Title,
			IsObsolete,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime,
			OrgGroupId
		)
	VALUES
		(
			@lNextNumber,
			@rCode,
			@rTitle,
			@rIsObsolete,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rOrgGroupId
		)
END
GO
PRINT N'Altering [sHrm].[pQualificationMasterGet]...';


GO
ALTER PROCEDURE [sHrm].[pQualificationMasterGet]
	
	@rOrgGroupId smallint,
	@rId [int] = 0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 SELECT 
			Id,
			Code,
			Title,
			IsObsolete,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime
	   FROM 
			sHrm.tQualificationMaster
	  WHERE 
			((Id = @rId) OR (@rId = 0))
		AND OrgGroupId = @rOrgGroupId
END
GO
PRINT N'Altering [sHrm].[pRptEmployeeAttendanceGet]...';


GO

ALTER PROCEDURE [sHrm].[pRptEmployeeAttendanceGet]
	 
	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='',
	@rEmployeeName nvarchar(200),
	@rEmployeeCode nvarchar (200),
	@rEmployeeId bigint,
	@rDepartmentId int,
	@rEmployeeGradeId int,
	@rForYear  smallint,
	@rForMonth tinyint,
	@rBatchId int,
	@rOrgId int
	--@rFromDate date,
	--@rToDate date
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
       SELECT 
			 @rBuilder1 AS Builder1,
			 @rBuilder2 AS Builder2, 
			 EM.Code AS EmployeeCode,
			 EM.EmployeeName,   
			 EM.EmployeeId,
			 EM.DepartmentName,
			 EM.EmployeeGrade,      
			 ISNULL(WD.TotalDays,ISNULL(AT.TotalWorkingDays,0)) As TotalDays,
			 ISNULL(AT.TotalWorkingDays,ISNULL(WD.WorkingDays,0)) AS WorkingDays, 
			 ISNULL(AT.LWP,0) AS LWP,
			 CONVERT(INT,(ISNULL(AT.TotalWorkingDays,0) - ISNULL(AT.LWP,0))) AS PresentDays,
			 MM.Title AS MonthName,
			 AT.ForYear As YearName
			 --L.LeaveReason,
			 --L.NoOfLeave,
			 --L.ReportDate,
			 --L.FromDate,
			 --L.ToDate,
			 --LPM.Title As LeavePeriod,
			 --LTM.Title As LeaveType,
			 --LTM.IsCarryForward,
			 --LTM.IsLWP
        FROM 
				sHrm.vEmployeeCommonDetail EM 
			LEFT JOIN sHrm.tEmployeeAttendance AT ON AT.EmployeeId=EM.EmployeeId
			LEFT JOIN sCommon.tMonthMaster MM ON MM.Id=AT.ForMonth
			LEFT JOIN sHrm.tWorkingDays WD ON  EM.EmployeeGradeId = WD.EmployeeGradeId
				AND WD.ForMonth=@rForMonth AND WD.ForYear=@rForYear AND WD.BatchId = @rBatchId
			--INNER JOIN sHrm.tLeave L ON L.EmployeeId = EM.EmployeeId
			--INNER JOIN sHrm.tLeavePeriodMaster LPM ON LPM.Id=L.LeavePeriodId
			--INNER JOIN sHrm.tLeaveTypeMaster LTM ON LTM.Id=L.LeaveTypeId
    	WHERE 
    			EM.OrgID = @rOrgId 
    		AND (AT.BatchId=@rBatchId)
    		AND ((AT.ForMonth=@rForMonth) OR (@rForMonth=0))
    		AND ((AT.ForYear=@rForYear) OR (@rForYear=0))
    		AND ((EM.EmployeeGradeId=@rEmployeeGradeId) OR (@rEmployeeGradeId=0))
    		AND ((EM.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
    		AND ((EM.Code like @rEmployeeCode) OR (@rEmployeeCode=''))
    		AND ((EM.EmployeeName like @rEmployeeName) OR (@rEmployeeName=''))
    		AND ((EM.EmployeeId=@rEmployeeId) OR (@rEmployeeId=0))
    		--AND ((L.FromDate>=@rFromDate) OR (ISNULL(@rFromDate,'')=''))
    		--AND ((L.ToDate>=@rToDate) OR (ISNULL(@rToDate,'')=''))
    		
    		ORDER BY AT.ForYear,AT.ForMonth
    		
END
GO
PRINT N'Altering [sHrm].[pRptEmployeeBirthday]...';


GO
ALTER PROCEDURE [sHrm].[pRptEmployeeBirthday]
	
	@rOrgId smallint,
	@rTypeId [int] = 0,
	@rGradeId [int] = 0,
	@rDepartmentId [int] = 0,
	@rDesignationId [int] = 0,
	@rEmployeeId [int] = 0,
	@rIsActive [bit] = 0,
	@rBirthMonth [smallint] = 0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

BEGIN

	 SELECT 
			   EM.Code AS EmployeeId,
			   ISNULL(EM.FirstName, '') + ' ' + ISNULL(EM.MiddleName, '') + ' ' + ISNULL(EM.LastName, '') AS Name,
			   EPD.DateOfBirth AS DateOfBirth,
			   DATEDIFF(YEAR, EPD.DateOfBirth, sCommon.fGetDate()) AS Age,
			   MONTH(EPD.DateOfBirth) AS MonthId,
			   Day(EPD.DateOfBirth) AS DayId,
			   RTRIM(DATENAME(MONTH, EPD.DateOfBirth)) + ' ' + LTRIM(STR(DAY(EPD.DateOfBirth))) AS BirthDayMonth
	   
	   FROM 
				sHrm.tEmployeeJobDetail EJD
		   INNER JOIN sHrm.tEmployeeMaster EM ON EJD.EmployeeId = EM.Id
		   INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EJD.EmployeeId = EPD.EmployeeId
		   INNER JOIN sHrm.tEmployeeTypeMaster ETM ON EJD.EmployeeTypeId = ETM.Id
		   INNER JOIN sHrm.tEmployeeGradeMaster EGM ON EJD.EmployeeGradeId = EGM.Id
		   INNER JOIN sHrm.tEmployeeDesignationMaster EDM ON EJD.EmployeeDesignationId = EDM.Id
		   INNER JOIN sSetup.tDepartmentMaster ODM ON EJD.OrganizationDepartmentId = ODM.Id
	   WHERE 
		   (EJD.EmployeeTypeId = @rTypeId OR @rTypeId  = 0) 
	   AND (EJD.EmployeeGradeId = @rGradeId OR @rGradeId = 0)
	   AND (EJD.OrganizationDepartmentId = @rDepartmentId OR @rDepartmentId  = 0) 
	   AND (EJD.EmployeeDesignationId = @rDesignationId OR @rDesignationId = 0)
	   AND (EM.Id = @rEmployeeId OR @rEmployeeId = 0) AND EM.IsObsolete = @rIsActive
	   AND (DATEPART(MONTH, EPD.DateOfBirth) = @rBirthMonth OR @rBirthMonth = 0)
	   AND EM.OrgID = @rOrgId
	   ORDER BY MonthId, DayId
END
GO
PRINT N'Altering [sHrm].[pRptEmployeeCommonDetail]...';


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

BEGIN

SET @rBloodGroupId = ISNULL(@rBloodGroupId,0)
SET @rMaritalStatusId = ISNULL(@rMaritalStatusId,0)

	SELECT
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
		    ECD.EmployeeId,
	        ECD.Code,	      	
			ECD.EmployeeName, 	 						
			ECD.PhoneNoCompany,
			ECD.CompanyEmail,
			ECD.ExtensionNo,		 
			ECD.DepartmentId,  			
			ECD.DepartmentName,
		    ECD.MobileNumber,
		    --ECD.OrgID,
		    ISNULL(ECD.BloodGroup,'Unknown') AS BloodGroup,
		    ISNULL((SELECT Title FROM sCommon.tAgeGroupMaster WHERE ((DATEDIFF(yy,ECD.DateOfBirth,GETDATE()) >= AgeFrom) AND ((DATEDIFF(yy,ECD.DateOfBirth,GETDATE())) <=AgeTo))),'NoRange') AS AgeGroupName,		     
		    ISNULL(CASE @rReportId
			WHEN 10081 THEN ECD.BloodGroup -- Blood Group List
			WHEN 10082 THEN ECD.BloodGroup -- Blood Group Summary 
			WHEN 10084 THEN ECD.BloodGroup  -- Blood Group Age Group Wise
			WHEN 10085 THEN ECD.GenderTitle   -- Gender Wise List
			WHEN 10086 THEN ECD.GenderTitle   -- Gender Wise Summary
			WHEN 10087 THEN ECD.GenderTitle   -- Gender Wise Age Group Wise
			--WHEN 10091 THEN ECD.MaritialStatusTitle  -- Marital Wise List
			WHEN 10092 THEN ECD.MaritialStatusTitle  -- Marital Wise Summary
			WHEN 10093 THEN ECD.MaritialStatusTitle  -- Marital Wise Age Group Wise
			WHEN 10095 THEN 'First Aid Training'
			--WHEN 10096 THEN 'Fire Training' 
			--WHEN 10098 THEN 'Disability'  
			WHEN 10097 THEN 'Employee List'
			WHEN 3 THEN 'Third'
			ELSE 'Other'
			END,'Unknown') AS Filter,
			@rIsDetail AS IsDetail,
			@rReportId AS ReportId
	FROM 
			[sHrm].[vEmployeeCommonDetail] ECD 
		
	WHERE
			((ECD.Code = @rEmployeeCode)OR @rEmployeeCode = '' )
	   AND (ECD.EmployeeTypeId = @rEmployeeTypeId OR @rEmployeeTypeId = 0)
	   AND(ECD.EmployeeStatusId=@rStatusId OR @rStatusId=0)	  
	   AND (ECD.OrganizationDepartmentId = @rDepartmentId OR @rDepartmentId = 0)
	   AND (ECD.EmployeeDesignationId = @rDesignationId OR @rDesignationId = 0)	
	   AND (ECD.EmployeeGradeId = @rGradeId OR @rGradeId = 0) 	   
	  -- AND (ECD.GenderId = @rGenderId OR @rGenderId = 0)  	    
	   AND (ECD.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)	   
	      --AND (DATEDIFF(YYYY, ECD.DateOfBirth, sCommon.fGetDate()) = @rAge OR @rAge = 0)
	   AND  ECD.OrgId = @rOrgId
	   AND (ECD.BloodGroupId = @rBloodGroupId OR @rBloodGroupId = 0)
	   AND (ECD.EmployeeGroupId = @rEmployeeGroupId OR @rEmployeeGroupId = 0)
	   AND ((DATEDIFF(yy,ECD.DateOfBirth,GETDATE()) <= @rAgeTo) OR (ISNULL(@rAgeTo,0)=0))
	   AND ((DATEDIFF(yy,ECD.DateOfBirth,GETDATE()) >= @rAgeFrom)OR (ISNULL(@rAgeFrom,0)=0))
	   AND (ECD.GenderId = @rGenderId OR @rGenderId = 0)
	   AND (ECD.MaritalStatusId = @rMaritalStatusId OR @rMaritalStatusId = 0)   
	   --AND (ECD.IsFireTraining = (CASE @rReportId WHEN 10096 THEN 1 ELSE ECD.IsFireTraining END))  
	   --AND (ECD.IsFirstAidTraining = (CASE @rReportId WHEN 10095 THEN 1 ELSE ECD.IsFirstAidTraining END)) 
	   --AND (ECD.IsDisability = (CASE @rReportId WHEN 10098 THEN 1 ELSE ECD.IsDisability END)) 
END
GO
PRINT N'Altering [sHrm].[pRptEmployeeJobDetails]...';


GO
ALTER PROCEDURE [sHrm].[pRptEmployeeJobDetails]
	
	@rOrgId smallint,
	@rTypeId [int],
	@rGradeId [int],
	@rDesignationId [int],
	@rDepartmentId [int],
	@rEmployeeId [int],
	@rReportingTo [int],
	@rIsActive [bit]
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

BEGIN

    SELECT 
			  EJD.EmployeeId AS EmployeeId,
			  vEM.Code AS EmployeeNumber,
			  vEM.EmployeeName AS EmployeeName,
			  EJD.EmployeeTypeId AS EmployeeTypeId,
			  ETM.Title AS [Type],
			  EJD.EmployeeGradeId AS GradeId,
			  EGM.Title AS Grade,
			  EJD.EmployeeDesignationId AS DesignationId,
			  EDM.Title AS Designation,
			  EJD.OrganizationDepartmentId AS DepartmentId,
			  ODM.Title AS Department,
			  vEEM.EmployeeName AS ReportingTo 
	  FROM 
			sHrm.tEmployeeJobDetail EJD
	    INNER JOIN sHrm.vExtEmployeeMaster vEM ON EJD.EmployeeId = vEM.Id  	  
		INNER JOIN sHrm.tEmployeeTypeMaster ETM	ON EJD.EmployeeTypeId = ETM.Id
		INNER JOIN sHrm.tEmployeeGradeMaster EGM ON EJD.EmployeeGradeId = EGM.Id
		INNER JOIN sHrm.tEmployeeDesignationMaster EDM ON EJD.EmployeeDesignationId = EDM.Id
		INNER JOIN sSetup.tDepartmentMaster ODM ON EJD.OrganizationDepartmentId = ODM.Id
		LEFT OUTER JOIN sHrm.vExtEmployeeMaster vEEM ON EJD.EmployeeId = vEEM.Id
	   WHERE 
			(EJD.EmployeeTypeId = @rTypeId OR @rTypeId = 0) 
	   AND (EJD.EmployeeGradeId = @rGradeId OR @rGradeId = 0)
	   AND (EJD.EmployeeDesignationId = @rDesignationId OR @rDesignationId = 0)
	   AND (EJD.EmployeeId = @rReportingTo OR @rReportingTo = 0)
	   AND (EJD.OrganizationDepartmentId = @rDepartmentId OR @rDepartmentId = 0)
	   AND (EJD.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	   AND vEM.IsObsolete = @rIsActive
	   AND EJD.OrgId = @rOrgId
END
GO
PRINT N'Altering [sHrm].[pRptEmployeeList]...';


GO
ALTER PROCEDURE [sHrm].[pRptEmployeeList]
	
	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='',
	@rReportId smallint,
	@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),
	--@rIsDetail bit = 0,
	--@rBloodGroupId [int] = 0,
	--@rMaritalStatusId [int] = 0,
	@rEmployeeCode nvarchar(50)='',
	@rEmployeeGroupId smallint,
	@rEmployeeStatusId smallint
									
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

BEGIN
 
	SELECT
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
		    ECD.EmployeeId,
	        ECD.Code,	      	
			ECD.EmployeeName, 	 								 
			ECD.DepartmentId,  			
			ECD.DepartmentName,
		    ECD.MobileNumber,
		    ECD.EmployeeDesignation
	FROM 
			[sHrm].[vEmployeeCommonDetail] ECD 
	WHERE
			((ECD.Code LIKE @rEmployeeCode)OR @rEmployeeCode = '' )
	   AND (ISNULL(ECD.EmployeeId,0) NOT IN( SELECT cast(item as bigint) FROM  sCommon.fnsplit(@rStrEmployeeId,',')) OR @rStrEmployeeId='') 
	   AND (ECD.EmployeeTypeId = @rEmployeeTypeId OR @rEmployeeTypeId = 0)
	   AND (ECD.OrganizationDepartmentId = @rDepartmentId OR @rDepartmentId = 0)
	   AND (ECD.EmployeeStatusId = @rEmployeeStatusId OR @rEmployeeStatusId = 0)
	   AND (ECD.EmployeeGroupId=@rEmployeeGroupId OR @rEmployeeGroupId=0)
	   AND (ECD.EmployeeGradeId = @rGradeId OR @rGradeId = 0)
	   AND (ECD.EmployeeDesignationId = @rDesignationId OR @rDesignationId = 0)	 	   
	   AND (ECD.GenderId = @rGenderId OR @rGenderId = 0)  	    
	   AND (ECD.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)	   
	   AND ((DATEDIFF(yy,ECD.DateOfBirth,GETDATE()) <= @rAgeTo) OR (ISNULL(@rAgeTo,0)=0))
	   AND ((DATEDIFF(yy,ECD.DateOfBirth,GETDATE()) >= @rAgeFrom)OR (ISNULL(@rAgeFrom,0)=0))
	   AND  ECD.OrgId = @rOrgId
END
GO
PRINT N'Altering [sHrm].[pRptEmployeePersonalDetails]...';


GO
ALTER PROCEDURE [sHrm].[pRptEmployeePersonalDetails]
	
	@rOrgId smallint,
	@rTypeId [int],
	@rGradeId [int],
	@rDesignationId [int],
	@rDepartmentId [int],
	@rEmployeeId [int],
	@rAge [smallint],
	@rIsActive [bit]
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

BEGIN

	SELECT 
			   EPD.UIDNumber AS UIDNumber,
			   EPD.DateOfBirth AS DateOfBirth,
			   DATEDIFF(YYYY, EPD.DateOfBirth, sCommon.fGetDate()) AS Age,
			   EPD.GenderId AS GenderId,
			   GM.Title AS Gender,
			   EPD.MaritalStatusId AS MaritalStatusId,
			   MSM.Title AS MaritalStatus,
			   EPD.IdentificationMark1 AS IdentificationMark1,
			   vEM.EmployeeName AS EmployeeName
	   FROM 
				sHrm.tEmployeePersonalDetail EPD
	   INNER JOIN sCommon.tGenderMaster GM ON EPD.GenderId = GM.Id
	   INNER JOIN sCommon.tMaritalStatusMaster MSM ON EPD.MaritalStatusId = MSM.Id
	   INNER JOIN sHrm.tEmployeeJobDetail EJD ON EPD.EmployeeId = EJD.EmployeeId
	   INNER JOIN sHrm.vExtEmployeeMaster vEM ON EJD.EmployeeId = vEM.Id  	  
	   INNER JOIN sHrm.tEmployeeTypeMaster ETM ON EJD.EmployeeTypeId = ETM.Id
	   INNER JOIN sHrm.tEmployeeGradeMaster EGM ON EJD.EmployeeGradeId = EGM.Id
	   INNER JOIN sHrm.tEmployeeDesignationMaster EDM ON EJD.EmployeeDesignationId = EDM.Id
	   INNER JOIN sSetup.tDepartmentMaster ODM ON EJD.OrganizationDepartmentId = ODM.Id
	   
	   WHERE 
				(EJD.EmployeeTypeId = @rTypeId OR @rTypeId = 0) 
		   AND (EJD.EmployeeGradeId = @rGradeId OR @rGradeId = 0)
		   AND (EJD.EmployeeDesignationId = @rDesignationId OR @rDesignationId = 0)
		   AND (DATEDIFF(YYYY, EPD.DateOfBirth, sCommon.fGetDate()) = @rAge OR @rAge = 0)
		   AND (EJD.OrganizationDepartmentId = @rDepartmentId OR @rDepartmentId = 0)
		   AND (EJD.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) AND vEM.IsObsolete = @rIsActive
		   AND EPD.OrgId = @rOrgId
END
GO
PRINT N'Altering [sHrm].[pValidateImportEmployee]...';


GO
ALTER PROCEDURE [sHrm].[pValidateImportEmployee]
    
    @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(20),     
        @lDOB nvarchar(15),        
        @lDOJ nvarchar(15),      
        @1ReturnCode int = 1,
        @1ExistEmployeeCode nvarchar(max) = '',
        @1ValidDOB nvarchar(max) = '',
        @1ValidDOJ nvarchar(max) = '',
        @1DuplicateEmployeeCode nvarchar(max) = ''
       
EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc
 
CREATE TABLE #tTable1 
 (
		Id bigint identity,
        Code nvarchar(20),
        FirstName nvarchar(100),
		EmployeeType nvarchar(100),
		EmployeeGroup nvarchar(100),
		EmployeeGrade nvarchar(100),
		Department nvarchar(100),
		Designation nvarchar(100),
        Gender nvarchar(10),
        DOB nvarchar(15),
		DOJ nvarchar(15),
		Religion nvarchar(100)
  )
  INSERT INTO #tTable1
	(
	    Code,
	    FirstName,
	    EmployeeType,
	    EmployeeGroup,
	    EmployeeGrade,
	    Department,
	    Designation,
	    Gender,
	    DOB,
	    DOJ,
	    Religion
    ) 
   SELECT
        Code,
	    FirstName,
	    EmployeeType,
	    EmployeeGroup,
	    EmployeeGrade,
	    Department,
	    Designation,
	    Gender,
	    DOB,
	    DOJ,
	    Religion   
   
   FROM OPENXML (@intDoc, '/Table/ImportEmployee', 1)
   With
   (
        Code nvarchar(50) '@Code',
        FirstName nvarchar(100) '@FirstName',
        EmployeeType nvarchar(100) '@EmployeeType',
        EmployeeGroup nvarchar(100) '@EmployeeGroup',
        EmployeeGrade nvarchar(100) '@EmployeeGrade',
        Department nvarchar(100) '@Department',
        Designation nvarchar(100) '@Designation',
		Gender nvarchar(10) '@Gender',
		DOB nvarchar(15) '@DOB',
		DOJ nvarchar(15) '@DOJ',
		Religion nvarchar(100) '@Religion'
   )   
EXEC sp_xml_removedocument @intDoc
		
SELECT @lCount =  COUNT(Id) FROM #tTable1
 
WHILE @lCount > 0 
BEGIN
  
    SELECT         
         
         @lCode = Code, 
         @lDOB=DOB,
         @lDOJ=DOJ
         
    FROM #tTable1 WHERE Id = @lCount 
     
    IF Exists ((select 1 from sHrm.tEmployeeMaster where Code = @lCode AND OrgId = @rOrgId))         
    BEGIN
		SET @1ExistEmployeeCode = @1ExistEmployeeCode + @lCode + ','
    END
	IF(ISDATE(@lDOB) = 0 AND @lDOB!='')
	BEGIN
		SET @1ValidDOB=@1ValidDOB + @lDOB+','
	END
	IF(ISDATE(@lDOJ) = 0 AND @lDOJ!='')
	BEGIN
		SET @1ValidDOJ=@1ValidDOJ + @lDOJ+','
	END
		SET @lCount = @lCount - 1	
    END	
    
	IF EXISTS(SELECT 1 fROM #tTable1 WHERE Code IS NULL OR Code='')
	BEGIN
		SELECT 'Code Should not be empty' AS EmployeeCode
	END
	ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE FirstName IS NULL OR FirstName='')
	BEGIN
		SELECT 'First Name Should not be empty' AS EmployeeCode
	END
	ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE Gender IS NULL OR Gender='')
	BEGIN
		SELECT 'Gender Should not be empty' AS EmployeeCode
	END
	ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE EmployeeType IS NULL OR EmployeeType='')
	BEGIN
		SELECT 'Employee Type Should not be empty' AS EmployeeCode
	END
	ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE EmployeeGroup IS NULL OR EmployeeGroup='')
	BEGIN
		SELECT 'Employee Group Should not be empty' AS EmployeeCode
	END
	ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE EmployeeGrade IS NULL OR EmployeeGrade='')
	BEGIN
		SELECT 'Employee Grade Should not be empty' AS EmployeeCode
	END
	ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE Department IS NULL OR Department='')
	BEGIN
		SELECT 'Department Should not be empty' AS EmployeeCode
	END
	
	ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE EmployeeType NOT IN(SELECT Title FROM sHrm.tEmployeeTypeMaster WHERE OrgId=@rOrgId))
	BEGIN
		SELECT 'Enter proper value for Employee Type' AS EmployeeCode
	END	
	ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE EmployeeGroup NOT IN(SELECT Title FROM sHrm.tEmployeeGroupMaster))
	BEGIN
		SELECT 'Enter proper value for Employee Group' AS EmployeeCode
	END	
	ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE EmployeeGrade NOT IN(SELECT Title FROM sHrm.tEmployeeGradeMaster WHERE OrgId=@rOrgId))
	BEGIN
		SELECT 'Enter proper value for Employee Grade' AS EmployeeCode
	END	
	ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE Department NOT IN(SELECT Title FROM sSetup.tDepartmentMaster WHERE OrgId=@rOrgId))
	BEGIN
		SELECT 'Enter proper value for Department' AS EmployeeCode
	END	
	ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE Designation!='' AND Designation NOT IN(SELECT Title FROM sHrm.tEmployeeDesignationMaster WHERE OrgId=@rOrgId))
	BEGIN
		SELECT 'Enter proper value for Designation' AS EmployeeCode
	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 for Religion' AS EmployeeCode
	END
	ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE Gender!='' AND Gender NOT IN(SELECT Title FROM sCommon.tGenderMaster))
	BEGIN
		SELECT 'Enter proper value for gender' AS EmployeeCode
	END
	ELSE
	BEGIN
	SELECT @1DuplicateEmployeeCode=COALESCE(@1DuplicateEmployeeCode ,'') 
	+ Code + ',' FROM #tTable1 GROUP BY Code HAVING ( COUNT(Code) > 1 )	
	IF(@1DuplicateEmployeeCode IS NOT NULL AND @1DuplicateEmployeeCode != '')
	BEGIN
		SET @1DuplicateEmployeeCode = 'Duplicate Code ' + @1DuplicateEmployeeCode
		SELECT @1DuplicateEmployeeCode AS EmployeeCode
	END
	ELSE
	IF((@1ExistEmployeeCode IS NULL OR @1ExistEmployeeCode = '') 
	AND (@1ValidDOB IS NULL OR @1ValidDOB = '') AND (@1ValidDOJ IS NULL OR @1ValidDOJ = ''))
	BEGIN
		SELECT '' AS EmployeeCode
	END
	ELSE IF (@1ExistEmployeeCode IS NOT NULL AND @1ExistEmployeeCode != '')
	BEGIN
		SET @1ExistEmployeeCode = 'Exist Code ' + @1ExistEmployeeCode
		Select @1ExistEmployeeCode AS EmployeeCode
	END
	ELSE IF (@1ValidDOB IS NOT NULL AND @1ValidDOB != '')
	BEGIN
		SET @1ValidDOB = 'Wrong DOB ' + @1ValidDOB
		Select @1ValidDOB AS EmployeeCode
	END
	ELSE IF (@1ValidDOJ IS NOT NULL AND @1ValidDOJ != '')
	BEGIN
		SET @1ValidDOJ = 'Wrong DOJ ' + @1ValidDOJ
		Select @1ValidDOJ AS EmployeeCode
	END
	END
END
GO
PRINT N'Altering [sLibrary].[pAssignOrganizationGet]...';


GO

ALTER PROCEDURE [sLibrary].[pAssignOrganizationGet]
	 
	@rLibraryId int,
	@rOrgGroupId smallint
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 
	SELECT
				OM.Id AS OrgId,
				OM.DisplayTitle AS Organization,
				CASE WHEN AO.LibraryId IS NULL THEN 'False' ELSE 'True' END AS IsObsolete
	FROM
			sSetup.tOrganizationMaster OM
		LEFT JOIN sLibrary.tAssignOrganization AO ON AO.OrgId=OM.Id AND AO.LibraryId=@rLibraryId
	WHERE
		OM.OrgGroupId=@rOrgGroupId
	Order by OM.OrderIndex
END
GO
PRINT N'Altering [sLibrary].[pBulkBookLogListGet]...';


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

	UNION

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

	UNION 

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


GO

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

	UNION ALL

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

	UNION ALL

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


GO
ALTER PROCEDURE [sLibrary].[pValidateImportBook]
    @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),             
        @1ReturnCode int = 1,
        @1ExistBookCode nvarchar(max) = '' 
       
EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc
 
CREATE TABLE #tTable1 
 (
		Id bigint identity,
        Code nvarchar(25),
        Title nvarchar(100)
  )
  INSERT INTO #tTable1
	(
	    Code,
	    Title	   
    ) 
   SELECT
        Code,
        Title	    
   
   FROM OPENXML (@intDoc, '/Table/ImportBook', 1)
   With
   (
   
        Code nvarchar(25) '@Code',   
        Title nvarchar(100) '@Title'     
   )     
   
EXEC sp_xml_removedocument @intDoc
			
IF EXISTS(SELECT 1 fROM #tTable1 WHERE Code IS NULL OR Code='')
BEGIN
	SELECT 'Code Should not be empty' AS BookCode
END
ELSE
IF EXISTS(SELECT 1 fROM #tTable1 WHERE Title IS NULL OR Title='')
BEGIN
	SELECT 'Title Should not be empty' AS BookCode
END
ELSE
BEGIN
			
SELECT @lCount =  COUNT(Id) FROM #tTable1

WHILE @lCount > 0 
BEGIN

	SELECT         
	@lCode = Code       
	 
	FROM #tTable1 WHERE Id = @lCount    

	IF Exists ((select 1 from sLibrary.tBookMaster where Code = @lCode))         
    BEGIN
		SET @1ExistBookCode = @1ExistBookCode + @lCode + ','
    END	       
   
	SET @lCount = @lCount - 1	
	END		
	Select @1ExistBookCode AS BookCode
END
			 
END
GO
PRINT N'Altering [sPayroll].[pCalculateStaticPayElement]...';


GO
ALTER PROCEDURE [sPayroll].[pCalculateStaticPayElement] 
	      
	        @rPayProcessEmployeeId bigint,
	        @rOrgId int,
	        @rSalary DECIMAL(22,6),
	        @rSourceId bigint,
	        @rDeductionAmount DECIMAL(22,6)
          
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

	BEGIN TRY
	BEGIN TRANSACTION  
	
	BEGIN
	
	DECLARE @lNextNumber BIGINT 
	DECLARE @1Basic DECIMAl(22,6) 
	DECLARE @1PfSalaryLimit DECIMAL(22,6)
	DECLARE @1PayProcesdsElementId bigint
	DECLARE @1ESISalaryLimit DECIMAL(22,6) 
    DECLARE @1Tax DECIMAL(22,6)
    DECLARE @1EmployeePfAmount Decimal(22,6)
    DECLARE @1EmployeeESIAmount Decimal(22,6)
    DECLARE @1TotalDeductionAmount DECIMAL(22,6)
    DECLARE @1EmployeePfPercent DECIMAL(22,2)
    DECLARE @1EmployerPfPercent DECIMAL(22,2)
    DECLARE @1EmployeeESIPercent DECIMAL(22,2)
    DECLARE @1EmployerESIPercent DECIMAL(22,2)
      
     SET @1Tax = 0.0
     SET @1EmployeePfAmount = 0.0
     SET @1EmployeeESIAmount = 0.0
	 SET @1Basic = 0.0
	 SET @1PfSalaryLimit = 0.0
	 SET @1EmployeePfPercent = 0.0
    SET @1EmployerPfPercent = 0.0
    SET @1EmployeeESIPercent = 0.0
    SET @1EmployerESIPercent = 0.0
	
	 --For Professional Tax
	 IF EXISTS (SELECT 1 FROM  sPayroll.tPayProcessElement Where PayProcessEmployeeId = @rPayProcessEmployeeId AND PayElementId = sCommon.fGetIntIdForOrg(57,@rOrgId))     	    
		BEGIN	
		  --      Select * from sPayroll.tProfessionalTaxRange
		        
		  --      SELECT  TOP 1  Tax  FROM sPayroll.tProfessionalTaxRange 
				--where Salary < @rSalary Order By Salary Desc
		        
				SELECT  TOP 1  @1Tax = Tax  FROM sPayroll.tProfessionalTaxRange 
				where Salary < @rSalary Order By Salary Desc
		        -- Professional Tax 
				UPDATE sPayroll.tPayProcessElement  
				SET AMOUNT = @1Tax
				WHERE PayProcessEmployeeId = @rPayProcessEmployeeId AND PayElementId = sCommon.fGetIntIdForOrg(57,@rOrgId)	 			 
		END	
	
	 --For PfElement
     IF EXISTS(SELECT 1 FROM  sPayroll.tPayProcessElement Where PayProcessEmployeeId = @rPayProcessEmployeeId AND PayElementId = sCommon.fGetIntIdForOrg(56,@rOrgId))
	  BEGIN
			  SET @1Basic = 0.0	          
	          SET @1PayProcesdsElementId = 0.0
	      
	      SELECT @1Basic = ISNULL(Amount,0) from sPayroll.tPayProcessElement Where PayProcessEmployeeId = @rPayProcessEmployeeId AND PayElementId = sCommon.fGetIntIdForOrg(1,@rOrgId)
	      
		  SELECT @1Basic =  Amount FROM sPayroll.tPaySetup Where SourceId = @rSourceId AND PayElementId = sCommon.fGetIntIdForOrg(1,@rOrgId)  --Basic Pay Element
	      SELECT @1PfSalaryLimit = PfSalaryLimit,@1EmployeePfPercent=EmployeePfPercent,@1EmployerPfPercent=EmployerPfPercent FROM  sPayroll.tPfSetup Where OrgId = @rOrgId 
	      Select @1PayProcesdsElementId = Id  FROM  sPayroll.tPayProcessElement Where PayProcessEmployeeId = @rPayProcessEmployeeId AND PayElementId = sCommon.fGetIntIdForOrg(56,@rOrgId)
	        
	       
	       IF(@1Basic > @1PfSalaryLimit)
	          BEGIN
	           SET @1EmployeePfAmount = @1Basic*@1EmployeePfPercent/100 
	             INSERT INTO  [sPayroll].[tPfProcess]
							   (
							    [PayProcessElementId]
							   ,[EmployeePfAmount]
							   ,[EmployerPfAmount]
							   ,[EmployerFpsAmount]
							   ,[EligibleFpsAmount]
							   )
							   Values
							   (
							     @1PayProcesdsElementId,
							     @1Basic*ISNULL(@1EmployeePfPercent,0)/100,
							     @1Basic*ISNULL(@1EmployerPfPercent,0)/100, --OR @1Basic*3.67/100
							     0.0,
							     0.0	    
							    ) 
							    
				 UPDATE sPayroll.tPayProcessElement 
				 SET Amount = @1EmployeePfAmount WHERE  PayProcessEmployeeId = @rPayProcessEmployeeId AND PayElementId = sCommon.fGetIntIdForOrg(56,@rOrgId) 			    
				
	          END   
	  END
	  
	  --FOR Esi Element
	 IF EXISTS(SELECT 1 FROM  sPayroll.tPayProcessElement Where PayProcessEmployeeId = @rPayProcessEmployeeId AND PayElementId = sCommon.fGetIntIdForOrg(55,@rOrgId))
	  BEGIN
			   SET @1PayProcesdsElementId = 0.0  
			   SET @1ESISalaryLimit = 0.0			
			   SELECT  @1ESISalaryLimit = EsiSalaryLimit,@1EmployeeESIPercent=EmployeeEsiPercent,@1EmployerESIPercent = EmployerEsiPercent FROM sPayroll.tEsiSetup Where OrgId = @rOrgId
			   SELECT @1PayProcesdsElementId = Id FROM  sPayroll.tPayProcessElement Where PayProcessEmployeeId = @rPayProcessEmployeeId AND PayElementId = sCommon.fGetIntIdForOrg(55,@rOrgId)
			    
		   IF(@1ESISalaryLimit > @rSalary)					   
			  BEGIN
			  SET @1EmployeeESIAmount = @rSalary * @1EmployeeESIPercent/100	
			   INSERT INTO [sPayroll].[tEsiProcess]
						   (
							    [PayProcessElementId]
							   ,[EmployeeEsiAmount]
							   ,[EmployerEsiAmount]
						   )
						   Values
						   (
						       @1PayProcesdsElementId
						      ,@rSalary * @1EmployeeESIPercent/100
						      ,@rSalary * @1EmployerESIPercent/100
						   )
						   
					 UPDATE sPayroll.tPayProcessElement 
				 SET Amount = @1EmployeeESIAmount WHERE  PayProcessEmployeeId = @rPayProcessEmployeeId AND PayElementId = sCommon.fGetIntIdForOrg(55,@rOrgId)  
			   END	 
	  END  
	  
	  SET @1TotalDeductionAmount = @rDeductionAmount + @1Tax + @1EmployeePfAmount + @1EmployeeESIAmount
	  
	  UPDATE sPayroll.tPayProcessEmployee  
	  SET  
	      TotalEarning = ROUND(@rSalary,0),
	      TotalDeduction = ROUND(@1TotalDeductionAmount,0),	       
		  NetAmount = ROUND(@rSalary,0) - ROUND(@1TotalDeductionAmount,0)  
	  WHERE ID =  @rPayProcessEmployeeId   
	    
    END
	--SELECT 1 AS Result	
	COMMIT TRANSACTION
	END TRY
	BEGIN CATCH
	ROLLBACK TRANSACTION
	RAISERROR ('Error In Calculate Static Pay Element', -- Message text.
               16, -- Severity.
               1 -- State.
               );
	--SELECT -1 AS RESULT
	END CATCH	
END
GO
PRINT N'Altering [sPayroll].[pEmployeePayElementMasterRemove]...';


GO
ALTER PROCEDURE [sPayroll].[pEmployeePayElementMasterRemove]
 (
	@rId int
 )
AS
SET NOCOUNT ON	
	DECLARE @1Result Int
	DECLARE @rPayElementId int
		
	BEGIN TRY	
    BEGIN TRANSACTION
			BEGIN	 
			
			    SET @rPayElementId = @rId
				 --SET @1Result = 1
				 
				 IF EXISTS(Select 1 FROM sPayroll.tPayProcessElement Where PayElementId = @rPayElementId)
				 BEGIN
				   SET @1Result = -101				   
				 END
				 ELSE IF EXISTS(Select 1  FROM sPayroll.tPaySetup  Where PayElementId = @rPayElementId)
				 BEGIN
				   SET @1Result = -101				   
				 END
				 ELSE IF EXISTS(Select 1  FROM sPayroll.tPaySetupDependent Where DependentPayElementId = @rPayElementId)
				 BEGIN
				   SET @1Result = -101				   
				 END
				  
				 ELSE
				   BEGIN
				      DELETE FROM sPayroll.tPayElement Where Id = @rPayElementId
				      SET @1Result = 1
				   END
				  
				 	  
			SELECT @1Result AS Result
				 	  
			END
	  COMMIT TRANSACTION
      END TRY
         
      BEGIN CATCH
	  ROLLBACK TRANSACTION
	  SELECT -1 AS RESULT
	  END CATCH
GO
PRINT N'Altering [sPayroll].[pGetPayProcessEmployeeDetail]...';


GO
ALTER PROCEDURE [sPayroll].[pGetPayProcessEmployeeDetail]
	
	 @rId int,
	 @rOrgId int,
	 @rEmployeeCode nvarchar(200),
	 @rEmployeeName nvarchar(200),
	 @rDepartmentId int,
	 @rEmployeeGradeId int,
	 @rForMonth int,
	 @rForYear int,
	 @rBatchId int,
	 @rAccountingYearId int
	 
	 
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

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

	SELECT  
		PP.ID As PayProcessId,
		PPE.ID AS PayProcessEmployeeId,
		PP.SalaryMonth,
		PP.SalaryYear,
		PPE.EmployeeId,
		EM.EmployeeName,
		EM.Code AS EmployeeCode,
		EM.EmployeeGradeId,
		EM.DepartmentId,
		EM.DepartmentName,
		PPE.TotalEarning,
		PPE.TotalDeduction,
		PPE.NetAmount,
	   (SELECT  t1.MonthTitle FROM (SELECT MonthTitle,MonthNumber FROM [sSetup].[fMonthYearForBatchGet] (@rBatchId))  AS T1
		WHERE MonthNumber = SalaryMonth) AS MonthTitle
		

	FROM sPayroll.tPayProcess PP INNER JOIN  
	sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId = PP.ID INNER JOIN
	sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = PPE.EmployeeId 

where 
      --(EM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) AND 
      OrgID = @rOrgId 
      AND ((EM.Code Like   @rEmployeeCode  ) OR (@rEmployeeCode = ''))
	  AND ((EM.FirstName Like '%' + @rEmployeeName  + '%') OR (@rEmployeeName = ''))
	  AND (EM.DepartmentId = @rDepartmentId OR @rDepartmentId = 0)
	  AND (EM.EmployeeGradeId = @rEmployeeGradeId OR @rEmployeeGradeId = 0) 
	  AND (PP.SalaryMonth = @rForMonth OR @rForMonth = 0)
	  AND (SalaryYear = @rForYear OR @rForYear = 0)
	  AND  PP.AccountingYearId = @rAccountingYearId
	  AND PP.BatchId = @rBatchId
	  
	  Order By EM.EmployeeName
END
GO
PRINT N'Altering [sPayroll].[pPayElementGet]...';


GO
ALTER PROCEDURE [sPayroll].[pPayElementGet]
	 @rId int,
	 @rCode nvarchar(20),
	 @rTitle nvarchar(100),
	 @rPayElementTypeId int,
	 @rPaidCategoryId int,
	 @rOrgId int,
	 @rIsWildCardSearch bit 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 		

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

 SELECT PE.Id
      ,PE.[Code]
      ,PE.[Title]
      ,[PayElementTypeId]
      ,[PaidCategoryId]
      ,ISNULL([IsLwp],0) AS IsLwp 
      ,ISNULL([IsEmployeeSpecific],0) As IsEmployeeSpecific
      ,ISNULL([IsDepend],0) As IsDepend
      ,ISNULL([IsAvailDuringProbation],0) AS IsAvailDuringProbation
      ,ISNULL([IsIncludeInPaySlip],0) AS IsIncludeInPaySlip
      ,[SortOrder]
      ,[IsObsolete]
      ,PET.Title AS PayElementType
      ,PC.Title AS PaidCategory     
     
  FROM  sPayroll.tPayElement PE INNER JOIN sPayroll.tPayElementType PET ON PET.Id = PE.PayElementTypeId
  INNER JOIN sPayroll.tPaidCategory PC ON PC.Id = PE.PaidCategoryId

Where  
     (PE.Id = @rId OR @rId = 0)
     AND (PE.Code Like @rCode OR ISNULL(@rCode,'') = '')
     AND (PE.Title Like @rTitle OR ISNULL(@rTitle,'') = '')
     AND (PayElementTypeId = @rPayElementTypeId OR @rPayElementTypeId = 0)
     AND (PaidCategoryId = @rPaidCategoryId OR @rPaidCategoryId = 0) 
     AND OrgId = @rOrgId 
     --AND IsObsolete = 0
		
END
GO
PRINT N'Altering [sPayroll].[pPayProcessEmployeeAdd]...';


GO
ALTER PROCEDURE [sPayroll].[pPayProcessEmployeeAdd] 
	      	        
            @rPayProcessId int            
           ,@rOrgId int
          
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 @1GradeId 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)
	
  
  --IF (@rId = 0)
   
    CREATE TABLE #tmpEmpDetail
	(
		Id INT IDENTITY (1, 1),
		EmployeeId  bigint,
		GradeId int
	)
	 
	INSERT INTO #tmpEmpDetail
    Select EmployeeId,EMployeeGradeId FROM sHrm.vEmployeeCommonDetail Where OrgId = @rOrgId 
    --AND EmployeeId = 1001000000039
   
   Select @1Count = COUNT(*) FROM #tmpEmpDetail 
       
   WHILE @1Count > 0 
    BEGIN	 
			--SELECT @1TotalEarningAmount
			--END	  
			EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sPayroll.tPayProcessEmployee', 0, 1, 1,@outNextNumber = @lNextNumber output	
		    SELECT @1EmployeeId = EmployeeId,@1GradeId = GradeId FROM #tmpEmpDetail WHERE ID = @1Count
					  
					  
		   INSERT INTO  [sPayroll].[tPayProcessEmployee]
				   (
				    [ID]
				   ,[PayProcessId]
				   ,[EmployeeId]
				   ,[GradeId]
				   ,TotalEarning
				   ,TotalDeduction
				   ,NetAmount
				   )
			 VALUES
				   (
				    @lNextNumber
				   ,@rPayProcessId
				   ,@1EmployeeId 
				   ,@1GradeId
				   ,0.0
				   ,0.0
				   ,0.0
				   )
				   
		      
	     -- 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  
		)  
		   
		   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 FROM 
		     (		     
		     SELECT PS.ID,SourceId,3016 AS SourceTypeId ,PayElementId,Amount,Percentage,ISNULL(IsDepend,0) AS IsDepend,PayElementTypeId,ProcessOrder FROM sPayroll.tPaySetup  PS INNER JOIN sPayroll.tPayElement  PE ON PE.ID = PS.PayElementId
			 WHERE SourceId = @1EmployeeId AND SourceTypeId = 3016   
		 
		 --ELSE 
		     UNION ALL
		      
		     --INSERT INTO #tmpPaysetupElement
		     SELECT PS.ID,SourceId,483 AS SourceTypeId,PayElementId,Amount,Percentage,IsDepend,PayElementTypeId,ProcessOrder FROM sPayroll.tPaySetup  PS  INNER JOIN sPayroll.tPayElement  PE ON PE.ID = PS.PayElementId
			 WHERE SourceId = @1GradeId AND SourceTypeId = 483 
			 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 = 3016)  			 
			 
		     ) 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
			  
			    SELECT @1PaySetupId = PaySetupId,@1SourceId = SourceId,@1PayElementId = PayElementId,@1Result = Amount,
			    @1Percentage = Percentage,@1IsDepend = IsDepend,@1PayElementTypeId=PayElementTypeId FROM #tmpPaysetupElement WHERE Id = @1PayElementCount
			      
			    SELECT @1IsLwp = IsLwp FROM sPayroll.tPayElement Where Id = @1PayElementId AND OrgId = @rOrgId
			       
			       IF(@1IsLwp = 1) 			     
			            SELECT @1LWPDeduction = [sPayroll].[fCalculateLWP] (@1EmployeeId, @rPayProcessId,ISNULL(@1Result,0))			      
			               
			     IF(@1IsDepend = 1)
			          BEGIN 
			               EXECUTE [sPayroll].[pCalculatePayrollAmount]  @1PaySetupId,@1Percentage,@1SourceId,@rOrgId,@1EmployeeId,@lNextNumber,@1Result OUTPUT			               
			          END 
			          
			    SET @1Result =  ROUND(ISNULL(@1Result,0.0) -  ISNULL(@1LWPDeduction,0.00),0)	       
			      
			    EXECUTE sCommon.pTableRowIdGet @rOrgId, '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,@rOrgId,@1TotalEarningAmount,@1SourceId,@1TotalDeductionAmount		 
	    
			--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].[pRptEmployeePaybillDetail]...';


GO


ALTER PROCEDURE [sPayroll].[pRptEmployeePaybillDetail]
	
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rOrgId int,
	 @rEmployeeId bigint,
	 @rEmployeeCode nvarchar(200),
	 @rEmployeeName nvarchar(200),
	 @rDepartmentId int,
	 @rEmployeeGradeId int,
	 @rForMonth int,
	 @rForYear int,
	 @rBatchId int,
	 @rAccountingYearId int
	 
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

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

	SELECT 
		EM.EmployeeId, 
		PP.ID As PayProcessId,
		PPE.ID AS PayProcessEmployeeId,
		PP.SalaryMonth,
		PP.SalaryYear,
		EM.EmployeeName,
		EM.Code AS EmployeeCode,
		PPE.TotalEarning,
		PPE.TotalDeduction,
		PPE.NetAmount,
		ISNULL(ESO.BankName,'') AS BankName,
		ISNULL(ESO.AccountNumber,'') AS AccountNumber,
		MM.Title AS MonthName		
		
	FROM sPayroll.tPayProcess PP 
	INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId=PP.ID
	INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = PPE.EmployeeId 
	LEFT JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.EmployeeId=PPE.EmployeeId	
	INNER JOIN sCommon.tMonthMaster MM ON MM.Id=PP.SalaryMonth	

where 
      (PPE.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) AND 
      EM.OrgID = @rOrgId 
      AND PP.BatchId=@rBatchId
      --AND PP.AccountingYearId=@rAccountingYearId
      AND ((EM.Code Like '%' +  @rEmployeeCode + '%' ) OR (@rEmployeeCode = ''))
	  AND ((EM.EmployeeName Like '%' + @rEmployeeName  + '%') OR (@rEmployeeName = ''))
	  AND (EM.DepartmentId = @rDepartmentId OR @rDepartmentId = 0)
	  AND (EM.EmployeeGradeId = @rEmployeeGradeId OR @rEmployeeGradeId = 0) 
	  AND (PP.SalaryMonth = @rForMonth OR @rForMonth = 0)
	  AND (PP.SalaryYear = @rForYear OR @rForYear = 0) 
	
END
GO
PRINT N'Altering [sPayroll].[pRptEmployeeSalaryDetail]...';


GO

ALTER PROCEDURE [sPayroll].[pRptEmployeeSalaryDetail]
	
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rOrgId int,
	 @rEmployeeId bigint,
	 @rEmployeeCode nvarchar(200),
	 @rEmployeeName nvarchar(200),
	 @rDepartmentId int,
	 @rEmployeeGradeId int,
	 @rForMonth int,
	 @rForYear int,
	 @rBatchId int,
	 @rAccountingYearId int
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

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

	SELECT 
		EM.EmployeeId, 
		PP.ID As PayProcessId,
		PPE.ID AS PayProcessEmployeeId,
		PP.SalaryMonth,
		PP.SalaryYear,
		EM.EmployeeName,
		EM.Code AS EmployeeCode,
		EM.EmployeeDesignation,
		EM.EmployeeGrade,
		ESO.EPFNumber,
		ESO.PanNumber,
		PPE.TotalEarning,		
		PPE.TotalDeduction,
		PPE.NetAmount,
		(CASE WHEN PayElementId = sCommon.fGetIntIdForOrg(1,@rOrgId) then PPE.TotalEarning else 0 END) AS TotalEarningTotal,
		(CASE WHEN PayElementId = sCommon.fGetIntIdForOrg(1,@rOrgId) then PPE.TotalDeduction else 0 END) AS TotalDeductionTotal,
		(CASE WHEN PayElementId = sCommon.fGetIntIdForOrg(1,@rOrgId) 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,
		EA.TotalWorkingDays,
		EA.LWP
				
		
		

	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 sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
	INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID 
	LEFT JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.EmployeeId=PPE.EmployeeId	
	INNER JOIN sHrm.tEmployeeAttendance EA ON EA.EmployeeId=EM.EmployeeId AND EA.ForMonth = PP.SalaryMonth AND EA.ForYear = PP.SalaryYear
	INNER JOIN sCommon.tMonthMaster MM ON MM.Id=PP.SalaryMonth
	

where 
      (EM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) AND 
      EM.OrgID = @rOrgId 
      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 (EM.EmployeeGradeId = @rEmployeeGradeId OR @rEmployeeGradeId = 0) 
	  AND (PP.SalaryMonth = @rForMonth OR @rForMonth = 0)
	  AND (PP.SalaryYear = @rForYear OR @rForYear = 0)
	  AND (PP.BatchId=@rBatchId)
	  --AND (PP.AccountingYearId=@rAccountingYearId)
	  
	 --GROUP BY PPE.EmployeeId,PP.ID,PPE.ID,PP.SalaryMonth,PP.SalaryYear,EM.EmployeeName,EM.Code,EM.EmployeeGrade,EM.DepartmentName,
		--EM.EmployeeDesignation,PPE.TotalEarning,PPE.TotalDeduction,PPE.NetAmount,PE.Amount,P.Title,P.PayElementTypeId,
		--ESO.BankName,
		--ESO.AccountNumber,
		--ESO.EPFNumber,
		--ESO.PanNumber,
		--EA.TotalWorkingDays,EA.LWP
END
GO
PRINT N'Altering [sPayroll].[pRptPayElementwiseSummaryDetail]...';


GO



ALTER PROCEDURE [sPayroll].[pRptPayElementwiseSummaryDetail]
	
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rOrgId int,
	 @rPayElementId int,
	 @rEmployeeId bigint,
	 @rEmployeeCode nvarchar(200),
	 @rEmployeeName nvarchar(200),
	 @rDepartmentId int,
	 @rEmployeeGradeId int,
	 @rForMonth int,
	 @rForYear int,
	 @rBatchId int,
	 @rAccountingYearId int
	 
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

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

	SELECT 
	
	PE.Amount,
	P.Title AS PayElement,
	EM.EmployeeName,
	EM.Code,
	EM.EmployeeDesignation,
	PP.SalaryMonth,
	PP.SalaryYear,
	MM.Title AS MonthName
		
		

	 from sPayroll.tPayProcessEmployee PPE
			  INNER JOIN sPayroll.tPayProcess PP ON PPE.PayProcessId=PP.ID
			  INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
			  INNER JOIN sPayroll.tPayElement P ON P.ID=PE.PayElementId
			  INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId=PPE.EmployeeId
			  INNER JOIN sCommon.tMonthMaster MM ON MM.Id=PP.SalaryMonth
	

where 
      (PPE.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) AND 
      EM.OrgID = @rOrgId 
      AND PP.BatchId=@rBatchId
      ----AND PP.AccountingYearId=@rAccountingYearId
      AND ((P.ID=@rPayElementId) OR (@rPayElementId=0))
      AND ((EM.Code Like  @rEmployeeCode) OR (@rEmployeeCode = ''))
	  AND ((EM.EmployeeName Like @rEmployeeName ) OR (@rEmployeeName = ''))
	  AND (EM.DepartmentId = @rDepartmentId OR @rDepartmentId = 0)
	  AND (EM.EmployeeGradeId = @rEmployeeGradeId OR @rEmployeeGradeId = 0) 
	  AND (PP.SalaryMonth = @rForMonth OR @rForMonth = 0)
	  AND (PP.SalaryYear = @rForYear OR @rForYear = 0)
	  
	
END
GO
PRINT N'Altering [sSecurity].[pLoggedInUserGet]...';


GO
ALTER PROCEDURE [sSecurity].[pLoggedInUserGet]
	@rOrgId [smallint],
	@rUserId [bigint],
	@rStoreLocationId [int],
	@rBatchId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
DECLARE @lOrgGroupId int
DECLARE @lBatchId int
DECLARE @lBatchTitle nvarchar(100)
DECLARE @lDisplayTitle nvarchar(100)
DECLARE @lAffiliationId smallint
DECLARE @lOrgGroupBatchId int
DECLARE	@lFromDate date
DECLARE	@lToDate date
--DECLARE @lLocationId int
--DECLARE @lLocationName nvarchar(100)

--SELECT @lLocationId = LocationId, @lLocationName = LocationName FROM sSecurity.vExtUserLocation
--WHERE StoreLocationId = @rStoreLocationId AND UserId = @rUserId 
	SELECT
		@lOrgGroupId=OM.OrgGroupId,
		@lBatchId=BM.Id,
		@lBatchTitle=BM.Title,
		@lDisplayTitle=OM.DisplayTitle,
		@lAffiliationId=OM.AffiliationId,
		@lOrgGroupBatchId=BM.OrgGroupBatchId,
		@lFromDate=BM.FromDate,
		@lToDate=BM.ToDate
	FROM sSetup.tOrganizationMaster OM
		INNER JOIN sSetup.tBatchMaster BM ON BM.OrgId=OM.Id AND BM.Id = @rBatchId AND BM.OrgId=@rOrgId
		
	SELECT 
		@rOrgId AS OrgId,
		@lOrgGroupId AS OrgGroupId,
		@lBatchId AS BatchId,
		@lBatchTitle AS BatchTitle,
		@lDisplayTitle AS OrgDisplayTitle,
		UserTbl.Id AS UserId, 		
		UserTbl.LoginTitle,
		UserTbl.DisplayTitle,		 
		--UserTbl.EmployeeId AS EmployeeId, 
		UserTbl.SourceId AS UserSourceId,
		UserTbl.SourceTypeId AS UserSourceTypeId,
		CASE WHEN UserTbl.SourceTypeId = 95 THEN
			(EM.FirstName + ISNULL(' ' + EM.MiddleName, '') + ' ' + EM.LastName)
		ELSE
			SA.Name
		END   AS EmployeeFullName,
		CASE WHEN UserTbl.SourceTypeId = 95 THEN
			(EM.FirstName + ISNULL(' ' + EM.MiddleName, '') + ' ' + EM.LastName)
		ELSE
			SA.Name
		END   AS UserFullName,
		--CASE WHEN UserTbl.SourceTypeId = 95 THEN
		--	EM.EmployeeJobTitleId
		--ELSE
		--	0
		--END AS EmployeeJobTitleId,
		ScreenTbl.Page AS HomePageUrl,
		MenuTbl.Id AS MenuId,
		UserPrefTbl.FavoriteScreenID AS ScreenID,
		UserTbl.SessionId AS SessionId,
		UR.RoleId,
		CASE WHEN UserTbl.SourceTypeId = 95 THEN
			0
		ELSE
			SA.RollNo
		END AS UserNo,
		CASE WHEN UserTbl.SourceTypeId = 95 THEN
			EM.DepartmentName
		ELSE
			SA.ClassName+' - '+SA.DivisionName
		END AS UserDepartment,
		CASE WHEN UserTbl.SourceTypeId = 95 THEN
			EM.Code
		ELSE
			SA.Code
		END AS UserIdNo,
		CASE WHEN UserTbl.SourceTypeId = 95 THEN
			EI.EmployeePhoto
		ELSE
			SI.StudentPhoto
		END AS UserPhoto,
		CASE WHEN UserTbl.SourceTypeId = 95 THEN
			EM.GenderId
		ELSE
			ISNULL(SO.GenderId,1)
		END AS GenderId,
		--0 AS AccountingYearId,
	 --   '' AS AccountingYearCode,
		--ISNULL((select Id from sAccounting.tAccountingYearMaster WHERE OrgId = @rOrgId AND IsActive = 1),0) AS AccountingYearId,
		--ISNULL((select Code from sAccounting.tAccountingYearMaster WHERE OrgId = @rOrgId AND IsActive = 1),0) AS AccountingYearCode,
		@lAffiliationId AS AffiliationId,
		@lOrgGroupBatchId AS OrgGroupBatchId,
		@lFromDate AS BatchFromDate,
		@lToDate AS BatchToDate
		
		
		--@lLocationId AS LocationId,
		--@lLocationName AS LocationName	
					
	FROM sSecurity.tUser UserTbl
		INNER JOIN sSecurity.tUserRole UR
			ON UR.UserId=UserTbl.Id AND UR.IsObsolete=0 AND UR.IsPrimary=1 AND UR.UserId=@rUserId
		--INNER JOIN sSetup.tOrganizationMaster OM
		--	ON OM.Id=UserTbl.OrgId
		--INNER JOIN sSetup.tBatchMaster BM
		--	ON BM.OrgId=OM.Id 
		--	AND BM.Id = @rBatchId -- add to remove duplicate
		LEFT JOIN sHrm.vExtEmployeeMaster EM
			ON EM.Id = UserTbl.SourceId 
			--AND UserTbl.OrgId = EM.OrgId 
			AND UserTbl.SourceTypeId = 95	
		LEFT JOIN sHrm.tEmployeeImages EI
			ON EI.EmployeeId=EM.Id
		LEFT JOIN sStudent.vStudentAcademic SA
			ON SA.StudentId = UserTbl.SourceId 
			--AND UserTbl.OrgId = SA.OrgId 
			AND SA.BatchId=@rBatchId 
			AND UserTbl.SourceTypeId = 2003	
		LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=SA.StudentId
		LEFT JOIN sStudent.tStudentImages SI
			ON SI.StudentId=SA.StudentId
		LEFT OUTER JOIN sSecurity.tUserPreference UserPrefTbl
			ON UserTbl.Id = UserPrefTbl.UserId 
			--AND  UserTbl.OrgId = UserPrefTbl.OrgId
		LEFT OUTER JOIN sSecurity.tScreen ScreenTbl
			ON UserPrefTbl.FavoriteScreenId = ScreenTbl.Id			
		LEFT OUTER JOIN sSecurity.tMenu MenuTbl
			ON MenuTbl.ScreenId =  ScreenTbl.Id	
	WHERE 
		UserTbl.Id = @rUserId 
		--AND
		--UserTbl.OrgId = @rOrgId
		AND UserTbl.IsObsolete=0

END
GO
PRINT N'Altering [sSecurity].[pPendingEmployeePasswordGet]...';


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

BEGIN
	SELECT 
			ISNULL(U.Id,0) AS Id,
			EC.EmployeeId,
			EC.Code,
			EC.EmployeeName AS Name,
			ISNULL(EC.MobileNumber,'') AS MobileNo,
			ISNULL(EC.CompanyEmail,'') AS EmailId,
			U.LoginTitle AS UserName,
			U.LoginPassword
	FROM 
			sHrm.vEmployeeCommunication EC
	LEFT JOIN sSecurity.tUser U ON U.SourceId=EC.EmployeeId AND U.SourceTypeId=95
	WHERE 
			((EC.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		AND	(EC.OrgId = @rOrgId)
		AND (EC.IsObsolete=0)
		AND (U.LoginPassWord is Null AND @rIsPendingLogin=1)
		OR (U.LoginPassWord is NOT Null AND @rIsCreatedLogin=1)
END
GO
PRINT N'Altering [sSecurity].[pPendingLoginStudentdGet]...';


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

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


GO
ALTER PROCEDURE [sSecurity].[pUserByLoginUserNameGet]
	@rOrgId [smallint],
	@rDisplayTitle [nvarchar](100),
	@rLoginTitle [nvarchar](20),
	@rRoleId int,
	@rSourceTypeId smallint,
	@rSourceCode nvarchar(20),
	@rSourcename nvarchar(100),
	@rCondition [tinyint],
	@rIsCommon bit,
	@rOrgGroupId smallint
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

SET @rDisplayTitle = sCommon.fSearchStringGet(@rDisplayTitle)
SET @rLoginTitle = sCommon.fSearchStringGet(@rLoginTitle) 
SET @rSourceCode= sCommon.fSearchStringGet(@rSourceCode)
SET @rSourceName= sCommon.fSearchStringGet(@rSourcename)
       SELECT 
            Users.Id,
			Users.DisplayTitle,
			Users.LoginTitle,
			--Users.EmployeeId,
			Users.SourceId AS UserSourceId,
			Users.SourceTypeId AS UserSourceTypeId,
			Users.IsObsolete,
			CASE WHEN Users.SourceTypeId = 95 THEN
			Emp.Code
			ELSE
				SN.Code
			END   AS EmployeeCode,
			CASE WHEN Users.SourceTypeId = 95 THEN
				(Emp.FirstName +  ' ' + Emp.LastName)
			ELSE
				SN.Name
			END   AS UserFullName,
			--CASE WHEN Users.SourceTypeId = 95 THEN
			--	Emp.EmployeeJobTitleId
			--ELSE
			--	0
			--END AS EmployeeJobTitleId,
			Uprof.ElectronicSignature AS ElectronicSignature,
            CASE WHEN Users.IsObsolete = 1 THEN 'Y' ELSE 'N' END AS ObsoleteDisplay,
            UR.RoleId,
            R.Title AS RoleName,
            Users.OrgId,
            Users.ValidUpto AS ValidUptoDate                     
       FROM sSecurity.tUser Users
			-- Commented For Employee Migration
			--INNER JOIN sCommon.tEmployeeMaster Emp
			-- End of comment for Employee Migration
			-- Added for Employee Migration
			LEFT JOIN sHrm.vExtEmployeeMaster Emp
			-- End of addition for Employee Migration
			ON Emp.Id = Users.SourceId AND Users.SourceTypeId = @rSourceTypeId
			AND((Emp.Code like @rSourceCode) OR (ISNULL(@rSourceCode,'') = ''))
			AND((Emp.EmployeeName like @rSourceName) OR (ISNULL(@rSourceName,'') = ''))
			LEFT JOIN sStudent.vStudentName SN
			ON SN.StudentId = Users.SourceId AND Users.SourceTypeId = @rSourceTypeId		
			AND((SN.Code like @rSourceCode) OR (ISNULL(@rSourceCode,'') = ''))
			AND((SN.Name like @rSourceName) OR (ISNULL(@rSourceName,'') = ''))
			LEFT JOIN sSecurity.tUserProfile Uprof
			ON Users.Id = Uprof.UserId
			INNER JOIN sSecurity.tUserRole UR ON UR.UserId=Users.Id AND UR.IsObsolete=0 AND UR.IsPrimary=1 AND (UR.RoleId=@rRoleId OR @rRoleId=0)
			INNER JOIN sSecurity.tRole R ON R.Id=UR.RoleId AND (R.OrgGroupId=@rOrgGroupId)
			
        WHERE ((Users.OrgId = @rOrgId) OR (@rOrgId=0))
	      AND ((Users.SourceTypeId = @rSourceTypeId) OR (@rSourceTypeId=0))
		  AND ((@rIsCommon=0 AND Users.SourceId Is Not Null) OR (@rIsCommon=1 AND Users.SourceId Is Null))
		  AND ((DisplayTitle LIKE @rDisplayTitle) OR (@rDisplayTitle = ''))
          AND ((LoginTitle LIKE @rLoginTitle) OR (@rLoginTitle = ''))   
          AND (ISNULL(Users.IsCommon,0)=@rIsCommon)                        
END	
--'sSecurity.tUser'
--'sCommon.tEmployeeMaster'
--'sSecurity.tUserProfile'
GO
PRINT N'Altering [sSecurity].[pUserModify]...';


GO
ALTER PROCEDURE [sSecurity].[pUserModify]

	@rUserId [bigint],
	@rLoginTitle nvarchar(100),
	@rLoginPassword [nvarchar](100),
	@rIsObsolete [bit],
	@rUpdatedUserId [bigint],
	@rValidUpto date,
	@rIsCommon bit,
	@rIsPassword bit,
	@rOrgGroupId smallint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN	
	
	IF(@rIsCommon=0)
	BEGIN
		IF EXISTS(SELECT Id FROM sSecurity.tUser WHERE LoginTitle = @rLoginTitle AND Id!=@rUserId)
		BEGIN
			SELECT -1 AS ReturnCode
			RETURN
		END
	END
	
	DECLARE @lCurrentDateTime DATETIME
	EXECUTE @lCurrentDateTime = sCommon.fGetDate		
	
	IF (@rIsPassword=1 AND ISNULL(@rLoginPassword, '') = '')
	BEGIN
			EXEC sSecurity.pUserRemove  @rUserId, @rIsObsolete, @rUpdatedUserId
	END
	ELSE
	BEGIN
		IF (@rIsPassword=1)
		BEGIN
			IF(@rIsCommon=0)
			BEGIN
				UPDATE sSecurity.tUser
				SET	
					LoginPassword = @rLoginPassword,				
					IsObsolete = @rIsObsolete,			
					ValidUpto = @rValidUpto,
					UpdatedUserId = @rUpdatedUserId,
					UpdatedDateTime = @lCurrentDateTime			
				WHERE 
					Id = @rUserId
			END
			ELSE
			BEGIN
				UPDATE sSecurity.tUser
				SET	
					LoginPassword = @rLoginPassword,				
					IsObsolete = @rIsObsolete,			
					ValidUpto = @rValidUpto,
					UpdatedUserId = @rUpdatedUserId,
					UpdatedDateTime = @lCurrentDateTime			
				WHERE 
					LoginTitle = @rLoginTitle
				AND OrgId IN(SELECT Id FROM sSetup.tOrganizationMaster WHERE OrgGroupId=@rOrgGroupId)
			END
		END
		ELSE
		BEGIN
			IF(@rIsCommon=0)
			BEGIN
				UPDATE sSecurity.tUser
				SET	
					IsObsolete = @rIsObsolete,			
					ValidUpto = @rValidUpto,
					UpdatedUserId = @rUpdatedUserId,
					UpdatedDateTime = @lCurrentDateTime			
				WHERE 
					Id = @rUserId
			END
			ELSE
			BEGIN
				UPDATE sSecurity.tUser
				SET	
					IsObsolete = @rIsObsolete,			
					ValidUpto = @rValidUpto,
					UpdatedUserId = @rUpdatedUserId,
					UpdatedDateTime = @lCurrentDateTime			
				WHERE 
					LoginTitle = @rLoginTitle
				AND OrgId IN(SELECT Id FROM sSetup.tOrganizationMaster WHERE OrgGroupId=@rOrgGroupId)
			END
		END
	END
		
	SELECT 1 AS ReturnCode
END
GO
PRINT N'Altering [sSecurity].[pUserOrganizationGet]...';


GO


ALTER PROCEDURE [sSecurity].[pUserOrganizationGet]
	 
	@rUserId bigint,
	@rOrgGroupId smallint
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 
	SELECT
				OM.Id AS OrgId,
				OM.DisplayTitle AS Organization,
				CASE WHEN UO.UserId IS NULL THEN 'False' ELSE 'True' END AS IsObsolete
	FROM
			sSetup.tOrganizationMaster OM
		LEFT JOIN sSecurity.tUserOrganization UO ON UO.OrgId=OM.Id AND UO.UserId=@rUserId
	WHERE
		OM.OrgGroupId=@rOrgGroupId
			order by OM.OrderIndex
END
GO
PRINT N'Altering [sSecurity].[pUserValidate]...';


GO
ALTER PROCEDURE [sSecurity].[pUserValidate]
	@rOrgId int,
	@rUserTitle [nvarchar](100),
	@rUserPassword [nvarchar](1000),
	@rHostAddress [nvarchar](15),
	@rSessionId [nvarchar](100)
WITH EXECUTE AS CALLER
AS
DECLARE @lUserId BIGINT
SET @lUserId = 0

DECLARE @lLoginAttempts INT
SET @lLoginAttempts = 0

DECLARE @lLoginDateTime DateTime
SET @lLoginDateTime = sCommon.fGetDate()

DECLARE @lLastLockoutDate DateTime
SET @lLastLockoutDate = NULL

DECLARE @lValidUpto Date
SET @lValidUpto = NULL

SET NOCOUNT ON

BEGIN
	SELECT 
		@lUserId = Id,
		@lValidUpto = ValidUpto
	FROM sSecurity.tUser 		
	WHERE 
		UPPER(LoginTitle) = UPPER(@rUserTitle) AND
		   	(LoginPassword = @rUserPassword  OR @rUserPassword = '')  AND 
			NumberOfLogonAttempt <= 5000 AND
			IsObsolete = 0 AND
			OrgId = @rOrgId
 
	IF @lUserId > 0
		BEGIN
		
			IF(@lValidUpto IS NOT NULL)
			BEGIN
				IF(CONVERT(date, getdate()) > @lValidUpto)
				BEGIN
					RAISERROR('Your Account is expired', 16, 1)
					RETURN
				END
			END
			
			--UPDATE sSecurity.tUser
			--SET IsOnline = 1,
			--	NumberOfLogonAttempt = 0,			
			--	UpdatedDate = sCommon.fGetDate()
			--WHERE Id = @lUserId
			IF(@lUserId != 1 AND @rUserTitle != 'SysSuperAdmin')
			BEGIN
			EXECUTE sSecurity.pUserLogAdd @rOrgId, @lUserId, @rHostAddress, 1, @lLoginDateTime, NULL, 1, @rSessionId
			END
			--INSERT INTO sSecurity.tUserLog(UserId, LoggedInIp, LoggedInDateTime)
			--VALUES (@lUserId, @rHostAddress, sCommon.fGetDate())

	--		SELECT Id, Title, TitleResourceKey 
	--		FROM sSecurity.tRole 
	--		INNER JOIN sSecurity.tUserRole
	--			ON RoleId = Id
	--		WHERE UserId = @lUserId AND sSecurity.tRole.IsObsolete = 0
			
		 --   UPDATE E
			--SET E.StatusId = 9
			--FROM sHrm.tEmployeeMaster E
			--JOIN sHrm.tEmployeeJobDetail J ON E.Id = J.EmployeeId 
			--WHERE 
			----J.activeupto <= getdate() and 
			--E.orgID= @rOrgId 	    
		    
			SELECT @lUserId 
		END
	ELSE
		BEGIN 
			SELECT @lUserId = Id,
					@lLoginAttempts = NumberOfLogonAttempt,
					@lLastLockoutDate = LastLockOutDate
			FROM sSecurity.tUser
			WHERE UPPER(LoginTitle) = UPPER(@rUserTitle) AND
					OrgId = @rOrgId
			
			IF @lUserId > 0
				BEGIN
					IF @lLoginAttempts > 5000
						BEGIN
							IF @lLastLockoutDate IS NULL
								BEGIN
									UPDATE sSecurity.tUser
									SET LastLockOutDate = sCommon.fGetDate(),
										UpdatedDateTime = sCommon.fGetDate()
									WHERE Id = @lUserId AND
										 OrgId = @rOrgId
								END
							RAISERROR('User account locked', 16, 1)
							RETURN
						END
					ELSE
						BEGIN
							UPDATE sSecurity.tUser
							SET NumberOfLogonAttempt = NumberOfLogonAttempt + 1,
								UpdatedDateTime = sCommon.fGetDate()
							WHERE Id = @lUserId AND
								OrgId = @rOrgId
						END
				END		

			RAISERROR('Username/password does not match or Inactive employee.', 16, 1)		
		END
END
GO
PRINT N'Altering [sSetup].[pBatchMasterAdd]...';


GO
ALTER PROCEDURE [sSetup].[pBatchMasterAdd]
	 
	@rId int,
	@rCode nvarchar(20),
	@rTitle nvarchar(100),
	@rOrgId int,
	@rIsHistory bit,
	@rIsObsolete bit,
	@rOrderIndex smallint,
	@rFromDate date,
	@rToDate date,
	@rCreatedUserId bigint,
	@rUpdatedUserId bigint,
	@rOrgGroupBatchId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	IF(@rId = 0)	
	BEGIN
			IF EXISTS(SELECT 1 FROM sSetup.tBatchMaster WHERE OrgId=@rOrgId AND OrgGroupBatchId=@rOrgGroupBatchId)
			BEGIN
				SELECT -100 AS Result
				RETURN
			END
	END
	
	 BEGIN TRANSACTION	
 IF(@rId = 0)	
BEGIN

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

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


GO
ALTER PROCEDURE [sSetup].[pClassSubjectAdd]
          
            @rId int 
           ,@rClassId int
           ,@rSubjectId int
           ,@rIsOptional bit
           ,@rIsPractical bit
           ,@rIsObsolete bit
           ,@rOrderIndex smallint 
           ,@rCreatedUserId bigint
           ,@rOrgId int
           ,@rSelected bit
           --,@rUpdatedUserId bigint 
       
 
AS
SET NOCOUNT ON

BEGIN

	BEGIN TRY
	
	BEGIN TRANSACTION
	DECLARE @lNextNumber bigint
	
	IF(@rId = 0)
	BEGIN
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sSetup.tClassSubject', 0, 1, 1,@outNextNumber = @lNextNumber output
		
	INSERT INTO [sSetup].[tClassSubject]
           (
            [Id],
            [OrgId]
           ,[ClassId]
           ,[SubjectId]
           ,[IsOptional]
           ,[IsPractical]
           ,[IsObsolete]
           ,[OrderIndex]
           ,[CreatedUserId]
           ,[CreatedDateTime]
           )
     VALUES
           (
            @lNextNumber
           ,@rOrgId 
           ,@rClassId  
           ,@rSubjectId
           ,@rIsOptional
           ,@rIsPractical
           ,@rIsObsolete
           ,@rOrderIndex
           ,@rCreatedUserId  
           ,sCommon.fGetDate()
           )
           SELECT @lNextNumber AS Result
     END
ELSE
BEGIN
SET @lNextNumber = @rId
	IF EXISTS (SELECT ClassSubjectId FROM sAssessment.tOptionalSubject WHERE ClassSubjectId=@rId)  AND @rIsOptional = 0
	BEGIN
		SELECT -101 AS Result
	END 	
	ELSE IF EXISTS (SELECT ClassSubjectId FROM sAssessment.tExamDetail WHERE ClassSubjectId=@rId) 
	BEGIN
		SELECT -102 AS Result
	END			
	ELSE IF @rSelected = 1 
	  BEGIN
			UPDATE [sSetup].[tClassSubject]
			SET 
				IsOptional=@rIsOptional
			   ,OrgId=@rOrgId
			   ,IsPractical=@rIsPractical
			   ,OrderIndex=@rOrderIndex  
			   ,IsObsolete = @rIsObsolete
			   ,UpdatedUserId = @rCreatedUserId
			   ,UpdatedDateTime = sCommon.fGetDate()
		   WHERE Id = @rId 
    	   SELECT @lNextNumber AS Result
      END
   ELSE
		BEGIN
			DELETE FROM [sSetup].[tClassSubject] 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 [sSetup].[pClassSubjectListGet]...';


GO
ALTER PROCEDURE [sSetup].[pClassSubjectListGet]
          
           @rClassId int,
           @rOrgId smallint
 
AS
SET NOCOUNT ON

BEGIN

SELECT ISNULL(CS.Id,0) AS ClassSubjectId
	  ,ISNULL(S.Id,0) AS SubjectId
	  ,ISNULL(S.Title,'') AS Subject
	  , ISNULL(CS.IsOptional,0)        
       AS IsOptional 
      ,ISNULL(CS.IsPractical,0)AS IsPractical  
      ,ISNULL(CS.IsObsolete,0) AS IsObsolete
      ,(CASE WHEN CS.Id Is Null THEN 'False' ELSE 'True' END) AS Selected 
	  --CS.IsOptional
	  --,CS.IsPractical
	  ,(CASE WHEN CS.OrderIndex Is Null THEN S.OrderIndex ELSE CS.OrderIndex END) AS OrderIndex 
	   
      
FROM [sSetup].[tSubjectMaster] S
	  LEFT JOIN [sSetup].[tClassSubject] CS ON  S.Id = CS.SubjectId AND CS.ClassId=@rClassId
WHERE (S.OrgId=@rOrgId)	  
	  order by CS.OrderIndex	
END
GO
PRINT N'Altering [sSetup].[pOrganizationGroupBatchMasterAdd]...';


GO
ALTER PROCEDURE [sSetup].[pOrganizationGroupBatchMasterAdd]
	 
	@rId int,
	@rCode nvarchar(20),
	@rTitle nvarchar(100),
	@rOrgGroupId int,
	@rIsHistory bit,
	@rIsObsolete bit,
	@rOrderIndex smallint,
	@rFromDate date,
	@rToDate date,
	@rCreatedUserId bigint,
	@rUpdatedUserId bigint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
 IF(@rId = 0)	
BEGIN

	DECLARE @lNextNumber INT 
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sSetup.tOrgGroupBatchMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	INSERT INTO sSetup.tOrgGroupBatchMaster
		(
			Id,
			Code,
			Title,
			OrgGroupId,
			IsHistory,
			IsObsolete,
			OrderIndex,
			FromDate,
			ToDate,
			CreatedUserId,
			CreatedDateTime
		)
	VALUES
		(
			@lNextNumber,
			@rCode,
			@rTitle,
			@rOrgGroupId,
			@rIsHistory,
			@rIsObsolete,
			@rOrderIndex,
			@rFromDate,
			@rToDate,
			@rCreatedUserId,
			sCommon.fGetDate()
		)
		             
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sSetup.tOrgGroupBatchMaster
	    SET
			Code=@rCode,
			Title=@rTitle,
			IsHistory=@rIsHistory,
			IsObsolete=@rIsObsolete,
			OrderIndex=@rOrderIndex,
			FromDate=@rFromDate,
			ToDate=@rToDate,
			UpdatedUserId=@rUpdatedUserId,
			UpdatedDateTime=sCommon.fGetDate()
			
	      WHERE Id = @rId 	   
	 END  
		SELECT @lNextNumber AS Result
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [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),
	@rCreatedUserId bigint,
	@rUpdatedUserId bigint,
	@rIsObsolete bit,
	@rOrgGroupId smallint,
	@rOrgLogo varbinary(max),
	@rIsLogo bit,
	@rEmployeeId bigint,
	@rOrderIndex int
	
	
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,
			CreatedUserId,
			CreatedDateTime,
			IsObsolete,
			OrgGroupId,
			EmployeeId,
			OrderIndex
			--OrgLogo
		)
	VALUES
		(
			@rCode,
			@rCode,
			@rTitle,
			@rDisplayTitle,
			@rAffiliationId,
			@rLanguageId,
			--@rInstituteTypeId,
			--@rInstituteSubTypeId,
			@rStreetOne,
			@rStreetTwo,
			@rStreetThree,
			@rCityName,
			@rStateName,
			@rCountryName,
			@rZipCode,
			@rHomePage,
			@rPhoneNo,
			@rFaxNo,
			--@rReportOrgTitle,
			@rTitle,
			@rSmallAddress1,
			@rSmallAddress2,
			@rCreatedUserId,
			sCommon.fGetDate(), 
			@rIsObsolete,
			@rOrgGroupId,
			@rEmployeeId,
			@rOrderIndex
			--@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,
			UpdatedUserId=@rUpdatedUserId,
			UpdatedDateTime=sCommon.fGetDate(), 
			IsObsolete=@rIsObsolete,
			OrgGroupId=@rOrgGroupId,
			EmployeeId=@rEmployeeId,
			OrderIndex=@rOrderIndex
			--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.CreatedUserId,
			OM.CreatedDateTime,
			OM.UpdatedUserId,
			OM.UpdatedDateTime,
			OM.IsObsolete,
			OM.OrgGroupId,
			OM.OrgLogo,
			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
      
  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)
		
END
GO
PRINT N'Altering [sSetup].[pOrgGroupMasterAdd]...';


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

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

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

				
			--		INSERT INTO [sCommon].[tTableRowId]
			--           ([OrgId]
			--           ,[TableTitle]
			--           ,[CurrentNumber]
			--           ,[Seed]
			--           ,[Increment])
			--SELECT
			--		   0
			--		  ,[TableTitle]		  
			--		  ,CurrentNumber		
			--		  ,CurrentNumber
			--		  ,1
			--	  FROM [sCommon].[tTableRowIdMaster] where 
			--	  (tableType =   '100StaticCommon') 
			--	  AND IdScope = 'OrgGroup' 

			 INSERT INTO [sSetup].[tOrgGroupBatchMaster]
					   ([Id]
					   ,[Code]
					   ,[Title]
					   ,[OrgGroupId]
					   ,[IsHistory]
					   ,[IsActive]
					   ,[IsObsolete]
					   ,[OrderIndex]
					   ,[FromDate]
					   ,[ToDate]
					   ,[CreatedUserId]
					   ,[CreatedDateTime]
					   ,[UpdatedUserId]
					   ,[UpdatedDateTime])
			     
				  SELECT @lOrgGroupBatchId
					   ,@rOrgGroupBatchName
					   ,@rOrgGroupBatchName
					   ,@lOrgGroupId
					   ,0
					   ,1
					   ,0
					   ,1
					   ,@rFromDate
					   ,@rToDate
					  ,@lCreatedUserId
					  ,@lCreatedDateTime
					  ,@lCreatedUserId
					  ,@lCreatedDateTime
					   --FROM [sSetup].[tOrgGroupBatchMaster]
					   -- WHERE  OrgGroupId =  1
		END
		ELSE
		BEGIN
			UPDATE sSetup.tOrgGroupMaster
			SET
				Title=@rTitle,
				PunchLine=@rPunchLine,
				CRMLicenceNo=@rCRMLicenceNo
			  WHERE Id = @rId 
	    END
	      
	   
	      
	      SELECT @rCode AS Result	
		COMMIT TRANSACTION
		
		  exec  [sCommon].[pOrganizationSetupAdd] @rId
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sSetup].[pOrgGroupMasterGet]...';


GO
ALTER PROCEDURE [sSetup].[pOrgGroupMasterGet]
	 
	 @rId int,
	 @rTitle nvarchar(100),
	 @rCode nvarchar(20)
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	BEGIN
		SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		SET @rCode = sCommon.fSearchStringGet(@rCode)
	END
	SELECT 
		OB.Id,
		OB.Code,
		OB.Title,
		OB.CRMLicenceNo,
		ISNULL(OB.PunchLine,'') AS PunchLine
  FROM 
        sSetup.tOrgGroupMaster OB
  WHERE 
		((OB.Id=@rId) OR (@rId=0))
	AND (OB.Id!=1)
	AND ((OB.Code like @rCode) OR (ISNULL(@rCode,'')='')) 
	AND ((OB.Title like @rTitle) OR (ISNULL(@rTitle,'')='')) 
END
GO
PRINT N'Altering [sSetup].[pPortalEmployeeDetailAdd]...';


GO
ALTER PROCEDURE [sSetup].[pPortalEmployeeDetailAdd]
	(
		@rStrXml nvarchar(MAX),
		@rOrgId int
	)
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
DECLARE @lInterrorCode INT,
			@intDoc INT
BEGIN
	BEGIN TRY
		
		EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rStrXml			
		SET @rStrXml=REPLACE(@rStrXml,'&','AND')
		
		BEGIN TRANSACTION	
			BEGIN
	
	--DELETE FROM sHrm.tEmployeeMaster WHERE OrgID = @rOrgId	
	INSERT INTO sHrm.tEmployeeMaster
	(
		OrgID,
		Id,
		Code,
		FirstName,
		MiddleName,
		LastName,
		StatusId,
		IsObsolete,
		CreatedUserId,
		CreatedDateTime,
		UpdatedUserId,
		UpdatedDateTime
	)
	SELECT
		OrgId,
		Id,
		Code,
		FirstName,
		MiddleName,
		LastName,
		StatusId,
		IsObsolete,
		CreatedUserId,
		sCommon.fGetDate(),
		UpdatedUserId,
		UpdatedDateTime
		
	FROM OPENXML (@intDoc, '/Table/EmployeeMaster', 1)
	WITH
	(
		Id BIGINT '@Id' ,
		Code nvarchar(10) '@Code',
		FirstName nvarchar(100) '@FirstName',
		LastName nvarchar(100) '@LastName',
		MiddleName nvarchar(100) '@MiddleName',
		StatusId tinyint '@StatusId',
		IsObsolete bit '@IsObsolete',
		CreatedUserId Bigint '@CreatedUserId',
		UpdatedUserId bigint '@UpdatedUserId',
		UpdatedDateTime DateTime '@UpdatedDateTime',
		OrgId smallint '@OrgId'
	)
	
	
	
	--DELETE FROM sHrm.tEmployeePersonalDetail WHERE OrgId= @rOrgId		
	INSERT INTO sHrm.tEmployeePersonalDetail
	(
		OrgId,
		EmployeeId,
		DateOfBirth,
		GenderId,
		MaritalStatusId,
		BloodGroupId,
		Qualification,
		UpdatedUserId,
		UpdatedDateTime
	)
	
	SELECT
		OrgId,
		EmployeeId,
		DateOfBirth,
		GenderId,
		MaritalStatusId,
		BloodGroupId,
		Qualification,
		UpdatedUserId,
		sCommon.fGetDate()
		
	FROM OPENXML (@intDoc, '/Table/EmployeeMaster', 1)
	WITH
	(
		Id BIGINT '@PersonalDetailId',
		EmployeeId BIGINT '@Id',
		DateOfBirth DATE '@DateOfBirth',
		GenderId TINYINT '@GenderId',
		MaritalStatusId TINYINT '@MaritalStatusId',
		BloodGroupId TINYINT '@BloodGroupId',
		Qualification NVARCHAR(50) '@Qualification',
		UpdatedUserId BIGINT '@UpdatedUserId',
		OrgId SMALLINT '@OrgId'
	)

	
	--DELETE FROM sHrm.tEmployeeJobDetail WHERE OrgId = @rOrgId
	INSERT INTO sHrm.tEmployeeJobDetail
	(
		OrgId,
		EmployeeId,
		OrganizationDepartmentId,
		DateOfJoining,		
		EmployeeTypeId,
		EmployeeGroupId,
		EmployeeDesignationId,
		EmployeeGradeId,	
		UpdatedUserId,
		UpdatedDateTime
	)
	SELECT
		OrgId,
		EmployeeId,
		OrganizationDepartmentId,
		DateOfJoining,
		EmployeeTypeId,
		EmployeeGroupId,
		EmployeeDesignationId,
		EmployeeGradeId,	
		UpdatedUserId,
		sCommon.fGetDate()
		
	FROM OPENXML (@intDoc, '/Table/EmployeeMaster', 1)
	WITH
	(
		Id BIGint '@JobDetailId' ,
		EmployeeId bigint '@Id',
		OrganizationDepartmentId int '@OrganizationDepartmentId',
		DateOfJoining Date '@DateOfJoining',
		OrgId smallint '@OrgId',
		EmployeeTypeId int '@EmployeeTypeId',
		EmployeeGroupId tinyint '@EmployeeGroupId',
		EmployeeDesignationId int '@EmployeeDesignationId',
		EmployeeGradeId int '@EmployeeGradeId',
		UpdatedUserId bigint '@UpdatedUserId'
	)
	
	
	--DELETE FROM sHrm.tEmployeeCommunication WHERE OrgId = @rOrgId
	INSERT INTO sHrm.tEmployeeCommunications
	(
		EmployeeId,
		MobileNumber,
		PersonalEmail,
		UpdatedUserId,
		UpdatedDateTime
	)
	SELECT
		EmployeeId,
		MobileNumber,
		PersonalEmail,
		UpdatedUserId,
		sCommon.fGetDate()
		
	FROM OPENXML (@intDoc, '/Table/EmployeeMaster', 1)
	WITH
	(
		Id BIGint '@CommunicationId' ,
		EmployeeId bigint '@Id',		
		MobileNumber nvarchar(20) '@MobileNumber',
		PersonalEmail nvarchar(100) '@PersonalEmail',
		OrgId smallint '@OrgId',
		UpdatedUserId bigint '@UpdatedUserId'
	)
	
	
	IF NOT EXISTS (SELECT ID FROM sHrm.tEmployeeGradeMaster WHERE ID = 1)
	BEGIN
		INSERT INTO sHrm.tEmployeeGradeMaster (Id,Code,Title,IsObsolete,CreatedUserId,CreatedDateTime) VALUES
		(1,'Default Grade','Default Grade',0,9999000000003,sCommon.fGetDate())
	END
	END	
			EXEC sp_xml_removedocument @intDoc
		COMMIT TRANSACTION	
		SELECT 1
	END TRY
	BEGIN CATCH
	SELECT -1
	END CATCH

END
GO
PRINT N'Altering [sSetup].[pPortalEmployeeDetailGet]...';


GO
ALTER PROCEDURE [sSetup].[pPortalEmployeeDetailGet]
	 @rOrgId int,
	 @rEmployeeMaxId bigint
		 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	 
BEGIN 	
	SELECT	E.OrgId,
			E.Id,
			Code,
			FirstName,
			MiddleName,
			LastName,
			StatusId,
			E.IsObsolete,
			E.CreatedUserId,
			E.UpdatedUserId,
			E.UpdatedDateTime,
			0 AS PersonalDetailId,
			DateOfBirth,
			GenderId,
			ISNULL(MaritalStatusId,0) AS MaritalStatusId ,
			ISNULL(BloodGroupId,0) AS BloodGroupId,
			ISNULL(Qualification,'') AS Qualification,
			0 AS JobDetailId, 
			OrganizationDepartmentId,
			DateOfJoining,		
			EmployeeTypeId,
			ISNULL(EmployeeGroupId,0) AS EmployeeGroupId,
			ISNULL(EmployeeDesignationId,0) AS EmployeeDesignationId,
			ISNULL(EmployeeGradeId,0) AS EmployeeGradeId,
			0 AS CommunicationId,
			MobileNumber,
			PersonalEmail,			
			 ISNULL(EmployeePhoto, CONVERT(VARBINARY(MAX), 0)) AS EmployeePhoto
			
		From sHrm.tEmployeeMaster E 
		LEFT JOIN sHrm.tEmployeePersonalDetail P ON E.Id = P.EmployeeId
		LEFT JOIN sHrm.tEmployeeJobDetail J ON E.Id = J.EmployeeId
		LEFT JOIN sHrm.tEmployeeCommunications C ON E.Id = C.EmployeeId
		LEFT JOIN SHRM.tEmployeeImages I ON E.ID = I.EmployeeId

 WHERE  E.OrgId = @rOrgId AND E.ID > @rEmployeeMaxId
 
 END
GO
PRINT N'Altering [sSetup].[pPortalEmployeeDetailUpdate]...';


GO
ALTER PROCEDURE [sSetup].[pPortalEmployeeDetailUpdate]
	(
		@rStrXml nvarchar(MAX),
		@rOrgId int
	)
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
DECLARE @lInterrorCode INT,
			@intDoc INT
BEGIN
	BEGIN TRY
		
		EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rStrXml			
		SET @rStrXml=REPLACE(@rStrXml,'&','AND')
		
		BEGIN TRANSACTION	
			BEGIN
	
	Update sHrm.tEmployeeMaster
	SET
		OrgID = A.OrgID,
		Code = A.Code,
		FirstName = A.FirstName,
		MiddleName = A.MiddleName,
		LastName = A.LastName,
		StatusId = A.StatusId,
		IsObsolete = A.IsObsolete,
		UpdatedDateTime = A.UpdatedDateTime
	FROM
	(
	SELECT
		OrgId,
		Id,
		Code,
		FirstName,
		MiddleName,
		LastName,
		StatusId,
		IsObsolete,		
		UpdatedDateTime		
	FROM OPENXML (@intDoc, '/Table/EmployeeMaster', 1)
	WITH
	(
		Id BIGINT '@Id' ,
		Code nvarchar(10) '@Code',
		FirstName nvarchar(100) '@FirstName',
		LastName nvarchar(100) '@LastName',
		MiddleName nvarchar(100) '@MiddleName',
		StatusId tinyint '@StatusId',
		IsObsolete bit '@IsObsolete',	
		UpdatedDateTime Datetime '@UpdatedDateTime',
		OrgId smallint '@OrgId'
	)) A
	Where sHrm.tEmployeeMaster.Id=	A.Id
	
	UPDATE sHrm.tEmployeePersonalDetail
	SET
		OrgId = A.OrgId,
		EmployeeId = A.EmployeeId,
		DateOfBirth = A.DateOfBirth,
		GenderId = A.GenderId,
		MaritalStatusId = A.MaritalStatusId,
		BloodGroupId = A.BloodGroupId,
		Qualification = A.Qualification,
		UpdatedUserId = A.UpdatedUserId,
		UpdatedDateTime = A.UpdatedDateTime
	FROM
	(
	SELECT
		OrgId,
		EmployeeId,
		DateOfBirth,
		GenderId,
		MaritalStatusId,
		BloodGroupId,
		Qualification,
		UpdatedUserId,
		UpdatedDateTime
		
	FROM OPENXML (@intDoc, '/Table/EmployeeMaster', 1)
	WITH
	(
		EmployeeId BIGINT '@Id',
		DateOfBirth DATE '@DateOfBirth',
		GenderId TINYINT '@GenderId',
		MaritalStatusId TINYINT '@MaritalStatusId',
		BloodGroupId TINYINT '@BloodGroupId',
		Qualification NVARCHAR(50) '@Qualification',
		UpdatedUserId BIGINT '@UpdatedUserId',
		UpdatedDateTime DateTime '@UpdatedDateTime',
		OrgId SMALLINT '@OrgId'
	)) A
	Where sHrm.tEmployeePersonalDetail.EmployeeId = A.EmployeeId

	UPDATE sHrm.tEmployeeJobDetail
	SET
		OrgId = A.OrgId	,
		EmployeeId = A.EmployeeId,
		OrganizationDepartmentId = A.OrganizationDepartmentId,
		DateOfJoining = A.DateOfJoining,		
		EmployeeTypeId = A.EmployeeTypeId,
		EmployeeGroupId = A.EmployeeGroupId,
		EmployeeDesignationId = A.EmployeeDesignationId,
		EmployeeGradeId = A.EmployeeGradeId,	
		UpdatedUserId = A.UpdatedUserId,
		UpdatedDateTime = A.UpdatedDateTime
	From
	(
	SELECT
		OrgId,
		EmployeeId,
		OrganizationDepartmentId,
		DateOfJoining,
		EmployeeTypeId,
		EmployeeGroupId,
		EmployeeDesignationId,
		EmployeeGradeId,	
		UpdatedUserId,
		UpdatedDateTime
	FROM OPENXML (@intDoc, '/Table/EmployeeMaster', 1)
	WITH
	(
		EmployeeId bigint '@Id',
		OrganizationDepartmentId int '@OrganizationDepartmentId',
		DateOfJoining Date '@DateOfJoining',
		OrgId smallint '@OrgId',
		EmployeeTypeId int '@EmployeeTypeId',
		EmployeeGroupId tinyint '@EmployeeGroupId',
		EmployeeDesignationId int '@EmployeeDesignationId',
		EmployeeGradeId int '@EmployeeGradeId',
		UpdatedUserId bigint '@UpdatedUserId',
		UpdatedDateTime Datetime '@UpdatedDateTime'
	)) A
	Where sHrm.tEmployeeJobDetail.EmployeeId = A.EmployeeId
	
	UPDATE sHrm.tEmployeeCommunications
	SET 
		EmployeeId = A.EmployeeId,
		MobileNumber = A.MobileNumber,
		PersonalEmail = A.PersonalEmail,
		UpdatedUserId = A.UpdatedUserId,
		UpdatedDateTime = A.UpdatedDateTime
	FROM
	(
	SELECT
		EmployeeId,
		MobileNumber,
		PersonalEmail,
		UpdatedUserId,
		UpdatedDateTime
		
	FROM OPENXML (@intDoc, '/Table/EmployeeMaster', 1)
	WITH
	(
		EmployeeId bigint '@Id',		
		MobileNumber nvarchar(20) '@MobileNumber',
		PersonalEmail nvarchar(100) '@PersonalEmail',
		OrgId smallint '@OrgId',
		UpdatedUserId bigint '@UpdatedUserId',
		UpdatedDateTime Datetime '@UpdatedDateTime'
	)) A
	Where sHrm.tEmployeeCommunications.EmployeeId = A.EmployeeId
	
	
	IF NOT EXISTS (SELECT ID FROM sHrm.tEmployeeGradeMaster WHERE ID = 1)
	BEGIN
		INSERT INTO sHrm.tEmployeeGradeMaster (Id,Code,Title,IsObsolete,CreatedUserId,CreatedDateTime) VALUES
		(1,'Default Grade','Default Grade',0,9999000000003,sCommon.fGetDate())
	END
	END	
			EXEC sp_xml_removedocument @intDoc
		COMMIT TRANSACTION	
		SELECT 1
	END TRY
	BEGIN CATCH
	SELECT -1
	END CATCH

END
GO
PRINT N'Altering [sSetup].[pPortalEmployeeUpdateDetailGet]...';


GO
ALTER PROCEDURE [sSetup].[pPortalEmployeeUpdateDetailGet]
	 @rOrgId int,
	  @rMaxUpdatedDateTime DateTime
		 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	 
BEGIN 	
	SELECT	E.OrgId,
			E.Id,
			Code,
			FirstName,
			MiddleName,
			LastName,
			StatusId,
			E.IsObsolete,
			E.CreatedUserId,
			E.UpdatedUserId,
			E.UpdatedDateTime,
			0 AS PersonalDetailId,
			DateOfBirth,
			GenderId,
			ISNULL(MaritalStatusId,0) AS MaritalStatusId ,
			ISNULL(BloodGroupId,0) AS BloodGroupId,
			ISNULL(Qualification,'') AS Qualification,
			0 AS JobDetailId, 
			OrganizationDepartmentId,
			DateOfJoining,		
			EmployeeTypeId,
			ISNULL(EmployeeGroupId,0) AS EmployeeGroupId,
			ISNULL(EmployeeDesignationId,0) AS EmployeeDesignationId,
			ISNULL(EmployeeGradeId,0) AS EmployeeGradeId,
			0 AS CommunicationId,
			MobileNumber,
			PersonalEmail,			
			 ISNULL(EmployeePhoto, CONVERT(VARBINARY(MAX), 0)) AS EmployeePhoto
			
		From sHrm.tEmployeeMaster E 
		LEFT JOIN sHrm.tEmployeePersonalDetail P ON E.Id = P.EmployeeId
		LEFT JOIN sHrm.tEmployeeJobDetail J ON E.Id = J.EmployeeId
		LEFT JOIN sHrm.tEmployeeCommunications C ON E.Id = C.EmployeeId
		LEFT JOIN SHRM.tEmployeeImages I ON E.ID = I.EmployeeId

 WHERE  E.OrgId = @rOrgId AND E.UpdatedDateTime > @rMaxUpdatedDateTime
 
 END
GO
PRINT N'Altering [sSetup].[pReportInfoGet]...';


GO


ALTER PROCEDURE [sSetup].[pReportInfoGet]

	@rReportId [int] = 0,	
	@rOrgId [smallint] = 0,
	@rUserId [bigint] = 0 ,
	@rUserTitle nvarchar(100) = ''
	
 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 
	
	SELECT 
	
			OM.ID AS OrgId,
			OM.Code AS OrgCode,
			OM.ReportOrgTitle,
			OM.SmallAddress1 AS ReportAddress1,
			OM.SmallAddress2 AS ReportAddress2,			
			OM.OrgLogo AS ReportOrgLogo,		
			(SELECT Title FROM sCommon.tReport WHERE Id = @rReportId) AS ReportTitle,
			@rUserId AS PrintedByUserId,
			@rUserTitle AS PrintedByUserDisplayTitle
				--RC.DetailBackgroundColor,	 
			--RC.Group1BackgroundColor,
			--RC.Group2BackgroundColor,
			--RC.Group3BackgroundColor,
			--RC.Group4BackgroundColor,
			--CC.ShortDatePattern,
			--CC.ShortTimePattern,
		 --   CC.LongDatePattern,
		 --   CC.LongTimePattern,
		 --   CC.NumberGroupSeparator,
		 --   CC.NumberNegativePattern,
		 --   CC.NumberGroupSizes
		 
      
  FROM 
		   sSetup.tOrganizationMaster OM 	
            
             
  WHERE 
  
       OM.Id = @rOrgId 
 
  order by OM.OrderIndex
		
END
GO
PRINT N'Altering [sSetup].[prptOrganizationGet]...';


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

BEGIN 
	 
	
	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.SmallAddress1,
			OM.SmallAddress2,
			OM.CreatedUserId,
			OM.CreatedDateTime,
			OM.UpdatedUserId,
			OM.UpdatedDateTime,
			OM.IsObsolete
      
  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
             
  WHERE 
  
     OM.Id = @rId 
	 
  
		Order By OM.OrderIndex
END
GO
PRINT N'Altering [sSetup].[pSubjectMasterAdd]...';


GO
ALTER PROCEDURE [sSetup].[pSubjectMasterAdd]
	 
	@rId int,
	@rCode nvarchar(20),
	@rNumber smallint,
	@rTitle nvarchar(100),
	@rOrgId int,
	@rIsObsolete bit,
	@rOrderIndex smallint,
	@rCreatedUserId bigint,
	@rUpdatedUserId bigint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	IF(@rId = 0)	
	BEGIN
		If Exists(select Id from sSetup.tSubjectMaster where Code=@rCode AND OrgId=@rOrgId)
			BEGIN
			select -102 as Result
			RETURN
		END 
	
		If Exists(select Id from sSetup.tSubjectMaster where Title=@rTitle and OrgId=@rOrgId)
			BEGIN
			select -103 as Result
			RETURN
		END 
		
		If Exists(select Id from sSetup.tSubjectMaster where Number=@rNumber and OrgId=@rOrgId)
			BEGIN
			select -104 as Result
			RETURN
		END 
		
		If Exists(select Id from sSetup.tSubjectMaster where OrderIndex=@rOrderIndex and OrgId=@rOrgId)
			BEGIN
			select -105 as Result
			RETURN
		END 
	END
	ELSE
	BEGIN
		If Exists(select Id from sSetup.tSubjectMaster where Code=@rCode AND OrgId=@rOrgId AND Id<>@rId)
		Begin
			select -102 as Result
			RETURN
		End
		If  Exists(select Id from sSetup.tSubjectMaster where Title=@rTitle AND OrgId=@rOrgId AND Id<>@rId)
		Begin
			select -103 as Result
			RETURN
		End
		
		If  Exists(select Id from sSetup.tSubjectMaster where Number=@rNumber AND OrgId=@rOrgId AND Id<>@rId)
		Begin
			select -104 as Result
			RETURN
		End
		
		If  Exists(select Id from sSetup.tSubjectMaster where OrderIndex=@rOrderIndex AND OrgId=@rOrgId AND Id<>@rId)
		Begin
			select -105 as Result
			RETURN
		End

	END
	
	 BEGIN TRANSACTION	
 IF(@rId = 0)	
BEGIN

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


	INSERT INTO sSetup.tSubjectMaster
		(
			Id,
			Code,
			Number,
			Title,
			OrgId,
			IsObsolete,
			OrderIndex,
			CreatedUserId,
			CreatedDateTime
			
		)
	VALUES
		(
			@lNextNumber,
			@rCode,
			@rNumber,
			@rTitle,
			@rOrgId,
			@rIsObsolete,
			@rOrderIndex,
			@rCreatedUserId,
			sCommon.fGetDate()
			
		)
		             
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sSetup.tSubjectMaster
	    SET
			Code=@rCode,
			Number=@rNumber,
			Title=@rTitle,
			OrgId=@rOrgId,
			IsObsolete=@rIsObsolete,
			OrderIndex=@rOrderIndex,
			UpdatedUserId=@rUpdatedUserId,
			UpdatedDateTime=sCommon.fGetDate()
			
	      
	      
	      WHERE Id = @rId 	   
	 END  
		SELECT @lNextNumber AS Result
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sSetup].[pXMLAutoGenerateTestQuestionAdd]...';


GO
ALTER PROCEDURE [sSetup].[pXMLAutoGenerateTestQuestionAdd]
	(	
		@rXmlquestionList nvarchar(MAX),
		@rTestId int		 
	)
AS

SET NOCOUNT ON

BEGIN
 
DECLARE @lInterrorCode INT,
		@intDoc INT
DECLARE @lNextNumber BIGINT
			
BEGIN TRY
BEGIN TRANSACTION	
  BEGIN
	EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlquestionList
	
	--DELETE  TQ FROM sEExam.tTestQuestion  TQ INNER JOIN  
	--(
	--SELECT QuestionId,TestId From
	--	OPENXML (@intDoc, '/Table/ImportQuestionList',1) 
	--	WITH (
	--	QuestionId bigint,
	--	TestId int		 
	--	)
	--	)A   
	--ON  A.QuestionId = TQ.QuestionId AND TQ.TestId = A.TestId 
	--WHERE A.QuestionId = TQ.QuestionId AND TQ.TestId = A.TestId  
	
	-----------------------
	
	IF NOT EXISTS(Select 1 FROM sEExam.tTestQuestion Where TestId = @rTestId)
	
	BEGIN
	
	INSERT INTO sEExam.tTestQuestion
	(
	    QuestionId,
		TestId,
		Marks,
		OrderIndex	
	)
	
    SELECT QuestionId,TestId,Marks,OrderIndex From
	OPENXML (@intDoc, '/Table/ImportQuestionList',1) 
	WITH 
	(
	QuestionId bigint '@QuestionId',
	TestId int '@TestId',
	Marks decimal(6,2) '@Marks',
	OrderIndex int '@OrderIndex'	 
	) 
	
	  
	  SELECT 1
	  
	END
	ELSE 
	  BEGIN  
	    SELECT -101
	  END
   END
	EXEC sp_xml_removedocument @intDoc
	COMMIT TRANSACTION
	
	END TRY
	BEGIN CATCH
	SELECT -1
	END CATCH

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,
	--@rTransportModeId int = null,
 --   @rPickupBusRouteDestinationId int = null,
 --   @rDropBusRouteDestinationId int = null,
	@rCreatedUserId bigint,
	@rUpdatedUserId bigint
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 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,
			--TransportModeId,
			--PickupBusRouteDestinationId,
			--DropBusRouteDestinationId,
			CreatedUserId,
			CreatedDateTime
		)
	VALUES
		(
			@lNextNumber,
			@rStudentId,
			@rClassId,
			@rDivisionId,
			@rRollNo,
			@rOrgId,
			@rBatchId,
			--@rTransportModeId,
			--@rPickupBusRouteDestinationId,
			--@rDropBusRouteDestinationId,
			@rCreatedUserId,
			sCommon.fGetDate()
		)
		         
	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,
			--TransportModeId=@rTransportModeId,
			--PickupBusRouteDestinationId=@rPickupBusRouteDestinationId,
			--DropBusRouteDestinationId=@rDropBusRouteDestinationId,
			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].[pDivisionAllotmentGet]...';


GO
ALTER PROCEDURE [sStudent].[pDivisionAllotmentGet]
	 
	 @rClassID int,
	 @rDivisionId int,
	 @rIsIDNoAlloted bit,
	 @rStrIDNo nvarchar(500),
	 @rCode nvarchar(20),
	 @rLastName nvarchar(100),
	 @rFirstName nvarchar(100),
	 @rOrgId int,
	 @rBatchId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

		DECLARE @ListofIDs TABLE(IDs nvarchar(20), ID INT IDENTITY(1,1));
		INSERT INTO @ListofIDs

		select q2.value from
		(SELECT cast('<x>'+replace(@rStrIDNo,',','</x><x>')+'</x>' as xml) as thexml)q1 CROSS APPLY
		(SELECT x.value('.','nvarchar(20)') as value FROM thexml.nodes('x') as f(x))q2
		
		
	 --IF(@rIsSearch=1)
		--BEGIN
			--SET @rGRNo = sCommon.fSearchStringGet(@rGRNo)
			SET @rLastName = sCommon.fSearchStringGet(@rLastName)
			SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
		--END
	
	SELECT 
			SN.AcademicId,
			SN.StudentId,
			--SO.GenderId,
			SN.ClassId,
			SN.DivisionId,
			SN.RollNo AS RollNo,
			SN.FirstName,
			--SM.MiddleName,
			SN.LastName,
			SN.FirstName+' '+SN.LastName AS Name,
			SN.Number AS GRNo,
			SN.Code
			
      
  FROM 
			[sStudent].[vStudentName] SN
           --sStudent.tAcademic A
           --INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId 
           ----INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId  
  WHERE 
			(SN.ClassId=@rClassId OR @rClassId=0)
			AND (SN.DivisionId=@rDivisionId OR @rDivisionId=0)
			AND ((SN.Code IN(SELECT IDs FROM @ListofIDs)) OR (ISNULL(@rStrIDNo,'') = ''))
			--AND ((SN.Code = @rCode) OR (ISNULL(@rCode,'') = ''))
			AND ((SN.LastName like @rLastName) OR (ISNULL(@rLastName,'') = ''))
			AND ((SN.FirstName like @rFirstName) OR (ISNULL(@rFirstName,'') = ''))
			AND SN.OrgID=@rOrgId 
			AND SN.BatchId=@rBatchId
			AND ((@rIsIDNoAlloted!=1) OR (ISNULL(SN.Code,'') = ''))
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
	
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			CM.DisplayTitle AS Class,
			DM.DisplayTitle AS Division,
			CM.DisplayTitle+' '+DM.DisplayTitle AS ClassDivision,
			--BGM.Title AS BloodGroup,
			--RM.Title AS Religion,
			ISNULL(GM.Title,'') As Gender,
			A.Id AS AcademicId,
			SO.DateOfBirth,
			CASE WHEN  @rReportId=10135
			THEN ISNULL(CCM.Title,'') 
		    WHEN  @rReportId=10136
			THEN ISNULL(RM.Title,'')
			WHEN @rReportId=20328
			THEN ISNULL(SCM.Title,'')
			WHEN  @rReportId=10152
			THEN ISNULL(BGM.Title,'') 
			WHEN  @rReportId=20329
			THEN  ([sStudent].[fStudentAgeGroupGet](SO.DateOfBirth,@rAsOnDate,@rOrgId))
		
			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
			INNER 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 (SA.InactiveDate<=@rAsOnDate OR SA.InactiveDate IS NULL)
		
END
GO
PRINT N'Altering [sStudent].[pRptStudentListGet]...';


GO

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

BEGIN 

	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			SA.AcademicId,
			SA.StudentId, 
			SA.ClassId,
			SA.DivisionId,
			SA.Code,
			SA.RollNo AS RollNo,			
			SA.FirstName,			
			SA.LastName,
			SA.Name,		
			SA.ClassName,
			SA.DivisionName,
			SA.StatusName,
			SA.DivisionOrder,
			SA.Number AS StudentNumber
      
	FROM 
		 	sStudent.vStudentAcademic SA
	WHERE 
			SA.OrgId=@rOrgId
		AND	SA.BatchId = @rBatchId
		AND (ISNULL(SA.StudentId,0) NOT IN( SELECT cast(item as bigint) FROM  sCommon.fnsplit(@rStrStudentId,',')) OR @rStrStudentId='') 
		AND (ISNULL(SA.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rStrCode,',')) OR @rStrCode='') 
		AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((SA.StudentId=@rStudentId) OR (@rStudentId=0))
		AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((SA.StatusId=@rStatusId)OR(@rStatusId=0))
END
GO
PRINT N'Altering [sStudent].[pRptStudentRegisterGet]...';


GO


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

BEGIN 

	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			SD.AcademicId,
			SD.StudentId, 
			SD.ClassId,
			SD.DivisionId,
			SD.ClassDivision,
			SD.Code,
			SD.RollNo,			
			SD.FirstName,
			SD.MiddleName,			
			SD.LastName,
			SD.Name,		
			SD.ClassName,
			SD.DivisionName,
			SD.StatusName,
			SD.StatusId,
			SD.LCProgress,
			SD.Religion,
			SD.FamilyCast,
			SD.FamilySubCast,
			SD.LCConduct,
			SD.BirthPlace,
			SD.BirthTaluka,
			SD.BirthDistrict,
			SD.LeftDate,
			SD.PreviousSchool,
			SD.DateOfBirth,
			SD.BirthDateInWord,
			SD.LeftReason,
			SD.AdmissionDate,
			SD.AdmissionStandard,
			SD.LeftStandard,
			SD.LCNumber,
			SD.LCDate,
			SD.StudentPhoto,
			SD.BloodGroup,
			SD.PresentAddress,
			SD.ContactNo,
			SD.Batch,
			SD.InactiveDate,
			OM.Title AS OrgName,
			SF.MotherName,
			SD.DivisionOrder,
			SD.Number AS StudentNumber
      
	FROM 
			sStudent.vStudentAllDetail SD
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=SD.OrgId
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId=SD.StudentId
	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 ((MONTH(SD.DateOfBirth)=@rDateOfBirth OR @rDateOfBirth=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 = '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
 )
AS
SET NOCOUNT ON

BEGIN
		DECLARE @Sql nvarchar(MAX)
		
		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'
		
		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)
		
		SELECT 
				*,
				SCS.ClassName+'-'+SCS.DivisionName AS ClassName1
		into sStudent.tTempStudent1
		FROM sStudent.vStudentCustomSearch SCS
		WHERE 
			SCS.OrgId = @rOrgId 
			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 ((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.Hobby Like '%' + @rHobby + '%') OR (@rHobby = ''))
			--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 ((SCS.IsPysicalDeformity=@rIsPysicalDeformity) OR (@rIsPysicalDeformity=0))
		    AND ((SCS.IsMajorIllness=@rIsMajorIllness) OR (@rIsMajorIllness=0)) 
		    
	SET @rOrderBy=Replace(@rOrderBy,'ID No','Code')
		SET @sql=
		'SELECT 
				StudentId,
				Code AS Code,
				Name,
				ClassName1 AS ClassName,
				StatusName 
		FROM sStudent.tTempStudent1 ORDER BY '+@rOrderBy
		exec(@Sql)
		
		DROP Table sStudent.tTempStudent1
END
GO
PRINT N'Altering [sStudent].[pStudentDataModify]...';


GO

ALTER PROCEDURE [sStudent].[pStudentDataModify]	 
	
	@rXML nvarchar(max),
	@rSubCategoryField nvarchar(100),
	@rCategoryId int
	
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 = 'CastCategory' OR @rSubCategoryField = 'TransportMode' OR @rSubCategoryField = 'House'
			OR @rSubCategoryField = 'MotherTongue' OR @rSubCategoryField = 'Nationality' OR @rSubCategoryField = 'AdmissionStandard' OR  @rSubCategoryField = 'AdmissionCategory' )
	BEGIN
		SET @rSubCategoryField = @rSubCategoryField + 'Id'
	END
		
	CREATE TABLE ListofData(Id bigint,StudentId bigint,SubCategory nvarchar(100),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(100),
						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
		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
		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
		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		 
	 
END 
	   COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
GO
PRINT N'Altering [sStudent].[pStudentDataUpdateGet]...';


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

BEGIN
		DECLARE @lDataTypeId nvarchar(1)
		SELECT @lDataTypeId=DataTypeId FROM sCommon.tUpdateFieldMaster WHERE Field=@rSubCategory
		
		IF(@rSubCategory = 'Gender' OR @rSubCategory = 'Religion' OR @rSubCategory = 'BloodGroup' 
			OR @rSubCategory = 'CastCategory' OR @rSubCategory = 'TransportMode' OR @rSubCategory = 'House'
			OR @rSubCategory = 'MotherTongue' OR @rSubCategory = 'Nationality' OR @rSubCategory = 'AdmissionStandard' OR  @rSubCategory = 'AdmissionCategory'
			)
		BEGIN
			SET @rSubCategory = @rSubCategory + 'Id'
		END
		 Declare @Sql nvarchar(max)
		 
		 SET @Sql =  CASE @rCategoryId					  
					 WHEN 1 THEN -- Communication
						'Select SA.StudentId,SA.AcademicId,SA.Code,SA.Name,SA.ClassName+'' - ''+SA.DivisionName AS ClassDivision,SA.RollNo,
						CASE WHEN '+@lDataTypeId+'=1 THEN
						ISNULL(SC.'+@rSubCategory+','''')
						WHEN '+@lDataTypeId+'=2 THEN
						ISNULL(SC.'+@rSubCategory+',''0'')
						WHEN '+@lDataTypeId+'=3 THEN
						ISNULL(SC.'+@rSubCategory+',''False'')
						WHEN '+@lDataTypeId+'=4 THEN
						ISNULL(SC.'+@rSubCategory+',''0001/01/01'')
						END AS SubCategory
							FROM 
							sStudent.vStudentAcademic SA
							LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=SA.StudentId
							Where SA.OrgId='+CAST(@rOrgId AS nvarchar(15))
							+'AND (SA.ClassId='+CAST(@rClassId AS nvarchar(15))+ 'OR '+CAST(@rClassId AS nvarchar(15))+'=0)
							AND (SA.DivisionId='+CAST(@rDivisionId AS nvarchar(15))+ 'OR '+CAST(@rDivisionId AS nvarchar(15))+'=0)
							AND (SA.StatusId='+ CAST(@rStatusId AS nvarchar(15)) +' OR '+CAST(@rStatusId AS nvarchar(15))+'=0)
							AND 
							('+CAST(@rIsBlank AS nvarchar(1))+'=0 
								OR ('+@lDataTypeId+'=1 AND ISNULL(SC.'+@rSubCategory+','''')='''')
								OR ('+@lDataTypeId+'=2 AND ISNULL(SC.'+@rSubCategory+',''0'')=''0'')
								OR ('+@lDataTypeId+'=3 AND ISNULL(SC.'+@rSubCategory+',''False'')=''False'')
								OR ('+@lDataTypeId+'=4 AND ISNULL(SC.'+@rSubCategory+',''0001/01/01'')=''0001/01/01'') 
							)'
					 WHEN 2 THEN -- Other
						'Select SA.StudentId,SA.AcademicId,SA.Code,SA.Name,SA.ClassName+'' - ''+SA.DivisionName AS ClassDivision,SA.RollNo,
						CASE WHEN '+@lDataTypeId+'=1 THEN
						ISNULL(SO.'+@rSubCategory+','''')
						WHEN '+@lDataTypeId+'=2 THEN
						ISNULL(SO.'+@rSubCategory+',''0'')
						WHEN '+@lDataTypeId+'=3 THEN
						ISNULL(SO.'+@rSubCategory+',''False'')
						WHEN '+@lDataTypeId+'=4 THEN
						SO.'+@rSubCategory+'
						END AS SubCategory
							FROM 
							sStudent.vStudentAcademic SA
							LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=SA.StudentId
							Where SA.OrgId='+CAST(@rOrgId AS nvarchar(15))
							+'AND (SA.ClassId='+CAST(@rClassId AS nvarchar(15))+ 'OR '+CAST(@rClassId AS nvarchar(15))+'=0)
							AND (SA.DivisionId='+CAST(@rDivisionId AS nvarchar(15))+ 'OR '+CAST(@rDivisionId AS nvarchar(15))+'=0)
							AND (SA.StatusId='+ CAST(@rStatusId AS nvarchar(15)) +' OR '+CAST(@rStatusId AS nvarchar(15))+'=0)
							AND 
							('+CAST(@rIsBlank AS nvarchar(1))+'=0 
								OR ('+@lDataTypeId+'=1 AND ISNULL(SO.'+@rSubCategory+','''')='''')
								OR ('+@lDataTypeId+'=2 AND ISNULL(SO.'+@rSubCategory+',''0'')=''0'')
								OR ('+@lDataTypeId+'=3 AND ISNULL(SO.'+@rSubCategory+',''False'')=''False'')
								OR ('+@lDataTypeId+'=4 AND ISNULL(SO.'+@rSubCategory+',''0001/01/01'')=''0001/01/01'') 
							)'
							
					WHEN 3 THEN -- Admission
						'Select SA.StudentId,SA.AcademicId,SA.Code,SA.Name,SA.ClassName+'' - ''+SA.DivisionName AS ClassDivision,SA.RollNo,
						CASE WHEN '+@lDataTypeId+'=1 THEN
						ISNULL(SAD.'+@rSubCategory+','''')
						WHEN '+@lDataTypeId+'=2 THEN
						ISNULL(SAD.'+@rSubCategory+',''0'')
						WHEN '+@lDataTypeId+'=3 THEN
						ISNULL(SAD.'+@rSubCategory+',''False'')
						WHEN '+@lDataTypeId+'=4 THEN
						ISNULL(SAD.'+@rSubCategory+',''0001/01/01'')
						END AS SubCategory 
							FROM 
							sStudent.vStudentAcademic SA
							INNER JOIN sStudent.tStudentAdmission SAD ON SAD.StudentId=SA.StudentId
							Where SA.OrgId='+CAST(@rOrgId AS nvarchar(15))
							+'AND (SA.ClassId='+CAST(@rClassId AS nvarchar(15))+ 'OR '+CAST(@rClassId AS nvarchar(15))+'=0)
							AND (SA.DivisionId='+CAST(@rDivisionId AS nvarchar(15))+ 'OR '+CAST(@rDivisionId AS nvarchar(15))+'=0)
							AND (SA.StatusId='+ CAST(@rStatusId AS nvarchar(15)) +' OR '+CAST(@rStatusId AS nvarchar(15))+'=0)
							AND 
							('+CAST(@rIsBlank AS nvarchar(1))+'=0 
								OR ('+@lDataTypeId+'=1 AND ISNULL(SAD.'+@rSubCategory+','''')='''')
								OR ('+@lDataTypeId+'=2 AND ISNULL(SAD.'+@rSubCategory+',''0'')=''0'')
								OR ('+@lDataTypeId+'=3 AND ISNULL(SAD.'+@rSubCategory+',''False'')=''False'')
								OR ('+@lDataTypeId+'=4 AND ISNULL(SAD.'+@rSubCategory+',''0001/01/01'')=''0001/01/01'') 
							)'
					 
					WHEN 4 THEN --Family
					   'Select SA.StudentId,SA.AcademicId,SA.Code,SA.Name,SA.ClassName+'' - ''+SA.DivisionName AS ClassDivision,SA.RollNo,
						CASE WHEN '+@lDataTypeId+'=1 THEN
						ISNULL(SAF.'+@rSubCategory+','''')
						WHEN '+@lDataTypeId+'=2 THEN
						ISNULL(SAF.'+@rSubCategory+',''0'')
						WHEN '+@lDataTypeId+'=3 THEN
						ISNULL(SAF.'+@rSubCategory+',''False'')
						WHEN '+@lDataTypeId+'=4 THEN
						ISNULL(SAF.'+@rSubCategory+',''0001/01/01'')
						END AS SubCategory
							FROM 
							sStudent.vStudentAcademic SA
							LEFT JOIN sStudent.tStudentFamily SAF ON SAF.StudentId=SA.StudentId
							Where SA.OrgId='+CAST(@rOrgId AS nvarchar(15))
							+'AND (SA.ClassId='+CAST(@rClassId AS nvarchar(15))+ 'OR '+CAST(@rClassId AS nvarchar(15))+'=0)
							AND (SA.DivisionId='+CAST(@rDivisionId AS nvarchar(15))+ 'OR '+CAST(@rDivisionId AS nvarchar(15))+'=0)
							AND (SA.StatusId='+ CAST(@rStatusId AS nvarchar(15)) +' OR '+CAST(@rStatusId AS nvarchar(15))+'=0)
							AND 
							('+CAST(@rIsBlank AS nvarchar(1))+'=0 
								OR ('+@lDataTypeId+'=1 AND ISNULL(SAF.'+@rSubCategory+','''')='''')
								OR ('+@lDataTypeId+'=2 AND ISNULL(SAF.'+@rSubCategory+',''0'')=''0'')
								OR ('+@lDataTypeId+'=3 AND ISNULL(SAF.'+@rSubCategory+',''False'')=''False'')
								OR ('+@lDataTypeId+'=4 AND ISNULL(SAF.'+@rSubCategory+',''0001/01/01'')=''0001/01/01'') 
							)'
				   
					WHEN 5 THEN --Health
					   'Select SA.StudentId,SA.AcademicId,SA.Code,SA.Name,SA.ClassName+'' - ''+SA.DivisionName AS ClassDivision,SA.RollNo,
						CASE WHEN '+@lDataTypeId+'=1 THEN
						ISNULL(SAH.'+@rSubCategory+','''')
						WHEN '+@lDataTypeId+'=2 THEN
						ISNULL(SAH.'+@rSubCategory+',''0'')
						WHEN '+@lDataTypeId+'=3 THEN
						ISNULL(SAH.'+@rSubCategory+',''False'')
						WHEN '+@lDataTypeId+'=4 THEN
						ISNULL(SAH.'+@rSubCategory+',''0001/01/01'')
						END AS SubCategory
							FROM 
							sStudent.vStudentAcademic SA
							LEFT JOIN sStudent.tStudentHealth SAH ON SAH.StudentId=SA.StudentId
							Where SA.OrgId='+CAST(@rOrgId AS nvarchar(15))
							+'AND (SA.ClassId='+CAST(@rClassId AS nvarchar(15))+ 'OR '+CAST(@rClassId AS nvarchar(15))+'=0)
							AND (SA.DivisionId='+CAST(@rDivisionId AS nvarchar(15))+ 'OR '+CAST(@rDivisionId AS nvarchar(15))+'=0)
							AND (SA.StatusId='+ CAST(@rStatusId AS nvarchar(15)) +' OR '+CAST(@rStatusId AS nvarchar(15))+'=0)
							AND 
							('+CAST(@rIsBlank AS nvarchar(1))+'=0 
								OR ('+@lDataTypeId+'=1 AND ISNULL(SAH.'+@rSubCategory+','''')='''')
								OR ('+@lDataTypeId+'=2 AND ISNULL(SAH.'+@rSubCategory+',''0'')=''0'')
								OR ('+@lDataTypeId+'=3 AND ISNULL(SAH.'+@rSubCategory+',''False'')=''False'')
								OR ('+@lDataTypeId+'=4 AND ISNULL(SAH.'+@rSubCategory+',''0001/01/01'')=''0001/01/01'') 
							)'
					WHEN 6 THEN --Academic Detail
					   'Select SA.StudentId,SA.AcademicId,SA.Code,SA.Name,SA.ClassName+'' - ''+SA.DivisionName AS ClassDivision,SA.RollNo,
						CASE WHEN '+@lDataTypeId+'=1 THEN
						ISNULL(AD.'+@rSubCategory+','''')
						WHEN '+@lDataTypeId+'=2 THEN
						ISNULL(AD.'+@rSubCategory+',''0'')
						WHEN '+@lDataTypeId+'=3 THEN
						ISNULL(AD.'+@rSubCategory+',''False'')
						WHEN '+@lDataTypeId+'=4 THEN
						ISNULL(AD.'+@rSubCategory+',''0001/01/01'')
						END AS SubCategory
							FROM 
							sStudent.vStudentAcademic SA
							LEFT JOIN sStudent.tAcademicDetail AD ON AD.AcademicId=SA.AcademicId
							Where SA.OrgId='+CAST(@rOrgId AS nvarchar(15))
							+'AND (SA.ClassId='+CAST(@rClassId AS nvarchar(15))+ 'OR '+CAST(@rClassId AS nvarchar(15))+'=0)
							AND (SA.DivisionId='+CAST(@rDivisionId AS nvarchar(15))+ 'OR '+CAST(@rDivisionId AS nvarchar(15))+'=0)
							AND (SA.BatchId='+CAST(@rBatchId AS nvarchar(15))+')
							AND (SA.StatusId='+ CAST(@rStatusId AS nvarchar(15)) +' OR '+CAST(@rStatusId AS nvarchar(15))+'=0)
							AND 
							('+CAST(@rIsBlank AS nvarchar(1))+'=0 
								OR ('+@lDataTypeId+'=1 AND ISNULL(AD.'+@rSubCategory+','''')='''')
								OR ('+@lDataTypeId+'=2 AND ISNULL(AD.'+@rSubCategory+',''0'')=''0'')
								OR ('+@lDataTypeId+'=3 AND ISNULL(AD.'+@rSubCategory+',''False'')=''False'')
								OR ('+@lDataTypeId+'=4 AND ISNULL(AD.'+@rSubCategory+',''0001/01/01'')=''0001/01/01'') 
							)'
					END
	--	print @Sql    
	    
	   EXECUTE  sp_executesql @Sql
END
GO
PRINT N'Altering [sStudent].[pStudentFullProfileGet]...';


GO

ALTER PROCEDURE [sStudent].[pStudentFullProfileGet]
	 
	 @rBatchId int,
	 @rStudentId bigint
	 --@rIsSearch bit
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	
	SELECT 
			--Academic
			SA.StudentId AS Id,
			SA.FirstName + ' ' + ISNULL(SA.MiddleName,'') + ' ' + 	SA.LastName AS StudentName,
			SA.Batch AS AcademicYear,
			ISNULL(SA.Code,' - ') AS Code,
			SA.ClassDivision AS ClassDiv,			
			SA.RollNo,
			ISNULL(SM.Title,'-') AS House,
			--Other
			ISNULL(SA.DateOfBirth,'0001/01/01') AS DateOfBirth,
			ISNULL(SA.BirthTaluka,'') AS BirthTaluka,
			ISNULL(SA.BirthPlace,'') AS BirthPlace,	
			ISNULL(SA.BirthDistrict,'') AS BirthDistrict,
			ISNULL(SA.BirthDateInWord,'') AS BirthDateInWord,
			ISNULL(SA.Gender,'') AS Gender,
			ISNULL(SA.Religion,'') AS Religion,
			--Admission			
			ISNULL(SA.AdmissionStandard,'') AS AdmissionStandard,
			ISNULL(SA.AdmissionDate,'0001/01/01') AS AdmissionDate,
		 
			ISNULL(SA.PreviousSchool,'') AS PreviousSchool,
			ISNULL(SA.AdmissionCategory,'') AS StudentAdmissionCategory,
			ISNULL(SA.LeftDate,'0001/01/01') AS LeftDate,			 
			ISNULL(SA.LeftStandard,'') AS LeftStandard,
			ISNULL(SA.InactiveDate,'0001/01/01') AS InactiveDate,		
			ISNULL(SA.LCNumber,'') AS LCNumber,
			ISNULL(SA.LCDate,'0001/01/01') AS LCDate,
			 
			--Communication
			ISNULL(SC.PresentStreetone,'') + ' ' + ISNULL(SC.PresentStreetTwo,'') + ' ' + ISNULL(SC.PresentStreetThree,'') AS PresentAddress,
			ISNULL(SC.PresentCity,'') AS PresentCity,
			ISNULL(SC.PresentState,'') AS PresentState,
			ISNULL(SC.PresentCountry,'') AS PresentCountry,
			ISNULL(SC.PresentZipCode,'') AS PresentZipCode,
			ISNULL(SC.PresentContactNo,'') AS PresentContactNo,
			
			ISNULL(SC.EmergencyStreetOne,'') + ' ' + ISNULL(SC.EmergencyStreetTwo,'') + ' ' + ISNULL(SC.EmergencyStreetThree,'') AS EmergencyAddress,
			ISNULL(SC.EmergencyCity,'') AS EmergencyCity,
			ISNULL(SC.EmergencyState,'') AS EmergencyState,
			ISNULL(SC.EmergencyCountry,'') AS EmergencyCountry,
			ISNULL(SC.EmergencyZipCode,'') AS EmergencyZipCode,
			ISNULL(SC.EmergencyContactNo,'') AS EmergencyContactNo,
			
			ISNULL(SC.PermanentStreetOne,'') + ' ' + ISNULL(SC.PermanentStreetTwo,'') + ' ' + ISNULL(SC.PermanentStreetThree,'') AS PermanentAddress,
			ISNULL(SC.PermanentCity,'') AS PermanentCity,
			ISNULL(SC.PermanentState,'') AS PermanentState,
			ISNULL(SC.PermanentCountry,'') AS PermanentCountry,
			ISNULL(SC.PermanentZipCode,'') AS PermanentZipCode,
			ISNULL(SC.PermanentContactNo,'') AS PermanentContactNo,
			--Parent Information
			ISNULL(SF.FatherName,'') AS FatherName,
			ISNULL(SF.FatherOccupation,'') AS FatherOccupation,
			ISNULL(SF.FatherQualification,'') AS FatherQualification,
			ISNULL(SF.FatherContactNo,'') AS FatherContactNo,
			ISNULL(SF.FatherMail,'') AS FatherMail,
			ISNULL(SF.FatherOfficeAddress,'') AS FatherOfficeAddress,
			
			ISNULL(SF.MotherName,'') AS MotherName,
			ISNULL(SF.MotherOccupation,'') AS MotherOccupation,
			ISNULL(SF.MotherQualification,'') AS MotherQualification,
			ISNULL(SF.MotherContactNo,'') AS MotherContactNo,
			ISNULL(SF.MotherMail,'') AS MotherMail,
			ISNULL(SF.MotherOfficeAddress,'') AS MotherOfficeAddress,
			
			ISNULL(SF.RelationshipName,'') AS RelationShip,
			ISNULL(SF.RelativeName,'') AS RelativeName,
			ISNULL(SF.RelativeOccupation,'') AS RelativeOccupation,
			ISNULL(SF.RelativeQualification,'') AS RelativeQualification,
			ISNULL(SF.RelativeContactNo,'') AS RelativeContactNo,
			ISNULL(SF.RelativeMail,'') AS RelativeMail,
			ISNULL(SF.RelativeOfficeAddress,'') AS RelativeOfficeAddress,
			
			
			--Health Information
			ISNULL(SA.BloodGroup,'') AS BloodGroup,
			ISNULL(SH.IdentificationMark1,'')+' '+ISNULL(SH.IdentificationMark2,'') as IdentificationMark,
			
			ISNULL(SH.FamilyDoctorName,'') AS FamilyDoctorName,
			ISNULL(SH.FamilyDoctorContactNo,'') AS FamilyDoctorContactNo,
			
			ISNULL(SH.IsPysicalDeformity,0) AS IsPysicalDeformity,
			ISNULL(SH.PysicalDeformityRemark,'') AS PysicalDeformityRemark,
			ISNULL(SH.IsMajorIllness,0) AS IsMajorIllness,
			ISNULL(SH.MajorIllnessRemark,'') As MajorIllnessRemark,
			ISNULL(SH.IsAllergy,0) AS IsAllergy,
			ISNULL(SH.AllergyRemark,'') As AllergyRemark,
			ISNULL(SH.IsPastHistory,0) As IsPastHistory ,
			ISNULL(SH.PastHistoryRemark,'') As PastHistoryRemark,
			--Hostel
			ISNULL(RM.Title,'') AS RoomNo,			
			ISNULL(HM.Title,'') AS Hostel,
			ISNULL(EMW.FirstName,'')+' '+ISNULL(EMW.LastName,'') AS WardenName,
			ISNULL(ECW.PhoneNoCompany,'') As WardenPhoneNo,
			ISNULL(ECW.ExtensionNo,'') AS WardenExtNo,
			ISNULL(ECW.MobileNumber,'') AS WardenMobileNo,
			ISNULL(EMA.FirstName,'')+' '+ISNULL(EMA.LastName,'') AS AssignedRoomBy,	
			ISNULL(ECA.PhoneNoCompany,'') AS AssignedRoomByPhoneNo,
			ISNULL(ECA.ExtensionNo,'') AS AssignedRoomByExtNo,
			ISNULL(ECA.MobileNumber,'') AS AssignedRoomByMobileNo,
			--Notification Details
			ISNULL(SC.ParentEmail,'') AS ParentEmail,
			ISNULL(SC.ParentContactNo,'') As ParentContactNo,
			ISNULL(SC.StudentEmail,'') AS StudentEmail,
			ISNULL(SC.StudentContactNo,'') AS StudentContactNo,
					
	   	    ISNULL(SA.StudentPhoto, CONVERT(VARBINARY(MAX), 0)) AS StudentPhoto,
		    --Transport Details
		    VM.Title AS VehicleName,
		    VM.RegistrationNumber AS VehicleRegistrationNumber,
		    VM.TypeOfVehicle,
		    ISNULL(BRM.Title,'') AS BusRoute,
		    BRM.DriverName,
		    BRM.DriverMobileNo,
		    BRM.ConductorName,
		    BRM.ConductorMobileNo,
		    ISNULL(BRDM.Title,'') AS BusRouteDestination,
		    
		    VM.Title AS DropVehicleName,
		    VM.RegistrationNumber AS DropVehicleRegistrationNumber,
		    VM.TypeOfVehicle AS DropTypeOfVehicle,
		    ISNULL(BRM1.Title,'') AS DropRoute,
		    BRM1.DriverName AS DropRouteDriverName,
		    BRM1.DriverMobileNo AS DropRouteDriverMobileNo,
		    BRM1.ConductorName AS DropRouteConductorName,
		    BRM1.ConductorMobileNo AS DropRouteConductorMobileNo,
		    ISNULL(BRDM1.Title,'') AS DropDestination,
		    
		    --ClassTeacher Details
		    ISNULL(EMT.Id,0) AS TeacherId,
		    EMT.FirstName+' '+EMT.MiddleName+' '+EMT.LastName AS TeacherFullName,
		    EDM.Title AS TeacherDesignation,
		    EPD.Qualification AS TeacherQualification,
		    ISNULL(EI.EmployeePhoto, CONVERT(VARBINARY(MAX), 0)) AS TeacherPhoto
  FROM 
           sStudent.vStudentAllDetail SA
           LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
           LEFT JOIN sStudent.tStudentHealth SH ON SA.StudentId=SH.StudentId
           LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SA.StudentId 
           
           LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId = SA.StudentId
          
           LEFT JOIN sActivity.tHouseMaster SM ON SM.ID = SO.HouseId
           LEFT JOIN sHostel.tAssignRoom AR ON AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003
           LEFT JOIN sHostel.tRoomMaster RM ON RM.Id=AR.RoomId
           LEFT JOIN sHostel.tHostelMaster HM ON HM.Id=RM.HostelId
           LEFT JOIN sHostel.tHostelWarden HW ON HW.HostelId=HM.Id
           LEFT JOIN sHrm.tEmployeeMaster EMW ON HW.EmployeeId=EMW.Id
           LEFT JOIN sHrm.tEmployeeMaster EMA ON RM.AssignedEmployeeId=EMA.Id
           LEFT JOIN sHrm.tEmployeeCommunications ECW ON EMW.Id=ECW.EmployeeId 
           LEFT JOIN sHrm.tEmployeeCommunications ECA ON  EMA.Id=ECA.EmployeeId
           LEFT JOIN sTransport.tAssignRoute AR1 ON AR1.SourceId=SA.StudentId AND AR1.SourceTypeId=2003
           LEFT JOIN sTransport.tBusRouteDestinationMaster BRDM ON BRDM.Id=AR1.PickupDestinationId
           LEFT JOIN sTransport.tBusRouteMaster BRM ON BRM.Id=BRDM.BusRouteId
           LEFT JOIN sTransport.tVehicleMaster VM ON VM.Id=BRM.VehicleId
           LEFT JOIN sTransport.tBusRouteDestinationMaster BRDM1 ON BRDM1.Id=AR1.DropDestinationId
           LEFT JOIN sTransport.tBusRouteMaster BRM1 ON BRM1.Id=BRDM1.BusRouteId
           LEFT JOIN sTransport.tVehicleMaster VM1 ON VM1.Id=BRM1.VehicleId
           
           LEFT JOIN sSetup.tDivisionMaster DM ON  DM.Id=SA.DivisionId
           LEFT JOIN sHrm.tEmployeeMaster EMT ON EMT.Id=DM.InchargeEmployeeId
           LEFT JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EMT.Id
           LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id=EJD.EmployeeDesignationId
           LEFT JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId=EMT.Id
           LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId=EMT.Id
             
  WHERE 
			((SA.StudentId=@rStudentId)OR(@rStudentId=0))
			AND(SA.BatchId=@rBatchId)
			
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
	
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
		)
	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()
		)
		--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
		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)
	
		SELECT 
			* into sStudent.tTempStudent
		FROM sStudent.vStudentCustomSearch SCS
		WHERE 
			SCS.OrgId = @rOrgId 
			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 ((SCS.IsPysicalDeformity=@rIsPysicalDeformity) OR (@rIsPysicalDeformity=0))
		    AND ((SCS.IsMajorIllness=@rIsMajorIllness) OR (@rIsMajorIllness=0)) 
			
		SET @rColumnName=Replace(@rColumnName,',Code',',Code AS [ID No]')
		--SET @rOrderBy=Replace(@rOrderBy,',Code',',Code AS [ID No]')
		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
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		--SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sStudent].[pXMLStudentMasterUpdate]...';


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

SET NOCOUNT ON

BEGIN
SET @rXmlDoc=REPLACE(@rXmlDoc,'&','AND')

DECLARE @lInterrorCode INT,	@intDoc INT

BEGIN TRY
BEGIN TRANSACTION	

	EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc
	-----------------------
	Update sStudent.tStudentMaster
	SET		
		FirstName = A.FirstName,
		MiddleName = A.MiddleName,
		LastName=A.LastName,
		OrgId=A.OrgId,
		StatusId=A.StatusId,
		Number = A.GrNo
	FROM	
	(	SELECT FirstName,MiddleName,LastName,OrgId,
		CASE WHEN StatusId1=1 AND StatusId2=0 THEN 1
			 WHEN StatusId1=0 AND StatusId2=0 THEN 2
			 WHEN StatusId1=0 AND StatusId2=1 THEN 3 END AS StatusId,
			 GrNo,	sCommon.fGetBigIntIdForOrg(StudentId,@rOrgId) AS StudentId
	FROM OPENXML (@intDoc, '/Table/StudentMaster', 1)
	WITH(		
		FirstName nvarchar(50) ,
		MiddleName nvarchar(50) ,
		LastName  nvarchar(50) ,
		OrgId int ,
		StatusId1 tinyint ,
		StatusId2 tinyint ,
		GrNo int ,
		StudentId bigint )) A
		
	Where sStudent.tStudentMaster.Id = A.StudentId 
  
	------- Student Academic
	Update sStudent.tAcademic
	SET
		ClassId=A.ClassId,
		DivisionId=A.DivisionId,
		RollNo=A.RollNo,
		OrgId=A.OrgId
	FROM
	(
	SELECT 	sCommon.fGetBigIntIdForOrg(StudentId,@rOrgId) AS StudentId,ClassId,DivisionId,RollNo,OrgId		
	FROM OPENXML (@intDoc, '/Table/StudentMaster', 1)
	WITH
	(
		StudentId bigint  ,
		ClassId int ,
		DivisionId int ,
		RollNo int ,
		OrgId smallint 
	)) A
	Where sStudent.tAcademic.StudentId = A.StudentId 
	EXEC sp_xml_removedocument @intDoc
	COMMIT TRANSACTION
	SELECT 1
	END TRY
	BEGIN CATCH
	SELECT -1
	END CATCH

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


		
-- 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)

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





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


GO
ALTER PROCEDURE [sTransport].[pAssignRouteAdd]
	 
	@rSourceTypeId smallint,
	@rSourceId bigint,
	@rPickupDestinationId int,
	@rDropDestinationId int,
	@rIsDeleted bit
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
If(@rIsDeleted=1)
BEGIN
	Delete from sTransport.tAssignRoute where SourceTypeId=@rSourceTypeId
AND SourceId=@rSourceId
	Select @rSourceId as Result
END	
ELSE
BEGIN

	BEGIN TRY
	
	 BEGIN TRANSACTION	
 IF NOT EXISTS(Select Top(1)* From sTransport.tAssignRoute where SourceTypeId=@rSourceTypeId AND SourceId=@rSourceId)
BEGIN

	DECLARE @lNextNumber BIGINT    
	SET @lNextNumber = @rSourceId 
	
	INSERT INTO sTransport.tAssignRoute
		(
			SourceTypeId,
			SourceId,
			PickupDestinationId,
			DropDestinationId
		)
	VALUES
		(
			@rSourceTypeId,
			@rSourceId,
			@rPickupDestinationId,
			@rDropDestinationId
		)
		             
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rSourceId
	    UPDATE  sTransport.tAssignRoute
	    SET
			PickupDestinationId=@rPickupDestinationId,
			DropDestinationId=@rDropDestinationId
			
	      WHERE SourceTypeId = @rSourceTypeId AND SourceId = @rSourceId 	   
	 END  
		SELECT @lNextNumber AS Result
		
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END
END
GO
PRINT N'Altering [sTransport].[pAssignRouteGet]...';


GO

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

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

SELECT  
		SM.Id as SourceId,
		SM.Code,
		SM.FirstName+' '+SM.LastName as Name,
		CM.Title+'-'+DM.Title as ClassDivisionName,
		ISNULL(BRDM.BusRouteId,0) BusRouteId,
		ISNULL(AR.PickupDestinationId,0) BusRouteDestinationId,
		ISNULL(BRDM2.BusRouteId,0) DropRouteId,
		ISNULL(AR.DropDestinationId,0) DropDestinationId,
		O.DisplayTitle AS Organization
	 
	 
		
  FROM sStudent.tAcademic A
	INNER JOIN sStudent.tStudentMaster SM ON A.StudentId=SM.Id AND SM.StatusId=1	
	INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
	INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
    LEFT JOIN sTransport.tAssignRoute AR ON AR.SourceId=A.StudentId 
	LEFT JOIN sTransport.tBusRouteDestinationMaster BRDM ON BRDM.Id=AR.PickupDestinationId
	LEFT JOIN sTransport.tBusRouteDestinationMaster BRDM2 ON BRDM2.Id=AR.DropDestinationId
	INNER JOIN sSetup.tOrganizationMaster O ON O.Id = A.OrgId
	
        
  WHERE 
		(A.ClassId=@rClassId OR @rClassId=0)
	AND (A.DivisionId=@rDivisionId OR @rDivisionId=0)
	AND (BRDM.Id=@rBusRouteDestinationId OR @rBusRouteDestinationId=0) 
	AND (BRDM2.Id=@rBusRouteDestinationId OR @rBusRouteDestinationId=0)
	AND (BRDM.BusRouteId=@rBusRouteId OR @rBusRouteId=0) 
	AND (BRDM2.BusRouteId=@rBusRouteId OR @rBusRouteId=0)
	AND (BRDM.Title Like @rBusRouteDestination OR ISNULL(@rBusRouteDestination,'') = '')
	AND (BRDM2.Title Like @rBusRouteDestination OR ISNULL(@rBusRouteDestination,'') = '')
	AND (A.Id = @rStudentId OR ISNULL(@rStudentId,0) = 0)
	AND (SM.Code = @rStudentCode  OR ISNULL(@rStudentCode,'')='')
	AND ((SM.FirstName + ' ' + SM.LastName) like @rStudentName + '%' OR ISNULL(@rStudentName,'') = '')	
	AND (A.OrgId = @rOrgId OR @rOrgId = 0)
	AND (A.BatchId=@rOrgGroupBatchId)
END
GO
PRINT N'Altering [sTransport].[pBusRouteDestinationMasterGet]...';


GO
ALTER PROCEDURE [sTransport].[pBusRouteDestinationMasterGet]
	 @rBusRouteId int
	 --@rCode nvarchar(20),
	 --@rOrgId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 		
		
	 --IF(@rIsSearch=1)
		--BEGIN
			--SET @rGRNo = sCommon.fSearchStringGet(@rGRNo)
			--SET @rLastName = sCommon.fSearchStringGet(@rLastName)
			--SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
		--END
	
	SELECT 
			BRDM.Id,
			BRDM.BusRouteID,
			BRDM.Title,
			BRM.Title as BusRoute,
			BRM.Remark,
			BRM.DriverName,
			BRM.DriverMobileNo, 
			BRM.ConductorName,
			BRM.ConductorMobileNo, 
			BRM.VehicleId,
			BRM.OrderIndex as BusRouteOrderIndex,
			BRM.IsObsolete as BusRouteIsObsolete,
			BRDM.Amount,
			BRDM.OrderIndex,
			BRDM.IsObsolete
			
  FROM 
			[sTransport].[tBusRouteDestinationMaster]  BRDM
			INNER JOIN [sTransport].[tBusRouteMaster] BRM ON BRM.Id=BRDM.BusRouteId  
WHERE 
			--((CM.Code=@rCode) OR (ISNULL(@rCode,'') = ''))
			(BRDM.BusRouteId=@rBusRouteId OR @rBusRouteId=0)
			--AND CM.OrgID=@rOrgId 
			order by BRDM.OrderIndex
END
GO
PRINT N'Altering [sTransport].[pBusRouteMasterAdd]...';


GO

ALTER PROCEDURE [sTransport].[pBusRouteMasterAdd]
	 
	        @rId int
	       ,@rTitle nvarchar(100)
	       ,@rRemark nvarchar(100)
	       ,@rDriverName nvarchar(50)
	       ,@rDriverMobileNo nvarchar(20)
	       ,@rConductorName nvarchar(50)
	       ,@rConductorMobileNo nvarchar(20)
	       ,@rVehicleId int
	       ,@rOrderIndex smallint
           ,@rIsObsolete bit
           ,@rCreatedUserId bigint           
           ,@rOrgGroupId int
           ,@rOrgGroupBatchId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	IF(@rId = 0)	
	BEGIN
		--If Exists(select Id from sTransport.tBusRouteMaster where Code=@rCode AND OrgGroupBatchId=@rOrgGroupBatchId)
		--	BEGIN
		--	select -102 as Result
		--	RETURN
		--END 
	
		If Exists(select Id from sTransport.tBusRouteMaster where Title=@rTitle AND OrgGroupBatchId=@rOrgGroupBatchId)
			BEGIN
			select -103 as Result
			RETURN
		END 
	END
	ELSE
	BEGIN
		--If Exists(select Id from sTransport.tBusRouteMaster where Code=@rCode AND OrgGroupBatchId=@rOrgGroupBatchId AND Id<>@rId)
		--Begin
		--	select -102 as Result
		--	RETURN
		--End
		If  Exists(select Id from sTransport.tBusRouteMaster where Title=@rTitle AND OrgGroupBatchId=@rOrgGroupBatchId AND Id<>@rId)
		Begin
			select -103 as Result
			RETURN
		End

	END
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber INT 
	

IF(@rId = 0)	
BEGIN
	--EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sTransport.tBusRouteMaster',@lNextNumber = @lNextNumber output
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sTransport.tBusRouteMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	
	INSERT INTO [sTransport].[tBusRouteMaster]
			   (
			    [Id]
			   ,[Title]
			   ,[Remark] 
			   ,[DriverName] 
			   ,[DriverMobileNo] 
			   ,[ConductorName] 
			   ,[ConductorMobileNo] 
			   ,[VehicleId] 
			   ,[OrderIndex]
			   ,[IsObsolete]
			   ,[CreatedUserId]
			   ,[CreatedDateTime]
			   ,[UpdatedUserId]
			   ,[UpdatedDateTime]
			   --,[OrgId]
			   ,[OrgGroupBatchId]
			   ,OrgGroupId 
			   )
		 VALUES
			   (
				@lNextNumber
			   --,@rCode
			   ,@rTitle
			   ,@rRemark
			   ,@rDriverName
			   ,@rDriverMobileNo
			   ,@rConductorName
			   ,@rConductorMobileNo 
			   ,@rVehicleId 
			   ,@rOrderIndex
			   ,@rIsObsolete
			   ,@rCreatedUserId
			   ,sCommon.fGetDate()
			   ,0
			   ,sCommon.fGetDate()
			   --,@rOrgId
			   ,@rOrgGroupBatchId
			   ,@rOrgGroupId
			   )
		    SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION         
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  [sTransport].[tBusRouteMaster] 
	    SET
			  Title=@rTitle
			 ,Remark=@rRemark
			 ,DriverName=@rDriverName 
			 ,DriverMobileNo=@rDriverMobileNo
			 ,ConductorName=@rConductorName
			 ,ConductorMobileNo=@rConductorMobileNo
			 ,VehicleId=@rVehicleId
			 ,OrderIndex=@rOrderIndex
	         ,[IsObsolete] = @rIsObsolete                          
             ,[UpdatedUserId] = @rCreatedUserId
             ,[UpdatedDateTime] = sCommon.fGetDate()    
             ,OrgGroupId = @rOrgGroupId      
             
	      WHERE Id = @rId 	    
	      SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION
	 END  	
COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sTransport].[pBusRouteMasterGet]...';


GO

ALTER PROCEDURE [sTransport].[pBusRouteMasterGet]
          
           --@rId bigint,
           @rTitle nvarchar(100),
           --@rOrgId int
           @rOrgGroupId int
           --@rIsWildCardSearch bit
          
AS
SET NOCOUNT ON

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

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
     
  FROM [sTransport].[tBusRouteMaster] BRM 
        
  WHERE 
	--	 CCM.Id = @rId OR @rId = 0
	--AND 
	((BRM.Title Like @rTitle)OR(ISNULL(@rTitle,'') = ''))
	--AND  CCM.OrgId = @rOrgId 
	AND BRM.OrgGroupId=@rOrgGroupId
	--AND  CCM.IsObsolete = 0
    order by BRM.OrderIndex
END
GO
PRINT N'Altering [sTransport].[pRptRoutewiseStudentListGet]...';


GO





ALTER PROCEDURE [sTransport].[pRptRoutewiseStudentListGet]
	 
	
	 
	 @rOrgGroupBatchId int,
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rClassId int,
	 @rDivisionId int,
	 @rRouteId int,
	 @rDestinationId int
	 
	 
	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,
			CM.DisplayTitle AS Class,
			DM.DisplayTitle AS Division,
			BRDM.Title AS DestinationPoint,
			BRM.Title AS BusRoute,
			A.RollNo,
			VM.Title AS Vehicle,
			VM.NoOfSeats,
			BRM.OrderIndex AS RouteOrder,
			BRDM.OrderIndex AS PickupOrder
			
			
			
      
	FROM 
			sTransport.tAssignRoute AR
			INNER JOIN sStudent.tAcademic A ON A.StudentId=AR.SourceId
			INNER JOIN sStudent.tStudentMaster SM ON A.StudentId=SM.Id 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 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 ((CM.Id=@rClassId) OR (@rClassId=0))
			AND ((DM.Id=@rDivisionId) OR (@rDivisionId=0))
			AND ((BRM.Id=@rRouteId) OR (@rRouteId=0))
			AND ((BRDM.Id=@rDestinationId) OR (@rDestinationId=0))
			
		
		
		
	END
GO
PRINT N'Altering [sTransport].[pTransportFeeUpdate]...';


GO
ALTER PROCEDURE [sTransport].[pTransportFeeUpdate]
	 
	@rClassId int, 
	@rFeeHeadId int,
	@rCreatedUserId bigint,
	@rOrgId int,
	@rBatchId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION
	 
	UPDATE FA
	    SET
				VariableAmount=BRDM.Amount,
				UpdatedUserId=@rCreatedUserId,
				UpdatedDateTime=sCommon.fGetDate() 
		FROM 
				sFee.tFeeAllocation FA
			INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=FA.SourceId AND SA.StatusId=1
				AND SA.OrgId=@rOrgId AND SA.BatchId=@rBatchId AND (SA.ClassId=@rClassId OR @rClassId=0)
			INNER JOIN sTransport.tAssignRoute AR ON AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003
			INNER JOIN sTransport.tBusRouteDestinationMaster BRDM ON BRDM.Id=AR.PickupDestinationId
			INNER JOIN sFee.tFeeSetup FS ON FS.Id=FA.FeeSetupId
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS.FeeId AND (FM.FeeHeadId=@rFeeHeadId OR @rFeeHeadId=0)
	      
	    WHERE 
				FA.SourcetypeId = 2001
			--AND FA.SourceId IN(SELECT SourceId FROM sFee.tFeeAllocation WHERE FeeSetupId=@rFeeSetupId OR @rFeeSetupId=0)

	INSERT INTO sFee.tFeeAllocation
		(
				SourceTypeId,
				SourceId,
				FeeSetupId,
				VariableAmount,
				DiscountAmount,
				CreatedUserId,
				CreatedDateTime
		)
		SELECT 
				2001,
				SA.AcademicId,
				FS.Id,
				BRDM.Amount,
				0.00,
				@rCreatedUserId,
				sCommon.fGetDate()
		FROM
				sTransport.tAssignRoute AR
			INNER JOIN sTransport.tBusRouteDestinationMaster BRDM ON BRDM.Id=AR.PickupDestinationId
			INNER JOIN sStudent.vStudentAcademic SA ON SA.StudentId=AR.SourceId AND SA.StatusId=1
				AND SA.OrgId=@rOrgId AND SA.BatchId=@rBatchId AND (SA.ClassId=@rClassId OR @rClassId=0) AND AR.SourceTypeId=2003
			INNER JOIN sFee.tFeeOptional FA ON FA.SourceId=SA.AcademicId 
				AND FA.BatchId=@rBatchId AND FA.SourceTypeId=2001 
				AND FA.SourceId NOT IN(
				SELECT FA1.SourceId FROM sFee.tFeeAllocation FA1 
					INNER JOIN sFee.tFeeSetup FS1 ON FS1.Id=FA1.FeeSetupId AND FS1.BatchId=@rBatchId 
					INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId AND (FM.FeeHeadId=@rFeeHeadId OR @rFeeHeadId=0))
			INNER JOIN sFee.tFeeSetup FS ON FS.Id=FA.FeeSetupId AND FS.BatchId=@rBatchId 
		
		  SELECT 1 AS Result    
		
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Creating [sAttendance].[pCheckHoliday]...';


GO
CREATE PROCEDURE [sAttendance].[pCheckHoliday]
	 
	@rDivisionId int,
	@rAttendanceDate date,
	@rBatchId int
	
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

 IF Exists(SELECT ES.Id FROM  
 sActivity.tEventSchedule ES INNER JOIN sActivity.tEventAssign EA
 ON ES.Id = EA.EventScheduleId 
 WHERE
 ES.FromDate = @rAttendanceDate
 AND SourceTypeId = 2005
 AND SourceId = @rDivisionId
 AND ES.IsHoliday = 1
 AND ES.BatchId = @rBatchId
  )
 SELECT 1 AS Result
 ELSE
 SELECT 0 AS Result
 
 
END
GO
PRINT N'Creating [sAttendance].[pMonthlyRegisterImportAll]...';


GO
CREATE PROCEDURE [sAttendance].[pMonthlyRegisterImportAll]
	 	 
	 	 @rBatchId int,
	 	 @rForMonth tinyint,
	 	 @rForYear smallint,
	 	 @rAttendanceTypeId tinyint,
	 	 @rSubjectId int,
	 	 @rCreatedUserId bigint
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	BEGIN TRY
	
	BEGIN TRANSACTION
	
	SELECT 
			SN.AcademicId 
	INTO 
			#tTable1
	FROM 
			sStudent.vStudentName SN
		INNER JOIN sAttendance.tMonthlyRegister MR ON MR.AcademicId=SN.AcademicId 
			AND	SN.BatchId=@rBatchId
			AND	MR.ForMonth=@rForMonth
			AND	MR.ForYear=@rForYear
			AND	MR.AttendanceTypeId=@rAttendanceTypeId
			AND	MR.SubjectId=@rSubjectId
	
	INSERT INTO sAttendance.tMonthlyRegister
	(
		AcademicId,
		AttendanceTypeId,
		SubjectId,
		ForMonth,
		ForYear,
		TotalCount,
		PresentCount,
		AbsentCount,
		AbsentDays,
		UpdatedUserId,
		UpdatedDateTime
	)
	Select 
		SN.AcademicId,
		@rAttendanceTypeId,
		@rSubjectId,
		MY.MonthNumber AS ForMonth, 
		MY.YearNumber AS ForYear,
		CASE 
			WHEN SS.WorkingDays IS NOT NULL
			THEN ISNULL(SS.WorkingDays,0)
			ELSE ISNULL(MS.WorkingDays,0) END AS TotalCount,
		(Select COUNT(1) FROM sAttendance.tStudentRegister SR1 WHERE SR1.AcademicId=SN.AcademicId 
			AND SR1.IsPresent=1 
			AND SR1.AttendanceTypeId=@rAttendanceTypeId
			AND ((SR1.SubjectId=@rSubjectId) OR (ISNULL(@rSubjectId,0)=0))
			AND DATEPART(MONTH,SR1.AttendanceDate)=@rForMonth 
			AND DATENAME(YEAR,SR1.AttendanceDate)=@rForYear) 
		AS PresentCount,
		(Select COUNT(1) FROM sAttendance.tStudentRegister SR2 WHERE SR2.AcademicId=SN.AcademicId 
			AND SR2.IsPresent=0 
			AND SR2.AttendanceTypeId=@rAttendanceTypeId
			AND ((SR2.SubjectId=@rSubjectId) OR (ISNULL(@rSubjectId,0)=0))
			AND DATEPART(MONTH,SR2.AttendanceDate)=@rForMonth 
			AND DATENAME(YEAR,SR2.AttendanceDate)=@rForYear) 
		AS AbsentCount,
		(SELECT [sAttendance].[fAbsentDaysGet](@rForMonth,@rForYear, @rAttendanceTypeId,@rSubjectId,SN.AcademicId) AS MyResult) 
		AS AbsentDays,
		@rCreatedUserId,
		sCommon.fGetDate()
	From 
		sStudent.vStudentName SN 
	LEFT JOIN sSetup.fMonthYearForBatchGET(@rBatchId) AS MY ON MY.BatchId=SN.BatchId
		AND MY.MonthNumber=@rForMonth AND MY.YearNumber=@rForYear
	LEFT JOIN sAttendance.tMonthlySetup MS ON MS.ClassId=SN.ClassId
		AND MS.ForMonth=MY.MonthNumber AND MS.ForYear=MY.YearNumber
	LEFT JOIN sAttendance.tStudentSetup SS ON SS.AcademicId=SN.AcademicId
		AND SS.ForMonth=MY.MonthNumber AND SS.ForYear=MY.YearNumber
	WHERE
		(MY.BatchId=@rBatchId)
	AND SN.AcademicId NOT IN(SELECT AcademicId FROM #tTable1)
	
	UPDATE sAttendance.tMonthlyRegister
SET 
		TotalCount=(CASE 
			WHEN SS.WorkingDays IS NOT NULL
			THEN ISNULL(SS.WorkingDays,0)
			ELSE ISNULL(MS.WorkingDays,0) END),
		PresentCount=(Select COUNT(1) FROM sAttendance.tStudentRegister SR1 WHERE SR1.AcademicId=SN.AcademicId 
			AND SR1.IsPresent=1 
			AND SR1.AttendanceTypeId=@rAttendanceTypeId
			AND ((SR1.SubjectId=@rSubjectId) OR (ISNULL(@rSubjectId,0)=0))
			AND DATEPART(MONTH,SR1.AttendanceDate)=@rForMonth 
			AND DATENAME(YEAR,SR1.AttendanceDate)=@rForYear),
		AbsentCount=(Select COUNT(1) FROM sAttendance.tStudentRegister SR2 WHERE SR2.AcademicId=SN.AcademicId 
			AND SR2.IsPresent=0 
			AND SR2.AttendanceTypeId=@rAttendanceTypeId
			AND ((SR2.SubjectId=@rSubjectId) OR (ISNULL(@rSubjectId,0)=0))
			AND DATEPART(MONTH,SR2.AttendanceDate)=@rForMonth 
			AND DATENAME(YEAR,SR2.AttendanceDate)=@rForYear),
		AbsentDays=(SELECT [sAttendance].[fAbsentDaysGet](@rForMonth,@rForYear, @rAttendanceTypeId,@rSubjectId,SN.AcademicId) AS MyResult),
		UpdatedUserId=@rCreatedUserId,
		UpdatedDateTime=sCommon.fGetDate()
FROM sAttendance.tMonthlyRegister MR
	INNER JOIN sStudent.vStudentName SN ON SN.AcademicId=MR.AcademicId
	LEFT JOIN sSetup.fMonthYearForBatchGET(@rBatchId) AS MY ON MY.BatchId=SN.BatchId
		AND MY.MonthNumber=@rForMonth AND MY.YearNumber=@rForYear
	LEFT JOIN sAttendance.tMonthlySetup MS ON MS.ClassId=SN.ClassId
		AND MS.ForMonth=MY.MonthNumber AND MS.ForYear=MY.YearNumber
	LEFT JOIN sAttendance.tStudentSetup SS ON SS.AcademicId=SN.AcademicId
		AND SS.ForMonth=MY.MonthNumber AND SS.ForYear=MY.YearNumber
	WHERE
		(MY.BatchId=@rBatchId)
	AND SN.AcademicId IN(SELECT AcademicId FROM #tTable1)
	AND	MR.ForMonth=@rForMonth
	AND	MR.ForYear=@rForYear
	AND	MR.AttendanceTypeId=@rAttendanceTypeId
	AND	MR.SubjectId=@rSubjectId
	
	UPDATE sAttendance.tMonthlyRegister
	SET 
		AveragePresence = (convert(decimal(5,2),(convert(decimal(5,2),PresentCount)*100)/(convert(decimal(5,2),TotalCount))))
	WHERE ISNULL(TotalCount,0)!=0
	
	SELECT 1 AS Result

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


GO
CREATE PROCEDURE [sAttendance].[pSetupDelete]

@rSetupTypeId tinyint, 
@rClassId int,
@rBatchId int,	
@rAcademicId bigint
 
WITH EXECUTE AS CALLER

AS
SET NOCOUNT ON
BEGIN

BEGIN TRY
	
	--@rSetupTypeId = 1 - Monthly Setup
	--@rSetupTypeId = 2 - Student Setup
	
BEGIN TRANSACTION	

IF @rSetupTypeId = 1 -- 
BEGIN
DELETE sAttendance.tMonthlySetup
WHERE BatchId = @rBatchId AND ClassId = @rClassId
SELECT 1 AS Result

END
ELSE IF @rSetupTypeId = 2
  BEGIN
  DELETE sAttendance.tStudentSetup
	WHERE AcademicId = @rAcademicId	 
 SELECT 1 AS Result 
 END
	COMMIT TRANSACTION			
	END TRY	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH			
END
GO
PRINT N'Creating [sAttendance].[pStudentRegisterDelete]...';


GO
CREATE PROCEDURE [sAttendance].[pStudentRegisterDelete]
	 
	 
	@rDivisionId int,
	@rAttendanceTypeId tinyint,
	@rAttendanceDate date,
	@rSubjectId int,
	@rRepeatCount tinyint
	 
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

BEGIN TRY
	
	 BEGIN TRANSACTION	

DELETE SR
FROM sAttendance.tStudentRegister SR
INNER JOIN sStudent.tAcademic A
ON SR.AcademicId= A.Id
WHERE A.DivisionId = @rDivisionId
AND SR.AttendanceTypeId = @rAttendanceTypeId
AND SR.AttendanceDate=@rAttendanceDate
AND ISNULL(SubjectId,0)=ISNULL(@rSubjectId,0) 
AND ISNULL(RepeatCount,0)=ISNULL(@rRepeatCount,0) 
 
	--Delete  from sAttendance.tStudentRegister where
	-- AcademicId=@rAcademicId and AttendanceTypeId=@rAttendanceTypeId 
	--AND AttendanceDate=@rAttendanceDate AND ISNULL(SubjectId,0)=ISNULL(@rSubjectId,0) 
	--AND ISNULL(RepeatCount,0)=ISNULL(@rRepeatCount,0)
	--Select @rAcademicId as Result
 SELECT 1 AS Result
	COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH			
END
GO
PRINT N'Creating [sCommon].[pNumberOrderIndexGet]...';


GO
CREATE PROCEDURE [sCommon].[pNumberOrderIndexGet]
          
           
           @rTableName nvarchar(100),
           @rScopeTypeId int,
           @rScope nvarchar(100),
           @rScopeId bigint
          
 
AS
SET NOCOUNT ON

BEGIN

 --ScopeTypeId = 1 Number and OrderIndex
 --ScopeTypeId = 2 Number
 --ScopeTypeId = 3 OrderIndex
  
 
DECLARE @lNumber as bigint
DECLARE @lOrderIndex as bigint
DECLARE @lNumberString as nvarchar(1000)
 DECLARE @lOrderIndexString as nvarchar(1000)

 SET @lNumberString = 'SELECT @lNumber = max(Number) + 1 FROM ' +  @rTableName + ' WHERE ' + @rScope  + ' = ' +  CONVERT(NVARCHAR(20), @rScopeId) 
SET @lOrderIndexString = 'SELECT @lOrderIndex = max(OrderIndex) + 1 FROM ' +  @rTableName + ' WHERE ' + @rScope + ' = ' +  CONVERT(NVARCHAR(20), @rScopeId) 

If @rScopeTypeId = 1
BEGIN
 EXECUTE sp_executesql @lNumberString,N' @lNumber bigint Output', @lNumber output
 EXECUTE sp_executesql @lOrderIndexString,N' @lOrderIndex bigint Output', @lOrderIndex output
END
ELSE IF  @rScopeTypeId = 2
BEGIN
 EXECUTE sp_executesql @lNumberString,N' @lNumber bigint Output', @lNumber output
 
END
 ELSE IF  @rScopeTypeId = 3
BEGIN
 
 EXECUTE sp_executesql @lOrderIndexString,N' @lOrderIndex bigint Output', @lOrderIndex output
END


--declare @dynsql varchar(500)   
--declare @params nvarchar(500)
--declare @salary money
--declare @username varchar(50)
--@dynsql='Select @sal=Salary,@usernm=Username from employee where EmployeeId=@empID'   
--@params='@empID int, @sal money OUTPUT, @usernm varchar(50) OUTPUT'
--exec sp_executesql @dynsql, @params, @empID=@EmployeeID, @sal=@salary OUTPUT, @usernm = @username OUTPUT
--SELECT @salary, @username

SELECT ISNULL(@lNumber,1) AS Number,ISNULL(@lOrderIndex,1) AS OrderIndex

END
GO
PRINT N'Creating [sCommon].[pReportFormatGet]...';


GO
CREATE PROCEDURE [sCommon].[pReportFormatGet]
	 
	 @rOrgId smallint,
	 @rReportFormatGroupId smallint
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
DECLARE @lReportId smallint

BEGIN 
	SELECT 
			@lReportId=RFGO.ReportId
  FROM 
            sCommon.tReport R
        INNER JOIN sCommon.tReportFormatGroupOrg RFGO ON RFGO.ReportId=R.Id AND RFGO.OrgId=@rOrgId
  WHERE 
			(R.ReportFormatGroupId=@rReportFormatGroupId)
IF(@lReportId IS NULL)
BEGIN
	SELECT 
			@lReportId=Min(Id)
	FROM 
            sCommon.tReport
	WHERE 
			(ReportFormatGroupId=@rReportFormatGroupId)
END

	SELECT @lReportId

END
GO
PRINT N'Creating [sCommon].[pReportFormatGroupMasterGet]...';


GO
CREATE PROCEDURE [sCommon].[pReportFormatGroupMasterGet]
	 
	 @rOrgGroupId smallint,
	 @rReportFormatGroupId smallint
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
		
BEGIN 
	SELECT 
			DISTINCT(OM.Id) AS OrgId,
			OM.DisplayTitle AS Organization,
			CASE WHEN RFGO.OrgId IS NULL OR RFGO.ReportFormatGroupId!=@rReportFormatGroupId THEN 'False' ELSE 'True' END AS IsObsolete,
			CASE WHEN RFGO.OrgId IS NULL OR RFGO.ReportFormatGroupId!=@rReportFormatGroupId THEN 0 ELSE RFGO.ReportId END AS ReportId
  FROM 
            sSetup.tOrganizationMaster OM
       LEFT JOIN sCommon.tReportFormatGroupOrg RFGO ON RFGO.OrgId=OM.Id AND (RFGO.ReportFormatGroupId=@rReportFormatGroupId)
       
  WHERE 
			(OM.OrgGroupId=@rOrgGroupId)
		ORDER BY OM.DisplayTitle
END
GO
PRINT N'Creating [sCommon].[pReportFormatGroupOrgAdd]...';


GO
CREATE PROCEDURE [sCommon].[pReportFormatGroupOrgAdd]
    
    @rReportFormatGroupId smallint,
	@rXmldoc [nvarchar](max)

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
BEGIN TRY

DECLARE @lCount INT
DECLARE @lInterrorCode INT,
		@intDoc INT,
		@lOrgId smallint,
		@lReportId smallint
		
BEGIN TRANSACTION
			
	DELETE FROM sCommon.tReportFormatGroupOrg WHERE ReportFormatGroupId=@rReportFormatGroupId	
			
	EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc
		
	CREATE TABLE #tTable  
	(
		Id bigint identity,	 
		OrgId smallint,
		ReportId smallint
	)
		
	INSERT INTO #tTable
	(
		OrgId,
		ReportId
	)
	SELECT
		OrgId,
		ReportId
	FROM OPENXML (@intDoc, '/Table/ReportFormatGroup', 1)
	WITH
	( 
		OrgId smallint '@OrgId',			
		ReportId smallint '@ReportId'
	)
		
	EXEC sp_xml_removedocument @intDoc
				
	SELECT @lCount =  COUNT(Id) FROM #tTable

	WHILE @lCount > 0 
	BEGIN
		SELECT		
				@lOrgId=OrgId,
				@lReportId=ReportId
													 	 
		FROM #tTable WHERE Id = @lCount  

		INSERT INTO sCommon.tReportFormatGroupOrg
		(
			OrgId,
			ReportId,
			ReportFormatGroupId
		)
		VALUES
		(
			@lOrgId,
			@lReportId,
			@rReportFormatGroupId
		)
		SET @lCount = @lCount - 1
	END			
COMMIT TRANSACTION			
	
SELECT 1
END TRY
BEGIN CATCH
ROLLBACK TRANSACTION
SELECT -1 
END CATCH
	
END
GO
PRINT N'Creating [sCommunication].[pBehaviourTypeMasterGet]...';


GO

CREATE PROCEDURE [sCommunication].[pBehaviourTypeMasterGet]
	 
	 @rId int,
	 @rTitle nvarchar(100),
	 @rOrgGroupId smallint
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	  --BEGIN
			--SET @rTitle = sCommon.fSearchStringGet(@rTitle)
	  --END
	 
	SELECT 
	BTM.Id,
	BTM.Title,
	BTM.Remark,
	BTM.BehaviourIndicatorId,
	BTM.OrgGroupId,
	BTM.IsObsolete,
	BTM.CreatedUserId,
	BIM.Title AS BehaviourType
  FROM 
        sCommunication.tBehaviourTypeMaster BTM
         INNER JOIN sCommunication.tBehaviourIndicatorMaster BIM
         ON BTM.BehaviourIndicatorId=BIM.Id
  WHERE 
      ((BTM.Id = @rId) OR (@rId = 0))
      AND  ((BTM.Title like @rTitle) OR (ISNULL(@rTitle,'') = '')) 
	  AND BTM.OrgGroupId = @rOrgGroupId	
END
GO
PRINT N'Creating [sCommunication].[pPhotoCategoryDelete]...';


GO
CREATE PROCEDURE [sCommunication].[pPhotoCategoryDelete]
	 
	 @rId int
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	BEGIN TRY
		BEGIN TRANSACTION
			Delete From sCommunication.tPhotoCategoryOrg Where PhotoCategoryId=@rId
			Delete from sCommunication.tPhotoCategoryMaster where Id=@rId
		COMMIT TRANSACTION
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
	END CATCH	
END
GO
PRINT N'Creating [sCommunication].[pPhotoCategoryOrgAdd]...';


GO

CREATE PROCEDURE [sCommunication].[pPhotoCategoryOrgAdd]
			
			@rPhotoCategoryId int
           ,@rOrgId smallint
           ,@rIsDeleted bit
           	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
 
If(@rIsDeleted=1)
BEGIN
	Delete from sCommunication.tPhotoCategoryOrg where PhotoCategoryId=@rPhotoCategoryId AND OrgId=@rOrgId
	Select @rOrgId as Result
END	
ELSE
BEGIN 

		BEGIN TRY
	
	 BEGIN TRANSACTION	    
	If Exists(select PhotoCategoryId from sCommunication.tPhotoCategoryOrg where PhotoCategoryId=@rPhotoCategoryId AND OrgId=@rOrgId)
		BEGIN
			SELECT @rOrgId AS Result
			RETURN
	  END 
	ELSE
			BEGIN
			INSERT INTO sCommunication.tPhotoCategoryOrg
			(
				PhotoCategoryId
			   ,OrgId
			)
			VALUES
			(	
				@rPhotoCategoryId
			   ,@rOrgId
			)		
			SELECT @rPhotoCategoryId AS Result
	END
	
	COMMIT TRANSACTION
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
	
END 	             
		
END
GO
PRINT N'Creating [sCommunication].[pPhotoCategoryOrgGet]...';


GO
CREATE PROCEDURE [sCommunication].[pPhotoCategoryOrgGet]
	 
	 @rPhotoCategoryId int,
	 @rOrgGroupId smallint
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 		
		
	SELECT 
			OM.Id AS OrgId,
			OM.DisplayTitle as Organization,
			CASE WHEN PCO.OrgId IS NULL OR PCO.PhotoCategoryId!=@rPhotoCategoryId THEN 0 ELSE 1 END AS IsObsolete
	FROM 
			sSetup.tOrganizationMaster OM
			LEFT JOIN sCommunication.tPhotoCategoryOrg PCO ON PCO.OrgId=OM.Id AND PCO.PhotoCategoryId=@rPhotoCategoryId
	WHERE (OM.OrgGroupId=@rOrgGroupId)
	Order BY OM.OrderIndex
END
GO
PRINT N'Creating [sCommunication].[pQueryCategoryAssignedToAdd]...';


GO

CREATE PROCEDURE [sCommunication].[pQueryCategoryAssignedToAdd]
	 
	@rSourceTypeId smallint,
	@rSourceId bigint,
	@rQueryCategoryId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION
	 IF EXISTS(SELECT 1 FROM sCommunication.tQueryCategoryAssignedTo WHERE SourceTypeId=@rSourceTypeId 
	 AND SourceId=@rSourceId AND QueryCategoryId=@rQueryCategoryId)
	 BEGIN
			SELECT @rQueryCategoryId AS Result
			RETURN
	 END
	INSERT INTO sCommunication.tQueryCategoryAssignedTo
		(
			SourceTypeId,
			SourceId,
			QueryCategoryId
		)
	VALUES
		(
			@rSourceTypeId,
			@rSourceId,
			@rQueryCategoryId
		) 
		
		SELECT @rQueryCategoryId AS Result
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Creating [sCommunication].[pQueryCategoryAssignedToDelete]...';


GO

CREATE PROCEDURE [sCommunication].[pQueryCategoryAssignedToDelete]
	 
	 @rId bigint
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 
	BEGIN TRY
		BEGIN TRANSACTION
			Delete from sCommunication.tQueryCategoryAssignedTo where SourceId=@rId
		COMMIT TRANSACTION
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
	END CATCH	
END
GO
PRINT N'Creating [sCommunication].[pQueryCategoryAssignedToGet]...';


GO

CREATE PROCEDURE [sCommunication].[pQueryCategoryAssignedToGet]
	 
	 @rQueryCategoryId int,
	 @rOrgGroupId smallint
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
		
BEGIN 
	SELECT 
			QCM.Id AS QueryCategoryId,
			QCA.SourceTypeId,
			'Functional Rolewise' AS SourceType,
			QCA.SourceId,
			'' AS SourceCode,
			R.Title AS SourceName
	FROM 
			sCommunication.tQueryCategoryAssignedTo QCA
		INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QCM.Id=QCA.QueryCategoryId AND (QCM.OrgGroupId = @rOrgGroupId)	
		INNER JOIN sSecurity.tRole R ON R.Id=QCA.SourceId AND QCA.SourceTypeId=2015
	WHERE 
			(QCA.QueryCategoryId = @rQueryCategoryId)
			
	UNION ALL
	
	SELECT 
			QCM.Id,
			QCA.SourceTypeId,
			'Specific Employeewise' AS SourceType,
			QCA.SourceId,
			EM.EmployeeCode AS SourceCode,
			EM.EmployeeName AS SourceName
	FROM 
			sCommunication.tQueryCategoryAssignedTo QCA
		INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QCM.Id=QCA.QueryCategoryId AND (QCM.OrgGroupId = @rOrgGroupId)	
		INNER JOIN sHrm.vExtEmployee EM ON EM.EmployeeId=QCA.SourceId AND QCA.SourceTypeId=95
	WHERE 
			(QCA.QueryCategoryId = @rQueryCategoryId)
END
GO
PRINT N'Creating [sCommunication].[pQueryCategoryMasterDelete]...';


GO

CREATE PROCEDURE [sCommunication].[pQueryCategoryMasterDelete]
	 
	 @rId int
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 
	BEGIN TRY
		BEGIN TRANSACTION
			Delete from sCommunication.tQueryCategoryAssignedTo where QueryCategoryId=@rId
			Delete from sCommunication.tQueryCategoryOrg where QueryCategoryId=@rId
			Delete from sCommunication.tQueryCategoryMaster where Id=@rId
		COMMIT TRANSACTION
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
	END CATCH	
END
GO
PRINT N'Creating [sCommunication].[pQueryCategoryOrgAdd]...';


GO

CREATE PROCEDURE [sCommunication].[pQueryCategoryOrgAdd]
			
			@rQueryCategoryId int
           ,@rOrgId smallint
           ,@rIsDeleted bit
           	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
 
If(@rIsDeleted=1)
BEGIN
	Delete from sCommunication.tQueryCategoryOrg where QueryCategoryId=@rQueryCategoryId AND OrgId=@rOrgId
	Select @rOrgId as Result
END	
ELSE
BEGIN 

		BEGIN TRY
	
	 BEGIN TRANSACTION	    
	If Exists(select QueryCategoryId from sCommunication.tQueryCategoryOrg where QueryCategoryId=@rQueryCategoryId AND OrgId=@rOrgId)
		BEGIN
			SELECT @rOrgId AS Result
			RETURN
	  END 
	ELSE
			BEGIN
			INSERT INTO sCommunication.tQueryCategoryOrg
			(
				QueryCategoryId
			   ,OrgId
			)
			VALUES
			(	
				@rQueryCategoryId
			   ,@rOrgId
			)		
			SELECT @rQueryCategoryId AS Result
	END
	
	COMMIT TRANSACTION
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
	
END 	             
		
END
GO
PRINT N'Creating [sCommunication].[pQueryCategoryOrgGet]...';


GO
CREATE PROCEDURE [sCommunication].[pQueryCategoryOrgGet]
	 
	 @rQueryCategoryId int,
	 @rOrgGroupId smallint
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 		
		
	SELECT 
			OM.Id AS OrgId,
			OM.DisplayTitle as Organization,
			CASE WHEN QCO.OrgId IS NULL OR QCO.QueryCategoryId!=@rQueryCategoryId THEN 0 ELSE 1 END AS IsObsolete
	FROM 
			sSetup.tOrganizationMaster OM
			LEFT JOIN sCommunication.tQueryCategoryOrg QCO ON QCO.OrgId=OM.Id AND QCO.QueryCategoryId=@rQueryCategoryId
	WHERE (OM.OrgGroupId=@rOrgGroupId)
	Order BY OM.OrderIndex
END
GO
PRINT N'Creating [sEExam].[pCreateQuestionGroup]...';


GO

CREATE Procedure [sEExam].[pCreateQuestionGroup]
     
      @rQuestionIdGroup nvarchar(max),
      @rQuestionGroupId bigint,
      @rIsCreate bit
     
AS 

BEGIN TRY
BEGIN TRANSACTION	

 IF(@rIsCreate=1)
 
  BEGIN   
     
     UPDATE sEExam.tQuestionMaster    
     SET GroupQuestionId = @rQuestionGroupId    
     Where Id IN (select item from [sCommon].[fnSplit](@rQuestionIdGroup,',')) 
     
     Select 1 AS Result
     
  END
  ELSE
   BEGIN
      UPDATE sEExam.tQuestionMaster
      SET GroupQuestionId = NULL
      Where Id IN (select item from [sCommon].[fnSplit](@rQuestionIdGroup,','))    
      
      Select 1 AS Result
      
   END
   
  COMMIT TRANSACTION
	
	END TRY
	BEGIN CATCH
	SELECT -1 AS Result
	END CATCH
GO
PRINT N'Creating [sEExam].[pDeactiveALLTestParticipant]...';


GO
CREATE PROCEDURE [sEExam].[pDeactiveALLTestParticipant]
	 
	 @rTestId bigint,	 
	 @rMode int	 
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	BEGIN TRY
		BEGIN TRANSACTION			   	   
		   
		  --IF(@rMode = 1)  --Activate All Participant
		  --  BEGIN
		    
				--CREATE Table #TempTestParticipant
				--(
				--   Id Int Identity(1,1), 
				--   SourceId bigint,
				--   SourceTypeId int,
				--   TestDate Date, 
				--   TotalMarks decimal(6,2)				   
				--)
		  --    SELECT StudentId FROM sStudent.vStudentAcademic VSA Where DivisionId = @rSourceId  
		     
		  --    UPDATE sEExam.tTestParticipant SET TestStatusId = 543 WHERE TestId = @rTestId  
		  -- 	  AND ISNULL(TestStatusId,0) NOT IN (544,545) 		   	   
			 --    -- When I Deactive Div Then Also Deactive Student Which Is Active 	   
			  
			 -- UPDATE sEExam.tTestAssign SET TestStatusId = 543 Where TestId = @rTestId 
			 -- AND ISNULL(TestStatusId,0) NOT IN (544,545) 
			  			  
			 -- SELECT 1 AS Result 			  
		  --  END	   	   
		   	    
		  -- ELSE 
		   IF(@rMode = 0) --DeActivate All Participant 
		   	 BEGIN 
		   	  UPDATE sEExam.tTestParticipant SET TestStatusId = 0 WHERE TestId = @rTestId  
		   	  AND ISNULL(TestStatusId,0) NOT IN (544,545)		   	   
			     -- When I Deactive Div Then Also Deactive Student Which Is Active 	   
			  UPDATE sEExam.tTestAssign SET TestStatusId = 0 Where TestId = @rTestId 
			  AND ISNULL(TestStatusId,0)  NOT IN (544,545) 
			  SELECT 1 AS Result  
		     END		    
		   ELSE   -- Delete All Participant
		     BEGIN
		           
		         Delete from  sEExam.tTestParticipant   WHERE TestId = @rTestId  
		   	     AND ISNULL(TestStatusId,0) NOT IN (544,545)	
		   	      		        		        
				 DELETE FROM sEExam.tTestAssign   Where TestId = @rTestId 
				 AND ISNULL(TestStatusId,0)  NOT IN (544,545) 
				  
				 SELECT 1 AS Result 
		     END 	
		COMMIT TRANSACTION	
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END
GO
PRINT N'Creating [sEExam].[pQuestionParagraphAdd]...';


GO


CREATE PROCEDURE [sEExam].[pQuestionParagraphAdd]
 
		@rId bigint,
		@rFigure varbinary(max),
		@rQuestionParagraphDescription nvarchar(max),
		@rQuestionParagraphDescription2 nvarchar(max),
		@rOrgId int,
		@rCreatedUserId bigint
 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	BEGIN TRANSACTION	
	DECLARE @lNextNumber BIGINT 
    IF(@rId = 0)
	  BEGIN
		
		EXECUTE sCommon.pTableRowIdGet  @rOrgId, 'sEExam.tQuestionParagraph', 0, 1, 1,@outNextNumber = @lNextNumber output
    
		 INSERT INTO [sEExam].[tQuestionParagraph]
			   (
				[Id]
			   ,[Figure]
			   ,[QuestionParagraphDescription]
			   ,[QuestionParagraphDescription2]
			   ,[OrgId]
			   ,[UpdatedUserId]
			   ,[UpdatedDateTime]
			   )
		 VALUES
			   (
				@lNextNumber
			   ,@rFigure
			   ,@rQuestionParagraphDescription
			   ,@rQuestionParagraphDescription2
			   ,@rOrgId
			   ,@rCreatedUserId 
			   ,sCommon.fGetDate()           
			   )  
     END
     ELSE
      BEGIN
         SET @lNextNumber = @rId
         UPDATE sEExam.tQuestionParagraph
          SET 
            Figure = @rFigure,
            QuestionParagraphDescription = @rQuestionParagraphDescription,
            QuestionParagraphDescription2 = @rQuestionParagraphDescription2,
            OrgId = @rOrgId,
            UpdatedUserId = @rCreatedUserId,
            UpdatedDateTime = sCommon.fGetDate()
            
            Where Id = @rId            
     END  
     
     Select @lNextNumber AS Result
     
    COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
       
END
GO
PRINT N'Creating [sEExam].[pQuestionParagraphGet]...';


GO


CREATE PROCEDURE sEExam.pQuestionParagraphGet
 
		@rParagraphId bigint,
		@rOrgId int

 
 AS
 
 BEGIN 
        SELECT   
             QuestionParagraphDescription2
        FROM 
        sEExam.tQuestionParagraph QP
        
        Where Id = @rParagraphId  AND OrgId = @rOrgId
       
 END
GO
PRINT N'Creating [sEExam].[pTestTemplateQuestionRemove]...';


GO
CREATE PROCEDURE [sEExam].[pTestTemplateQuestionRemove]
	 
	@rTestTemplateId bigint,
	@rQuestionId bigint 
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY	
	 BEGIN TRANSACTION
	--DECLARE @lNextNumber BIGINT
	--EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sEExam.tTestQuestion', 0, 1, 1,@outNextNumber = @lNextNumber output

      DELETE FROM sEExam.tTestTemplateQuestion Where TestTemplateId = @rTestTemplateId AND QuestionId = @rQuestionId
  
	  SELECT 1 AS Result          
	
	
	  COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -101 AS Result
	END CATCH	
		
END
GO
PRINT N'Creating [sEExam].[pTestTopicAnalysisGet]...';


GO


CREATE PROCEDURE [sEExam].[pTestTopicAnalysisGet]
			
			@rTestId int
			
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	
Select 
     
    Topic,
    TopicId,
    COUNT(Skipp) AS SKIP,
    COUNT(NotAttemted) AS NotAttempt,
    COUNT(Wrong) AS Wrong,
    COUNT(True) AS RightA
    
     --Pvt.[0] AS Wrong,
     --Pvt.[1] AS true
     --Pvt.[-1] AS Skip, 
 from
 (
    SELECT  
	TPA.TestId,
	TopicId,
    DTM.Title AS Topic, 
	CASE When tpa.AnswerStatusId = 533 Then 'Skipp' END AS Skipp,
	CASE WHEN tpa.AnswerStatusId = 532 Then 'NotAtt' END AS NotAttemted,
	CASE When tpa.AnswerStatusId = 531 AND ISNULL(Qo.IsKey,0) = 1 THEN 'True' END AS True,
	CASE When tpa.AnswerStatusId = 531 AND ISNULL(Qo.IsKey,0) = 0 THEN 'Wrong' END AS Wrong
	 
	--CASE When tpa.AnswerStatusId = 533 Then 'Skipp'
	--WHEN tpa.AnswerStatusId = 532 Then 'NotAttemted'
	--When tpa.AnswerStatusId = 531 AND ISNULL(Qo.IsKey,0) = 1 THEN 'True'
	--ELSE 'Wrong' END AS IsKey123 ,
 --   TQ.QuestionDescription,
 --   DTM.Title AS Topic,  
 --   tpa.AnswerStatusId 
	
FROM  
	sEExam.tTestParticipantAnswer TPA
	INNER JOIN sEExam.tTestParticipant TP ON TP.Id = TPA.TestParticipantId
	INNER JOIN sEExam.tTestQuestion TQM ON TQM.QuestionId = TPA.QuestionId AND TP.TestId = TQM.TestId
	INNER JOIN sEExam.tQuestionMaster TQ  ON TPA.QuestionId=TQ.Id AND TQM.QuestionId = TQ.Id
	INNER JOIN sEExam.tDataTopicMaster DTM ON DTM.Id = TQ.TopicId
	LEFT JOIN sEExam.tQuestionOption QO   ON QO.Id=TPA.QuestionOptionId AND QO.QuestionId = TPA.QuestionId	
    where TP.TestId = @rTestId  
 ) t
 
 
 Group By Topic,TopicId
		
END
GO
PRINT N'Creating [sFee].[pFeeMasterBulkAdd]...';


GO
CREATE PROCEDURE [sFee].[pFeeMasterBulkAdd]
    
    @rOrgGroupId smallint,
    @rCreatedUserId bigint,
	@rXmldoc [nvarchar](max)

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
--BEGIN TRY

DECLARE @lCount INT
DECLARE @lInterrorCode INT,
		@intDoc INT,
		@lFeeId int,
		@lCode nvarchar(20),
		@lNumber int,
		@lTitle nvarchar(100),
		@lFeeHeadId int,
		@lOrderIndex int
		
BEGIN TRANSACTION
			
	EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc
		
	CREATE TABLE #tTable  
	(
		Id bigint identity,	 
		FeeId int,
		Code nvarchar(20),
		Number int,
		Title nvarchar(100),
		FeeHeadId int,
		OrderIndex int
	)
		
	INSERT INTO #tTable
	(
		FeeId,
		Code,
		Number,
		Title,
		FeeHeadId,
		OrderIndex
	)
	SELECT
		FeeId,
		Code,
		Number,
		Title,
		FeeHeadId,
		OrderIndex
	FROM OPENXML (@intDoc, '/Table/FeeMaster', 1)
	WITH
	( 		
		FeeId int '@FeeId',
		Code nvarchar(20) '@Code',
		Number int '@Number',
		Title nvarchar(100) '@Title',
		FeeHeadId int '@FeeHeadId',
		OrderIndex int '@OrderIndex'
	) WHERE FeeId=0
		
	--EXEC sp_xml_removedocument @intDoc
				
	SELECT @lCount =  COUNT(Id) FROM #tTable

	WHILE @lCount > 0 
	BEGIN
		SELECT		
				@lFeeId=FeeId,
				@lCode=Code,
				@lNumber=Number,
				@lTitle=Title,
				@lFeeHeadId=FeeHeadId,
				@lOrderIndex=OrderIndex
													 	 
		FROM #tTable WHERE Id = @lCount  
		
		DECLARE @lNextNumber BIGINT 
	
		EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sFee.tFeeMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
		
		INSERT INTO sFee.tFeeMaster
		(
			OrgGroupId,
			Id,
			Code,
			Number,
			Title,
			FeeHeadId,
			OrderIndex,
			CreatedUserId,
			CreatedDateTime,
			IsObsolete
		)
		VALUES
		(
			@rOrgGroupId,
			@lNextNumber,
			@lCode,
			@lNumber,
			@lTitle,
			@lFeeHeadId,
			@lOrderIndex,
			@rCreatedUserId,
			sCommon.fGetDate(),
			0
		)
		SET @lCount = @lCount - 1
	END	
	
	DELETE FROM #tTable
	
	INSERT INTO #tTable
	(
		FeeId,
		Code,
		Number,
		Title,
		FeeHeadId,
		OrderIndex
	)
	SELECT
		FeeId,
		Code,
		Number,
		Title,
		FeeHeadId,
		OrderIndex
	FROM OPENXML (@intDoc, '/Table/FeeMaster', 1)
	WITH
	( 		
		FeeId int '@FeeId',
		Code nvarchar(20) '@Code',
		Number int '@Number',
		Title nvarchar(100) '@Title',
		FeeHeadId int '@FeeHeadId',
		OrderIndex int '@OrderIndex'
	) WHERE FeeId!=0
		
	EXEC sp_xml_removedocument @intDoc
				
	SELECT @lCount =  COUNT(Id) FROM #tTable

	WHILE @lCount > 0 
	BEGIN
		SELECT		
				@lFeeId=FeeId,
				@lCode=Code,
				@lNumber=Number,
				@lTitle=Title,
				@lFeeHeadId=FeeHeadId,
				@lOrderIndex=OrderIndex
													 	 
		FROM #tTable WHERE Id = @lCount  

		UPDATE sFee.tFeeMaster
		SET
			Code=@lCode,
			Number=@lNumber,
			Title=@lTitle,
			FeeHeadId=@lFeeHeadId,
			OrderIndex=@lOrderIndex
		WHERE Id=@lFeeId
		
		SET @lCount = @lCount - 1
	END	
			
COMMIT TRANSACTION			
	
SELECT 1
--END TRY
--BEGIN CATCH
--ROLLBACK TRANSACTION
--SELECT -1 
--END CATCH
	
END
GO
PRINT N'Creating [sFee].[pFeeMasterBulkGet]...';


GO
CREATE PROCEDURE [sFee].[pFeeMasterBulkGet]
	 
	 @rOrgGroupId smallint,
	 @rFeeHeadId int
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
		
BEGIN 
	SELECT 
			FM.Id,
			FM.Code,
			FM.Number,
			FM.Title,
			FM.FeeHeadId,
			FM.OrderIndex,
			CASE WHEN (SELECT COUNT(*) FROM sFee.tFeeSetup FS WHERE FS.FeeId=FM.Id) <= 0 THEN 'True' ELSE 'False' END AS IsObsolete
  FROM 
            sFee.tFeeMaster FM
       
  WHERE 
			(FM.OrgGroupId=@rOrgGroupId)
		AND ((FM.FeeHeadId=@rFeeHeadId) OR (@rFeeHeadId=0))
		ORDER BY FM.OrderIndex
END
GO
PRINT N'Creating [sFee].[pValidateBulkFee]...';


GO
CREATE PROCEDURE [sFee].[pValidateBulkFee]

	@rOrgGroupId smallint,
	@rXmldoc [nvarchar](max)
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
DECLARE @lCount INT
DECLARE @lInterrorCode INT,
		@intDoc INT,
		@lFeeId int,
        @lCode nvarchar(20),       
        @lNumber int,
        @lTitle nvarchar(100),
        @lFeeHeadId int,
        @1ExistCode nvarchar(max) = '',
        @1ExistNumber nvarchar(max) = '',
        @1ExistTitle nvarchar(max) = '',
        @1DuplicateCode nvarchar(max) = '',
        @1DuplicateNumber nvarchar(max) = '',
        @1DuplicateTitle nvarchar(max) = ''
       
EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc
 
CREATE TABLE #tTable1 
 (
		Id bigint identity,
		FeeId int,
        Code nvarchar(20),
        Number int,
        Title nvarchar(100),
        FeeHeadId int
  )
  INSERT INTO #tTable1
	(
		FeeId,
	    Code,
	    Number, 
	    Title,
	    FeeHeadId
    ) 
   SELECT
		FeeId,
        Code,
	    Number, 
	    Title,
	    FeeHeadId
   
   FROM OPENXML (@intDoc, '/Table/FeeMaster', 1)
   With
   (
		FeeId int '@FeeId',
        Code nvarchar(50) '@Code',
        Number int '@Number',
        Title nvarchar(100) '@Title',
        FeeHeadId int '@FeeHeadId'
   )   
EXEC sp_xml_removedocument @intDoc
			
SELECT @lCount =  COUNT(Id) FROM #tTable1
 
WHILE @lCount > 0 
  BEGIN
  
       SELECT         
         @lFeeId = FeeId,
         @lCode = Code, 
         @lNumber = Number,
         @lTitle = Title,
         @lFeeHeadId = FeeHeadId
         
     FROM #tTable1 WHERE Id = @lCount 
     
    IF Exists ((select 1 from sFee.tFeeMaster where Code = @lCode AND OrgGroupId = @rOrgGroupId AND @lFeeId=0))         
      BEGIN
		    SET @1ExistCode = @1ExistCode + @lCode + ','
       END	  
	IF Exists ((select 1 from sFee.tFeeMaster where Number = @lNumber AND OrgGroupId = @rOrgGroupId  AND @lFeeId=0))         
      BEGIN
			SET @1ExistNumber = @1ExistNumber + CAST(@lNumber as varchar(max)) + ','
       END
	IF Exists ((select 1 from sFee.tFeeMaster where Title = @lTitle AND OrgGroupId = @rOrgGroupId AND @lFeeId=0))         
      BEGIN
			SET @1ExistTitle = @1ExistTitle + @lTitle  + ','
       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 'Enter Code' AS Code
			RETURN
		END
		
		IF EXISTS(SELECT 1 fROM #tTable1 WHERE Number IS NULL OR Number='')
		BEGIN
			SELECT 'Enter Number' AS Code
			RETURN
		END
		
		IF EXISTS(SELECT 1 fROM #tTable1 WHERE Title IS NULL OR Title='')
		BEGIN
			SELECT 'Enter Title' AS Code
			RETURN
		END
		
		IF EXISTS(SELECT 1 fROM #tTable1 WHERE FeeHeadId IS NULL OR FeeHeadId=0)
		BEGIN
			SELECT 'Select Fee Head' AS Code
			RETURN
		END
		
		SELECT @1DuplicateCode=COALESCE(@1DuplicateCode ,'') 
		+ Code + ',' FROM #tTable1 GROUP BY Code HAVING ( COUNT(Code) > 1 )	
		IF(@1DuplicateCode IS NOT NULL AND @1DuplicateCode != '')
		BEGIN
			SET @1DuplicateCode = 'Duplicate Code ' + @1DuplicateCode
			SELECT @1DuplicateCode AS Code
			RETURN
		END
			
		SELECT @1DuplicateNumber=COALESCE(@1DuplicateNumber ,'') 
			+ CONVERT(VARCHAR(20),Number) + ',' FROM #tTable1 GROUP BY Number HAVING ( COUNT(Number) > 1 AND ISNULL(Number,'')!='')	
		IF(@1DuplicateNumber IS NOT NULL AND @1DuplicateNumber != '')
		BEGIN
			SET @1DuplicateNumber = 'Duplicate Number ' + @1DuplicateNumber
			SELECT @1DuplicateNumber AS Code
			RETURN
		END
		
		SELECT @1DuplicateTitle=COALESCE(@1DuplicateTitle ,'') 
		+ Title + ',' FROM #tTable1 GROUP BY Title HAVING ( COUNT(Title) > 1 )	
		IF(@1DuplicateTitle IS NOT NULL AND @1DuplicateTitle != '')
		BEGIN
			SET @1DuplicateTitle = 'Duplicate Title ' + @1DuplicateTitle
			SELECT @1DuplicateTitle AS Code
			RETURN
		END
		
		IF((@1ExistCode IS NULL OR @1ExistCode = '') AND (@1ExistNumber IS NULL OR @1ExistNumber = '') AND (@1ExistTitle IS NULL OR @1ExistTitle = ''))
		BEGIN
			SELECT '' AS Code
			RETURN
		END
		
		IF (@1ExistCode IS NOT NULL AND @1ExistCode != '')
		BEGIN
			SET @1ExistCode = 'Exist Code ' + @1ExistCode
			Select @1ExistCode AS Code
			RETURN
		END
		
		IF (@1ExistNumber IS NOT NULL AND @1ExistNumber != '')
		BEGIN
			SET @1ExistNumber = 'Exist Number ' + @1ExistNumber
			Select @1ExistNumber AS Code
			RETURN
		END
		
		IF (@1ExistTitle IS NOT NULL AND @1ExistTitle != '')
		BEGIN
			SET @1ExistTitle = 'Exist Title ' + @1ExistTitle
			Select @1ExistTitle AS Code
			RETURN
		END
		Select '' AS Code
END
GO
PRINT N'Creating [sLibrary].[pBookLocationMasterAdd]...';


GO
CREATE PROCEDURE [sLibrary].[pBookLocationMasterAdd]
	
	@rLibraryId int,
	@rId int,
	@rCode nvarchar(20),
	@rTitle nvarchar(100),
	@rIsObsolete bit,
	@rCreatedUserId bigint,
	@rOrgId smallint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	 
	 IF(@rId = 0)	
	 BEGIN
			IF EXISTS(SELECT 1 FROM sLibrary.tBookLocationMaster WHERE Code=@rCode AND LibraryId=@rLibraryId)
			BEGIN
				SELECT -101 AS Result
				RETURN
			END
			IF EXISTS(SELECT 1 FROM sLibrary.tBookLocationMaster WHERE Title=@rTitle AND LibraryId=@rLibraryId)
			BEGIN
				SELECT -102 AS Result
				RETURN
			END
	 END
	 ELSE
	 BEGIN
			IF EXISTS(SELECT 1 FROM sLibrary.tBookLocationMaster WHERE Code=@rCode AND LibraryId=@rLibraryId AND ID<>@rId)
			BEGIN
				SELECT -101 AS Result
				RETURN
			END
			IF EXISTS(SELECT 1 FROM sLibrary.tBookLocationMaster WHERE Title=@rTitle AND LibraryId=@rLibraryId AND ID<>@rId)
			BEGIN
				SELECT -102 AS Result
				RETURN
			END
	 END
	 
 IF(@rId = 0)	
BEGIN
	DECLARE @lNextNumber BIGINT   
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sLibrary.tBookLocationMaster', 0, 1, 1,@outNextNumber = @lNextNumber output

	INSERT INTO sLibrary.tBookLocationMaster
		(
			LibraryId,
			Id,
			Code,
			Title,
			IsObsolete,
			CreatedUserId,
			CreatedDateTime
		)
	VALUES
		(
			@rLibraryId,
			@lNextNumber,
			@rCode,
			@rTitle, 
			@rIsObsolete,
			@rCreatedUserId,
			sCommon.fGetDate()
		)
		             
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE sLibrary.tBookLocationMaster
	    SET
			Code=@rCode,
			Title=@rTitle,
			IsObsolete=@rIsObsolete,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate()
	      
	      WHERE Id = @rId 	   
	 END  
		SELECT @lNextNumber AS Result
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Creating [sLibrary].[pBookLocationMasterGet]...';


GO
CREATE PROCEDURE [sLibrary].[pBookLocationMasterGet]
	 
	 @rLibraryId int,
	 @rId int = 0,
	 @rCode nvarchar(20),
	 @rTitle nvarchar(100),
	 @rIsSearch bit = 1
	 	 
	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 
			BLM.LibraryId,
			BLM.Id,
			BLM.Code,
			BLM.Title,	
			BLM.IsObsolete
  FROM 
            sLibrary.tBookLocationMaster BLM
  WHERE 
  
		((BLM.Id = @rId) OR (@rId = 0))
    AND ((BLM.Code like @rCode) OR (ISNULL(@rCode,'') = '')) 
	AND ((BLM.Title like @rTitle) OR (ISNULL(@rTitle,'') = '')) 
END
GO
PRINT N'Creating [sLibrary].[pBookMasterDelete]...';


GO
CREATE PROCEDURE [sLibrary].[pBookMasterDelete]
	 
	 @rId bigint
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 
	--BEGIN TRY
			DECLARE @lCount int
			Select @lCount=Count(*) FROM sLibrary.tBookLog WHERE ResourceSourceId=@rId
			IF(@lCount <= 1)
			BEGIN
			BEGIN TRANSACTION
				Delete from sLibrary.tBookLog WHERE ResourceSourceId=@rId
				Delete from sLibrary.tBookMaster WHERE Id=@rId
			COMMIT TRANSACTION	
			END
			ELSE
			BEGIN
				SELECT -101 Result,N'Record Reffered in Book Log Table can not deleted' AS ResultText
				--EXEC sp_addmessage 50006, 1, N'Record Reffered in Book Log Table can not deleted';
				--RAISERROR (50006,16,1,'')
			END
	--END TRY
	
	--BEGIN CATCH 
	--	ROLLBACK TRANSACTION
	--END CATCH	
END
GO
PRINT N'Creating [sLibrary].[pBookRelease]...';


GO

CREATE PROCEDURE [sLibrary].[pBookRelease]
		
		@rResourceSourceTypeId smallint,
		@rResourceSourceId bigint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	BEGIN TRANSACTION
	
	UPDATE sLibrary.tBookLog
	    SET
			StatusId=521,
			UpdatedUserId=1,
			UpdatedDateTime=sCommon.fGetDate()
		WHERE IsCurrentStatus=1 AND StatusId=522 AND ResourceSourceTypeId=@rResourceSourceTypeId AND ResourceSourceId=@rResourceSourceId
	
	SELECT 1 AS Result
	
	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Creating [sLibrary].[pBulkBookRelease]...';


GO

CREATE PROCEDURE [sLibrary].[pBulkBookRelease]
		
		@rLibraryId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	BEGIN TRANSACTION
	
	UPDATE sLibrary.tBookLog
	    SET
			StatusId=521,
			UpdatedUserId=1,
			UpdatedDateTime=sCommon.fGetDate()
		WHERE IsCurrentStatus=1 AND StatusId=522 AND DueDate <= sCommon.fGetDate()  AND LibraryId=@rLibraryId 
	
	SELECT 1 AS Result
	
	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Creating [sSecurity].[pUserWithEmployeeDetailByEmployeeId_Delete]...';


GO
CREATE PROCEDURE [sSecurity].[pUserWithEmployeeDetailByEmployeeId_Delete]
	@rEmployeeId [bigint]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	SELECT 
		E.UserId AS UserId,		
		UserIsObsolete AS UserIsObsolete,
		DisplayTitle AS DisplayTitle,
		LoginTitle AS LoginTitle,
		EmployeeId AS EmployeeId, 
		EmployeeCode AS EmployeeCode,
		FullName AS EmployeeFullName,
		FirstName AS FirstName,
		MiddleName AS MiddleName,
		LastName AS LastName,
		EmployeeTypeId AS EmployeeTypeId,
		EmployeeCategoryId AS EmployeeCategoryId,
		GenderId AS GenderId,
		DateOfBirth AS DateOfBirth,
		DateOfJoining AS DateOfJoining,
		PermanentAddressId AS PermanentAddressId,
		CommunicationAddressId AS CommunicationAddressId,
		--CommunicationContactId AS CommunicationContactId,
		--EC.PhoneNumber AS PhoneNumberHome,
		--E.PhoneNoCompany AS PhoneNumberOffice,
		--EC.MobileNumber AS PhoneNumberMobile,
		E.CompanyEmail AS EmailPrimary,
		--EC.Email AS EmailAlternative,
		E.OrganizationDepartmentId AS OrganizationDepartmentId,
		E.OrganizationDepartment AS OrganizationDepartment,
		UP.ElectronicSignature AS ElectronicSignature
		
	FROM 
		sCommon.vExtEmployeeWithAllUser E
		--LEFT JOIN sHrm.vExtEmployeeContact EC	
		--		ON E.CommunicationContactId = EC.Id
				
		LEFT JOIN sSecurity.tUserProfile UP
				ON UP.UserId = E.UserId
	WHERE
		EmployeeId = @rEmployeeId
END
GO
PRINT N'Creating [sSecurity].[pUserWithEmployeeDetailByRoleId_Delete]...';


GO
CREATE PROCEDURE [sSecurity].[pUserWithEmployeeDetailByRoleId_Delete]
	@rOrgId [int],
	@rRoleId [int]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	SELECT 
		U.Id AS UserId,		
		U.DisplayTitle AS DisplayTitle,
		U.LoginTitle AS LoginTitle,
		U.IsObsolete AS UserIsObsolete,
		E.Id AS EmployeeId,
		E.Code AS EmployeeCode,
		ISNULL(E.FirstName, '') + ' ' + ISNULL(E.MiddleName, '') + ' ' + ISNULL(E.LastName, '') AS EmployeeFullName,
		E.FirstName AS FirstName,
		E.MiddleName AS MiddleName,
		E.LastName AS LastName,
		-- Commented for Employee Migration	
		--E.EmployeeTypeId AS EmployeeTypeId,
		-- End of comment for Employee Migration
		--Added for Employee Migration
		EJD.EmployeeJobTitleId AS EmployeeTypeId,
		E.EmployeeTypeId AS EmployeeCategoryId,
		EPD.GenderId AS GenderId,
		EPD.DateOfBirth AS DateOfBirth,
		EA.DateOfJoining AS DateOfJoining,
		EC.PermanentAddressId AS PermanentAddressId,
		EC.PresentAddressId AS CommunicationAddressId,
		EC.PresentContactId AS CommunicationContactId,
		ECON.PhoneNumber AS PhoneNumberHome,
		EC.PhoneNoCompany AS PhoneNumberOffice,
		ECON.MobileNumber AS PhoneNumberMobile,
		EC.CompanyEmail AS EmailPrimary,
		ECON.Email AS EmailAlternative
		---- End of addition for Employee Migration
		-- Commented for Employee Migration	
		--E.EmployeeTypeId AS EmployeeTypeId,
		--E.EmployeeCategoryId AS EmployeeCategoryId,
		--E.GenderId AS GenderId,
		--E.DateOfBirth AS DateOfBirth,
		--E.DateOfJoining AS DateOfJoining,
		--E.PermanentAddressId AS PermanentAddressId,
		--E.CommunicationAddressId AS CommunicationAddressId,
		--E.CommunicationContactId AS CommunicationContactId,
		--EC.PhoneNumberHome,
		--EC.PhoneNumberOffice,
		--EC.PhoneNumberMobile,
		--EC.EmailPrimary,
		--EC.EmailAlternative
		-- END of comment for Employee Migration
	FROM 
		sSecurity.tUser U
			INNER JOIN sSecurity.tUserRole UR
				ON UR.UserId = U.Id															
			-- Commented for Employee Migration	
			--INNER JOIN sCommon.tEmployeeMaster E
			--	ON U.EmployeeId = E.Id								
			--LEFT JOIN sCommon.tEmployeeContact EC	
			--	ON E.CommunicationContactId = EC.Id				
			-- END of comment for Employee Migration
			--Added for Employee Migration
			INNER JOIN sHrm.vExtEmployeeMaster E
				ON U.SourceId = E.Id AND U.SourceTypeId=95
			INNER JOIN sHrm.vExtEmployeeJobDetail EJD
				ON E.Id = EJD.EmployeeId	
			INNER JOIN sHrm.tEmployeePersonalDetail EPD
				ON E.Id = EPD.EmployeeId
			INNER JOIN sHrm.vExtEmployeeAdministration EA
				ON E.Id = EA.EmployeeId	
			INNER JOIN sHrm.vExtEmployeeCommunication EC
				ON E.Id = EC.EmployeeId		
			LEFT OUTER JOIN sHrm.vExtEmployeeContact ECON
				ON EC.PresentContactId = ECON.Id		
			-- END of addition for Employee Migration
	WHERE 
		UR.RoleId = @rRoleId
	AND	UR.IsObsolete = 0	
	AND U.OrgId = @rOrgId
		
END
GO
PRINT N'Creating [sSecurity].[pUserWithEmployeeDetailByUserId_Delete]...';


GO
CREATE PROCEDURE [sSecurity].[pUserWithEmployeeDetailByUserId_Delete]
	@rOrgId [smallint],
	@rUserId [int] = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	SELECT 
		U.Id AS UserId,	
		U.DisplayTitle AS DisplayTitle,	
		U.LoginTitle AS LoginTitle,
		E.Id AS EmployeeId,
		E.Code AS EmployeeCode,
		ISNULL(E.FirstName, '') + ' ' + ISNULL(E.MiddleName, '') + ' ' + ISNULL(E.LastName, '') AS EmployeeFullName,
		E.FirstName AS FirstName,
		E.MiddleName AS MiddleName,
		E.LastName AS LastName,
		--Added for Employee Migration
		EJD.EmployeeJobTitleId AS EmployeeTypeId,
		E.EmployeeTypeId AS EmployeeCategoryId,
		EPD.GenderId AS GenderId,
		EPD.DateOfBirth AS DateOfBirth,
		EA.DateOfJoining AS DateOfJoining,
		EC.PermanentAddressId AS PermanentAddressId,
		EC.PresentAddressId AS CommunicationAddressId,
		EC.PresentContactId AS CommunicationContactId,
		ECON.PhoneNumber AS PhoneNumberHome,
		EC.PhoneNoCompany AS PhoneNumberOffice,
		ECON.MobileNumber AS PhoneNumberMobile,
		EC.CompanyEmail AS EmailPrimary,
		ECON.Email AS EmailAlternative
		---- End of addition for Employee Migration
		-- Commented for Employee Migration
		--E.EmployeeTypeId AS EmployeeTypeId,
		--E.EmployeeCategoryId AS EmployeeCategoryId,
		--E.GenderId AS GenderId,
		--E.DateOfBirth AS DateOfBirth,
		--E.DateOfJoining AS DateOfJoining,
		--E.PermanentAddressId AS PermanentAddressId,
		--E.CommunicationAddressId AS CommunicationAddressId,
		--E.CommunicationContactId AS CommunicationContactId,
		--EC.PhoneNumberHome,
		--EC.PhoneNumberOffice,
		--EC.PhoneNumberMobile,
		--EC.EmailPrimary,
		--EC.EmailAlternative
		-- End of comment for Employee Migration
	FROM 
		sSecurity.tUser U
			-- Commented for Employee Migration	
			--INNER JOIN sCommon.tEmployeeMaster E
			--	ON U.EmployeeId = E.Id					
			--LEFT JOIN sCommon.tEmployeeContact EC	
			--	ON E.CommunicationContactId = EC.Id	
			-- End of comment for Employee Migration	
			--Added for Employee Migration
			INNER JOIN sHrm.vExtEmployeeMaster E
				ON U.SourceId = E.Id AND U.SourceTypeId=95	
			INNER JOIN sHrm.vExtEmployeeJobDetail EJD
				ON E.Id = EJD.EmployeeId	
			INNER JOIN sHrm.tEmployeePersonalDetail EPD
				ON E.Id = EPD.EmployeeId
			INNER JOIN sHrm.vExtEmployeeAdministration EA
				ON E.Id = EA.EmployeeId	
			INNER JOIN sHrm.vExtEmployeeCommunication EC
				ON E.Id = EC.EmployeeId		
			LEFT OUTER JOIN sHrm.vExtEmployeeContact ECON
				ON EC.PresentContactId = ECON.Id		
			-- End of addition for Employee Migration				
	WHERE 
		((U.ID = @rUserId) OR (@rUserId = 0))
		AND U.OrgId = @rOrgId
END
GO
PRINT N'Altering [sPayroll].[fCalculateLWP]...';


GO


ALTER FUNCTION [sPayroll].[fCalculateLWP]
	(
		@rEmployeeId bigint,
		@rPayProcessId int,	 
		@rAmount decimal(22,6)
	)
RETURNS DECIMAL(22,6)
AS
	BEGIN	
        DECLARE @lLWPDeduction decimal(22,2)
        SET @lLWPDeduction = 0.0

		IF(@rAmount > 0)
		BEGIN 
			DECLARE @1SalaryMonth int
			DECLARE @1SalaryYaer int
			DECLARE @1WorkingDays int
			DECLARE @1TotalDays int			
			DECLARE @1LWP decimal(12,2) 
			
			
			
			
			SELECT @1SalaryMonth = SalaryMonth,@1SalaryYaer = SalaryYear from sPayroll.tPayProcess Where Id = @rPayProcessId	    
			SELECT @1LWP = LWP, @1WorkingDays = TotalWorkingDays from sHrm.tEmployeeAttendance 
			where ForMonth = @1SalaryMonth AND ForYear = @1SalaryYaer AND EmployeeId = @rEmployeeId	
			
			select @1TotalDays = datediff(day, 
					dateadd(day, 0, dateadd(month, ((@1SalaryYaer - 1900) * 12) + @1SalaryMonth - 1, 0)),
					dateadd(day, 0, dateadd(month, ((@1SalaryYaer - 1900) * 12) + @1SalaryMonth, 0))
					)
			
			 
		    IF(@1TotalDays > 0)
			SET @lLWPDeduction =  ((@rAmount/@1TotalDays) * @1LWP)
	    END
	    
	    
    RETURN ISNULL(@lLWPDeduction,0)
END
GO
PRINT N'Refreshing [sFee].[vUserChrageReceiptBook]...';


GO
EXECUTE sp_refreshview N'sFee.vUserChrageReceiptBook';


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'Altering [sHrm].[vEmployeeCustomSearch]...';


GO


/******************************************************************************  
 Purpose          : To get Batch Wise  Class
 Created date     : 21 Nov 2013
 Author           : Kundan Patel 
 Copyright©       : Copyright © Sapphire Software Solutions
 ******************************************************************************/  
ALTER VIEW [sHrm].[vEmployeeCustomSearch]  
  
AS  
  
SELECT 	
	   EM.OrgId
      ,EM.Id AS EmployeeId
      ,EM.Code
      ,EM.FirstName
      ,EM.MiddleName
      ,EM.LastName
      ,ISNULL(EM.FirstName, '') + ' ' + ISNULL(EM.MiddleName, '') + ' ' + ISNULL(EM.LastName, '') AS Name
      ,EM.StatusId
      ,SM.Title AS StatusName
      ,EM.IsObsolete
      ,0 AS EmployeeJobDetail
      ,EJD.EmployeeDesignationId
      ,EDM.Title AS EmployeeDesignation
      ,EJD.OrganizationDepartmentId
      ,ODM.Title AS OrganizationDepartment
      ,EJD.DateOfJoining
      --,EJD.EPFNumber
      --,EJD.ESINumber
      ,EJD.EmployeeTypeId
      ,ETM.Title AS EmployeeType
      ,EJD.DateOfleaving
      ,EJD.ReasonOfleaving
      --,ELM.StreetOne
      --,ELM.StreetTwo
      --,ELM.StreetThree
      --,ELM.CityName
      --,ELM.StateName
      --,ELM.CountryName
      --,ELM.ZipCode
      --,ELM.PhoneNo
      --,ELM.FaxNo
      --,ELM.NameOfOccupier
      --,ELM.AddressOfOccupier
      --,ELM.SmallAddress1
      --,ELM.SmallAddress2
      --,ELM.RegistrationNumber
      --,ELM.LicenceNumber
      --,ELM.EsicNumber
      --,ELM.EsicAddress1
      --,ELM.EsicAddress2
      --,ELM.NatureOfIndustry
      --,ELM.ByProduct
      --,ELM.DangerousOperation
      --,ELM.NatureOfTest
      --,ELM.NatureOfTestNonHazardous
      --,ELM.RowMaterialUsed
      --,ELM.HazardousProcess
      --,ELM.Cmo
      --,ELM.NicNumber
      --,ELM.CountryId
      --,ELM.StateId
      ,0 AS EmployeePersonalDetailId
      ,EPD.UIDNumber
      ,EPD.DateOfBirth
      ,EPD.GenderId
      ,GM.Title AS Gender
      ,EPD.ReligionId
      ,RM.Title AS Religion
      ,EPD.MaritalStatusId
      ,MSM.Title AS MaritalStatus
      ,EPD.IdentificationMark1
      ,EPD.BloodGroupId
      ,BGM.Title AS BloodGroup
      ,EPD.Qualification
      ,EJD.EmployeeGroupId
      
  FROM 
		sHrm.tEmployeeMaster EM
	INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id=EJD.EmployeeDesignationId
	INNER JOIN sSetup.tDepartmentMaster ODM ON ODM.Id = EJD.OrganizationDepartmentId
	INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId = EM.Id
	LEFT JOIN sCommon.tGenderMaster GM ON GM.Id=EPD.GenderId
	LEFT JOIN sCommon.tReligionMaster RM ON RM.Id=EPD.ReligionId
	LEFT JOIN sCommon.tMaritalStatusMaster MSM ON MSM.Id=EPD.MaritalStatusId
	LEFT JOIN sCommon.tBloodGroupMaster BGM ON BGM.Id=EPD.BloodGroupId
	INNER JOIN sHrm.tEmployeeTypeMaster ETM ON ETM.Id = EJD.EmployeeTypeId
	INNER JOIN sCommon.tStatusMaster SM ON SM.Id = EM.StatusId AND SM.StatusTypeId = 4
GO
PRINT N'Altering [sHrm].[vEmployeeColumnName]...';


GO



/******************************************************************************  
 Purpose          : To get Batch Wise  Class
 Created date     : 21 Nov 2013
 Author           : Kundan Patel 
 Copyright©       : Copyright © Sapphire Software Solutions
 ******************************************************************************/  
ALTER VIEW [sHrm].[vEmployeeColumnName]  
  
AS  
  
SELECT 	
	   --EM.OrgId
    --  ,EM.Id AS EmployeeId
       EM.Code
      ,EM.FirstName
      ,EM.MiddleName
      ,EM.LastName
      ,ISNULL(EM.FirstName, '') + ' ' + ISNULL(EM.MiddleName, '') + ' ' + ISNULL(EM.LastName, '') AS Name
      --,EM.StatusId
      ,SM.Title AS StatusName
      --,EM.IsObsolete
      --,EJD.Id AS EmployeeJobDetailId
      --,EJD.EmployeeDesignationId
      ,EDM.Title AS EmployeeDesignation
      --,EJD.OrganizationDepartmentId
      ,ODM.Title AS OrganizationDepartment
      ,EJD.DateOfJoining
      --,EJD.EPFNumber
      --,EJD.ESINumber
      --,EJD.EmployeeTypeId
      ,ETM.Title AS EmployeeType
      ,EJD.DateOfleaving
      ,EJD.ReasonOfleaving
      --,ELM.StreetOne
      --,ELM.StreetTwo
      --,ELM.StreetThree
      --,ELM.CityName
      --,ELM.StateName
      --,ELM.CountryName
      --,ELM.ZipCode
      --,ELM.PhoneNo
      --,ELM.FaxNo
      --,ELM.NameOfOccupier
      --,ELM.AddressOfOccupier
      --,ELM.SmallAddress1
      --,ELM.SmallAddress2
      --,ELM.RegistrationNumber
      --,ELM.LicenceNumber
      --,ELM.EsicNumber
      --,ELM.EsicAddress1
      --,ELM.EsicAddress2
      --,ELM.NatureOfIndustry
      --,ELM.ByProduct
      --,ELM.DangerousOperation
      --,ELM.NatureOfTest
      --,ELM.NatureOfTestNonHazardous
      --,ELM.RowMaterialUsed
      --,ELM.HazardousProcess
      --,ELM.Cmo
      --,ELM.NicNumber
      --,ELM.CountryId
      --,ELM.StateId
      --,EPD.Id AS EmployeePersonalDetailId
      ,EPD.UIDNumber
      ,EPD.DateOfBirth
      ,EPD.Qualification
      --,EPD.GenderId
      ,GM.Title AS Gender
      --,EPD.ReligionId
      ,RM.Title AS Religion
      --,EPD.MaritalStatusId
      ,MSM.Title AS MaritalStatus
      ,EPD.IdentificationMark1
      --,EPD.BloodGroupId
      ,BGM.Title AS BloodGroup
      
  FROM sHrm.tEmployeeMaster EM
		INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
		--LEFT JOIN sHrm.tEmployeeJobTitleMaster EJTM ON EJTM.Id=EJD.EmployeeJobTitleId
		LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id=EJD.EmployeeDesignationId
		INNER JOIN sSetup.tDepartmentMaster ODM ON ODM.Id = EJD.OrganizationDepartmentId
		INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId = EM.Id
		LEFT JOIN sCommon.tGenderMaster GM ON GM.Id=EPD.GenderId
		LEFT JOIN sCommon.tReligionMaster RM ON RM.Id=EPD.ReligionId
		LEFT JOIN sCommon.tMaritalStatusMaster MSM ON MSM.Id=EPD.MaritalStatusId
		LEFT JOIN sCommon.tBloodGroupMaster BGM ON BGM.Id=EPD.BloodGroupId
		--LEFT JOIN sHrm.tQualificationMaster QM ON QM.Id=EPD.HigestQualificationId
		INNER JOIN sHrm.tEmployeeTypeMaster ETM ON ETM.Id = EJD.EmployeeTypeId
		INNER JOIN sCommon.tStatusMaster SM ON SM.Id = EM.StatusId AND SM.StatusTypeId = 4
GO
PRINT N'Refreshing [sLibrary].[vOrganizationLibrary]...';


GO
EXECUTE sp_refreshview N'sLibrary.vOrganizationLibrary';


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


GO





/******************************************************************************  
 Purpose          : To get Batch Wise  Class
 Created date     : 21 Nov 2013
 Author           : Kundan Patel 
 Copyright©       : Copyright © Sapphire Software Solutions
 ******************************************************************************/  
ALTER VIEW [sSetup].[vUserOrganization]  
  
AS  
  
SELECT 	
	  OM.Id as Id,
	  OM.DisplayTitle,
	  OM.OrgGroupId,
	  OM.IsObsolete,
	  UO.UserId,
	  ISNULL(OM.OrderIndex,0) AS OrderIndex
	  	   
  FROM 
  
	sSetup.tOrganizationMaster OM
	INNER JOIN sSecurity.tUserOrganization UO ON UO.OrgId=OM.Id
GO
PRINT N'Altering [sAccounting].[vLedgerMaster]...';


GO




ALTER VIEW [sAccounting].[vLedgerMaster]

AS
	select	L.Id,
		L.Title,
		L.LedgerGroupId,
		L.LedgerTypeId,
		L.AccountingYearId,		 
		AY.AccountId,
		LedgerMainGroupId
		
	FROM sAccounting.tLedgerMaster L 
		 INNER JOIN  sAccounting.tAccountingYearMaster AY 
	ON   L.AccountingYearId = AY.Id AND IsObsolete = 0
	 INNER JOIN sAccounting.tLedgerGroupMaster LGM ON LedgerGroupId = LGM.Id  
	 WHERE L.IsObsolete = 0
GO
PRINT N'Altering [sHrm].[vEmployeeCommonDetail]...';


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].[vEmployeeCommonDetail]

AS
	 SELECT EM.OrgID,
	        EM.Id AS EmployeeId,
	        EM.Code,
	        ISNULL(EM.FirstName, '') AS FirstName,
	        ISNULL(EM.LastName, '') AS LastName,
	        ISNULL(EM.FirstName, '') + ' ' + ISNULL(EM.LastName, '') AS  EmployeeName,	 
	        EM.StatusId AS EmployeeStatusId,						
			--EM.FirstName,
			--EM.MiddleName,
			--EM.LastName,			
			--EM.OrgID,
			--EPD.GenderId,
			--EPD.DateOfBirth,
			--EJD.DateOfJoining,
			--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,		 
			ISNULL(ODM.Id,0) AS DepartmentId,  
			--ISNULL(ODM.Title,'') AS DepartmentCode,  
			ISNULL(ODM.Title,'') AS DepartmentName,
		    ISNULL(EC.MobileNumber,'') AS MobileNumber,
		    0 AS EmployeeJobTitleId		    
		    ,ISNULL(EJD.EmployeeDesignationId,0) AS EmployeeDesignationId
			,ISNULL(EJD.OrganizationDepartmentId,0) AS OrganizationDepartmentId
			,ISNULL(EJD.EmployeeTypeId,0) AS EmployeeTypeId
			,ISNULL(EPD.BloodGroupId,0) AS BloodGroupId
			,ISNULL(BG.Title,'UNKNOWN') AS BloodGroup
			,ISNULL(EPD.GenderId,0) AS GenderId			 
			,EPD.DateOfBirth	 
		    ,MSM.Id AS MaritalStatusId
		    ,GM.Title As GenderTitle
		    ,MSM.Title As MaritialStatusTitle
			,EJD.EmployeeGroupId
		    ,EM.IsObsolete
		    ,ISNULL(EDM.Title,'') as EmployeeDesignation 
		    ,0 AS GradeNumber
		    ,ISNULL(EJD.EmployeeGradeId,0) AS EmployeeGradeId
		    ,EGM.Title AS EmployeeGrade
		    --,RM.Title As RelationshipTitle
		    --,RM.Id As RelationshipId
			--ISNULL(EDM.Id,0) AS DesignationId
		  
	    FROM 
			sHrm.tEmployeeMaster EM
	    INNER JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id = EJD.EmployeeId AND EM.IsObsolete = 0 
	    INNER JOIN sSetup.tDepartmentMaster ODM ON EJD.OrganizationDepartmentId = ODM.Id AND ODM.IsObsolete = 0					     
	    INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EM.Id = EPD.EmployeeId	  	     
	    LEFT JOIN sHrm.tEmployeeCommunications EC ON EM.Id = EC.EmployeeId  
		LEFT JOIN sCommon.tBloodGroupMaster BG ON EPD.BloodGroupId = BG.Id AND BG.IsObsolete = 0			  
		LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EJD.EmployeeDesignationId  = EDM.Id AND EDM.IsObsolete = 0	
		LEFT JOIN sHrm.tEmployeeGradeMaster EGM ON EGM.Id = EJD.EmployeeGradeId 
		LEFT JOIN sCommon.tGenderMaster  GM ON EPD.GenderId = GM.Id AND GM.IsObsolete = 0	
        LEFT JOIN sCommon.tMaritalStatusMaster MSM ON EPD.MaritalStatusId= MSM.Id AND MSM.IsObsolete = 0
GO
PRINT N'Altering [sHrm].[vExtEmployeeFamilyDetail]...';


GO


/******************************************************************************    
 Purpose          : External view to get data from sHrm.tEmployeeJobDetail table    
 Created date     : 03 Sep 2010    
 Author           : Rajendra Patel   
 Copyright©       : Copyright © Sapphire Software    
 Last Change Desc : EJD Added in Select
 *******************************************************************************/    
ALTER VIEW [sHrm].[vExtEmployeeFamilyDetail]
 
AS     

SELECT 
	EFD.Id AS DependentId, 
	(RM.Title + '  -  '+EFD.Name) AS Name,
	EM.Code AS EmployeeCode,
	EM.EmployeeId  AS EmployeeId,
	RM.Title AS Relation,
	RM.Id AS RelationId,
	EFD.Name AS DependentName,
	ISNULL(EFD.DateOfBirth,'') AS DateOfBirth,
	ISNULL(DATEDIFF(yy,EFD.DateOfBirth,GETDATE()),0)  AS AGE,
    EM.EmployeeName AS EmployeeName,
    EM.OrgID,
    EM.DepartmentId,
    EM.DepartmentName,
    EM.EmployeeDesignationId AS DesignationId
   
 FROM sHrm.tEmployeeFamilyDetails EFD  
	 INNER JOIN sHrm.vEmployeeCommonDetail EM ON EFD.EmployeeId = EM.EmployeeId 
	 INNER JOIN sCommon.tRelationshipMaster RM ON RM.Id=EFD.RelationshipId
	 INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EFD.EmployeeId
GO
PRINT N'Altering [sHrm].[vEmployeeCommunication]...';


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].[vEmployeeCommunication]

AS
	 SELECT EM.Id,
	        EM.Id AS EmployeeId,
	        EM.Code,
	        ISNULL(EM.FirstName, '') + ' ' + ISNULL(EM.LastName, '') EmployeeName,			
			EM.FirstName,
			EM.MiddleName,
			EM.LastName,			
			EM.OrgID,
			EJD.DateOfJoining,
			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,
			ISNULL(ODM.Id,0) AS DepartmentId,  
			ISNULL(ODM.Title,'') AS DepartmentCode,  
			ISNULL(ODM.Title,'') AS DepartmentName,
		    ISNULL(EC.MobileNumber,'') AS MobileNumber,
			95 AS ParticipantSourceTypeId,
			EC.PersonalEmail,
			EPD.DateOfBirth
	   FROM 
			sHrm.tEmployeeMaster EM
	   INNER JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id = EJD.EmployeeId 
	   INNER JOIN sHrm.tEmployeeCommunications EC ON EM.Id = EC.EmployeeId 
	   LEFT JOIN sSetup.tDepartmentMaster ODM ON EJD.OrganizationDepartmentId = ODM.Id 
	   LEFT JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId=EM.Id
GO
PRINT N'Altering [sHrm].[vExtEmployeeJobDetail]...';


GO


/******************************************************************************    
 Purpose          : External view to get data from sHrm.tEmployeeJobDetail table    
 Created date     : 03 Sep 2010    
 Author           : Rajendra Patel   
 Copyright©       : Copyright © Sapphire Software    
 Last Change Desc : EJD Added in Select
 *******************************************************************************/    
ALTER VIEW [sHrm].[vExtEmployeeJobDetail]  AS     
 
SELECT 
		0 AS Id,
		EJD.EmployeeId,
		ISNULL(ISNULL(EM.FirstName, ' ') + ' ' + ISNULL(EM.MiddleName, ' ') + ' ' + ISNULL(EM.LastName, ' '), ' ') AS EmployeeName,  
		EM.IsObsolete AS EmployeeMasterIsObsolete, 
		EJD.OrganizationDepartmentId,
		EJD.EmployeeTypeId,
		EM.Code AS EmployeeCode,   
		EJD.UpdatedUserId AS UpdatedUserId, 
		ODM.Title AS DepartmentName,  
		EDM.Id AS EmployeeDesignationId,  
		EDM.Title AS EmployeeDesignation,  
		EDM.IsObsolete AS  EmployeeDesignationMasterIsObsolete       
 FROM 
		sHrm.tEmployeeJobDetail EJD  
	INNER JOIN sHrm.tEmployeeMaster EM ON EJD.EmployeeId = EM.Id  
	INNER JOIN sSetup.tDepartmentMaster ODM ON EJD.OrganizationDepartmentId = ODM.Id 
	LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EJD.EmployeeDesignationId = EDM.Id
GO
PRINT N'Altering [sHrm].[vExtEmployeeMaster]...';


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].[vExtEmployeeMaster]

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,
			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(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
			
	   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.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
GO
PRINT N'Refreshing [sSecurity].[vExtUser]...';


GO
EXECUTE sp_refreshview N'sSecurity.vExtUser';


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


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].[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,
	  SM.FirstName+' '+SM.LastName AS Name,
	  --SM.DepartmentId,
	  SM.StatusId,
	  CM.DisplayTitle AS ClassName,
	  DM.DisplayTitle AS DivisionName,
	  STM.Title AS StatusName,
	  --ISNULL(SO.DateOfBirth,'') AS DateOfBirth,
	  SM.RecordStatusId,
	  --ISNULL(SO.GenderId,0) AS GenderId,
	  DM.InchargeEmployeeId,
	  --SI.StudentPhoto,
	  --DATEDIFF(yy,ISNULL(SO.DateOfBirth,GETDATE()),GETDATE()) AS Age,
	  BM.OrgGroupBatchId,
	  SM.AdmissionCategoryId,
	  DM.OrderIndex DivisionOrder
	   
  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 sStudent.tStudentOther SO
	--ON SO.StudentId=A.StudentId
	--LEFT JOIN sStudent.tStudentImages SI 
	--ON SI.StudentId=A.StudentId
GO
PRINT N'Altering [sStudent].[vStudentAllDetail]...';


GO


/******************************************************************************  
 Purpose          : To get Doctor details  
 Created date     : 18 Jan 2012  
 Author           : Rajendra Patel 
 Copyright©       : Copyright © Sapphire Software Solutions
 Last Change Desc : Moved EmployeeMaster from sCommon to sHrm.
*******************************************************************************/  
ALTER VIEW [sStudent].[vStudentAllDetail]  
  
AS  
  
SELECT 
	  A.Id AS AcademicId,	  
	  A.ClassId,
	  A.DivisionId,
	  A.RollNo,
	  A.OrgId,
	  A.BatchId,
	  SM.Id AS StudentId,
	  SM.Code,
	  SM.Number,
	  SM.FirstName,
	  SM.MiddleName,
	  SM.LastName,
	  SM.FirstName+' '+SM.LastName AS Name,
	  CM.DisplayTitle+' / '+DM.DisplayTitle AS ClassDivision,
	  SM.StatusId,
	  CM.DisplayTitle AS ClassName,
	  DM.DisplayTitle AS DivisionName,
	  STM.Title AS StatusName,
	  SA.LCProgress,
	  SA.LCConduct,
	  SA.LeftDate,
	  SA.PreviousSchool,
	  SA.LeftReason,
	  SA.InactiveDate,
	  SA.AdmissionDate,
	  AdmissionStandard=(SELECT Title FROM SSetup.tClassMaster WHERE Id=SA.AdmissionStandardId),
	  LeftStandard=(SELECT Title FROM SSetup.tClassMaster WHERE Id=SA.LeftStandardId),
	  SA.LCNumber,
	  SA.LCDate,
	  RM.Title AS Religion,
	  SO.FamilyCast,
	  SO.FamilySubCast,
	  SO.BirthPlace,
	  SO.BirthTaluka,
	  SO.BirthDistrict,
	  ISNULL(SO.DateOfBirth,'0001/01/01') AS DateOfBirth,
	  SO.BirthDateInWord,
	  (SI.StudentPhoto) AS StudentPhoto,
	  BGM.Title AS BloodGroup,
	  ISNULL(SC.PermanentStreetOne,'')+' '+ISNULL(SC.PresentStreetTwo,'')+' '+ISNULL(SC.PresentStreetThree,'')+' '+ISNULL(SC.PresentCity,'')+' '+ISNULL(SC.PresentState,'')+' '+ISNULL(SC.PresentZipCode,'') AS PresentAddress,
	  ISNULL(GM.Title,'') AS Gender,
	  ISNULL(SC.StudentContactNo,'') AS ContactNo,
	  BM.Title AS Batch,
	  ISNULL(ACM.Title,'') AS AdmissionCategory,
	  SO.HouseId,
	  ISNULL(SC.PresentStreetone,'') AS PresentStreetone,
	  ISNULL(SC.PresentStreetTwo,'') AS PresentStreetTwo,
	  ISNULL(SC.PresentStreetThree,'') AS PresentStreetThree,
	  ISNULL(SC.PresentCity,'-') AS PresentCity,
	  ISNULL(SC.PresentState,'-') As PresentState,
	  ISNULL(SC.PresentZipCode,'-') as PresentZipCode,
	  ISNULL(SC.PresentCountry,'-') AS PresentCountry,
	  ISNULL(SC.PresentContactNo,'-') as PresentContactNo,
	  ISNULL(SC.ParentEmail,'-') AS ParentEmail,
	  ISNULL(SC.ParentContactNo,'-') AS ParentContactNo,
	  DM.OrderIndex AS DivisionOrder
  FROM 
  
	sStudent.tAcademic A
	INNER JOIN sStudent.tStudentMaster SM
		ON A.StudentId=SM.Id	
	INNER JOIN sSetup.tClassMaster CM
		ON CM.Id=A.ClassId
	INNER JOIN sSetup.tDivisionMaster DM
		ON DM.Id=A.DivisionId
	INNER JOIN sStudent.tStatusMaster STM
		ON STM.Id=SM.StatusId
	LEFT JOIN sStudent.tStudentCommunication SC 
		ON SC.StudentId=A.StudentId
	LEFT JOIN sStudent.tStudentOther SO
		ON SO.StudentId=A.StudentId
	LEFT JOIN sStudent.tStudentAdmission SA
		ON SA.StudentId=A.StudentId
	LEFT JOIN sCommon.tReligionMaster RM
		ON RM.Id=SO.ReligionId
	LEFT JOIN sStudent.tStudentImages SI
		ON SI.StudentId=A.StudentId
	LEFT JOIN 	sCommon.tBloodGroupMaster BGM
		ON BGM.Id=SO.BloodGroupId
	INNER JOIN sSetup.tBatchMaster BM
		ON BM.Id=A.BatchId
	LEFT JOIN sCommon.tGenderMaster GM 
		ON GM.Id=SO.GenderId
	LEFT JOIN sStudent.tAdmissionCategoryMaster ACM 
		ON ACM.Id=SM.AdmissionCategoryId
GO
PRINT N'Creating [sAlert].[vEventMaster]...';


GO




/******************************************************************************
	Purpose          : External view to get data from sAlert.tTemplatemaster table
	Created date     : 27 May 2009
	Author           : System Generated
	Copyright©       : Copyright © Sapphire Software
	Last Change Desc : 
*******************************************************************************/

CREATE VIEW [sAlert].[vEventMaster]

AS
	 SELECT 
			   EM.[Id]
			  ,EM.[ModuleId]
			  ,EM.[Title]
			  ,EM.[IsObsolete]
			  ,MP.OrgGroupId
	FROM 
			[sAlert].[tEventMaster] EM
		INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId=EM.ModuleId
GO
PRINT N'Creating [sCommunication].[vOrgwiseQueryCategory]...';


GO





/******************************************************************************  
 Purpose          : To get Batch Wise  Class
 Created date     : 21 Nov 2013
 Author           : Kundan Patel 
 Copyright©       : Copyright © Sapphire Software Solutions
 ******************************************************************************/  
CREATE VIEW [sCommunication].[vOrgwiseQueryCategory]  
  
AS  
  
SELECT 	
	  QCM.Id,
	  QCM.Title,
	  QCM.OrgGroupId,
	  QCM.IsObsolete,
	  QCO.OrgId
	  	   
  FROM 
  
	sCommunication.tQueryCategoryMaster QCM
	INNER JOIN sCommunication.tQueryCategoryOrg QCO ON QCO.QueryCategoryId=QCM.Id
GO
PRINT N'Altering [sFee].[vFeeColumnName]...';


GO


/******************************************************************************  
 Purpose          : To get Batch Wise  Class
 Created date     : 21 Nov 2013
 Author           : Kundan Patel 
 Copyright©       : Copyright © Sapphire Software Solutions
 ******************************************************************************/  
ALTER VIEW [sFee].[vFeeColumnName]  
  
AS  
  
SELECT 	
		 --SA.AcademicId,	  
		 --SA.ClassId,
		 --SA.DivisionId,
		 SA.RollNo,
		 --SA.OrgId,
		 --SA.BatchId,
		 OGBM.Title AS OrgGroupBatch,
		 OM.Title AS Organization,
		 BM.Title AS Batch,
		 --SA.StudentId,
		 SA.Code AS [ID No],
		 SA.Number,
		 SA.FirstName,
		 SA.LastName,
		 SA.Name,
		 --SA.DepartmentId,
		 --SA.StatusId,
		 SA.ClassName,
		 SA.DivisionName,
		 SA.StatusName,
		 --FA.VariableAmount,
		 --FA.DiscountAmount,
   --      FA.AdditionalAmount,
   --      FA.NotApplicable,
   --      FCM.Number AS FeeCategoryNumber,
   --      FCM.Code AS FeeCategoryCode,
   --      FCM.Title AS FeeCategoryName,
	  --   FCM.OrderIndex AS FeeCategoryOrderIndex,
	  --   FHM.Code AS FeeHeadCode,
	  --   FHM.Title AS FeeHeadTitle,
	  --   FM.Code AS FeeCode,
	  --   FM.Number AS FeeNumber,
	  --   FM.Title AS FeeName,
	  --   FM.OrderIndex AS FeeOrderIndex,
	  --   FS.Amount AS FeeSetupAmount,
	  --   FS.StartDate,
	  --   FS.EndDate,
	     R.ReceiptNumber,
	     R.ReceiptDate,
	     R.ReceiptAmount,
	     R.ChequeNo,
	     R.BankName,
	     R.Remark,
	     RBM.Code AS ReceiptBookCode,
	     RBM.Title AS ReceiptBookName,
	     RBM.Address1,
	     RBM.Address2,
	     RBM.BankAccountNumber,
	     --RD.Amount AS ReceiptDetailAmount,
	     PTM.Title AS PayType,
	     U.DisplayTitle AS CreatedUserName
	  	  	   
FROM 
		sStudent.vStudentAcademic SA
	INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=SA.OrgGroupBatchId
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=SA.OrgId
	INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA.BatchId
	--INNER JOIN sFee.tFeeAllocation FA ON FA.SourceId=SA.AcademicId
	INNER JOIN sFee.tReceipt R ON R.SourceId=SA.AcademicId
	INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
	--INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId=R.Id
	--INNER JOIN sFee.tFeeSetup FS ON FS.Id=RD.FeeSetupId
	--INNER JOIN sFee.tFeeCategoryMaster FCM ON FCM.Id=FS.FeeCategoryId
	--INNER JOIN sFee.tFeeCategoryClass FCC ON FCC.FeeCategoryId=FCM.Id
	--INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS.FeeId
	--INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
	INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=R.PayTypeId 
	INNER JOIN sSecurity.tUser U ON U.Id=R.CreatedUserId
GO
PRINT N'Altering [sFee].[vFeeCustomSearch]...';


GO

/******************************************************************************  
 Purpose          : To get Batch Wise  Class
 Created date     : 21 Nov 2013
 Author           : Kundan Patel 
 Copyright©       : Copyright © Sapphire Software Solutions
 ******************************************************************************/  
ALTER VIEW [sFee].[vFeeCustomSearch]  
  
AS  
  
SELECT 	
		 SA.AcademicId,	  
		 SA.ClassId,
		 SA.DivisionId,
		 SA.RollNo,
		 SA.OrgGroupBatchId,
		 SA.OrgId,
		 SA.BatchId,
		 OGBM.Title AS OrgGroupBatch,
		 OM.Title AS Organization,
		 BM.Title AS Batch,
		 SA.StudentId,
		 SA.Code,
		 SA.Number,
		 SA.FirstName,
		 SA.LastName,
		 SA.Name,
		 SA.StatusId,
		 SA.ClassName,
		 SA.DivisionName,
		 SA.StatusName,
		 --FA.Id AS FeeAllocationId,
		 --FA.VariableAmount,
		 --FA.DiscountAmount,
   --      FA.AdditionalAmount,
   --      FA.NotApplicable,
   --      FCC.IsCommon,
   --      FCM.Id AS FeeCategoryId,
   --      FCM.Number AS FeeCategoryNumber,
   --      FCM.Code AS FeeCategoryCode,
   --      FCM.Title AS FeeCategoryName,
	  --   FCM.OrderIndex AS FeeCategoryOrderIndex,
	  --   FHM.Id AS FeeHeadId,
	  --   FHM.Code AS FeeHeadCode,
	  --   FHM.Title AS FeeHeadTitle,
	  --   FM.Id AS FeeId,
	  --   FM.Code AS FeeCode,
	  --   FM.Number AS FeeNumber,
	  --   FM.Title AS FeeName,
	  --   FM.OrderIndex AS FeeOrderIndex,
	  --   FS.Id AS FeeSetupId,
	  --   FS.IsVariable,
	  --   FS.Amount AS FeeSetupAmount,
	  --   FS.StartDate,
	  --   FS.EndDate,
	     R.Id AS ReceiptId,
	     R.ReceiptNumber,
	     R.ReceiptDate,
	     R.ReceiptAmount,
	     R.ChequeNo,
	     R.BankName,
	     R.Remark,
	     R.IsObsolete,
	     RBM.Id AS FeeReceiptBookId,
	     RBM.Code AS ReceiptBookCode,
	     RBM.Title AS ReceiptBookName,
	     RBM.Address1,
	     RBM.Address2,
	     RBM.BankAccountNumber,
	     --RD.Amount AS ReceiptDetailAmount,
	     PTM.Id AS PayTypeId, 
	     PTM.Title AS PayType,
	     U.Id AS CreatedUserId,
	     U.DisplayTitle AS CreatedUserName
FROM 
		sStudent.vStudentAcademic SA
	INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=SA.OrgGroupBatchId
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=SA.OrgId
	INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA.BatchId
	--LEFT JOIN sFee.tFeeAllocation FA ON FA.SourceId=SA.AcademicId
	INNER JOIN sFee.tReceipt R ON R.SourceId=SA.AcademicId
	INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
	--INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId=R.Id
	--LEFT JOIN sFee.tFeeSetup FS ON FS.Id=RD.FeeSetupId
	--LEFT JOIN sFee.tFeeCategoryMaster FCM ON FCM.Id=FS.FeeCategoryId
	--LEFT JOIN sFee.tFeeCategoryClass FCC ON FCC.FeeCategoryId=FCM.Id
	--INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS.FeeId
	--INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
	INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=R.PayTypeId 
	LEFT JOIN sSecurity.tUser U ON U.Id=R.CreatedUserId
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].[vStudentCustomSearch]...';


GO
EXECUTE sp_refreshview N'sStudent.vStudentCustomSearch';


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


GO
EXECUTE sp_refreshview N'sStudent.vStudentColumnName';


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


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 [sCommon].[vEmployeeMaster]  
  
AS  
  
SELECT 
			EM.OrgId,
			EM.Id,  
			EM.Code,  
			EM.FirstName,  
			EM.MiddleName,  
			EM.LastName,  
			(EM.FirstName + ISNULL(' ' + EM.MiddleName, '') + ISNULL(' ' + EM.LastName, '')) EmployeeName, 
			EM.GenderId,  
			EM.DateOfBirth,  
			EM.DateOfJoining,   
			EM.StatusId,  
			EM.CreatedUserId,  
			EM.CreatedDateTime,  
			EM.UpdatedUserId,  
			EM.UpdatedDateTime, 
			EM.IsObsolete,
			vEU.Id AS UserId,  
			ODM.Id DepartmentId,  
			ODM.Title  DepartmentCode,  
			ODM.Title DepartmentName
 
  FROM 
			sHrm.vExtEmployeeMaster EM  
	  INNER JOIN sSecurity.vExtUser vEU ON EM.Id = vEU.SourceId ANd EM.OrgId = vEU.OrgId
	  LEFT JOIN sSetup.tDepartmentMaster ODM ON EM.DepartmentId = ODM.Id ANd EM.OrgId = ODM.OrgId
GO
PRINT N'Altering [sCommon].[vExtEmployeeWithAllUser]...';


GO








/******************************************************************************
	Purpose          : External view to get data from sEmployee and User tables
	Created date     : 02 Sept 2009
	Author           : Rajendra Patel
	Copyright©       : Copyright © Sapphire Software
	Last Change Desc : Added Employee Company Mails and Phone nos
*******************************************************************************/

ALTER VIEW [sCommon].[vExtEmployeeWithAllUser]
AS
	 SELECT 
			EM.Id						AS EmployeeId,
			EM.Code						AS EmployeeCode,
			ISNULL(EM.FirstName, '') +
			' ' + 
			ISNULL(EM.MiddleName, '') +
			' ' + 
			ISNULL(EM.LastName, '')		AS FullName,
			EM.FirstName				AS FirstName,
			EM.MiddleName				AS MiddleName,
			EM.LastName					AS LastName,
			EM.EmployeeTypeId			AS EmployeeTypeId,
			1		AS EmployeeCategoryId,
			EM.GenderId					AS GenderId,
			EM.DateOfBirth				AS DateOfBirth,
			EM.DateOfJoining			AS DateOfJoining,
			EM.StatusId					AS EmployeeStatusId,
			EM.IsObsolete				AS EmployeeIsObsolete,
			ISNULL(EM.DepartmentId, 0)				AS OrganizationDepartmentId,
			ODM.Title					AS OrganizationDepartment,
			EM.PhoneNoCompany,
			EM.CompanyEmail,
			EM.ExtensionNo,	
			U.Id						AS UserId,		
			U.DisplayTitle				AS DisplayTitle,
			U.LoginTitle				AS LoginTitle,
			U.LoginPassword				AS LoginPassword,
			U.LastLockOutDate			AS LastLockOutDate,
			U.NumberOfLogonAttempt		AS NumberOfLogonAttempt,
			U.IsObsolete				AS UserIsObsolete,
			EM.OrgId
		
	FROM
			sHrm.vExtEmployeeMaster EM
		LEFT OUTER JOIN sSecurity.tUser U ON U.SourceId = EM.Id AND U.SourceTypeId=95
		LEFT OUTER JOIN sSetup.tDepartmentMaster ODM ON EM.DepartmentId = ODM.Id
	WHERE StatusId=7
GO

 
 