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

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


GO
CREATE SCHEMA [sPoliciesForms]
    AUTHORIZATION [dbo];


GO
PRINT N'Altering [sAdmission].[tAdmissionCriteria]...';


GO
ALTER TABLE [sAdmission].[tAdmissionCriteria]
    ADD [ReceiptBookId] INT NULL;


GO
PRINT N'Altering [sAdmission].[tAdmissionForm]...';


GO
ALTER TABLE [sAdmission].[tAdmissionForm]
    ADD [BirthState]   NVARCHAR (150) NULL,
        [BirthCountry] NVARCHAR (150) NULL;


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


GO
ALTER TABLE [sAssessment].[tExamStatus]
    ADD [UpdatedDateTime] DATETIME NULL;


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


GO
ALTER TABLE [sAssessment].[tStudentRemark]
    ADD [ExamCenter] NVARCHAR (100) NULL;


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


GO
ALTER TABLE [sAssessment].[tTempAllExam]
    ADD [SubjectObtainTerm1] DECIMAL (8, 2) NULL,
        [SubjectObtainTerm2] DECIMAL (8, 2) NULL,
        [SubjectMaxTerm1]    DECIMAL (8, 2) NULL,
        [SubjectMaxTerm2]    DECIMAL (8, 2) NULL;


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


GO
ALTER TABLE [sAssessment].[tTempAllExamSubjectActivity]
    ADD [GradeSetIdText] NVARCHAR (50) NULL;


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


GO
ALTER TABLE [sCommon].[tModuleMaster]
    ADD [ModuleGroupId] TINYINT NULL;


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


GO
ALTER TABLE [sCommon].[tPrefixConfig]
    ADD [ScopeSourceTypeId] SMALLINT NULL;


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


GO
ALTER TABLE [sFee].[tReceiptBookMaster]
    ADD [ReceiptBookHeader] VARBINARY (MAX) NULL,
        [HeaderDisplayId]   TINYINT         NULL;


GO
PRINT N'Altering [sFrontOffice].[tLostFoundRegister]...';


GO
ALTER TABLE [sFrontOffice].[tLostFoundRegister]
    ADD [ItemPhoto] VARBINARY (MAX) NULL;


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


GO
ALTER TABLE [sHrm].[tEmployeeJobDetail]
    ADD [EmployeeBusinessHeadId] BIGINT NULL;


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


GO
ALTER TABLE [sHrm].[tLeaveBalance] ALTER COLUMN [BalanceLeave] DECIMAL (8, 2) NOT NULL;


GO
ALTER TABLE [sHrm].[tLeaveBalance]
    ADD [LastYearCarryForwarded] DECIMAL (8, 2) NULL;


GO
PRINT N'Starting rebuilding table [sOp].[tGatewayConfiguration]...';


GO
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;

SET XACT_ABORT ON;

BEGIN TRANSACTION;

CREATE TABLE [sOp].[tmp_ms_xx_tGatewayConfiguration] (
    [Id]               INT             NULL,
    [OrgGroupId]       SMALLINT        NOT NULL,
    [PaymentGatewayId] SMALLINT        NULL,
    [GatewayURL]       NVARCHAR (1000) NULL,
    [ServerPort]       NVARCHAR (50)   NULL,
    [LoginId]          NVARCHAR (50)   NULL,
    [LoginPassword]    NVARCHAR (50)   NULL,
    [ProductId]        NVARCHAR (100)  NULL,
    [TermsCondition]   NVARCHAR (MAX)  NULL,
    [PrivacyPolicy]    NVARCHAR (MAX)  NULL,
    [PaymentPolicy]    NVARCHAR (MAX)  NULL,
    [Disclaimer]       NVARCHAR (MAX)  NULL
);

IF EXISTS (SELECT TOP 1 1
           FROM   [sOp].[tGatewayConfiguration])
    BEGIN
        INSERT INTO [sOp].[tmp_ms_xx_tGatewayConfiguration] ([OrgGroupId], [PaymentGatewayId], [GatewayURL], [ServerPort], [LoginId], [LoginPassword], [ProductId], [TermsCondition], [PrivacyPolicy], [PaymentPolicy], [Disclaimer])
        SELECT [OrgGroupId],
               [PaymentGatewayId],
               [GatewayURL],
               [ServerPort],
               [LoginId],
               [LoginPassword],
               [ProductId],
               [TermsCondition],
               [PrivacyPolicy],
               [PaymentPolicy],
               [Disclaimer]
        FROM   [sOp].[tGatewayConfiguration];
    END

DROP TABLE [sOp].[tGatewayConfiguration];

EXECUTE sp_rename N'[sOp].[tmp_ms_xx_tGatewayConfiguration]', N'tGatewayConfiguration';

COMMIT TRANSACTION;

SET TRANSACTION ISOLATION LEVEL READ COMMITTED;


GO
PRINT N'Starting rebuilding table [sProcurement].[tStockIssue]...';


GO
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;

SET XACT_ABORT ON;

BEGIN TRANSACTION;

CREATE TABLE [sProcurement].[tmp_ms_xx_tStockIssue] (
    [Id]                         INT             NOT NULL,
    [Number]                     NVARCHAR (20)   NOT NULL,
    [IssuedByName]               NVARCHAR (100)  NOT NULL,
    [FirstAidId]                 INT             NULL,
    [ToOrganizationDepartmentId] INT             NOT NULL,
    [FromStoreLocationId]        INT             NOT NULL,
    [Remark]                     NVARCHAR (300)  NULL,
    [CreatedUserId]              BIGINT          NOT NULL,
    [CreatedDateTime]            DATETIME        NOT NULL,
    [StockIssueRequestId]        INT             NULL,
    [OrgGroupId]                 SMALLINT        NOT NULL,
    [IssueToSourceTypeId]        INT             NULL,
    [IssueToSourceId]            BIGINT          NULL,
    [IsPaid]                     BIT             NULL,
    [TotalAmount]                DECIMAL (12, 2) NULL,
    [StockIssueTypeId]           INT             NULL
);

IF EXISTS (SELECT TOP 1 1
           FROM   [sProcurement].[tStockIssue])
    BEGIN
        INSERT INTO [sProcurement].[tmp_ms_xx_tStockIssue] ([Id], [Number], [IssuedByName], [ToOrganizationDepartmentId], [FirstAidId], [FromStoreLocationId], [Remark], [CreatedUserId], [CreatedDateTime], [StockIssueRequestId], [OrgGroupId], [IssueToSourceTypeId], [IssueToSourceId], [IsPaid], [TotalAmount])
        SELECT [Id],
               [Number],
               [IssuedByName],
               [ToOrganizationDepartmentId],
               [FirstAidId],
               [FromStoreLocationId],
               [Remark],
               [CreatedUserId],
               [CreatedDateTime],
               [StockIssueRequestId],
               [OrgGroupId],
               [IssueToSourceTypeId],
               [IssueToSourceId],
               [IsPaid],
               [TotalAmount]
        FROM   [sProcurement].[tStockIssue];
    END

DROP TABLE [sProcurement].[tStockIssue];

EXECUTE sp_rename N'[sProcurement].[tmp_ms_xx_tStockIssue]', N'tStockIssue';

COMMIT TRANSACTION;

SET TRANSACTION ISOLATION LEVEL READ COMMITTED;


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


GO
ALTER TABLE [sStudent].[tStudentCommunication]
    ADD [PresentDistanceFromSchool] DECIMAL (10, 2) NULL;


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


GO
ALTER TABLE [sStudent].[tStudentFamily]
    ADD [IsFatherExStudent]   BIT           NULL,
        [FatherPassOutYear]   NVARCHAR (20) NULL,
        [IsMotherExStudent]   BIT           NULL,
        [MotherPassOutYear]   NVARCHAR (20) NULL,
        [IsRelativeExStudent] BIT           NULL,
        [RelativePassOutYear] NVARCHAR (20) NULL;


GO
PRINT N'Creating [sPoliciesForms].[tFolderFile]...';


GO
CREATE TABLE [sPoliciesForms].[tFolderFile] (
    [Id]              INT            NOT NULL,
    [IsForms]         BIT            NOT NULL,
    [IsFolder]        BIT            NOT NULL,
    [Title]           NVARCHAR (100) NOT NULL,
    [Remark]          NVARCHAR (200) NOT NULL,
    [ContentType]     NVARCHAR (200) NULL,
    [PerentFolderId]  INT            NOT NULL,
    [Size]            FLOAT          NULL,
    [Accessible]      SMALLINT       NOT NULL,
    [ViewAccess]      SMALLINT       NOT NULL,
    [UploadAccess]    SMALLINT       NOT NULL,
    [EditAccess]      SMALLINT       NOT NULL,
    [DeleteAccess]    SMALLINT       NOT NULL,
    [OrgId]           SMALLINT       NOT NULL,
    [IsObsolete]      BIT            NOT NULL,
    [CreatedUserId]   BIGINT         NOT NULL,
    [CreatedDateTime] DATETIME       NOT NULL,
    [UpdatedUserId]   BIGINT         NULL,
    [UpdatedDateTime] DATETIME       NULL
);


GO
PRINT N'Creating [sPoliciesForms].[tFolderImageName]...';


GO
CREATE TABLE [sPoliciesForms].[tFolderImageName] (
    [Id]        INT            IDENTITY (1, 1) NOT NULL,
    [ImageName] NVARCHAR (100) NULL,
    [Extension] NVARCHAR (200) NULL
);


GO
PRINT N'Creating PK_tFolderImageName...';


GO
ALTER TABLE [sPoliciesForms].[tFolderImageName]
    ADD CONSTRAINT [PK_tFolderImageName] 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 [sPoliciesForms].[tFolderFilePermission]...';


GO
CREATE TABLE [sPoliciesForms].[tFolderFilePermission] (
    [Id]           BIGINT IDENTITY (1, 1) NOT NULL,
    [FolderFileId] INT    NOT NULL,
    [RoleId]       INT    NOT NULL,
    [IsAccess]     BIT    NOT NULL,
    [IsView]       BIT    NOT NULL,
    [IsUpload]     BIT    NOT NULL,
    [IsEdit]       BIT    NOT NULL,
    [IsDelete]     BIT    NOT NULL
);


GO
PRINT N'Creating PK_tFolderFilePermission...';


GO
ALTER TABLE [sPoliciesForms].[tFolderFilePermission]
    ADD CONSTRAINT [PK_tFolderFilePermission] 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 [sAccounting].[tExpenseDetail]...';


GO
CREATE TABLE [sAccounting].[tExpenseDetail] (
    [Id]                INT             IDENTITY (1, 1) NOT NULL,
    [ExpenseId]         INT             NULL,
    [ExpenseSubGroupId] INT             NULL,
    [Amount]            DECIMAL (12, 2) NULL,
    [Remark]            NVARCHAR (200)  NULL
);


GO
PRINT N'Creating PK_tExpenseDetail...';


GO
ALTER TABLE [sAccounting].[tExpenseDetail]
    ADD CONSTRAINT [PK_tExpenseDetail] 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 [sAccounting].[tExpenseSubGroupMaster]...';


GO
CREATE TABLE [sAccounting].[tExpenseSubGroupMaster] (
    [Id]              INT            NOT NULL,
    [ExpenseGroupId]  INT            NOT NULL,
    [Code]            NVARCHAR (100) NOT NULL,
    [Title]           NVARCHAR (100) NOT NULL,
    [IsObsolete]      BIT            NOT NULL,
    [CreatedUserId]   BIGINT         NOT NULL,
    [CreatedDateTime] DATETIME       NOT NULL,
    [UpdatedUserId]   BIGINT         NULL,
    [UpdatedDateTime] DATETIME       NULL,
    [OrgId]           SMALLINT       NULL
);


GO
PRINT N'Creating [sAppraisal].[tAppraisalTypeMaster]...';


GO
CREATE TABLE [sAppraisal].[tAppraisalTypeMaster] (
    [Id]              INT             NOT NULL,
    [Title]           NVARCHAR (100)  NOT NULL,
    [Remark]          NVARCHAR (1000) NOT NULL,
    [ValidFrom]       DATE            NOT NULL,
    [ValidTo]         DATE            NOT NULL,
    [IsObsolete]      BIT             NOT NULL,
    [CreatedUserId]   BIGINT          NOT NULL,
    [CreatedDateTime] DATETIME        NOT NULL,
    [UpdatedUserId]   BIGINT          NULL,
    [UpdatedDateTime] DATETIME        NULL,
    [BatchId]         INT             NOT NULL
);


GO
PRINT N'Creating [sAppraisal].[tBHRatingStatus]...';


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


GO
PRINT N'Creating [sAppraisal].[tBusinessHeadsRatingStatus]...';


GO
CREATE TABLE [sAppraisal].[tBusinessHeadsRatingStatus] (
    [Id]               INT     IDENTITY (1, 1) NOT NULL,
    [BusinessHeadId]   BIGINT  NOT NULL,
    [AppraisalTypeId]  INT     NULL,
    [BHRatingStatusId] TINYINT NULL
);


GO
PRINT N'Creating PK_tBusinessHeadsRatingStatus...';


GO
ALTER TABLE [sAppraisal].[tBusinessHeadsRatingStatus]
    ADD CONSTRAINT [PK_tBusinessHeadsRatingStatus] 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 [sAppraisal].[tKPAEmployee]...';


GO
CREATE TABLE [sAppraisal].[tKPAEmployee] (
    [Id]              BIGINT   NOT NULL,
    [EmployeeId]      BIGINT   NOT NULL,
    [KPAStatusId]     TINYINT  NOT NULL,
    [BatchId]         INT      NULL,
    [CreatedUserId]   BIGINT   NOT NULL,
    [CreatedDateTime] DATETIME NOT NULL,
    [UpdatedUserId]   BIGINT   NULL,
    [UpdatedDateTime] DATETIME NULL,
    [KPATemplateId]   INT      NULL
);


GO
PRINT N'Creating [sAppraisal].[tKPAEmployeeDetail]...';


GO
CREATE TABLE [sAppraisal].[tKPAEmployeeDetail] (
    [Id]              BIGINT          IDENTITY (1, 1) NOT NULL,
    [KPAEmployeeId]   BIGINT          NOT NULL,
    [KPATypeId]       TINYINT         NULL,
    [KPAMeasureId]    TINYINT         NULL,
    [Indicator]       NVARCHAR (200)  NULL,
    [IndicatorRemark] NVARCHAR (200)  NULL,
    [Weightage]       DECIMAL (10, 2) NULL
);


GO
PRINT N'Creating [sAppraisal].[tKPAEmployeeRating]...';


GO
CREATE TABLE [sAppraisal].[tKPAEmployeeRating] (
    [Id]                                    BIGINT          NOT NULL,
    [AppraisalTypeId]                       INT             NULL,
    [KPAEmployeeId]                         BIGINT          NOT NULL,
    [RatingStatusId]                        TINYINT         NULL,
    [RecommendationIncrement]               DECIMAL (8, 2)  NULL,
    [RecommendationDesignation]             NVARCHAR (100)  NULL,
    [RecommendationJustification]           NVARCHAR (300)  NULL,
    [CreatedUserId]                         BIGINT          NOT NULL,
    [CreatedDateTime]                       DATETIME        NOT NULL,
    [UpdatedUserId]                         BIGINT          NULL,
    [UpdatedDateTime]                       DATETIME        NULL,
    [BusinessHeadRating]                    DECIMAL (10, 2) NULL,
    [BusinessHeadRecommendationIncrement]   DECIMAL (8, 2)  NULL,
    [BusinessHeadRecommendationDesignation] NVARCHAR (100)  NULL
);


GO
PRINT N'Creating [sAppraisal].[tKPAEmployeeRatingDetail]...';


GO
CREATE TABLE [sAppraisal].[tKPAEmployeeRatingDetail] (
    [AutoId]              INT             IDENTITY (1, 1) NOT NULL,
    [KPAEmployeeRatingId] BIGINT          NOT NULL,
    [KPAEmployeeDetailId] BIGINT          NOT NULL,
    [MyRating]            DECIMAL (10, 2) NULL,
    [MyRemark]            NVARCHAR (200)  NULL,
    [ManagerRemark]       NVARCHAR (200)  NULL,
    [ManagerRating]       DECIMAL (10, 2) NULL
);


GO
PRINT N'Creating [sAppraisal].[tKPAMeasureMaster]...';


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


GO
PRINT N'Creating [sAppraisal].[tKPAStatus]...';


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


GO
PRINT N'Creating [sAppraisal].[tKPATemplateDetail]...';


GO
CREATE TABLE [sAppraisal].[tKPATemplateDetail] (
    [AutoId]          INT             IDENTITY (1, 1) NOT NULL,
    [KPATemplateId]   INT             NOT NULL,
    [KPATypeId]       TINYINT         NOT NULL,
    [KPAMeasureId]    TINYINT         NOT NULL,
    [Indicator]       NVARCHAR (200)  NULL,
    [IndicatorRemark] NVARCHAR (200)  NULL,
    [Weightage]       DECIMAL (10, 2) NOT NULL
);


GO
PRINT N'Creating [sAppraisal].[tKPATemplateMaster]...';


GO
CREATE TABLE [sAppraisal].[tKPATemplateMaster] (
    [Id]              INT            NOT NULL,
    [Indicator]       NVARCHAR (200) 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
);


GO
PRINT N'Creating [sAppraisal].[tKPATypeMaster]...';


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


GO
PRINT N'Creating [sAppraisal].[tRatingStatus]...';


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


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


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


GO
PRINT N'Creating PK_tDisplayHeaderTypeMaster...';


GO
ALTER TABLE [sCommon].[tHeaderDisplayMaster]
    ADD CONSTRAINT [PK_tDisplayHeaderTypeMaster] 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 [sCommon].[tModuleGroupMaster]...';


GO
CREATE TABLE [sCommon].[tModuleGroupMaster] (
    [Id]         TINYINT       NOT NULL,
    [Title]      NVARCHAR (50) NOT NULL,
    [IsObsolete] BIT           NOT NULL
);


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


GO
CREATE TABLE [sOp].[tGatewayProduct] (
    [Id]                     INT             NOT NULL,
    [GatewayConfigurationId] INT             NOT NULL,
    [Title]                  NVARCHAR (150)  NULL,
    [GatewayURL]             NVARCHAR (1000) NULL,
    [ServerPort]             NVARCHAR (50)   NULL,
    [LoginId]                NVARCHAR (50)   NULL,
    [LoginPassword]          NVARCHAR (50)   NULL,
    [ProductId]              NVARCHAR (100)  NULL
);


GO
PRINT N'Creating PK_tGatewayProduct_1...';


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


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


GO
CREATE TABLE [sOp].[tGatewayProductReceiptBookMapping] (
    [GatewayProductId] INT NOT NULL,
    [ReceiptBookId]    INT NOT NULL
);


GO
PRINT N'Creating [sProcurement].[tSstockIssueTypeMaster]...';


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


GO
PRINT N'Creating PK_tConductIndicatorMaster...';


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


GO
PRINT N'Creating PK_tTravelPeriodMaster...';


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


GO
PRINT N'Creating PK_tInsterestTypeMaster...';


GO
ALTER TABLE [sLoan].[tInsterestTypeMaster]
    ADD CONSTRAINT [PK_tInsterestTypeMaster] 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

GO
PRINT N'Creating [sPoliciesForms].[fFolderSizeGet]...';


GO

CREATE FUNCTION [sPoliciesForms].[fFolderSizeGet](@PerentFolderId INT)
RETURNS FLOAT WITH EXECUTE AS CALLER
AS 
BEGIN

	DECLARE @Size FLOAT=0

	;WITH FolderSize (id,  Size)
	AS
	(
		SELECT id, ISNULL(Size,0)Size 
		FROM [sPoliciesForms].[tFolderFile]  
		WHERE PerentFolderId =@PerentFolderId
  		UNION ALL
  		SELECT e.id,  ISNULL(e.Size,0)Size 
		FROM [sPoliciesForms].[tFolderFile] e
		INNER JOIN FolderSize r
		ON e.PerentFolderId = r.id
	)
	SELECT @Size= ISNULL(SUM(Size),0) FROM FolderSize
	RETURN @Size
 END
GO
PRINT N'Creating [sPoliciesForms].[fFileFolderSizeGet]...';


GO

CREATE FUNCTION [sPoliciesForms].[fFileFolderSizeGet](@len FLOAT)
RETURNS nvarchar(2000) WITH EXECUTE AS CALLER
AS 
BEGIN

	DECLARE @order int= 1
	DECLARE @size NVARCHAR(50)=''

	WHILE  (@len >= 1024  AND  @order < 5)
		BEGIN
		SET 	@order=@order+1
		SET @len = @len / 1024 
	END

	select @size=item  from [sCommon].[fnSplitRowID]('BYTES,KB,MB,GB,TB,',',') WHERE RowID=@order

	RETURN CONVERT(NVARCHAR(50),CEILING(@len))+'  '+ @size
 
END
GO
PRINT N'Creating [sPoliciesForms].[fFolderPathGet]...';


GO

CREATE FUNCTION [sPoliciesForms].[fFolderPathGet](@FolderId INT)
RETURNS NVARCHAR(MAX) WITH EXECUTE AS CALLER
AS 
BEGIN
DECLARE @columns VARCHAR(MAX)=''
;WITH
cteReports (id, PerentFolderId, Title, EmpLevel)
AS
(
SELECT id, PerentFolderId, Title, 0 AS EmpLevel
FROM [sPoliciesForms].[tFolderFile]  
WHERE id =@FolderId  AND IsFolder=1
UNION ALL
SELECT e.id, e.PerentFolderId, e.Title, r.EmpLevel + 1
FROM [sPoliciesForms].[tFolderFile] e
INNER JOIN cteReports r  ON e.id = r.PerentFolderId
WHERE IsFolder=1
)
SELECT  @columns = COALESCE(@columns + '\\', '') + Title  FROM cteReports order by id
RETURN @columns
END
GO
PRINT N'Creating [sAppraisal].[fGetInnerHtml]...';


GO
-- select [sAppraisal].[fGetInnerHtml](1001000000016,3,52)
-- drop function [sAppraisal].[fGetInnerHtml]
CREATE function [sAppraisal].[fGetInnerHtml](@rKEDID bigint)
returns varchar(max)
as
begin
	declare @res varchar(max)='',@i int	= 1
	select @res = @res + '<td width="80%"><table width="100%"><tr>'		
		
	select @res = @res + '
	<td width="30" style="color: #678197; text-align: center; border: 1px solid #E5EFF8; background: none repeat scroll 0% 0% #FFF; margin: 0px; padding: 3px;">' + convert(varchar,KRD.MyRating) + '</td>
	<td width="50" style="color: #678197; text-align: center; border: 1px solid #E5EFF8; background: none repeat scroll 0% 0% #FFF; margin: 0px; padding: 3px;">' + convert(varchar,KRD.ManagerRating) + '</td>
	<td width="85" style="color: #678197; text-align: center; border: 1px solid #E5EFF8; background: none repeat scroll 0% 0% #FFF; margin: 0px; padding: 3px;">' + convert(varchar,KR.BusinessHeadRating) + '</td>'


	from [sAppraisal].[tKPAEmployeeRatingDetail] KRD
	LEFT JOIN [sAppraisal].[tKPAEmployeeRating] KR on 	KR.Id = KRD.KPAEmployeeRatingId
	LEFT JOIN [sAppraisal].[tAppraisalTypeMaster] AS ATM ON ATM.id=KR.AppraisalTypeId
	where KRD.KPAEmployeeDetailId = @rKEDID AND ATM.IsObsolete=0
	AND Kr.RatingStatusId>=5
	select @res = @res +'</tr></table></td>'
	
	return @res
end
GO
PRINT N'Creating [sAttendance].[fAttendanceTotalDayGet]...';


GO
CREATE FUNCTION [sAttendance].[fAttendanceTotalDayGet](@rAcademicId bigint,@rMonth int,@rYear int,@rPresent tinyint)
RETURNS int WITH EXECUTE AS CALLER
AS 
BEGIN
	DECLARE @lCount int=0
	IF(@rPresent = 0)
	BEGIN
		SELECT @lCount = COUNT(SR.AttendanceDate)
		FROM sStudent.vStudentAcademic SA
		INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.AcademicId AND SR.AttendanceTypeId = 1
		WHERE SA.AcademicId = @rAcademicId  
		AND DATEPART(MONTH,SR.AttendanceDate) = @rMonth
		AND DATEPART(YEAR,SR.AttendanceDate) = @rYear 
		GROUP BY AttendanceDate
	END
	ELSE IF(@rPresent = 1)
    BEGIN
		SELECT @lCount = COUNT(SR.AcademicId)
		FROM sStudent.vStudentAcademic SA
		INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.AcademicId AND SR.AttendanceTypeId = 1
		WHERE SA.AcademicId = @rAcademicId  
		AND DATEPART(MONTH,SR.AttendanceDate) = @rMonth
		AND DATEPART(YEAR,SR.AttendanceDate) = @rYear 
		AND SR.IsPresent = 1
		GROUP BY SR.AcademicId
	END
    ELSE IF(@rPresent = 2)
    BEGIN
		SELECT @lCount = COUNT(SR.AcademicId)
		FROM sStudent.vStudentAcademic SA
		INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.AcademicId AND SR.AttendanceTypeId = 1
		WHERE SA.AcademicId = @rAcademicId  
		AND DATEPART(MONTH,SR.AttendanceDate) = @rMonth
		AND DATEPART(YEAR,SR.AttendanceDate) = @rYear 
		AND SR.IsPresent = 0
		GROUP BY SR.AcademicId
	END
	RETURN @lCount 
END
GO
PRINT N'Creating [sBiometric].[fEmployeeTravelGet]...';


GO
 

CREATE FUNCTION [sBiometric].[fEmployeeTravelGet](@rDate date, @rEmployeeId bigint)
RETURNS [nvarchar](200) WITH EXECUTE AS CALLER
AS 
BEGIN
DECLARE @lEmployeeTravel nvarchar(200)=''
SELECT @lEmployeeTravel = 'Travel'
FROM 
sHrm.tEmployeeTravel ET 
WHERE 
ET.StatusId = 642 
AND ET.EmployeeId = @rEmployeeId 
AND @rDate BETWEEN ET.TravelFromDate AND ET.TravelToDate
RETURN  ISNULL(@lEmployeeTravel,'')
END
GO
PRINT N'Creating [sCommon].[fnSplitRowID]...';


GO

CREATE FUNCTION [sCommon].[fnSplitRowID](@sInputList [nvarchar](max), @sDelimiter [nvarchar](100) = ',')
RETURNS @List TABLE (RowID int IDENTITY(1,1),[item] [nvarchar](1000) NULL
) WITH EXECUTE AS CALLER
AS 
BEGIN
DECLARE @sItem VARCHAR(8000)
WHILE CHARINDEX(@sDelimiter,@sInputList,0) <> 0
 BEGIN
 SELECT
  @sItem=RTRIM(LTRIM(SUBSTRING(@sInputList,1,CHARINDEX(@sDelimiter,@sInputList,0)-1))),
  @sInputList=RTRIM(LTRIM(SUBSTRING(@sInputList,CHARINDEX(@sDelimiter,@sInputList,0)+LEN(@sDelimiter),LEN(@sInputList))))
 
 IF LEN(@sItem) > 0
  INSERT INTO @List SELECT @sItem
 END

IF LEN(@sInputList) > 0
 INSERT INTO @List SELECT @sInputList -- Put the last item in
RETURN
END
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.SUId,
		 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.ChequeDate,
	     R.ChequeClearDate,
	     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.ChequeDate,
	     R.ChequeClearDate,
	     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,
	     SA.SUId
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'Altering [sSetup].[vExamSubject]...';


GO










/******************************************************************************  
 Purpose          : To get Batch Wise  Class
 Created date     : 21 Nov 2013
 Author           : Kundan Patel 
 Copyright©       : Copyright © Sapphire Software Solutions
 ******************************************************************************/  
ALTER VIEW [sSetup].[vExamSubject]  
  
AS  
  
SELECT 	
	  SM.Id AS SubjectId,
	  ED.Id AS ExamDetailId,
	  ED.ExamId,
	  SM.Title AS SubjectName,
	  SM.IsObsolete,
	  ED.DisplayOrder AS OrderIndex,
	  CS.Id AS ClassSubjectId,
	  SM.Code As SubjectCode
	  	   
  FROM 
  
	sAssessment.tExamDetail ED
	INNER JOIN sSetup.tClassSubject CS ON CS.Id = ED.ClassSubjectId
	INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = CS.SubjectId
GO
PRINT N'Altering [sStudent].[vStudentCustomSearch]...';


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


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


GO








 
ALTER VIEW [sStudent].[vStudentVerification]  
  
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.StatusId,
	  CM.DisplayTitle AS ClassName,
	  DM.DisplayTitle AS DivisionName,	   
	  SM.RecordStatusId,	  
	  DM.InchargeEmployeeId, 
	  BM.OrgGroupBatchId,	  
	  SM.AdmissionCategoryId,
	  DM.OrderIndex DivisionOrder,
	  BM.IsActive AS IsActiveBatch,
	  BM.Title AS BatchName,
	  SM.IsBlackList,
	  SM.BlackListReason,
	  CM.OrderIndex AS ClassOrderIndex,
	  ISNULL(A.ExemptionTypeId,0) AS ExemptionTypeId,
	  ISNULL(SM.SUId,'') AS SUId ,
	  SA.AdmissionDate,
	  SA.PreviousSchool,
	  SO.DateOfBirth,
	  SO.BirthPlace,
	  GEN.Title As Gender,
	  SO.FamilyCast,
	  CC.Title As CastCatagory,
	  SO.MotherTongue,
	  --NM.Title AS Nationality,
	  SF.FatherName,
	 SF.FatherContactNo,
	 sf.MotherName,
	 SF.MotherContactNo,
	 SC.PresentStreetOne,
	 SC.PresentStreetTwo,
	 SC.PresentStreetThree,
	 SC.StudentContactNo,
	 SO.UIDNumber,
	 SO.AdhaarNumber,
	 STA.BankBranch,
	 STA.BankAccountNumber,
	 STA.BankName,
	 STA.BankIFSCCode,
	Dept.ID as DepartmentId,
	  SA.ADMISSIONStandardId,
	  NM.OrgGroupId,
	   [sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Name,
	   R.Title As Religion,
	   SC.StudentEmail,
	   CON.Nationality
	  
	  
	  
  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 sStudent.tStudentAdmission SA ON SA.StudentID=SM.Id   
	INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
	INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId 
	LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=SM.Id
	INNER JOIN sCommon.tGenderMaster GEN ON GEN.Id=SO.GenderId
	LEFT JOIN sCommon.tCastCategoryMaster CC oN CC.Id=SO.CastCategoryId
	LEFT JOIN sCommon.tNationalityMaster NM ON NM.Id=SO.NationalityId 
	LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SM.Id
	LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId =SM.Id
	LEFT JOIN sStudent.tStudentAdditional STA ON STA.StudentId=Sm.Id
	INNER JOIN sSetup.tDepartmentMaster Dept ON Dept.Id=Cm.DepartmentId
	LEFT JOIN sCommon.tReligionMaster R ON R.id=SO.ReligionId
 INNER JOIN sSetup.tOrganizationMaster OM
	    ON SM.OrgId = OM.Id
	LEFT JOIN sCommon.tCountryMaster CON ON CON.ID = SO.NationalityID
GO




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


GO
ALTER PROCEDURE [sAcademic].[pClassworkStudentGet]
	 @rStudentId bigint,
	 @rBatchId int,	 
	 @rFromDate date='',
     @rToDate date='',
     @rHomeWorkEndDate	date='' 
    
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	DECLARE @lDivisionId int
	SELECT @lDivisionId = DivisionId FROM sStudent.tAcademic WHERE StudentId = @rStudentId AND BatchId = @rBatchId
	
	SELECT 
			AC.Id,
			AC.EmployeeId,
			AC.ClassId,
			AC.DivisionId,
			AC.SubjectId,
		    AC.Classwork,
		    AC.Homework,
		    AC.ClassWorkDate,
		    AC.HomeWorkEndDate,
		    --ISNULL(AC.HomeWorkEndDate,'') AS HomeWorkEndDate,
		    ISNULL(SM.Title,'') as SubjectName,
		    ISNULL(EM.FirstName +' ' + EM.LastName,'') AS TeacherName,
		    ISNULL(CM.Title,'') AS ClassName,
		    ISNULL(DM.Title,'') AS DivisionName,
		    DM.OrgId
	FROM 
			sAcademic.tClasswork AC			 
			INNER Join sSetup.tSubjectMaster SM On SM.Id=AC.SubjectId
			INNER Join sHrm.tEmployeeMaster EM On EM.Id = AC.EmployeeId
			INNER Join sSetup.tClassMaster CM On CM.Id = AC.ClassId
			INNER Join sSetup.tDivisionMaster DM On DM.Id = AC.DivisionId
			
	WHERE 
	    AC.DivisionId = @lDivisionId		 
		AND (AC.ClassWorkDate>=@rFromDate OR ISNULL(@rFromDate,'')='')
		AND (AC.ClassWorkDate<=@rToDate OR ISNULL(@rToDate,'')='')
		AND (AC.HomeWorkEndDate>=@rHomeWorkEndDate OR ISNULL(@rHomeWorkEndDate,'')='')
		order by  AC.CreatedDateTime desc
END
GO
PRINT N'Altering [sAccounting].[pExpenseGroupMasterAdd]...';


GO

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

	END
	
	
	
	 --BEGIN TRANSACTION	
	 DECLARE @lNextNumber int

	IF(@rId = 0)	
	BEGIN
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAccounting.tExpenseGroupMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	--EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sCanteen.tCanteenMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	INSERT INTO sAccounting.tExpenseGroupMaster
		(
			OrgId,
			Id, 
			Code,
			Title, 
			IsObsolete,			
		    CreatedUserId, 
		    CreatedDateTime, 
		    UpdatedUserId, 
            UpdatedDateTime
		)
	VALUES
		(
		    @rOrgId ,
			@lNextNumber , 
			@rCode ,      
			@rTitle ,	
			@rIsObsolete,				
			@rCreatedUserId ,
			sCommon.fGetDate() ,
			@rUpdatedUserId ,
			sCommon.fGetDate()									
		)
		
		   SELECT 1 AS Result
	END	 

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

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


GO
ALTER PROCEDURE [sAccounting].[pExpenseListingModify]
           
        @rId bigint,
        @rEmployeeId bigint,
      
        @rOrgId smallint,
        @rStatusId int,
        @rStatusReason nvarchar(100)
        --@rLeaveRemark nvarchar(200) 
        
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	
	BEGIN TRANSACTION

	BEGIN
		UPDATE sAccounting.tExpense 
		SET 	 
		  [StatusId]=@rStatusId,
		  StatusReason=@rStatusReason
                            
		WHERE EmployeeId = @rEmployeeId AND Id=@rId
	 END 
	   SELECT @rEmployeeId AS Result	   
	   COMMIT TRANSACTION
	END TRY	
	BEGIN CATCH
		ROLLBACK TRANSACTION
		SELECT -1 AS RESULT
	END CATCH
END
GO
PRINT N'Altering [sAccounting].[pExpenseOfCandidateAdd]...';


GO

ALTER PROCEDURE [sAccounting].[pExpenseOfCandidateAdd]
	 
	 @rOrgId smallint,
	 @rId int,
	 @rEmployeeId bigint,
	 @rExpenseDate date,
	 @rExpenseGroupId int,
	 @rAmount decimal(12,2),
	 @rRemark nvarchar(200),
	 @rCreatedUserId bigint,
	 --@rCreatedDateTime datetime,
	 @rUpdatedUserId bigint,
	 --@rUpdatedDateTime datetime,
	 @rStatusId int,
	 @rExpenseDetailXml nvarchar(max)
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rExpenseDetailXml
BEGIN
	--BEGIN TRY
	
	-- BEGIN TRANSACTION	
	 DECLARE @lNextNumber int

			IF(@rId = 0)	
			BEGIN
			EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAccounting.tExpense', 0, 1, 1,@outNextNumber = @lNextNumber output
			--EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sCanteen.tCanteenMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
			INSERT INTO  sAccounting.tExpense
			(
			OrgId,
			Id,
			EmployeeId	,
			ExpenseDate	,
			ExpenseGroupId,
			Amount,
			Remark,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime,
			StatusId	
			)
			VALUES
			(
		    @rOrgId ,
			@lNextNumber ,
			@rEmployeeId ,
			@rExpenseDate ,
			@rExpenseGroupId ,
			@rAmount ,
			@rRemark ,
			@rCreatedUserId ,
			sCommon.fGetDate() ,
			@rUpdatedUserId ,
			sCommon.fGetDate(),	
			@rStatusId 								
			)
		
			INSERT INTO sAccounting.tExpenseDetail
			(ExpenseId,ExpenseSubGroupId,Amount,Remark)
			SELECT @lNextNumber,ExpenseSubGroupId,Amount,Remark
			FROM OPENXML (@loDoc, '/Table/ExpenseDetail', 1)
			WITH (ExpenseSubGroupId int,Amount decimal(12,2),Remark nvarchar(200)) 
		    SELECT 1 AS Result
			END	 

	ELSE
			BEGIN
			SET @lNextNumber = @rId
			UPDATE  sAccounting.tExpense
		    SET
	    
			ExpenseDate=@rExpenseDate,
			ExpenseGroupId=@rExpenseGroupId,
			Amount=@rAmount,
			Remark=@rRemark,			
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate(),
			StatusId=@rStatusId
	    
			WHERE Id = @rId
			DELETE sAccounting.tExpenseDetail WHERE ExpenseId= @rId
			INSERT INTO sAccounting.tExpenseDetail
			(ExpenseId,ExpenseSubGroupId,Amount,Remark)
			SELECT @lNextNumber,ExpenseSubGroupId,Amount,Remark
			FROM OPENXML (@loDoc, '/Table/ExpenseDetail', 1)
			WITH (ExpenseSubGroupId int,Amount decimal(12,2),Remark nvarchar(200)) 
	 SELECT 11 AS Result
	 END  	

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


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

BEGIN 		
		
	SELECT 
			DM.Id  as SourceId,
			CM.Title+'-'+DM.Title as DivDept,
			2005 as SourceTypeId,
			CASE WHEN EA.SourceId IS NULL OR EA.EventScheduleId!=@rEventScheduleId THEN 0 ELSE 1 END AS IsObsolete
  FROM 
			sSetup.tDivisionMaster DM
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=DM.ClassId
			INNER JOIN sSetup.tBatchClass BC ON CM.Id=BC.ClassId AND BC.BatchId=@rBatchId
			LEFT JOIN sActivity.tEventAssign EA ON EA.SourceId=DM.Id AND EA.SourceTypeId=2005 AND EA.EventScheduleId=@rEventScheduleId
	 WHERE
		DM.OrgId=@rOrgId
		UNION
	SELECT 
			ODM.Id  as SourceId,
			ODM.Title as DivDept,
			2004 as SourceTypeId,
			CASE WHEN EA.SourceId IS NULL OR EA.EventScheduleId!=@rEventScheduleId THEN 0 ELSE 1 END AS IsObsolete
  FROM 
			sSetup.tDepartmentMaster ODM
			LEFT JOIN sActivity.tEventAssign EA ON EA.SourceId=ODM.Id AND EA.SourceTypeId=2004 AND EA.EventScheduleId=@rEventScheduleId
	WHERE
		ODM.OrgId=@rOrgId
END
GO
PRINT N'Altering [sActivity].[pMyEventGet]...';


GO
ALTER PROCEDURE [sActivity].[pMyEventGet]
	 
	 @rSourceTypeId smallint,
	 @rSourceId bigint,
	 @rOrgId smallint,
	 @rBatchId int,
	 @rFromDate date='',
	 @rTodate date=''
	 --@rSyncedEventScheduleId int = 0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	IF(@rSourceTypeId=2003)
	BEGIN
		SELECT
				ISNULL(EE.Id,0) AS Id,
				ES.Id AS EventScheduleId,
				ES.Title,
				ES.FromDate,
				ES.ToDate,
				ES.IsCommonForAll,
				ES.IsHoliday,
				ES.IsEnrollment,
				ES.CreatedDateTime,
				ES.Remark AS Remark,
				EE.Remark AS EventEnrollmentRemark
		FROM 
				sActivity.tEventSchedule ES
			LEFT JOIN sActivity.tEventEnrollment EE ON EE.EventScheduleId=ES.Id AND EE.SourceId=@rSourceId AND EE.SourceTypeId=2003
		WHERE 
	        
			 ((ES.Id IN(SELECT EventScheduleId FROM sActivity.tEventAssign WHERE SourceTypeId=2005 AND 
				SourceId=(SELECT DivisionId FROM sStudent.vStudentName WHERE StudentId=@rSourceId 
					AND OrgId=@rOrgId AND BatchId=@rBatchId))) OR ES.ISCommonForAll = 1)
					
		AND (ES.BatchId=@rBatchId) 
		AND ((Convert(date,ES.FromDate)<=@rFromDate) OR ISNULL(@rFromDate,'')='')
		AND ((Convert(date,ES.Todate)>=@rTodate) OR ISNULL(@rTodate,'')='')
		--AND (ES.Id > @rSyncedEventScheduleId OR @rSyncedEventScheduleId = 0)
		ORDER BY ES.FromDate DESC
		
		
		
	END
	ELSE
	BEGIN
		SELECT
				ISNULL(EE.Id,0) AS Id,
				ES.Id AS EventScheduleId,
				ES.Title,
				ES.FromDate,
				ES.ToDate,
				ES.IsCommonForAll,
				ES.IsHoliday,
				ES.IsEnrollment,
				ES.CreatedDateTime,
				ES.Remark AS Remark,
				EE.Remark AS EventEnrollmentRemark
		FROM 
				sActivity.tEventSchedule ES
			LEFT JOIN sActivity.tEventEnrollment EE ON EE.EventScheduleId=ES.Id AND EE.SourceId=@rSourceId AND EE.SourceTypeId=95
		WHERE 
	  
			 (ES.Id IN(SELECT EventScheduleId FROM sActivity.tEventAssign WHERE SourceTypeId=2004 AND 
				SourceId=(SELECT OrganizationDepartmentId FROM sHrm.vExtEmployeeJobDetail WHERE EmployeeId=@rSourceId))) 
		AND (ES.BatchId=@rBatchId)
	   AND ((Convert(date,ES.FromDate)<=@rFromDate) OR ISNULL(@rFromDate,'')='')
		AND ((Convert(date,ES.Todate)>=@rTodate) OR ISNULL(@rTodate,'')='')
		--AND (ES.Id > @rSyncedEventScheduleId OR @rSyncedEventScheduleId = 0)
		ORDER BY ES.FromDate DESC
	END
END
GO
PRINT N'Altering [sAdmission].[pAdmissionCriteriaSetupAdd]...';


GO

ALTER PROCEDURE [sAdmission].[pAdmissionCriteriaSetupAdd]
		@rClassId int
		,@rBatchId int
		,@rIsValidateBirthdate bit
		,@rFromDateOfBirth date
		,@rToDateOfBirth date
		,@rIsParentAcademicRequired bit
		,@rIsStudentAcademicRequired bit
		,@rIsFamilyDetailRequired bit
		,@rIsSiblingDetailRequired bit
		,@rIsReferenceDetailRequired bit
		
		,@rIsFixStudentAcademic bit
		,@rStudentAcademicFor nvarchar(300)
		,@rStudentAcademicRemark nvarchar(max)
		,@rFamilyDetailRemark nvarchar(max)
		,@rIsFixParentAcademic bit
		,@rParentAcademicFor nvarchar(300)
		,@rParentAcademicRemark nvarchar(max)
		,@rConfirmationRemark nvarchar(max)
		,@rAdmissionFormRemark nvarchar(max),
		@rReference1 nvarchar(150),
		@rReference2 nvarchar(150),
		@rIsOtherInformationRequired bit,
		@rIsPayFormFeeOnline bit = NULL,
		@rFormFeeName nvarchar(100)=NULL,
		@rFormFeeAmount decimal(12,2)=NULL,
		@rIsHostelDetailRequired	bit	,
		@rIsTransportDetailRequired	bit	,
		@rIsHealthDetailRequired	bit	,
		@rIsBirthPlaceDetailRequired	bit	,
		@rIsAadhaarDetailRequired	bit	,
		@rIsBloodGroupDetailRequired	bit,
		@rReceiptBookId int = NULL	
		
		
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	--BEGIN TRY
	

	
 BEGIN TRANSACTION	
	
	IF(@rFormFeeAmount=0)
		SET @rFormFeeAmount=NULL
	
	Delete from sAdmission.tAdmissionCriteria where ClassId=@rClassId AND BatchId=@rBatchId

	INSERT INTO sAdmission.tAdmissionCriteria
		(
			 ClassId
			 ,BatchId
			 ,IsValidateBirthdate
			 ,FromDateOfBirth
			,ToDateOfBirth
			,IsParentAcademicRequired
			,IsStudentAcademicRequired
			,IsFamilyDetailRequired
			,IsSiblingDetailRequired
			,IsReferenceDetailRequired
			
			,IsFixStudentAcademic
			,StudentAcademicFor
			,StudentAcademicRemark
			,FamilyDetailRemark
			,IsFixParentAcademic
			,ParentAcademicFor
			,ParentAcademicRemark
			,ConfirmationRemark
			,AdmissionFormRemark,
			Reference1,
			Reference2,
			IsOtherInformationRequired,
			IsPayFormFeeOnline,
			FormFeeName,
			FormFeeAmount,
			IsHostelDetailRequired,
			IsTransportDetailRequired,
			IsHealthDetailRequired,
			IsBirthPlaceDetailRequired,
			IsAadhaarDetailRequired,
			IsBloodGroupDetailRequired,
			ReceiptBookId	
		)
	VALUES
		(
			 @rClassId
			,@rBatchId
			,@rIsValidateBirthdate
			,@rFromDateOfBirth
			,@rToDateOfBirth
			,@rIsParentAcademicRequired
			,@rIsStudentAcademicRequired
			,@rIsFamilyDetailRequired
			,@rIsSiblingDetailRequired
			,@rIsReferenceDetailRequired
			
			,@rIsFixStudentAcademic
			,@rStudentAcademicFor
			,@rStudentAcademicRemark
			,@rFamilyDetailRemark
			,@rIsFixParentAcademic
			,@rParentAcademicFor
			,@rParentAcademicRemark
			,@rConfirmationRemark
			,@rAdmissionFormRemark,
			@rReference1,
			@rReference2,
			@rIsOtherInformationRequired,
			@rIsPayFormFeeOnline,
			@rFormFeeName,
			@rFormFeeAmount,
			@rIsHostelDetailRequired,
			@rIsTransportDetailRequired,
			@rIsHealthDetailRequired,
			@rIsBirthPlaceDetailRequired,
			@rIsAadhaarDetailRequired,
			@rIsBloodGroupDetailRequired,	
			@rReceiptBookId
			
		)
		     SELECT 103 AS Result
	
		COMMIT TRANSACTION
	
			
END
GO
PRINT N'Altering [sAdmission].[pAdmissionCriteriaSetupGet]...';


GO


ALTER PROCEDURE [sAdmission].[pAdmissionCriteriaSetupGet]
	 
	 @rClassId int=0,
	 @rBatchId int=0
	 
	  

	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
	 

BEGIN 
	 
	 
	
	SELECT 
		
		ClassId,
		BatchId,
		ISNULL(IsValidateBirthdate,'') AS IsValidateBirthdate,
		ISNULL(FromDateOfBirth,'') AS FromDateOfBirth,
		ISNULL(ToDateOfBirth,'')AS ToDateOfBirth,
		ISNULL(IsParentAcademicRequired,'') AS IsParentAcademicRequired,
		ISNULL(IsStudentAcademicRequired,'') AS IsStudentAcademicRequired,
		ISNULL(IsFamilyDetailRequired,'') AS IsFamilyDetailRequired,
		ISNULL(IsSiblingDetailRequired,'') AS IsSiblingDetailRequired,
		ISNULL(IsReferenceDetailRequired,'') AS IsReferenceDetailRequired,
		
		ISNULL(IsFixStudentAcademic,'') AS IsFixStudentAcademic,
		StudentAcademicFor,
		StudentAcademicRemark,
		FamilyDetailRemark,
		ISNULL(IsFixParentAcademic,'') AS IsFixParentAcademic,
		ParentAcademicFor,
		ParentAcademicRemark,
		ConfirmationRemark,
		AdmissionFormRemark,
		ISNULL(Reference1,'') AS Reference1,
		ISNULL(Reference2,'')AS Reference2,
		ISNULL(IsOtherInformationRequired,0) As IsOtherInformationRequired,
		ISNULL(IsPayFormFeeOnline,0) AS IsPayFormFeeOnline,
		ISNULL(FormFeeName,'') AS FormFeeName,
		ISNULL(FormFeeAmount,0) AS FormFeeAmount,
		ISNULL(IsHostelDetailRequired,0) AS IsHostelDetailRequired,
		ISNULL(IsTransportDetailRequired,0) AS IsTransportDetailRequired,
		ISNULL(IsHealthDetailRequired,0) AS IsHealthDetailRequired,
		ISNULL(IsBirthPlaceDetailRequired,0) AS IsBirthPlaceDetailRequired,
		ISNULL(IsAadhaarDetailRequired,0) AS IsAadhaarDetailRequired,
		ISNULL(IsBloodGroupDetailRequired,0) AS IsBloodGroupDetailRequired,
		ISNULL(ReceiptBookId,0) AS ReceiptBookId
  FROM 
            sAdmission.tAdmissionCriteria
			 
  WHERE 
   (ClassId=@rClassId)
   AND BatchId=@rBatchId
	
END
GO
PRINT N'Altering [sAdmission].[pAdmissionFormAdd]...';


GO
ALTER PROCEDURE [sAdmission].[pAdmissionFormAdd]
		 @rId bigint
		,@rFormNo int
		,@rFirstName nvarchar(100)
		,@rMiddleName nvarchar(100)
		,@rLastName	nvarchar(100)
		,@rForClassId int
		,@rForBatchId	int		 
		,@rDateOfBirth date
		,@rDateOfBirthInWord nvarchar(100)
		,@rOrgId smallint
		,@rBatchId int
		,@rStatusId	smallint
		,@rStreetOne nvarchar(50)
		,@rStreetTwo nvarchar(50)
		,@rStreetThree nvarchar(50)
		,@rCountry nvarchar(50)
		,@rState nvarchar(50)
		,@rCity	nvarchar(50)
		,@rZipCode	nvarchar(20)
		,@rContactNo nvarchar(20)
		,@rContactEmail	nvarchar(50)
		,@rRemark nvarchar(200)
		,@rPreviousSchool nvarchar(200)
		,@rMeritMarks decimal(10, 2)
		,@rMeritGrade nvarchar(20)
		,@rGenderId	int
		,@rReligionId int
		,@rFamilyCast nvarchar(100)
		,@rFamilySubCast nvarchar(100)
		,@rCastCategoryId int
		,@rCreatedUserId bigint
		,@rFormPassword nvarchar(100)=''
		,@rDataEntryModeId smallint
		,@rDataEntryStatusId smallint
		,@rStudentPhoto varbinary(max),
		 @rNationality nvarchar(150),
		 @rMotherTongue nvarchar(150),
		 @rOtherInformation nvarchar(150),
		 @rIsPysicalDeformity bit,
		 @rPysicalDeformityRemark nvarchar(200),
         @rIsMajorIllness bit,
         @rMajorIllnessRemark nvarchar(200),
         @rIsAllergy bit,
         @rAllergyRemark nvarchar(200),
         @rBirthPlace nvarchar(150),
         @rBirthTaluka nvarchar(150),
         @rBirthDistrict nvarchar(150),
         @rBloodGroupId tinyint,
         @rAdhaarNumber nvarchar(20),
         @rIsHostelRequired bit=0,
		 @rIsTransportRequired bit=0,
		 @rBirthState nvarchar(150)='',
		 @rBirthCountry nvarchar(150)=''
		
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	--BEGIN TRY
		
 BEGIN TRANSACTION	
 DECLARE @lNextNumber BIGINT
 DECLARE @lBIGID BIGINT
 DECLARE @lSMALLID INT
 
 IF(@rId = 0)	
	BEGIN
	
	
	
		IF Exists(select FormNo from sAdmission.tAdmissionForm where FormNo=@rFormNo AND BatchId=@rBatchId)
			BEGIN
			select -101 as Result
			RETURN
		END 
	
	--EXECUTE sCommon.pPrefixSetupNextNumberGet @rOrgId = @rOrgId, @rPrefixFunctionalityId = 2006,@rStoreLocationId = 0, @rNextNumber  = @rFormNo OUTPUT

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

	--	IF @rFormNo = '-300'
	--  BEGIN
	--	SELECT -300 AS Result, '' AS Number, 0 AS Id 
	--	RETURN
	--  END
	IF(@rFormNo = 0)
	BEGIN
	SELECT @rFormNo = ISNULL(MAX(FormNo),0) + 1 FROM sAdmission.tAdmissionForm WHERE BatchId=@rBatchId
	
	END
	
	IF(@rFormPassword = '')
	BEGIN
	SELECT @rFormPassword = @rFormNo
	
	END
	
	
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAdmission.tAdmissionForm', 0, 1, 1,@outNextNumber = @lNextNumber output
	
--SET	 @lBIGID  = @lNextNumber
--SET	 @lSMALLID  = CONVERT(int, @lBIGID)
	-- IF(@rFormNo = 0)
	-- BEGIN
	-- select convert(int,@lNextNumber)
	--SET @rFormNo = ISNULL(@rFormNo,@lNextNumber)
	--END
	INSERT INTO sAdmission.tAdmissionForm
		(
			 Id
			,FormNo
			,FirstName
			,MiddleName
			,LastName
			,ForClassId			 
			,ForBatchId
			,DateOfBirth
			,DateOfBirthInWord
			,OrgId
			,BatchId
			,StatusId
			,StreetOne
			,StreetTwo
			,StreetThree
			,Country
			,State
			,City
			,ZipCode
			,ContactNo
			,ContactEmail
			,Remark
			,PreviousSchool
			,MeritMarks
			,MeritGrade
			,GenderId
			,ReligionId
			,FamilyCast
			,FamilySubCast
			,CastCategoryId
			,CreatedUserId
			,CreatedDateTime
			,FormPassword
			,DataEntryModeId
			,DataEntryStatusId
			,StudentPhoto,
			Nationality,
			MotherTongue,
			OtherInformation,
			IsPysicalDeformity,
           PysicalDeformityRemark,
           IsMajorIllness,
           MajorIllnessRemark,
           IsAllergy,
           AllergyRemark,
           BirthPlace,
         BirthTaluka,
         BirthDistrict,
         BloodGroupId,
         AdhaarNumber,
         IsHostelRequired,
         IsTransportRequired,
         BirthState,
         BirthCountry
			
		)
	VALUES
		(
			 @lNextNumber
			,@rFormNo
			,@rFirstName
			,@rMiddleName
			,@rLastName
			,@rForClassId			 
			,@rForBatchId
			,@rDateOfBirth
			,@rDateOfBirthInWord
			,@rOrgId
			,@rBatchId
			,@rStatusId
			,@rStreetOne
			,@rStreetTwo
			,@rStreetThree
			,@rCountry
			,@rState
			,@rCity
			,@rZipCode
			,@rContactNo
			,@rContactEmail
			,@rRemark
			,@rPreviousSchool
			,@rMeritMarks
			,@rMeritGrade
			,@rGenderId
			,@rReligionId
			,@rFamilyCast
			,@rFamilySubCast
			,@rCastCategoryId
			,@rCreatedUserId
			,sCommon.fGetDate()
			,@rFormPassword
			,@rDataEntryModeId
			,@rDataEntryStatusId
			,@rStudentPhoto,
			@rNationality,
			@rMotherTongue,
			@rOtherInformation,
			@rIsPysicalDeformity,
			   @rPysicalDeformityRemark,
			   @rIsMajorIllness,
			   @rMajorIllnessRemark,
			   @rIsAllergy,
			   @rAllergyRemark,
			  @rBirthPlace,
			 @rBirthTaluka,
			 @rBirthDistrict,
			 @rBloodGroupId,
			 @rAdhaarNumber,
			 @rIsHostelRequired,
			 @rIsTransportRequired,
			 @rBirthState,
			@rBirthCountry
		)
		             
	END	 
	 ELSE
	 BEGIN
	 
	 
	 
	 	IF Exists(select FormNo from sAdmission.tAdmissionForm where FormNo=@rFormNo AND BatchId=@rBatchId And Id <> @rId)
			BEGIN
			select -101 as Result
			RETURN
		END 
	
	 
	 
	 SET @lNextNumber = @rId
	    UPDATE  sAdmission.tAdmissionForm
	    SET
	        FormNo = @rFormNo
			,FirstName=@rFirstName
			,MiddleName=@rMiddleName
			,LastName=@rLastName
			,ForClassId=@rForClassId			
			,DateOfBirth=@rDateOfBirth
			,DateOfBirthInWord=@rDateOfBirthInWord
			,StatusId=@rStatusId
			,StreetOne=@rStreetOne
			,StreetTwo=@rStreetTwo
			,StreetThree=@rStreetThree
			,Country=@rCountry
			,State=@rState
			,City=@rCity
			,ZipCode=@rZipCode
			,ContactNo=@rContactNo
			,ContactEmail=@rContactEmail
			,Remark=@rRemark
			,PreviousSchool=@rPreviousSchool
			,MeritMarks=@rMeritMarks
			,MeritGrade=@rMeritGrade
			,GenderId=@rGenderId
			,ReligionId=@rReligionId
			,FamilyCast=@rFamilyCast
			,FamilySubCast=@rFamilySubCast
			,CastCategoryId=@rCastCategoryId
			,UpdatedUserId=@rCreatedUserId
			,UpdatedDateTime=sCommon.fGetDate()
			--,DataEntryModeId = @rDataEntryModeId
			--,DataEntryStatusId = @rDataEntryStatusId
			,StudentPhoto = @rStudentPhoto,
			Nationality =@rNationality,
			MotherTongue=@rMotherTongue,
			OtherInformation=@rOtherInformation,
			IsPysicalDeformity=@rIsPysicalDeformity,
           PysicalDeformityRemark=@rPysicalDeformityRemark,
           IsMajorIllness=@rIsMajorIllness,
           MajorIllnessRemark=@rMajorIllnessRemark,
           IsAllergy=@rIsAllergy,
           AllergyRemark=@rAllergyRemark,
           BirthPlace=@rBirthPlace,
		   BirthTaluka=@rBirthTaluka,
			BirthDistrict=@rBirthDistrict,
			BloodGroupId=@rBloodGroupId,
			AdhaarNumber=@rAdhaarNumber,
			IsHostelRequired= @rIsHostelRequired,
			IsTransportRequired=@rIsTransportRequired,
			BirthState=@rBirthState,
			BirthCountry=@rBirthCountry
	      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 [sAdmission].[pAdmissionFormGet]...';


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

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


GO
ALTER PROCEDURE [sAdmission].[pAdmissionFormOnlineGet]
	 @rAdmissionFormId bigint = 0,
	 @rFormNo int,
	 @rOrgId int
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
		
	SELECT 
			iSNULL(Id,0) as id,
			FormNo,
			FirstName,
			MiddleName,
			LastName,
			ForClassId,
			iSNULL(ForBatchId, 0) as ForBatchId,
			ForBatch,
			DateOfBirth,
			DateOfBirthInWord,
			OrgId,
			BatchId,
			StatusId,
			StreetOne,
			StreetTwo,
			StreetThree,
			Country,
			State,
			City,
			ZipCode,
			ContactNo,
			ContactEmail,
			Remark,
			PreviousSchool,
			MeritMarks,
			MeritGrade,
			iSNULL(GenderId,0) as GenderId,
			iSNULL(ReligionId,0) as ReligionId ,
			FamilyCast,
			FamilySubCast,
			iSNULL(CastCategoryId,0) as CastCategoryId,
			CreatedUserId,
			CreatedDateTime,
			iSNULL(UpdatedUserId,0) aS UpdatedUserId,
			UpdatedDateTime,
			iSNULL(StudentId,0) as StudentId,
			FormPassword,
			iSNULL(DataEntryModeId,0) as DataEntryModeId,
			iSNULL(DataEntryStatusId,0) as DataEntryStatusId,
			StudentPhoto,
			iSNULL(AdmissionCategoryId,0) AS AdmissionCategoryId,
			Nationality,
			MotherTongue,
			OtherInformation,
			iSNULL(IsPysicalDeformity,0) aS IsPysicalDeformity ,
			PysicalDeformityRemark,
			iSNULL(IsMajorIllness,0) aS IsMajorIllness ,
			MajorIllnessRemark,
			iSNULL(IsAllergy,0) aS IsAllergy,
			AllergyRemark,
			BirthPlace,
			BirthTaluka,
			BirthDistrict,
			iSNULL(BloodGroupId,0) AS  BloodGroupId,
			AdhaarNumber,
			iSNULL(IsHostelRequired,0) as IsHostelRequired,
			iSNULL(IsTransportRequired,0) as IsTransportRequired,
			BirthState,
			BirthCountry
  FROM 
           sAdmission.tAdmissionForm AF
  WHERE 
  
      ((AF.Id = @rAdmissionFormId) OR (@rAdmissionFormId = 0))
		AND ((AF.FormNo=@rFormNo) OR (@rFormNo=0))
		AND AF.OrgId=@rOrgId
       
 order by AF.FormNo
END
GO
PRINT N'Altering [sAdmission].[pRptAdmissionFormGet]...';


GO


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

AS
 SET NOCOUNT ON
			 

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

				
END
GO
PRINT N'Altering [sAppraisal].[pConductAdd]...';


GO
/******************************
** Name:  [sAppraisal].[pConductTypeMasterAdd]
** Desc:  Create and Update Data in Loan ConductTypeMaster
** Auth:  Savan Vaghela
** Date:  08-March-2017
** Page:  /Pages/Hrm/Appraisal/ConductTypeMaster.aspx
************************************************************
** Change History
************************************************************
** PR      Date                Author            Description 
**
** 1    08-March-2017      Savan Vaghela       
************************************************************/
--[sAppraisal].[pConductAdd]
ALTER PROCEDURE [sAppraisal].[pConductAdd]
	    @rId BIGINT,
		@rConductDate DATETIME,
		@rEmployeeId BIGINT,
		@rConductTypeId INT,
		@rBatchId int,
		@rTitle nvarchar(100),
		@rRemark nvarchar(400),
		@rOrgId SmallINT,
		@rOrgGroupId SmallINT,
		@rCreatedUserId BIGINT		       
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
		--IF(@rId = 0)	
		--	BEGIN
		--		IF Exists(SELECT Id FROM [sAppraisal].[tConductTypeMaster]  WHERE Title=@rTitle AND OrgGroupId=@rOrgGroupId )
		--			BEGIN
		--				SELECT -102 as Result
		--				RETURN
		--			END 
		--	END
		
		--ELSE
		--	BEGIN
		--		IF  Exists(SELECT Id FROM [sAppraisal].[tConductTypeMaster]  WHERE Title=@rTitle AND OrgGroupId=@rOrgGroupId AND Id<>@rId )
		--			BEGIN
		--				SELECT -102 as Result
		--				RETURN
		--			END
		--	END
	
		BEGIN TRANSACTION	
		DECLARE @lNextNumber BIGINT 
	
		IF(@rId = 0)	
			BEGIN
				EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAppraisal.tConduct', 0, 1, 1,@outNextNumber = @lNextNumber output
				INSERT INTO [sAppraisal].[tConduct]
				(
					Id,
					ConductDate,
					EmployeeId,
					ConductTypeId,
					Title,
					Remark,
					BatchId,
					CreatedUserId,
					CreatedDateTime
					
				)
				VALUES
				(
					@lNextNumber,
					@rConductDate,
					@rEmployeeId,
					@rConductTypeId,
					@rTitle,
					@rRemark,
					@rBatchId,
					@rCreatedUserId,
					sCommon.fGetDate()
					
				)
				SELECT 1 AS Result
			END	 
		ELSE
			BEGIN
			SET @lNextNumber = @rId
				UPDATE  [sAppraisal].[tConduct]
				SET
					Title=@rTitle,
					Remark=@rRemark,
					ConductDate=@rConductDate
					
				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 [sAssessment].[pCCEResultDetailAdd]...';


GO
 
 
ALTER PROCEDURE [sAssessment].[pCCEResultDetailAdd]
	 
	     
            @rAcademicId bigint
		   ,@rClassSubjectId int
		   ,@rObtain decimal(6,2)		
		   ,@rExamOrder int
		   ,@rCCEExamId INT  -- CCEId
		   ,@rSubExamId INT  -- CCEId
		   ,@rOrgId int
		   ,@rIsPresent bit = null,
		   @rCCEGradePointMarks decimal(6,2)=0,
		   @rClassId int=0,
		   @rSubjectMaximum decimal(6,2)=0,
		   @rFA1DecimalFormat int=0,
		   @rFA2DecimalFormat int=0,
		   @rFA3DecimalFormat int=0,
		   @rFA4DecimalFormat int=0,
		   @rSA1DecimalFormat int=0,
		   @rSA2DecimalFormat int=0,
		   @rTerm1DecimalFormat int=0,
		   @rTerm2DecimalFormat int=0,
		   @rAnnualDecimalFormat int=0 ,
		    @rFA1GradePointMax decimal(6,2)=0,
		   @rFA2GradePointMax decimal(6,2)=0,
		   @rFA3GradePointMax decimal(6,2)=0,
		   @rFA4GradePointMax decimal(6,2)=0,
		   @rSA1GradePointMax decimal(6,2)=0,
		   @rSA2GradePointMax decimal(6,2)=0,
		  
		   @rIsIncludeInTotal bit=0,
		   @rIncludeInTotalTerm1 bit=0,
		   @rIncludeInTotalTerm2 bit=0,
		   @rIncludeInTotalAnnual bit=0,
		   @rIsGradeUpdate bit=0
		 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	--BEGIN TRY
	
	-- BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 
	 DECLARE @lMaxiMark decimal(6,2)
	 --SELECT  @lMaxiMark = Maximum FROM sAssessment.tExamDetail Where ExamId = @rSubExamId AND ClassSubjectId = @rClassSubjectId
	 SET @lMaxiMark = @rSubjectMaximum
	

 
--IF ISNULL(@lCCEResultDetailId,0) = 0
	IF NOT EXISTS(select 1 from  sAssessment.tCCEResultDetail Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId)
	 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],
			   MaxGradePointFA1,
			   MaxGradePointFA2,
			   MaxGradePointSA1,
			   MaxGradePointFA3,
			   MaxGradePointFA4,
			   MaxGradePointSA2,
			    IncludeInTotalTerm1,
			    IncludeInTotalTerm2,
			    IncludeInTotalAnnual,
			    IsUpgradedGrade
			   
			   )
		 VALUES
			   (
			    @rAcademicId
			   ,@rClassSubjectId
			   ,0.00
			   ,0.00
			   ,0.00
			   ,0.00
			   ,0.00
			   ,0.00
			   ,0
			   ,sCommon.fGetDate(),
			   0.00,
			   0.00,
			   0.00,
			   0.00,
			   0.00,
			   0.00,
			   0,
			   0,
			   0,
			   @rIsGradeUpdate
			   ) 
			  
END		 
     		IF(@rExamOrder=1) 
     		BEGIN
     			if (@rIsIncludeInTotal = 1 )  
     			begin   		
     				set @rFA1GradePointMax = @rFA1GradePointMax
     			END
     			else
     			BEGIN
     			set @rFA1GradePointMax = 0     		 
     		    END 
     	 
     		UPDATE [sAssessment].[tCCEResultDetail] 
            SET [FA1]=ISNULL(@rObtain,0),FA1Max =@lMaxiMark ,IsPresentFA1=@rIsPresent,
     		GRADEPOINTFA1 = round((@rCCEGradePointMarks *ISNULL(@rObtain,0))/@lMaxiMark,@rFA1DecimalFormat), 
     		MaxGradePointFA1 = @rFA1GradePointMax
     		Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
     	 
     		END		
     		
		    IF(@rExamOrder=2) 
			BEGIN
			if (@rIsIncludeInTotal = 1 )     	
			BEGIN	
     			set @rFA2GradePointMax = @rFA2GradePointMax
     		END
     		else
			BEGIN
     			set @rFA2GradePointMax = 0     	
     		END	
			UPDATE [sAssessment].[tCCEResultDetail] 
			SET [FA2]=ISNULL(@rObtain,0),FA2Max =@lMaxiMark ,IsPresentFA2=@rIsPresent,
			GradePointFA2 =round((@rCCEGradePointMarks * ISNULL(@rObtain,0))/@lMaxiMark,@rFA2DecimalFOrmat),
			MaxGradePointFA2 =@rFA2GradePointMax
			Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
			END
			
			 IF(@rExamOrder=3)
			BEGIN
			if (@rIsIncludeInTotal = 1 )   
		 		
     			set @rSA1GradePointMax = @rSA1GradePointMax
     	 
     		else
     		 
     			set @rSA1GradePointMax = 0     
     			
     	    if (@rIncludeInTotalTerm1 = 1 )   
		 		
     			set @rIncludeInTotalTerm1 = @rIncludeInTotalTerm1
     	 
     		else
     		 
     			set @rIncludeInTotalTerm1 = 0      
     				
			 UPDATE [sAssessment].[tCCEResultDetail] 
			 SET [SA1]=ISNULL(@rObtain,0),SA1Max =@lMaxiMark ,IsPresentSA1=@rIsPresent,
			 GradePointSA1 =round((@rCCEGradePointMarks *ISNULL(@rObtain,0) )/@lMaxiMark,@rSA1DecimalFormat),
			  MaxGradePointSA1 = @rSA1GradePointMax,IncludeInTotalTerm1=@rIncludeInTotalTerm1
			 Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
			 
			 UPDATE [sAssessment].[tCCEResultDetail] 
			 SET [Term1]= ISNULL(FA1,0)+ISNULL(FA2,0)+ISNULL(SA1,0),Term1TotalGradePoint =  ROUND(GradePointFA1+ ISNULL(GradePointFA2,0)+ GradePointSA1,
			  @rTerm1DecimalFormat) 
			  --Term1GradePoint = ROUND(( ISNULL(GradePointFA1,0)+ ISNULL(GradePointFA2,0)+ ISNULL(GradePointSA1,0)) * 10 / 50 ,@rTerm1DecimalFormat) 
			 Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
			 END
			 
			IF(@rExamOrder=4) 
			BEGIn
			if (@rIsIncludeInTotal = 1 )  
			BEGIN   		
     			set @rFA3GradePointMax = @rFA3GradePointMax
     		ENd
     		else
     		BEGIN
     			set @rFA3GradePointMax = 0   
     		ENd
     			  
			UPDATE [sAssessment].[tCCEResultDetail] 
			SET [FA3]=ISNULL(@rObtain,0),FA3Max =@lMaxiMark ,IsPresentFA3=@rIsPresent,
			GradePointFA3 = round((@rCCEGradePointMarks * ISNULL(@rObtain,0))/@lMaxiMark,@rFA3DecimalFormat)  ,
			MaxGradePointFA3 = @rFA3GradePointMax
			Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
			END
			
			IF(@rExamOrder=5) 
			BEGIN
			if (@rIsIncludeInTotal = 1 )     	
			BEGIN	
     			set @rFA4GradePointMax = @rFA4GradePointMax
     		END
     		else
     		BEGIN
     			set @rFA4GradePointMax = 0   
     		END
			UPDATE [sAssessment].[tCCEResultDetail] 
			SET [FA4]=ISNULL(@rObtain,0),FA4Max =@lMaxiMark ,IsPresentFA4=@rIsPresent,
			GradePointFA4 =round((@rCCEGradePointMarks * ISNULL(@rObtain,0))/@lMaxiMark,@rFA4DecimalFormat) ,
			MaxGradePointFA4 = @rFA4GradePointMax
			Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
			END
			
			  IF(@rExamOrder=6) 
			BEGIN
			if (@rIsIncludeInTotal = 1 )     	
			BEGIN	
     			set @rSA2GradePointMax = @rSA2GradePointMax
			END
     		else
     		BEGIN
     			set @rSA2GradePointMax = 0  
     		END
     		if (@rIncludeInTotalTerm2 = 1 )     	
			BEGIN	
     			set @rIncludeInTotalTerm2 = @rIncludeInTotalTerm2
			END
     		else
     		BEGIN
     			set @rIncludeInTotalTerm2 = 0  
     		END
     		if (@rIncludeInTotalAnnual = 1 )     	
			BEGIN	
     			set @rIncludeInTotalAnnual = @rIncludeInTotalAnnual
			END
     		else
     		BEGIN
     			set @rIncludeInTotalAnnual = 0  
     		END
     		
			UPDATE [sAssessment].[tCCEResultDetail] 
			SET [SA2]=ISNULL(@rObtain,0),SA2Max =@lMaxiMark ,IsPresentSA2=@rIsPresent,
			GradePointSA2 =round((@rCCEGradePointMarks *ISNULL(@rObtain,0) )/@lMaxiMark,@rSA2DecimalFormat),
			  MaxGradePointSA2 = @rSA2GradePointMax,IncludeInTotalTerm2=@rIncludeInTotalTerm2,IncludeInTotalAnnual=@rIncludeInTotalAnnual
			Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
		 
			UPDATE [sAssessment].[tCCEResultDetail] 
			SET [FA]= ISNULL(FA1,0)+ISNULL(FA2,0)+ISNULL(FA3,0)+ISNULL(FA4,0),
			FAGradePoint=ROUND(GradePointFA1+GradePointFA2+GradePointFA3 +GradePointFA4,0) 
			Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
			
			UPDATE [sAssessment].[tCCEResultDetail] 
			SET [SA]=ISNULL(SA1,0)+ISNULL(SA2,0),SAGradePoint = ROUND( GradePointSA1+GradePointSA2  ,0) 
			Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
			
				
			UPDATE [sAssessment].[tCCEResultDetail] 
			SET [Term2]=ISNULL(FA3,0)+ISNULL(FA4,0)+ISNULL(SA2,0), 
			Term2TotalGradePoint =  ROUND(GradePointFA3+GradePointFA4+ GradePointSA2, @rTerm2DecimalFormat ) 
			--Term2GradePoint = ROUND(( ISNULL(GradePointFA3,0)+ISNULL(GradePointFA4,0)+ISNULL(GradePointSA2,0)) * 10 / 50 ,@rTerm2DecimalFormat) 
			Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
			
			UPDATE [sAssessment].[tCCEResultDetail] 
			SET [TOTAL]=ISNULL(FA1,0)+ISNULL(FA2,0)+ISNULL(FA3,0)+ISNULL(FA4,0)+ISNULL(SA1,0)+ISNULL(SA2,0) 
			Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
		     END
        
--	END	 
--ELSE
--	 BEGIN
 
	     	 
	     
--	        IF(@rExamOrder=1) 
--	        UPDATE [sAssessment].[tCCEResultDetail] SET [FA1]=ISNULL(@rObtain,0),FA1Max =@lMaxiMark ,IsPresentFA1=@rIsPresent,	GRADEPOINTFA1 = round((@rCCEGradePointMarks *ISNULL(@rObtain,0))/@lMaxiMark,Convert(INT,@rFA1DecimalFormat))Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
--			ELSE IF(@rExamOrder=2) UPDATE [sAssessment].[tCCEResultDetail] SET [FA2]=ISNULL(@rObtain,0),FA2Max =@lMaxiMark ,IsPresentFA2=@rIsPresent,GradePointFA2 =round((@rCCEGradePointMarks * ISNULL(@rObtain,0))/@lMaxiMark,Convert(INT,@rFA2DecimalFOrmat)) Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
--			ELSE IF(@rExamOrder=3)
--			BEGIN
--			 UPDATE [sAssessment].[tCCEResultDetail] SET [SA1]=ISNULL(@rObtain,0),SA1Max =@lMaxiMark ,IsPresentSA1=@rIsPresent,GradePointSA1 =round((@rCCEGradePointMarks *ISNULL(@rObtain,0) )/@lMaxiMark,Convert(INT,@rSA1DecimalFormat)) Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
--			 UPDATE [sAssessment].[tCCEResultDetail] SET [Term1]= ISNULL(FA1,0)+ISNULL(FA2,0)+ISNULL(SA1,0),Term1TotalGradePoint = ROUND(GradePointFA1+GradePointFA2+GradePointSA1 ,Convert(INT,@rTerm1DecimalFormat)),Term1GradePoint = ROUND(( ISNULL(GradePointFA1,0)+ ISNULL(GradePointFA2,0)+ ISNULL(GradePointSA1,0)) * 10 / 50 ,Convert(INT,@rTerm1DecimalFormat)) Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
--			 END
--			ELSE IF(@rExamOrder=4) UPDATE [sAssessment].[tCCEResultDetail] SET [FA3]=ISNULL(@rObtain,0),FA3Max =@lMaxiMark ,IsPresentFA3=@rIsPresent,GradePointFA3 =   round((@rCCEGradePointMarks * ISNULL(@rObtain,0))/@lMaxiMark,Convert(INT,@rFA3DecimalFormat))  Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
--			ELSE IF(@rExamOrder=5) UPDATE [sAssessment].[tCCEResultDetail] SET [FA4]=ISNULL(@rObtain,0),FA4Max =@lMaxiMark ,IsPresentFA4=@rIsPresent,GradePointFA4 =round((@rCCEGradePointMarks * ISNULL(@rObtain,0))/@lMaxiMark,Convert(INT,@rFA4DecimalFormat)) Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
--			ELSE IF(@rExamOrder=6) UPDATE [sAssessment].[tCCEResultDetail] SET [SA2]=ISNULL(@rObtain,0),SA2Max =@lMaxiMark ,IsPresentSA2=@rIsPresent,GradePointSA2 =round((@rCCEGradePointMarks *ISNULL(@rObtain,0) )/@lMaxiMark,Convert(INT,@rSA2DecimalFormat))   Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
--			BEGIN
--			UPDATE [sAssessment].[tCCEResultDetail] SET [FA]= ISNULL(FA1,0)+ISNULL(FA2,0)+ISNULL(FA3,0)+ISNULL(FA4,0),FAGradePoint=ROUND(GradePointFA1+GradePointFA2+GradePointFA3 +GradePointFA4,0) Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
--			UPDATE [sAssessment].[tCCEResultDetail] SET [SA]=ISNULL(SA1,0)+ISNULL(SA2,0),SAGradePoint = ROUND( GradePointSA1+GradePointSA2  ,0) Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
			
--			UPDATE [sAssessment].[tCCEResultDetail] SET [Term2]=ISNULL(FA3,0)+ISNULL(FA4,0)+ISNULL(SA2,0), Term2TotalGradePoint = ROUND(GradePointFA3+GradePointFA4+GradePointSA2 ,Convert(INT,@rTerm2DecimalFormat)),Term2GradePoint = ROUND(( ISNULL(GradePointFA3,0)+ISNULL(GradePointFA4,0)+ISNULL(GradePointSA2,0)) * 10 / 50,Convert(INT,@rTerm2DecimalFormat)) Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId

--			UPDATE [sAssessment].[tCCEResultDetail] SET [TOTAL]=ISNULL(FA1,0)+ISNULL(FA2,0)+ISNULL(FA3,0)+ISNULL(FA4,0)+ISNULL(SA1,0)+ISNULL(SA2,0) Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
--			END 
		 
		
	
--	 END  
		
 
	
		
END
GO
PRINT N'Altering [sAssessment].[pCCEResultDetailSubjectGradeUpdate]...';


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

	
		DECLARE @MinimumScore decimal(5,2)
		DECLARE @GradeTitle nvarchar(10)
		DECLARE @GradePoint decimal(6,2)
		DECLARE @lCount int
		DECLARE @lDataSetID INT
		DECLARE @lMaxiMark Decimal(5,2)
		--SELECT @lDataSetID=GradeSetId FROM sAssessment.tExamMaster WHERE Id = @rCCEExamId 
		
		
		 --  Update  D  Set D.FATerm1 = NULL FROM
			--sAssessment.tCCEResultDetail D INNER JOIN sStudent.tAcademic A ON D.AcademicId = A.Id
			----INNER JOIN #tempAcademic TA ON D.AcademicId = TA.AcademicId AND D.ClassSubjectId = TA.ClassSubjectid
			--WHERE A.BatchId = @rBatchId AND A.DivisionId = @rDivisionId AND A.ClassId = @rClassId
			
		 --  Update  D  Set D.Term1Grade = NULL FROM
			--sAssessment.tCCEResultDetail D INNER JOIN sStudent.tAcademic A ON D.AcademicId = A.Id
			----INNER JOIN #tempAcademic TA ON D.AcademicId = TA.AcademicId AND D.ClassSubjectId = TA.ClassSubjectid
			--WHERE A.BatchId = @rBatchId AND A.DivisionId = @rDivisionId AND A.ClassId = @rClassId	
			
			--Update  D  Set D.FATerm2 = NULL FROM
			--sAssessment.tCCEResultDetail D INNER JOIN sStudent.tAcademic A ON D.AcademicId = A.Id
			----INNER JOIN #tempAcademic TA ON D.AcademicId = TA.AcademicId AND D.ClassSubjectId = TA.ClassSubjectid
			--WHERE A.BatchId = @rBatchId AND A.DivisionId = @rDivisionId AND A.ClassId = @rClassId	

			
			--Update  D  Set D.SAGRADE = NULL FROM
			--sAssessment.tCCEResultDetail D INNER JOIN sStudent.tAcademic A ON D.AcademicId = A.Id
			----INNER JOIN #tempAcademic TA ON D.AcademicId = TA.AcademicId AND D.ClassSubjectId = TA.ClassSubjectid
			--WHERE A.BatchId = @rBatchId AND A.DivisionId = @rDivisionId AND A.ClassId = @rClassId			 

			--Update  D  Set D.FAGRADE = NULL FROM
			--sAssessment.tCCEResultDetail D INNER JOIN sStudent.tAcademic A ON D.AcademicId = A.Id
			----INNER JOIN #tempAcademic TA ON D.AcademicId = TA.AcademicId AND D.ClassSubjectId = TA.ClassSubjectid
			--WHERE A.BatchId = @rBatchId AND A.DivisionId = @rDivisionId AND A.ClassId = @rClassId			 

	        
	  --      Update  D  Set D.Term2Grade = NULL FROM
			--sAssessment.tCCEResultDetail D INNER JOIN sStudent.tAcademic A ON D.AcademicId = A.Id
			----INNER JOIN #tempAcademic TA ON D.AcademicId = TA.AcademicId AND D.ClassSubjectId = TA.ClassSubjectid
			--WHERE A.BatchId = @rBatchId AND A.DivisionId = @rDivisionId AND A.ClassId = @rClassId	

			
			--Update  D  Set D.Grade = NULL FROM  
			--sAssessment.tCCEResultDetail D INNER JOIN sStudent.tAcademic A ON D.AcademicId = A.Id
			----INNER JOIN #tempAcademic TA ON D.AcademicId = TA.AcademicId AND D.ClassSubjectId = TA.ClassSubjectid
			--WHERE A.BatchId = @rBatchId AND A.DivisionId = @rDivisionId AND A.ClassId = @rClassId	
	
			
		
	
		 SELECT @lDataSetID=GradeSetId FROM sAssessment.tCCEExamSetting WHERE CCEExamId = @rCCEExamId AND ClassId = @rClassId AND BatchId = @rBatchId
		 
		 -- CREATE TABLE #tempAcademic
			--(
			--	AcademicId bigint,
			--	classSubjectId decimal(5,2) 				 
			--) 
		 
		CREATE TABLE #tempGradeSetDetail
			(
		Id INT IDENTITY (1, 1),
		MinimumScore decimal(5,2),
		GradeTitle nvarchar(10),
		GradePoint decimal(6,2) 					 
			) 
			INSERT INTO #tempGradeSetDetail
	SELECT MinimumScore,GradeCode,GradePoint		
	FROM sAssessment.tGradeSetDetail where GradesetId=@lDataSetID
	order by MinimumScore DESC

SELECT @lCount =  COUNT(Id) FROM #tempGradeSetDetail
 
  
while ( @lCount > 0 )
BEGIN
	SELECT
		@MinimumScore =MinimumScore,
		@GradeTitle=GradeTitle,
		@GradePoint=GradePoint
		FROM #tempGradeSetDetail WHERE Id = @lCount

		 IF @rExamOrder = 1 
		BEGIN				
			Update  D  Set D.GradeFA1 = @GradeTitle FROM
			sAssessment.tCCEResultDetail D INNER JOIN sStudent.tAcademic A ON D.AcademicId = A.Id
			WHERE A.BatchId = @rBatchId AND A.DivisionId = @rDivisionId AND A.ClassId = @rClassId			
			AND (((D.FA1 * 100)/FA1Max)  >= @MinimumScore ) 
			--AND FA1MAX > 0 
			 
			
		END
		IF @rExamOrder = 2 
		BEGIN							
		
		
			Update  D  Set D.GradeFA2 = @GradeTitle FROM
			sAssessment.tCCEResultDetail D INNER JOIN sStudent.tAcademic A ON D.AcademicId = A.Id
			WHERE A.BatchId = @rBatchId AND A.DivisionId = @rDivisionId AND A.ClassId = @rClassId			
			AND (((D.FA2 * 100)/FA2Max)  >= @MinimumScore)  
			--AND FA2MAX > 0
			
		END
		IF @rExamOrder = 3 
		BEGIN				
			
			
		Update  D  Set D.GradeSA1 = @GradeTitle FROM
			sAssessment.tCCEResultDetail D INNER JOIN sStudent.tAcademic A ON D.AcademicId = A.Id
			WHERE A.BatchId = @rBatchId AND A.DivisionId = @rDivisionId AND A.ClassId = @rClassId
			
			AND (D.SA1 * 100)/SA1Max  >= @MinimumScore 
			--AND SA1MAX > 0
			 
		END
		IF @rExamOrder = 4 
		BEGIN				
		
		
				
			Update  D  Set D.GradeFA3 = @GradeTitle FROM
			sAssessment.tCCEResultDetail D INNER JOIN sStudent.tAcademic A ON D.AcademicId = A.Id
			WHERE A.BatchId = @rBatchId AND A.DivisionId = @rDivisionId AND A.ClassId = @rClassId			
			AND (D.FA3 * 100)/FA3Max  >= @MinimumScore
			--AND FA3MAX > 0 
			
		END
		IF @rExamOrder = 5 
		BEGIN				
		
			
			Update  D  Set D.GradeFA4 = @GradeTitle FROM
			sAssessment.tCCEResultDetail D INNER JOIN sStudent.tAcademic A ON D.AcademicId = A.Id
			WHERE A.BatchId = @rBatchId AND A.DivisionId = @rDivisionId AND A.ClassId = @rClassId			
			AND (D.FA4 * 100)/FA4Max  >= @MinimumScore 
			--And FA4MAx > 0
		END
		IF @rExamOrder = 6 
		BEGIN		
		
			Update  D  Set D.GradeSA2 = @GradeTitle FROM
			sAssessment.tCCEResultDetail D INNER JOIN sStudent.tAcademic A ON D.AcademicId = A.Id
			WHERE A.BatchId = @rBatchId AND A.DivisionId = @rDivisionId AND A.ClassId = @rClassId			
			AND (D.SA2 * 100)/SA2Max  >= @MinimumScore 
			--AND SA2Max > 0
			 
		END
		
		
	if (@rCCEExamId = 7 AND @rExamOrder=3)
	begin
	
	   --Truncate Table #tempAcademic
	 
		--INSERT INTO #tempAcademic
		--SELECT AcademicId,ClassSubjectId	
		--FROM sAssessment.tCCEResultDetail where (ISNULL(FA1MAX,0)+ISNULL(FA2MAX,0) > 0 )
		 
	
	
			-- ALL FA Term1	
			
			
			
			
			
			Update  D  Set D.FATerm1 = @GradeTitle FROM
			sAssessment.tCCEResultDetail D INNER JOIN sStudent.tAcademic A ON D.AcademicId = A.Id
			--INNER JOIN #tempAcademic TA ON D.AcademicId = TA.AcademicId AND D.ClassSubjectId = TA.ClassSubjectid
			WHERE A.BatchId = @rBatchId AND A.DivisionId = @rDivisionId AND A.ClassId = @rClassId			 
			--AND  ((ISNULL(FA1MAX,0)+ISNULL(FA2MAX,0)) > 0 )	
			AND ISNULL( ((D.FA1+D.FA2) * 100)/NULLIF(ISNULL(FA1MAX,0)+ISNULL(FA2MAX,0),0),0)  >= @MinimumScore
			AND (NULLIF(ISNULL(FA1MAX,0)+ISNULL(FA2MAX,0),0) > 0)
			
	
	
		--   Truncate Table #tempAcademic
	 
		--INSERT INTO #tempAcademic
		--SELECT AcademicId,ClassSubjectId	
		--FROM sAssessment.tCCEResultDetail where ((ISNULL(FA1MAX,0)+ISNULL(FA2MAX,0)+ISNULL(SA1MAX,0) > 0 ))		
			
			-- Term1
			
			
			
			Update  D  Set D.Term1Grade = @GradeTitle FROM
			sAssessment.tCCEResultDetail D INNER JOIN sStudent.tAcademic A ON D.AcademicId = A.Id
			--INNER JOIN #tempAcademic TA ON D.AcademicId = TA.AcademicId AND D.ClassSubjectId = TA.ClassSubjectid
			WHERE A.BatchId = @rBatchId AND A.DivisionId = @rDivisionId AND A.ClassId = @rClassId			 
			--AND ((ISNULL(FA1MAX,0)+ISNULL(FA2MAX,0)+ISNULL(SA1MAX,0) > 0 ))
			 AND ISNULL(( Term1TotalGradePoint * 100)/NULLIF(ISNULL(MaxGradePointFA1,0)+ISNULL(MaxGradePointFA2,0)+ISNULL(MaxGradePointSA1,0),0),0)  >= @MinimumScore 
		 	--DECLARE @lGrade nvarchar(10),@lGradePoint decimal(6,2)
			--Set @lGrade = (Select GS.GradeCode,GS.GradePoint from 	sAssessment.tGradeSetDetail GS 
			--INNER JOIN #tempGradeSetDetail TG ON TG.Id = GS.gradesetId WHere GS.Gradesetid=@lDataSetID)
			
			 UPDATE sAssessment.tCCEResultDetail Set Term1GradePoint = @GradePoint 
			 Where  Term1Grade = @GradeTitle AND AcademicId IN (Select Id From sStudent.tAcademic 
			 Where ClassId=@rClassId And BatchId=@rBatchId AND DivisionId=@rDivisionId)	
	
		 
	END	
		
	if (@rCCEExamId = 8 AND @rExamOrder=6)
	BEGIN
	    
	    
	 --   		   Truncate Table #tempAcademic
	 
		--INSERT INTO #tempAcademic
		--SELECT AcademicId,ClassSubjectId	
		--FROM sAssessment.tCCEResultDetail where ((ISNULL(FA3MAX,0)+ISNULL(FA4MAX,0)) > 0 )		
	       
			-- Term2 FA	Grade
			
			
			
				Update  D  Set D.FATerm2 = @GradeTitle FROM
			sAssessment.tCCEResultDetail D INNER JOIN sStudent.tAcademic A ON D.AcademicId = A.Id
			--INNER JOIN #tempAcademic TA ON D.AcademicId = TA.AcademicId AND D.ClassSubjectId = TA.ClassSubjectid
			WHERE A.BatchId = @rBatchId AND A.DivisionId = @rDivisionId AND A.ClassId = @rClassId			 
			--AND ((ISNULL(FA3MAX,0)+ISNULL(FA4MAX,0)) > 0 )		
			AND ((D.FA3+D.FA4) * 100)/NULLIF(ISNULL(FA3MAX,0)+ISNULL(FA4MAX,0),0)  >= @MinimumScore
		     AND (NULLIF(ISNULL(FA3MAX,0)+ISNULL(FA4MAX,0),0) > 0)
		
		--		INSERT INTO #tempAcademic
		--SELECT AcademicId,ClassSubjectId	
		--FROM sAssessment.tCCEResultDetail where ( (ISNULL(SA1MAX,0)+ISNULL(SA2MAX,0))	> 0)
		
			-- All SA	
		
		

			
				Update  D  Set D.SAGRADE = @GradeTitle FROM
			sAssessment.tCCEResultDetail D INNER JOIN sStudent.tAcademic A ON D.AcademicId = A.Id
			--INNER JOIN #tempAcademic TA ON D.AcademicId = TA.AcademicId AND D.ClassSubjectId = TA.ClassSubjectid
			WHERE A.BatchId = @rBatchId AND A.DivisionId = @rDivisionId AND A.ClassId = @rClassId			 
			--AND ( (ISNULL(SA1MAX,0)+ISNULL(SA2MAX,0))	> 0)
			AND (( D.SA * 100)/NULLIF(ISNULL(SA1MAX,0)+ISNULL(SA2MAX,0),0)  >= @MinimumScore)
			
	
		--		INSERT INTO #tempAcademic
		--SELECT AcademicId,ClassSubjectId	
		--FROM sAssessment.tCCEResultDetail where ((ISNULL(FA1MAX,0)+ISNULL(FA2MAX,0)+ISNULL(FA3MAX,0)+ISNULL(FA4MAX,0)) > 0 )
		
			-- ALL FA Grade	
			


			
			Update  D  Set D.FAGRADE = @GradeTitle FROM
			sAssessment.tCCEResultDetail D INNER JOIN sStudent.tAcademic A ON D.AcademicId = A.Id
			--INNER JOIN #tempAcademic TA ON D.AcademicId = TA.AcademicId AND D.ClassSubjectId = TA.ClassSubjectid
			WHERE A.BatchId = @rBatchId AND A.DivisionId = @rDivisionId AND A.ClassId = @rClassId			 
			--AND ((ISNULL(FA1MAX,0)+ISNULL(FA2MAX,0)+ISNULL(FA3MAX,0)+ISNULL(FA4MAX,0)) > 0 )
			AND ((D.FA * 100)/NULLIF(ISNULL(FA1MAX,0)+ISNULL(FA2MAX,0)+ISNULL(FA3MAX,0)+ISNULL(FA4MAX,0),0)   >= @MinimumScore )


		--		INSERT INTO #tempAcademic
		--SELECT AcademicId,ClassSubjectId	
		--FROM sAssessment.tCCEResultDetail where (ISNULL(FA3MAX,0)+ISNULL(FA4MAX,0)+ISNULL(SA2MAX,0)) > 0		
			
	        -- Term 2 Grade
	   
	        
			Update  D  Set D.Term2Grade = @GradeTitle FROM
			sAssessment.tCCEResultDetail D INNER JOIN sStudent.tAcademic A ON D.AcademicId = A.Id
			--INNER JOIN #tempAcademic TA ON D.AcademicId = TA.AcademicId AND D.ClassSubjectId = TA.ClassSubjectid
			WHERE A.BatchId = @rBatchId AND A.DivisionId = @rDivisionId AND A.ClassId = @rClassId			 
			--AND (ISNULL(FA3MAX,0)+ISNULL(FA4MAX,0)+ISNULL(SA2MAX,0)) > 0
			AND (( Term2TotalGradePoint * 100)/NULLIF(ISNULL(MaxGradePointFA3,0)+ISNULL(MaxGradePointFA4,0)+ISNULL(MaxGradePointSA2,0),0)  >= @MinimumScore)
			
			--select   @GradeTitle,A.Id,D.Term2TotalGradePoint,( Term2TotalGradePoint * 100)/NULLIF(ISNULL(MaxGradePointFA3,0)+ISNULL(MaxGradePointFA4,0)+ISNULL(MaxGradePointSA2,0),0),@MinimumScore    FROM
			--sAssessment.tCCEResultDetail D INNER JOIN sStudent.tAcademic A ON D.AcademicId = A.Id
			-- WHERE A.BatchId = @rBatchId AND A.DivisionId = @rDivisionId AND A.ClassId = @rClassId			 
			-- AND (( Term2TotalGradePoint * 100)/NULLIF(ISNULL(MaxGradePointFA3,0)+ISNULL(MaxGradePointFA4,0)+ISNULL(MaxGradePointSA2,0),0)  >= @MinimumScore)
			
			
			 UPDATE sAssessment.tCCEResultDetail Set Term2GradePoint = @GradePoint 
			 Where  Term2Grade = @GradeTitle AND AcademicId IN (Select Id From sStudent.tAcademic 
			 Where ClassId=@rClassId And BatchId=@rBatchId AND DivisionId=@rDivisionId)	
	
		--			INSERT INTO #tempAcademic
		--SELECT AcademicId,ClassSubjectId	
		--FROM sAssessment.tCCEResultDetail where (ISNULL(FA1MAX,0)+ISNULL(FA2MAX,0)+ISNULL(SA1MAX,0)+ISNULL(FA3MAX,0)+ISNULL(FA4MAX,0)+ISNULL(SA2MAX,0)) > 0
			-- overall Grade
		
			
			
			Update  D  Set D.Grade = @GradeTitle FROM  
			sAssessment.tCCEResultDetail D INNER JOIN sStudent.tAcademic A ON D.AcademicId = A.Id
			--INNER JOIN #tempAcademic TA ON D.AcademicId = TA.AcademicId AND D.ClassSubjectId = TA.ClassSubjectid
			WHERE A.BatchId = @rBatchId AND A.DivisionId = @rDivisionId AND A.ClassId = @rClassId			 
			--AND (ISNULL(FA1MAX,0)+ISNULL(FA2MAX,0)+ISNULL(SA1MAX,0)+ISNULL(FA3MAX,0)+ISNULL(FA4MAX,0)+ISNULL(SA2MAX,0)) > 0
			--AND ( (D.Term1TotalGradePoint+D.Term2TotalGradePoint) * 100)/NULLIF(ISNULL(MaxGradePointFA1,0)+ISNULL(MaxGradePointFA2,0)+ISNULL(MaxGradePointSA1,0)+ISNULL(MaxGradePointFA3,0)+ISNULL(MaxGradePointFA4,0)+ISNULL(MaxGradePointSA2,0),0)  >= @MinimumScore
			AND Round((D.Term1TotalGradePoint+D.Term2TotalGradePoint),0)  >= @MinimumScore
   	      UPDATE sAssessment.tCCEResultDetail Set GradePoint = (@GradePoint) Where  Grade = @GradeTitle AND AcademicId IN (Select Id From sStudent.tAcademic Where ClassId=@rClassId And BatchId=@rBatchId AND DivisionId=@rDivisionId)	
	

	
	END		 
 
		 
		 
			SET @lCount = @lCount - 1
		
 END
 
 if (@rCCEExamId = 7 AND @rExamOrder=3)
	begin
	
		update CR set Term1CGPA =  (CRD.GradePoint) from  sAssessment.tCCEResult CR 
		Inner Join (select Avg(ISNULL(Term1GradePoint,0)) AS GradePoint,AcademicId 
		From sAssessment.tCCEResultDetail WHERE ISNULL(IncludeInTotalTerm1,0) > 0  Group By ACademicId ) CRD 
		ON CR.AcademicId = CRD.AcademicId 
		INNER JOIN sStudent.tAcademic A ON CR.AcademicId = A.Id
		AND A.ClassId=@rClassId And A.BatchId=@rBatchId AND A.DivisionId=@rDivisionId
		
	
	end
 	  
  if (@rCCEExamId = 8 AND @rExamOrder=6)
	BEGIN
	
		update CR set Term2CGPA =  (CRD.GradePoint) from  sAssessment.tCCEResult CR 
		Inner Join (select Avg(ISNULL(Term2GradePoint,0)) AS GradePoint,AcademicId From sAssessment.tCCEResultDetail WHERE ISNULL(IncludeInTotalTerm2,0) > 0 Group By ACademicId ) CRD 
		ON CR.AcademicId = CRD.AcademicId 
		INNER JOIN sStudent.tAcademic A ON CR.AcademicId = A.Id
		AND A.ClassId=@rClassId And A.BatchId=@rBatchId AND A.DivisionId=@rDivisionId
         
	
	
		update CR set cgpa =  (CRD.GradePoint) from  sAssessment.tCCEResult CR 
			Inner Join (select Avg(ISNULL(GradePoint,0)) AS GradePoint,AcademicId From sAssessment.tCCEResultDetail WHERE  ISNULL(IncludeInTotalAnnual,0)  > 0 Group By ACademicId ) CRD 
			ON CR.AcademicId = CRD.AcademicId
			INNER JOIN sStudent.tAcademic A ON CR.AcademicId = A.Id
			AND A.ClassId=@rClassId And A.BatchId=@rBatchId AND A.DivisionId=@rDivisionId
			
		 
    END
 
END
GO
PRINT N'Altering [sAssessment].[pCCEResultGenerate]...';


GO
 
ALTER PROCEDURE [sAssessment].[pCCEResultGenerate]
	
	@rClassId int,
	@rExamId int,
	@rBatchId int,
	@rOrgId int,
	@rExamOrder int,
	@rCCEExamId int,
	@rDivisionId int,
	@rExam int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	
	
	DECLARE @lCount_MarkEntryStudent int
	DECLARE @lAcademicId bigint,@lGradeUpdate bit,@lExam1 int,@lExam2 int,@lExam3 int
	Declare @lCCESettingMaxMark decimal(6,2),@lIncludeInTotalTerm1 bit,@lIncludeInTotalTerm2 bit,@lIncludeInTotalAnnual bit 
	Declare @lFA1GradePointMax decimal(6,2),@lFA2GradePointMax decimal(6,2),@lSA1GradePointMax decimal(6,2),@lFA3GradePointMax decimal(6,2),
			@lFA4GradePointMax decimal(6,2),@lSA2GradePointMax decimal(6,2),@lTerm1GradePointMax decimal(6,2),@lTerm2GradePointMax decimal(6,2),@lAnnualGradePointMAx decimal(6,2)
	
	
	SELECT @lCCESettingMaxMark=MaxMark  FROM sAssessment.tCCEExamSetting WHERE CCEExamId = @rExamOrder AND ClassId = @rClassId AND BatchId = @rBatchId
	SELECT @lGradeUpdate=IsUpgradGrade FROM sAssessment.tCCEExamSetting WHERE  ClassId = @rClassId AND BatchId = @rBatchId AND CCEExamId=@rCCEExamId
		 
	 Declare @lFA1DecimalFormat nvarchar(10),@lFA2DecimalFormat nvarchar(10),@lFA3DecimalFormat nvarchar(10),@lFA4DecimalFormat nvarchar(10),@lSA1DecimalFormat nvarchar(10),@lSA2DecimalFormat nvarchar(10)
	 Declare @lTerm1DecimalFormat nvarchar(10),@lTerm2DecimalFormat nvarchar(10),@lAnnualDecimalFormat nvarchar(10)
	
	
	 Select @lFA1DecimalFormat = DecimalFormat,@lFA1GradePointMax=MaxMark from sAssessment.tCCEExamSetting Where ClassId =@rClassId AND  CCEExamId = 1 AND BatchId = @rBatchId
	 Select @lFA2DecimalFormat = DecimalFormat,@lFA2GradePointMax=MaxMark from sAssessment.tCCEExamSetting Where ClassId =@rClassId AND  CCEExamId = 2 AND BatchId = @rBatchId
	 Select @lFA3DecimalFormat = DecimalFormat,@lFA3GradePointMax=MaxMark from sAssessment.tCCEExamSetting Where ClassId =@rClassId AND  CCEExamId = 4 AND BatchId = @rBatchId
	 Select @lFA4DecimalFormat = DecimalFormat,@lFA4GradePointMax=MaxMark from sAssessment.tCCEExamSetting Where ClassId =@rClassId AND  CCEExamId = 5 AND BatchId = @rBatchId
	 Select @lSA1DecimalFormat = DecimalFormat,@lSA1GradePointMax=MaxMark from sAssessment.tCCEExamSetting Where ClassId =@rClassId AND  CCEExamId = 3 AND BatchId = @rBatchId
	 Select @lSA2DecimalFormat = DecimalFormat,@lSA2GradePointMax=MaxMark from sAssessment.tCCEExamSetting Where ClassId =@rClassId AND  CCEExamId = 6 AND BatchId = @rBatchId
	 Select   @lTerm1DecimalFormat = DecimalFormat,@lTerm1GradePointMax=MaxMark from sAssessment.tCCEExamSetting Where ClassId =@rClassId AND   CCEExamId = 7 AND BatchId = @rBatchId
	 Select   @lTerm2DecimalFormat = DecimalFormat,@lTerm2GradePointMax=MaxMark from sAssessment.tCCEExamSetting Where ClassId =@rClassId AND  CCEExamId = 8 AND BatchId = @rBatchId
	 Select  @lAnnualDecimalFormat = DecimalFormat,@lAnnualGradePointMAx=MaxMark from sAssessment.tCCEExamSetting Where ClassId =@rClassId AND  CCEExamId = 9 AND BatchId = @rBatchId
	 
	 Select @lExam1=EM.Id from sAssessment.tCCEExamSetting ES	 
	 INNER JOIN sAssessment.tExamMaster EM oN EM.ExamSubGroupId = ES.ExamSubGroupId 
	 Where ES.ClassId =@rClassId AND ES.CCEExamId = 7 AND ES.BatchId = @rBatchId AND  EM.ClassId = @rClassId
	 
	  Select @lExam2=EM.Id  from sAssessment.tCCEExamSetting ES 
	  INNER JOIN sAssessment.tExamMaster EM ON EM.ExamSubGroupId = ES.ExamSubGroupId
	  Where ES.ClassId=@rClassId and ES.CCEExamId =8 and Es.BatchId=@rBatchId AND  EM.ClassId = @rClassId
	  
	  Select  @lExam3=EM.Id from sAssessment.tCCEExamSetting ES 
	  INNER JOIN sAssessment.tExamMaster EM ON EM.ExamSubGroupId= ES.ExamSubGroupId
	  wHERE ES.ClassId=@rClassId AND ES.CCEExamId=9 AND ES.BatchId=@rBatchId AND  EM.ClassId = @rClassId
	  
	  if @lFA1DecimalFormat ='0' BEGIN SET @lFA1DecimalFormat=0 END
	  if @lFA1DecimalFormat ='0.0' BEGIN SET @lFA1DecimalFormat=1 END
	  if @lFA1DecimalFormat ='0.00' BEGIN SET @lFA1DecimalFormat=2 END
	  if @lFA2DecimalFormat ='0' BEGIN SET @lFA2DecimalFormat=0 END
	  if @lFA2DecimalFormat ='0.0' BEGIN SET @lFA2DecimalFormat=1 END
	  if @lFA2DecimalFormat ='0.00' BEGIN SET @lFA2DecimalFormat=2 END
	  if @lFA3DecimalFormat ='0' BEGIN SET @lFA3DecimalFormat=0 END
	  if @lFA3DecimalFormat ='0.0' BEGIN SET @lFA3DecimalFormat=1 END
	  if @lFA3DecimalFormat ='0.00' BEGIN SET @lFA3DecimalFormat=2 END
	  if @lFA4DecimalFormat ='0' BEGIN SET @lFA4DecimalFormat=0 END
	  if @lFA4DecimalFormat ='0.0' BEGIN SET @lFA4DecimalFormat=1 END
	  if @lFA4DecimalFormat ='0.00' BEGIN SET @lFA4DecimalFormat=2 END
	   
	  if @lSA1DecimalFormat ='0' BEGIN SET @lSA1DecimalFormat=0 END
	  if @lSA1DecimalFormat ='0.0' BEGIN SET @lSA1DecimalFormat=1 END
	  if @lSA1DecimalFormat ='0.00' BEGIN SET @lSA1DecimalFormat=2 END
	  if @lSA2DecimalFormat ='0' BEGIN SET @lSA2DecimalFormat=0 END
	  if @lSA2DecimalFormat ='0.0' BEGIN SET @lSA2DecimalFormat=1 END
	  if @lSA2DecimalFormat ='0.00' BEGIN SET @lSA2DecimalFormat=2 END
	  if @lTerm1DecimalFormat ='0' BEGIN SET @lTerm1DecimalFormat=0 END
	  if @lTerm1DecimalFormat ='0.0' BEGIN SET @lTerm1DecimalFormat=1 END
	  if @lTerm1DecimalFormat ='0.00' BEGIN SET @lTerm1DecimalFormat=2 END
	  if @lTerm2DecimalFormat ='0' BEGIN SET @lTerm2DecimalFormat=0 END
	  if @lTerm2DecimalFormat ='0.0' BEGIN SET @lTerm2DecimalFormat=1 END
	  if @lTerm2DecimalFormat ='0.00' BEGIN SET @lTerm2DecimalFormat=2 END
	   if @lAnnualDecimalFormat ='0' BEGIN SET @lAnnualDecimalFormat=0 END
	  if @lAnnualDecimalFormat ='0.0' BEGIN SET @lAnnualDecimalFormat=1 END
	  if @lAnnualDecimalFormat ='0.00' BEGIN SET @lAnnualDecimalFormat=2 END


	
	CREATE TABLE #TempMarkEntryStudent(
	[AutoId] [int] identity,
	[AcademicId] [bigint] NOT NULL,
	[ExamId] [int] NULL,
	[OrgId] [int] NULL,
	[ClassId] [int] NULL,
	)
	 
	INSERT INTO #TempMarkEntryStudent 
	SELECT  
		SA.Id  AS AcademicId,
		EM.Id AS ExamId,
		SA.OrgId,
		EM.ClassId
    FROM  
		sStudent.tAcademic  SA 
		INNER JOIN sStudent.tStudentMaster SM ON SA.StudentId = SM.Id 
		INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = SA.ClassId 
		INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=SA.Id
		--LEFT JOIN sAssessment.tCCEResult CR ON CR.AcademicId = SA.AcademicId
	WHERE 
		(EM.ClassId = @rClassId OR @rClassId = 0 )    
		AND (EM.Id=@rExamId OR @rExamId = 0)
		AND (EM.BatchId = @rBatchId or @rBatchId=0)
		AND SM.StatusId=1
		AND SA.BatchId=@rBatchId
		AND SA.DivisionId=@rDivisionId
    
    SET @lCount_MarkEntryStudent = 0
    SELECT @lCount_MarkEntryStudent = COUNT(AutoId) FROM #TempMarkEntryStudent
     
     --SELECT * FROM #TempMarkEntryStudent
    
  --  EXEC sAssessment.pCCEResultDetailSubjectGradeUpdate @rExamOrder,@rCCEExamId,@rExamId,@rBatchId,@rClassId,@rDivisionId,
		--@rFA1GradePointMax = @lFA1GradePointMax,@rFA2GradePointMax=@lFA2GradePointMax,@rFA3GradePointMax=@lFA3GradePointMax,@rFA4GradePointMax=@lFA4GradePointMax,
		--@rSA1GradePointMax=@lSA1GradePointMax,@rSA2GradePointMax=@lSA2GradePointMax,@rTerm1GradePointMax=@lTerm1GradePointMax,@rTerm2GradePointMax=@lTerm2GradePointMax,
		--@rAnnualGradePointMax=@lAnnualGradePointMAx
    
	CREATE TABLE #TempCCEMarkEntry (
	[AutoId] [int] identity,
	[AcademicId] [bigint] NOT NULL ,
	[ResultDetailId] [bigint] NULL,
	[ClassSubjectId] [int] NULL,
	[Obtain] [decimal](5,2) NULL,
	[IsPresent] [bit] NULL,
	[ExamId] [int] NULL,
	SubjectMaximum [decimal](5,2) NULL,
	IsIncludeInTotal bit NULL 
	)
	Declare @lConvertedMark decimal(6,2)
	 
	WHILE (@lCount_MarkEntryStudent > 0)
	BEGIN
		
		SET @lAcademicId = 0
		SELECT @lAcademicId = AcademicId FROM #TempMarkEntryStudent WHERE AutoId = @lCount_MarkEntryStudent
		 
	    EXEC sAssessment.pCCEResultAdd @rAcademicId=@lAcademicId,@rUpdatedUserId=0,@rOrgId=@rOrgId
			
		INSERT INTO #TempCCEMarkEntry 
		SELECT 
			SA.Id as AcademicId,
			ISNULL(RD.ID,0) AS ResultDetailId,
			ED.ClassSubjectId AS ClassSubjectId,
			ISNULL(RD.Obtain,0) AS Obtain,
			RD.IsPresent,
			@rExamId,
			ED.Maximum AS SubjectMaximum,
			ED.IsIncludeInTotal
		FROM sAssessment.tResultDetail RD 
			INNER JOIN sAssessment.tResult R ON R.Id= RD.ResultId
			INNER JOIN 	sStudent.tAcademic SA ON SA.Id = R.AcademicId
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id = SA.StudentId
			INNER JOIN sAssessment.tExamMaster EM ON  EM.Id=R.ExamId 	
			INNER JOIN sAssessment.tExamDetail ED ON  RD.ExamDetailId = ED.Id		
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			LEFT JOIN sAssessment.tOptionalSubject o on o.AcademicId=SA.Id and o.ClassSubjectId=CS. Id  
			    AND SA.Id =@lAcademicId
		WHERE
			(SA.ClassId = @rClassId)    
			AND SM.StatusId=1
			AND SA.BatchId=@rBatchId
			AND R.ExamId = @rExamId
			AND R.AcademicId = @lAcademicId
			AND SA.DivisionId =@rDivisionId
			 AND ((CS.IsOptional = 1 AND  isnull(o.AcademicId,0)<>0) OR (CS.IsOptional = 0))   
			 
			DECLARE @lCount int
			SET @lCount = 0
			SELECT @lCount = COUNT(AcademicId) FROM #TempCCEMarkEntry
			 
				WHILE (@lCount > 0)
				BEGIN
					DECLARE @lClassSubjectId int
				    DECLARE @lObtain decimal(5,2)
				    DECLARE @lIsPresent bit
				    DECLARE @rIsPresent bit
				    DECLARE @lSubjectMaximum decimal(5,2)
				    Declare @lIsIncludeInTotal bit  
					SELECT @lClassSubjectId = ClassSubjectId,@lIsIncludeInTotal=IsIncludeInTotal, @lObtain = Obtain,@lIsPresent = IsPresent,@lSubjectMaximum = SubjectMaximum   FROM #TempCCEMarkEntry WHERE AcademicId = @lAcademicId AND ExamId = @rExamId AND AutoId = @lCount
					
					if @rExamOrder=3
				BEGIN
					Select @lIncludeInTotalTerm1=IsIncludeInTotal  from sAssessment.tExamDetail Where Examid = @lExam1 AND ClassSubjectId= @lClassSubjectId
					 --Select @lIncludeInTotalTerm1,@lClassSubjectId
				END
					if @rExamOrder=6
					BEGIN
					Select @lIncludeInTotalTerm2=IsIncludeInTotal  from sAssessment.tExamDetail Where Examid = @lExam2 AND ClassSubjectId= @lClassSubjectId
					Select @lIncludeInTotalAnnual=IsIncludeInTotal  from sAssessment.tExamDetail Where Examid = @lExam3 AND ClassSubjectId= @lClassSubjectId
					--select  @lIncludeInTotalAnnual,@lClassSubjectId,@lExam3
				END
				 
					EXEC sAssessment.pCCEResultDetailAdd @rAcademicId=@lAcademicId,@rClassSubjectId=@lClassSubjectId,@rObtain=@lObtain,@rExamOrder=@rExamOrder,@rCCEExamId=@rCCEExamId,@rSubExamId=@rExamId,@rOrgId=@rOrgId,@rIsPresent=@lIsPresent,@rCCEGradePointMarks=@lCCESettingMaxMark,@rClassId=@rClassId,@rSubjectMaximum = @lSubjectMaximum,@rFA1DecimalFormat=@lFA1DecimalFormat,
												@rFA2DecimalFormat=@lFA2DecimalFormat,@rFA3DecimalFormat=@lFA3DecimalFormat,@rFA4DecimalFormat=@lFA4DecimalFormat,
												@rSA1DecimalFormat=@lSA1DecimalFormat,@rSA2DecimalFormat=@lSA2DecimalFormat,@rTerm1DecimalFormat=@lTerm1DecimalFormat,@rTerm2DecimalFormat=@lTerm2DecimalFormat,@rAnnualDecimalFormat=@lAnnualDecimalFormat ,
												@rFA1GradePointMax = @lFA1GradePointMax,@rFA2GradePointMax=@lFA2GradePointMax,@rFA3GradePointMax=@lFA3GradePointMax,@rFA4GradePointMax=@lFA4GradePointMax,
												@rSA1GradePointMax=@lSA1GradePointMax,@rSA2GradePointMax=@lSA2GradePointMax 
												,@rIsIncludeInTotal = @lIsIncludeInTotal,@rIncludeInTotalTerm1=@lIncludeInTotalTerm1,@rIncludeInTotalTerm2=@lIncludeInTotalTerm2,
												@rIncludeInTotalAnnual=@lIncludeInTotalAnnual,@rIsGradeUpdate=@lGradeUpdate
					SET @lCount = @lCount -1
						
					
				END
				
				 TRUNCATE TABLE #TempCCEMarkEntry
				--DELETE FROM #TempCCEMarkEntry
				--DBCC CHECKIDENT (#TempCCEMarkEntry, RESEED, 1);
		SET @lCount_MarkEntryStudent = @lCount_MarkEntryStudent -1
	    
	END

	 
	EXEC sAssessment.pCCEResultDetailSubjectGradeUpdate @rExamOrder,@rCCEExamId,@rExamId,@rBatchId,@rClassId,@rDivisionId  
		 
	IF (@rExamOrder = 3)
	BEGIN
	Update   CCER  Set   WorkingDaysTerm1 = TotalDays,AttendanceTerm1 = PresentDays from	
	sAssessment.tCCEResult CCER INNER JOIN sAssessment.tStudentRemark SR ON SR.AcademicID = CCER.Academicid 
	WHere SR.ExamID =@rExam AND @rCCEExamId=7
	END
	
	IF (@rExamOrder = 6)
	BEGIN
	Update   CCER  Set   WorkingDaysTerm2= TotalDays,AttendanceTerm2 = PresentDays from 
	sAssessment.tCCEResult CCER INNER JOIN sAssessment.tStudentRemark SR ON SR.AcademicID = CCER.Academicid 
	WHere SR.ExamID =@rExam AND @rCCEExamId=8
	
	Exec sAssessment.pCCEResultOverallGradeUpdate @rExamOrder,@rCCEExamId,@rBatchId,@rClassId,@rDivisionId
	
	END
	 
	 IF @rExamOrder =6 AND @lGradeUpdate=1
	 BEGIN
		 
		 EXEC sAssessment.pCCESubjectGradeUpgrade  @rBatchId=@rBatchId,@rClassId=@rClassId,@rDivisionId=@rDivisionId,@rOrgId=@rOrgId 
	  
	END		
	--	END
		DROP TABLE #TempMarkEntryStudent
	DROP TABLE #TempCCEMarkEntry
	SELECT 1 AS Result
	
END
GO
PRINT N'Altering [sAssessment].[pCCERptFirstTermResultGet]...';


GO


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

	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 


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

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

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

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

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


GO
 
ALTER PROCEDURE [sAssessment].[pCCESubjectGradeUpgrade]
	   
	  @rBatchId INT
	 ,@rClassId INT,
	  @rDivisionId int,
	  @rOrgId int 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 	
 
	Create Table #tempMark 
	(
		Id int identity(1,1),
		Convertedmark decimal(6,2),
		AcademicId bigint
	)
	INsert Into #tempMark
	(
		Convertedmark,
		AcademicId
	)
	 SELECT   sum(Isnull(CC.Convertedmark,0)),SA.Id 
		FROM  sAssessment.tCCECSMaster CM	
		  INNER JOIN sAssessment.tCCECSGroupMaster CGM ON CGM.Id=CM.CCECAGroupId AND CM.OrgId=@rOrgId
		  INNER JOIN sAssessment.tCCECSClass CL ON CL.CCECSGroupId = CGM.Id				
		   INNER JOIN sStudent.tAcademic SA ON   SA.ClassId = CL.ClassId 
		  INNER JOIN   sAssessment.tCCECSExamScore CC  ON CC.CCECSID=CM.ID   AND CC.AcademicId = SA. Id  
		   
		  WHERE 
		  --((SA.AcademicId = @lAcademicId) OR (@lAcademicId=0))						  
		  SA.DivisionId=@rDivisionId and SA.Batchid = @rBatchId
		  Group by SA.Id 
		  
        
        
		Update CR SET  CR.ConvertedMark=temp.Convertedmark from
		sAssessment.tCCEResult CR
		INNER JOIN #tempMark temp on temp.AcademicId = CR.AcademicId
			
		 
		 
		CREATE Table #tempdetail
		(
			AcademicId bigint,
			Grade nvarchar(10),
			HigherGrade nvarchar(10),
			GradePoint decimal(6,2),
			HigherGradePoint decimal(6,2),
			ConvertedMark decimal(6,2),
			ClassSubjectId int
			 
		) ;
	 
		 
	  WITH cte  AS 
	 (
		 
		SELECT  D.AcademicId,D.ClassSubjectId,D.Grade,sAssessment.fGetHigherGrade(D.Grade) AS HigherGrade,D.GradePoint,sAssessment.fGetHigherGradepoint(D.GradePoint) AS HigherGradePoint,
				CR.ConvertedMark,
		row_number() OVER(PARTITION BY D.AcademicId ORDER BY D.Grade desc) AS [rn]
		FROM  sAssessment.tCCEResultDetail D 
	 
		inner join  sStudent.tAcademic A ON A.id=D.academiciD
		INNER JOIN sAssessment.tCCEResult CR on CR.Academicid= A.id
		WHERE D.Grade NOT IN ('A1','E1','E2') And A.batchid=@rBatchId ANd A.divisionid=@rDivisionId AND CR.Convertedmark>=53 AND CR.ConvertedMark<=65 AND ISNULL(D.IncludeInTotalAnnual,0)  > 0
	 )
	 INSERT INTo #tempdetail
		(
			AcademicId, 
			Grade,
			HigherGrade,
			GradePoint,
			HigherGradePoint ,
			ConvertedMark,
			ClassSubjectId 
		) 
	  
	select AcademicId,Grade,HigherGrade,GradePoint,HigherGradePoint,ConvertedMark,ClassSubjectId from cte WHERE [rn] <= 2  
	 
		Update D Set D.Grade=temp.HigherGrade,D.GradePoint=temp.HigherGradePoint,IsUpgradedgrade=1
		from sAssessment.tCCEResultDetail  D INNER JOIN  #tempdetail temp on temp.Academicid= D.Academicid 
		 And  temp.ClassSubjectId = D.ClassSubjectId
		
		update CR set cgpa =  (CRD.GradePoint) from  sAssessment.tCCEResult CR 
		Inner Join (select Avg(ISNULL(GradePoint,0)) AS GradePoint,AcademicId From sAssessment.tCCEResultDetail WHERE  ISNULL(IncludeInTotalAnnual,0)  > 0  Group By ACademicId ) CRD 
		ON CR.AcademicId = CRD.AcademicId
		INNER JOIN sStudent.tAcademic A ON CR.AcademicId = A.Id
		AND A.ClassId=@rClassId And A.BatchId=@rBatchId AND A.DivisionId=@rDivisionId;
	 
	WITH T  AS 
	 (
		SELECT  D.AcademicId,D.ClassSubjectId,D.Grade,sAssessment.fGetHigherGrade(D.Grade) AS HigherGrade,D.GradePoint,sAssessment.fGetHigherGradepoint(D.GradePoint) AS HigherGradePoint,
				CR.ConvertedMark,D.IncludeInTotalAnnual,
		row_number() OVER(PARTITION BY D.AcademicId ORDER BY D.Grade desc) AS [rn]
		FROM  sAssessment.tCCEResultDetail D 
	 
		inner join  sStudent.tAcademic A ON A.id=D.academiciD
		INNER JOIN sAssessment.tCCEResult CR on CR.Academicid= A.id
		WHERE D.Grade NOT IN ('A1','E1','E2') And A.batchid=@rBatchId ANd A.divisionid=@rDivisionId AND CR.Convertedmark>=40 AND CR.ConvertedMark<=52  AND ISNULL(D.IncludeInTotalAnnual,0)  > 0
	 )
	  INSERT INTo #tempdetail
		(
			AcademicId, 
			Grade,
			HigherGrade,
			GradePoint,
			HigherGradePoint,
			ConvertedMark,
			ClassSubjectId
		) 
	select AcademicId,Grade,HigherGrade,GradePoint,HigherGradePoint,ConvertedMark,ClassSubjectId from T WHERE [rn] <= 1	
		 
		Update D Set D.Grade=temp.HigherGrade,D.GradePoint=temp.HigherGradePoint,IsUpgradedgrade=1
		from sAssessment.tCCEResultDetail  D INNER JOIN  #tempdetail temp on temp.Academicid= D.Academicid AND temp.ClassSubjectId = D.ClassSubjectId
		
		update CR set cgpa =  (CRD.GradePoint) from  sAssessment.tCCEResult CR 
		Inner Join (select Avg(ISNULL(GradePoint,0)) AS GradePoint,AcademicId From sAssessment.tCCEResultDetail WHERE  ISNULL(IncludeInTotalAnnual,0)  > 0  Group By ACademicId ) CRD 
		ON CR.AcademicId = CRD.AcademicId
		INNER JOIN sStudent.tAcademic A ON CR.AcademicId = A.Id
		AND A.ClassId=@rClassId And A.BatchId=@rBatchId AND A.DivisionId=@rDivisionId
		 
END
GO
PRINT N'Altering [sAssessment].[pCSEXamIndicatorAdd]...';


GO


ALTER PROCEDURE [sAssessment].[pCSEXamIndicatorAdd]
	 	
	@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 @lCount INT

			  	
					 
			UPDATE AI SET AI.IndicatorIds = Replace(Term1Indicator,',','.') FROM sAssessment.tCCECSExamScore AI
			INNER JOIN OPENXML (@loDoc, '/Table/CSEXamIndicator', 1)
				WITH ( 				
							AcademicId Bigint,
							CCECSId int,
							ExamId int,
							Term1Indicator NVARCHAR(20)			
					  ) A 	ON AI.AcademicId = A.AcademicId AND AI.ExamId=A.ExamId
			AND A.CCECSId = AI.CCECSId 
			 --INNER JOIN sSetup.tOrganizationMaster OM ON  OM.Id = @rORGId	
		 
		INSERT INTO sAssessment.tCCECSExamScore
			(AcademicId,CCECSId,ExamId,IndicatorIds)
			
			SELECT	A.AcademicId,A.CCECSId,A.ExamId,Replace(Term1Indicator,',','.') 
         			
			FROM OPENXML (@loDoc, '/Table/CSEXamIndicator', 1)
			WITH ( 			
					AcademicId Bigint,
					CCECSId int,	
					ExamId int,
					Term1Indicator nvarchar(20) 
					 
				  ) A 	
			LEFT JOIN sAssessment.tCCECSExamScore AI ON AI.AcademicId = A.AcademicId AND AI.ExamId=A.ExamId  AND A.CCECSId = AI.CCECSId 
			       WHERE (AI.AcademicId IS NULL AND AI.ExamId IS NULL AND AI.CCECSId IS NULL)
			
			--sAssessment.tCCECSMaster AM ON AM.Id = A.CCECSId 			
			--INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = AM.OrgId AND OM.Id = @rORGId
			--AND A.AcademicId NOT IN (Select AcademicId From sAssessment.tCCECSExamScore Where AcademicId =A.AcademicId AND A.ExamId = ExamId AND CCECSId=AM.Id)
	     
	
    -- Updated by Kp
	UPDATE A SET A.DescriptiveIndicator = 
 					stuff((select ',' + B.Title from sAssessment.tCCECSIndicatorMaster B
				WHERE A.CCECSid=B.CCECSId 
						and ','+ (replace(IndicatorIds,'.',',') )+',' like '%,'+CAST(Number as varchar(10))+',%'				
				for xml path('')),1,1,'') 
         From sAssessment.tCCECSExamScore A    
         INNER JOIN      			
			OPENXML (@loDoc, '/Table/CSEXamIndicator', 1)
			WITH ( 		
					AcademicId Bigint,	
					CCECSId int,	
					ExamId int,
					Term1Indicator nvarchar(20) 
					 
				  )B1
				  ON A.ExamId=B1.ExamId AND A.AcademicId = B1.AcademicId AND B1.CCECSId = A.CCECSId 
	
	 SELECT 1 AS Result
	END		
	END TRY
	
	BEGIN CATCH 
	
		
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sAssessment].[pExamListGet]...';


GO
ALTER PROC [sAssessment].[pExamListGet]
	
	@rAcademicId bigint=0,
	@rBatchId int=0

AS
BEGIN
	DECLARE @lTotalMarks decimal=0,@lTotalObtain decimal=0,@lResultStatus nvarchar(50)='' ,@lResultGrade nvarchar(10)='',@lRankNumber int=0,@lPercentage decimal=0,@lPercentile decimal=0
	DECLARE @lempgrid VARCHAR(max)=''
	SELECT  @lempgrid = @lempgrid + '<tr>
	<td align="left" scope="col">' + ISNULL(Cm.DisplayTitle,'')+' - '+isnull(Dm.DisplayTitle,'')+' : '+isnull(E.Name,'') + '</td>
	<td align="left" scope="col">' + isnull(BM.Title,'') + '</td>
	<td align="left" scope="col">' +  convert(varchar,isnull(R.TotalMarks,0)) + '</td>
	<td align="left" scope="col">' +  convert(varchar,isnull(R.TotalObtain,'')) + '</td>
	<td align="left" scope="col">' + isnull(R.ResultStatus,'') + '</td>
	<td align="left" scope="col">' + isnull(R.ResultGrade,'') + '</td>
	<td align="left" scope="col">' +  convert(varchar,isnull(R.RankNumber,0)) + '</td>
	<td align="left" scope="col">' +  convert(varchar,isnull(R.Percentage,0)) + '</td>
	<td align="left" scope="col">' +  convert(varchar,isnull(R.Percentile,0)) + '</td>
	  <td scope="col" align="center"><a  class="fa fa-plus-square" href="javascript:;" 
    onclick="SelectResult(this,' + convert(varchar,isnull(E.Id,0)) + ');"></a></td></tr>'	
 From
 sStudent.tAcademic AD 
 INNER JOIN  sAssessment.vExamMaster E ON E.BatchId = AD.BatchId AND E.ClassId = AD.ClassId
 INNER JOIN sSetup.tBatchMaster BM ON E.BatchId = BM.Id 
 INNER JOIN sSetup.tClassMaster CM ON CM.Id=AD.ClassId
 INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=AD.DivisionId
 INNER JOIN sAssessment.tResult R ON AD.Id = R.AcademicId AND R.ExamId = E.Id
 
 WHERE ((AD.Id=@rAcademicId) OR (@rAcademicId=0))
	--AND ((AD.BatchId =  @rBatchId) OR (@rBatchId=0))
	 AND IsProcessResult=1
	 ORDER BY DM.OrderIndex DESC
	select isnull(@lempgrid,'') as EmpGrid
END
GO
PRINT N'Altering [sAssessment].[pExamMasterGet]...';


GO
ALTER PROCEDURE [sAssessment].[pExamMasterGet]
	 @rTitle nvarchar(100),
	 @rExamGroupId int,
	 @rClassId int,
	 @rOrgId int ,
	 @rBatchId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 		
					 
	--SET @rTitle = sCommon.fSearchStringGet(@rTitle)
	SELECT 
	EM.Id,
	EGM.Title as ExamGroup,
	ESGM.Title as ExamName,
	CM.DisplayTitle as ClassName,
	ISNULL(IsProcessResult,0) AS IsProcessResult,
	IsNull(IsMarksInDecimal,0) AS IsMarksInDecimal,
	ISNULL(ISNegativeMarks,0) AS ISNegativeMarks ,
	ISNULL(IsIncludeCoScholastic,0) AS IsIncludeCoScholastic 
  FROM 
			[sAssessment].[tExamMaster] EM			
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=EM.ClassId
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.ID = EM.ExamSubGroupId
			INNER JOIN sAssessment.tExamGroupMaster EGM ON EGM.Id=ESGM.ExamGroupId
WHERE		(CM.OrgId = @rOrgId  OR @rOrgId=0) AND (EM.BatchId=@rBatchId)
			AND (EGM.Id=@rExamGroupId OR @rExamGroupId=0)
			AND (CM.Id=@rClassId or @rClassId=0)  
		--	AND ((EM.Name Like  @rTitle )OR(ISNULL(@rTitle,'') = ''))
			ORDER BY EGM.Title ,ESGM.Title

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


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

	declare @quer varchar(max)=''
	DEClare @lOrgId int,@lCode nvarchar(20),@lClassId int,@lDivisionId int,@lBatchId int
	DEClare @lClassGroupId int
	
  		SET @lOrgId=ISNULL(@rOrgId,0)
  		SET @lBatchId=ISNULL(@rBatchId,0)
  		SET @lClassId=ISNULL(@rClassId,0)
  		SET @lDivisionId=ISNULL(@rDivisionId,0)
  	    SET @lCode=ISNULL(@rCode,'')
     DELETE FROM sAssessment.tAllBatchResult 
 select @quer = 'INSERT INTO sAssessment.tAllBatchResult 
  	(
	SubjectId,StudentId
	)
	 SELECT 
			 DISTINCT SM.Id AS Subject,STM.Id AS StudentID FROM
              sStudent.tStudentMaster STM
			  INNER JOIN sStudent.tAcademic AD ON STM.Id = AD.StudentId 
			  INNER JOIN sSetup.tClassMaster CM ON CM.Id=AD.ClassId
			  INNER JOIn sSetup.tClassSubject CS ON CS.ClassId=CM.Id
			  INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId 
			  AND SM.OrgId=' + convert(varchar,@lOrgId) + '
			  INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=SM.Id 
  	          WHERE STM.OrgId=' + convert(varchar,@lOrgId) + '
  			  AND AB.OrgId =' + convert(varchar,@lOrgId) + '
  			  AND ((STM.Code = ''' + @lCode + ''') OR (''' + @lCode + ''' = ''''))
  			  AND ((AD.ClassId = ''' + convert(varchar,@lClassId) + ''') OR (' + convert(varchar,@lClassId) + ' = 0))
  			  AND ((AD.DivisionId = ''' + convert(varchar,@lDivisionId) + ''') OR (' + convert(varchar,@lDivisionId) + ' = 0))
  			  AND  AD.BatchId='+Convert(varchar,@lBatchId)+''
  			--SELECT  @quer
  	     EXEC (@quer)
  	     
	    DEClare @query varchar(max)

  		select @query=  ' UPDATE  AR  SET PG = RD.Obtain FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=101 AND  ESGM.Code = ''101'' AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		
		 	exec (@query)
		 	
		 	select @query=  ' UPDATE  AR  SET Nursary = RD.Obtain FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=102 AND  ESGM.Code = ''101'' AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		
		 	exec (@query)
		 	
		 	select @query=  ' UPDATE  AR  SET SrKg = RD.Obtain FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=104 AND  ESGM.Code = ''101'' AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
		
		 	exec (@query)
		 	select @query=  ' UPDATE  AR  SET JrKg = RD.Obtain FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=103 AND  ESGM.Code = ''101'' AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		
		 	exec (@query)
		 	
   select @query=  ' UPDATE  AR  SET First = RD.Obtain FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId 
			WHERE CGM.ClassGroupId=1 AND  ESGM.Code = ''101'' AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 
select @query=  ' UPDATE  AR  SET Second = RD.Obtain FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=2 AND ESGM.Code = ''101'' AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 	
		 
	select @query=  ' UPDATE  AR  SET Third = RD.Obtain FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=3 AND ESGM.Code = ''101'' AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		   exec (@query)
		  
	select @query=  ' UPDATE  AR  SET Fourth = RD.Obtain FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=4 AND  ESGM.Code = ''101'' AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) +''
			
		 	exec (@query)
		 
select @query=  ' UPDATE  AR  SET Fifth = RD.Obtain FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=5 AND  ESGM.Code = ''101'' AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 	
select @query=  ' UPDATE  AR  SET Sixth = RD.Obtain FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=6 AND  ESGM.Code = ''101'' AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 	
select @query=  ' UPDATE  AR  SET Seventh = RD.Obtain FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=7 AND ESGM.Code = ''101'' AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
		 	exec (@query)
		 
	select @query=  ' UPDATE  AR  SET Eighth = RD.Obtain FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=8 AND  ESGM.Code = ''101'' AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 	
	select @query=  ' UPDATE  AR  SET Ninth = RD.Obtain FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=9 AND ESGM.Code = ''101'' AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
		
		 	exec (@query)
		 	
select @query=  ' UPDATE  AR  SET Tenth = RD.Obtain FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=10 AND ESGM.Code = ''101'' AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
		
		 	exec (@query)
		 	
	select @query=  ' UPDATE  AR  SET Eleventh = RD.Obtain FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=11 AND  ESGM.Code = ''101'' AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 
	select @query=  ' UPDATE  AR  SET Twelfth = RD.Obtain FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=12 AND ESGM.Code = ''101'' AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			exec (@query)
			
		 	select @query=  ' UPDATE  AR  SET PG1 = RD.Obtain FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=101 AND  ESGM.Code = ''102'' AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 	
		 	select @query=  ' UPDATE  AR  SET Nursary1 = RD.Obtain FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=102 AND  ESGM.Code = ''102'' AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
		
		 	exec (@query)
		 	select @query=  ' UPDATE  AR  SET SrKg1 = RD.Obtain FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=104 AND  ESGM.Code = ''102'' AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 	select @query=  ' UPDATE  AR  SET JrKg1 = RD.Obtain FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=103 AND  ESGM.Code = ''102'' AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 
   select @query=  ' UPDATE  AR  SET First1 = RD.Obtain FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId 
			WHERE CGM.ClassGroupId=1 AND  ESGM.Code = ''102'' AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 
		
select @query=  ' UPDATE  AR  SET Second1 = RD.Obtain FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=2 AND ESGM.Code = ''102'' AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 	
	select @query=  ' UPDATE  AR  SET Third1 = RD.Obtain FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=3 AND ESGM.Code = ''102'' AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
		
		   exec (@query)
		  
	select @query=  ' UPDATE  AR  SET Fourth1 = RD.Obtain FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=4 AND  ESGM.Code = ''102'' AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
		
		 	exec (@query)
		 	
select @query=  ' UPDATE  AR  SET Fifth1 = RD.Obtain FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=5 AND  ESGM.Code = ''102'' AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 
select @query=  ' UPDATE  AR  SET Sixth1 = RD.Obtain FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=6 AND  ESGM.Code = ''102'' AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 	
select @query=  ' UPDATE  AR  SET Seventh1 = RD.Obtain FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=7 AND ESGM.Code = ''102'' AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 	
	select @query=  ' UPDATE  AR  SET Eighth1 = RD.Obtain FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=8 AND  ESGM.Code = ''102'' AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 
	select @query=  ' UPDATE  AR  SET Ninth1 = RD.Obtain FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=9 AND ESGM.Code = ''102'' AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 
select @query=  ' UPDATE  AR  SET Tenth1 = RD.Obtain FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=10 AND ESGM.Code = ''102'' AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 	
		 	
	select @query=  ' UPDATE  AR  SET Eleventh1 = RD.Obtain FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=11 AND  ESGM.Code = ''102'' AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 	
	select @query=  ' UPDATE  AR  SET Twelfth1 = RD.Obtain FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=12 AND ESGM.Code = ''102'' AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
				exec (@query)
		 
		 	select @query=  ' UPDATE  AR  SET PG2 = RD.Obtain FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=101 AND  ESGM.Code = ''103'' AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 	select @query=  ' UPDATE  AR  SET Nursary2 = RD.Obtain FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=102 AND  ESGM.Code = ''103'' AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 	select @query=  ' UPDATE  AR  SET SrKg2 = RD.Obtain FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=104 AND  ESGM.Code = ''103'' AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 	select @query=  ' UPDATE  AR  SET JrKg2 = RD.Obtain FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=103 AND  ESGM.Code = ''103'' AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) +''
			
		 	exec (@query)
		 
   select @query=  ' UPDATE  AR  SET First2 = RD.Obtain FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId 
			WHERE CGM.ClassGroupId=1 AND  ESGM.Code = ''103'' AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 
		
select @query=  ' UPDATE  AR  SET Second2 = RD.Obtain FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=2 AND ESGM.Code = ''103'' AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 	
	select @query=  ' UPDATE  AR  SET Third2 = RD.Obtain FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=3 AND ESGM.Code = ''103'' AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		   exec (@query)
		   	
	select @query=  ' UPDATE  AR  SET Fourth2 = RD.Obtain FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=4 AND  ESGM.Code = ''103'' AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
		
		 	exec (@query)
		 	
select @query=  ' UPDATE  AR  SET Fifth2 = RD.Obtain FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=5 AND  ESGM.Code = ''103'' AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
		
		 	exec (@query)
		 	
select @query=  ' UPDATE  AR  SET Sixth2 = RD.Obtain FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=6 AND  ESGM.Code = ''103'' AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			exec (@query)
			
select @query=  ' UPDATE  AR  SET Seventh2 = RD.Obtain FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=7 AND ESGM.Code = ''103'' AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 		
	select @query=  ' UPDATE  AR  SET Eighth2 = RD.Obtain FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=8 AND  ESGM.Code = ''103'' AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 	
	select @query=  ' UPDATE  AR  SET Ninth2 = RD.Obtain FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=9 AND ESGM.Code = ''103'' AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 		
select @query=  ' UPDATE  AR  SET Tenth2 = RD.Obtain FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=10 AND ESGM.Code = ''103'' AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 	
	select @query=  ' UPDATE  AR  SET Eleventh2 = RD.Obtain FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=11 AND  ESGM.Code = ''103'' AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
		
		 	exec (@query)
		 	
	select @query=  ' UPDATE  AR  SET Twelfth2 = RD.Obtain FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=12 AND ESGM.Code = ''103'' AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
	   	exec (@query)
	   
		 	select @query='SELECT AR.StudentId,SM.Id AS SubjectId,Isnull(PG,0) AS PG,Isnull(Nursary,0) AS Nursary,Isnull(SrKg,0) AS SrKg , Isnull(JrKg,0) AS JrKg,Isnull(First,0) AS FirstAnnual,
		 	Isnull(Second,0) AS Second, Isnull(Third,0) As  Third, Isnull(Fourth,0) AS Fourth,Isnull(Fifth,0) AS Fifth, Isnull(Sixth,0) AS Sixth, Isnull(Seventh,0) AS Seventh, Isnull(Eighth,0) AS Eighth, Isnull(Ninth,0) AS Ninth, 
		 	Isnull(Tenth,0) As Tenth, Isnull(Eleventh,0) As Eleventh, Isnull(Twelfth,0) As Twelfth ,
		 	Isnull(PG1,0) AS PG1,Isnull(Nursary1,0) AS Nursary1,Isnull(SrKg1,0) AS SrKg1 , Isnull(JrKg1,0) AS JrKg1,Isnull(First1,0) AS First1,
		 	Isnull(Second1,0) AS Second1, Isnull(Third1,0) As  Third1, Isnull(Fourth1,0) AS Fourth1,Isnull(Fifth1,0) AS Fifth1, Isnull(Sixth1,0) AS Sixth1, Isnull(Seventh1,0) AS Seventh1, Isnull(Eighth1,0) AS Eighth1, Isnull(Ninth1,0) AS Ninth1, 
		 	Isnull(Tenth1,0) As Tenth1, Isnull(Eleventh1,0) As Eleventh1, Isnull(Twelfth1,0) As Twelfth1,
		 	Isnull(PG2,0) AS PG2,Isnull(Nursary2,0) AS Nursary2,Isnull(SrKg2,0) AS SrKg2 , Isnull(JrKg2,0) AS JrKg2,Isnull(First2,0) AS First2,
		 	Isnull(Second2,0) AS Second2, Isnull(Third2,0) As  Third2, Isnull(Fourth2,0) AS Fourth2,Isnull(Fifth2,0) AS Fifth2, Isnull(Sixth2,0) AS Sixth2, Isnull(Seventh2,0) AS Seventh2, Isnull(Eighth2,0) AS Eighth2, Isnull(Ninth2,0) AS Ninth2, 
		 	Isnull(Tenth2,0) As Tenth2, Isnull(Eleventh2,0) As Eleventh2, Isnull(Twelfth2,0) As Twelfth2
		 	, SM.Code As SubjectCode,A.Code,A.Name,A.BatchName,A.BatchId,SM.OrderIndex,A.RollNo
		     FROM sStudent.vStudentLastAcademic A  INNER JOIN  sAssessment.tAllBatchResult AR ON  AR.StudentId=A.StudentId 
	       INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=AR.SubjectId 
		    WHERE A.OrgId=' + convert(varchar,@lOrgId) + ' '
		   
		 exec (@query)
END
GO
PRINT N'Altering [sAssessment].[pRptCCEResultGet]...';


GO



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

	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	SELECT 
			--@rBuilder1 AS Builder1,
			--@rBuilder2 AS Builder2,
			 CONVERT (nvarchar(20),EM.GradeSetId) AS GradeSetIdText,
			  CONVERT (nvarchar(20),EM.CoScholasticGradeSetId) AS CoScholasticGradeSetIdText,
			SM.Code,
			  [sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Name,
			ISNULL(SF.FatherName,'') AS FatherName,
			ISNULL(SF.MotherName,'')AS MotherName,
			A.RollNo,
			CCER.AcademicId,
			CONVERT(NVARCHAR,CCER.AcademicId) AS AcademicIdText,
			CONVERT(NVARCHAR,EM.Id)AS ExamIdText,
			CONVERT(NVARCHAR,@rCCEExamId) AS CCEExamIdText,
			 
			 
			ISNULL(SC.ParentContactNo,'') AS ContactNo,
			 
			ISNULL(SC.PresentStreetOne,'')+' '+ISNULL(SC.PresentStreetTwo,'')+' '+ISNULL(SC.PresentStreetThree,'')+' '+ISNULL(SC.PresentCity,'')+' '+ISNULL(SC.PresentState,'') AS PresentAddress,
			--SO.DateOfBirth,
			CONVERT(VARCHAR(10),SO.DateOfBirth,103) AS DateOfBirth,
			CM.DisplayTitle AS Class,
			DM.DisplayTitle AS Division,
			ISNULL(HM.Title,'') AS House,
			ISNULL(CCER.AttendanceTerm1,0) AS AttendanceTerm1,
			ISNULL(CCER.AttendanceTerm2,0) AS AttendanceTerm2,
			ISNULL(CCER.WorkingDaysTerm1,0) AS WorkingDaysTerm1,
			ISNULL(CCER.WorkingDaysTerm2,0) AS WorkingDaysTerm2,
			ISNULL(SR.StudentHeight,0) AS Height,
			ISNULL(SR.StudentWeight,0) AS Weight,
			ISNULL(SR.VisionLeft,'') AS VisionLeft,
			ISNULL(SR.VisionRight,'') AS VisionRight,
			ISNULL(SR.DentalHygiene,'') AS DentalHygiene,
			ISNULL(BGM.Title,'') AS BloodGroup,
			EM.IsOnPrePrinted,
			EM.IsDisplayBirthDate,
			EM.IsDisplayPhoto,
			EM.IsDisplaySchoolName,			
			EM.IsLockForEdit,
			EM.IsIncludeCoScholastic,
			EM.IsDisplayAttendance,
			EM.IsDisplayHeightWeight,
			EM.IsResultStatus,
			EM.Remark1,
			EM.Remark2,
			EM.Remark3,
			EM.ExamSubGroupId,
			ESM.Code AS ExamSubGroupTitle,	
			EM.DisplayTitle,
			SI.StudentPhoto,
			ISNULL(EM.ExamMaximum,0) AS ExamMaximum,
			ISNULL(EM.FooterAdjustment,0) AS FooterAdjustment,
			ISNULL(EM.DetailAdjustment,0) AS DetailAdjustment,
			ISNULL(EM.TermScopeId,0) AS TermScopeId,	
			TSM.Title AS TermScopeTitle,
		ISNULL(EM.ReportId,0) as ReportId,
			'' AS GradeString,
			A.BatchId,
			BM.Title,
			SR.ResultRemark1,
			SR.ResultRemark2,
			(CASE EM.IsDisplayImageHeader WHEN 1 THEN
			OI.CertificateHeaderA4 
			ELSE NULL END)AS  MarksheetHeaderA4,
				ISNULL(EM.IsDisplayImageHeader,0) AS IsImageHeader	
			
			
			--CASE WHEN ED.ClassSubjectId=CS.Id THEN 'Yes' ELSE 'false' END AS Selected
      
	FROM 
	
			
            sAssessment.tCCEResult CCER  
            
			INNER JOIN sStudent.tAcademic A ON CCER.AcademicId=A.Id
		
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId
			left Join sStudent.tStudentFamily SF ON SF.StudentId =SM.Id
			LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=A.StudentId
			
			LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
			LEFT JOIN sActivity.tHouseMaster HM ON HM.Id=SO.HouseId
			LEFT JOIN sCommon.tBloodGroupMaster BGM ON BGM.Id=SO.BloodGroupId
			LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=SM.Id
			INNER JOIN sAssessment.tCCEExamSetting CE ON CE.ClassId = CM.Id AND CE.CCEExamId = @rCCEExamId AND CE.BatchId = @rBatchId 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ExamSubGroupId = CE.ExamSubGroupId AND EM.ClassId = CE.ClassId AND EM.BatchId = @rBatchId 
			Inner Join sAssessment.tExamSubGroupMaster ESM ON ESM.Id=EM.ExamSubGroupId
		 --INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id
			LEFT JOIN sSetup.tTermScopeMaster TSM ON TSM.Id = EM.TermScopeId
			LEFT JOIN sAssessment.tStudentRemark SR ON A. Id = SR.AcademicId AND EM. Id = SR.ExamId
			Inner Join sSetup.tBatchMaster BM ON BM.Id=A.BatchId
			--CROSS JOIN  sAssessment.tcceRptGroup RG ON CCER.AcademicId = RG.Id
				INNER JOIN sSetup.tOrganizationMaster OM ON SM.OrgId = OM.Id
				LEFT JOIN sSetup.tOrgImages OI ON OI.Orgid = OM.Id
	WHERE 
			
    A.BatchId = @rBatchId 
		
	AND (A.DivisionId=@rDivisionId OR @rDivisionId=0)
	AND (A.ClassId=@rClassId OR @rClassId=0) 
	 
	AND(CE.CCEExamId = @rCCEExamId OR @rCCEExamId=0)
	AND ( CCER.AcademicId=@rAcademicId OR @rAcademicId=0)
	AND (SM.StatusId=@rStatus OR @rStatus=0) 
	AND ((SM.Code=@rCode) OR (@rCode=''))
	AND((A.RollNo>=@rFromRollNo)OR (@rFromRollNo=0))
	AND ((A.RollNo<=@rToRollNo) OR(@rToRollNo=0))
	ORDER BY A.RollNo 
END
GO
PRINT N'Altering [sAssessment].[pRptExamAdmitcard]...';


GO
 

ALTER PROCEDURE [sAssessment].[pRptExamAdmitcard]
	  
	  @rBatchId int,
	  @rClassId int,
	  @rDivisionId int,
	 -- @rExamId int=0,
	  @rExamSubGroupId int=0,
	  @rCode nvarchar(20),
	  @rFromRollNo int,
	  @rToRollNo int,
	  @rDepartmentId int,
	  @rSubjectId int=0
	  
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON 
BEGIN 	
	SELECT 		
	       	ESGM.Title AS ExamName,
	       	ISNULL(ED.DisplayOrder,0) as DisplayOrder,
	        ISNULL(ED.ExamDate,GETDATE()) as ExamDate,
	        ISNULL(ED.ExamTime,'') as ExamTime,
	        V.SubjectName AS SubjectName,
	        CM.DisplayTitle+' / '+DM.DisplayTitle AS ClassDivision,
	         CM.DisplayTitle AS ClassName,
	         CM.Id As ClassId,
	         DM.Id AS DiVisionId,
	        V.ClassSubjectId AS ClassSubjectId,
	        SA.Name,
	        SA.RollNo,
	        SA.Code,
	        SF.FatherName,
	        So.DateOfBirth,
	        GM.Title AS Gender,
	        EM.Remark1,
	        EM.Remark2,
	        EM.Remark3,
	        SA.AcademicId,
	        SI.StudentPhoto,
	        SF.MotherName,
	        SR. ExamCenter,
	        SR.ExamSeatNo,
	        V.SubjectCode AS SubjectCode
	        
	        --EM.Id As ExamId,
	     
			FROM
			sStudent.vStudentAcademic SA 
			INNER JOIN sSetup.tClassMaster CM ON SA.ClassId=CM.Id 
			INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId=CM.Id AND SA.DivisionId=DM.Id
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tExamSubGroupMaster	ESGM ON ESGM.Id = EM.ExamSubGroupId
			INNER JOIN sAssessment.tExamGroupMaster EGM ON EGM.Id=ESGM.ExamGroupId
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			LEFT JOIN sSetup.vClassSubject V ON V.ClassSubjectId = Ed.ClassSubjectId  
			LEFT JOIN sAssessment.tOptionalSubject OS on OS.AcademicId=SA.AcademicId and OS.ClassSubjectId=V.ClassSubjectId
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId=SA.StudentId  
			LEFT JOIN sStudent.tStudentOther SO ON So.StudentId=SA.StudentId  
			LEFT JOIN sCommon.tGenderMaster GM ON GM.Id=So.GenderId   
			LEFT JOIN  sStudent.tStudentImages SI ON SI.StudentId=SA.StudentId 
			LEFT JOIN sAssessment.tStudentRemark SR ON SR.ExamId=EM.Id AND SR.AcademicId=SA.AcademicId
	WHERE 
			EM.BatchId = @rBatchId 
		 AND (SA.ClassId=@rClassId OR @rClassId=0) 
		 AND (SA.DivisionId=@rDivisionId OR @rDivisionId=0)
		 AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		 AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		 AND ((ESGM.Id = @rExamSubGroupId) OR (@rExamSubGroupId = 0))	
	     AND ((SA.Code=@rCode) OR (@rCode=''))
	     AND (SA.DepartmentId=@rDepartmentId OR @rDepartmentId=0) 
	     AND (V.SubjectId=@rSubjectId OR @rSubjectId=0) 
	    AND ((V.IsOptional = 1 AND  isnull(OS.AcademicId,0) <> 0) OR (V.IsOptional = 0))
END
GO
PRINT N'Altering [sAssessment].[pRptResultSheetOnlyCoScholasticTermwiseGet]...';


GO


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

BEGIN 

DECLARE @GradeString nvarchar(1000),
@GradeSetId int
 
SELECT @GradeSetId = GradesetId FROM sAssessment.tExamMaster WHERE Id = @rExamId
SELECT @GradeString = [sAssessment].[fGradeStringGet](@GradeSetId)  
	SELECT 
			ESGM.Title AS Exam,
			StuM.Code,
			StuM.FirstName+' '+StuM.MiddleName+' '+StuM.LastName AS Name,
			A.RollNo,
			CCEEM.AcademicId,
			--RD.Obtain,
			ISNULL(R.ResultStatus,'') AS ResultStatus,
			CM.DisplayTitle AS Class,
			DM.DisplayTitle AS Division,
			ISNULL(R.TotalMarks,0) AS TotalMarks,
			ISNULL(R.TotalObtain,0) AS TotalObtain,
			ISNULL(R.Percentage,0) AS Percentage,
			ISNULL(R.RankNumber,0) AS RankNumber,
			ISNULL(R.ResultGrade,0) AS ResultGrade,
			ISNULL(R.Percentile,0) AS Percentile,
			--SM.Title AS ClassSubject,
			--RD.Id AS ResultDetailId,
			ISNULL(R.Id,0) AS ResultId,
			--CS.Id AS SubjectId,
			--ED.Maximum,
			--RD.SubjectGrade,
			EM.IsMarksInDecimal,
			--SM.OrderIndex AS SubjectCode,
			--SM.Code AS SubjectCode,
			--SM.OrderIndex AS SubjectOrderIndex,
			ISNULL(EM.Remark1,'') AS Remark1,
			ISNULL(EM.Remark2,'') AS Remark2,
			ISNULL(EM.Remark3,'') AS Remark3,
			EM.DisplayTitle,
			EM.IsRankNo, 
			EM.IsGrade,
			EM.IsPercentile,
			EM.IsPercentage,
			EM.IsSubjectPercentile,
			EM.IsProcessResult,
			EM.IsMarksInDecimal,
			EM.IsNegativeMarks,
			EM.IsIncludeCoScholastic,
			EM.IsOnPrePrinted,
			EM.IsDisplayPhoto,
			EM.IsDisplayBirthDate,
			EM.IsLockForEdit,
			EM.IsDisplaySchoolName,			
			EM.IsDisplayAttendance,
			EM.IsDisplayHeightWeight,
			EM.IsResultStatus,
			REPLICATE(',',EM.FooterAdjustment) AS FooterAdjustmentText,
			REPLICATE(',',EM.DetailAdjustment) AS DetailAdjustmentText,
			EM.FooterAdjustment,
			EM.DetailAdjustment,
			ISNULL(R.ResultRemark,'') AS ResultRemark,
			SO.DateOfBirth,
			AD.HeightTerm1,
			AD.WeightTerm1,
			AD.HeightTerm2,
			AD.WeightTerm2,
			AD.HeightAnnual,
			AD.WeightAnnual,
			AD.PresentDaysTerm1,
			AD.PresentDaysTerm2,
			AD.PresentDaysAnnual,
			AD.TotalDaysTerm1,
			AD.TotalDaysTerm2,
			AD.TotalDaysAnnual,
			EM.TermScopeId,
			SI.StudentPhoto,
			@GradeString AS GradeString,
			CCEEM.Grade,
			CCEEM.GradeIndicator,
			CCEEM.DescriptiveIndicator,
			CCEM.Title AS CoSubject,
			CCEM.OrderIndex AS CoOrderIndex,
			CCEGM.Title AS CoSubjectGroup,
			CCEGM.OrderIndex AS CoOrderIndexGroup,
			EM.IsDisplayPrincipalSign,
			Em.IsDisplayTeacherSign,
			EI.EmployeeSign ,
			SR.StudentHeight,
			SR.TotalDays,
			SR.PresentDays,
			SR.StudentWeight,
			EM.IsCoScholasticGrade,
			EM.IsCoScholasticGradeIndicator,
			EM.IsCoScholasticGradeDesIndicator
	FROM 
			 
			 
			sAssessment.tCCECSExamScore CCEEM INNER JOIN   
			--INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
			  sAssessment.tExamMaster EM ON EM.Id=CCEEM.ExamId AND CCEEM.ExamId=@rExamId
			--INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			--INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId		
			INNER JOIN sStudent.tAcademic A ON A.Id=CCEEM.AcademicId
			LEFT JOIN sStudent.tAcademicDetail AD ON AD.AcademicId=A.Id
			INNER JOIN sAssessment.tCCECSMaster CCEM ON CCEM.Id=CCEEM.CCECSId
			INNER JOIN sAssessment.tCCECSGroupMaster CCEGM ON CCEGM.Id= CCEM.CCECAGroupId	
			INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
			
			LEFT JOIN sAssessment.tStudentRemark SR ON A.Id = SR.AcademicId AND EM.Id = SR.ExamId
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = StuM.Id
			
			
			LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
			LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=StuM.Id
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
			LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = Dm.InchargeEmployeeId
			
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.EXAMSUBGROUPID
			LEFT JOIN sAssessment.tResult R ON R.AcademicId = CCEEM.AcademicId AND R.ExamId = CCEEM.ExamId
	WHERE 
			
		EM.BatchId = @rBatchId 
		AND (A.ClassId=@rClassId OR @rClassId=0) 
		--AND ((SM.Id=@rSubjectId) OR (@rSubjectId=0))
		AND (A.DivisionId=@rDivisionId OR @rDivisionId=0)
		AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((R.RankNumber >= @rFromRank) OR (@rFromRank=0))
		AND ((R.RankNumber <= @rToRank) OR (@rToRank=0))
		AND ((R.ResultGrade = @rGrade) OR (@rGrade=''))		
		AND (CCEEM.ExamId = @rExamId)
		AND ((StuM.Code=@rCode) OR (@rCode=''))		
		AND ((StuM.StatusId=@rStatusId)OR(@rStatusId=0))
		order by A.RollNo--,CS.OrderIndex 
		--AND A.id = 1005000000007
END
GO
PRINT N'Altering [sAssessment].[pRptResultSheetStandardMultiExamGet]...';


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

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
 begin
 

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

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

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

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


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

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

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

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

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


GO
 


ALTER PROCEDURE [sAssessment].[pRptResultSheetSubjectAcivityMultiExamGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 
	 @rSubjectId int = 0,
	 @rBatchId int=0,
	 @rClass int=0,
	 @rDivisionId int=0,
	 @rExamId int,
	 @rCode nvarchar(20)='',
	 @rFromRollNo int=0,
	 @rToRollNo int=0,
	 @rFromRank int=0,
	 @rToRank int=0,
	 @rGrade nvarchar(20)='',
	 @rResultId bigint=0,
	 @rStatusId int=0,
	 @rAcademicId bigint=0,
	 @rOrgId int=0
	  
	 
	   
	 
	 
	  
	 

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
 begin
 

  
-- --drop table sAssessment.tTempAllExam	

 --Select * from   sAssessment.tTempAllExamSubjectActivity
DECLARE @GradeString nvarchar(1000),
@GradeSetId int , @IsIncludeSubExam bit
SELECT @GradeSetId = GradesetId,
	   @IsIncludeSubExam = ISNULL(IsIncludeSubExam,0)  FROM sAssessment.tExamMaster WHERE Id = @rExamId
SELECT @GradeString = [sAssessment].[fGradeStringGet](@GradeSetId)
 
--#TempAllExam
	CREATE TABLE #TempAllExam
	(
		AcademicIdText nvarchar(20),
		ExamIdText nvarchar(20),
		CoScholasticScopeIdText nvarchar(20),
		
		AcademicId bigint,
		ExamName Nvarchar(150),
		StudCode NVarchar(20),
		StudentName Nvarchar(150),
		RollNo int,
		ResultStatus Nvarchar(20),	
		ClassName NVarchar(50),		
		Division NVarchar(50),
		TotalMark decimal(8,2),
		TotalObtain decimal(8,2),
		Percentage decimal(8,2),
		RankNumber int,
		ResultGrade NVarchar(50),
		
		--MaximumMark1 decimal(8,2),		
		SubjectGrade1 NVarchar(50),
		--Obtain1 decimal(8,2),
		--ExamMaximum1 decimal(8,2),
		IsPresent1 bit,
						
		MaximumMark2 decimal(8,2),	
		SubjectGrade2 NVarchar(50),
		Obtain2 decimal(8,2),
		ExamMaximum2 decimal(8,2),
		IsPresent2 bit,
				
		MaximumMark3 decimal(8,2),
		SubjectGrade3 NVarchar(50),
		Obtain3 decimal(8,2),
		ExamMaximum3 decimal(8,2),
		IsPresent3 bit,		
		
		MaximumMark4 decimal(8,2),	
		SubjectGrade4 NVarchar(50),
		Obtain4 decimal(8,2),
		ExamMaximum4 decimal(8,2),
		IsPresent4 bit,	
				
		MaximumMark5 decimal(8,2),		
		SubjectGrade5 NVarchar(50),
		Obtain5 decimal(8,2),
		ExamMaximum5 decimal(8,2),
		IsPresent5 bit,	
				
		MaximumMark6 decimal(8,2),		
		SubjectGrade6 NVarchar(50),
		Obtain6 decimal(8,2),
		ExamMaximum6 decimal(8,2),
		IsPresent6 bit,	
		
		MaximumMark7 decimal(8,2),		
		SubjectGrade7 NVarchar(50),
		Obtain7 decimal(8,2),
		ExamMaximum7 decimal(8,2),
		IsPresent7 bit,	
		
		MaximumMark8 decimal(8,2),	
		SubjectGrade8 NVarchar(50),
		Obtain8 decimal(8,2),
		ExamMaximum8 decimal(8,2),
		IsPresent8 bit,	
		
		SubjectGradeTerm1 NVarchar(50),
		SubjectGradeTerm2 NVarchar(50),
		IsMarksInDecimal bit,
		column_visible bit,
		--Obtain decimal(5,2),
		Percentile decimal(5,2),
		--ClassSubject nvarchar(100),
		ResultDetailId bigint,
		ResultId bigint,	
		Remark1 nvarchar(150),
		Remark2 nvarchar(150),
		Remark3 nvarchar(150),
		DisplayTitle nvarchar(150),		
		IsRankNo bit, 
		IsGrade bit,
		IsPercentile bit,
		IsPercentage bit,
		IsSubjectPercentile bit,
		IsProcessResult bit,
		IsNegativeMarks bit,
		IsIncludeCoScholastic bit,
		IsOnPrePrinted bit,
		IsDisplayPhoto bit,
		IsDisplayBirthDate bit,
		IsLockForEdit bit,
		IsDisplaySchoolName bit,			
		IsDisplayAttendance bit,
		IsDisplayHeightWeight bit,
		IsResultStatus bit,
		FooterAdjustmentText nvarchar(max),
		DetailAdjustmentText nvarchar(max),
		FooterAdjustment smallint,
		DetailAdjustment smallint,
		ResultRemark nvarchar(200),
		DateOfBirth date,
		HeightTerm1 decimal(5,2),
		WeightTerm1 decimal(5,2),
		HeightTerm2 decimal(5,2),
		WeightTerm2 decimal(5,2),
		HeightAnnual decimal(5,2),
		WeightAnnual decimal(5,2),
		PresentDaysTerm1 smallint,
		PresentDaysTerm2 smallint,
		PresentDaysAnnual smallint,
		TotalDaysTerm1 smallint,
		TotalDaysTerm2 smallint,
		TotalDaysAnnual smallint,
		TotalMarkTerm1 decimal(8,2),
		TotalObtainTerm1 decimal(8,2),
		PercentageTerm1 decimal(8,2),
		RankNumberTerm1 int,
		ResultGradeTerm1 NVarchar(50),
		PercentileTerm1 decimal(8,2),
		ResultStatusTerm1 Nvarchar(20),		   
		TotalMarkTerm2 decimal(8,2),
		TotalObtainTerm2 decimal(8,2),
		PercentageTerm2 decimal(8,2),
		RankNumberTerm2 int,
		ResultGradeTerm2 NVarchar(50),
		PercentileTerm2 decimal(8,2),
		ResultStatusTerm2 Nvarchar(20), 
		TermScopeId tinyint,		 
		StudentPhoto varbinary(max),
		GradeString nvarchar(1000),
		IsDisplayGradeString bit,		 
		IsDisplayInMarksheet bit,
		IsShowSubjectGrade bit,
		IsIncludeInTotal bit,
		ClassSubjectID int,
		SubjectId int,
		--Maximum decimal(5,2),
		SubjectOrderIndex smallint,
		SubjectGrade NVarchar(50),
		SubjectName NVarchar(150),
		SubjectCode Nvarchar(50),	
		SubjectMinimum decimal(8,2),		
		SubjectMaximum decimal(8,2),
		SubjectObtain  decimal(8,2),
		
		Exam1Name Nvarchar(150),		
		TotalMarks1 decimal(8,2),		
		TotalObtain1 decimal(8,2),
		Percentage1 decimal(8,2),
		RankNumber1 int,
		ResultGrade1 NVarchar(50),
		Percentile1 decimal(8,2),
		ResultStatus1 Nvarchar(20),
		
		SubActivityGrade1 nvarchar(10),
		
		Exam2Name nvarchar(150),	
		TotalMarks2 decimal(8,2),
		TotalObtain2 decimal(8,2),
		Percentage2 decimal(8,2),
		RankNumber2 int,
		ResultGrade2 NVarchar(50),
		Percentile2 decimal(8,2),
		ResultStatus2 Nvarchar(20),
		
		SubActivityGrade2 nvarchar(10),
		
		Exam3Name nvarchar(150),	
		TotalMarks3 decimal(8,2),
		TotalObtain3 decimal(8,2),
		Percentage3 decimal(8,2),
		RankNumber3 int,
		ResultGrade3 NVarchar(50),
		Percentile3 decimal(8,2),		
		ResultStatus3 Nvarchar(20),
		
		SubActivityGrade3 nvarchar(10),
		
		Exam4Name nvarchar(150),	
		TotalMarks4 decimal(8,2),
		TotalObtain4 decimal(8,2),
		Percentage4 decimal(8,2),
		RankNumber4 int,
		ResultGrade4 NVarchar(50),
		Percentile4 decimal(8,2),
		ResultStatus4 Nvarchar(20),
		
		SubActivityGrade4 nvarchar(10),
		
		Exam5Name nvarchar(150),		
		TotalMarks5 decimal(8,2),
		TotalObtain5 decimal(8,2),
		Percentage5 decimal(8,2),
		RankNumber5 int,
		ResultGrade5 NVarchar(50),
		Percentile5 decimal(8,2),
		ResultStatus5 Nvarchar(20),
		
		SubActivityGrade5 nvarchar(10),
		
		Exam6Name nvarchar(150),	
		TotalMarks6 decimal(8,2),
		TotalObtain6 decimal(8,2),
		Percentage6 decimal(8,2),
		RankNumber6 int,
		ResultGrade6 NVarchar(50),
		Percentile6 decimal(8,2),
		ResultStatus6 Nvarchar(20),
		
		SubActivityGrade6 nvarchar(10),
		
		Exam7Name nvarchar(150),		
		TotalMarks7 decimal(8,2),
		TotalObtain7 decimal(8,2),
		Percentage7 decimal(8,2),
		RankNumber7 int,
		ResultGrade7 NVarchar(50),
		Percentile7 decimal(8,2),
		ResultStatus7 Nvarchar(20),
		
		--SubActivityGrade7 nvarchar(10),
		
		Exam8Name nvarchar(150),
		TotalMarks8 decimal(8,2),
		TotalObtain8 decimal(8,2),
		Percentage8 decimal(8,2),
		RankNumber8 int,
		ResultGrade8 NVarchar(50),
		Percentile8 decimal(8,2),
		ResultStatus8 Nvarchar(20),
		ResultRemark1 nvarchar(200),
		ResultRemark2 nvarchar(200),
		TotalDays smallint,
		PresentDays smallint,
		StudentHeight decimal(6,2),
		StudentWeight decimal(6,2),
		ExamSeatNo nvarchar(20),
		ExamId int,
		IsDisplayParentName bit,
		FatherName nvarchar(30),
		MotherName nvarchar(30),
		IsShowSubjectMark bit, 
		IsOptionalSubject bit,
		CoScholasticScopeId tinyint,
		IsDisplayPrincipalSign bit,
		IsDisplayTeacherSign bit,
		EmployeeSign varbinary(max),
		
		ActivityName nvarchar(200),
		SubActivityName nvarchar(200),
		SubActivityId int,
		ActivityId Int,
		 SubActivityGrade nvarchar(10),
		SubActivityGradeIndicator nvarchar(50),
		SubActivityDescriptiveIndicator nvarchar(200),
		SubjectActivityOrderIndex Smallint,
		SubActivityOrderIndex smallint,
		ColumnSubjectCount SmallInt,
		MarksheetHeaderA4 varbinary(max),
		IsImageHeader bit,
		Height1 decimal(6,2),
		Height2 decimal(6,2),
		Height3 decimal(6,2),
		Height4 decimal(6,2),
		Height5 decimal(6,2),
		Height6 decimal(6,2),
		Weight1 decimal(6,2),
		Weight2 decimal(6,2),
		Weight3 decimal(6,2),
		Weight4 decimal(6,2),
		Weight5 decimal(6,2),
		Weight6 decimal(6,2),
		TotalDays1 smallint,
		PresentDays1 smallint,
		TotalDays2 smallint,
		PresentDays2 Smallint,
		TotalDays3 smallint,
		PresentDays3 smallint,
		TotalDays4 smallint,
		PresentDays4 smallint,
		TotalDays5 smallint,
		PresentDays5 smallint,
		TotalDays6 smallint,
		PresentDays6 smallint,
		MyActivity1 nvarchar(200),
		MyActivity2 nvarchar(200),
		MyActivity3 nvarchar(200),
		MyActivity4 nvarchar(200),
		MyActivity5 nvarchar(200),
		MyActivity6 nvarchar(200),
		GeneralRemark1 nvarchar(200),
		GeneralRemark2 nvarchar(200),
		GeneralRemark3 nvarchar(200),
		GeneralRemark4 nvarchar(200),
		GeneralRemark5 nvarchar(200),
		GeneralRemark6 nvarchar(200),
		PresentAddress nvarchar(500) ,
		 MobileNo nvarchar(50),
		House nvarchar(20),
		 
		AttendanceTerm1 int ,
		AttendanceTerm2 int,
		WorkingDaysTerm1 int,
		WorkingDaysTerm2 int,
		  BloodGroup nvarchar(10),
		  GradeSetIdText nvarchar(50),
		  IsDisplayMonthlyAttendanceText nvarchar(20)
		
 
	)	
	
	 --print 'temp created'    	
	INSERT INTO  #TempAllExam 
	(
	AcademicIdText,
	ExamIdText,
	CoScholasticScopeIdText,
	
	AcademicId,
	ExamName,
	StudCode,
	StudentName,
	RollNo,
	ResultStatus,
	ClassName,
	Division,
	TotalMark,
	TotalObtain,
	Percentage,
	RankNumber,
	ResultGrade,
	IsMarksInDecimal,
	column_visible,
	--Obtain,
	Percentile,
	--ClassSubject,
	ResultDetailId,
	ResultId,

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


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

		ISNULL(EM.Remark1,'') AS Remark1,
		ISNULL(EM.Remark2,'') AS Remark2,
		ISNULL(EM.Remark3,'') AS Remark3,
		EM.DisplayTitle,
		EM.IsRankNo, 
		EM.IsGrade,
		EM.IsPercentile,
		EM.IsPercentage,
		EM.IsSubjectPercentile,
		EM.IsProcessResult,
		EM.IsNegativeMarks,
		EM.IsIncludeCoScholastic,
		EM.IsOnPrePrinted,
		EM.IsDisplayPhoto,
		EM.IsDisplayBirthDate,
		EM.IsLockForEdit,
		EM.IsDisplaySchoolName,			
		EM.IsDisplayAttendance,
		EM.IsDisplayHeightWeight,
		EM.IsResultStatus,
		REPLICATE(',',EM.FooterAdjustment) AS FooterAdjustmentText,
		REPLICATE(',',EM.DetailAdjustment) AS DetailAdjustmentText,
		EM.FooterAdjustment,
		EM.DetailAdjustment,
		ISNULL(R.ResultRemark,'') AS ResultRemark,
		SO.DateOfBirth,
		AD.HeightTerm1,
		AD.WeightTerm1,
		AD.HeightTerm2,
		AD.WeightTerm2,
		AD.HeightAnnual,
		AD.WeightAnnual,
		AD.PresentDaysTerm1,
		AD.PresentDaysTerm2,
		AD.PresentDaysAnnual,
		AD.TotalDaysTerm1,
		AD.TotalDaysTerm2,
		AD.TotalDaysAnnual,
		EM.TermScopeId,
		SI.StudentPhoto,
		@GradeString AS GradeString,
		EM.IsDisplayGradeString,
		ED.IsDisplayInMarksheet,
		ED.IsShowSubjectGrade,
		ED.IsIncludeInTotal,
	    SAM.ClassSubjectId,
		CS.SubjectId AS SubjectId,
		--ED.Maximum,
		(CASE ISNULL(ED.DisplayOrder,0)
		WHEN 0 THEN CS.OrderIndex
		ELSE ED.DisplayOrder END) AS SubjectOrderIndex,
		
		--SM.OrderIndex AS SubjectOrderIndex,
		RD.SubjectGrade,
		SM.Title AS SubjectName,
		ISNULL(SM.Code,'') AS SubjectCode,
		ED.Minimum,
		ED.Maximum,
		RD.Obtain,
		SR.ResultRemark1,
		SR.ResultRemark2,
		SR.TotalDays,
		SR.PresentDays,
		SR.StudentHeight,
		SR.StudentWeight,
		SR.ExamSeatNo,
		@rExamId,
		EM.IsDisplayParentName,
		SF.FatherName,
		SF.MotherName,
		ED.IsShowSubjectMark,
		--EMP.FirstName
		(CASE ISNULL(OS.AcademicId,0)
		WHEN 0 THEN 0
		ELSE 1 END) AS IsOptionalSubject,
		EM.CoScholasticScopeId,
		EM.IsDisplayPrincipalSign,
		Em.IsDisplayTeacherSign,
		EI.EmployeeSign,
		SSA.Grade AS SubActivityGrade,
		SAM.Title AS ActivityName,
		SSAM.Title AS SubActivityName,
		SSA.SubjectSubActivityId AS SubActivityId,
		SAM.Id AS ActivityId,
		SSA.GradeIndicator AS SubActivityGradeIndicator,
		SSA.DescriptiveIndicator AS SubActivityDescriptiveIndicator,
		SAM.OrderIndex AS SubjectActivityOrderIndex,
		SSAM.OrderIndex AS SubActivityOrderIndex,
		CASE WHEN CS.OrderIndex % 2 = 0 THEN 2 
				ELSE 1 END   AS   ColumnSubjectCount,
		(CASE EM.IsDisplayImageHeader WHEN 1 THEN
			OI.CertificateHeaderA4 
			ELSE NULL END)AS  MarksheetHeaderA4,
		ISNULL(EM.IsDisplayImageHeader,0) AS IsImageHeader	,
		ISNULL(SC.PresentStreetONe,'')+' '+ISNULL(SC.PresentStreetTwo,'')+' '+ISNULL(SC.PresentStreetThree,'')+' '+ISNULL(SC.PresentCity,'')+' '+ISNULL(SC.PresentState,'') AS PresentAddress,
		 SC.ParentContactNo,
		ISNULL(HM.Title,'') AS House,
		ISNULL(CCER.AttendanceTerm1,0) AS AttendanceTerm1,
		ISNULL(CCER.AttendanceTerm2,0) AS AttendanceTerm2,
		ISNULL(CCER.WorkingDaysTerm1,0) AS WorkingDaysTerm1,
		ISNULL(CCER.WorkingDaysTerm2,0) AS WorkingDaysTerm2,
		ISNULL(BGM.Title,'') AS BloodGroup,
		CONVERT (nvarchar(50),EM.GradeSetId) AS GradeSetIdText,
				Convert(nvarchar(20),ISNULL(EM.IsDisplayMonthlyAttendance,0))
		 
			 
			
FROM 


	
			 
	sAssessment.tCCESubjectSubActivityExamScore SSA
	INNER JOIN sAssessment.tCCESubjectSubActivityMaster SSAM ON SSAM.Id = SSA.SubjectSubActivityId
	INNER JOIN sAssessment.tCCESubjectActivityMaster SAM ON SAM.Id = SSAM.SubjectActivityId
	
	 INNER JOIN sAssessment.vCCEExamClassSubject CS ON CS.ClassSubjectId=SAM.ClassSubjectId
	
	 INNER JOIN sAssessment.tExamMaster EM ON EM.Id=SSA.ExamId
	INNER JOIN sAssessment.tExamDetail ED ON EM.Id=ED.ExamId AND ED.ClassSubjectId = SAM.ClassSubjectId
			
			
	--INNER JOIN sSetup.tClassSubject CS ON CS.Id=SAM.ClassSubjectId
	INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId					 
	  

	 
	 INNER JOIN sStudent.tAcademic  A ON   SSA.AcademicId = A.Id
	 
	LEFT JOIN    sAssessment.tCCEResult CCER    ON  CCER.AcademicId=A.Id
	INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
	INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
	INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
	LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = Dm.InchargeEmployeeId
	 
	INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.EXAMSUBGROUPID
	LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=StuM.Id
	
	 LEFT JOIN sCommon.tBloodGroupMaster BGM ON BGM.Id=SO.BloodGroupId
	LEFT JOIN sStudent.tAcademicDetail AD ON AD.AcademicId=A.Id
	LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=StuM.Id
	
	LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = StuM.Id
	LEFT JOIN sAssessment.tOptionalSubject OS ON OS.AcademicId = A.Id AND OS.ClassSubjectId = ED.ClassSubjectId  
	
	LEFT JOIN sAssessment.tResult R ON R.AcademicId = SSA.AcademicId AND R.ExamId = SSA.ExamId
	LEFT JOIN sAssessment.tResultDetail RD  ON R.Id = RD.ResultId AND ED.ExamId = R.ExamId
	LEFT JOIN sAssessment.tStudentRemark SR ON A.Id = SR.AcademicId AND EM.Id = SR.ExamId
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = StuM.OrgId
	LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = OM.Id
	LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId =Stum.ID
	LEFT JOIN sActivity.tHouseMaster HM ON HM.Id=SO.HouseId
	--LEFT JOIN sAcademic.tTeacherSubjectDivision TSD ON TSD.SubjectId=SM.Id AND TSD.DivisionId = A.DivisionId
	--LEFT JOIN sHrm.tEmployeeMaster EMP ON TSD.EmployeeId = EMP.Id
	
	 WHERE
		SSA.ExamId = @rExamId 
		AND ((A.DivisionId =  @rDivisionId) OR (@rDivisionId=0))
		AND ((A.ClassId =  @rClass) OR (@rClass=0))		 
		AND ((A.BatchId =  @rBatchId) OR (@rBatchId=0))
		AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		--AND ((R.RankNumber >= @rFromRank) OR (@rFromRank=0))
		--AND ((R.RankNumber <= @rToRank) OR (@rToRank=0))
		--AND ((R.ResultGrade = @rGrade) OR (@rGrade=''))
		--AND ((StuM.Code=@rCode) OR (@rCode=''))	
		--AND ((R.Id = @rResultId) OR (@rResultId = 0))	
		--AND ((StuM.StatusId=@rStatusId)OR(@rStatusId=0))
		AND((A.Id=@rAcademicId)OR (@rAcademicId=0))
		--AND ((CS.SubjectId=@rSubjectId) OR(@rSubjectId=0) ) 
		 
	 
	Order By ED.DisplayOrder
 
	
 --print 'temp insert'
  --SET @IsIncludeSubExam = 1
	create TABLE #tempcombineExam
	(	Id int IDENTITY,
		ExamID int )

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


	
	
	
	

	
	SELECT @rBuilder1 , T.*
	FROM #TempAllExam T
	
	
		
	drop table #tempcombineExam
	Drop table #TempAllExam
	
	END

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


GO
 

ALTER PROCEDURE [sAssessment].[pRptSubjectActivityExamDetailGet]
	  
	   @rOrgId int=0
	  ,@rExamId int=0,
	  @rClass int=0,
	  @rDivisionId int=0,
	  @rBatchId int=0,
	  @rBuilder1 nvarchar(max)='',
	  @rAcademicId bigint=0,
	  @rCode nvarchar(20)='',
	  @rFromRollNo int=0,
	  @rToRollNo int=0
	  
	  
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON 
BEGIN 	 
Declare @GradeString nvarchar(500),@GradeSetId int
SELECT @GradeSetId = GradesetId  FROM sAssessment.tExamMaster WHERE Id = @rExamId
SELECT @GradeString = [sAssessment].[fGradeStringGet](@GradeSetId)

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


GO

ALTER PROC [sAssessment].[pStudentResultViewGet]
	
	@rAcademicId bigint=0,
	@rBatchId int=0,
	@rExamId int=0 
 
AS
BEGIN
	
	DECLARE @lResultGrid VARCHAR(max)=''
	SELECT @lResultGrid = @lResultGrid + '<tr>
	<td align="left" scope="col">' + isnull(SBM.Title,'') + '</td>
	<td align="left" scope="col">' + convert(varchar,isnull(ED.Maximum,0)) + '</td>
	<td align="left" scope="col">' + convert(varchar,isnull(ED.Minimum,0))+ '</td>
	<td align="left" scope="col">' + convert(varchar,isnull(RD.Obtain,0)) + '</td>
	<td align="left" scope="col">' + convert(varchar,isnull(RD.GraceMark,0)) + '</td>
	<td align="left" scope="col">' + isnull(RD.Remark,'') + '</td>
	<tr>'
    	
   FROM sStudent.tAcademic AD
	INNER JOIN sAssessment.tExamMaster EM ON EM.BatchId = AD.BatchId AND EM.ClassId = AD.ClassId
	INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId = EM.Id
	INNER JOIN sAssessment.tResult R ON AD.Id = R.AcademicId AND R.ExamId = EM.Id
	INNER JOIN sAssessment.tResultDetail RD ON RD.ExamDetailId = ED.Id AND R.Id = RD.ResultId
	INNER JOIN sSetup.tClassSubject CS ON CS.Id = ED.ClassSubjectId
	INNER JOIN sSetup.tSubjectMaster SBM ON SBM.Id = CS.SubjectId
	INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId
	Where
	((AD.Id=@rAcademicId) OR (@rAcademicId=0))
	AND ((AD.BatchId =  @rBatchId) OR (@rBatchId=0))
   AND ((EM.Id=@rExamId) OR (@rExamId=0))
  
select isnull(@lResultGrid,'') as ResultGrid
END
GO
PRINT N'Altering [sAssetManagement].[pAssetMasterListGet]...';


GO
ALTER PROCEDURE [sAssetManagement].[pAssetMasterListGet]
	@rOrgId [int] ,
	@rAssetTag [int] = 0,
	@rAssetDescription [nvarchar](50) = '',
	@rModelNo [nvarchar](50) = '',
	@rManufacturer [nvarchar](50) = '',
	@rCategoryId [int] = 0,
	@rLocationId [int] = 0,
	@rDepartmentId [int] = 0,
	@rCode [nvarchar](50) = '',
	@rStatusId [int] = 0,
	@rTag [int] = 0,
	@rFromDate [datetime] = '',
	@rToDate [datetime] = '',
	@rIscritical [bit] = 0,
	@rStoreLocationId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
        IF @rFromDate IS NULL
         SET @rFromDate = sCommon.fGetDate()
         
       SELECT Tas.Id AS AssetTag,
                  Tas.CODE,
                  Tas.Title AS AssetDescription,
                  Tas.LocationId,
                  LOC.Title AS Location,
                  Tas.StatusId,
                  STAT.title AS status,
                  Tas.ModelNumber AS ModelNo,
                  Tas.CategoryId,
                  Cat.TITLE AS Category,
                  'AS' AS Manufacturer,
                  Tas.MaintenanceAlertPeriod,
                  day(Tas.NextMaintenanceDate) AS NextMaintenanceDate,
                  Tas.NextMaintenanceDate AS DueDate,
                  ISNULL(Tas.NextMaintenanceDate, sCommon.fGetDate()) AS NextDate,
            Tas.LastMaintenanceDate AS lastDate,
            Tas.Iscritical,
            AD.Title AS  DepartmentTitle 

          FROM sAssetManagement.tAssetMaster Tas
         INNER JOIN  sFixedAsset.tCategoryMaster Cat
         ON TAS.CATEGORYID = CAT.ID
         INNER JOIN  sCommon.tStatusMaster STAT
         ON STAT.ID =  Tas.UsageStatusId 
         INNER JOIN  sFixedAsset.VextLocationMaster LOC
         ON LOC.ID = TAS.LocationId
         INNER JOIN sSetup.tDepartmentMaster  AD
         ON AD.Id = Tas.DepartmentID
           
        WHERE 
         Tas.OrgId = @rOrgId AND
        ((((Tas.Id = @rAssetTag) OR (@rAssetTag = 0)) 
        AND ((Tas.Code = @rCode) OR (@rCode = '')) 
        AND ((Tas.Title = @rAssetDescription) OR (@rAssetDescription = '')) 
        AND ((Tas.ModelNumber = @rModelNo) OR (@rModelNo = '')) 
        AND ((Tas.CategoryId = @rCategoryId) OR (@rCategoryId = 0))  
        AND ((Tas.LocationId = @rLocationId) OR (@rLocationId = 0))
        AND ((Tas.DepartmentId = @rDepartmentId) OR (@rDepartmentId = 0)) 
        AND((Tas.StoreLocationId=@rStoreLocationId) OR @rStoreLocationId=0)
        AND ((Tas.UsageStatusId = @rStatusId) OR (@rStatusId = 0))) AND @rTag = 0 AND Tas.UsageStatusId <> 124 )
        
        OR ((((Tas.Id = @rAssetTag) OR (@rAssetTag = 0)) 
        AND ((Tas.Code = @rCode) OR (@rCode = '')) 
        AND ((Tas.Title = @rAssetDescription) OR (@rAssetDescription = '')) 
        AND ((Tas.ModelNumber = @rModelNo) OR (@rModelNo = '')) 
        AND ((Tas.CategoryId = @rCategoryId) OR (@rCategoryId = 0))  
        AND ((Tas.LocationId = @rLocationId) OR (@rLocationId = 0))
        AND ((Tas.DepartmentId = @rDepartmentId) OR (@rDepartmentId = 0)) 
         AND  (CONVERT(NVARCHAR(10), DATEADD(DD,(- Tas.MaintenanceAlertPeriod), Tas.NextMaintenanceDate), 111)  <=  CONVERT(NVARCHAR(10), @rFromDate, 111) )  
        AND  (Tas.NextMaintenanceDate  >=  @rFromDate ) 
         AND((Tas.StoreLocationId=@rStoreLocationId) OR @rStoreLocationId=0)
        AND ((Tas.UsageStatusId = @rStatusId) OR (@rStatusId = 0))) AND @rTag = 1 AND Tas.UsageStatusId <> 124  ) 
          OR ((((Tas.Id = @rAssetTag) OR (@rAssetTag = 0)) 
          AND ((Tas.Code = @rCode) OR (@rCode = '')) 
        AND ((Tas.LocationId = @rLocationId) OR (@rLocationId = 0)) 
        AND ((Tas.ModelNumber = @rModelNo) OR (@rModelNo = '')) 
        AND ((Tas.DepartmentId = @rDepartmentId) OR (@rDepartmentId = 0)) 
        AND ((Tas.CategoryId = @rCategoryId) OR (@rCategoryId = 0)) 
        AND ((Tas.LocationId = @rLocationId) OR (@rLocationId = 0))
        AND ((Tas.UsageStatusId = @rStatusId) OR (@rStatusId = 0))
        AND  (CONVERT(NVARCHAR(10), Tas.NextMaintenanceDate, 111)  >=  CONVERT(NVARCHAR(10), @rFromDate, 111) ) 
        AND (Tas.NextMaintenanceDate  <= (@rToDate + 1) )
        AND((Tas.StoreLocationId=@rStoreLocationId) OR (@rStoreLocationId=0))
        AND ((Iscritical = @rIscritical))) AND @rTag = 2 AND Tas.UsageStatusId <> 124 ) 
        
        ORDER BY  Tas.Id DESC
         
        
END
GO
PRINT N'Altering [sAssetManagement].[pRptAssetMasterListGet]...';


GO
ALTER PROCEDURE [sAssetManagement].[pRptAssetMasterListGet]
	@rOrgId [int] ,
	@rAssetTag [int] = 0,
	@rAssetDescription [nvarchar](50) = '',
	@rModelNo [nvarchar](50) = '',
	@rManufacturer [nvarchar](50) = '',
	@rCategoryId [int] = 0,
	@rLocationId [int] = 0,
	@rCode [nvarchar](50) = '',
	@rStatusId [int] = 0,
	@rTag [int] = 0,
	@rFromDate [datetime] = '',
	@rToDate [datetime] = '',
	@rIscritical [bit] = 0,
	@rStoreLocationId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
DECLARE @lDepartmentId Int
SET @lDepartmentId = @rLocationId
BEGIN
      SELECT Tas.Id AS AssetTag,
                  Tas.CODE,
                  Tas.Title AS AssetDescription,
                  Tas.LocationId,
                  LOC.Title AS Location,
                  Tas.StatusId,
                  STAT.title AS status,
                  Tas.ModelNumber AS ModelNo,
                  Tas.CategoryId,
                  Cat.TITLE AS Category,
                  'AS' AS Manufacturer,
                  Tas.MaintenanceAlertPeriod,
                  day(Tas.NextMaintenanceDate) AS NextMaintenanceDate,
                  Tas.NextMaintenanceDate AS DueDate,
                  sCommon.fReportDateGet(CAST(ISNULL(Tas.NextMaintenanceDate, sCommon.fGetDate())AS DATETIME)) AS NextDate,
            sCommon.fReportDateGet(CAST(Tas.LastMaintenanceDate AS DATETIME)) AS lastDate,
            Tas.Iscritical,
             Cat.TITLE AS HCategory,             
                  STAT.title AS HTitle,
            sCommon.fReportDateGet(CAST(@rFromDate  AS DATETIME)) AS FromDate,
                  sCommon.fReportDateGet(CAST(@rToDate AS DATETIME)) AS ToDate,
                  @rModelNo AS ModelNo,
                  @rCode AS  HAssetTag,
                  @rAssetDescription AS HAssetDescription,
                  ODM.Title AS DeptName
            
         FROM sAssetManagement.tAssetMaster Tas
         INNER JOIN  sFixedAsset.tCategoryMaster Cat
         ON TAS.CATEGORYID = CAT.ID
         INNER JOIN  sCommon.tStatusMaster STAT
         ON STAT.ID =  Tas.UsageStatusId 
         INNER JOIN  sFixedAsset.VextLocationMaster LOC
         ON LOC.ID = TAS.LocationId
         --INNER JOIN (SELECT DISTINCT DepartmentId, DepartmentTitle FROM sAssetManagement.vExtAssetDepartment) AD
         --ON AD.DepartmentId = Tas.DepartmentID
          	INNER JOIN sSetup.tDepartmentMaster ODM
      	ON ODM.Id = Tas.DepartmentID
         
        WHERE 
        Tas.OrgId = @rOrgId AND
        ((((Tas.Id = @rAssetTag) OR (@rAssetTag = 0)) 
        AND ((Tas.Code = @rCode) OR (@rCode = '')) 
        AND ((Tas.Title = @rAssetDescription) OR (@rAssetDescription = '')) 
        AND ((Tas.ModelNumber = @rModelNo) OR (@rModelNo = '')) 
        AND ((Tas.CategoryId = @rCategoryId) OR (@rCategoryId = 0))  
        AND ((Tas.LocationId = @rLocationId) OR (@rLocationId = 0))
        AND ((Tas.DepartmentId = @lDepartmentId) OR (@lDepartmentId = 0)) 
        AND((Tas.StoreLocationId=@rStoreLocationId) OR @rStoreLocationId=0)
        AND ((Tas.UsageStatusId = @rStatusId) OR (@rStatusId = 0))) AND @rTag = 0 AND Tas.UsageStatusId <> 124 )
        
        OR ((((Tas.Id = @rAssetTag) OR (@rAssetTag = 0)) 
        AND ((Tas.Code = @rCode) OR (@rCode = '')) 
        AND ((Tas.Title = @rAssetDescription) OR (@rAssetDescription = '')) 
        AND ((Tas.ModelNumber = @rModelNo) OR (@rModelNo = '')) 
        AND ((Tas.CategoryId = @rCategoryId) OR (@rCategoryId = 0))  
        AND ((Tas.LocationId = @rLocationId) OR (@rLocationId = 0))
        AND ((Tas.DepartmentId = @lDepartmentId) OR (@lDepartmentId = 0)) 
         AND  (CONVERT(NVARCHAR(10), DATEADD(DD,(- Tas.MaintenanceAlertPeriod), Tas.NextMaintenanceDate), 111)  <=  CONVERT(NVARCHAR(10), @rFromDate, 111) )  
        AND  (Tas.NextMaintenanceDate  >=  @rFromDate ) 
         AND((Tas.StoreLocationId=@rStoreLocationId) OR @rStoreLocationId=0)
        AND ((Tas.UsageStatusId = @rStatusId) OR (@rStatusId = 0))) AND @rTag = 1 AND Tas.UsageStatusId <> 124  ) 
          OR ((((Tas.Id = @rAssetTag) OR (@rAssetTag = 0)) 
          AND ((Tas.Code = @rCode) OR (@rCode = '')) 
        AND ((Tas.LocationId = @rLocationId) OR (@rLocationId = 0)) 
        AND ((Tas.ModelNumber = @rModelNo) OR (@rModelNo = '')) 
        AND ((Tas.DepartmentId = @lDepartmentId) OR (@lDepartmentId = 0)) 
        AND ((Tas.CategoryId = @rCategoryId) OR (@rCategoryId = 0)) 
        AND ((Tas.LocationId = @rLocationId) OR (@rLocationId = 0))
        AND ((Tas.UsageStatusId = @rStatusId) OR (@rStatusId = 0))
        AND  (CONVERT(NVARCHAR(10), Tas.NextMaintenanceDate, 111)  >=  CONVERT(NVARCHAR(10), @rFromDate, 111) ) 
        AND (Tas.NextMaintenanceDate  <= (@rToDate + 1) )
        AND((Tas.StoreLocationId=@rStoreLocationId) OR (@rStoreLocationId=0))
        AND ((Iscritical = @rIscritical))) AND @rTag = 2 AND Tas.UsageStatusId <> 124 ) 

        ORDER BY  Tas.NextMaintenanceDate  
END
GO
PRINT N'Altering [sAssetManagement].[pRptAssetMissingListGet]...';


GO
ALTER PROCEDURE [sAssetManagement].[pRptAssetMissingListGet]
	@rOrgId [int],
	@rLocationId [int] = 0,
	@rCategoryId [int] = 0,
	@rReasonId [int] = 0,
	@rFromDate [datetime] = '',
	@rToDate [datetime] = '',
	@rStoreLocationId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
BEGIN
      
       
            
            
       SELECT 
                  LOC.Title AS Location,
                  Tas.CODE AS AssetTag,
                  Tas.Title AS AssetDescription,
                  Tas.ModelNumber,
                  STAT.title AS status,
                  Cat.TITLE AS Category,
                  sCommon.fReportDateGet(CAST(@rFromDate AS DATETIME)) AS FromDate,
                  sCommon.fReportDateGet(CAST(@rToDate AS DATETIME)) AS ToDate,
                  RM.Title AS Notes,
                  Cat.Title AS Category,
                  ODM.Title AS DepartmentTitle,
                  AA.CreatedDateTime 
                  
                  
         FROM sAssetManagement.tAssetAudit AA
         INNER JOIN 
         sAssetManagement.tAssetAuditDetail AAD
         ON (AA.Id = AAD.AssetAuditId AND AAD.AssetCheck = 0)
         INNER JOIN
         sAssetManagement.tAssetAdjustmentDetail AAJD
         ON AAJD.AssetAuditDetailId = AAD.Id
         INNER JOIN
         sCommon.tReasonMaster RM
         ON RM.Id = AAJD.ReasonId
         INNER JOIN
         sAssetManagement.tAssetMaster Tas ON AAD.AssetId = Tas.Id
         INNER JOIN  sFixedAsset.tCategoryMaster Cat
         ON TAS.CATEGORYID = CAT.ID
         --INNER JOIN (SELECT DISTINCT DepartmentId, DepartmentTitle FROM sAssetManagement.vExtAssetDepartment) AD
         --ON AD.DepartmentId = Tas.DepartmentID
          	INNER JOIN sSetup.tDepartmentMaster ODM
	    ON ODM.Id = Tas.DepartmentID
         INNER JOIN  sCommon.tStatusMaster STAT
         ON STAT.ID =  Tas.UsageStatusId 
         INNER JOIN  sFixedAsset.VextLocationMaster LOC
         ON LOC.ID = TAS.LocationId
         
         WHERE 
         AA.OrgId = @rOrgId 
         AND ((AA.StoreLocationId=@rStoreLocationId) OR(@rStoreLocationId=0))
         AND (sCommon.fReportDateGet(AA.CreatedDateTime) BETWEEN  sCommon.fReportDateGet(@rFromDate)  AND sCommon.fReportDateGet(@rToDate) 
         AND (TAS.LocationId = @rLocationId) OR (@rLocationId = 0))   
         AND ((AA.CreatedDateTime >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
		AND ((AA.CreatedDateTime < (@rToDate+1)) OR (ISNULL(@rToDate,'') = ''))     
		AND ((Tas.CategoryId = @rCategoryId) OR (@rCategoryId = 0))
		 AND ((RM.Id = @rReasonId) OR (@rReasonId = 0))
         --AND ((sCommon.fReportDateGet(AA.CreatedDateTime) BETWEEN sCommon.fReportDateGet(@rFromDate) AND sCommon.fReportDateGet(@rToDate)) AND ((Tas.CategoryId = @rCategoryId) OR (@rCategoryId = 0)))
         --AND ((sCommon.fReportDateGet(AA.CreatedDateTime) BETWEEN sCommon.fReportDateGet(@rFromDate) AND sCommon.fReportDateGet(@rToDate)) AND ((RM.Id = @rReasonId) OR (@rReasonId = 0)))
 
        
END
GO
PRINT N'Altering [sAttendance].[pMonthlyRegisterStudentviewGet]...';


GO
ALTER PROCEDURE [sAttendance].[pMonthlyRegisterStudentviewGet]
	 	 
	 	 @rBatchId int,
	 	 @rAcademicId bigint,
	 	 @rAttendanceTypeId tinyint
	 	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
declare @lAttedanceGrid nvarchar(max)=''
	Select 
	@lAttedanceGrid = @lAttedanceGrid + '<tr>
	<td align="left" scope="col">' + Isnull(MY.MonthTitle,'')  + '</td>
	<td align="left" scope="col">' +convert(varchar, isnull( MY.YearNumber,0))+ '</td>
	<td align="left" scope="col">' + convert(varchar,isnull(MR.AttendanceCount,0)) + '</td>
	<td align="left" scope="col">' + convert(varchar,isnull(MR.PresentCount,0)) + '</td>
	<td align="left" scope="col">' + convert(varchar,isnull(MR.AbsentCount,0)) + '</td>
	<td align="left" scope="col">' + convert(varchar,isnull(MR.AveragePresence,0)) + '</td>
	<td align="left" scope="col">' + convert(varchar,isnull(MR.AbsentDays,0),103) + '</td>
	<tr>'
		
	From sStudent.vStudentName SN 
	INNER JOIN sSetup.fMonthYearForBatchGET(@rBatchId) AS MY ON MY.BatchId=SN.BatchId AND SN.AcademicId=@rAcademicId 
	LEFT JOIN sAttendance.tMonthlyRegister MR ON MR.AcademicId=SN.AcademicId 
		AND MR.AttendanceTypeId=@rAttendanceTypeId
		AND MR.ForMonth=MY.MonthNumber AND MR.ForYear=MY.YearNumber
	WHERE
		SN.AcademicId=@rAcademicId
		SELECT  isnull(@lAttedanceGrid ,'') AS AttedanceGrid
END
GO
PRINT N'Altering [sBiometric].[pTimeSheetListGet]...';


GO


ALTER PROCEDURE [sBiometric].[pTimeSheetListGet]
	 @rEmployeeId bigint=0,
	 @rFromDate Date,
	 @rToDate Date,
	 @rStatus nvarchar(10) = '0'

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	CREATE TABLE #TempMonthTrans (
	Id int Identity,
	EmployeeId bigint,	
	Attn_Date DateTime,
	PresentStatus nvarchar(5),
	FirstIn nvarchar(20),
	LastOut nvarchar(20),
	OverTime nvarchar(20),
	LateBy nvarchar(20),
	Duration nvarchar(20),	
	EarlyBy nvarchar(20)
	
	)
	INSERT INTO #TempMonthTrans
	
	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 01) as datetime),D01,D01_IN,D01_OUT,D01_O,D01_L,D01_T,D01_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	IF  Month(@rFromDate) <> 2 or (((YEAR(@rFromDate) % 4 = 0 AND YEAR(@rFromDate) % 100 <> 0) OR YEAR(@rFromDate) % 400 = 0 And Month(@rFromDate)  =2)) 
	BEGIN
		INSERT INTO #TempMonthTrans
	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 29) as datetime),D29,D29_IN,D29_OUT,D29_O,D29_L,D29_T,D29_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
	END
	
	IF Month(@rFromDate) <> 2
	BEGIN
	INSERT INTO #TempMonthTrans
	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 30) as datetime),D30,D30_IN,D30_OUT,D30_O,D30_L,D30_T,D30_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
	END
	
	IF Month(@rFromDate) NOT IN (2,4,6,9,11)
	BEGIN
	INSERT INTO #TempMonthTrans
	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 31) as datetime),D31,D31_IN,D31_OUT,D31_O,D31_L,D31_T,D31_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
	END
	
	SELECT TM.*,MT.Tot_Attn + Tot_WeekOff + Tot_Holiday  AS TotalPresent,Tot_Abs AS TotalAbsent,Tot_WeekOff AS TotalWeekOff,
	Tot_Holiday AS Totalholiday,Tot_Leave AS TotalLeave,EM.FirstName + ' ' + EM.LastName As ShortName,EM.Code as EmpCode , [sBiometric].[fEmployeeLeaveTypeGet] (TM.ATTN_DATE,TM.EmployeeId) AS LeaveStatus , [sBiometric].[fEmployeeTravelGet](TM.ATTN_DATE,TM.EmployeeId) AS EmployeeTravel
	FROM #TempMonthTrans TM 
	INNER JOIN sBiometric.tMonthTrans MT ON MT.EmployeeId=TM.EmployeeId
	INNER JOIN sHRM.tEmployeeMaster EM ON EM.Id=TM.EmployeeId
	WHERE 
	TM.ATTN_DATE >= @rFromDate AND TM.ATTN_DATE <=@rToDate 	
	AND (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND MT.Attn_dt=cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime)
	AND (PresentStatus = @rStatus OR @rStatus='0')
	Order By TM.EmployeeId,TM.Attn_Date
END
GO
PRINT N'Altering [sCertificate].[pRptCharacterCertificateGet]...';


GO



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

DECLARE @lConfigValue nvarchar(50)

DECLARE @lIsDisplayImageHeader bit=0

SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 180 AND SourceTypeId = 1016 AND SourceId = @rOrgId
	
	IF (@lConfigValue IS NULL) OR (@lConfigValue = 'Default')
	BEGIN
	SET @lIsOnPrePrinted = 0
	SET @lIsDisplayImageHeader = 0
	END
	ELSE IF (@lConfigValue = 'Blank')
	BEGIN
	SET @lIsOnPrePrinted = 1
	SET @lIsDisplayImageHeader = 0
	END
	ELSE IF (@lConfigValue = 'Image')
	BEGIN
	SET @lIsOnPrePrinted = 0
	SET @lIsDisplayImageHeader = 1
	END
	
	--SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 158 AND SourceTypeId = 1016 AND SourceId = @rOrgId
	
	--IF (@lConfigValue IS NULL) OR (@lConfigValue = 'False')
	--SET @lIsDisplayImageHeader = 0
	--ELSE
	--SET @lIsDisplayImageHeader = 1	
	
	SELECT 
			@rBuilder1 AS Builder1,
		    @rBuilder2 AS Builder2,
			C.Id,
			C.AcademicId,
			SM.Code,
			SM.FirstName+' '+SM.MiddleName+' '+SM.LastName AS Name,
			CM.DisplayTitle+' - '+DM.DisplayTitle AS Class,
			BM.Title AS Batch,
			SO.DateOfBirth,
			ISNULL(SO.BirthDateInWord,'') AS DOBInWords,
			ISNULL(SO.BirthPlace,'') AS BirthPlace,
			ISNULL(SO.BirthTaluka,'') AS Taluka,
			ISNULL(SO.BirthDistrict,'')	AS District,		
			C.characterDate,
			C.Number,
			ISNULL(SO.FamilyCast,'') AS Caste,
			ISNULL(SO.FamilySubCast,'') AS SubCaste,
			ISNULL(OM.CityName,'') AS City,
			ISNULL(OM.StateName,'') AS CityState,
			SO.GenderId,
			SI.StudentPhoto,
			OM.OrgLogo,
			OM.Title AS OrgName,
			OM.StateName+' '+OM.StreetTwo+' '+OM.StreetThree AS OrgAddress,
			OM.PhoneNo,
			SM.StatusId,
			A.RollNo,
			DM.OrderIndex AS DivisionOrder,
			OM.ReportOrgTitle,
			OM.SmallAddress1,
			OM.SmallAddress2,
			OM.RegistrationDetail,
			@lIsOnPrePrinted AS IsOnPrePrinted,
			@lIsDisplayImageHeader AS IsDisplayImageHeader,
			OI.CertificateHeaderA4  ,
			SA.AdmissionDate,
			SF.FatherName
	FROM 
			sCertificate.tCharacter C
			INNER JOIN sStudent.tAcademic A ON C.AcademicId=A.Id
			LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=A.StudentId
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId
			INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
			INNER JOIN sSetup.tDivisionMaster DM ON A.DivisionId = DM.Id  
			INNER JOIN sSetup.tClassMaster CM ON CM.Id= DM.ClassId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id=A.BatchId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId
			LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = OM.Id
			LEFT JOIN sStudent.tStudentAdmission SA ON SA.StudentId=A.StudentId
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId=A.StudentId
	WHERE  
			A.OrgId=@rOrgId
		AND	A.BatchId = @rBatchId 
		AND ((A.ClassId=@rClassId) OR (@rClassId=0))
		AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((SM.Code = @rCode) OR (ISNULL(@rCode,'') = ''))
		AND ((SM.FirstName = @rName) OR (ISNULL(@rName,'') = ''))
		AND ((C.Number=@rNumber) OR (@rNumber=''))
		AND ((C.Number >= @rFromNo) OR (@rFromNo=''))
		AND ((C.Number <= @rToNo) OR (@rToNo=''))
		AND ((C.characterDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((C.characterDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		--Group By C.AcademicId,C.Number,SM.Code,SM.FirstName,SM.LastName,SM.MiddleName,CM.DisplayTitle,BM.Title,SO.DateOfBirth,SO.BirthDateInWord,
		--SO.BirthPlace,SO.BirthTaluka,SO.BirthDistrict,C.characterDate,OM.CityName,OM.StateName,SO.FamilyCast,SO.FamilySubCast,SO.GenderId,SI.StudentPhoto,SM.StatusId,OM.OrgLogo,OM.Title,
		--OM.StreetOne,OM.StreetThree,OM.StreetTwo,OM.PhoneNo
	END
GO
PRINT N'Altering [sCertificate].[pRptLeavingCertificateGet]...';


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

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

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


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


GO
ALTER PROCEDURE [sCommon].[pMaxCodeWithPrefixGet]
	 
	 @rPrefixFunctionalityId smallint,
	 @rOrgId smallint,
	 @rDepartmentId int,
	 @rEmployeeTypeId int=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 
BEGIN TRY
	
	DECLARE @lSourceTypeId int
	DECLARE @lOutCode nvarchar(20)
	DECLARE @lPrefix nvarchar(10)
	DECLARE @lNumberLength tinyint
	
	IF @rPrefixFunctionalityId=2007 -- Student
	BEGIN
		SELECT @lSourceTypeId=SourceTypeId FROM sCommon.tPrefixConfig WHERE PrefixFunctionalityId = @rPrefixFunctionalityId AND OrgId =@rOrgId
			IF @lSourceTypeId IS NOT NULL
			BEGIN
				IF @lSourceTypeId = 2021 -- Organization
				BEGIN
					SELECT @lPrefix=Prefix,@lNumberLength=NumberLength FROM sCommon.tPrefixConfig WHERE PrefixFunctionalityId = @rPrefixFunctionalityId AND SourceId = @rOrgId
					SELECT @lOutCode=MAX(Code) FROM sStudent.tStudentMaster WHERE OrgId = @rOrgId
				END
				IF @lSourceTypeId = 2017 -- Department
				BEGIN
					SELECT @lPrefix=Prefix,@lNumberLength=NumberLength FROM sCommon.tPrefixConfig WHERE PrefixFunctionalityId = @rPrefixFunctionalityId AND SourceId = @rDepartmentId
					SELECT @lOutCode=MAX(SM.Code) FROM sStudent.tStudentMaster SM INNER JOIN sStudent.tAcademic A ON A.StudentId = SM.Id
					INNER JOIN sSetup.tClassMaster CM ON CM.Id = A.ClassId WHERE SM.OrgId = @rOrgId AND CM.DepartmentId = @rDepartmentId
				END
				
				IF CHARINDEX(@lPrefix,@lOutCode) > 0
				BEGIN
					SELECT @lOutCode = RIGHT(@lOutCode, LEN(@lOutCode)-LEN(@lPrefix))
					SELECT @lOutCode = (CONVERT(bigint, @lOutCode)+1)
					SELECT @lOutCode = RIGHT(REPLICATE('0', @lNumberLength), @lNumberLength-LEN(@lPrefix)-LEN(@lOutCode))+@lOutCode
					SELECT @lOutCode = @lPrefix + @lOutCode
				END
				ELSE
				BEGIN
					SELECT @lOutCode = 1
					IF @lNumberLength != 0
					BEGIN
						SELECT @lOutCode = RIGHT(REPLICATE('0', @lNumberLength), @lNumberLength-LEN(@lPrefix)-LEN(@lOutCode))+@lOutCode
					END
					SELECT @lOutCode = @lPrefix + @lOutCode
				END
			END
	END
	IF @rPrefixFunctionalityId=2008 -- Employee
	BEGIN
		SELECT @lSourceTypeId=SourceTypeId FROM sCommon.tPrefixConfig WHERE PrefixFunctionalityId = @rPrefixFunctionalityId AND OrgId =@rOrgId
			IF @lSourceTypeId IS NOT NULL
			BEGIN
				IF @lSourceTypeId = 2021 -- Organization
				BEGIN
					SELECT @lPrefix=Prefix,@lNumberLength=NumberLength FROM sCommon.tPrefixConfig WHERE PrefixFunctionalityId = @rPrefixFunctionalityId AND SourceId = @rOrgId
					SELECT @lOutCode=MAX(Code) FROM sHrm.tEmployeeMaster WHERE OrgId = @rOrgId
				END
				
				IF @lSourceTypeId = 2017 -- Department
				BEGIN
					SELECT @lPrefix=Prefix,@lNumberLength=NumberLength FROM sCommon.tPrefixConfig WHERE PrefixFunctionalityId = @rPrefixFunctionalityId AND SourceId = @rDepartmentId
					SELECT @lOutCode=MAX(EM.Code) FROM sHrm.tEmployeeMaster EM INNER JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id = EJD.EmployeeId
					WHERE EM.OrgId = @rOrgId AND EJD.OrganizationDepartmentId = @rDepartmentId
				END
				
				IF CHARINDEX(@lPrefix,@lOutCode) > 0
				BEGIN
					SELECT @lOutCode = RIGHT(@lOutCode, LEN(@lOutCode)-LEN(@lPrefix))
					SELECT @lOutCode = (CONVERT(bigint, @lOutCode)+1)
					SELECT @lOutCode = RIGHT(REPLICATE('0', @lNumberLength), @lNumberLength-LEN(@lPrefix)-LEN(@lOutCode))+@lOutCode
					SELECT @lOutCode = @lPrefix + @lOutCode
				END
				ELSE
				BEGIN
					SELECT @lOutCode = 1
					IF @lNumberLength != 0
					BEGIN
						SELECT @lOutCode = RIGHT(REPLICATE('0', @lNumberLength), @lNumberLength-LEN(@lPrefix)-LEN(@lOutCode))+@lOutCode
					END
					SELECT @lOutCode = @lPrefix + @lOutCode
				END
			END
	END
	
	IF @rPrefixFunctionalityId=2009 -- Organization
	BEGIN
		DECLARE @lOrgGroupId smallint
		DECLARE @lScopeSourceTypeId smallint
		SELECT @lSourceTypeId=SourceTypeId,@lScopeSourceTypeId=ISNULL(ScopeSourceTypeId,0),@lOrgGroupId=OrgId FROM sCommon.tPrefixConfig WHERE PrefixFunctionalityId = @rPrefixFunctionalityId AND SourceId =@rOrgId
			IF @lSourceTypeId IS NOT NULL
			BEGIN
				IF @lSourceTypeId = 2021 -- Organization
				BEGIN
					IF(@lScopeSourceTypeId=2010)
						BEGIN
							SELECT @lPrefix=Prefix,@lNumberLength=NumberLength FROM sCommon.tPrefixConfig WHERE PrefixFunctionalityId = @rPrefixFunctionalityId AND SourceId = @rOrgId
							SELECT @lOutCode=MAX(SUId) FROM sStudent.tStudentMaster SM
							INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SM.OrgId
							 WHERE OM.OrgGroupId = @lOrgGroupId
						END
					ELSE
						BEGIN
							SELECT @lPrefix=Prefix,@lNumberLength=NumberLength FROM sCommon.tPrefixConfig WHERE PrefixFunctionalityId = @rPrefixFunctionalityId AND SourceId = @rOrgId
							SELECT @lOutCode=MAX(SUId) FROM sStudent.tStudentMaster WHERE OrgId = @rOrgId
						END	
				END
				
				IF CHARINDEX(@lPrefix,@lOutCode) > 0
				BEGIN
					SELECT @lOutCode = RIGHT(@lOutCode, LEN(@lOutCode)-LEN(@lPrefix))
					SELECT @lOutCode = (CONVERT(bigint, @lOutCode)+1)
					SELECT @lOutCode = RIGHT(REPLICATE('0', @lNumberLength), @lNumberLength-LEN(@lPrefix)-LEN(@lOutCode))+@lOutCode
					SELECT @lOutCode = @lPrefix + @lOutCode
				END
				ELSE
				BEGIN
					SELECT @lOutCode = 1
					IF @lNumberLength != 0
					BEGIN
						SELECT @lOutCode = RIGHT(REPLICATE('0', @lNumberLength), @lNumberLength-LEN(@lPrefix)-LEN(@lOutCode))+@lOutCode
					END
					SELECT @lOutCode = @lPrefix + @lOutCode
				END
			END
	END
	END TRY
	BEGIN CATCH
	SET @lOutCode = ''
	END CATCH
	SELECT @lOutCode Result
END
GO
PRINT N'Altering [sCommon].[pOrganizationSetupRemove]...';


GO


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

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


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

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

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

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

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

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

DELETE FROM sTimetable.tAssignOrg WHERE OrgId = @rOrgId

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

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

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

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

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

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

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

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

/* -- Date : 05/10/2016 -- */

DELETE FROM sAdmission.tAdmissionInquiryFollowup WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
--DELETE FROM sAssessment.tStaticCCECSGroupMaster WHERE OrgId = @rOrgId
--DELETE FROM sAssessment.tStaticCCECSMaster WHERE OrgId = @rOrgId

/* -- Date : 20/10/2016 -- */

DELETE FROM sAssessment.tOptionalCCECS WHERE CAST(LEFT(AcademicId, 4) AS BIGINT) = @rOrgId

/* -- Date : 24/11/2016 -- */
DELETE FROM sBiometric.tMonthTrans WHERE CAST(LEFT(EmployeeId, 4) AS BIGINT) = @rOrgId

/* -- Date : 23/12/2016 -- */
DELETE FROM sAdmission.tAdmissionFormReceipt WHERE CAST(LEFT(BatchId, 4) AS INT) = @rOrgId
DELETE FROM sAssessment.tCCEExamStatus WHERE CAST(LEFT(BatchId, 4) AS INT) = @rOrgId
DELETE FROM sAttendance.tAttendanceGroup WHERE CAST(LEFT(BatchId, 4) AS INT) = @rOrgId
DELETE FROM sAttendance.tAttendanceGroupStudent WHERE CAST(LEFT(AcademicId, 4) AS BIGINT) = @rOrgId
DELETE FROM sFee.tAccountPosting WHERE CAST(LEFT(AccountId, 4) AS INT) = @rOrgId
DELETE FROM sHrm.tLeaveBalanceAddRequest WHERE CAST(LEFT(BatchId, 4) AS INT) = @rOrgId

/* -- Date : 14/02/2017 -- */

DELETE FROM sCRM.tChannelPartnerMaster WHERE OrgId = @rOrgId
DELETE FROM sCRM.tInstituteGroupMaster WHERE OrgId = @rOrgId
DELETE FROM sCRM.tInstituteMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sSetup.tOrganizationOtherDetail WHERE OrgId = @rOrgId

DELETE FROM sAppraisal.tConduct WHERE CAST(LEFT(BatchId, 4) AS INT) = @rOrgId
DELETE FROM sAssessment.tAllBatchClassGroup WHERE OrgId= @rOrgId
DELETE FROM sAssessment.tAllBatchResult WHERE CAST(LEFT(StudentId, 4) AS BIGINT) = @rOrgId
DELETE FROM sAssessment.tAllBatchSubject WHERE OrgId= @rOrgId
DELETE FROM sHrm.tEmployeeTravel WHERE OrgId= @rOrgId


DELETE FROM sLoan.tLoanDetail WHERE OrgId= @rOrgId
DELETE FROM sLoan.tLoanEMI WHERE CAST(LEFT(LoanDetailId, 4) AS BIGINT) = @rOrgId
DELETE FROM sLoan.tLoanPayrollMapping WHERE OrgId= @rOrgId
DELETE FROM sLoan.tLoanTypeMaster WHERE OrgId= @rOrgId
DELETE FROM sPayroll.tPayrollCustomSearch WHERE OrgId= @rOrgId
DELETE FROM sErp.tChannelMaster WHERE OrgId = @rOrgId

DELETE FROM sAccounting.tExpenseDetail WHERE CAST(LEFT(ExpenseId, 4) AS int) = @rOrgId
DELETE FROM sAccounting.tExpenseSubGroupMaster WHERE OrgId= @rOrgId
DELETE FROM sAppraisal.tAppraisalTypeMaster WHERE CAST(LEFT(BatchId, 4) AS int) = @rOrgId
DELETE FROM sAppraisal.tBusinessHeadsRatingStatus WHERE CAST(LEFT(AppraisalTypeId, 4) AS int) = @rOrgId
DELETE FROM sAppraisal.tKPAEmployee WHERE CAST(LEFT(BatchId, 4) AS int) = @rOrgId
DELETE FROM sAppraisal.tKPAEmployeeDetail WHERE CAST(LEFT(KPAEmployeeId, 4) AS bigint) = @rOrgId
DELETE FROM sAppraisal.tKPAEmployeeRating WHERE CAST(LEFT(KPAEmployeeId, 4) AS bigint) = @rOrgId
DELETE FROM sAppraisal.tKPAEmployeeRatingDetail WHERE CAST(LEFT(KPAEmployeeRatingId, 4) AS bigint) = @rOrgId
DELETE FROM sPoliciesForms.tFolderFile WHERE OrgId = @rOrgId
DELETE FROM sPoliciesForms.tFolderFilePermission WHERE CAST(LEFT(FolderFileId, 4) AS int) = @rOrgId


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

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

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

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


GO

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

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




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

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

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


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

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

DELETE FROM sStudent.tCustomTagMaster WHERE OrgGroupId = @rOrgGroupId

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

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

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

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

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

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

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

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

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

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

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

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

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

DELETE FROM sErp.tCustomerMaster WHERE OrgGroupId = @rOrgGroupId

/* -- Date : 05/10/2016 -- */
DELETE FROM sHostel.tAttendanceRegister WHERE CAST(LEFT(HostelId, 4) AS INT) = @rOrgGroupId
DELETE FROM sRecruitment.tCandidateCommunications WHERE CAST(LEFT(CandidateId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sRecruitment.tCandidateImages WHERE CAST(LEFT(CandidateId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sRecruitment.tCandidateMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sRecruitment.tCandidatePreviousEmployment WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sRecruitment.tCandidateQualification WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sRecruitment.tCandidateVacancyCriteriaScore WHERE CAST(LEFT(CandidateId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sRecruitment.tInterviewCriteria WHERE CAST(LEFT(VacancyId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sRecruitment.tRecruitmentStatusLog WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sRecruitment.tVacancy WHERE OrgGroupId = @rOrgGroupId

/* -- Date : 24/11/2016 -- */

DELETE FROM siTax.tAssessmentYear WHERE OrgGroupId = @rOrgGroupId
DELETE FROM siTax.tForm16 WHERE OrgGroupId = @rOrgGroupId
DELETE FROM siTax.tForm16Detail WHERE CAST(LEFT(Form16Id, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM siTax.tIncomeTaxChallan WHERE CAST(LEFT(AssesmentYearId, 4) AS INT) = @rOrgGroupId
DELETE FROM siTax.tIncomeTaxGroup WHERE OrgGroupId = @rOrgGroupId
DELETE FROM siTax.tIncomeTaxSlab WHERE OrgGroupId = @rOrgGroupId
DELETE FROM siTax.tIncomeTaxSubGroup WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sSetup.tBatchGroupMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sActivity.tPlacementCompanyMaster WHERE OrgGroupId = @rOrgGroupId


DELETE FROM sAppraisal.tConductTypeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sErp.tCustomerActivationLog WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sSecurity.tIpPolicy WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sSecurity.tIpPolicyDetail WHERE  CAST(LEFT(IpPolicyId, 4) AS int) = @rOrgGroupId
DELETE FROM sSecurity.tTimePolicy WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sSecurity.tUserPolicy WHERE  CAST(LEFT(TimePolicyId, 4) AS int) = @rOrgGroupId


DELETE FROM sAppraisal.tKPATemplateDetail WHERE CAST(LEFT(KPATemplateId, 4) AS int) = @rOrgGroupId
DELETE FROM sAppraisal.tKPATemplateMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sOp.tGatewayProduct WHERE CAST(LEFT(GatewayConfigurationId, 4) AS int) = @rOrgGroupId
DELETE FROM sOp.tGatewayProductReceiptBookMapping WHERE CAST(LEFT(ReceiptBookId, 4) AS int) = @rOrgGroupId
DELETE FROM sProcurement.tSstockIssueTypeMaster WHERE OrgGroupId = @rOrgGroupId


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

	-- special case will come orgwise and orggroupwise

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



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

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


GO
ALTER PROCEDURE [sCommon].[pPrefixConfigAdd]
	
	@rPrefixFunctionalityId int,
	@rSourceTypeId int,
	@rSourceId bigint,
	@rPrefix nvarchar(10),
	@rNumberLength int,
	@rOrgId smallint,
	@rScopeSourceTypeId smallint = 0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	BEGIN TRANSACTION	
	
	INSERT INTO sCommon.tPrefixConfig
		(
			PrefixFunctionalityId,
			SourceTypeId,
			SourceId,
			Prefix,
			NumberLength,
			OrgId,
			ScopeSourceTypeId
		)
	VALUES
		(
			@rPrefixFunctionalityId,
			@rSourceTypeId,
			@rSourceId,
			@rPrefix,
			@rNumberLength,
			@rOrgId,
			@rScopeSourceTypeId
		)
	
	SELECT 1 AS Result
	
	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sCommon].[pPrefixConfigGet]...';


GO
ALTER PROCEDURE [sCommon].[pPrefixConfigGet]
	
	@rOrgId int,
	@rPrefixFunctionalityId int,
	@rSourceTypeId int,
	@rOrgGroupId int = 0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	  
	  IF @rPrefixFunctionalityId = 2007 -- Student
	  BEGIN
		IF @rSourceTypeId = 2021 -- Organization
		BEGIN
			 SELECT 
				SourceId,
				ISNULL(Prefix,'') AS Prefix,
				ISNULL(NumberLength,0) AS NumberLength
			 FROM 
			 sCommon.tPrefixConfig
			 WHERE SourceId = @rOrgId AND SourceTypeId = 2021 AND PrefixFunctionalityId = @rPrefixFunctionalityId
		END
		
		IF @rSourceTypeId = 2017 -- Department
		BEGIN
			 SELECT 
				DM.Title AS DepartmentName,
				DM.Id AS DepartmentId,
				ISNULL(PC.Prefix,'') AS Prefix,
				ISNULL(PC.NumberLength,0) AS NumberLength
			 FROM 
			 sSetup.tDepartmentMaster DM
			 LEFT JOIN sCommon.tPrefixConfig PC ON DM.Id = PC.SourceId AND PC.SourceTypeId = 2017 AND PrefixFunctionalityId = @rPrefixFunctionalityId
			 WHERE DM.OrgId = @rOrgId
		END
	  END
	  
	  IF @rPrefixFunctionalityId = 2008 -- Employee
	  BEGIN
	    IF @rSourceTypeId = 2021 -- Organization
		BEGIN
			 SELECT 
				SourceId,
				ISNULL(Prefix,'') AS Prefix,
				ISNULL(NumberLength,0) AS NumberLength
			 FROM 
			 sCommon.tPrefixConfig
			WHERE SourceId = @rOrgId AND SourceTypeId = 2021 AND PrefixFunctionalityId = @rPrefixFunctionalityId
		END
		
		IF @rSourceTypeId = 2017 -- Department
		BEGIN
			 SELECT 
				DM.Title AS DepartmentName,
				DM.Id AS DepartmentId,
				ISNULL(PC.Prefix,'') AS Prefix,
				ISNULL(PC.NumberLength,0) AS NumberLength
			 FROM 
			 sSetup.tDepartmentMaster DM
			 LEFT JOIN sCommon.tPrefixConfig PC ON DM.Id = PC.SourceId AND PC.SourceTypeId = 2017 AND PrefixFunctionalityId = @rPrefixFunctionalityId
			 WHERE DM.OrgId = @rOrgId
		END
	  
		--IF @rSourceTypeId = 2025 -- Employee Type
		--BEGIN
		--	 SELECT 
		--		ETM.Title AS EmployeeTypeName,
		--		ETM.Id AS EmployeeTypeId,
		--		ISNULL(PC.Prefix,'') AS Prefix,
		--		ISNULL(PC.NumberLength,0) AS NumberLength
		--	 FROM 
		--	 sHrm.tEmployeeTypeMaster ETM
		--	 LEFT JOIN sCommon.tPrefixConfig PC ON ETM.Id = PC.SourceId AND PC.SourceTypeId = 2025 AND PrefixFunctionalityId = @rPrefixFunctionalityId
		--	 WHERE ETM.OrgId = @rOrgId
		--END
	  END
	  
	  IF @rPrefixFunctionalityId = 2009 -- Organization
	  BEGIN
		IF @rSourceTypeId = 2021 -- Organization
		BEGIN
			 SELECT 
				OM.Title AS OrgName,
				OM.Id AS OrgId,
				ISNULL(PC.Prefix,'') AS Prefix,
				ISNULL(PC.NumberLength,0) AS NumberLength,
				ISNULL(PC.ScopeSourceTypeId,0) AS ScopeSourceTypeId
			 FROM 
			 sSetup.tOrganizationMaster OM
			 LEFT JOIN sCommon.tPrefixConfig PC ON OM.Id = PC.SourceId AND PC.SourceTypeId = 2021 AND PrefixFunctionalityId = @rPrefixFunctionalityId
			 WHERE OM.OrgGroupId = @rOrgGroupId
		END
	  END
END
GO
PRINT N'Altering [sCommunication].[pBlogGet]...';


GO
ALTER PROCEDURE [sCommunication].[pBlogGet]
	 
	 @rId bigint,
	 @rOrgGroupBatchId int,
	 @rTitle nvarchar(200),
	 @rCreatedUserId bigint,
	 @rIsSearch bit = 1,
	 @rOrgId smallint,
	 @rSyncedBlogId bigint=0,
	 @rCreatedDateTime Date=''
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 
	 IF @rIsSearch = 1
		BEGIN
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		END
	
	SELECT 
			Distinct(B.Id),
			B.OrgGroupBatchId,
		    OGBM.Title AS OrgGroupBatch,
		    B.Title,
		    B.Remark,
		    B.IsPublish,
		    U.DisplayTitle AS BlogCreatedUserName,
		    B.CreatedDateTime AS BlogCreatedDateTime,		 
		    (SELECT  ISNULL(Count(1),0) FROM sCommunication.tBlogFavorite BF WHERE BF.BlogId = B.Id) AS TotalBlogFavorite,
		    (SELECT ISNULL( Count(1),0) FROM sCommunication.tBlogComment BC WHERE BC.BlogId = B.Id) AS TotalBlogComment
		    
  FROM 
            sCommunication.tBlog B
            INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=B.OrgGroupBatchId
            INNER JOIN sSecurity.tUser U ON U.Id=B.CreatedUserId
			INNER JOIN sCommunication.tBlogScope BS ON BS.BlogId=B.Id AND ((BS.SourceId=@rOrgId)OR (@rOrgId=0))
  WHERE 
  
		((B.Id = @rId) OR (@rId = 0))
	AND ((B.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
	AND ((B.CreatedUserId=@rCreatedUserId) OR (@rCreatedUserId=0))
	AND ((B.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	AND ( B.Id > @rSyncedBlogId OR @rSyncedBlogId = 0)
	AND ((convert(date,B.CreatedDateTime) = convert(date,@rCreatedDateTime)) OR (ISNULL(@rCreatedDateTime,'') = ''))
END
GO
PRINT N'Altering [sCommunication].[pCircularListGet]...';


GO
ALTER PROCEDURE [sCommunication].[pCircularListGet]
	 
	 @rOrgGroupBatchId int,
	 @rUserId bigint,
	 @rUserSourceId bigint,
	 @rUserSourceTypeId int,
	 @rSyncedCircularId bigint = 0,
	 @rStartDate date=''
	 
	 	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	
	 DECLARE @lAcademicId bigint,@lStudentId bigint,@lClassId int,@lDivisionId int,@lOrgId int,@lDepartmentId int,@lEmployeeId bigint

	
	if @rUserSourceTypeId   = 95 -- For Employee Login
	
	BEGIN
	
		--DECLARE @lDepartmentId int,@lOrgId int,@lDepartmentId int
		
		SELECT @lDepartmentId=EJD.OrganizationDepartmentId,@lOrgId = EM.OrgId,@lEmployeeId = EM.Id FROM sHrm.tEmployeeMaster EM INNER JOIN sHrm.tEmployeeJobDetail EJD
			 ON EJD.EmployeeId = EM.Id WHERE EM.Id=@rUserSourceId
		
	SELECT 	
			C.Id as CircularId,
			C.Title,
			C.Remark,
			C.StartDate,
			ISNULL(CV.UserId,0) AS UserId,
			U.DisplayTitle as CreatedUserName,
			CTM.HighlightColor,
			CTM.Title AS CircularTypeTitle,
			C.OrgGroupId
			  
	 FROM 
            sCommunication.tCircular C 
            INNER JOIN sCommunication.tCircularTypeMaster CTM
				ON CTM.Id=C.CircularTypeId
            LEFT JOIN sCommunication.tCircularView CV ON CV.CircularId=C.Id AND UserId=@rUserId           
            INNER JOIN (SELECT CS.CircularId FROM sCommunication.tCircularScope CS
             WHERE ((CS.SourceTypeId = 2021 AND CS.SourceId =@lOrgId) OR
            (CS.SourceTypeId = 2017 AND CS.SourceId =@lDepartmentId) OR
            (CS.SourceTypeId = 95 AND CS.SourceId =@lEmployeeId))
              AND (CS.CircularId > @rSyncedCircularId OR @rSyncedCircularId = 0)) D
				ON D.CircularId= C.Id
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=C.OrgGroupBatchId AND OGBM.Id=@rOrgGroupBatchId
            INNER JOIN sSecurity.tUser U ON U.Id=C.CreatedUserId
            WHERE ( c.Id > @rSyncedCircularId OR @rSyncedCircularId = 0)
            AND C.AssigneeId IN (1,3) 
            AND ((C.StartDate=@rStartDate) OR (isnull(@rStartDate,'')=''))
           	ORDER BY C.StartDate DESC
			
	
 END
 ELSE IF @rUserSourceTypeId   = 2003 -- For Student Login
 BEGIN
 
 
 SELECT @lAcademicId = A.Id,@lStudentId = A.StudentId,@lClassId = A.ClassId, @lDivisionId = A.DivisionId, @lOrgId= A.OrgId, @lDepartmentId=CM.DepartmentId
  FROM sStudent.tAcademic A INNER JOIN sSetup.tBatchMaster BM
	ON A.BatchId = BM.Id 
	AND BM.IsActive = 1 
	INNER JOIN sSetup.tClassMaster CM ON CM.Id = A.ClassId
 WHERE StudentId = @rUserSourceId AND BM.OrgGroupBatchId = @rOrgGroupBatchId
  
 	SELECT 	
			C.Id as CircularId,
			C.Title,
			C.Remark,
			C.StartDate,
			ISNULL(CV.UserId,0) AS UserId,
			U.DisplayTitle as CreatedUserName,
			CTM.HighlightColor,
			CTM.Title AS CircularTypeTitle,
			C.OrgGroupId
	 FROM 
            sCommunication.tCircular C 
            INNER JOIN sCommunication.tCircularTypeMaster CTM
				ON CTM.Id=C.CircularTypeId      
            LEFT JOIN sCommunication.tCircularView CV ON CV.CircularId=C.Id AND UserId=@rUserId
            INNER JOIN (SELECT CS.CircularId FROM sCommunication.tCircularScope CS
            WHERE ((CS.SourceTypeId = 2021 AND CS.SourceId =@lOrgId) OR
            (CS.SourceTypeId = 2017 AND CS.SourceId =@lDepartmentId) OR
            (CS.SourceTypeId = 2016 AND CS.SourceId =@lClassId) OR
            (CS.SourceTypeId = 2005 AND CS.SourceId =@lDivisionId) OR
            (CS.SourceTypeId = 2003 AND CS.SourceId =@lStudentId) OR
            (CS.SourceTypeId = 2001 AND CS.SourceId =@lAcademicId) )
            AND (CS.CircularId > @rSyncedCircularId OR @rSyncedCircularId = 0)) D
				ON D.CircularId= C.Id
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=C.OrgGroupBatchId AND OGBM.Id=@rOrgGroupBatchId
            INNER JOIN sSecurity.tUser U ON U.Id=C.CreatedUserId
            WHERE ( c.Id > @rSyncedCircularId OR @rSyncedCircularId = 0)
            AND C.AssigneeId IN (1,2) 
             AND ((C.StartDate=@rStartDate) OR (isnull(@rStartDate,'')=''))
            ORDER BY C.StartDate DESC

 END
 ELSE
  --For Other Users
 BEGIN
 
 SELECT 	
			C.Id as CircularId,
			C.Title,
			C.Remark,
			C.StartDate,
			ISNULL(CV.UserId,0) AS UserId,
			U.DisplayTitle as CreatedUserName,
			CTM.HighlightColor,
			CTM.Title AS CircularTypeTitle,
			C.OrgGroupId
	 FROM 
            sCommunication.tCircular C     
            INNER JOIN sCommunication.tCircularTypeMaster CTM
				ON CTM.Id=C.CircularTypeId  
            LEFT JOIN sCommunication.tCircularView CV ON CV.CircularId=C.Id AND UserId=@rUserId     
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=C.OrgGroupBatchId AND OGBM.Id=@rOrgGroupBatchId
            INNER JOIN sSecurity.tUser U ON U.Id=C.CreatedUserId
            WHERE ( C.Id > @rSyncedCircularId OR @rSyncedCircularId = 0)
             AND C.AssigneeId IN (1,2,3)
             AND ((C.StartDate=@rStartDate) OR (isnull(@rStartDate,'')=''))
            ORDER BY C.StartDate DESC

 
 	--SELECT 	
		--	C.Id as CircularId,
		--	C.Title,
		--	C.Remark,
		--	C.StartDate,
		--	CV.UserId,
		--	U.DisplayTitle as CreatedUserName	    
	 --FROM 
  --          sCommunication.tCircular C       
  --          LEFT JOIN sCommunication.tCircularView CV ON CV.CircularId=C.Id AND UserId=@rUserId     
  --          INNER JOIN sCommunication.tCircularScope CS ON CS.CircularId=C.Id 
  --          INNER JOIN ( SELECT A.DivisionId FROM sStudent.tAcademic A            
  --           WHERE A.StudentId = @rUserSourceId ) D
  --          ON D.DivisionId =  CS.SourceId AND CS.SourceTypeId = 2005
  --          INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=C.OrgGroupBatchId AND OGBM.Id=@rOrgGroupBatchId
  --          INNER JOIN sSecurity.tUser U ON U.Id=C.CreatedUserId
  --          WHERE ( C.Id > @rSyncedCircularId OR @rSyncedCircularId = 0)
  --          Order by C.CreatedDateTime DESC


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


GO

ALTER PROCEDURE [sCommunication].[pPollGet]
	 @rId bigint = 0,
	 @rOrgGroupBatchId int,
	 @rCreatedUserId bigint,
	 @rSourceTypeId smallint,
	 @rCreatedDateTime datetime=''
	 
	 	 
	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,
			ISNULL(PR.CreatedUserId,0) AS PollResultUserId,
			(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=2017 
         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
         LEFT JOIN sCommunication.tPollResult PR ON P.Id = PR.PollId AND  PR.CreatedUSerId = @rCreatedUserId
  WHERE 
  
      ((P.Id = @rId) OR (@rId = 0))
	AND ((P.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	AND ((convert(date,P.CreatedDateTime)=CONVERT(date,@rCreatedDateTime)) OR (ISNull(@rCreatedDateTime,'')=''))
	
	--UNION
	
	--SELECT 
	
	--		P.Id as PollId,
	--		P.Title AS PollTitle,
	--		P.Remark AS PollRemark,
	--		P.IsOwnAnswer,
	--		P.IsOpen,
	--		P.CreatedDateTime AS PollCreatedDateTime,
	--		ISNULL(PR.CreatedUserId,0) AS PollResultUserId,
	--		(SELECT  ISNULL(Count(1),0) FROM sCommunication.tPollResult PR WHERE PR.PollId=P.Id) AS TotalPollVote
 -- FROM 
 --           sCommunication.tPoll P
 --           LEFT JOIN sCommunication.tPollResult PR ON P.Id = PR.PollId AND  PR.CreatedUSerId = @rCreatedUserId
 -- WHERE 
  
 --     ((P.Id = @rId) OR (@rId = 0))
 --   AND ((P.CreatedUserId = @rCreatedUserId) OR (@rCreatedUserId = 0))
	--AND ((P.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	
	
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,
			ISNULL(PR.CreatedUserId,0) AS PollResultUserId,
			(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=2005
         INNER JOIN sStudent.vStudentAcademic SA ON SA.DivisionId=PM.SourceId AND SA.IsActiveBatch = 1
         INNER JOIN sSecurity.tUser U ON U.SourceId=SA.StudentId AND U.SourceTypeId=@rSourceTypeId AND U.Id=@rCreatedUserId
         LEFT JOIN sCommunication.tPollResult PR ON P.Id = PR.PollId AND  PR.CreatedUSerId = @rCreatedUserId
         
  WHERE 
  
      ((P.Id = @rId) OR (@rId = 0))
	AND ((P.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	AND ((convert(date,P.CreatedDateTime)=CONVERT(date,@rCreatedDateTime)) OR (ISNull(@rCreatedDateTime,'')=''))
	
	
	--UNION
	
	--SELECT 
	
	--		P.Id as PollId,
	--		P.Title AS PollTitle,
	--		P.Remark AS PollRemark,
	--		P.IsOwnAnswer,
	--		P.IsOpen,
	--		P.CreatedDateTime AS PollCreatedDateTime,
	--		ISNULL(PR.CreatedUserId,0) AS PollResultUserId,
	--		(SELECT  ISNULL(Count(1),0) FROM sCommunication.tPollResult PR WHERE PR.PollId=P.Id) AS TotalPollVote
 -- FROM 
 --           sCommunication.tPoll P
 --            LEFT JOIN sCommunication.tPollResult PR ON P.Id = PR.PollId AND  PR.CreatedUSerId = @rCreatedUserId
 -- WHERE 
  
 --     ((P.Id = @rId) OR (@rId = 0))
 --    AND ((P.CreatedUserId = @rCreatedUserId) OR (@rCreatedUserId = 0))
	--AND ((P.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	
	
END

ELSE 

BEGIN
	--SELECT 
	
	--		P.Id as PollId,
	--		P.Title AS PollTitle,
	--		P.Remark AS PollRemark,
	--		P.IsOwnAnswer,
	--		P.IsOpen,
	--		P.CreatedDateTime AS PollCreatedDateTime,
	--		ISNULL(PR.CreatedUserId,0) AS PollResultUserId,
	--		(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=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
 --         LEFT JOIN sCommunication.tPollResult PR ON P.Id = PR.PollId AND  PR.CreatedUSerId = @rCreatedUserId
 -- WHERE 
  
 --     ((P.Id = @rId) OR (@rId = 0))
	--AND ((P.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	
	
	--UNION
	
	SELECT 
	
			P.Id as PollId,
			P.Title AS PollTitle,
			P.Remark AS PollRemark,
			P.IsOwnAnswer,
			P.IsOpen,
			P.CreatedDateTime AS PollCreatedDateTime,
			ISNULL(PR.CreatedUserId,0) AS PollResultUserId,
			(SELECT  ISNULL(Count(1),0) FROM sCommunication.tPollResult PR WHERE PR.PollId=P.Id) AS TotalPollVote
  FROM 
            sCommunication.tPoll P
            LEFT JOIN sCommunication.tPollResult PR ON P.Id = PR.PollId AND  PR.CreatedUSerId = @rCreatedUserId
  WHERE 
  
      ((P.Id = @rId) OR (@rId = 0))
    AND ((P.CreatedUserId = @rCreatedUserId) OR (@rCreatedUserId = 0))
	AND ((P.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	AND ((convert(date,P.CreatedDateTime)=CONVERT(date,@rCreatedDateTime)) OR (ISNull(@rCreatedDateTime,'')=''))
	
END


END
GO
PRINT N'Altering [sErp].[pCustomerMasterAdd]...';


GO
ALTER PROCEDURE [sErp].[pCustomerMasterAdd]  	 	 
	   @rId int, 
	   @rOrgId smallint, 
	   @rOrgGroupId smallint, 
	   @rCRMLicenceId int, 
	   @rTitle nvarchar(200), 
	   @rShortTitle nvarchar(100), 
	   @rStreetOne nvarchar(50), 
	   @rStreetTwo nvarchar(50), 
	   @rStreetThree nvarchar(50), 
	   @rCityName nvarchar(100), 
	   @rZipCode nvarchar(20),	
	   @rHomePage nvarchar(100), 
	   @rPhoneNo nvarchar(50), 
       @rMobileNo nvarchar(50), 
       @rContactPerson nvarchar(100),
       @rCreatedUserId bigint,       
       --@rUpdatedUserId bigint, 
       @rIsObsolete bit,
       @rCustomerStatusId tinyint,
       @rChannelId int, 
       @rInstallationTypeId tinyint,
	   @rStateId int, 
	   @rCountryId int, 
	 @rDomain  nvarchar(200),
	  @rDb nvarchar(100), 
	  @rInstallationDate date
       
       
   
    	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
--BEGIN
--	BEGIN TRY
	
	IF(@rId = 0)	
	BEGIN
		If Exists(select Id from sErp.tCustomerMaster where OrgGroupId=@rOrgGroupId AND OrgId=@rOrgId)
			BEGIN
			select -104 as Result
			RETURN
		END 
	
		If Exists(select Id from sErp.tCustomerMaster where Title=@rTitle AND OrgId=@rOrgId)
			BEGIN
			select -103 as Result
			RETURN
		END 
		If Exists(select Id from sErp.tCustomerMaster where ShortTitle=@rShortTitle AND OrgId=@rOrgId)
			BEGIN
			select -102 as Result
			RETURN
		END 
		If Exists(select Id from sErp.tCustomerMaster where CRMLicenceId=@rCRMLicenceId AND OrgId=@rOrgId)
			BEGIN
			select -101 as Result
			RETURN
		END 
			If Exists(select Id from sErp.tCustomerMaster where Domain=@rDomain AND OrgId=@rOrgId AND @rInstallationTypeId=1 OR @rInstallationTypeId=2)
			BEGIN
			select -105 as Result
			RETURN
		END 
		If Exists(select Id from sErp.tCustomerMaster where Db=@rDb AND OrgId=@rOrgId)
			BEGIN
			select -106 as Result
			RETURN
		END 
		
	END
	ELSE
	BEGIN
		If Exists(select Id from sErp.tCustomerMaster where OrgGroupId=@rOrgGroupId AND OrgId=@rOrgId AND Id<>@rId)
		Begin
			select -104 as Result
			RETURN
		End
		If  Exists(select Id from sErp.tCustomerMaster where Title=@rTitle  AND OrgId=@rOrgId AND Id<>@rId)
		Begin
			select -103 as Result
			RETURN
		End
        If Exists(select Id from sErp.tCustomerMaster where ShortTitle=@rShortTitle AND OrgId=@rOrgId AND Id<>@rId)
			BEGIN
			select -102 as Result
			RETURN
		END 
		If Exists(select Id from sErp.tCustomerMaster where CRMLicenceId=@rCRMLicenceId AND OrgId=@rOrgId AND Id<>@rId)
			BEGIN
			select -101 as Result
			RETURN
		END 
		If Exists(select Id from sErp.tCustomerMaster where Domain=@rDomain AND OrgId=@rOrgId AND Id<>@rId AND @rInstallationTypeId=1 AND @rInstallationTypeId=2)
			BEGIN
			select -105 as Result
			RETURN
		END 
		If Exists(select Id from sErp.tCustomerMaster where Db=@rDb AND OrgId=@rOrgId AND Id<>@rId)
			BEGIN
			select -106 as Result
			RETURN
		END 
	END
	
	 --BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sErp.tCustomerMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sErp.tCustomerMaster
		(
			 Id ,
			 OrgId ,
			 OrgGroupId ,
			 CRMLicenceId ,
			 Title ,
			 ShortTitle ,
			 StreetOne,
			 StreetTwo ,
			 StreetThree ,
		     CityName ,
			 ZipCode,
			 HomePage ,
	         PhoneNo ,
			 MobileNo ,
			 ContactPerson ,
			 CreatedUserId , 
			 CreatedDateTime, 
			 UpdatedUserId, 
			 UpdatedDateTime,
			 IsObsolete,
			 CustomerStatusId ,
			 ChannelId ,
			 InstallationTypeId,
			 StateId ,
			 CountryId ,
			 Domain ,
			 Db ,
			 InstallationDate 
        )
	VALUES
		(
			 @lNextNumber , 
			 @rOrgId,
			 @rOrgGroupId , 
			 @rCRMLicenceId , 
			 @rTitle , 
			 @rShortTitle, 
			 @rStreetOne , 
			 @rStreetTwo , 
		     @rStreetThree , 
			 @rCityName,
			 @rZipCode,
			 @rHomePage,
			 @rPhoneNo,
			 @rMobileNo,
			 @rContactPerson,
			 @rCreatedUserId,
			 sCommon.fGetDate(), 
			@rCreatedUserId,
			 sCommon.fGetDate(), 
			 @rIsObsolete,
			 @rCustomerStatusId,
			 @rChannelId,
			 @rInstallationTypeId,
			 @rStateId,
			 @rCountryId,
			 @rDomain,
			 @rDb,
			 @rInstallationDate
			  			  			
		)
		INSERT INTO sErp.tCustomerActivationLog
			(
			OrgGroupId,
			LogDate,
			StatusRemark,
			CreatedUserId,
			CreatedDateTime,
			CustomerStatusId
			)
			VALUES
			(
			@rOrgGroupID , 
			sCommon.fGetDate(),
			'',
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rCustomerStatusId
			
			)
		    SELECT 1 AS Result
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sErp.tCustomerMaster
	    SET		
	     OrgGroupId= @rOrgGroupId,
			 CRMLicenceId =@rCRMLicenceId,
			 Title=@rTitle ,
			 ShortTitle=@rShortTitle ,
			 StreetOne=@rStreetOne,
			 StreetTwo=@rStreetTwo ,
			 StreetThree=@rStreetThree ,
		     CityName= @rCityName,
			 ZipCode=@rZipCode,
			 HomePage= @rHomePage,
	         PhoneNo=@rPhoneNo ,
			 MobileNo= @rMobileNo,
			 ContactPerson =@rContactPerson,
		
			 UpdatedUserId=@rCreatedUserId, 
			 UpdatedDateTime=sCommon.fGetDate(),
			 IsObsolete=@rIsObsolete,
			 CustomerStatusId= @rCustomerStatusId,
			 ChannelId=@rChannelId ,
			 InstallationTypeId=@rInstallationTypeId,
			 StateId=@rStateId ,
			 CountryId =@rCountryId,
			 Domain =@rDomain,
			 Db =@rDb,
			 InstallationDate =@rInstallationDate
	    
	      
	      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 [sErp].[pCustomerOrgAdd]...';


GO
ALTER PROCEDURE [sErp].[pCustomerOrgAdd]
	@rOrgId smallint,
	@rCustomerId int,
    @rOrgNumber int,
    @rOrgName nvarchar(200),
    @rActivationDate date,
    @rInActiveDate date,
    @rCreatedUserId [bigint],   
    @rCustomerStatusId tinyint ,
    @rIsActive bit  ,
    @rIsSave bit   	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	BEGIN TRY
	
	
	
	IF (@rIsSave=1)
	BEGIN
		If Exists(select CO.CustomerId from sErp.tCustomerOrg CO 
		LEFT JOIN sErp.tCustomerMaster CM ON CO.CustomerId=CM.Id 
		where CO.OrgNumber=@rOrgNumber AND CM.OrgId=@rOrgId)
			BEGIN
			select -102 as Result
			RETURN
		END 
	
		--If Exists(select CustomerId from sErp.tCustomerOrg where OrgName=@rOrgName)
		--	BEGIN
		--	select -103 as Result
		--	RETURN
		--END 
	END
	ELSE
	-- IF NOT EXISTS(SELECT 1 FROM sErp.tCustomerOrg Where  OrgNumber = @rOrgNumber)
	BEGIN
		If  Exists(select CO.CustomerId from sErp.tCustomerOrg CO
		LEFT JOIN sErp.tCustomerMaster CM ON CO.CustomerId=CM.Id 
		where CO.OrgNumber=@rOrgNumber AND CO.CustomerId <> @rCustomerId 
		--AND CO.OrgNumber<>OrgNumber 
		AND CM.OrgId=@rOrgId)
		Begin
			select -102 as Result
			RETURN
		End
		--If   Exists(select CustomerId from sErp.tCustomerOrg where OrgName=@rOrgName AND CustomerId <> CustomerId)
		--Begin
		--	select -103 as Result
		--	RETURN
		--End

	END
	
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

--IF NOT EXISTS(SELECT 1 FROM sErp.tCustomerOrg Where CustomerId = @rCustomerId AND OrgNumber = @rOrgNumber)
IF(@rIsSave=1)
	BEGIN
		 
		 
	INSERT INTO sErp.tCustomerOrg
		(CustomerId,
			OrgNumber,
			OrgName,
			ActivationDate,
			InActiveDate,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime,
			CustomerStatusId,
			IsActive	

		)
	VALUES
		(
			 @rCustomerId ,
				 @rOrgNumber,
				 @rOrgName,
				 @rActivationDate ,
				 @rInActiveDate ,
				 @rCreatedUserId,
				 sCommon.fGetDate(),
				 @rCreatedUserId,
				 sCommon.fGetDate(),
			     @rCustomerStatusId,
			     @rIsActive
		)
		    SELECT 1 AS Result
	END	 

ELSE
	 BEGIN
		 
	    UPDATE  sErp.tCustomerOrg
	    SET 
			 --OrgNumber=@rOrgNumber
			  OrgName=@rOrgName,
			 CustomerStatusId=@rCustomerStatusId,
				UpdatedUserId = @rCreatedUserId,
			UpdatedDateTime = sCommon.fGetDate(),
	      IsActive=@rIsActive,
	      ActivationDate=@rActivationDate,
	      InActiveDate=@rInActiveDate
	      WHERE 	CustomerId = @rCustomerId
		AND OrgNumber = @rOrgNumber
	      SELECT 11 AS Result
	 END  	

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


GO
ALTER PROCEDURE [sErp].[pCustomerOrgGet]

	 @rCustomerId int,
	 @rOrgId smallint,
	 @rOrgNumber int=0
	 
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	
	
	SELECT 
			CM.CustomerId,
			CM.OrgNumber ,
			CM.OrgNumber AS RowIndex,
			CM.OrgName,
			CM.ActivationDate,
		   CM.InActiveDate,
		   CM.CustomerStatusId,
		    CS.Title AS CustomerStatus,
		    COM.Title AS CustomerName,
		    CM.IsActive,
		    COM.OrgGroupId
	FROM 
			 sErp.tCustomerOrg CM
			 LEFT JOIN sErp.tCustomerStatusMaster CS ON CS.Id=CM.CustomerStatusId
			 LEFT JOIN sErp.tCustomerMaster COM ON COM.Id=CM.CustomerId
	WHERE 
	
			((CM.CustomerId = @rCustomerId) OR (@rCustomerId = 0))
			AND((COM.OrgId = @rOrgId)OR (@rOrgId=0))
			AND ((CM.OrgNumber = @rOrgNumber) OR (@rOrgNumber = 0))
		
		ORDER BY CM.OrgNumber DESC
END
GO
PRINT N'Altering [sErp].[pCustomerOrgListGet]...';


GO
ALTER PROCEDURE [sErp].[pCustomerOrgListGet]
	 
	 @rOrgId smallint,
	 @rOrgGroupId smallint,
	 @rCustomerId int=0,
	 @rOrgNumber int=0,
	 @rOrgName nvarchar(200),
	 @rCustomerStatusId tinyint=0,
	 @rChannelId int=0,
	 @rInstallationTypeId tinyint=0
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	BEGIN
		SET @rOrgName = sCommon.fSearchStringGet(@rOrgName)
	
	END
	
	SELECT 
			CM.CustomerId,
			COM.Title AS CustomerName,
			CM.OrgNumber,
			CM.OrgName,
			CM.ActivationDate,
		   CM.InActiveDate,
		   COM.CustomerStatusId,
		    CS.Title AS CustomerStatus,
		    COM.Title AS CustomerName,
		    CM.IsActive,
		    COM.OrgGroupId,
		    COM.ChannelId,
		    CC.Title AS ChannelName,
		    COM.InstallationTypeId,
		    IM.Title AS InstallationType
	FROM 
			 sErp.tCustomerOrg CM
			
			 LEFT JOIN sErp.tCustomerMaster COM ON COM.Id=CM.CustomerId
			  LEFT JOIN sErp.tCustomerStatusMaster CS ON CS.Id=COM.CustomerStatusId
			 LEFT JOIN sErp.tInstallationTypeMaster IM ON IM.Id= COM.InstallationTypeId
			 LEFT JOIN sErp.tChannelMaster CC ON CC.Id= COM.ChannelId
	WHERE 
	
			((CM.CustomerId = @rCustomerId) OR (@rCustomerId = 0))
			AND((COM.OrgId = @rOrgId)OR (@rOrgId=0))
			AND((COM.OrgGroupId = @rOrgGroupId)OR (@rOrgGroupId=0))
				AND ((CM.OrgName like @rOrgName) OR (ISNULL(@rOrgName,'') = ''))
			AND ((CM.OrgNumber = @rOrgNumber) OR (@rOrgNumber = 0))
			AND((COM.ChannelId = @rChannelId)OR (@rChannelId=0))
			AND((COM.InstallationTypeId = @rInstallationTypeId)OR (@rInstallationTypeId=0))
			AND((COM.CustomerStatusId = @rCustomerStatusId)OR (@rCustomerStatusId=0))
		
		ORDER BY CM.CreatedDateTime DESC
END
GO
PRINT N'Altering [sFee].[pReceiptBookMasterAdd]...';


GO

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

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


GO

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

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

BEGIN
SELECT RBM.Id 
	  ,RBM.Code
      ,RBM.Title
      ,RBM.FullTitle
      ,RBM.Address1
      ,RBM.Address2
      ,RBM.BankAccountNumber
      ,RBM.IsObsolete
      ,RBM.Remark1
      ,RBM.Remark2
      ,ISNULL(RBM.IsOnPrePrinted ,0) AS IsOnPrePrinted
      ,ISNULL(RBM.IsSupressLogo,0) AS IsSupressLogo
      ,RBM.ReportId  
       --,RBM.OrderIndex  
      ,ISNULL(RBM.OrderIndex,0) AS OrderIndex
      ,ISNULL(RBM.IsDisplaySchoolName,0) AS IsDisplaySchoolName
      ,ISNULL(RBM.IsMonthDetailOnly,0) AS IsMonthDetailOnly
      ,ISNULL(RBM.IsServiceTaxApplicable,0) AS IsServiceTaxApplicable
	  ,ISNULL(RBM.ServiceTaxPercentage,0) AS ServiceTaxPercentage
	  ,ISNULL(RBM.BankName,'') AS BankName
	  ,ISNULL(RBM.IsFeeInvoiceHeadwise,0) AS IsFeeInvoiceHeadwise
	  ,ISNULL(RBM.GroupTitle,'') AS GroupTitle
	  ,ISNULL(RBM.IsSuppressFeeDetail,0) AS IsSuppressFeeDetail
	  ,RBM.ReceiptLogo
	  ,ISNULL(RBM.HeaderDisplayId,1) AS HeaderDisplayId
	  ,RBM.ReceiptBookHeader
	
      
     
  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].[pRptFeeReceiptDetailsGet]...';


GO
ALTER PROCEDURE [sFee].[pRptFeeReceiptDetailsGet]
			
			
			@rReportId int=0,
			@rReceiptId bigint = 0,
			@rOrgGroupId int = 0,
			@rReceiptBookId int = 0,
			@rFromReceiptNo int=0,
			@rToReceiptNo int=0,
			@rOrgId int = 0,
			@rBatchId int = 0,
			@rReceiptDate Date=''

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 	
	
	DECLARE @lOrgGroupId int = 0
	DECLARE @lAmountInWord nvarchar(500) = ''
	DECLARE @lReceiptAmount Decimal(12,2) = 0.0
	DECLARE @lCurrencyCode nvarchar(20) = ''
 
	IF(@rOrgGroupId=0)
	BEGIN
		SELECT @lOrgGroupId = OrgGroupId ,@lReceiptAmount = R.ReceiptAmount  FROM sFee.tReceipt R 
		INNER JOIN sSetup.tOrgGroupBatchMaster OB ON R.OrgGroupBatchId = OB.Id 
		WHERE R.Id = @rReceiptId

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

	SELECT 
			FRD.ReceiptId,
			FR.ReceiptNumber,
			FR.ReceiptDate,
			SA.AcademicId,
			--SA.FirstName+' '+SA.MiddleName+' '+SA.LastName AS Name,
			SA.Name 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,			
			
			(CASE WHEN @rOrgGroupId = 0 -- For Single Receipt
					THEN @lAmountInWord 
				  WHEN @rOrgGroupId != 0 -- For Bulk Receipt
					THEN sFinanceCommon.fNumberToWordsWithDecimal(ISNULL(FR.ReceiptAmount,0.00),1,2,@rOrgGroupId)
			END) AS ReceiptAmountInWords,
			
			ISNULL(FR.DiscountAmount,0.00) AS DiscountAmount,
			FR.Remark,
			ISNULL(U.DisplayTitle,'') AS UserName,
			OM.OrgLogo,
			RBM.Remark1,
			RBM.Remark2,			 
			ISNULL(RBM.IsOnPrePrinted,0) AS IsOnPrePrinted,
			ISNULL(RBM.IsSupressLogo,0) AS IsSupressLogo,
			ISNULL(RBM.IsDisplaySchoolName,0) AS IsDisplaySchoolName,
			RBM.ReportId,
			OM.Title AS OrganizationName,
			--(CASE  WHEN (RBM.ReportId = 20775 OR RBM.ReportId = 20777 OR RBM.ReportId = 20874 OR RBM.ReportId =20427 OR RBM.ReportId =20890 OR RBM.ReportId =20901 OR RBM.ReportId =20902) AND ISNULL(RBM.IsMonthDetailOnly,0) = 0  THEN 
			--	[sFee].[fFeeHeadMonthDetailGet](FR.ID,FHM.Id) -- Fee name in detail	
				  
			  
			(CASE WHEN  RBM.ReportId = 20576 
			  THEN -- HM patel report
				[sFee].[fReceiptMonthDetailGet](FR.ID)	
				
			WHEN ISNULL(RBM.IsMonthDetailOnly,0) = 1  THEN				
				 [sFee].[fFeeHeadMonthNameGet](FR.ID,FHM.Id) -- Month name in detail
	
			ELSE '' END) AS MonthDetail,    
			
			DM.Title AS DepartmentName,
			FM.OrderIndex AS FeeOrderIndex,
			FHM.OrderIndex AS FeeHeadOrderIndex,
			FR.IsObsolete AS IsCancelReceipt,
			@lCurrencyCode AS CurrencyCode,
			BM.Title AS Batch,
			FR.ChequeDate AS ChequeDate,
			ISNULL(RBM.IsMonthDetailOnly,0) AS IsMonthDetailOnly,
	        ISNULL(RBM.IsFeeInvoiceHeadwise,0) AS IsFeeInvoiceHeadwise,
	        ISNULL(RBM.GroupTitle,'') AS GroupTitle,
	        ISNULL(RBM.IsSuppressFeeDetail,0) AS IsSuppressFeeDetail,
	        ISNULL(CGM.Title,'') AS CollectionGroupName,
	        ISNULL(FI.InvoiceNumber,0) AS InvoiceNumber,
	        SA.SUID,
	        ISNULL(RBM.HeaderDisplayId,1) AS HeaderDisplayId,
	        RBM.ReceiptBookHeader
	        
	FROM 
	
			sFee.tReceipt FR				
			INNER JOIN sFee.tReceiptDetail FRD
				ON FR.Id=FRD.ReceiptId AND FR.SourceTypeId=2001				
			INNER JOIN sFee.tFeeSetup FS
				ON FRD.FeeSetupId = FS.Id				
			INNER JOIN sFee.tFeeMaster FM
				ON FS.FeeId=FM.Id						
			INNER JOIN sFee.tFeeHeadMaster FHM
				ON FHM.Id=FM.FeeHeadId
			INNER JOIN sStudent.vStudentAcademic SA
				ON SA.AcademicId = FR.SourceId
			INNER JOIn sFinanceCommon.tPayTypeMaster PTM
				ON PTM.Id=FR.PayTypeId
			--LEFT JOIN sFee.tFeeAllocation FA
			--	ON FA.FeeSetupId=FS.Id
			INNER JOIN sFee.tReceiptBookMaster RBM 
				ON RBM.Id=FR.ReceiptBookId
			LEFT JOIN sSecurity.tUser U
				ON U.Id=FR.CreatedUserId
			INNER JOIN sSetup.tDepartmentMaster DM
				ON SA.DepartmentId =DM.Id
			LEFT JOIN sSetup.tOrganizationMaster OM
				ON OM.Id=DM.OrgId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = FR.BatchId
			LEFT JOIN sFee.tCollectionGroupMaster CGM
				ON CGM.Id=FR.CollectionGroupId
			LEFT JOIN sFee.tFeeInvoice FI
				ON FI.Id=FR.FeeInvoiceId
	WHERE 
	 ((FR.Id=@rReceiptId) OR (@rReceiptId = 0))
	 AND ((RBM.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId = 0))
	 AND ((FR.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId = 0))
	 AND ((FR.ReceiptNumber >= @rFromReceiptNo) OR (@rFromReceiptNo = 0))
	 AND ((FR.ReceiptNumber <= @rToReceiptNo) OR (@rToReceiptNo = 0))
	 AND ((FR.BatchId = @rBatchId) OR (@rBatchId = 0))
	 AND ((BM.OrgId = @rOrgId) OR (@rOrgId = 0))
	 AND ((FR.ReceiptDate = @rReceiptDate) OR (ISNULL(@rReceiptDate,'') = ''))
	  
ORDER BY FS.StartDate,FHM.OrderIndex,FM.OrderIndex ASC

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


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

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

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

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


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




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

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

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


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


GO
ALTER PROCEDURE [sHrm].[pEmployeeAttenanceView_NewGet]

		@rOrgId int
		,@rForMonth smallint
		,@rForYear smallint
		,@rBatchId int 
		,@rDepartmentId int 

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

	DECLARE @lFirstDate Date
	SET @lFirstDate = CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'/'+CONVERT(NVARCHAR(2),@rForMonth)+'/01'))
		
BEGIN 
  
	SELECT  
			 @lFirstDate AS LastDate
			,PT.EmployeeId
			,Code
			,Name
			,ForYear
			,ForMonth
			,ForMonthInWord
			,(ISNULL(TC.TCount,0) - ISNULL(AC.ACount,0)) AS PresentCount
			,ISNULL(TC.TCount,0) AS AttendanceCount
			,ISNULL(AC.ACount,0) As  AbsentCount
			,ISNULL(PC.PCount,0) As  PresentUpto
			,0 AS TotalPresent
			,[sHrm].[fWeekHOffHolidayLeaveGet](@rForYear,@rForMonth,1,@rBatchId,PT.EmployeeId,[1],@rOrgId) AS P1
			,[sHrm].[fWeekHOffHolidayLeaveGet](@rForYear,@rForMonth,2,@rBatchId,PT.EmployeeId,[2],@rOrgId) AS P2
			,[sHrm].[fWeekHOffHolidayLeaveGet](@rForYear,@rForMonth,3,@rBatchId,PT.EmployeeId,[3],@rOrgId) AS P3 
			,[sHrm].[fWeekHOffHolidayLeaveGet](@rForYear,@rForMonth,4,@rBatchId,PT.EmployeeId,[4],@rOrgId) AS P4
			,[sHrm].[fWeekHOffHolidayLeaveGet](@rForYear,@rForMonth,5,@rBatchId,PT.EmployeeId,[5],@rOrgId) AS P5
			,[sHrm].[fWeekHOffHolidayLeaveGet](@rForYear,@rForMonth,6,@rBatchId,PT.EmployeeId,[6],@rOrgId) AS P6
			,[sHrm].[fWeekHOffHolidayLeaveGet](@rForYear,@rForMonth,7,@rBatchId,PT.EmployeeId,[7],@rOrgId) AS P7
			,[sHrm].[fWeekHOffHolidayLeaveGet](@rForYear,@rForMonth,8,@rBatchId,PT.EmployeeId,[8],@rOrgId) AS P8
			,[sHrm].[fWeekHOffHolidayLeaveGet](@rForYear,@rForMonth,9,@rBatchId,PT.EmployeeId,[9],@rOrgId) AS P9
			,[sHrm].[fWeekHOffHolidayLeaveGet](@rForYear,@rForMonth,10,@rBatchId,PT.EmployeeId,[10],@rOrgId) AS P10
			,[sHrm].[fWeekHOffHolidayLeaveGet](@rForYear,@rForMonth,11,@rBatchId,PT.EmployeeId,[11],@rOrgId) AS P11
			,[sHrm].[fWeekHOffHolidayLeaveGet](@rForYear,@rForMonth,12,@rBatchId,PT.EmployeeId,[12],@rOrgId) AS P12
			,[sHrm].[fWeekHOffHolidayLeaveGet](@rForYear,@rForMonth,13,@rBatchId,PT.EmployeeId,[13],@rOrgId) AS P13
			,[sHrm].[fWeekHOffHolidayLeaveGet](@rForYear,@rForMonth,14,@rBatchId,PT.EmployeeId,[14],@rOrgId) AS P14
			,[sHrm].[fWeekHOffHolidayLeaveGet](@rForYear,@rForMonth,15,@rBatchId,PT.EmployeeId,[15],@rOrgId) AS P15
			,[sHrm].[fWeekHOffHolidayLeaveGet](@rForYear,@rForMonth,16,@rBatchId,PT.EmployeeId,[16],@rOrgId) AS P16
			,[sHrm].[fWeekHOffHolidayLeaveGet](@rForYear,@rForMonth,17,@rBatchId,PT.EmployeeId,[17],@rOrgId) AS P17
			,[sHrm].[fWeekHOffHolidayLeaveGet](@rForYear,@rForMonth,18,@rBatchId,PT.EmployeeId,[18],@rOrgId) AS P18
			,[sHrm].[fWeekHOffHolidayLeaveGet](@rForYear,@rForMonth,19,@rBatchId,PT.EmployeeId,[19],@rOrgId) AS P19
			,[sHrm].[fWeekHOffHolidayLeaveGet](@rForYear,@rForMonth,20,@rBatchId,PT.EmployeeId,[20],@rOrgId) AS P20
			,[sHrm].[fWeekHOffHolidayLeaveGet](@rForYear,@rForMonth,21,@rBatchId,PT.EmployeeId,[21],@rOrgId) AS P21
			,[sHrm].[fWeekHOffHolidayLeaveGet](@rForYear,@rForMonth,22,@rBatchId,PT.EmployeeId,[22],@rOrgId) AS P22
			,[sHrm].[fWeekHOffHolidayLeaveGet](@rForYear,@rForMonth,23,@rBatchId,PT.EmployeeId,[23],@rOrgId) AS P23
			,[sHrm].[fWeekHOffHolidayLeaveGet](@rForYear,@rForMonth,24,@rBatchId,PT.EmployeeId,[24],@rOrgId) AS P24
			,[sHrm].[fWeekHOffHolidayLeaveGet](@rForYear,@rForMonth,25,@rBatchId,PT.EmployeeId,[25],@rOrgId) AS P25
			,[sHrm].[fWeekHOffHolidayLeaveGet](@rForYear,@rForMonth,26,@rBatchId,PT.EmployeeId,[26],@rOrgId) AS P26
			,[sHrm].[fWeekHOffHolidayLeaveGet](@rForYear,@rForMonth,27,@rBatchId,PT.EmployeeId,[27],@rOrgId) AS P27
			,[sHrm].[fWeekHOffHolidayLeaveGet](@rForYear,@rForMonth,28,@rBatchId,PT.EmployeeId,[28],@rOrgId) AS P28
			,[sHrm].[fWeekHOffHolidayLeaveGet](@rForYear,@rForMonth,29,@rBatchId,PT.EmployeeId,[29],@rOrgId) AS P29
			,[sHrm].[fWeekHOffHolidayLeaveGet](@rForYear,@rForMonth,30,@rBatchId,PT.EmployeeId,[30],@rOrgId) AS P30
			,[sHrm].[fWeekHOffHolidayLeaveGet](@rForYear,@rForMonth,31,@rBatchId,PT.EmployeeId,[31],@rOrgId) AS P31
	FROM
		(
			SELECT   
				 Em.Code
				,Em.FirstName + ' ' + Em.LastName AS Name
				,Em.Id AS EmployeeId 
				,YEAR(ER.AttendanceDate) AS ForYear
				,MONTH(ER.AttendanceDate) AS ForMonth
				,DATENAME(MONTH, ER.AttendanceDate) AS ForMonthInWord
				,(CASE ER.IsPresent WHEN 1 THEN 'P' WHEN 0 THEN 'A' ELSE  ' ' END )AS  IsPresent		
				,DAY(ER.AttendanceDate) AS DayPart 
			FROM
				sHrm.tEmployeeMaster Em 
				INNER JOIN sHrm.tEmployeeAttendanceRegister ER ON ER.EmployeeId= EM.Id
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
				LEFT JOIN sSetup.tDepartmentMaster DM ON DM.Id=EJD.OrganizationDepartmentId
		    WHERE  
				((EM.OrgId=@rOrgId) OR (@rOrgId= 0))
				AND ((ER.BatchId=@rBatchId) OR (@rBatchId= 0))
				AND ((YEAR(ER.AttendanceDate)=@rForYear) OR (@rForYear= 0))
				AND ((MONTH(ER.AttendanceDate)=@rForMonth) OR (@rForMonth= 0))
				AND ((DM.Id=@rDepartmentId) OR (@rDepartmentId=0))
				) AS SourceTable
			
			PIVOT
			(	
				MIN(IsPresent)
				FOR DayPart IN ([0], [1], [2], [3], [4],[5],[6],[7],[8],[9],[10],[11],[12],[13],[14],[15],[16],[17],[18],[19],[20],[21],[22],[23],[24],[25],[26],[27],[28],[29],[30],[31])
			) AS PT
			LEFT JOIN
			(
				SELECT EM.Id AS EmployeeId, COUNT(1) AS TCount 
				FROM sHrm.tEmployeeAttendanceRegister ER
				INNER JOIN sHrm.tEmployeeMaster EM ON ER.EmployeeId = EM.Id 
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.Employeeid = EM.Id
				INNER JOIN sSetup.tDepartmentMaster Deprt ON Deprt.Id= EJD.OrganizationDepartmentId
				WHERE 		
				((EM.OrgId=@rOrgId) OR (@rOrgId= 0))
				AND ((ER.BatchId=@rBatchId) OR (@rBatchId= 0))
				AND ((YEAR(ER.AttendanceDate)=@rForYear) OR (@rForYear= 0))
				AND ((MONTH(ER.AttendanceDate)=@rForMonth) OR (@rForMonth= 0))
				AND ((Deprt.Id=@rDepartmentId) OR (@rDepartmentId=0))
				GROUP BY Em.Id
			) TC ON TC.EmployeeId = PT.employeeid

			LEFT JOIN
			(
				SELECT EM.Id AS EmployeeId, COUNT(1) AS ACount 
				FROM sHrm.tEmployeeAttendanceRegister ER
				INNER JOIN sHrm.tEmployeeMaster EM ON ER.EmployeeId = EM.Id 
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.Employeeid = EM.Id
				INNER JOIN sSetup.tDepartmentMaster Deprt ON Deprt.Id= EJD.OrganizationDepartmentId
				WHERE
				ER.IsPresent = 0	 		
				AND (EM.StatusId = 7)
				AND ((EM.OrgId=@rOrgId) OR (@rOrgId= 0))
				AND ((ER.BatchId=@rBatchId) OR (@rBatchId= 0))
				AND ((YEAR(ER.AttendanceDate)=@rForYear) OR (@rForYear= 0))
				AND ((MONTH(ER.AttendanceDate)=@rForMonth) OR (@rForMonth= 0))
				AND ((Deprt.Id=@rDepartmentId) OR (@rDepartmentId=0))				
				GROUP BY EM.Id
			) AC ON AC.EmployeeId = PT.EmployeeId
			LEFT JOIN
			(
				SELECT EM.Id AS Employeeid, COUNT(1) AS PCount  
				FROM sHrm.tEmployeeAttendanceRegister ER 
				INNER JOIN sHrm.tEmployeeMaster EM ON ER.EmployeeId = EM.Id 
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.Employeeid = EM.Id
				INNER JOIN sSetup.tDepartmentMaster Deprt ON Deprt.Id= EJD.Organizationdepartmentid
				WHERE  
				ER.AttendanceDate < (convert(date,CONVERT(nvarchar(10), @rForYear)+ '/' +  CONVERT(nvarchar(10), @rForMonth) + '/' + '01' ))
				AND ER.IsPresent = 1	    		
				AND ((EM.OrgId=@rOrgId) OR (@rOrgId= 0))
				AND ((ER.BatchId=@rBatchId) OR (@rBatchId= 0))	          
				AND ((Deprt.Id=@rDepartmentId) OR (@rDepartmentId=0))				
				GROUP BY EM.Id
			) PC ON PC.Employeeid = PT.EmployeeId

			ORDER BY Code
	  
END
GO
PRINT N'Altering [sHrm].[pEmployeeMasterGet]...';


GO
--EXEC [sHrm].[pEmployeeMasterGet] 1001,0,'001'

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

BEGIN
	   IF @rCode <> ''
		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,
				DEP.title AS EmployeeDepartment
	
   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
		   LEFT JOIN [sSetup].[tDepartmentMaster]			   AS DEP ON DEP.id=EJD.OrganizationDepartmentId
	WHERE 
			    EM.OrgId = @rOrgId
		   AND ((EM.Id = @rId) OR (@rId = 0))
		   AND ((EM.Code Like  @rCode ) OR (@rCode = ''))
END
GO
PRINT N'Altering [sHrm].[pEmployeeProfileGet]...';


GO
ALTER PROCEDURE [sHrm].[pEmployeeProfileGet]
(
	@rOrgId int,
	@rDepartmentId int = 0,
	@rEmployeeId bigint,
	@rGroupId int
)
AS
SET NOCOUNT ON

BEGIN
		SELECT 
				EM.Id AS EmployeeId,
				ISNULL(EM.FirstName, '') + ' ' + ISNULL(EM.MiddleName, '') + ' ' + ISNULL(EM.LastName, '') AS Name,
				EC.CompanyEmail AS EmailId,
				DM.Id AS DepartmentId,
				DM.Title AS DepartmentName,
				CONVERT(date,EJD.DateOfJoining) AS DateOfJoining,
				EM.Code AS Code,
				ISNULL(EI.EmployeePhoto, CONVERT(VARBINARY(MAX), 0)) AS EmployeePhoto,
				GrpM.Id AS EmployeeGroupId,
				GrpM.Title AS GroupName,
				[sHrm].[fEmployeeSubjectGet](EM.Id) AS Subjects,
				ISNULL(EC.MobileNumber,'') AS MobileNumber
		FROM 
				sHrm.tEmployeeMaster EM
			INNER JOIN  sHrm.tEmployeeCommunications EC ON EC.EmployeeId=EM.Id
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
			LEFT JOIN sSetup.tDepartmentMaster DM ON DM.Id=EJD.OrganizationDepartmentId
			LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId=EM.Id
			LEFT JOIN sHrm.tEmployeeGroupMaster GrpM ON GrpM.Id=EJD.EmployeeGroupId
		WHERE 
				EM.OrgId = @rOrgId 
			AND ((EJD.OrganizationDepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))	
			AND ((EM.Id=@rEmployeeId) OR (@rEmployeeId=0))
			AND ((EJD.EmployeeGroupId = @rGroupId) OR (@rGroupId = 0))	
END
GO
PRINT N'Altering [sHrm].[pEmployeeTravelAdd]...';


GO
ALTER PROCEDURE [sHrm].[pEmployeeTravelAdd]
        @rOrgId int,
        @rId bigint,
        @rEmployeeId bigint,
        @rReportDate date,
        @rTravelFromDate date,
        @rTravelToDate date,
        @rTravelPeriodId tinyint,       
        @rTravelReason nvarchar(200),
        @rTravelRemark nvarchar(200),
        @rNoOfDays decimal(5,2),
        @rFromTime datetime=null,
		@rToTime datetime=null,
        @rBatchId int,
       
        @rCreatedUserId bigint,
        @rStatusId int
       
AS
SET NOCOUNT ON

BEGIN


      DECLARE @1Days int
	BEGIN TRY
	
	BEGIN TRANSACTION

	DECLARE @lNextNumber bigint
	 
    IF (@rId = 0)
     BEGIN
       
       IF(@rTravelPeriodId = 2) --For Half Leave	  	
       SELECT @1Days = SUM(NoOfDays) from sHrm.tEmployeeTravel where EmployeeId = @rEmployeeId AND OrgId = @rOrgId AND TravelFromDate = @rTravelFromDate
       ELSE
         SET @1Days = 1
     		
	   IF NOT EXISTS(SELECT 1 FROM sHrm.tEmployeeTravel WHERE EmployeeId = @rEmployeeId 
	   AND(( TravelFromDate  BETWEEN @rTravelFromDate AND @rTravelToDate) OR (TravelToDate BETWEEN @rTravelFromDate AND @rTravelToDate)
	   OR (@rTravelFromDate  BETWEEN TravelFromDate AND TravelToDate) OR (@rTravelToDate BETWEEN TravelFromDate AND TravelToDate)) AND OrgId = @rOrgId AND BatchId = @rBatchId AND StatusId!=643)OR @1Days != 1 
	   BEGIN
	    EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sHrm.tEmployeeTravel', 0, 1, 1,@outNextNumber = @lNextNumber output	
	    
		  INSERT INTO sHrm.tEmployeeTravel
           (
            [Id]
           ,[EmployeeId]
           ,[ReportDate]
           ,TravelFromDate
           ,TravelToDate
           ,TravelPeriodId       
           ,TravelReason
           ,TravelRemark
           ,NoOfDays
            ,[FromTime]
           ,[ToTime]
           ,[OrgId] 
            ,[CreatedUserId]
           ,[CreatedDateTime]
           ,[UpdatedUserId]
           ,[UpdatedDateTime] 
           ,BatchId                              
           ,[StatusId]
          
           )
     VALUES
           (
            @lNextNumber
           ,@rEmployeeId 
           ,@rReportDate 
           ,@rTravelFromDate
           ,@rTravelToDate 
           ,@rTravelPeriodId          
           ,@rTravelReason 
           ,@rTravelRemark
           ,@rNoOfDays
           ,@rFromTime
           ,@rToTime  
           ,@rOrgId 
           ,@rCreatedUserId 
           ,sCommon.fGetDate()
           ,@rCreatedUserId 
           ,sCommon.fGetDate()
           ,@rBatchId                      
           ,@rStatusId       
          
           )
            SELECT 1 AS Result
            END
          ELSE
            SET @lNextNumber = -101            
          END
	ELSE
	BEGIN
	SET @lNextNumber = @rId
		UPDATE sHrm.tEmployeeTravel
		SET 	 
		   [EmployeeId]= @rEmployeeId 
		  ,[ReportDate]= @rReportDate 
		  ,[TravelFromDate]= @rTravelFromDate
		  ,TravelToDate= @rTravelToDate
		  ,[TravelPeriodId]= @rTravelPeriodId
		 
		  ,TravelReason= @rTravelReason
		  ,TravelRemark=@rTravelRemark
		  ,NoOfDays = @rNoOfDays
		  ,[OrgId]= @rOrgId        
		  ,[UpdatedUserId]= @rCreatedUserId
		  ,[UpdatedDateTime]= sCommon.fGetDate()
		  ,[FromTime] = @rFromTime
          ,[ToTime] = @rToTime    
		WHERE Id = @rId
		 SELECT 11 AS Result
	 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].[pEmployeeTravelGet]...';


GO

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

BEGIN
    
	SELECT 
		   E.[Id] AS TravelId
		  ,E.[EmployeeId]
		  ,[ReportDate]
		  ,TravelFromDate
		  ,TravelToDate
		  ,TravelPeriodId		  
		  ,TravelReason
		  ,TravelRemark
		  ,TPM.Title AS TravelPeriod
		 ,StatusReason
		  ,EM.EmployeeName
		  ,EM.Code AS EmployeeCode
		  ,ISNULL(E.StatusId,0) AS StatusId
		  ,ISNULL(SM.Title,'Pending') AS StatusName
		  ,E.NoOfDays    
		  ,ISNULL(E.FromTime,'') AS FromTime
          ,ISNULL(E.ToTime,'') AS ToTime
		  --,(ISNULL((Select NoOfLeave FROM sHrm.tLeaveTypeGradeSettings LGS WHERE LGS.EmployeeGradeId = EM.EmployeeGradeId AND LGS.LeaveTypeId = L.LeaveTypeId),0) - L.NoOfLeave) AS AvailableLeave
      
  FROM 
			sHrm.tEmployeeTravel E
	  INNER JOIN sHrm.tTravelPeriodMaster TPM ON TPM.Id = E.TravelPeriodId
	  
	  INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = E.EmployeeId 
	  INNER JOIN sCommon.tStatusMaster SM ON SM.Id = E.StatusId
	  --INNER JOIN sHrm.tLeaveTypeGradeSettings LTGS ON LTGS.EmployeeGradeId = EM.EmployeeGradeId AND LTGS.LeaveTypeId = L.LeaveTypeId 
  WHERE 
		  (E.Id = @rId OR @rId = 0)
      AND (E.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
      AND ((E.TravelFromDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
      AND ((E.TravelFromDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
       
      AND BatchId = @rBatchId AND E.OrgId = @rOrgId 
      AND (EM.Code = @rEmployeeCode OR ISNULL(@rEmployeeCode,'') = '')
      AND (EM.EmployeeName like @rEmployeeName+'%' OR ISNULL(@rEmployeeName,'') = '')
      AND (E.StatusId = @rStatusId OR @rStatusId = 0)
      Order By [ReportDate] DESC
END
GO
PRINT N'Altering [sHrm].[pEmployeeTravelListingGet]...';


GO

ALTER PROCEDURE [sHrm].[pEmployeeTravelListingGet]
(
	@rOrgId int,
    @rId bigint = 0,
    @rEmployeeId  bigint,   
    @rTravelFromDate date,
  
    @rTravelToDate date,
    @rOrgGroupBatchId int,
    @rEmployeeCode nvarchar(100)='',
    @rEmployeeName nvarchar(100)='',
    @rStatusId int = 0 
 )
AS
SET NOCOUNT ON

BEGIN
    
	SELECT 
		   T.[Id] AS TravelId
		  ,T.[EmployeeId]
		  ,T.[ReportDate]
		  ,T.TravelFromDate
		  ,T.TravelToDate
		  ,T.TravelPeriodId
		 ,T.TravelRemark
		  ,T.TravelReason
		  ,T.StatusReason
		  ,TPM.Title AS TravelPeriod
		 
		  ,EM.EmployeeName
		  ,EM.Code AS EmployeeCode
		  ,T.NoOfDays
		  ,ISNULL(T.StatusId,0) AS StatusId
		  ,ISNULL(SM.Title,'Pending') AS StatusName
		  --,ISNULL(T.LeaveRemark,'') AS  TravelRemark
		  ,OM.DisplayTitle AS OrganizationName
      
  FROM 
		 sHrm.tEmployeeTravel T
	  INNER JOIN sSetup.tBatchMaster BM ON BM.Id = T.BatchId		
	  INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
	  INNER JOIN sHrm.tTravelPeriodMaster TPM ON TPM.Id = T.TravelPeriodId
	
	  INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = T.EmployeeId
	  INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = T.EmployeeId
	  INNER JOIN sCommon.tStatusMaster SM ON SM.Id = T.StatusId
  WHERE 
		  (T.Id = @rId OR @rId = 0)
      AND (EJD.EmployeeManagerId = @rEmployeeId OR @rEmployeeId = 0)
      AND ((T.TravelFromDate >= @rTravelFromDate) OR (ISNULL(@rTravelFromDate,'') = ''))
      AND ((T.TravelFromDate <= @rTravelToDate) OR (ISNULL(@rTravelToDate,'') = ''))
        
      AND BM.OrgGroupBatchId = @rOrgGroupBatchId
      AND ((T.OrgId = @rOrgId) OR (@rOrgId = 0))
      AND (EM.Code = @rEmployeeCode OR ISNULL(@rEmployeeCode,'') = '')
      AND (EM.EmployeeName like @rEmployeeName+'%' OR ISNULL(@rEmployeeName,'') = '')
      AND (T.StatusId = @rStatusId OR @rStatusId = 0)  
      Order By [ReportDate] DESC    
END
GO
PRINT N'Altering [sHrm].[pExportLeave]...';


GO

ALTER PROCEDURE [sHrm].[pExportLeave]
	
	@rFromBatchId int,
	@rToBatchId int,
	@rOrgId int,
	@rIsDelete bit
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
BEGIN TRY 

	IF (@rIsDelete=1)
	BEGIN
		DELETE FROM sHrm.tLeaveBalance WHERE BatchId = @rToBatchId
		SELECT 101 AS RESULT
		RETURN
	END

	IF EXISTS (SELECT 1 FROM sHrm.tLeaveBalance WHERE BatchId = @rToBatchId)
	BEGIN
		SELECT -101 AS RESULT
		RETURN
	END
	
	BEGIN TRANSACTION
	
	DECLARE @lCount int
	
	-- Leave Balance Temp Table
	
	CREATE TABLE #TempLeaveBalance
	(
	[AutoId] int IDENTITY,
	[EmployeeId] bigint NOT NULL,
	[LeaveTypeId] int NOT NULL,
	[BatchId] int NOT NULL,
	[PendingNoOfLeave] decimal(5,2) NOT NULL,
	[MaximumCarryForward] int NOT NULL,
	[SettingNoOfLeave] int NOT NULL,
	[EmployeeNoOfLeave] decimal(5,2) NOT NULL	
	)
	
	-- End Create Table
	
	INSERT INTO #TempLeaveBalance 
	SELECT 
		EM.Id,
		ISNULL(B.LeaveTypeId,0),
		@rToBatchId,
		(CASE WHEN (ISNULL(B.NoOfLeave,0)-ISNULL(A.NoOfLeave,0)) > 0 
		   THEN ISNULL(B.NoOfLeave,0)-ISNULL(A.NoOfLeave,0)
		   ELSE 0
		END) AS NoOfLeave,	
		ISNULL(B.MaximumCarryForward,0), 
		ISNULL(B.NoOfLeave,0),
		ISNULL(A.NoOfLeave,0)
	FROM 
		sHrm.tEmployeeMaster EM
		INNER JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id = EJD.EmployeeId AND StatusId=7
		LEFT JOIN 
		(
			SELECT L.EmployeeId,L.LeaveTypeId,SUM(L.NoOfLeave) AS NoOfLeave,LTM.MaximumCarryForward  FROM sHrm.tLeave L
			INNER JOIN sHrm.tLeaveTypeMaster LTM ON L.LeaveTypeId = LTM.Id AND IsCarryForward=1 AND IsLWP = 0 AND StatusId=550
			WHERE L.BatchId=@rFromBatchId AND L.OrgId = @rOrgId
			GROUP BY L.EmployeeId,L.LeaveTypeId,LTM.MaximumCarryForward 
		)A ON A.EmployeeId=EM.Id
		LEFT JOIN 
		(
		    SELECT LeaveTypeId,EmployeeGradeId,NoOfLeave,LTM.MaximumCarryForward FROM sHrm.tLeaveTypeGradeSettings LTGS
		    INNER JOIN sHrm.tLeaveTypeMaster LTM ON LTM.Id = LTGS.LeaveTypeId
		    WHERE LTGS.OrgId = @rOrgId
		)B ON B.EmployeeGradeId = EJD.EmployeeGradeId --AND A.LeaveTypeId=B.LeaveTypeId
		WHERE EM.OrgID = @rOrgId
	
	--SELECT * FROM #TempLeaveBalance 
		
	SELECT @lCount = COUNT(EmployeeId) FROM #TempLeaveBalance
	
	WHILE (@lCount > 0)
	BEGIN
		
		-- Leave Balance Entry
		
		INSERT INTO sHrm.tLeaveBalance 
		SELECT 
				EmployeeId,
				LeaveTypeId,
				(
				CASE 
					WHEN (EmployeeNoOfLeave >= MaximumCarryForward) THEN (SettingNoOfLeave)
					WHEN (MaximumCarryForward >= PendingNoOfLeave) THEN (SettingNoOfLeave+PendingNoOfLeave)
					ELSE SettingNoOfLeave+MaximumCarryForward
				END
				) AS NoOfLeave,
				BatchId
				
		FROM #TempLeaveBalance WHERE AutoId = @lCount
		
		-- END Leave Balance Entry
		
		SET @lCount = @lCount -1
	END

	DROP Table #TempLeaveBalance
	SELECT 1 AS Result
	COMMIT TRANSACTION
END TRY

BEGIN CATCH 
		DROP TABLE #TempLeaveBalance 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
END CATCH	
END
GO
PRINT N'Altering [siTax].[pForm16Add]...';


GO
/******************************
** Name:  [siTax].[pForm16IncomeTaxSlabDetailGet]   
** Desc:  Calcalation Of Tax TaxAmount
** Auth:  Savan Vaghela
** Date:  16-January-2017
** Page:  
************************************************************
** Change History
************************************************************
** PR      Date                Author            Description 
**
** 1    06-Febuary-2017      Savan Vaghela  configure TaxExeption
************************************************************/
--EXEC [siTax].[pForm16Add]  3333000000041,100100016,1001,1001000000003,100100001,100100001
ALTER PROCEDURE [siTax].[pForm16Add]   
	@rEmployeeId bigint,
	@rAssesmentYearId bigint,
	@rOrgGroupId int,
	@rCreatedUserId bigint,
	@rPayrollId BIgINT = null,
	@rPayrollYearId BIGINT=null 	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
		BEGIN TRANSACTION	
			DECLARE @lNextNumber BIGINT 
					BEGIN
	 					DECLARE @Count INT =0,@Counter INT=0,@NetAmount DECIMAL(18,2)=0
											
						DECLARE @TableIncomeTaxSlab TABLE (RowID int Identity(1,1), IncomeTaxSubgroupId INT,DefaultPayElementId INT,  NetAmount DECIMAL(18,2),Amount DECIMAL(18,2))
						DECLARE @TableIncome TABLE (PayElementDefaultId INT, NetAmount DECIMAL(18,2), Amount DECIMAL(18,2))

						INSERT INTO @TableIncome
						SELECT PE.PayElementDefaultId,SUM(PPE.TotalEarning) AS NetAmount,SUM(ISNULL(PEM.Amount,0))Amount
						FROM sPayroll.tPayProcessEmployee           AS PPE 
						INNER JOIN sPayroll.tPayProcess             AS PP   ON PP.ID=PPE.PayProcessId
						INNER JOIN sPayroll.tPayrollGroupMaster     AS PGM  ON PGM.ID=PPE.PayrollGroupId
						INNER JOIN sPayroll.tPayrollMaster          AS PYM  ON PYM.Id=PGM.PayrollId
						INNER JOIN sPayroll.tPayrollYearMaster      AS PY   ON PY.Id=PP.PayrollYearId
						INNER JOIN sPayroll.tPayProcessElement      AS PEM  ON PEM.PayProcessEmployeeId=PPE.ID
						INNER JOIN sPayroll.tPayElement             AS PE   ON PE.ID=PEM.PayElementId AND PE.PayrollId=PYM.ID
						INNER JOIN sPayroll.tPayElementDefault      AS PPDE ON PPDE.id=PE.PayElementDefaultId
						WHERE PE.PayElementDefaultId in 
						(
							SELECT DefaultPayElementId 
							FROM [siTax].[tStaticIncomeTaxSubGroup] 
							WHERE ISNULL(DefaultPayElementId,0)<>0 
							UNION
							SELECT  56 as DefaultPayElementId
						)
						AND PYM.ID=@rPayrollId AND PY.Id=@rPayrollYearId AND PPE.EmployeeId=@rEmployeeId
						GROUP BY PPE.EmployeeId,PE.PayElementDefaultId,PEM.PayElementId,PE.TITLE

						UPDATE @TableIncome SET Amount=Amount + (SELECT ISNULL(Amount,0) FROM @TableIncome WHERE  PayElementDefaultId=56) WHERE  PayElementDefaultId=54
						--UPDATE @TableIncome SET Amount=Amount + (2000) WHERE  PayElementDefaultId=52
						DELETE FROM @TableIncome WHERE  PayElementDefaultId=56
						
						--INSERT INTO @TableIncomeTaxSlab
						--SELECT ITSG.Id AS IncomeTaxSubgroupId,ITSG.DefaultPayElementId,ISNULL(Details.NetAmount,0)NetAmount,ISNULL(Details.Amount,0)Amount
						--FROM [siTax].[tStaticIncomeTaxSubGroup]  AS ITSG
						--LEFT JOIN (
						--SELECT * FROM (SELECT PE.PayElementDefaultId,SUM(PPE.TotalEarning) AS NetAmount,SUM(ISNULL(PEM.Amount,0))Amount
						--FROM sPayroll.tPayProcessEmployee AS PPE 
						--INNER JOIN sPayroll.tPayProcess AS PP ON PP.ID=PPE.PayProcessId
						--INNER JOIN sPayroll.tPayrollGroupMaster  AS PGM ON PGM.ID=PPE.PayrollGroupId
						--INNER JOIN sPayroll.tPayrollMaster AS PYM ON PYM.Id=PGM.PayrollId
						--INNER JOIN sPayroll.tPayrollYearMaster AS PY ON PY.Id=PP.PayrollYearId
						--INNER JOIN sPayroll.tPayProcessElement AS PEM ON PEM.PayProcessEmployeeId=PPE.ID
						--INNER JOIN sPayroll.tPayElement AS PE On PE.ID=PEM.PayElementId AND PE.PayrollId=PYM.ID
						--INNER JOIN sPayroll.tPayElementDefault AS PPDE ON PPDE.id=PE.PayElementDefaultId
						--WHERE PE.PayElementDefaultId in (SELECT DefaultPayElementId FROM [siTax].[tStaticIncomeTaxSubGroup] WHERE ISNULL(DefaultPayElementId,0)<>0)
						--AND PYM.ID=@rPayrollId AND PY.Id=@rPayrollYearId AND PPE.EmployeeId=@rEmployeeId
						--GROUP BY PPE.EmployeeId,PE.PayElementDefaultId,PEM.PayElementId,PE.TITLE) AS Details
						--) AS  Details ON Details.PayElementDefaultId=ITSG.DefaultPayElementId
						--WHERE ISNULL(ITSG.DefaultPayElementId,0)<>0

						INSERT INTO @TableIncomeTaxSlab
						SELECT ITSG.Id AS IncomeTaxSubgroupId,ITSG.DefaultPayElementId,ISNULL(Details.NetAmount,0)NetAmount,ISNULL(Details.Amount,0)Amount
						FROM [siTax].[tStaticIncomeTaxSubGroup]  AS ITSG
						LEFT JOIN (
						SELECT * FROM (SELECT * FROM @TableIncome) AS Details
						) AS  Details ON Details.PayElementDefaultId=ITSG.DefaultPayElementId
						WHERE ISNULL(ITSG.DefaultPayElementId,0)<>0



						
						SELECT @Count=COUNT(1) FROM @TableIncomeTaxSlab
						SELECT TOP 1 @NetAmount=  MAX(NetAmount) FROM @TableIncomeTaxSlab WHERE NetAmount<>0 
						
						

							IF NOT EXISTS(SELECT 1 FROM [siTax].[tForm16] WHERE EmployeeId=@rEmployeeId AND AssesmentYearId=@rAssesmentYearId and OrgGroupId=@rOrgGroupId)
								BEGIN
								    
									EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'siTax.tForm16', 0, 1, 1,@outNextNumber = @lNextNumber output
									
									INSERT INTO  [siTax].[tForm16]  (Id,EmployeeId,AssesmentYearId,IsObsolete,CreatedUserId,CreatedDateTime,OrgGroupId)
									
									VALUES (@lNextNumber,@rEmployeeId,@rAssesmentYearId,0,@rCreatedUserId,getdate(),@rOrgGroupId)

									INSERT INTO  [siTax].[tForm16Detail] (Form16Id,IncomeTaxSubgroupId,GrossAmount,QualifyingAmount,DeductibleAmount,IsObsolete,CreatedUserId,CreatedDateTime)
									
									SELECT @lNextNumber,StaticIncomeTaxSubGroupId,0,0,0,0,@rCreatedUserId,getdate() 
									FROM [siTax].[tIncomeTaxSubGroup] 
									WHERE 
										AssesmentYearId=@rAssesmentYearId and OrgGroupId=@rOrgGroupId
									

								END
							ELSE
								BEGIN
									SELECT @lNextNumber=Id 
									FROM [siTax].[tForm16] 
									WHERE 
										EmployeeId=@rEmployeeId AND AssesmentYearId=@rAssesmentYearId and OrgGroupId=@rOrgGroupId
								END


							UPDATE [siTax].[tForm16Detail] SET GrossAmount=ISNULL(@NetAmount,0) WHERE Form16Id=@lNextNumber AND IncomeTaxSubgroupId=1
							WHILE (@Count>@Counter)
							BEGIN
								 SET @Counter=@Counter+1	
								 DECLARE 	@IncomeTaxSubgroupId int=0
								 DECLARE 	@Amount DECIMAL(18,2)=0
								 
								 SELECT @IncomeTaxSubgroupId=IncomeTaxSubgroupId,@Amount=Amount   
								 FROM @TableIncomeTaxSlab 
								 WHERE RowID=@Counter
								 UPDATE [siTax].[tForm16Detail] 
								 SET GrossAmount=@Amount
								 WHERE 
									 Form16Id=@lNextNumber 
									 AND IncomeTaxSubgroupId=@IncomeTaxSubgroupId
								 
							END
							--UPDATE [siTax].[tForm16Detail] SET GrossAmount=GrossAmount + (SELECT ISNULL(SUM(Amount),0) FROM [siTax].[tIncomeTaxChallan] WHERE  AssesmentYearId=@rAssesmentYearId and EmployeeId=@rEmployeeId AND IsObsolete=0) 
							--WHERE Form16Id=@lNextNumber AND IncomeTaxSubgroupId=@IncomeTaxSubgroupId
							

							SELECT 1 as Result

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


GO
ALTER PROCEDURE [sOp].[pGatewayConfigurationAdd]
	
	@rId int,
	@rOrgGroupId smallint,
	@rPaymentGatewayId smallint,
	@rGatewayURL nvarchar(1000),
	@rServerPort nvarchar(50),
	@rLoginId nvarchar(50),
	@rLoginPassword nvarchar(50),
	@rProductId nvarchar(100),
	@rTermsCondition nvarchar(max)='',
	@rPrivacyPolicy nvarchar(max)='',
	@rPaymentPolicy nvarchar(max)='',
	@rDisclaimer nvarchar(max)=''
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	BEGIN TRY
	BEGIN TRANSACTION	
	
	DECLARE @lNextNumber INT     
	IF(@rId = 0)	
	BEGIN
		
		EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sOp.tGatewayConfiguration', 0, 1, 1,@outNextNumber = @lNextNumber output

		INSERT INTO sOp.tGatewayConfiguration
			(
				Id,
				OrgGroupId,
				PaymentGatewayId,
				GatewayURL,
				ServerPort,
				LoginId,
				LoginPassword,
				ProductId,
				TermsCondition,
				PrivacyPolicy,
				PaymentPolicy,
				Disclaimer
			)
		VALUES
			(
				@lNextNumber,
				@rOrgGroupId,
				@rPaymentGatewayId,
				@rGatewayURL,
				@rServerPort,
				@rLoginId,
				@rLoginPassword,
				@rProductId,
				@rTermsCondition,
				@rPrivacyPolicy,
				@rPaymentPolicy,
				@rDisclaimer
			)

	END 
	ELSE
	BEGIN

		SET @lNextNumber = @rId
	    UPDATE  sOp.tGatewayConfiguration
	    SET
			PaymentGatewayId=@rPaymentGatewayId,
			GatewayURL=@rGatewayURL,
			ServerPort=@rServerPort,
			LoginId=@rLoginId,
			LoginPassword=@rLoginPassword,
			ProductId=@rProductId,
			TermsCondition=@rTermsCondition,
			PrivacyPolicy=@rPrivacyPolicy,
			PaymentPolicy=@rPaymentPolicy,
			Disclaimer=@rDisclaimer
	     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 [sOp].[pGatewayConfigurationGet]...';


GO
ALTER PROCEDURE [sOp].[pGatewayConfigurationGet]
	 
	 @rOrgGroupId smallint
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			
BEGIN 
	SELECT
			ISNULL(GC.Id,0) AS Id,
			GC.OrgGroupId,
			GC.PaymentGatewayId,
			GC.GatewayURL,
			GC.ServerPort,
			GC.LoginId,
			GC.LoginPassword,
			GC.ProductId,
			ISNULL(TermsCondition,'') AS TermsCondition,
			ISNULL(PrivacyPolicy,'') AS PrivacyPolicy,
			ISNULL(PaymentPolicy,'') AS PaymentPolicy,
			ISNULL(Disclaimer,'') AS Disclaimer
	FROM
			sOp.tGatewayConfiguration GC
	WHERE 
			GC.OrgGroupId=@rOrgGroupId
END
GO
PRINT N'Altering [sSecurity].[pDashletGet]...';


GO


ALTER PROCEDURE [sSecurity].[pDashletGet]
	@rOrgGroupId int=0,
	@rDate date='',
	@rDashletId int=0,
	@rOrgGroupBatchId int=0,
	@rUserId bigint=0,
	@rUserSourceId bigint=0,
	@rUserSourceTypeId int=0,
	@rOrgId Int=0,
	@rSourceTypeId smallint=0,
	@rSourceId bigint=0,
	@rBatchId int=0,
	@rExamId int=0
	
									
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
BEGIN
if(@rDashletId='1')
       BEGIN
        exec sCommunication.pCircularListGet @rUserSourceId=@rUserSourceId,@rOrgGroupBatchId=@rOrgGroupBatchId,@rUserSourceTypeId=@rUserSourceTypeId,@rUserId=@rUserId,@rStartDate=@rDate
        END
 if(@rDashletId='2')
        BEGIN
        SELECT  N.Id,N.Title FROM sCommunication.tNews N WHERE N.OrgGroupBatchId=@rOrgGroupBatchId AND Convert(date,N.CreatedDateTime)=convert(date,getdate())
        END
 if(@rDashletId='3')
          BEGIN
        exec sActivity.pMyEventGet @rSourceTypeId=@rSourceTypeId,@rSourceId=@rSourceId,@rOrgId=@rOrgId,@rBatchId=@rBatchId,@rFromDate=@rDate,@rToDate=@rDate
          END
if(@rDashletId='4')
        BEGIN
        exec sCommunication.pAssignTaskGet @rId=0,@rOrgId=@rOrgId,@rCreatedUserId=@rUserId,@rIsAssignTaskToMe=1,@rStatus=0,@rIsSearch=1
        END
 if(@rDashletId='5')
        BEGIN
        exec sCommunication.pAssignTaskGet @rId=0,@rOrgId=@rOrgId,@rCreatedUserId=@rUserId,@rIsAssignTaskToMe=0,@rStatus=0,@rIsSearch=1
        END
 if(@rDashletId='6')
        BEGIN
       
        SELECT 	EM.FirstName + ' ' + EM.MiddleName + ' ' + EM.LastName AS Name,	EM.DepartmentName  FROM [sHrm].[vExtEmployeeMaster] EM	
        WHERE  	EM.OrgId = @rOrgId  
         AND (MONTH(EM.DateOfBirth) = CAST(MONTH(GETDATE()) AS varchar(2))) AND EM.DateOfBirth!='' AND EM.StatusId=7
	    AND (DAY(EM.DateOfBirth) = CAST(DAY(GETDATE()) AS varchar(2)))   
		
        END
 if(@rDashletId='7')
        BEGIN
        SELECT SC.FirstName + ' ' + SC.MiddleName + ' ' + SC.LastName AS Name, SC.ClassName+' '+SC.DivisionName AS ClassName FROM sStudent.vStudentAllDetail SC WHERE SC.OrgId=@rOrgId AND SC.BatchId=@rBatchId
         AND (MONTH(SC.DateOfBirth) = CAST(MONTH(GETDATE()) AS varchar(2))) AND SC.DateOfBirth!='' AND SC.StatusId=1
	    AND (DAY(SC.DateOfBirth) = CAST(DAY(GETDATE()) AS varchar(2)))   
        END
         if(@rDashletId='10')
        BEGIN
       exec sAttendance.pDashletAttendanceStatusGet @rAcademicId=@rSourceId
        END
   
   if(@rDashletId='11')
        BEGIN
        exec [sHrm].[pLeaveListingGet] @rOrgId=@rOrgId,@rEmployeeId=@rUserSourceId,@rLeaveTypeId=0,@rOrgGroupBatchId=@rOrgGroupBatchId,@rFromDate=@rDate,@rTodate=''
        END
   if(@rDashletId='12')
        BEGIN
     exec sCommunication.pPollGet @rOrgGroupBatchId=@rOrgGroupBatchId,@rSourceTypeId=@rUserSourceTypeId,@rCreatedUserId=@rUserId,@rCreatedDateTime=@rDate
        END
  if(@rDashletId='14')
       BEGIN
        exec sCommunication.pMyBookGet @rReaderSourceTypeId=@rUserSourceTypeId,@rReaderSourceId=@rUserSourceId,@rBatchId=@rBatchId

        END
  if(@rDashletId='16')
        BEGIN
      exec [sFee].[pRptFeeReceiptTotalGet] @rFromDate=@rDate,@rToDate=@rDate,@rOrgGroupBatchId=@rOrgGroupBatchId
        END
      
  if(@rDashletId='17')
        BEGIN
      exec [sFee].[pFeeDueAlertGet] @rSourceId=@rSourceId,@rSourceTypeId=@rSourceTypeId,@rBatchId=@rBatchId

        END
  if(@rDashletId='18')
        BEGIN
     exec sCommunication.pBlogGet @rId=0,@rOrgGroupBatchId=@rOrgGroupBatchId,@rTitle=NULL,@rCreatedUserId=0,@rOrgId=@rOrgId,@rCreatedDateTime=@rDate
        END
 if(@rDashletId='19')
        BEGIN
     exec sAssessment.pStudentResultGet @rAcademicId=@rSourceId,@rStudentId=@rUserSourceId,@rBatchId=@rBatchId,@rExamId=@rExamId
     END
  if(@rDashletId='21')
       BEGIN
       SELECT vCD.ClassDivisionName,ISNULL(EM.FirstName+' '+ EM.LastName,'') AS ClassTeacherName,CASE WHEN COUNT(SR.AcademicId)=0 THEN 'Pending' ELSE 'Complete' END AS PresentStatus
        FROM sStudent.tAcademic A INNER JOIN sSetup.vClassDivision vCD ON vCD.ClassId=A.ClassId 
       AND vCD.DivisionId=A.DivisionId AND A.OrgId=vCD.OrgId AND A.OrgId=@rOrgId  AND A.BatchId=@rBatchId AND vCD.IsObsolete=0 
       INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vCD.DivisionId LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId 
       LEFT JOIN sAttendance.tStudentRegister SR ON A.Id = SR.AcademicId AND SR.AttendanceTypeId = 1 
       AND SR.IsPresent=1 AND SR.AttendanceDate=@rDate GROUP BY A.DivisionId,A.BatchId,vCD.ClassDivisionName,vCD.OrderIndex,EM.FirstName,EM.LastName ORDER BY vCD.OrderIndex
         END
  if(@rDashletId='22')
       BEGIN
        SELECT VL.Id,VL.VisitorName, VL.NoOfVisitor, VL.WhomToMeetName FROM sFrontOffice.tVisitorLog VL  INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=VL.OrgId 
        WHERE VL.OrgId=@rOrgId AND VL.VisitDate=@rDate ORDER BY VL.VisitDate DESC,VL.InTime DESC
        END
  if(@rDashletId='23')
       BEGIN
        SELECT DispatchedTo, DispatchedCity  FROM sFrontOffice.tCourierDispatch  WHERE OrgGroupId=@rOrgGroupId AND DispatchDate=@rDate  AND @rDashletId='23' ORDER BY DispatchDate
        END
    if(@rDashletId='24')
       BEGIN
        SELECT ReceiveFrom, ReceiveFor  FROM  sFrontOffice.tCourierReceive  WHERE OrgGroupId=@rOrgGroupId  AND ReceiveDate=@rDate  AND @rDashletId='24' ORDER BY ReceiveDate
    END
     if(@rDashletId='25')
        BEGIN
     SELECT ISNULL(Ps.LectureNumber,'') AS LactureNumber,PS.EmployeeId,ISNULL(SMT.Title,'') AS Subject,ISNULL(EM1.FirstName,'') + ' '+ISNULL(EM1.LastName,'') AS EmployeeName,ISNULL(Em.FirstName,'') + ' '+ISNULL(Em.LastName,'') AS ProxyEmployeeName, ISNULL(DV.Code,'') AS ClassDivisionName,ISNULL(SM.Title,'') AS ProxySubject from sTimetable.tProxySetting PS 
     INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = PS.SubjectId INNER JOIN sCommon.tDayMaster DM ON DM.Id = PS.DayId INNER JOIN sSetup.tDivisionMaster DV ON DV.Id = PS.DivisionId
     INNER JOIN sTimetable.tTimeTable TT ON TT.Id=PS.TimeTableId 
     INNER JOIN sSetup.tSubjectMaster SMT ON SMT.Id = TT.SubjectId 
     INNER JOIN sHrm.tEmployeeMaster EM1  ON TT.EmployeeId=EM1.Id 
     INNER JOIN sHrm.tEmployeeMaster Em ON Em.Id = PS.EmployeeId  WHERE PS.ProxyDate=@rDate AND PS.BatchId=@rBatchId AND ((PS.EmployeeId=@rSourceId) OR (@rSourceId=0))  ORDER BY PS.ProxyDate
        END
  END
GO
PRINT N'Altering [sSecurity].[pIpPolicyAdd]...';


GO
 
ALTER PROCEDURE [sSecurity].[pIpPolicyAdd]
	 
        @rId int,
        @rTitle nvarchar(100),
        @rRemark nvarchar(300),
        @rIsObsolete bit,
        @rCreatedUserId bigint,
        @rOrgGroupId smallint,
        @rIpPolicyDetailXml nvarchar(max)
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

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

BEGIN
	--BEGIN TRY
	
	IF(@rId = 0)	
	BEGIN
		IF EXISTS (SELECT 1 FROM sSecurity.tIpPolicy WHERE Title=@rTitle AND OrgGroupId=@rOrgGroupId)
		BEGIN SELECT -101 AS Result RETURN END 
	END
	ELSE
	BEGIN
		IF EXISTS (SELECT 1 FROM sSecurity.tIpPolicy WHERE Title=@rTitle AND OrgGroupId=@rOrgGroupId AND Id<>@rId)
		BEGIN SELECT -101 AS Result RETURN END
	END
	
	--BEGIN TRANSACTION	
	DECLARE @lNextNumber int 

	IF(@rId = 0)	
	BEGIN
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sSecurity.tIpPolicy', 0, 1, 1,@outNextNumber = @lNextNumber output
	INSERT INTO sSecurity.tIpPolicy
		(Id,Title,Remark,IsObsolete,CreatedUserId,CreatedDateTime,OrgGroupId)
	VALUES
		(@lNextNumber,@rTitle,@rRemark,@rIsObsolete,@rCreatedUserId,sCommon.fGetDate(),@rOrgGroupId)
	
	    INSERT INTO sSecurity.tIpPolicyDetail
			(IpPolicyId,IP)
		SELECT @lNextNumber,IP
		FROM OPENXML (@loDoc, '/Table/IpPolicyDetail', 1)
		WITH (IP nvarchar(100)) 	
		
		SELECT 1 AS Result
	END	 
	ELSE
	BEGIN
	SET @lNextNumber = @rId
	UPDATE sSecurity.tIpPolicy
	SET Title=@rTitle,Remark=@rRemark,IsObsolete=@rIsObsolete,UpdatedUserId=@rCreatedUserId,UpdatedDateTime=sCommon.fGetDate()
	WHERE Id = @rId AND OrgGroupId= @rOrgGroupId
	
	DELETE sSecurity.tIpPolicyDetail WHERE IpPolicyId= @rId
	INSERT INTO sSecurity.tIpPolicyDetail
		(IpPolicyId,IP)
	SELECT @lNextNumber,IP
	FROM OPENXML (@loDoc, '/Table/IpPolicyDetail', 1)
	WITH (IP nvarchar(100)) 
	
	SELECT 11 AS Result
	END  	
--	COMMIT TRANSACTION		
--	END TRY
--	BEGIN CATCH 
--		ROLLBACK TRANSACTION
--		SELECT -1 AS Result
--	END CATCH	
END
GO
PRINT N'Altering [sSecurity].[pModulePermissionAdd]...';


GO
ALTER PROCEDURE [sSecurity].[pModulePermissionAdd]
          
            @rOrgGroupId smallint,
            @rXML nvarchar(max) ,
            @rModuleGroupId tinyint=0
 
AS
SET NOCOUNT ON
DECLARE @lInterrorCode INT
--Declare @Sql nvarchar(max) 
DECLARE @loDoc INT


BEGIN
	
		BEGIN TRY
	
	 BEGIN TRANSACTION	
	
	EXEC sp_xml_preparedocument @loDoc OUTPUT,@rXML
	CREATE TABLE #ListofData(ModuleId int,IsPermission bit,OrgGroupId int)
	insert into #ListofData
		select E.ModuleId,E.IsPermission,E.OrgGroupId
		from
		(
				SELECT ModuleId,IsPermission,OrgGroupId FROM
				OPENXML (@loDoc, '/Modules/Module', 2)
				WITH (
						ModuleId int, 
						IsPermission bit,
						OrgGroupId int)	
						)E 		
	

	--DELETE FROM sSecurity.tModulePermission WHERE OrgGroupId=@rOrgGroupId
    DELETE MP FROM sSecurity.tModulePermission  MP
	INNER JOIN sCommon.tModuleMaster MM ON MM.Id=MP.ModuleId
	LEFT JOIN sCommon.tModuleGroupMaster MG ON MG.Id=MM.ModuleGroupId 
	WHERE MP.OrgGroupId=@rOrgGroupId AND ((MM.ModuleGroupId=@rMOduleGroupId) OR (isnull(@rMOduleGroupId,0)=0))
	
	
	--DELETE FROM sSecurity.tOrganizationTask WHERE OrgGroupId=@rOrgGroupId AND 
	--TaskId IN(SELECT TaskId From sSecurity.tTask WHERE 
	--	ModuleId IN(SELECT ModuleId FROM #ListofData WHERE IsPermission = 0))
		
	--DELETE FROM sSecurity.tPermission WHERE OrgGroupId=@rOrgGroupId AND 
	--TaskId IN(SELECT TaskId From sSecurity.tTask WHERE 
	--	ModuleId IN(SELECT ModuleId FROM #ListofData WHERE IsPermission = 0))
		
	INSERT INTO sSecurity.tModulePermission 
	SELECT OrgGroupId,ModuleId FROM #ListofData WHERE IsPermission=1 
	--Exec sp_executesql @sql
	Drop Table #ListofData
	--INSERT INTO sSecurity.tModulePermission
 --          (
 --           [OrgId],
 --           ModuleId            
 --          )
 --    VALUES
 --          (
 --            @rOrgId,
 --            @rModuleId     
 --          )
 
	 SELECT 1 AS Result
	COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
	
END
GO
PRINT N'Altering [sSecurity].[pModulePermissionGet]...';


GO
ALTER PROCEDURE [sSecurity].[pModulePermissionGet]
          
        @rOrgGroupId int,
        @rMOduleGroupId tinyint=0
        
          
 
AS
SET NOCOUNT ON

BEGIN
  Select MM.Id,MM.Title AS ModuleName,(CASE WHEN MP.ModuleId IS NULL THEN 'False'
        ELSE 'True' END) AS Selected,ISNULL(MP.OrgGroupId,0) AS OrgGroupId ,ISNULL(MG.Title,'') AS ModuleGroup   from sCommon.tModuleMaster MM
LEFT JOIN sSecurity.tmodulepermission MP ON MP.ModuleId = MM.Id AND MP.OrgGroupId = @rOrgGroupId
INNER JOIN sCommon.tModuleGroupMaster MG ON MG.Id=MM.ModuleGroupId
WHERE MM.IsObsolete = 0 
AND ((MM.ModuleGroupId=@rMOduleGroupId) or (isnull(@rMOduleGroupId,0)=0))
order by MM.Title
END
GO
PRINT N'Altering [sSecurity].[pUserFavoriteScreenGet]...';


GO
ALTER PROCEDURE [sSecurity].[pUserFavoriteScreenGet]
	
	@rUserId [bigint]
	 
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN  
      SELECT  
           UserId,
           FavoriteScreenId AS FavoraiteScreenId,
           S.Title AS UserFavoraiteScreen,
           --CASE WHEN S.ScreenTypeId = 1 THEN S.Page
           --ELSE S.Page + '?MenuID=' +CONVERT(Nvarchar(50),M.Id) END AS PagePath,
            CASE WHEN S.ScreenTypeId = 1 THEN  S.Page + '?MenuID=' +CONVERT(Nvarchar(50),(SELECT Id FROM sSecurity.tMenu M WHERE M.ScreenId = U.FavoriteScreenId AND M.IsObsolete = 0)) 
           ELSE S.Page  END AS PagePath,
           T.ResourceTypeId 
                       
      FROM
 	  sSecurity.tUserFavoriteScreen U INNER JOIN sSecurity.tScreen S ON U.FavoriteScreenId = S.Id  
 	  --INNER JOIN sSecurity.tMenu M On M.ScreenId = S.Id
 	  INNER JOIN sSecurity.tTask T ON S.TaskId = T.Id
		 
	  where UserId = @rUserId
		 
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

DECLARE @lTimePolicyId int
DECLARE @lIpPolicyId int
DECLARE @lAccessTime nvarchar(300)

DECLARE @lTimePolicy TABLE(Id int identity, AccessTime nvarchar(100))
DECLARE @lIpPolicyDetail TABLE(IP nvarchar(100))

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
			
			SELECT 
				@lTimePolicyId = TimePolicyId ,@lIpPolicyId = IpPolicyId 
			FROM sSecurity.tUserPolicy 
				WHERE  UserId = @lUserId
			
			IF(@lTimePolicyId IS NOT NULL AND @lTimePolicyId !=0)	
			BEGIN
				SELECT @lAccessTime = AccessTime FROM sSecurity.tTimePolicy	WHERE  Id = @lTimePolicyId
				INSERT @lTimePolicy SELECT * FROM sCommon.fnSplit(@lAccessTime,',')
				DECLARE @lCount int 
				SELECT @lCount = COUNT(AccessTime) FROM @lTimePolicy
				DECLARE @LoopCounter INT = 1
				
				DECLARE @lIsValid bit = 0
				
				WHILE (@LoopCounter <= @lCount)
				BEGIN
						
					DECLARE @lTime nvarchar(100)
					SELECT @lTime = AccessTime FROM @lTimePolicy WHERE Id = @LoopCounter
					DECLARE @lFromTime nvarchar(100)
					DECLARE @lToTime nvarchar(100)
					SELECT @lFromTime = SUBSTRING(@lTime, 1, 5 )
					SELECT @lToTime = SUBSTRING(@lTime, 7, 10 )
					IF(CONVERT(time,getdate()) BETWEEN CONVERT(time,@lFromTime) AND CONVERT(time,@lToTime))
					BEGIN	
						SET @lIsValid = 1
					END 
					ELSE IF(@lIsValid=0)
					BEGIN 
						RAISERROR('Not allowed due to time policy constrain', 16, 1)
						RETURN
					END 
					 SET @LoopCounter  = @LoopCounter  + 1
				END
			END
			
			IF(@lIpPolicyId IS NOT NULL AND @lIpPolicyId !=0)	
			BEGIN
				INSERT @lIpPolicyDetail SELECT IP FROM sSecurity.tIpPolicyDetail WHERE  IpPolicyId = @lIpPolicyId
				IF NOT EXISTS (SELECT 1 FROM @lIpPolicyDetail WHERE IP = @rHostAddress)
				BEGIN 
					RAISERROR('Not allowed due to ip policy constrain', 16, 1)
					RETURN
				END
			END
			
			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 > 250
						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 user.', 16, 1)		
		END
END
GO
PRINT N'Altering [sStudent].[pIDNoGenerationGet]...';


GO
ALTER PROCEDURE [sStudent].[pIDNoGenerationGet]
	 
	 @rClassID int,
	 @rDivisionId int,
	 @rRecordStatusId smallint,
	 @rOrgId smallint,
	 @rBatchId int

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	SELECT 
			SO.AcademicId,
			SO.StudentId,
			SO.GenderId,
			SO.ClassId,
			SO.DivisionId,
			SO.RecordStatusId,
			SO.RollNo AS RollNo,
			SO.Code,
			SO.Number,
			SO.FirstName,
			SO.LastName,
			[sStudent].[fStudentNameGet](SO.FirstName , SO.MiddleName, So.LastName,OM.StudentNameFormatId ) AS Name,
			SO.ClassName+'-'+SO.DivisionName AS ClassDivisionName
  FROM 
			[sStudent].[vStudentOther]  SO
			INNER JOIN sSetup.tOrganizationMaster OM
			ON SO.OrgId = OM.Id
		
  WHERE 
			(SO.ClassId=@rClassId OR @rClassId=0)
			AND (SO.DivisionId=@rDivisionId OR @rDivisionId=0)
			AND (SO.RecordStatusId=@rRecordStatusId OR @rRecordStatusId=0)
			AND SO.BatchId=@rBatchId
			AND SO.OrgId=@rOrgId order by SO.DivisionId,SO.RollNo
END
GO
PRINT N'Altering [sStudent].[pImportStudent]...';


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

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
BEGIN TRY

DECLARE @lCount INT
DECLARE @lInterrorCode INT,
			@intDoc INT,
			@lCode nvarchar(20),
			@lNumber bigint,
			@lRegistrationNumber nvarchar(20),
			@lFirstName nvarchar(100),
			@lMiddleName nvarchar(100),
			@lLastName nvarchar(100),
			@lClassId int,
			@lClass nvarchar(100),
			@lDivisionId int,
			@lDivision nvarchar(100),
			@lRollNo int,
			@lAdmissionStandardId int,
			@lAdmissionStandard nvarchar(100),
			@lAdmissionDate date,
			@lPreviousSchool nvarchar(200),
			@lDOB date,
			@lGenderId int = 0,
			@lGender nvarchar(10),
			@lBloodGroupId int = 0,
			@lBloodGroup nvarchar(10),
			@lAdmissionCategoryId int,
			--@lAdmissionCategory nvarchar(100),
			@lReligionId int,
			@lReligion nvarchar(100),
			@lFamilyCast nvarchar(100),
			@lFamilySubCast nvarchar(100),
			@lCastCategoryId int = 0,
			@lCastCategory nvarchar(100),
			@lParentContactNo nvarchar(20),
			@lParentEmail nvarchar(50),
			@lStudentContactNo nvarchar(20),
			@lStudentEmail nvarchar(50),
			@lPresentStreetOne nvarchar(150),
			@lPresentStreetTwo nvarchar(150),
			@lPresentStreetThree nvarchar(150),
			@lPresentCity nvarchar(50),
			@lPresentZipCode nvarchar(20),
			@lPresentState nvarchar(50),
			@lPresentCountry nvarchar(50),
			@lPresentContactNo nvarchar(20),
			--@lEmergencyStreetOne nvarchar(50),
			--@lEmergencyStreetTwo nvarchar(50),
			--@lEmergencyStreetThree nvarchar(50),
			--@lEmergencyCountry nvarchar(50),
			--@lEmergencyState nvarchar(50),
			--@lEmergencyCity nvarchar(50),
			--@lEmergencyZipCode nvarchar(20),
			@lEmergencyContactNo nvarchar(20),
			@lBirthPlace nvarchar(150),
			@lBirthTaluka nvarchar(150),
			@lBirthDistrict nvarchar(150),
			@lBirthDateInWord nvarchar(150),
			@lHouseId int,
			@lHouse nvarchar(100),
			--@lMotherTongueId int,
			@lMotherTongue nvarchar(100),
			@lAdhaarNumber nvarchar(20),
			@lUIDNumber nvarchar(50),
			@lQuotaId int,
			@lQuota nvarchar(100),
			-- New Add
			@lSUId nvarchar(20),
			@lLeftStandardId int,
			@lLeftStandard nvarchar(100),
			@lLeftDate date,
			@lLCNumber nvarchar(20),
			@lLCDate date,
			@lLCReason nvarchar(200) ,
			@lLCProgress nvarchar(200) ,
            @lLCConduct nvarchar(200) ,
            @lLCRemark nvarchar(200),
            @lStatusId smallint


			
			
DECLARE @EmployeeId bigint			
--DECLARE @OutClassId int
--DECLARE @OutDivisionId int
DECLARE @OutStudentId bigint 
--DECLARE @OutAdmissionStandardId int
--DECLARE @OutReligionId int
--DECLARE @OutAdmissionCategoryId int		
SET @lAdmissionCategoryId=sCommon.fGetIntIdForOrg(1,@rOrgGroupId)	
			
EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc
	
	CREATE TABLE #tTable  
	(
		Id bigint identity,	 
		Code nvarchar(20),
		Number bigint,
		RegistrationNumber nvarchar(20),
		FirstName nvarchar(100),
		MiddleName nvarchar(100),
		LastName nvarchar(100),
		ClassId int null,
		Class nvarchar(100),
		DivisionId int null,
		Division nvarchar(100),
		RollNo int,
		AdmissionStandardId int,
		AdmissionStandard nvarchar(100),
		AdmissionDate date,
		PreviousSchool nvarchar(200),
		DOB date,
		GenderId int null,
		Gender nvarchar(10),
		BloodGroupId int null,
		BloodGroup nvarchar(10),
		ReligionId int,
		Religion nvarchar(100),
		--AdmissionCategoryId int,
		--AdmissionCategory nvarchar(100),
		FamilyCast nvarchar(100),
		FamilySubCast nvarchar(100),
		CastCategoryId int,
		CastCategory nvarchar(100),
		ParentContactNo nvarchar(20),
		ParentEmail nvarchar(50),
		StudentContactNo nvarchar(20),
		StudentEmail nvarchar(50),
		PresentStreetOne nvarchar(150),
		PresentStreetTwo nvarchar(150),
		PresentStreetThree nvarchar(150),
		PresentCity nvarchar(50),
		PresentZipCode nvarchar(20),
		PresentState nvarchar(50),
		PresentCountry nvarchar(50),
		PresentContactNo nvarchar(20),
		--EmergencyStreetOne nvarchar(50),
		--EmergencyStreetTwo nvarchar(50),
		--EmergencyStreetThree nvarchar(50),
		--EmergencyCountry nvarchar(50),
		--EmergencyState nvarchar(50),
		--EmergencyCity nvarchar(50),
		--EmergencyZipCode nvarchar(20),
		EmergencyContactNo nvarchar(20),
		BirthPlace nvarchar(150),
		BirthTaluka nvarchar(150),
		BirthDistrict nvarchar(150),
		BirthDateInWord nvarchar(150),
		CreatedUserId bigint,
		HouseId int,
		House nvarchar(100),
		MotherTongueId int,
		MotherTongue nvarchar(100),
		AdhaarNumber nvarchar(20),
		UIDNumber nvarchar(20),
		QuotaId int,
		Quota nvarchar(100),
		SUId nvarchar(20),
		LeftStandardId int,
		LeftStandard nvarchar(100),
		LeftDate date,
		LCNumber nvarchar(20),
		LCDate date,
		LCReason nvarchar(200) ,
		LCProgress nvarchar(200) ,
        LCConduct nvarchar(200) ,
        LCRemark nvarchar(200),
        StatusId smallint
	)
		
	INSERT INTO #tTable
	(
		Code,
		Number,
		RegistrationNumber,
		FirstName,
		MiddleName,
		LastName,
		ClassId,
		Class,
		DivisionId,
		Division,
		RollNo,
		AdmissionStandardId,
		AdmissionStandard,
		AdmissionDate,
		PreviousSchool,
		DOB,
		GenderId,
		Gender,
		BloodGroupId,
		BloodGroup,
		ReligionId,
		Religion,
		--AdmissionCategoryId,
		--AdmissionCategory,
		FamilyCast,
		FamilySubCast,
		CastCategoryId,
		CastCategory,
		ParentContactNo,
		ParentEmail,
		StudentContactNo,
		StudentEmail,
		PresentStreetOne,
		PresentStreetTwo,
		PresentStreetThree,
		PresentCity,
		PresentZipCode,
		PresentState,
		PresentCountry,
		PresentContactNo,
		--EmergencyStreetOne,
		--EmergencyStreetTwo,
		--EmergencyStreetThree,
		--EmergencyCountry,
		--EmergencyState,
		--EmergencyCity,
		--EmergencyZipCode,
		EmergencyContactNo,
		BirthPlace,
		BirthTaluka,
		BirthDistrict,
		BirthDateInWord,
		CreatedUserId,
		HouseId,
		House,
		MotherTongueId,
		MotherTongue,
		AdhaarNumber,
		UIDNumber,
		QuotaId,
		Quota,
		SUId,
		LeftStandardId,
		LeftStandard,
		LeftDate,
		LCNumber,
		LCDate,
		LCReason,
		LCProgress,
        LCConduct,
        LCRemark,
        StatusId
	)
	SELECT
	 
		Code,
		Number,
		RegistrationNumber,
		FirstName,
		MiddleName,
		LastName,
		0,
		Class,
		0,
		Division,
		RollNo,
		0,
		AdmissionStandard,
		AdmissionDate,
		PreviousSchool,
		DOB,
		0,
		Gender,
		0,
		BloodGroup,
		0,
		Religion,
		--0,
		--AdmissionCategory,
		FamilyCast,
		FamilySubCast,
		0,
		CastCategory,
		ParentContactNo,
		ParentEmail,
		StudentContactNo,
		StudentEmail,
		PresentStreetOne,
		PresentStreetTwo,
		PresentStreetThree,
		PresentCity,
		PresentZipCode,
		PresentState,
		PresentCountry,
		PresentContactNo,
		--EmergencyStreetOne,
		--EmergencyStreetTwo,
		--EmergencyStreetThree,
		--EmergencyCountry,
		--EmergencyState,
		--EmergencyCity,
		--EmergencyZipCode,
		EmergencyContactNo,
		BirthPlace,
		BirthTaluka,
		BirthDistrict,
		BirthDateInWord,
		CreatedUserId,
		0,
		House,
		0,
		MotherTongue,
		AdhaarNumber,
		UIDNumber,
		0,
		Quota,
		SUId,
		0,
		LeftStandard,
		LeftDate,
		LCNumber,
		LCDate,
		LCReason,
		LCProgress,
        LCConduct,
        LCRemark,
        StatusId
			
	FROM OPENXML (@intDoc, '/Table/ImportStudent', 1)
	WITH
	( 
		Code nvarchar(20) '@Code',
		Number bigint '@Number',
		RegistrationNumber nvarchar(20) '@RegistrationNumber',
		FirstName nvarchar(100) '@FirstName',
		MiddleName nvarchar(100) '@MiddleName',
		LastName nvarchar(100) '@LastName',
		Class nvarchar(100) '@Class',
		Division nvarchar(100) '@Division',
		RollNo int '@RollNo',
		AdmissionStandard nvarchar(100) '@AdmissionStandard',
		AdmissionDate date '@AdmissionDate',
		PreviousSchool nvarchar(200) '@PreviousSchool',
		DOB date '@DOB',
		Gender nvarchar(10) '@Gender',
		BloodGroup nvarchar(10) '@BloodGroup', 			
		Religion nvarchar(100) '@Religion',
		--AdmissionCategory nvarchar(100) '@AdmissionCategory',
		FamilyCast nvarchar(100) '@FamilyCast',
		FamilySubCast nvarchar(100) '@FamilySubCast',
		CastCategory nvarchar(100) '@CastCategory',
		ParentContactNo nvarchar(20) '@ParentContactNo',
		ParentEmail nvarchar(50) '@ParentEmail',
		StudentContactNo nvarchar(20) '@StudentContactNo',
		StudentEmail nvarchar(50) '@StudentEmail',
		PresentStreetOne nvarchar(150) '@PresentStreetOne',
		PresentStreetTwo nvarchar(150) '@PresentStreetTwo',
		PresentStreetThree nvarchar(150) '@PresentStreetThree',
		PresentCity nvarchar(50) '@PresentCity',
		PresentZipCode nvarchar(20) '@PresentZipCode',
		PresentState nvarchar(50) '@PresentState',
		PresentCountry nvarchar(50) '@PresentCountry',
		PresentContactNo nvarchar(20) '@PresentContactNo',
		--EmergencyStreetOne nvarchar(50) '@EmergencyStreetOne',
		--EmergencyStreetTwo nvarchar(50) '@EmergencyStreetTwo',
		--EmergencyStreetThree nvarchar(50) '@EmergencyStreetThree',
		--EmergencyCountry nvarchar(50) '@EmergencyCountry',
		--EmergencyState nvarchar(50) '@EmergencyState',
		--EmergencyCity nvarchar(50) '@EmergencyCity',
		--EmergencyZipCode nvarchar(20) '@EmergencyZipCode',
		EmergencyContactNo nvarchar(20) '@EmergencyContactNo',
		 
		BirthPlace nvarchar(150) '@BirthPlace',
		BirthTaluka nvarchar(150) '@BirthTaluka',
		BirthDistrict nvarchar(150) '@BirthDistrict',		
		BirthDateInWord nvarchar(150) '@BirthDateInWord',
		CreatedUserId bigint '@CreatedUserId',
		House nvarchar(100) '@House',
		MotherTongue nvarchar(100) '@MotherTongue',
		AdhaarNumber nvarchar(20) '@AdhaarNumber',
		UIDNumber nvarchar(20) '@UIDNumber',
		Quota nvarchar(20) '@Quota',
		SUId nvarchar(20) '@SUId',
		LeftStandard nvarchar(100) '@LeftStandard',
		LeftDate date '@LeftDate',
		LCNumber nvarchar(20) '@LCNumber',
		LCDate date '@LCDate',
		LCReason nvarchar(200) '@LCReason',
		LCProgress nvarchar(200) '@LCProgress',
        LCConduct nvarchar(200) '@LCConduct',
        LCRemark nvarchar(200) '@LCRemark',
        StatusId smallint '@StatusId'
	)
	
	--print 'check'
 
EXEC sp_xml_removedocument @intDoc
			
SELECT @lCount =  COUNT(Id) FROM #tTable

WHILE @lCount > 0 

BEGIN
		SET @lCode = ''
		SET @lNumber = null
		SET @lRegistrationNumber = null
		SET @lFirstName = ''
		SET @lMiddleName = ''
		SET @lLastName = ''
		SET @lClassId = null
		SET @lClass = ''
		SET @lDivisionId = null
		SET @lDivision = ''
		SET @lRollNo = null
		SET @lAdmissionStandardId = null
		SET @lAdmissionStandard = ''
		SET @lAdmissionDate  = ''
		SET @lPreviousSchool = ''
		SET @lDOB = ''
		SET @lGenderId = null
		SET @lGender = ''
		SET @lBloodGroupId = null
		SET @lBloodGroup = ''
		SET @lReligionId  = null
		SET @lReligion = ''
		--SET @lAdmissionCategoryId  = null
		--SET @lAdmissionCategory = ''
		SET @lFamilyCast = ''
		SET @lFamilySubCast = ''
		SET @lCastCategoryId  = null
		SET @lCastCategory = ''
		SET @lParentContactNo = ''
		SET @lParentEmail = ''
		SET @lStudentContactNo = ''
		SET @lStudentEmail = ''
		SET @lPresentStreetOne = ''
		SET @lPresentStreetTwo = ''
		SET @lPresentStreetThree = ''
		SET @lPresentCity = ''
		SET @lPresentZipCode = ''
		SET @lPresentState = ''
		SET @lPresentCountry = ''
		SET @lPresentContactNo = ''
		--SET @lEmergencyStreetOne = ''
		--SET @lEmergencyStreetTwo = ''
		--SET @lEmergencyStreetThree = ''
		--SET @lEmergencyCountry = ''
		--SET @lEmergencyState = ''
		--SET @lEmergencyCity = ''
		--SET @lEmergencyZipCode = ''
		SET @lEmergencyContactNo = ''
		SET @lBirthPlace = ''
		SET @lBirthTaluka = ''
		SET @lBirthDistrict = ''
		SET @lBirthDateInWord = ''
		--SET @OutClassId = null
		--SET @OutDivisionId = null
		SET @OutStudentId = null
		--SET @OutAdmissionStandardId = null
		--SET @OutReligionId = null,
		SET @lHouseId=NULL
		SET	@lHouse=''
		--SET @lMotherTongueId=NULL
		SET	@lMotherTongue=''
		SET	@lAdhaarNumber=''
		SET @lUIDNumber=''
		SET @lQuotaId = NULL
		SET	@lQuota =''
		SET	@lSUId =''
		SET	@lLeftStandardId=NULL
		SET	@lLeftStandard = ''
		SET	@lLeftDate = ''
		SET	@lLCNumber = ''
		SET	@lLCDate = ''
		SET	@lLCReason = ''
		SET	@lLCProgress = ''
        SET	@lLCConduct = ''
        SET	@lLCRemark = ''
        SET @lStatusId = NULL
		
SELECT		
		@lCode = Code,
		@lNumber=Number,
		@lRegistrationNumber = RegistrationNumber,
		@lFirstName = FirstName,
		@lMiddleName = MiddleName,
		@lLastName = LastName,
		@lClass = Class,
		@lDivision = Division,
		@lRollNo = RollNo,
		@lAdmissionStandard = AdmissionStandard,
		@lAdmissionDate  = CASE WHEN AdmissionDate = '' THEN  NULL ELSE AdmissionDate END,
		@lPreviousSchool = PreviousSchool,
		@lReligion = Religion,
		--@lAdmissionCategory = AdmissionCategory,
		@lFamilyCast = FamilyCast,
		@lFamilySubCast = FamilySubCast,
		@lCastCategory = CastCategory,
		@lDOB = CASE WHEN DOB = '' THEN  NULL ELSE DOB END,
		@lGender = Gender,
		@lBloodGroup = BloodGroup,
		@lParentContactNo = ParentContactNo,
		@lParentEmail = ParentEmail,
		@lStudentContactNo = StudentContactNo,
		@lStudentEmail = StudentEmail,
		@lPresentStreetOne = PresentStreetOne,
		@lPresentStreetTwo = PresentStreetTwo,
		@lPresentStreetThree = PresentStreetThree,
		@lPresentCountry = PresentCountry,
		@lPresentState = PresentState,
		@lPresentCity = PresentCity,
		@lPresentZipCode = PresentZipCode,
		@lPresentContactNo = PresentContactNo,
		--@lEmergencyStreetOne = EmergencyStreetOne,
		--@lEmergencyStreetTwo = EmergencyStreetTwo,
		--@lEmergencyStreetThree = EmergencyStreetThree,
		--@lEmergencyCountry = EmergencyCountry,
		--@lEmergencyState = EmergencyState,
		--@lEmergencyCity = EmergencyCity,
		--@lEmergencyZipCode = EmergencyZipCode,
		@lEmergencyContactNo = EmergencyContactNo,		 
		@lBirthPlace = BirthPlace,
		@lBirthTaluka = BirthTaluka,
		@lBirthDistrict = BirthDistrict,
		@lBirthDateInWord = BirthDateInWord,
		@lHouse = House,
		@lMotherTongue = MotherTongue,
		@lAdhaarNumber = AdhaarNumber,
		@lUIDNumber = UIDNumber,
		@lSUId = SUId,
		@lLeftStandard = LeftStandard,
		@lLeftDate = CASE WHEN LeftDate = '' THEN  NULL ELSE LeftDate END,
		@lLCNumber = LCNumber,
		@lLCDate = CASE WHEN LCDate = '' THEN  NULL ELSE LCDate END,
		@lLCReason = LCReason,
		@lLCProgress = LCProgress,
        @lLCConduct = LCConduct,
        @lLCRemark = LCRemark,
        @lStatusId = StatusId
											 	 
FROM #tTable WHERE Id = @lCount  

	SELECT	@lGenderId = ID FROM sCommon.tGenderMaster WHERE Title = @lGender
	SELECT	@lLeftStandardId  = ID FROM sSetup.tClassMaster WHERE Title = @lLeftStandard AND OrgId = @rOrgId
	SELECT	@lClassId  = ID FROM sSetup.tClassMaster WHERE Title = @lClass AND OrgId = @rOrgId
	SELECT	@lDivisionId  = ID FROM sSetup.tDivisionMaster WHERE Title = @lDivision AND ClassId=@lClassId AND OrgId = @rOrgId
	SELECT	@lBloodGroupId  = ID FROM sCommon.tBloodGroupMaster WHERE Title = @lBloodGroup
	SELECT	@lAdmissionStandardId  = ID FROM sSetup.tClassMaster WHERE Title = @lAdmissionStandard AND OrgId = @rOrgId
	SELECT	@lReligionId  = ID FROM sCommon.tReligionMaster WHERE Title = @lReligion AND OrgGroupId = @rOrgGroupId
	--SELECT	@lAdmissionCategoryId  = ID FROM tAdmissionCategoryMaster WHERE Title = @lAdmissionCategory AND OrgGroupId = @rOrgGroupId
	SELECT	@lCastCategoryId  = ID FROM sCommon.tCastCategoryMaster WHERE Title = @lCastCategory AND OrgGroupId = @rOrgGroupId	
	SELECT	@lHouseId  = ID FROM sActivity.tHouseMaster WHERE Title = @lHouse AND OrgId = @rOrgId
	SELECT	@lQuotaId  = ID FROM sCommon.tQuotaMaster WHERE Title = @lQuota AND OrgGroupId = @rOrgGroupId	
	--SELECT	@lMotherTongueId  = ID FROM sCommon.tMotherTongueMaster WHERE Title = @lMotherTongue
	
	IF(@lGenderId IS NULL)
		SET @lGenderId = 0
	IF(@lBloodGroupId IS NULL)
		SET	@lBloodGroupId = 0
	IF(@lCastCategoryId IS NULL)
		SET	@lCastCategoryId = 0
	IF(@lHouseId IS NULL)
		SET	@lHouseId = 0
	IF(@lQuotaId IS NULL)
		SET	@lQuotaId = 0	
	--IF(@lMotherTongueId IS NULL)
	--	SET	@lMotherTongueId = 0		
		
--IF 	@lClassId IS NULL  AND @lClass != ''
--BEGIN
--	EXEC [sSetup].[pClassMasterAdd] 0,@lClass,@lClass,@lClass,@lClass,1,0,0,0,@rUserId,@rUserId,@rOrgId,@OutClassId OUTPUT
-- END
--ELSE
--BEGIN
--SET @OutClassId = @lClassId
--END

--IF 	@lAdmissionStandardId IS NULL  AND @lAdmissionStandard != ''
--BEGIN
--	EXEC [sSetup].[pClassMasterAdd] 0,@lAdmissionStandard,@lAdmissionStandard,@lAdmissionStandard,@lAdmissionStandard,1,0,0,0,@rUserId,@rUserId,@rOrgId,0,@OutAdmissionStandardId OUTPUT
-- END
--ELSE
--BEGIN
--SET @OutAdmissionStandardId = @lAdmissionStandardId
--END

--IF 	@lDivisionId IS NULL  AND @lDivision != ''
--BEGIN
--	SET @EmployeeId = sCommon.fGetBigIntIdForOrg(1,@rOrgId)
--	EXEC [sSetup].[pDivisionMasterAdd] 0,@lDivision,@lDivision,@lDivision,@lClassId,@EmployeeId,NULL,0,@rUserId,@rUserId,0,@rOrgId,@OutDivisionId OUTPUT
-- END
--ELSE
--BEGIN
--SET @OutDivisionId = @lDivisionId
--END

--IF 	@lReligionId IS NULL  AND @lReligion != ''
--BEGIN
--	EXEC [sCommon].[pReligionMasterAdd] 0,@lReligion,@lReligion,0,@rUserId,@rOrgId,@OutReligionId OUTPUT
-- END
--ELSE
--BEGIN
--SET @OutReligionId = @lReligionId
--END

--IF 	@lAdmissionCategoryId IS NULL  AND @lAdmissionCategory != ''
--BEGIN
--	EXEC [sStudent].[pAdmissionCategoryMasterAdd] 0,@lAdmissionCategory,@lAdmissionCategory,0,@rUserId,@rOrgId,@OutAdmissionCategoryId OUTPUT
-- END
--ELSE
--BEGIN
--SET @OutAdmissionCategoryId = @lAdmissionCategoryId
--END

BEGIN TRANSACTION

IF(@lStatusId=1)
	EXEC sStudent.pStudentMasterAdd 0,@lCode,@lRegistrationNumber,@lNumber,@lFirstName,@lMiddleName,@lLastName,@rOrgId,@lAdmissionCategoryId,1,502,@rUserId,@rUserId,@OutStudentId OUTPUT,@lSUId
ELSE
	EXEC sStudent.pStudentMasterAdd 0,@lCode,@lRegistrationNumber,@lNumber,@lFirstName,@lMiddleName,@lLastName,@rOrgId,@lAdmissionCategoryId,3,502,@rUserId,@rUserId,@OutStudentId OUTPUT,@lSUId

EXEC sStudent.pAcademicAdd 0,@OutStudentId,@lClassId,@lDivisionId,@lRollNo,@rOrgId,@rBatchId,@rUserId,@rUserId

EXEC sStudent.pStudentCommunicationAdd @OutStudentId,@lPresentStreetOne,@lPresentStreetTwo,@lPresentStreetThree,
			@lPresentCountry,@lPresentState,@lPresentCity,@lPresentZipCode,@lPresentContactNo,NULL,NULL,NULL,NULL,NULL,
			NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,@lEmergencyContactNo,@lParentContactNo,@lParentEmail,
			@lStudentContactNo,@lStudentEmail,@rUserId,@rUserId

EXEC sStudent.pStudentOtherAdd @OutStudentId,@lUIDNumber,@lDOB,@lGenderId,@lReligionId,@lBloodGroupId,@lBirthPlace,@lBirthTaluka,@lBirthDistrict,@lBirthDateInWord,
			@lFamilyCast,@lFamilySubCast,@lCastCategoryId,NULL,@lHouseId,NULL,NULL,'',@rUserId,@rUserId,'',@lAdhaarNumber,@lMotherTongue,@lQuotaId

IF(@lStatusId=1)		
	EXEC [sStudent].[pStudentAdmissionAdd] @OutStudentId,@lPreviousSchool,NULL,NULL,NULL,NULL,
			@lAdmissionStandardId,@lAdmissionDate,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,
			NULL,NULL,NULL,NULL,NULL,@rBatchId,@rUserId,@rUserId,1
ELSE
	EXEC [sStudent].[pStudentAdmissionAdd] @OutStudentId,@lPreviousSchool,NULL,NULL,NULL,NULL,
			@lAdmissionStandardId,@lAdmissionDate,NULL,@lLeftStandardId,@lLeftDate,NULL,NULL,NULL,@lLCReason,@lLCProgress,@lLCConduct,NULL,
			@lLCNumber,@lLCDate,@lLCRemark,NULL,NULL,@rBatchId,@rUserId,@rUserId,0
			

		SET @lCount = @lCount - 1	
		COMMIT TRANSACTION			
END


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


GO
ALTER PROCEDURE [sStudent].[pMyClassGet]
	 
	 @rSourceId bigint,
	 @rOrgId int,
	 @rBatchId int
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
DECLARE @lDivisionId int
BEGIN 

SELECT @lDivisionId=DivisionId From sStudent.tAcademic Where StudentId=@rSourceId AND OrgId=@rOrgId AND BatchId=@rBatchId
	
		SELECT
				vSF.AcademicId,
				vSF.Name,
				vSF.ClassName+ ' - '+vSF.DivisionName AS ClassDiv,
				vSF.RollNo,
				ISNULL(vSF.StudentPhoto,0) AS StudentPhoto,
				ISNULL(vSF.ParentContactNo,'') ParentContactNo
		FROM 
				sStudent.vStudentFull vSF
		WHERE 
		
		(vSF.OrgId=@rOrgId)
		AND (vSF.BatchId=@rBatchId)
		AND (vSF.DivisionId=@lDivisionId)
		AND (vSF.StatusId=1)
		
		Order by vSF.RollNo
END
GO
PRINT N'Altering [sStudent].[pStudentCommunicationAdd]...';


GO
ALTER PROCEDURE [sStudent].[pStudentCommunicationAdd]
	 
	@rStudentId bigint,
	@rPresentStreetOne nvarchar(150),
	@rPresentStreetTwo nvarchar(150),
	@rPresentStreetThree nvarchar(150),
	@rPresentCountry nvarchar(50),
	@rPresentState nvarchar(50),
	@rPresentCity nvarchar(50),
	@rPresentZipCode nvarchar(20),
	@rPresentContactNo nvarchar(20),
	@rPermanentStreetOne nvarchar(150),
	@rPermanentStreetTwo nvarchar(150),
	@rPermanentStreetThree nvarchar(150),
	@rPermanentCountry nvarchar(50),
	@rPermanentState nvarchar(50),
	@rPermanentCity nvarchar(50),
	@rPermanentZipCode nvarchar(20),
	@rPermanentContactNo nvarchar(20),
	@rEmergencyStreetOne nvarchar(150),
	@rEmergencyStreetTwo nvarchar(150),
	@rEmergencyStreetThree nvarchar(150),
	@rEmergencyCountry nvarchar(50),
	@rEmergencyState nvarchar(50),
	@rEmergencyCity nvarchar(50),
	@rEmergencyZipCode nvarchar(20),
	@rEmergencyContactNo nvarchar(20),
	@rParentContactNo nvarchar(20),
	@rParentEmail nvarchar(50),
	@rStudentContactNo nvarchar(20),
	@rStudentEmail nvarchar(50),
	@rCreatedUserId bigint,
	@rUpdatedUserId bigint,
	@rPresentDistanceFromSchool decimal(10,2)=0
	
	
	
	
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
IF NOT EXISTS(SELECT * FROM sStudent.tStudentCommunication WHERE StudentId = @rStudentId)
BEGIN

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


	INSERT INTO sStudent.tStudentCommunication
		(
			StudentId, 
			PresentStreetOne,
			PresentStreetTwo,
			PresentStreetThree,
			PresentCountry,
			PresentState,
			PresentCity,
			PresentZipCode,
			PresentContactNo,
			PermanentStreetOne,
			PermanentStreetTwo,
			PermanentStreetThree,
			PermanentCountry,
			PermanentState,
			PermanentCity,
			PermanentZipCode,
			PermanentContactNo,
			EmergencyStreetOne,
			EmergencyStreetTwo,
			EmergencyStreetThree,
			EmergencyCountry,
			EmergencyState,
			EmergencyCity,
			EmergencyZipCode,
			EmergencyContactNo,
			ParentContactNo,
			ParentEmail,
			StudentContactNo,
			StudentEmail,
			CreatedUserId,
			CreatedDateTime,
			PresentDistanceFromSchool
			
		)
	VALUES
		(
			@rStudentId,
			@rPresentStreetOne,
			@rPresentStreetTwo,
			@rPresentStreetThree,
			@rPresentCountry,
			@rPresentState,
			@rPresentCity,
			@rPresentZipCode,
			@rPresentContactNo,
			@rPermanentStreetOne,
			@rPermanentStreetTwo,
			@rPermanentStreetThree,
			@rPermanentCountry,
			@rPermanentState,
			@rPermanentCity,
			@rPermanentZipCode,
			@rPermanentContactNo,
			@rEmergencyStreetOne,
			@rEmergencyStreetTwo,
			@rEmergencyStreetThree,
			@rEmergencyCountry,
			@rEmergencyState,
			@rEmergencyCity,
			@rEmergencyZipCode,
			@rEmergencyContactNo,
			@rParentContactNo,
			@rParentEmail,
			@rStudentContactNo,
			@rStudentEmail,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rPresentDistanceFromSchool
	
			
		)
		SELECT 1 AS Result             
	END	 
	 ELSE
	 BEGIN
	 --SET @lNextNumber = @rStudentId
	    UPDATE  sStudent.tStudentCommunication
	    SET
			StudentId=@rStudentId,
			PresentStreetOne=@rPresentStreetOne, 
			PresentStreetTwo=@rPresentStreetTwo, 
			PresentStreetThree=@rPresentStreetThree,
			PresentCountry=@rPresentCountry,
			PresentState=@rPresentState,
			PresentCity=@rPresentCity,
			PresentZipCode=@rPresentZipCode,
			PresentContactNo=@rPresentContactNo,
			PermanentStreetOne=@rPermanentStreetOne,
			PermanentStreetTwo=@rPermanentStreetTwo,
			PermanentStreetThree=@rPermanentStreetThree,
			PermanentCountry=@rPermanentCountry,
			PermanentState=@rPermanentState,
			PermanentCity=@rPermanentCity,
			PermanentZipCode=@rPermanentZipCode,
			PermanentContactNo=@rPermanentContactNo,
			EmergencyStreetOne=@rEmergencyStreetOne,
			EmergencyStreetTwo=@rEmergencyStreetTwo,
			EmergencyStreetThree=@rEmergencyStreetThree,
			EmergencyCountry=@rEmergencyCountry,
			EmergencyState=@rEmergencyState,
			EmergencyCity=@rEmergencyCity,
			EmergencyZipCode=@rEmergencyZipCode,
			EmergencyContactNo=@rEmergencyContactNo,
			ParentContactNo=@rParentContactNo,
			ParentEmail=@rParentEmail,
			StudentContactNo=@rStudentContactNo,
			StudentEmail=@rStudentEmail,
			UpdatedUserId=@rUpdatedUserId,
			UpdatedDateTime=sCommon.fGetDate(),
			PresentDistanceFromSchool=@rPresentDistanceFromSchool
			
	      
	      
	      WHERE StudentId = @rStudentId 	
	      
	 END  
		SELECT 11 AS Result
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sStudent].[pStudentCommunicationGet]...';


GO
ALTER PROCEDURE [sStudent].[pStudentCommunicationGet]
	 
	 @rStudentId bigint
	 
	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 
			SC.StudentId, 
			SC.PresentStreetOne,
			SC.PresentStreetTwo,
			SC.PresentStreetThree,
			SC.PresentCountry,
			SC.PresentState,
			SC.PresentCity,
			SC.PresentZipCode,
			SC.PresentContactNo,
			SC.PermanentStreetOne,
			SC.PermanentStreetTwo,
			SC.PermanentStreetThree,
			SC.PermanentCountry,
			SC.PermanentState,
			SC.PermanentCity,
			SC.PermanentZipCode,
			SC.PermanentContactNo,
			SC.EmergencyStreetOne,
			SC.EmergencyStreetTwo,
			SC.EmergencyStreetThree,
			SC.EmergencyCountry,
			SC.EmergencyState,
			SC.EmergencyCity,
			SC.EmergencyZipCode,
			SC.EmergencyContactNo,
			SC.ParentContactNo,
			SC.ParentEmail,
			SC.StudentContactNo,
			SC.StudentEmail,
			isnull(SC.PresentDistanceFromSchool,0) AS PresentDistanceFromSchool
			
			
			
      
  FROM 
          sStudent.tStudentCommunication SC
             
  WHERE 
		(SC.StudentId = @rStudentId)
		--	((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 [sStudent].[pStudentFamilyAdd]...';


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

	 


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


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

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

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


GO

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


GO

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

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

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


GO

ALTER PROCEDURE [sStudent].[pStudentImportGet]
	 
	@rClassId int=0,
	@rDivisionId int=0,
	@rOrgId int,
	@rBatchId int,
	@rStatusId int=0
	
	
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

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

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


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

BEGIN 	 
		BEGIN
			SET @rCode= sCommon.fSearchStringGet(@rCode)
			SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
			SET @rLastName = sCommon.fSearchStringGet(@rLastName)
		END
 
	SELECT 
			
			SA.AcademicId,
			SA.StudentId,
			 
			SA.ClassId,
			Sa.MiddleName,
			ISNULL(SA.AdmissionDate,'')As AdmissionDate,
			SA.PreviousSchool,
			ISNULL(SA.DateOfBirth,'') As DateOfBirth,
			SA.BirthPlace,
			SA.Gender,
			SA.FamilyCast,
			SA.CastCatagory AS CasteCategory,
			SA.MotherTongue,
			SA.Nationality,
			Sa.FatherName,
			SA.FatherContactNo,
			SA.Mothername,
			SA.MotherContactNo,
			SA.PresentStreetOne,
			SA.PresentStreetTwo,
			SA.PresentStreetThree,
			ISNULL(SA.StudentContactNo,'')As StudentContactNo,
			SA.UIDNumber,
			SA.AdhaarNumber,
			SA.BankBranch,
			SA.BankAccountNumber,
			SA.BankName,
			SA.BankIFSCCode,
			SA.DepartmentId,
			SA.FirstName,
			SA.LastName,
			 SA.Name,
			SA.Code,
			SA.ADMISSIONStandardId, 
			SA.DivisionId,
			SA.DivisionName,
			ISNULL(SA.Number,0) AS Number,
			SA.RollNo,
			SA.StatusId,
			--SA.StatusName,
			SA.OrgId,
			--SA.Age,
			ISNULL(SA.AdmissionCategoryId,0) AS AdmissionCategoryId,
			SA.Religion,
			SA.StudentEmail,
			SA.Name,
			(select  Title  from sSetup.tClassMaster where OrgId=@rOrgId AND id=SA.ADMISSIONStandardId  ) As AdmissionStandard,
			SA.ClassName
  FROM 
          sStudent.vStudentVerification SA  
          
  WHERE 
 
		((SA.ClassId=@rClassId)OR(@rClassId=0))
		AND((SA.DivisionId=@rDivisionId)OR(@rDivisionId=0))
		AND((SA.Code like @rCode) OR (ISNULL(@rCode,'') = '')) 
		AND((SA.FirstName like @rFirstName) OR (ISNULL(@rFirstName,'') = '')) 
		AND((SA.LastName like @rLastName) OR (ISNULL(@rLastName,'') = '')) 
		AND((SA.StatusId=@rStatusId)OR(@rStatusId=0))	
		AND(SA.OrgId=@rOrgId OR @rOrgId = 0)
		AND (OrgGroupBatchId = @rOrgGroupBatchId	or @rOrgGroupBatchId = 0)	
		AND(SA.BatchId=@rBatchId or @rBatchId = 0)
		AND(SA.DepartmentId=@rDepartmentId or @rDepartmentId = 0)
		and ((sa.RollNO=@rRollNO)OR(@rRollNo=0))
		--AND((SA.Number=@rNumber)OR(@rNumber=0))	

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


GO
ALTER PROCEDURE [sStudent].[pStudentVerificationUpdate]
	 
	@rAdmissionDate date='',
	@rPreviousSchool nvarchar(50)='',
	@rStudentId bigint,
	@rDateOfBirth date,
	@rBirthPlace nvarchar(150),
	@rFamilyCast nvarchar(100),
	@rMotherTongue nvarchar(100),
	@rUIDNumber nvarchar(50),
	@rAdhaarNumber nvarchar(20),
	@rFatherContactNo nvarchar(10),
	@rMotherName nvarchar(50),
	@rMotherContactNo nvarchar(10),
	@rStudentContactNo nvarchar(10),
	@rBankBranch nvarchar(100),
	@rBankAccountNumber nvarchar(20),
	@rBankName nvarchar(100),
	@rBankIFSCCode nvarchar(20),
	@rGenderId int,
	@rClassId int=0,
	@rCastCategoryId int,
	
	@rNationalityId int,
	@rPresentStreetOne nvarchar(300),
	@rPresentStreetTwo nvarchar(300),
	@rPresentStreetThree nvarchar(300),
	@rReligionId int,
	@rFirstName nvarchar(50),
	@rMiddleName nvarchar(50),
	@rLastName nvarchar(50),
	@rStudentEmail nvarchar(50),
	@rAdmissionStandardId int,
	@rFatherName nvarchar(50)
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON			 

BEGIN 	 
		update sStudent.tStudentMaster Set FirstName=@rFirstName,MiddleName=@rMiddleName,LastName=@rLastName Where Id=@rStudentId
		Update sStudent.tStudentAdmission Set AdmissionDate=@rAdmissionDate,PreviousSchool=@rPreviousSchool,AdmissionStandardId=@rAdmissionStandardId  Where StudentId =@rStudentId
		Update sStudent.tStudentOther Set DateOfBirth=@rDateOfBirth,BirthPlace=@rBirthPlace,FamilyCast=@rFamilyCast,MotherTongue=@rMotherTongue,UIDNumber=@rUIDNumber,AdhaarNumber=@rAdhaarNumber,GenderId=@rGenderId,CastCategoryId =@rCastCategoryId,NationalityId=@rNationalityId,ReligionId=@rReligionId Where StudentId=@rStudentId
		 
		 Update sStudent.tStudentFamily  Set FatherContactNo=@rFatherContactNo,MotherName=@rMotherName,MotherContactNo=@rMotherContactNo,FatherName=@rFatherName where StudentId=@rStudentId
		 Update sStudent.tStudentCommunication Set StudentContactNo=@rStudentContactNo,PresentStreetOne=@rPresentStreetOne,PresentStreetTwo=@rPresentStreetTwo,PresentStreetThree=@rPresentStreetThree,StudentEmail=@rStudentEmail Where StudentId=@rStudentId
		 update  sStudent.tStudentAdditional Set BankBranch=@rBankBranch,BankAccountNumber=@rBankAccountNumber,BankName=@rBankName,BankIFSCCode=@rBankIFSCCode where StudentId=@rStudentId
END
GO
PRINT N'Altering [sStudent].[pStudentViewProfileGet]...';


GO

ALTER PROCEDURE [sStudent].[pStudentViewProfileGet]
	 
	 @rBatchId int,
	 @rAcademicId bigint,
	 @rReportId int=0,
	 @rOrgId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	
	SELECT 
			
			SA.StudentId AS Id,
			SA.FirstName + ' ' + ISNULL(SA.MiddleName,'') + ' ' + 	SA.LastName AS StudentName,
			ISnull(SA.Batch,'') AS AcademicYear,
			ISNULL(SA.Code,' ') AS Code,
			SA.ClassDivision AS ClassDiv,			
			Isnull(SA.RollNo,'') AS RollNo,
			convert(varchar,ISNULL(SA.DateOfBirth,'0001/01/01'),103) AS DateOfBirth,
			ISNULL(SM.Title,'-') AS House,
			ISNULL(SA.BirthTaluka,'') AS BirthTaluka,
			ISNULL(SA.BirthPlace,'') AS BirthPlace,	
			ISNULL(SA.BirthDistrict,'') AS BirthDistrict,
			ISNULL(SA.BirthDateInWord,'') AS BirthDateInWord,                           
			ISNULL(SA.Gender,'') AS Gender,
			ISNULL(SA.Religion,'') AS Religion,
			ISNULL(SA.AdmissionStandard,'') AS AdmissionStandard,
			convert(varchar,ISNULL(SA.AdmissionDate,'0001/01/01'),103) AS AdmissionDate,
			ISNULL(SA.PreviousSchool,'') AS PreviousSchool,
			ISNULL(SA.AdmissionCategory,'') AS StudentAdmissionCategory,
            convert(varchar,ISNULL(SA.LeftDate,'0001/01/01'),103) AS LeftDate,
			ISNULL(SA.LeftStandard,'') AS LeftStandard,
			convert(varchar,ISNULL(SA.InactiveDate,'01/01/0001'),103) AS InactiveDate,
			ISNULL(SA.LCNumber,'') AS LCNumber,
			convert(varchar,ISNULL(SA.LCDate,'01/01/0001'),103) AS LCDate,
			ISNULL(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,
			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,
			ISNULL(SA.BloodGroup,'') AS BloodGroup,
			ISNULL(SH.IdentificationMark1,'')+' '+ISNULL(SH.IdentificationMark2,'') as IdentificationMark,
			ISNULL(SH.FamilyDoctorName,'') AS FamilyDoctorName,
			ISNULL(SH.FamilyDoctorContactNo,'') AS FamilyDoctorContactNo,
			case When isnull(SH.IsPysicalDeformity,0)=0 then 'NO' Else 'Yes' End As IsPysicalDeformity,
			SH.PysicalDeformityRemark ,
			case When isnull(SH.IsMajorIllness,0)=0 then 'NO' Else 'Yes' End As IsMajorIllness,
			ISNULL(SH.MajorIllnessRemark,'') As MajorIllnessRemark,
			 case When isnull(SH.IsAllergy,0)=0 then 'NO' Else 'Yes' End As IsAllergy,
			ISNULL(SH.AllergyRemark,'') As AllergyRemark,
			 case When isnull(SH.IsPastHistory,0)=0 then 'NO' Else 'Yes' End As IsPastHistory,
			ISNULL(SH.PastHistoryRemark,'') As PastHistoryRemark,
			ISNULL(RM.Title,'') AS RoomNo,			
			ISNULL(HM.Title,'') AS Hostel,
			ISNULL(EMW.FirstName,'')+' '+ISNULL(EMW.LastName,'') AS WardenName,
			ISNULL(ECW.PhoneNoCompany,'') As WardenPhoneNo,
			ISNULL(ECW.ExtensionNo,'') AS WardenExtNo,
			ISNULL(ECW.MobileNumber,'') AS WardenMobileNo,
			ISNULL(EMA.FirstName,'')+' '+ISNULL(EMA.LastName,'') AS AssignedRoomBy,	
			ISNULL(ECA.PhoneNoCompany,'') AS AssignedRoomByPhoneNo,
			ISNULL(ECA.ExtensionNo,'') AS AssignedRoomByExtNo,
			ISNULL(ECA.MobileNumber,'') AS AssignedRoomByMobileNo,
			--Notification Details
			ISNULL(SC.ParentEmail,'') AS ParentEmail,
			ISNULL(SC.ParentContactNo,'') As ParentContactNo,
			ISNULL(SC.StudentEmail,'') AS StudentEmail,
			ISNULL(SC.StudentContactNo,'') AS StudentContactNo,
		   ISnull( VM.Title,'') AS VehicleName,
		    ISNULL( VM.RegistrationNumber,'') AS VehicleRegistrationNumber,
		      ISNULL(TV.Title ,'') AS TypeOfVehicle ,
		   ISNULL(BRM.Title,'') AS BusRoute,
		   ISNULL( BRM.DriverName,'') AS DriverName,
		     ISNULL(BRM.DriverMobileNo,'') AS DriverMobileNo,
		   ISNULL( BRM.ConductorName,'') AS ConductorName,
		   ISNULL( BRM.ConductorMobileNo,'') AS ConductorMobileNo ,
		    ISNULL(BRDM.Title,'') AS BusRouteDestination,
		    isnull(VM.Title,'') AS DropVehicleName,
		    isnull(VM.RegistrationNumber,'') AS DropVehicleRegistrationNumber,
		    isnull(TV1.Title,'') AS DropTypeOfVehicle,
		    ISNULL(BRM1.Title,'') AS DropRoute,
		   isnull( BRM1.DriverName,'') AS DropRouteDriverName,
		   isnull(BRM1.DriverMobileNo,'') AS DropRouteDriverMobileNo,
		    isnull(BRM1.ConductorName,'') AS DropRouteConductorName,
		    isnull(BRM1.ConductorMobileNo,'') AS DropRouteConductorMobileNo,
		    ISNULL(BRDM1.Title,'') AS DropDestination,
		   ISNULL( EMT.FirstName+' '+EMT.MiddleName+' '+EMT.LastName,'') AS TeacherFullName,
		    isnull( EDM.Title,'') AS TeacherDesignation,
		   ISNULL( EPD.Qualification,'') AS TeacherQualification,
		    ISNULL(DF.IsDisplayFamilyDetail,0) AS IsDisplayFamilyDetail,
		    ISNULL(DF.IsDisplaySiblingDetail,0) AS IsDisplaySiblingDetail,
		    ISNULL(DF.IsDisplayPassportDetail,0) AS IsDisplayPassportDetail,
		    ISNULL(DF.IsDisplayBankDetail,0) AS IsDisplayBankDetail,
		    ISNULL(DF.IsDisplayCBSEREGDetail,0) AS IsDisplayCBSEREGDetail,
		    ISNULL(DF.IsDisplayCollegeDetail,0) AS IsDisplayCollegeDetail,
		    ISNULL(DF.IsDisplayGOVREGNoDetail,0) AS IsDisplayGOVREGNoDetail,
		    ISNULL(DF.IsDisplayHealthDetail,0) AS IsDisplayHealthDetail,
		    ISNULL(DF.IsDisplayTransportDetail,0) AS IsDisplayTransportDetail,
		    ISNULL(DF.IsDisplayHostelDetail,0) AS IsDisplayHostelDetail,
		    ISNULL(DF.IsDisplayClubDetail,0) AS IsDisplayClubDetail,
		    
		    ISNULL(DF.IsDisplaySSCResultDDetail,0) AS IsDisplaySSCResultDDetail,
		    ISNULL(DF.IsDisplayHSCResultDetail,0) AS IsDisplayHSCResultDetail,
		    ISNULL(DF.IsDisplayJeeDetail,0) AS IsDisplayJeeDetail,
		    ISNULL(DF.IsDisplayDiplomaDetail,0) AS IsDisplayDiplomaDetail,
		
		    isnull(SS.SiblingName1,'') AS SiblingName1,
	        ISNULL (SS.SiblingInstitue1,'') AS SiblingInstitue1,
	        ISNULL(SS.SiblingClass1,'')AS SiblingClass1,
	        ISNULL(SS.SiblingAge1,'')AS SiblingAge1,
	        ISNULL(SS.SiblingRelation1,'')AS SiblingRelation1,
	        isnull(SS.SiblingName2,'') AS SiblingName2,
	        ISNULL(SS.SiblingInstitue2,'')AS SiblingInstitue2,
	        ISNULL(SS.SiblingClass2,'')AS SiblingClass2,
	        ISNULL(SS.SiblingAge2,'') AS SiblingAge2,
	        ISNULL(SS.SiblingRelation2,'')AS SiblingRelation2,
	        isnull(SS.SiblingName3,'') AS SiblingName3,
	        ISNULL( SS.SiblingInstitue3,'')AS SiblingInstitue3,
	        ISNULL(SS.SiblingClass3,'')AS SiblingClass3,
	        ISNULL(SS.SiblingAge3,'')AS SiblingAge3,
	        ISNULL(SS.SiblingRelation3,'')AS SiblingRelation3,
	        ISNULL(SAD.BankAccountNumber,'')AS BankAccountNumber,
	        ISNULL(SAD.BankName,'')AS BankName,
	        ISNULL(SAD.BankBranch,'') AS BankBranch,
	        ISNULL(SAD.BankIFSCCode,'')AS BankIFSCCode,
	        ISNULL(SAD.Class9BoardRegistrationNumber,'') AS Class9BoardRegistrationNumber,
	        ISNULL(SAD.Class11BoardRegistrationNumber,'')AS Class11BoardRegistrationNumber,
	        ISNULL(SAD.PassportNumber,'')AS PassportNumber, 
	        ISNULL(SAD.PassportType,'') AS PassportType,
	       ISNULL( SAD.PassportCountryCode,'') AS PassportCountryCode,
	       	convert(varchar,ISNULL(SAD.PassportExpiryDate,'01/01/0001'),103) AS PassportExpiryDate,
	       	convert(varchar,ISNULL(SAD.PassportIssueDate,'01/01/0001'),103) AS PassportIssueDate,
	      ISNULL(SA.UIDNumber,'')AS UIDNumber,
	      ISNULL(SA.AdhaarNumber,'') AS AdhaarNumber,
	      case When isnull(SA.IsTransfer,0)=0 then 'No' Else 'Yes' End As IsTransfer,
	      ISNULL(SA.TransferFrom,'') AS TransferFrom,
	      ISNULL(SA.CertificateName,'') AS CertificateName,
	       case When isnull(SA.IsTFWS,0)=0 then 'No' Else 'Yes 'End As IsTFWS,
	      case When isnull(SA.IsCertificateHolder,0)=0 then 'No' Else 'Yes' End As IsCertificateHolder,
	       ISNULL(CD.SSCBoard,'') AS SSCBoard,
	       ISNULL(CD.SSCSchool,'') AS SSCSchool,
	       ISNULL(CD.SSCPassingYear,'') AS SSCPassingYear,
	       ISNULL(CD.SSCObtainMarks,0) AS SSCObtainMarks,
	       ISNULL(CD.SSCOutOfMarks,0) AS SSCOutOfMarks,
	       ISNULL(CD.SSCMathMarks,0) AS SSCMathMarks,
	       ISNULL(CD.SSCMathOutOfMarks,0) AS SSCMathOutOfMarks,
	       ISNULL(CD.SSCPercentage,0) AS SSCPercentage,
	       ISNULL(CD.HSCBoard,'') AS HSCBoard,
	       ISNULL(CD.HSCSchool,'') AS HSCSchool,
	       ISNULL(CD.HSCPassingYear,0) AS HSCPassingYear,
	       ISNULL(CD.HSCObtainMarks,0) AS HSCObtainMarks,
	       ISNULL(CD.HSCOutOfMarks,0) AS HSCOutOfMarks,
	       ISNULL(CD.HSCPercentage,0) AS HSCPercentage,
	       ISNULL(CD.HSCPhysicsMarks,0) AS HSCPhysicsMarks,
	       ISNULL(CD.HSCPhysicsOutOfMarks,0) AS HSCPhysicsOutOfMarks,
	       ISNULL(CD.HSCChemistryMarks,0) AS HSCChemistryMarks,
	       ISNULL(CD.HSCChemistryOutOfMarks,0) AS HSCChemistryOutOfMarks,
	       ISNULL(CD.HSCMathMarks,0) AS HSCMathMarks,
	       ISNULL(CD.HSCMathOutOfMarks,0) AS HSCMathOutOfMarks,
	       ISNULL(CD.HSCBiologyMarks,0) AS HSCBiologyMarks,
	       ISNULL(CD.HSCBiologyOutOfMarks,0) AS HSCBiologyOutOfMarks,
	       ISNULL(CD.PCMMarks,0) AS PCMMarks,
	       ISNULL(CD.PCBMarks,0) AS PCBMarks,
	       ISNULL(CD.JEERollNo,'') AS JEERollNo,
	       ISNULL(CD.JEEMeritNo,'') AS JEEMeritNo,
	       ISNULL(CD.JEEMeritMarks,0) AS JEEMeritMarks,
	       ISNULL(CD.JEEOutOfMarks,0) AS JEEOutOfMarks,
	       ISNULL(CD.DiplomaBoard,'') AS DiplomaBoard,
	       ISNULL(CD.DiplomaCollege,'') AS DiplomaCollege,
	       ISNULL(CD.DiplomaPassingYear,'') AS DiplomaPassingYear,
	       ISNULL(CD.DiplomaObtainMarks,0) AS DiplomaObtainMarks,
	       ISNULL(CD.DiplomaOutOfMarks,0) AS DiplomaOutOfMarks,
	       ISNULL(CD.DiplomaPercentage,0) AS DiplomaPercentage,
	      ISNULL(CD.ApplicationNo,'') AS ApplicationNo,
	      ISNULL(CD.AdmissionRound,0) AS AdmissionRound,
           ISNULL(MS.Title,'') AS MaritalStatus,
	      ISNULL(ACD.RepeatCount,1)AS RepeatCount,
	      ISNULL(SO.MotherTongue,'') As MotherTongue,
	      ISNULL(SO.FamilyCast,'') AS FamilyCast,
	      ISNULL(CM.Nationality,'') AS Nationality,
           ISNULL(CT.Title,'') AS CasteCategory,
          --StudentPhoto = case when SA.StudentPhoto is null then '' else SA.StudentPhoto end,
	    StudentPhoto=(SELECT CAST(SA.StudentPhoto as varbinary(max)) FOR XML PATH(''), BINARY BASE64) ,
		TeacherPhoto=(SELECT CAST(EI.EmployeePhoto as varbinary(max)) FOR XML PATH(''), BINARY BASE64) ,
		 FatherPhoto=(SELECT CAST(SA.FatherPhoto as varbinary(max)) FOR XML PATH(''), BINARY BASE64) ,
		MotherPhoto=(SELECT CAST(SA.MotherPhoto as varbinary(max)) FOR XML PATH(''), BINARY BASE64) ,
		RelativePhoto=(SELECT CAST(SA.RelativePhoto as varbinary(max)) FOR XML PATH(''), BINARY BASE64) 
		    
  FROM 
           sStudent.vStudentAllDetail SA
           LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
           LEFT JOIN sStudent.tStudentHealth SH ON SA.StudentId=SH.StudentId
           LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SA.StudentId 
           LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId = SA.StudentId
           LEFT JOIN sActivity.tHouseMaster SM ON SM.ID = SO.HouseId
           LEFT JOIN sHostel.tAssignRoom AR ON AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003
           LEFT JOIN sHostel.tRoomMaster RM ON RM.Id=AR.RoomId
           LEFT JOIN sHostel.tHostelMaster HM ON HM.Id=RM.HostelId 
            LEFT JOIN
            (
		   SELECT 
		   employeeId, 
		   HostelId,   
		   ROW_NUMBER() OVER (PARTITION BY HostelId ORDER By HostelId ) as ROWNo 
		   FROM sHostel.tHostelwarden 
            )  HW ON HW.HostelId=HM.Id AND RowNo = 1       
           --LEFT JOIN sHostel.tHostelWarden HW ON HW.HostelId=HM.Id
           LEFT JOIN sHrm.tEmployeeMaster EMW ON HW.EmployeeId=EMW.Id
           LEFT JOIN sHrm.tEmployeeMaster EMA ON RM.AssignedEmployeeId=EMA.Id
           LEFT JOIN sHrm.tEmployeeCommunications ECW ON EMW.Id=ECW.EmployeeId 
           LEFT JOIN sHrm.tEmployeeCommunications ECA ON  EMA.Id=ECA.EmployeeId
           LEFT JOIN sTransport.tAssignRoute AR1 ON AR1.SourceId=SA.StudentId AND AR1.SourceTypeId=2003
           LEFT JOIN sTransport.tBusRouteDestinationMaster BRDM ON BRDM.Id=AR1.PickupDestinationId
           LEFT JOIN sTransport.tBusRouteMaster BRM ON BRM.Id=BRDM.BusRouteId
           LEFT JOIN sTransport.tVehicleMaster VM ON VM.Id=BRM.VehicleId
           LEFT JOIN sTransport.tVehicleTypeMaster TV ON TV.Id = VM.VehicleTypeId
           LEFT JOIN sTransport.tBusRouteDestinationMaster BRDM1 ON BRDM1.Id=AR1.DropDestinationId
           LEFT JOIN sTransport.tBusRouteMaster BRM1 ON BRM1.Id=BRDM1.BusRouteId
           LEFT JOIN sTransport.tVehicleMaster VM1 ON VM1.Id=BRM1.VehicleId
           LEFT JOIN sTransport.tVehicleTypeMaster TV1 ON TV1.Id = VM1.VehicleTypeId
           LEFT JOIN sSetup.tDivisionMaster DM ON  DM.Id=SA.DivisionId
           LEFT JOIN sHrm.tEmployeeMaster EMT ON EMT.Id=DM.InchargeEmployeeId
           LEFT JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EMT.Id
           LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id=EJD.EmployeeDesignationId
           LEFT JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId=EMT.Id
           LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId=EMT.Id
           LEFT JOIN sStudent.tStudentSibling  SS ON SS.StudentId=SA.StudentId 
           LEFT JOIN sStudent.tStudentAdditional  SAD ON SAD.StudentId=SA.StudentId 
           LEFT JOIN sStudent.tCollegeDetail  CD ON CD.StudentId=SA.StudentId 
           LEFT JOIN sStudent.tAcademicDetail  ACD ON ACD.AcademicId=SA.AcademicId 
           LEFT JOIN sCommon.tMaritalStatusMaster  MS ON MS.Id=CD.MaritalStatusId
           LEFT JOIN sConfig.fDisplayFieldGet(@rOrgId) AS DF ON DF.OrgId=SA.OrgId
           LEFT JOIN sCommon.tCastCategoryMaster CT ON CT.Id = SO.CastCategoryId
           LEFT JOIN sCommon.tCountryMaster CM ON CM.Id=SO.NationalityId
             
  WHERE 
			((SA.AcademicId=@rAcademicId)OR(@rAcademicId=0))
			AND(SA.BatchId=@rBatchId)
		
END
GO
PRINT N'Altering [sTimetable].[pRptTimeTableProxyListGet]...';


GO
 
ALTER PROCEDURE [sTimetable].[pRptTimeTableProxyListGet]
	   
	  @rBatchId int,
	  @rEmployeeId bigint,
	  --@rDayId smallint,
	  --@rLectureNo smallint,
	  @rTimeTableSchemaId int,
	  @rProxyDate date,
	  @rBuilder1 nvarchar(max)='',
	  @rClassId int=0,
	  @rDivisionId int=0
	  
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON 

BEGIN    
	SELECT 	 
	--PS.Id AS ProxySettingId,
	Cm.Title+ '/'+DV.Title AS DivisionName,
	ISNULL(PS.EmployeeId,0) AS EmployeeId,
	ISNULL(PS.SubjectId,0) AS SubjectId,
	ISNULL(Em.FirstName,'') + ' '+ISNULL(em.LastName,'') AS ProxyEmployee,  
	ISNULL(SM.Title,'') AS ProxySubject,
	PS.DivisionId,
	ISNULL(PS.LectureNumber,'') AS LactureNumber,
	ISNULL(DM.Title,'') +'-'+ISNULL(convert(nvarchar(4),Ps.LectureNumber),'') AS DayLacture,
	ISNULL(SMT.Title,'') AS Subject,
	@rBuilder1 AS Builder,
    ISNULL(Em1.FirstName,'') + ' '+ISNULL(EM1.LastName,'') AS Teachername  ,
    EM1.Id As TeacherId,
    SMT.OrderIndex
	
	FROM 
	sTimetable.tProxySetting PS
	INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = PS.SubjectId 
	INNER JOIN sHrm.tEmployeeMaster Em ON Em.Id = PS.EmployeeId
	INNER JOIN sCommon.tDayMaster DM ON DM.Id = PS.DayId
	INNER JOIN sSetup.tDivisionMaster DV ON DV.Id = PS.DivisionId
	INNER JOIN sSetup.tClassMaster CM On CM.Id=DV.ClassId
    INNER JOIN sTimetable.tTimeTable TT  ON TT.Id=PS.TimeTableId
    INNER JOIN sSetup.tSubjectMaster SMT ON SMT.Id = TT.SubjectId 
   INNER JOIN sHrm.tEmployeeMaster EM1  ON TT.EmployeeId=EM1.Id
  

	WHERE 
	    PS.BatchId = @rBatchId  AND  PS.TimeTableSchemaId =@rTimeTableSchemaId
	    AND PS.ProxyDate = @rProxyDate
	    AND ((TT.EmployeeId= @rEmployeeId) OR(@rEmployeeId=0))
	    AND((PS.DivisionId=@rDivisionId) OR (@rDivisionId=0))
	     AND((DV.ClassId=@rClassId) OR (@rClassId=0))
	END
GO
PRINT N'Altering [sTimetable].[pTimeTableAssignDivisionGet]...';


GO

ALTER PROCEDURE [sTimetable].[pTimeTableAssignDivisionGet]
	 
	@rId int	,
	@rOrgId smallint ,
	@rBatchId int=0
    -- @rOrgGroupId  smallint
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
		
BEGIN 
	SELECT
				CM.Title +'-'+ DM.Title AS ClassDivision,
				CM.Id As ClassId,
				DM.Id AS DivisionId,
				 
				 CASE WHEN AD.TimeTableSchemaId IS NULL THEN 'False' ELSE 'True' END AS IsObsolete
	FROM
			sSetup.tDivisionMaster DM 
			INNER JOIN sSetup.tClassMaster CM On CM.Id = DM.ClassId 
			 LEFT JOIN sTimetable.tAssignDivision AD ON AD.DivisionId= DM.Id AND AD.TimeTableSchemaId=@rId
			 INNER JOIN sSetup.tBatchClass BC ON BC.ClassId=CM.Id 
			
			   
	 WHERE
	 	DM.OrgId=@rOrgId 
	 	AND BatchId=@rBatchId
	ORDER BY  CM.OrderIndex,DM.OrderIndex
END
GO
PRINT N'Altering [sTool].[pDeleteStaticData]...';


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

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


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

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

DELETE FROM sAdmission.tInquiryModeMaster

DELETE FROM sFee.tFeeMainGroupMaster

DELETE FROM sPayroll.tPayElementDefault

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


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

DELETE FROM sCommon.tRangeGroupMaster

DELETE FROM sHostel.tLogStatusMaster

DELETE FROM sSetup.tStudentNameFormatMaster

DELETE FROM sCommon.tMainCastCategoryMaster

DELETE FROM sOp.tFunctionalityMaster
DELETE FROM sOp.tPaymentGatewayMaster

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

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

DELETE FROM sActivity.tEventMainTypeMaster
DELETE FROM sAlert.tOSType

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

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

DELETE FROM sCommon.tTemplateSourceMaster
DELETE FROM sErp.tCustomerStatusMaster
DELETE FROM sErp.tInstallationTypeMaster
DELETE FROM sRecruitment.tRecruitmentStatusMaster

DELETE FROM sAssessment.tStaticCCECSMaster
DELETE FROM sAssessment.tStaticCCECSGroupMaster

DELETE FROM siTax.tStaticIncomeTaxGroup
DELETE FROM siTax.tStaticIncomeTaxSubGroup

DELETE FROM sCommon.tImportFieldMaster
DELETE FROM sCRM.tHostingTypeMaster
DELETE FROM sHrm.tMainLeaveTypeMaster

DELETE FROM sAppraisal.tConductIndicatorMaster
DELETE FROM sHrm.tTravelPeriodMaster
DELETE FROM sLoan.tInsterestTypeMaster

DELETE FROM sAppraisal.tBHRatingStatus
DELETE FROM sAppraisal.tConductIndicatorMaster
DELETE FROM sAppraisal.tKPAMeasureMaster
DELETE FROM sAppraisal.tKPATypeMaster
DELETE FROM sAppraisal.tRatingStatus
DELETE FROM sCommon.tHeaderDisplayMaster
DELETE FROM sCommon.tModuleGroupMaster



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


GO





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

BEGIN 


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


GO
ALTER PROCEDURE [sTransport].[pTransportFeeUpdate]
	 
	@rClassId int, 
	@rFeeHeadId int,
	@rCreatedUserId bigint,
	@rOrgId int,
	@rOrgGroupId int,
	@rBatchId int,
	@rIsUpdate bit = 0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION

	CREATE TABLE #TempRouteDestination
	(	Id int IDENTITY,	   
	    AcademicId bigint,
	    PickupDestinationId int,
	    FeeSetupId int,		 
		Amount Decimal(12,2),
		ReceiptAmount  Decimal(12,2)
    )
	 INSERT INTO #TempRouteDestination
	 SELECT	  
	 A.AcademicId,
	 AR.PickupDestinationId,
	 FS.Id,	 
	 BRD.Amount,
	 sFee.fStudentFeeSetupReceiptAmountGet(AcademicId,Fs.Id)
	 FROM sTransport.tAssignRoute AR
	 INNER JOIN sTransport.tBusRouteDestinationMaster  BRD ON AR.PickupDestinationId = BRD.Id 
	 INNER JOIN sStudent.vStudentAcademic A ON AR.SourceId = A.StudentId  
	 INNER JOIN sFee.tFeeSetup FS ON A.ClassId = FS.ClassId AND A.AdmissionCategoryId = FS.AdmissionCategoryId AND FS.BatchId = A.BatchId
	 INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id 
	 INNER JOIN sFee.tFeeHeadMaster FHM ON FM.FeeHeadId = FHM.Id
	 WHERE AR.PickupDestinationId > 0
	 AND FHM.Number = 1001
	 AND FHM.OrgGroupId = @rOrgGroupId
	 AND A.BatchId = @rBatchId
	 AND FS.IsVariable = 1
	 AND FS.IsOptional = 1
	 

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


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

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

--DELETE FROM sFee.tFeeAllocation 

--DELETE FO
--FROM sFee.tFeeAllocation  FO
--RIGHT JOIN #TempRouteDestination RD
--ON FO.FeeSetupId = RD.FeeSetupId AND FO.SourceTypeId = 2001 AND FO.SourceId = RD.AcademicId
--Where  RD.ReceiptAmount = 0



	 
	 --INSERT INTO sFee.tFeeOptional
	 --(
	 --FeeSetupId,
	 --SourceTypeId,
	 --SourceId,
	 --BatchId
	 --)
	 --SELECT FS.Id FROM sFee.tFeeSetup FS
	 --INNER JOIN sFee.tFeeMaster FM
	 --ON FS.FeeId = FM.Id 
	 --INNER JOIN sFee.tFeeHeadMaster FHM
	 --ON FM.FeeHeadId = FHM.Id
	 
	

	--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 
		
		
	--	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)
		
DROP TABLE	#TempRouteDestination
	
		  SELECT 1 AS Result    
		
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Creating [sPoliciesForms].[pFolderFileAdd]...';


GO
/******************************
** Name:  [sPoliciesForms].[pFolderFileAdd]
** Desc:  Insert Record on FolderFile Table
** Auth:  Savan Vaghela
** Date:  3-April-2017
** Page:  /Pages/Hrm/PoliciesForms/FormsMaster.aspx
************************************************************
** Change History
************************************************************
** PR      Date                Author            Description 
**
** 1    3-April-2017      Savan Vaghela       
************************************************************/
--EXEC [sPoliciesForms].[pFolderFileAdd]
CREATE PROCEDURE [sPoliciesForms].[pFolderFileAdd]
	    @rId int,
		@rIsForms Bit,
		@rIsFolder BIT,
		@rTitle nvarchar(200),
		@rRemark nvarchar(400),
		@rContentType nvarchar(400) = null,
		@rPerentFolderId INT,
		@rSize Float = null,
		@rAccessible  SMALLINT,
		@rViewAccess SMALLINT,
		@rUploadAccess SMALLINT,
		@rEditAccess SMALLINT,
		@rDeleteAccess  SMALLINT,
		@rOrgId SMALLINT,
		@rIsObsolete bit =null,
        @rCreatedUserId bigint ,
		@Access NVARCHAR(MAX),
		@View   NVARCHAR(MAX),  
		@Upload NVARCHAR(MAX),
		@Edit   NVARCHAR(MAX),
		@Delete NVARCHAR(MAX),
		@rOrgGroupId INT
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
		IF(@rId = 0)	
			BEGIN
				IF Exists(SELECT Id FROM [sPoliciesForms].[tFolderFile] WHERE Title=@rTitle AND PerentFolderId=@rPerentFolderId )
					BEGIN
						SELECT -101 as Result
						RETURN
					END 
				
			END
		
		ELSE
			BEGIN
				IF  Exists(SELECT Id FROM [sPoliciesForms].[tFolderFile] WHERE Title=@rTitle  AND PerentFolderId=@rPerentFolderId AND Id<>@rId )
					BEGIN
						SELECT -101 as Result
						RETURN
					END
			END
	
		BEGIN TRANSACTION	
		DECLARE @lNextNumber BIGINT 
	
		IF(@rId = 0)	
			BEGIN

				



				


				EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sPoliciesForms.tFolderFile', 0, 1, 1,@outNextNumber = @lNextNumber output
				INSERT INTO [sPoliciesForms].[tFolderFile]
				(
					Id,
					IsForms,
					IsFolder,
					Title,
					Remark,
					ContentType,
					PerentFolderId,
					Size,
					Accessible,
					ViewAccess,
					UploadAccess,
					EditAccess,
					DeleteAccess,
					OrgId,
					IsObsolete,
					CreatedUserId,
					CreatedDateTime
					 
				)
				VALUES
				(
					@lNextNumber,
					@rIsForms,
					@rIsFolder,
					@rTitle,
					@rRemark,
					@rContentType,
					@rPerentFolderId,
					@rSize,
					@rAccessible,
					@rViewAccess,
					@rUploadAccess,
					@rEditAccess,
					@rDeleteAccess,
					@rOrgId,
					0,
					@rCreatedUserId,
					sCommon.fGetDate()
					
				)

				DECLARE @AccessibleToFD      TABLE (RowID INT ,item int)INSERT INTO @AccessibleToFD SELECT * FROM [sCommon].[fnSplitRowID](@Access,',')
				DECLARE @ViewAccessFD        TABLE (RowID INT ,item int)INSERT INTO @ViewAccessFD   SELECT * FROM [sCommon].[fnSplitRowID](@View,',')
				DECLARE @UploadAccessFD      TABLE (RowID INT ,item int)INSERT INTO @UploadAccessFD SELECT * FROM [sCommon].[fnSplitRowID](@Upload,',')
				DECLARE @EditAccessFD        TABLE (RowID INT ,item int)INSERT INTO @EditAccessFD   SELECT * FROM [sCommon].[fnSplitRowID](@Edit,',')
				DECLARE @DeleteAccessFD      TABLE (RowID INT ,item int)INSERT INTO @DeleteAccessFD SELECT * FROM [sCommon].[fnSplitRowID](@Delete,',')
				DECLARE @rRoleId INT

				SELECT @rRoleId=RoleId from [sSecurity].[tUserRole] Where UserID=CreatedUserId
				SET @rRoleId= ISNULL(@rRoleId,0)

				SELECT 
					ROL.ID
					,@lNextNumber
					,CASE WHEN @rAccessible  =1 THEN  CONVERT(bit,0)  WHEN @rAccessible  =3 THEN  CONVERT(bit,1) WHEN  AccessibleToFD.RowID IS NOT NULL THEN CONVERT(bit,1) ELSE CONVERT(bit,0) END AS Access 
					,CASE WHEN @rViewAccess  =1 THEN  CONVERT(bit,0)  WHEN @rViewAccess  =3 THEN  CONVERT(bit,1) WHEN  ViewAccessFD.RowID IS NOT NULL THEN CONVERT(bit,1) ELSE CONVERT(bit,0) END AS 'View'  
					,CASE WHEN (@rUploadAccess=1 OR @rUploadAccess=-1) THEN  CONVERT(bit,0)  WHEN @rUploadAccess=3 THEN  CONVERT(bit,1) WHEN  UploadAccessFD.RowID IS NOT NULL THEN CONVERT(bit,1) ELSE CONVERT(bit,0) END AS 'Upload' 
					,CASE WHEN @rEditAccess  =1 THEN  CONVERT(bit,0)  WHEN @rEditAccess  =3 THEN  CONVERT(bit,1) WHEN  EditAccessFD.RowID IS NOT NULL THEN CONVERT(bit,1) ELSE CONVERT(bit,0) END AS 'Edit'  
					,CASE WHEN @rDeleteAccess=1 THEN  CONVERT(bit,0)  WHEN @rDeleteAccess=3 THEN  CONVERT(bit,1) WHEN  DeleteAccessFD.RowID IS NOT NULL THEN CONVERT(bit,1) ELSE CONVERT(bit,0) END AS 'Delete' 
				FROM sSecurity.tRole       AS ROL
					LEFT JOIN  @AccessibleToFD AS AccessibleToFD ON AccessibleToFD.item=ROL.Id
					LEFT JOIN  @ViewAccessFD   AS ViewAccessFD   ON ViewAccessFD.item=ROL.Id
					LEFT JOIN  @UploadAccessFD AS UploadAccessFD ON UploadAccessFD.item=ROL.Id
					LEFT JOIN  @EditAccessFD   AS EditAccessFD   ON EditAccessFD.item=ROL.Id
					LEFT JOIN  @DeleteAccessFD AS DeleteAccessFD ON DeleteAccessFD.item=ROL.Id
				WHERE ROL.IsObsolete = 0 AND ROL.OrgGroupId = @rOrgGroupId









				SELECT 1 AS Result
			END	 
		ELSE
			BEGIN
			SET @lNextNumber = @rId
				UPDATE  [sPoliciesForms].[tFolderFile]
				SET
				Title=@rTitle,
				Remark=@rRemark,
				IsObsolete=@rIsObsolete,
				UpdatedUserId=@rCreatedUserId,
				UpdatedDateTime=sCommon.fGetDate()
				WHERE Id = @rId
				SELECT 11 AS Result
			END  	
		COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END
GO
PRINT N'Creating [sPoliciesForms].[pFolderFileGet]...';


GO
/******************************
** Name:  [sPoliciesForms].[pFolderFileGet]
** Desc:  get Record From FolderFile Table
** Auth:  Savan Vaghela
** Date:  3-April-2017
** Page:  /Pages/Hrm/PoliciesForms/FormsMaster.aspx
************************************************************
** Change History
************************************************************
** PR      Date                Author            Description 
**
** 1    3-April-2017      Savan Vaghela       
************************************************************/
--EXEC [sPoliciesForms].[pFolderFileGet] 1001,1001000000003,0
CREATE PROCEDURE [sPoliciesForms].[pFolderFileGet]
	@rOrgId SMALLINT,
	@rCreatedUserId bigint,
	@rPerentFolderId INT,
	@rIsForms BIT
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	SELECT
		UFF.Id 
		,UFF.Title
		,CASE WHEN UFF.IsFolder=1 THEN 'Folder' ELSE 'File' END AS Type
		,CASE WHEN UFF.IsFolder=1 THEN 1 ELSE 0  END AS TypeId
		,CASE WHEN UFF.IsFolder=1 THEN     [sPoliciesForms].[fFileFolderSizeGet]([sPoliciesForms].[fFolderSizeGet](UFF.Id)) ELSE [sPoliciesForms].[fFileFolderSizeGet](ISNULL(UFF.Size,0))  END AS Size
		,USR.DisplayTitle AS CreatedUser
	FROM   [sPoliciesForms].[tFolderFile] AS UFF
		LEFT JOIN [sSecurity].[tUser] AS USR ON USR.id=UFF.CreatedUserId
	WHERE UFF.OrgId=@rOrgId
		AND UFF.CreatedUserId=@rCreatedUserId
		AND UFF.PerentFolderId=@rPerentFolderId
		AND UFF.IsForms=@rIsForms
	Order BY UFF.CreatedDateTime 


	--union all



	 
	-- SELECT
	--	UFF.Id 
	--	,UFF.Title
	--	,CASE WHEN UFF.IsFolder=1 THEN 'Folder' ELSE 'File' END AS Type
	--	,CASE WHEN UFF.IsFolder=1 THEN 1 ELSE 0  END AS TypeId
	--	,CASE WHEN UFF.IsFolder=1 THEN     [sPoliciesForms].[fFileFolderSizeGet]([sPoliciesForms].[fFolderSizeGet](UFF.Id)) ELSE [sPoliciesForms].[fFileFolderSizeGet](ISNULL(UFF.Size,0))  END AS Size
	--	,USR.DisplayTitle AS CreatedUser
	--FROM   [sPoliciesForms].[tFolderFile] AS UFF
	--	LEFT JOIN [sSecurity].[tUser] AS USR ON USR.id=UFF.CreatedUserId
	--WHERE UFF.OrgId=@rOrgId
	--	AND UFF.CreatedUserId<>@rCreatedUserId
	--	AND UFF.PerentFolderId=@rPerentFolderId
	--	AND UFF.IsForms=@rIsForms



















	SELECT
		UFF.Id 
		,UFF.Title
		,CASE WHEN UFF.IsFolder=1 THEN 'Folder' ELSE 'File' END AS Type
		,CASE WHEN UFF.IsFolder=1 THEN 1 ELSE 0  END AS TypeId
		,CASE WHEN UFF.IsFolder=1 THEN     [sPoliciesForms].[fFileFolderSizeGet]([sPoliciesForms].[fFolderSizeGet](UFF.Id)) ELSE [sPoliciesForms].[fFileFolderSizeGet](ISNULL(UFF.Size,0))  END AS Size
		,USR.DisplayTitle AS CreatedUser
	FROM   [sPoliciesForms].[tFolderFile] AS UFF
		LEFT JOIN [sSecurity].[tUser] AS USR ON USR.id=UFF.CreatedUserId
	WHERE UFF.OrgId=@rOrgId
		AND UFF.CreatedUserId=@rCreatedUserId
		AND UFF.PerentFolderId=@rPerentFolderId
		AND UFF.IsFolder=1
	Order BY UFF.CreatedDateTime 


	SELECT
		UFF.Id 
		,UFF.Title
		,CASE WHEN UFF.IsFolder=1 THEN 'Folder' ELSE 'File' END AS Type
		,CASE WHEN UFF.IsFolder=1 THEN 1 ELSE 0  END AS TypeId
		,CASE WHEN UFF.IsFolder=1 THEN     [sPoliciesForms].[fFileFolderSizeGet]([sPoliciesForms].[fFolderSizeGet](UFF.Id)) ELSE [sPoliciesForms].[fFileFolderSizeGet](ISNULL(UFF.Size,0))  END AS Size
		,USR.DisplayTitle AS CreatedUser
		,ISNULL(Exe.ImageName,'unknown.png') AS ImageName
	FROM   [sPoliciesForms].[tFolderFile] AS UFF
		LEFT JOIN [sSecurity].[tUser] AS USR ON USR.id=UFF.CreatedUserId
		LEFT JOIN (
				   select * from [sPoliciesForms].[tFolderImageName]
				   ) AS Exe On LOWER(Exe.Extension)=LOWER(reverse(left(reverse(UFF.Title),charindex('.',reverse(UFF.Title))-1)))
	WHERE UFF.OrgId=@rOrgId
		AND UFF.CreatedUserId=@rCreatedUserId
		AND UFF.PerentFolderId=@rPerentFolderId
		AND UFF.IsFolder=0
	Order BY UFF.CreatedDateTime 



END
GO
PRINT N'Creating [sPoliciesForms].[pFileExitsCheck]...';


GO
/******************************
** Name:  [sPoliciesForms].[pFolderFileAdd]
** Desc:  Insert Record on FolderFile Table
** Auth:  Savan Vaghela
** Date:  3-April-2017
** Page:  /Pages/Hrm/PoliciesForms/FormsMaster.aspx
************************************************************
** Change History
************************************************************
** PR      Date                Author            Description 
**
** 1    3-April-2017      Savan Vaghela       
************************************************************/
--EXEC [sPoliciesForms].[pFolderFileAdd]
CREATE PROCEDURE [sPoliciesForms].[pFileExitsCheck]
	 	@rTitle nvarchar(200),
	 	@rPerentFolderId INT
WITH EXECUTE AS CALLER
AS
BEGIN
	 
	 
			BEGIN
				IF Exists(SELECT Id FROM [sPoliciesForms].[tFolderFile] WHERE IsFolder=0 AND Title=@rTitle AND PerentFolderId=@rPerentFolderId )
					BEGIN
						SELECT 1 as Result
					END 
				ELSE
					BEGIN	
						SELECT 0 as Result
					END
			END
		
		 
			 
	
		 
	 
	
	 
END
GO
PRINT N'Creating [sAccounting].[pExpenseSubGroupMasterAdd]...';


GO

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

	END
	
	
	
	 --BEGIN TRANSACTION	
	 DECLARE @lNextNumber int

	IF(@rId = 0)	
	BEGIN
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAccounting.tExpenseSubGroupMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	--EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sCanteen.tCanteenMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	INSERT INTO sAccounting.tExpenseSubGroupMaster
		(
			OrgId,			
			Id,
			ExpenseGroupId,
			Code,
			Title, 
			IsObsolete,			
		    CreatedUserId, 
		    CreatedDateTime, 
		    UpdatedUserId, 
            UpdatedDateTime
		)
	VALUES
		(
		    @rOrgId ,
			@lNextNumber , 
			@rExpenseGroupId,
			@rCode ,      
			@rTitle ,	
			@rIsObsolete,				
			@rCreatedUserId ,
			sCommon.fGetDate() ,
			@rUpdatedUserId ,
			sCommon.fGetDate()									
		)
		
		   SELECT 1 AS Result
	END	 

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

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


GO
CREATE PROCEDURE [sAccounting].[pExpenseSubGroupMasterGet]

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

BEGIN 
	BEGIN
		SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		SET @rCode = sCommon.fSearchStringGet(@rCode)
	END
	
	SELECT 
			ES.Id,
			ES.Code	,	
			ES.Title,				
		    ES.OrgId,
		    ES.CreatedUserId,
		    ES.CreatedDateTime,
		    ES.IsObsolete,
		    ES.ExpenseGroupId,
		    EG.Title AS ExpenseGroupType
		    
	FROM sAccounting.tExpenseSubGroupMaster ES
	
		LEFT JOIN	sAccounting.tExpenseGroupMaster EG ON EG.Id=ES.ExpenseGroupId
	WHERE 
		(ES.OrgId = @rOrgId)
		AND	((ES.Id = @rId) OR (@rId = 0))
		AND	((ES.ExpenseGroupId = @rExpenseGroupId) OR (@rExpenseGroupId = 0))
		AND ((ES.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
		AND ((ES.Code like @rCode) OR (ISNULL(@rCode,'') = ''))
		
		ORDER BY ES.CreatedDateTime DESC
END
GO
PRINT N'Creating [sAccounting].[pRptExpenseListGet]...';


GO
CREATE PROCEDURE [sAccounting].[pRptExpenseListGet]
	 
	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='',
	@rEmployeeCode nvarchar(100),
    @rEmployeeName nvarchar(100) ,
	@rEmployeeId  bigint=0, 
	@rFromDate date,
    @rTodate date,   
    @rExpenseGroupId int=0,    
    @rStatusId int=0,
    @rOrgId smallint,
    @rIsDetail bit
	

	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
       SELECT 
			 @rBuilder1 AS Builder1,
			 @rBuilder2 AS Builder2, 
			 E.Id AS ExpenseId,
			 E.EmployeeId,
			 E.Amount,
			 E.Remark,
			 E.CreatedUserId,
			 E.CreatedDateTime,			 
			 E.UpdatedUserId,
			 E.UpdatedDateTime,
			 E.ExpenseDate,
			 E.ExpenseGroupId,
			 EGM.Title AS ExpenseGroupName,
			 EM.EmployeeName,
			 EM.Code AS EmployeeCode,
			 E.StatusReason,
			 ISNULL(E.StatusId,0) AS StatusId,
			 ISNULL(SM.Title,'Pending') AS StatusName,
			 --OM.DisplayTitle AS OrganizationName,
			 ED.Amount AS ExpenseDetailAmount,
			 ESGM.Title As ExpenseTitle,
			 ESGM.Id As ExpenseSubGroupId,
			 @rIsDetail AS IsDetail
			 
        FROM 
				sAccounting.tExpense E
	  INNER JOIN sAccounting.tExpenseGroupMaster EGM ON EGM.Id = E.ExpenseGroupId
	  INNER JOIN sAccounting.tExpenseSubGroupMaster ESGM ON ESGM.ExpenseGroupId= EGM.Id
	  LEFT JOIN sAccounting.tExpenseDetail ED ON E.Id=ED.ExpenseId ANd ED.ExpenseSubGroupId = ESGM.Id
	  INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = E.EmployeeId 
	  INNER JOIN sCommon.tStatusMaster SM ON SM.Id = E.StatusId
	  --INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = E.OrgId
    	WHERE 
    		
    		
    		--(E.Id = @rId OR @rId = 0)
     (E.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
      AND ((E.ExpenseDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
      AND ((E.ExpenseDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
      AND (E.ExpenseGroupId = @rExpenseGroupId OR @rExpenseGroupId = 0)      
       AND ((E.OrgId = @rOrgId) OR (@rOrgId = 0))
      AND (EM.Code = @rEmployeeCode OR ISNULL(@rEmployeeCode,'') = '')
      AND (EM.EmployeeName like @rEmployeeName+'%' OR ISNULL(@rEmployeeName,'') = '')
      AND (E.StatusId = @rStatusId OR @rStatusId = 0)
      Order By ExpenseDate DESC
    		
END
GO
PRINT N'Creating [sAdmission].[pAdmissionFormConfirmGet]...';


GO
CREATE PROCEDURE [sAdmission].[pAdmissionFormConfirmGet]
	 @rAdmissionFormId bigint = 0

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
		
	SELECT 
			iSNULL(AF.Id,0) as Id,
			AF.FormNo,
			AF.FirstName,
			AF.MiddleName,
			AF.LastName,
			AF.ForClassId,
			iSNULL(AF.ForBatchId, 0) as ForBatchId,
			AF.ForBatch,
			AF.DateOfBirth,
			AF.DateOfBirthInWord,
			AF.OrgId,
			AF.BatchId,
			AF.StatusId,
			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,
			iSNULL(AF.GenderId,0) as GenderId,
			iSNULL(AF.ReligionId,0) as ReligionId ,
			AF.FamilyCast,
			AF.FamilySubCast,
			iSNULL(AF.CastCategoryId,0) as CastCategoryId,
			AF.CreatedUserId,
			AF.CreatedDateTime,
			iSNULL(AF.UpdatedUserId,0) aS UpdatedUserId,
			AF.UpdatedDateTime,
			iSNULL(AF.StudentId,0) as StudentId,
			AF.FormPassword,
			iSNULL(AF.DataEntryModeId,0) as DataEntryModeId,
			iSNULL(AF.DataEntryStatusId,0) as DataEntryStatusId,
			AF.StudentPhoto,
			iSNULL(AF.AdmissionCategoryId,0) AS AdmissionCategoryId,
			AF.Nationality,
			AF.MotherTongue,
			AF.OtherInformation,
			iSNULL(AF.IsPysicalDeformity,0) aS IsPysicalDeformity ,
			AF.PysicalDeformityRemark,
			iSNULL(AF.IsMajorIllness,0) aS IsMajorIllness ,
			AF.MajorIllnessRemark,
			iSNULL(AF.IsAllergy,0) aS IsAllergy,
			AF.AllergyRemark,
			AF.BirthPlace,
			AF.BirthTaluka,
			AF.BirthDistrict,
			iSNULL(AF.BloodGroupId,0) AS  BloodGroupId,
			AF.AdhaarNumber,
			iSNULL(AF.IsHostelRequired,0) as IsHostelRequired,
			iSNULL(AF.IsTransportRequired,0) as IsTransportRequired,
			AF.BirthState,
			AF.BirthCountry,
			OM.Title AS SchoolName,
			BM.Title AS BatchName,
			CM.Title AS ClassName,
			GM.Title AS Gender,
			RM.Title AS ReligionName,
			CCM.Title AS CastCategoryName,
			BGM.Title AS BloodGroup
			
  FROM
   sAdmission.tAdmissionForm AF
   LEFT JOIN sSetup.tOrganizationMaster OM ON AF.OrgId = OM.Id 
   LEFT JOIN sSetup.tBatchMaster BM ON AF.BatchId=BM.Id 
   LEFT JOIN sSetup.tClassMaster CM ON AF.ForClassId = CM.Id 
   LEFT JOIN sCommon.tGenderMaster GM ON AF.GenderId = GM.Id
    LEFT JOIN sCommon.tReligionMaster RM ON RM.Id = AF.ReligionId 
    LEFT JOIN sCommon.tCastCategoryMaster CCM ON CCM.Id = AF.CastCategoryId 
    LEFT JOIN sCommon.tBloodGroupMaster BGM ON BGM.Id = AF.BloodGroupId
  WHERE 
  
      ((AF.Id = @rAdmissionFormId) OR (@rAdmissionFormId = 0))
       
 
END
GO
PRINT N'Creating [sAlert].[pAdmissionStatusGet]...';


GO
CREATE PROCEDURE [sAlert].[pAdmissionStatusGet]
	
	@rAdmissionFormId bigint,
	@rBatchId int,
	@rTemplate nvarchar(max),
	@rSubject nvarchar(100)=''
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	SELECT 
		AF.Id AS AdmissionFormId,
		AF.FormNo,
		AF.FirstName+' '+AF.MiddleName+' '+AF.LastName AS Name,
		AF.ContactNo AS MobileNo,	
		AF.ContactEmail AS EmailId,
	    REPLACE (
		REPLACE (
		REPLACE(@rTemplate,'[Name]',AF.FirstName+' '+AF.MiddleName+' '+AF.LastName),
		'[AdmissionStatus]',ISNULL(ASM.Title,'')),
		'[ForClass]',ISNULL(CM.Title,''))
		AS MsgText,
		@rSubject AS [Subject]
	FROM sAdmission.tAdmissionForm AF 
		INNER JOIN sAdmission.tAdmissionFormSelected AFS ON AF.Id = AFS.AdmissionFormId 
		INNER JOIN sSetup.tClassMaster CM ON CM.Id = AF.ForClassId
		LEFT JOIN sAdmission.tAdmissionStatusMaster ASM ON ASM.Id = AFS.AdmissionStatusId 
	WHERE	
		AF.Id = @rAdmissionFormId AND AF.BatchId = @rBatchId
END
GO
PRINT N'Creating [sAlert].[pSMSViewGet]...';


GO
CREATE PROCEDURE [sAlert].[pSMSViewGet]
	@rMobileNumber nvarchar(50),
	@rEmail nvarchar(50)
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
declare  @lAlertgrid VARCHAR(max)=''
BEGIN
    SELECT  @lAlertgrid = @lAlertgrid + '<tr>
	<td align="left" scope="col">' + isnull(AL.SourceEvent,'') + '</td>
	<td align="left" scope="col">' + isnull(EM.Title,'') + '</td>
	<td align="left" scope="col">' +  isnull(AL.AlertSubject,'') + '</td>
	<td align="left" scope="col">' +  isnull(AL.AlertMessage,'') + '</td>
	<td align="left" scope="col">' + Convert(varchar,isnull(AL.CreatedDateTime,''),120) + '</td>
	</tr>'	
	FROM
		sAlert.tAlertLog AL
		INNER JOIN sAlert.tEventMaster EM ON EM.Id=AL.EventId
	WHERE  ((AL.ContactId = @rMobileNumber) OR (AL.ContactId = @rEmail))
	And AL.OrgId=1101
	ORDER BY Convert(varchar,isnull(AL.CreatedDateTime,103)) DESC
		
END
 SELECT ISNULL(@lAlertgrid,'') AS Alertgrid
GO
PRINT N'Creating [sAppraisal].[pAppraisalTypeMasterAdd]...';


GO
/******************************
** Name:  [sAppraisal].[pAppraisalTypeMasterAdd]
** Desc:  Create and Update Data in Loan [tAppraisalTypeMaster]
** Auth:  Savan Vaghela
** Date:  17-March-2017
** Page:  /Pages/Hrm/Appraisal/AppraisalTypeMaster.aspx
************************************************************
** Change History
************************************************************
** PR      Date                Author            Description 
**
** 1    17-March-2017      Savan Vaghela       
************************************************************/
--EXEC [sAppraisal].[pAppraisalTypeMasterAdd] 0,1001,3333,1001000000009
CREATE PROCEDURE [sAppraisal].[pAppraisalTypeMasterAdd]
	    @rId int,
		@rTitle nvarchar(200),
		@rRemark nvarchar(1000),
		@rValidFrom DATE,
		@rValidTo DATE,
		@rOrgId SmallINT,
		@rBatchId int,
		@rIsObsolete bit =null,
        @rCreatedUserId bigint 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
		IF(@rId = 0)	
			BEGIN
				IF Exists(SELECT Id FROM [sAppraisal].[tAppraisalTypeMaster] WHERE Title=@rTitle AND BatchId=@rBatchId )
					BEGIN
						SELECT -101 as Result
						RETURN
					END 
				
			END
		
		ELSE
			BEGIN
				IF  Exists(SELECT Id FROM [sAppraisal].[tAppraisalTypeMaster] WHERE Title=@rTitle AND BatchId=@rBatchId AND Id<>@rId )
					BEGIN
						SELECT -101 as Result
						RETURN
					END
			END
	
		BEGIN TRANSACTION	
		DECLARE @lNextNumber BIGINT 
	
		IF(@rId = 0)	
			BEGIN
				EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAppraisal.tAppraisalTypeMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
				INSERT INTO [sAppraisal].[tAppraisalTypeMaster]
				(
					Id,
					Title,
					Remark,
					ValidFrom,
					ValidTo,
					IsObsolete,
					CreatedUserId,
					CreatedDateTime,
					BatchId
				)
				VALUES
				(
					@lNextNumber,
					@rTitle,
					@rRemark,
					@rValidFrom,
					@rValidTo,
					0,
					@rCreatedUserId,
					sCommon.fGetDate(),
					@rBatchId
				)
				SELECT 1 AS Result
			END	 
		ELSE
			BEGIN
			SET @lNextNumber = @rId
				UPDATE  [sAppraisal].[tAppraisalTypeMaster]
				SET
				Title=@rTitle,
				Remark=@rRemark,
				ValidFrom=@rValidFrom,
				ValidTo=@rValidTo,
				IsObsolete=@rIsObsolete,
				UpdatedUserId=@rCreatedUserId,
				UpdatedDateTime=sCommon.fGetDate()
				WHERE Id = @rId
				SELECT 11 AS Result
			END  	
		COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END
GO
PRINT N'Creating [sAppraisal].[pAppraisalTypeMasterGet]...';


GO
/******************************
** Name:  [sAppraisal].[pAppraisalTypeMasterAdd]
** Desc:  Create and Update Data in Loan [tAppraisalTypeMaster]
** Auth:  Savan Vaghela
** Date:  17-March-2017
** Page:  /Pages/Hrm/Appraisal/AppraisalTypeMaster.aspx
************************************************************
** Change History
************************************************************
** PR      Date                Author            Description 
**
** 1    17-March-2017      Savan Vaghela       
************************************************************/
--EXEC [sAppraisal].[pAppraisalTypeMasterGet] '',0,1001,1001
CREATE PROCEDURE [sAppraisal].[pAppraisalTypeMasterGet]
	@rTitle VARCHAR(250),
	@rBatchId int,
	@rOrgId smallint,
	@rOrgGroupId smallint
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 

	SET @rTitle = sCommon.fSearchStringGet(@rTitle)
	SET @rBatchId= CASE WHEN @rBatchId=-1 THEN 0 ELSE @rBatchId END
	SELECT 
		ATM.Id
		,ATM.Title
		,ATM.Remark
		,CONVERT(VARCHAR,ATM.ValidFrom,107)ValidFromDate
		,CONVERT(VARCHAR,ATM.ValidTo,107)ValidToDate
		,CONVERT(VARCHAR,ATM.ValidFrom,103)ValidFrom
		,CONVERT(VARCHAR,ATM.ValidTo,103)ValidTo
		,ATM.BatchId
		,BMS.Title AS BatchName
		,BMS.OrgId
		,ATM.IsObsolete
		,CASE ATM.[IsObsolete] WHEN 0 THEN 'N' ELSE 'Y' END AS InActive
	FROM 
		[sAppraisal].[tAppraisalTypeMaster] AS ATM
		LEFT JOIN [sSetup].[tBatchMaster]   AS BMS ON BMS.Id=ATM.BatchId
		LEFT JOIN [sSetup].[tOrganizationMaster] AS ORG On ORG.Id=BMS.OrgId 

	WHERE		ORG.OrgGroupId=@rOrgGroupId
			AND ((BMS.OrgId=@rOrgId)       OR (@rOrgId=0))
			AND ((ATM.BatchId=@rBatchId)   OR (@rBatchId=0))
			AND ((ATM.Title LIKE @rTitle)  OR (@rTitle='')) 
	Order BY ATM.CreatedDateTime DESC, ATM.Title
END
GO
PRINT N'Creating [sAppraisal].[pBHRatingStatusChange]...';


GO
/******************************
** Name:  [sAppraisal].[pKPAEmployeeRatingStatusChange]
** Desc:  Employee Rating Status SET
** Auth:  Savan Vaghela
** Date:  24-March-2017
** Page:  /Pages/Hrm/Appraisal/BusinessHeadRatings.aspx
************************************************************
** Change History
************************************************************
** PR      Date                Author            Description 
**
** 1    24-March-2017      Savan Vaghela       
************************************************************/
--[sAppraisal].[pKPAEmployeeRatingStatusChange] 1001000000172,100100114,100100042,3,'7,8,9,10,11,12,','1,1,1,1,1,1,','a,b,c,d,e,f'
CREATE PROCEDURE [sAppraisal].[pBHRatingStatusChange]
	   @rKPAEmployeeRatingId BIGINT,
	   @rBusinessHeadRating DECIMAL(5,2),
	   @rBusinessHeadRecommendationIncrement DECIMAL(5,2),
	   @rBusinessHeadRecommendationDesignation nvarchar(200),
	   @rBusinessHeadId BIGINT = null,
	   @rAppraisalTypeId INT=null
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
		BEGIN TRANSACTION	
			BEGIN
				UPDATE [sAppraisal].[tKPAEmployeeRating] 
				SET 
					BusinessHeadRating=@rBusinessHeadRating
					,BusinessHeadRecommendationIncrement=@rBusinessHeadRecommendationIncrement
					,BusinessHeadRecommendationDesignation=@rBusinessHeadRecommendationDesignation
					,RatingStatusId=5 
				WHERE ID =@rKPAEmployeeRatingId	


				IF NOT EXISTS(
						SELECT BusinessHeadId 
						FROM [sAppraisal].[tBusinessHeadsRatingStatus] 
						WHERE BusinessHeadId=@rBusinessHeadId AND AppraisalTypeId=@rAppraisalTypeId)
					BEGIN
						INSERT INTO [sAppraisal].[tBusinessHeadsRatingStatus] 
						(
							BusinessHeadId
							,AppraisalTypeId
							,BHRatingStatusId
						)
						VALUES 
						(
							@rBusinessHeadId
							,@rAppraisalTypeId
							,1
						)
					END



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


GO
/******************************
** Name:  [sAppraisal].[pKPAEmployeeGet]
** Desc:  Get Employee details for Business Head Ratting Status
** Auth:  Savan Vaghela
** Date:  24-March-2017
** Page:  /Pages/Hrm/Appraisal/SetKPAForTeam.aspx
************************************************************
** Change History
************************************************************
** PR      Date                Author            Description 
**
** 1    24-March-2017      Savan Vaghela       
************************************************************/

--[sAppraisal].[pBusinessHeadRatingsStatusGet] 0,100100114,1001,1001,100100063
CREATE PROCEDURE [sAppraisal].[pBusinessHeadRatingsStatusGet]
	@rEmployeeManagerId           BIGINT,
	@rBatchId					  INT,
	@rOrgId						  SMALLINT,
	@rOrgGroupId				  SMALLINT,
	@rAppraisalTypeId			  INT
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 

	 SELECT 
		EMP.Id
		,EMP.Code
		,ISNULL(EMP.FirstName,'') +' '+ ISNULL(EMP.LastName,'') AS Employee
		,ISNULL(DEG.Id,'') AS DesignationId
		,ISNULL(DEG.Title,'') AS DesignationName
		,ManagerRat.ManagerRating
		,KER.RecommendationDesignation AS PromotionRecommend
		,CONVERT(NVARCHAR(50),KER.RecommendationIncrement) +' %' AS ManagerRecommend
		,KER.BusinessHeadRating AS BHRating
		,CONVERT(NVARCHAR(20),KER.BusinessHeadRecommendationIncrement)+' %' AS BHRecommend
		,KER.BusinessHeadRecommendationDesignation AS BHPromotionRecommend
		,KER.Id AS KPAEmployeeRatingId
		,KER.RatingStatusId
		,CASE WHEN KER.RatingStatusId=4 THEN  CONVERT(BIT,1) ELSE CONVERT(BIT,0) END AS Enabled
		,(SELECT Title FROM [sAppraisal].[tRatingStatus] WHERE ID =ISNULL(KER.RatingStatusId,1))  AS RatingStatus
	FROM [sHrm].[tEmployeeMaster]  AS EMP
		LEFT JOIN [sHrm].[tEmployeeJobDetail]			AS EJD ON EJD.EmployeeId=EMP.Id
		LEFT JOIN [sHrm].[tEmployeeMaster]				AS EMD ON EMD.Id= EJD.EmployeeManagerId
		LEFT JOIN [sSetup].[tOrganizationMaster]		AS ORG ON Org.id=EMP.OrgID
		LEFT JOIN [sHrm].[tEmployeeDesignationMaster]   AS DEG ON DEG.Id=EJD.EmployeeDesignationId
		LEFT JOIN [sAppraisal].[tKPAEmployee]			AS KPA ON KPA.EmployeeId=EMP.Id
		LEFT JOIN [sAppraisal].[tKPAEmployeeRating]		AS KER ON KER.KPAEmployeeId=KPA.Id
		LEFT JOIN 
					(
						SELECT KER.KPAEmployeeId,KRD.KPAEmployeeRatingId,CONVERT(DECIMAL(18,2),AVG(KRD.ManagerRating))ManagerRating 
						FROM [sAppraisal].[tKPAEmployeeRating]             AS KER
						INNER JOIN [sAppraisal].[tKPAEmployeeRatingDetail] AS KRD ON KRD.KPAEmployeeRatingId=KER.Id
						GROUP BY KER.KPAEmployeeId,KRD.KPAEmployeeRatingId
					) AS ManagerRat ON ManagerRat.KPAEmployeeId=KPA.Id AND ManagerRat.KPAEmployeeRatingId=KER.Id


	WHERE
		ORG.OrgGroupId=@rOrgGroupId 
		AND ((EMP.OrgID=@rOrgId)OR(@rOrgId=0))
		AND	EJD.EmployeeBusinessHeadId=@rEmployeeManagerId 
		AND Emp.ID<>@rEmployeeManagerId 
		AND EMP.StatusId=7
		AND KPA.BatchId=@rBatchId
		AND KER.AppraisalTypeId=@rAppraisalTypeId
		--AND KER.RatingStatusId>=4
	Order by EMP.FirstName, EMP.Code





	DECLARE @ManagerRat TABLE (ManagerRating DECIMAL(18,2))
	INSERT INTO @ManagerRat 

	SELECT  ManagerRat.ManagerRating
	FROM [sHrm].[tEmployeeMaster]  AS EMP
		LEFT JOIN [sHrm].[tEmployeeJobDetail]			AS EJD ON EJD.EmployeeId=EMP.Id
		LEFT JOIN [sHrm].[tEmployeeMaster]				AS EMD ON EMD.Id= EJD.EmployeeManagerId
		LEFT JOIN [sSetup].[tOrganizationMaster]		AS ORG ON Org.id=EMP.OrgID
		LEFT JOIN [sHrm].[tEmployeeDesignationMaster]   AS DEG ON DEG.Id=EJD.EmployeeDesignationId
		LEFT JOIN [sAppraisal].[tKPAEmployee]			AS KPA ON KPA.EmployeeId=EMP.Id
		LEFT JOIN [sAppraisal].[tKPAEmployeeRating]		AS KER ON KER.KPAEmployeeId=KPA.Id
		LEFT JOIN 
					(
						SELECT KER.KPAEmployeeId,KRD.KPAEmployeeRatingId,CONVERT(DECIMAL(18,2),AVG(KRD.ManagerRating))ManagerRating 
						FROM [sAppraisal].[tKPAEmployeeRating]             AS KER
						INNER JOIN [sAppraisal].[tKPAEmployeeRatingDetail] AS KRD ON KRD.KPAEmployeeRatingId=KER.Id
						GROUP BY KER.KPAEmployeeId,KRD.KPAEmployeeRatingId
					) AS ManagerRat ON ManagerRat.KPAEmployeeId=KPA.Id AND ManagerRat.KPAEmployeeRatingId=KER.Id



	WHERE
		ORG.OrgGroupId=@rOrgGroupId 
		AND ((EMP.OrgID=@rOrgId)OR(@rOrgId=0))
		AND	EJD.EmployeeBusinessHeadId=@rEmployeeManagerId 
		AND Emp.ID<>@rEmployeeManagerId 
		AND EMP.StatusId=7
		AND KPA.BatchId=@rBatchId
		AND KER.AppraisalTypeId=@rAppraisalTypeId
		AND KER.RatingStatusId>=4
	--GROUP BY ManagerRat.ManagerRating
	





	
	
	
	
	SELECT 1 AS Rank,'5%'  AS Per,1 AS Normal,COUNT(0)Actual FROM @ManagerRat WHERE ManagerRating>4 UNION ALL
	SELECT 2 AS Rank,'15%' AS Per,1 AS Normal,COUNT(0)Actual FROM @ManagerRat WHERE ManagerRating<=4 AND ManagerRating>3 UNION ALL
	SELECT 3 AS Rank,'60%' AS Per,2 AS Normal,COUNT(0)Actual FROM @ManagerRat WHERE ManagerRating<=3 AND ManagerRating>2 UNION ALL
	SELECT 4 AS Rank,'15%' AS Per,1 AS Normal,COUNT(0)Actual FROM @ManagerRat WHERE ManagerRating<=2 AND ManagerRating>1 UNION ALL
	SELECT 5 AS Rank,'5%'  AS Per,1 AS Normal,COUNT(0)Actual FROM @ManagerRat WHERE ManagerRating<=1 AND ManagerRating>0 


END
GO
PRINT N'Creating [sAppraisal].[pBusinessHeadRatingStatusChange]...';


GO
/******************************
** Name:  [sAppraisal].[pConductTypeMasterAdd]
** Desc:  Create and Update Data in Loan ConductTypeMaster
** Auth:  Savan Vaghela
** Date:  30-March-2017
** Page:  /Pages/Hrm/Appraisal/KPATemplatesMaster.aspx
************************************************************
** Change History
************************************************************
** PR      Date                Author            Description 
**
** 1    30-March-2017      Savan Vaghela       
************************************************************/
--[sAppraisal].[pConductTypeMasterAdd]
CREATE PROCEDURE [sAppraisal].[pBusinessHeadRatingStatusChange]
	  	@rBusinessHeadsId			  INT,
		@rBHRatingStatusId            SMALLINT,
		@rEmployeeBusinessHeadId      BIGINT,
		@rAppraisalTypeId			  INT,
		@rBatchId					  INT,
		@rOrgId						  SMALLINT,
		@rOrgGroupId				  SMALLINT
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
		BEGIN TRANSACTION	
			IF (@rBHRatingStatusId=3)
				BEGIN
					DECLARE @rTotalEmployee INT = 0
					DECLARE @AwaitingApprovalBH  INT=0

					SELECT @AwaitingApprovalBH=COUNT(0)
					FROM [sAppraisal].[tKPAEmployee] AS KPA
					LEFT JOIN [sAppraisal].[tKPAEmployeeRating] AS KER ON KER.KPAEmployeeId=KPA.Id
					WHERe KPA.BatchId=@rBatchId 
					AND KER.AppraisalTypeId=@rAppraisalTypeId
					AND KER.RatingStatusId>=5
					AND  KPA.EmployeeId in 
					(
						SELECT EMP.Id	FROM [sHrm].[tEmployeeMaster]  AS EMP 
						INNER JOIN [sHrm].[tEmployeeJobDetail]         AS EJD On EJD.EmployeeId=EMP.Id
						LEFT  JOIN [sSetup].[tOrganizationMaster]      AS ORG ON Org.id=EMP.OrgID	
						WHERE ORG.OrgGroupId=@rOrgGroupId	
						AND ((EMP.OrgID=@rOrgId)OR(@rOrgId=0)) 
						AND	EJD.EmployeeBusinessHeadId=@rEmployeeBusinessHeadId 		
						AND Emp.ID<>@rEmployeeBusinessHeadId AND EMP.StatusId=7
					)
					SELECT @rTotalEmployee=COUNT(0)
					FROM [sAppraisal].[tKPAEmployee] AS KPA
					LEFT JOIN [sAppraisal].[tKPAEmployeeRating] AS KER ON KER.KPAEmployeeId=KPA.Id
					WHERe KPA.BatchId=@rBatchId 
					AND KER.AppraisalTypeId=@rAppraisalTypeId
					AND  KPA.EmployeeId in 
					(
						SELECT EMP.Id	FROM [sHrm].[tEmployeeMaster]  AS EMP 
						INNER JOIN [sHrm].[tEmployeeJobDetail]         AS EJD On EJD.EmployeeId=EMP.Id
						LEFT  JOIN [sSetup].[tOrganizationMaster]      AS ORG ON Org.id=EMP.OrgID	
						WHERE ORG.OrgGroupId=@rOrgGroupId	
						AND ((EMP.OrgID=@rOrgId)OR(@rOrgId=0)) 
						AND	EJD.EmployeeBusinessHeadId=@rEmployeeBusinessHeadId 		
						AND Emp.ID<>@rEmployeeBusinessHeadId AND EMP.StatusId=7
					)




					IF (@AwaitingApprovalBH>0)
						BEGIN
							IF (@AwaitingApprovalBH=@rTotalEmployee)
								BEGIN
									UPDATE [sAppraisal].[tBusinessHeadsRatingStatus]		
									SET 
										BHRatingStatusId=@rBHRatingStatusId 
									WHERE 
										Id=@rBusinessHeadsId
								END
						END

					
		
					UPDATE [sAppraisal].[tKPAEmployeeRating] 
					SET RatingStatusId=6
					WHERE 
					RatingStatusId=5  
					AND AppraisalTypeId=@rAppraisalTypeId
					AND  KPAEmployeeId IN
										(
											SELECT 
											KER.KPAEmployeeId
											FROM [sAppraisal].[tKPAEmployee] AS KPA
											LEFT JOIN [sAppraisal].[tKPAEmployeeRating] AS KER ON KER.KPAEmployeeId=KPA.Id
											WHERe KPA.BatchId=@rBatchId 
											AND KER.AppraisalTypeId=@rAppraisalTypeId AND KER.RatingStatusId=5
											AND  KPA.EmployeeId in 
											(
												SELECT EMP.Id	
												FROM [sHrm].[tEmployeeMaster]            AS EMP 
												INNER JOIN [sHrm].[tEmployeeJobDetail]   AS EJD On EJD.EmployeeId=EMP.Id
												LEFT JOIN [sSetup].[tOrganizationMaster] AS ORG ON Org.id=EMP.OrgID	
												WHERE ORG.OrgGroupId=@rOrgGroupId	
												AND ((EMP.OrgID=@rOrgId)OR(@rOrgId=0))
												AND	EJD.EmployeeBusinessHeadId=@rEmployeeBusinessHeadId 		
												AND Emp.ID<>@rEmployeeBusinessHeadId AND EMP.StatusId=7
											)
										)
				END
			ELSE
			BEGIN
				UPDATE [sAppraisal].[tBusinessHeadsRatingStatus]		
						SET 
							BHRatingStatusId=@rBHRatingStatusId 
						WHERE 
							Id=@rBusinessHeadsId
			END

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


GO
/******************************
** Name:  [sAppraisal].[pKPAEmployeeGet]
** Desc:  Get Employee details for set KPA Details
** Auth:  Savan Vaghela
** Date:  29-March-2017
** Page:  /Pages/Hrm/Appraisal/RatingStatusofBusinessHead.aspx
************************************************************
** Change History
************************************************************
** PR      Date                Author            Description 
**
** 1    29-March-2017      Savan Vaghela       
************************************************************/
--[sAppraisal].[pBusinessHeadsRatingStatusGet] 0,100100114,1001,1001,100100067,'Admin'
CREATE PROCEDURE [sAppraisal].[pBusinessHeadsRatingStatusGet]
	@rEmployeeBusinessHeadId           BIGINT,
	@rBatchId					  INT,
	@rOrgId						  SMALLINT,
	@rOrgGroupId				  SMALLINT,
	@rAppraisalTypeId			  INT,
	@rUserFullName				  nVARCHAR(100)
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 

	DECLARE @rTotalEmployee INT = 0
	DECLARE @rTotalKPAEmployee INT = 0
	DECLARE @AvgRating DECIMAL(10,2)=0
	DECLARE @AvgIncrement DECIMAL(10,2)=0
	DECLARE @AvgPromotions INT=0
	DECLARE @AwaitingApprovalBH  INT=0
	

			 


			SELECT 
			@AvgRating=ISNULL(AVG(BusinessHeadRating),0)
			,@AvgIncrement=ISNULL(AVG(BusinessHeadRecommendationIncrement),0) 
			FROM [sAppraisal].[tKPAEmployee] AS KPA
			LEFT JOIN [sAppraisal].[tKPAEmployeeRating] AS KER ON KER.KPAEmployeeId=KPA.Id
			WHERe KPA.BatchId=@rBatchId 
			AND KER.AppraisalTypeId=@rAppraisalTypeId AND KER.RatingStatusId>=5
			AND  KPA.EmployeeId in 
			(
				SELECT EMP.Id	
				FROM [sHrm].[tEmployeeMaster]            AS EMP 
				INNER JOIN [sHrm].[tEmployeeJobDetail]   AS EJD On EJD.EmployeeId=EMP.Id
				LEFT JOIN [sSetup].[tOrganizationMaster] AS ORG ON Org.id=EMP.OrgID	
				WHERE ORG.OrgGroupId=@rOrgGroupId	
				AND ((EMP.OrgID=@rOrgId)OR(@rOrgId=0))
				AND	EJD.EmployeeBusinessHeadId=@rEmployeeBusinessHeadId 		
				AND Emp.ID<>@rEmployeeBusinessHeadId AND EMP.StatusId=7
			)



			SELECT @AvgPromotions=ISNULL(COUNT(1),0) 
			FROM [sAppraisal].[tKPAEmployee]			AS KPA
			LEFT JOIN [sAppraisal].[tKPAEmployeeRating] AS KER ON KER.KPAEmployeeId=KPA.Id
			WHERe KPA.BatchId=@rBatchId 
			AND KER.AppraisalTypeId=@rAppraisalTypeId AND KER.RatingStatusId>=5
			AND LEN(RTRIM(LTRIM(KER.BusinessHeadRecommendationDesignation)))>=4
			AND  KPA.EmployeeId in 
			(
				SELECT EMP.Id	FROM [sHrm].[tEmployeeMaster]  AS EMP 
				INNER JOIN [sHrm].[tEmployeeJobDetail]		   AS EJD On EJD.EmployeeId=EMP.Id
				LEFT  JOIN [sSetup].[tOrganizationMaster]	   AS ORG ON Org.id=EMP.OrgID	
				WHERE ORG.OrgGroupId=@rOrgGroupId	
				AND ((EMP.OrgID=@rOrgId)OR(@rOrgId=0)) 
				AND	EJD.EmployeeBusinessHeadId=@rEmployeeBusinessHeadId 		
				AND Emp.ID<>@rEmployeeBusinessHeadId AND EMP.StatusId=7
			)





			IF EXISTS (
							SELECT KER.Id FROM [sAppraisal].[tKPAEmployee] AS KPA
							LEFT JOIN [sAppraisal].[tKPAEmployeeRating] AS KER ON KER.KPAEmployeeId=KPA.Id
							WHERe KPA.BatchId=@rBatchId 
							AND KER.AppraisalTypeId=@rAppraisalTypeId AND  KPA.EmployeeId in (SELECT EMP.Id	FROM [sHrm].[tEmployeeMaster]  AS EMP 
							INNER JOIN [sHrm].[tEmployeeJobDetail] AS EJD On EJD.EmployeeId=EMP.Id
							LEFT  JOIN [sSetup].[tOrganizationMaster] AS ORG ON Org.id=EMP.OrgID	
							WHERE ORG.OrgGroupId=@rOrgGroupId	
							AND ((EMP.OrgID=@rOrgId)OR(@rOrgId=0)) 
							AND	EJD.EmployeeBusinessHeadId=@rEmployeeBusinessHeadId 		
							AND Emp.ID<>@rEmployeeBusinessHeadId 		
							AND EMP.StatusId=7)
					  )
			
				BEGIN
					SELECT @AwaitingApprovalBH=COUNT(0)
					FROM [sAppraisal].[tKPAEmployee] AS KPA
					LEFT JOIN [sAppraisal].[tKPAEmployeeRating] AS KER ON KER.KPAEmployeeId=KPA.Id
					WHERe KPA.BatchId=@rBatchId 
					AND KER.AppraisalTypeId=@rAppraisalTypeId
					AND KER.RatingStatusId>=5
					AND  KPA.EmployeeId in 
					(
						SELECT EMP.Id	FROM [sHrm].[tEmployeeMaster]  AS EMP 
						INNER JOIN [sHrm].[tEmployeeJobDetail]         AS EJD On EJD.EmployeeId=EMP.Id
						LEFT  JOIN [sSetup].[tOrganizationMaster]      AS ORG ON Org.id=EMP.OrgID	
						WHERE ORG.OrgGroupId=@rOrgGroupId	
						AND ((EMP.OrgID=@rOrgId)OR(@rOrgId=0)) 
						AND	EJD.EmployeeBusinessHeadId=@rEmployeeBusinessHeadId 		
						AND Emp.ID<>@rEmployeeBusinessHeadId AND EMP.StatusId=7
					)
					SELECT @rTotalEmployee=COUNT(0)
					FROM [sAppraisal].[tKPAEmployee] AS KPA
					LEFT JOIN [sAppraisal].[tKPAEmployeeRating] AS KER ON KER.KPAEmployeeId=KPA.Id
					WHERe KPA.BatchId=@rBatchId 
					AND KER.AppraisalTypeId=@rAppraisalTypeId
					AND  KPA.EmployeeId in 
					(
						SELECT EMP.Id	FROM [sHrm].[tEmployeeMaster]  AS EMP 
						INNER JOIN [sHrm].[tEmployeeJobDetail]         AS EJD On EJD.EmployeeId=EMP.Id
						LEFT  JOIN [sSetup].[tOrganizationMaster]      AS ORG ON Org.id=EMP.OrgID	
						WHERE ORG.OrgGroupId=@rOrgGroupId	
						AND ((EMP.OrgID=@rOrgId)OR(@rOrgId=0)) 
						AND	EJD.EmployeeBusinessHeadId=@rEmployeeBusinessHeadId 		
						AND Emp.ID<>@rEmployeeBusinessHeadId AND EMP.StatusId=7
					)
				END







			SELECT 
			BHS.Id																		  AS Id
			,@rUserFullName                                                               AS UserName
			,@AvgRating														 	          AS AvgRating
			,@AvgIncrement													 	          AS AvgIncrement
			,@AvgPromotions													   	          AS AvgPromotions
			

			,CASE 
				WHEN (BHS.BHRatingStatusId=4) THEN 4
				WHEN ((@AwaitingApprovalBH>0)  AND  (@AwaitingApprovalBH<>@rTotalEmployee)) THEN 1
				WHEN ((@AwaitingApprovalBH>0)  AND  (@AwaitingApprovalBH=@rTotalEmployee) AND (BHS.BHRatingStatusId<>3)) THEN 2
				WHEN ((@AwaitingApprovalBH>0)  AND  (@AwaitingApprovalBH=@rTotalEmployee) AND (BHS.BHRatingStatusId=3)) THEN 3
				ELSE 1	END	  
			AS BHRatingStatusId


			
			,CASE
				WHEN (BHS.BHRatingStatusId=4) THEN 'Rejected'  
				WHEN ((@AwaitingApprovalBH>0)  AND  (@AwaitingApprovalBH<>@rTotalEmployee)) THEN 'Not Confirmed yet' 
				WHEN ((@AwaitingApprovalBH>0)  AND  (@AwaitingApprovalBH=@rTotalEmployee) AND  (BHS.BHRatingStatusId<>3)) THEN 'Completed, Awaiting your approval' 
				WHEN ((@AwaitingApprovalBH>0)  AND  (@AwaitingApprovalBH=@rTotalEmployee) AND (BHS.BHRatingStatusId=3)) THEN 'Completed & Approved' 
				ELSE 'Not Applicable Right Now'	END	  
			AS Title



			,CASE WHEN  (@AwaitingApprovalBH>0 AND  @AwaitingApprovalBH<>@rTotalEmployee) THEN 1 ELSE 0 END              AS  RatingStatus 
			,CASE WHEN ((@AwaitingApprovalBH>0)  AND  (@AwaitingApprovalBH=@rTotalEmployee) AND (BHS.BHRatingStatusId=3)) THEN CONVERT(BIT,0) ELSE CONVERT(BIT,1) END AS  Enabled 
			from [sAppraisal].[tBusinessHeadsRatingStatus] AS BHS
			LEFT JOIN  [sAppraisal].[tBHRatingStatus] AS BRS ON BRS.Id =BHS.BHRatingStatusId
			WHERE BHS.BusinessHeadId=@rEmployeeBusinessHeadId AND AppraisalTypeId=@rAppraisalTypeId










	 
END
GO
PRINT N'Creating [sAppraisal].[pConductGet]...';


GO
/******************************
** Name:  [sLoan].[ptLoanDetailGet]   
** Desc:  Employee Loan Detail 
** Auth:  Savan Vaghela
** Date:  19-January-2017
** Page:  Pages/Hrm/IncomeTax/IncomeTaxChallan.aspx
************************************************************
** Change History
************************************************************
** PR      Date                Author            Description 
**
** 1    19-January-2017      Savan Vaghela       
************************************************************/
--EXEC [sAppraisal].[pConductGet] 0,0,'',null,null,-1
CREATE PROCEDURE [sAppraisal].[pConductGet]
	@rId BIGINT, 
	@rOrgGroupId smallint,
	@rOrgId smallint,
	@rTitle VARCHAR(50)='',
	@rFromDate datetime ,
	@rToDate datetime ,
	@rConductTypeId INT,
	@rEmployeeId BIGINT=null,
	@rBatchId INT
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	
	BEGIN
		SET @rTitle = sCommon.fSearchStringGet(@rTitle)
	END
	
	SELECT 
		CND.Id
		,CONVERT(VARCHAR,CND.ConductDate,103)ConductDate
		,CND.EmployeeId
		,EMP.Code AS EmpCode
		,ISNULL(EMP.FirstName,'') +' '+ ISNULL(EMP.LastName,'') AS EmpName
		,CND.ConductTypeId
		,CTM.Title AS ConductType
		,CND.Title
		,CND.Remark 
		,EMP.[OrgID]
		,OMD.Title AS 'OrgName'
		,DEP.title AS 'EmpDept'
		,USR.DisplayTitle
		,CONVERT(VARCHAR,CND.CreatedDateTime,103)CreatedDateTime
		,CTM.ConductIndicatorId
	FROM [sAppraisal].[tConduct] AS CND
		INNER JOIN [sAppraisal].[tConductTypeMaster]       AS CTM ON CTM.Id=CND.ConductTypeId
		INNER JOIN [sAppraisal].[tConductIndicatorMaster]  AS CIM ON CIM.Id=CTM.ConductIndicatorId
		INNER JOIN [sHrm].[tEmployeeMaster]				   AS EMP ON EMP.Id=CND.EmployeeId
		INNER JOIN [sSetup].[tOrganizationMaster]		   AS OMD ON OMD.Id=EMP.OrgID
		INNER JOIN [sHrm].[tEmployeeJobDetail]			   AS EJD ON EJD.EmployeeId=EMP.id
		INNER JOIN [sSetup].[tDepartmentMaster]			   AS DEP ON DEP.id=EJD.OrganizationDepartmentId
		LEFT  JOIN [sSecurity].[tUser]                     AS USR ON USR.Id=CND.CreatedUserId 

	WHERE		((CND.BatchId=@rBatchId))
			AND	((OMD.[OrgGroupId] = @rOrgGroupId)   OR (@rOrgGroupId=0))
			AND ((OMD.[Id] = @rOrgId)                OR (@rOrgId=0))
			AND ((CND.EmployeeId = @rEmployeeId)     OR (@rEmployeeId=0))
			AND ((CND.Id = @rId )                    OR (@rId =0))
			AND ((CND.ConductTypeId=@rConductTypeId) OR (@rConductTypeId=0))
			AND ((EMP.[FirstName] +' '+ EMP.[LastName] LIKE @rTitle) OR (@rTitle=''))
			AND CONVERT(DATE,CND.ConductDate)	BETWEEN CONVERT(DATE,ISNULL(@rFromDate, CONVERT(DATE,CND.ConductDate))) 
			AND CONVERT(DATE,ISNULL(@rToDate, CONVERT(DATE,CND.ConductDate)))
	ORDER BY 
		EMP.Code,CND.ConductDate

END
GO
PRINT N'Creating [sAppraisal].[pEmployeeRatingStatusGet]...';


GO
/******************************
** Name:  [sAppraisal].[pKPATemplateMasterGet]
** Desc:  Employee Rating Status SET
** Auth:  Savan Vaghela
** Date:  22-March-2017
** Page:  /Pages/Hrm/Appraisal/EmployeeRateEntry.aspx
************************************************************
** Change History
************************************************************
** PR      Date                Author            Description 
**
** 1    22-March-2017      Savan Vaghela       
************************************************************/
-- [sAppraisal].[pEmployeeRatingStatusGet] 1001000000154,100100114,100100063
CREATE PROCEDURE [sAppraisal].[pEmployeeRatingStatusGet]
	@rEmployeeId BIGINT,
	@rBatchId INT,
	@rAppraisalTypeId INT
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 

SELECT 
		KED.Id AS KPAEmployeeDetailId
		,Indicator AS Name
		, KPAMeasureId AS TypeID
		,KMD.Title AS TypeName 
		, IndicatorRemark AS Remarks
		,CONVERT(int,Weightage) AS Weightage
		,ERD.MyRating
		,ERD.MyRemark
		,ERD.ManagerRemark
		,ERD.ManagerRating
		,KER.RatingStatusId
		,(SELECT Title FROM [sAppraisal].[tRatingStatus] WHERE ID = ISNULL(KER.RatingStatusId,1)) AS RatingStatus 
	FROM [sAppraisal].[tKPAEmployee] AS KPA
		LEFT JOIN [sAppraisal].[tKPAEmployeeDetail]       AS KED ON KED.KPAEmployeeId=KPA.Id
		LEFT JOIN [sAppraisal].[tKPAMeasureMaster]        AS KMD ON KMD.Id=KED.KPAMeasureId
		LEFT JOIN [sAppraisal].[tKPAEmployeeRating]       AS KER ON KER.KPAEmployeeId=KPA.Id
		LEFT JOIN [sAppraisal].[tKPAEmployeeRatingDetail] AS ERD ON ERD.KPAEmployeeRatingId=KER.Id AND ERD.KPAEmployeeDetailId=KED.Id
	WHERE  KPATypeId=1 
		AND KPA.EmployeeId=@rEmployeeId 
		AND KPA.BatchId=@rBatchId 
		AND KER.AppraisalTypeId=@rAppraisalTypeId 
		AND KER.RatingStatusId>=2
	ORDER BY KED.Id

	SELECT 
		KED.Id AS KPAEmployeeDetailId
		,Indicator AS Name
		, KPAMeasureId AS TypeID
		,KMD.Title AS TypeName 
		, IndicatorRemark AS Remarks
		,CONVERT(int,Weightage) AS Weightage
		,ERD.MyRating
		,ERD.MyRemark
		,ERD.ManagerRemark
		,ERD.ManagerRating
		,KER.RatingStatusId
		,(SELECT Title FROM [sAppraisal].[tRatingStatus] WHERE ID = ISNULL(KER.RatingStatusId,1)) AS RatingStatus  
	FROM [sAppraisal].[tKPAEmployee] AS KPA
		LEFT JOIN [sAppraisal].[tKPAEmployeeDetail]       AS KED ON KED.KPAEmployeeId=KPA.Id
		LEFT JOIN [sAppraisal].[tKPAMeasureMaster]        AS KMD ON KMD.Id=KED.KPAMeasureId
		LEFT JOIN [sAppraisal].[tKPAEmployeeRating]       AS KER ON KER.KPAEmployeeId=KPA.Id
		LEFT JOIN [sAppraisal].[tKPAEmployeeRatingDetail] AS ERD ON ERD.KPAEmployeeRatingId=KER.Id AND ERD.KPAEmployeeDetailId=KED.Id
	WHERE  KPATypeId=2 
		AND KPA.EmployeeId=@rEmployeeId 
		AND KPA.BatchId=@rBatchId 
		AND KER.AppraisalTypeId=@rAppraisalTypeId
		AND KER.RatingStatusId>=2
	ORDER BY KED.Id





	 SELECT 
		 KPA.Id
		,KPA.EmployeeId
		,KPA.BatchId	
		,KPA.KPAStatusId
		,KPS.Title AS KPAStatus
		,ISNULL(KER.RatingStatusId,1)RatingStatusId
		,(SELECT Title FROM [sAppraisal].[tRatingStatus] WHERE ID = ISNULL(KER.RatingStatusId,1)) AS RatingStatus
		,RecommendationIncrement,RecommendationDesignation,RecommendationJustification
	FROM [sAppraisal].[tKPAEmployee] AS KPA
		LEFT JOIN (
					SELECT AppraisalTypeId,KPAEmployeeId,RatingStatusId ,CONVERT(smallint,RecommendationIncrement)RecommendationIncrement,RecommendationDesignation,RecommendationJustification
					FROM [sAppraisal].[tKPAEmployeeRating] 
					WHERE  AppraisalTypeId=@rAppraisalTypeId
				  )	AS KER ON KER.KPAEmployeeId=KPA.Id
		LEFT JOIN [sAppraisal].[tKPAStatus] AS KPS ON KPS.id=KPA.KPAStatusId
		
		
		 
			
	WHERE KPA.EmployeeId=@rEmployeeId AND KPA.BatchId=@rBatchId 
	ORDER BY KPA.Id

END
GO
PRINT N'Creating [sAppraisal].[pGetMyRatingHtml]...';


GO
-- exec [sAppraisal].[pGetMyRatingHtml] 1001000000164,100100114,2
-- drop proc [sAppraisal].[pGetMyRatingHtml]
CREATE proc [sAppraisal].[pGetMyRatingHtml]
@rEmployeeId bigint,
@rBatchId int,
@rKPATypeId SmallINT
as
begin
	IF	EXISTS(SELECT ID from [sAppraisal].[tAppraisalTypeMaster] 
			WHERE ID IN(SELECT AppraisalTypeId FROM [sAppraisal].[tKPAEmployeeRating] WHERE  RatingStatusId >=5 AND KPAEmployeeId IN (SELECT ID FROM [sAppraisal].[tKPAEmployee] WHERE EmployeeId=@rEmployeeId AND BatchId=@rBatchId))
			AND IsObsolete=0)
		BEGIN


			declare @lTableMain varchar(500)='',@lTableHead varchar(max)='',@lTableTail varchar(500)=''
			select @lTableMain = @lTableMain + '
			<table style="width: 100%; border: 1px solid #E5EFF8; width: 100%; border-collapse: collapse; margin: 0px auto;">
				<tr>
					<td  style="background: #F4F9FE;"></td>
					<td style="font-size: 11px; font-weight: bold; padding: 3px; background: none repeat scroll 0% 0% #F4F9FE; border: 1px solid #E5EFF8; text-align: center; color: #66A3D3;">Title</td>
					<td>
						<table style="width: 100%; border: 1px solid #E5EFF8; width: 100%; border-collapse: collapse; margin: 0px auto;"><tr>'
	
			select @lTableHead = @lTableHead + 
			'<td width="20%"   style="font-size: 11px; font-weight: bold; padding: 3px; background: none repeat scroll 0% 0% #F4F9FE; border: 1px solid #E5EFF8; text-align: center; color: #66A3D3;" colspan="3">' + isnull(Title,'') + 
			'</td>'
			from [sAppraisal].[tAppraisalTypeMaster] 
			WHERE ID IN(SELECT AppraisalTypeId FROM [sAppraisal].[tKPAEmployeeRating] WHERE  RatingStatusId >=5 AND KPAEmployeeId IN (SELECT ID FROM [sAppraisal].[tKPAEmployee] WHERE EmployeeId=@rEmployeeId AND BatchId=@rBatchId))
			AND IsObsolete=0


		
			select @lTableHead = @lTableHead + '</tr>'
	
			declare @tbltmp table(tid int identity(1,1),Title varchar(500))
			insert into @tbltmp
			select Title from [sAppraisal].[tAppraisalTypeMaster]
			WHERE ID IN(SELECT AppraisalTypeId FROM [sAppraisal].[tKPAEmployeeRating] WHERE  RatingStatusId >=5 AND KPAEmployeeId IN (SELECT ID FROM [sAppraisal].[tKPAEmployee] WHERE EmployeeId=@rEmployeeId AND BatchId=@rBatchId))
			AND IsObsolete=0
	
			declare @cnt int,@i int,@res varchar(max)=''
			select @cnt = count(*),@i = 1 from @tbltmp
	
			select @res = @res + '<tr>'
	
			while @i<= @cnt
			begin		
				select @res = @res + '
				<td style="font-size: 11px; font-weight: bold; padding: 3px; background: none repeat scroll 0% 0% #F4F9FE; border: 1px solid #E5EFF8; text-align: center; color: #66A3D3;"  width="30"> Self </td>
				<td style="font-size: 11px; font-weight: bold; padding: 3px; background: none repeat scroll 0% 0% #F4F9FE; border: 1px solid #E5EFF8; text-align: center; color: #66A3D3;"  width="50"> Manager </td>
				<td style="font-size: 11px; font-weight: bold; padding: 3px; background: none repeat scroll 0% 0% #F4F9FE; border: 1px solid #E5EFF8; text-align: center; color: #66A3D3;"  width="85"> Bussiness Head </td>'
				select @i = @i + 1		
			end
			select @res = @res + '</tr></table>'
	
			select @lTableHead = @lTableHead + @res
			select @lTableTail = @lTableTail + '</td></tr>'
	
			declare @lTableResult varchar(max)=''
			select @lTableResult = @lTableResult + '<tr>
			<td style="color: #678197; text-align: center; border: 1px solid #E5EFF8; background: none repeat scroll 0% 0% #FFF; margin: 0px; padding: 2px;">' + CONVERT(VARCHAR, ROW_NUMBER() OVER (ORDER BY KED.Id))  + '</td>
			<td style="color: #678197; text-align: center; border: 1px solid #E5EFF8; background: none repeat scroll 0% 0% #FFF; margin: 0px; padding: 2px; font-size: 12PX;
    font-weight: 600" >' + isnull(KED.Indicator,'') + '</td>
			' + [sAppraisal].[fGetInnerHtml](KED.Id) + '</tr>'
			from [sAppraisal].[tKPAEmployee] AS KPA
			LEFT JOIN [sAppraisal].[tKPAEmployeeDetail] AS KED ON KED.KPAEmployeeId = KPA.Id
	
	
			WHERE KED.KPATypeId=@rKPATypeId AND KPA.EmployeeId = @rEmployeeId AND KPA.BatchId = @rBatchId
			ORDER BY KED.Id
		
			select @lTableMain + @lTableHead + @lTableTail + @lTableResult + '</table>' as Head,CONVERT(BIT,1) AS Status
		END
	ELSE
	BEGIN
		select '<table width="100%"><tr><td style="width: 100%; text-align: center; color: rgb(102, 163, 211); font-size: 15px; font-weight: bold; background: rgb(244, 249, 254); border-width: 1px; border-style: solid; border-color: rgb(229, 239, 248); border-image: initial; padding: 7px;">No ratings available for the selected financial year</td></tr></table>' as Head, CONVERT(BIT,0) AS Status
	END
end
GO
PRINT N'Creating [sAppraisal].[pKPAEmployeeAdd]...';


GO
/******************************
** Name:  [sAppraisal].[pKPAEmployeeAdd]
** Desc:  Create and Update Data in Loan ConductTypeMaster
** Auth:  Savan Vaghela
** Date:  20-March-2017
** Page:  /Pages/Hrm/Appraisal/SetKPAForTeam.aspx
************************************************************
** Change History
************************************************************
** PR      Date                Author            Description 
**
** 1    20-March-2017      Savan Vaghela       
************************************************************/
--[sAppraisal].[pKPAEmployeeAdd]
CREATE PROCEDURE [sAppraisal].[pKPAEmployeeAdd]
	    @rEmployeeId BIGINT,
		@rBatchId INT,
		@rKPATemplateId INT,
		@rOrgId SmallINT,
		@rOrgGroupId SmallINT,
		@rCreatedUserId bigint,
		@KPATypeId NVARCHAR(MAX),
		@KPAMeasureId NVARCHAR(MAX),
		@Indicator NVARCHAR(MAX),
		@IndicatorRemark NVARCHAR(MAX),
		@Weightage NVARCHAR(MAX)
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
		BEGIN TRANSACTION	
		
		DECLARE @lNextNumber BIGINT 
		DECLARE @KPAEmployeeId BIGINT 
		

		IF NOT EXISTS(SELECT Id FROM [sAppraisal].[tKPAEmployee]  WHERE EmployeeId=@rEmployeeId AND BatchId=@rBatchId )
			BEGIN
				EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAppraisal.tKPAEmployee', 0, 1, 1,@outNextNumber = @lNextNumber output
		
				INSERT INTO [sAppraisal].[tKPAEmployee]
				(
					Id,
					EmployeeId,
					KPAStatusId,
					BatchId,
					KPATemplateId,
					CreatedUserId,
					CreatedDateTime
					
				)
				VALUES
				(
					@lNextNumber,
					@rEmployeeId,
					2,
					@rBatchId,
					@rKPATemplateId,
					@rCreatedUserId,
					sCommon.fGetDate()			
				)

				INSERT INTO [sAppraisal].[tKPAEmployeeDetail](KPAEmployeeId,KPATypeId,KPAMeasureId,Indicator,IndicatorRemark,Weightage)
				SELECT @lNextNumber,KPATypeId.item,KPAMeasureId.item,ISNULL(Indicator.item,''),ISNULL(IndicatorRemark.item,''),Weightage.item
				FROM scommon.fnSplitRowID(@KPATypeId,',') AS KPATypeId
				LEFT JOIN (SELECT * FROM scommon.fnSplitRowID(@IndicatorRemark,',')) AS IndicatorRemark
				ON KPATypeId.RowID=IndicatorRemark.RowID
				LEFT JOIN (SELECT * FROM scommon.fnSplitRowID(@Weightage,','))AS Weightage
				ON KPATypeId.RowID=Weightage.RowID
				LEFT JOIN (SELECT * FROM scommon.fnSplitRowID(@Indicator,','))AS Indicator
				ON KPATypeId.RowID=Indicator.RowID   
				LEFT JOIN (SELECT * FROM scommon.fnSplitRowID(@KPAMeasureId,','))AS KPAMeasureId
				ON KPATypeId.RowID=KPAMeasureId.RowID  
				
				SELECT 1 AS Result
			END	 
		ELSE
			BEGIN

			SELECT @KPAEmployeeId=Id FROM [sAppraisal].[tKPAEmployee]  WHERE EmployeeId=@rEmployeeId AND BatchId=@rBatchId
						
				UPDATE  [sAppraisal].[tKPAEmployee]
				SET
					KPATemplateId=@rKPATemplateId,
					KPAStatusId=2,
					UpdatedUserId=@rCreatedUserId,
					UpdatedDateTime=sCommon.fGetDate()
				WHERE EmployeeId=@rEmployeeId AND BatchId=@rBatchId
				
				DELETE FROM [sAppraisal].[tKPAEmployeeDetail] WHERE KPAEmployeeId=@KPAEmployeeId
				
				INSERT INTO [sAppraisal].[tKPAEmployeeDetail](KPAEmployeeId,KPATypeId,KPAMeasureId,Indicator,IndicatorRemark,Weightage)
				
				SELECT @KPAEmployeeId,KPATypeId.item,KPAMeasureId.item,ISNULL(Indicator.item,''),ISNULL(IndicatorRemark.item,''),Weightage.item
				FROM scommon.fnSplitRowID(@KPATypeId,',') AS KPATypeId
				LEFT JOIN (SELECT * FROM scommon.fnSplitRowID(@IndicatorRemark,',')) AS IndicatorRemark
				ON KPATypeId.RowID=IndicatorRemark.RowID
				LEFT JOIN (SELECT * FROM scommon.fnSplitRowID(@Weightage,','))AS Weightage
				ON KPATypeId.RowID=Weightage.RowID
				LEFT JOIN (SELECT * FROM scommon.fnSplitRowID(@Indicator,','))AS Indicator
				ON KPATypeId.RowID=Indicator.RowID   
				LEFT JOIN (SELECT * FROM scommon.fnSplitRowID(@KPAMeasureId,','))AS KPAMeasureId
				ON KPATypeId.RowID=KPAMeasureId.RowID  
				
				
				SELECT 11 AS Result
			END  	
		COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END
GO
PRINT N'Creating [sAppraisal].[pKPAEmployeeDetailGet]...';


GO
/******************************
** Name:  [sAppraisal].[pKPATemplateMasterGet]
** Desc:  Create and Update Data in Loan ConductTypeMaster
** Auth:  Savan Vaghela
** Date:  17-March-2017
** Page:  /Pages/Hrm/Appraisal/KPATemplatesMaster.aspx
************************************************************
** Change History
************************************************************
** PR      Date                Author            Description 
**
** 1    17-March-2017      Savan Vaghela       
************************************************************/
-- [sAppraisal].[pKPAEmployeeDetailGet] 1001000000001
CREATE PROCEDURE [sAppraisal].[pKPAEmployeeDetailGet]
	@KPAEmployeeId BIGINT
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	
	
	SELECT 
		KED.Id
		,Indicator AS Name
		, KPAMeasureId AS Type
		, IndicatorRemark AS Remarks
		,CONVERT(int,Weightage) AS Weightage
		,KMD.Title AS TypeName 
	FROM [sAppraisal].[tKPAEmployeeDetail] AS KED
		LEFT JOIN [sAppraisal].[tKPAMeasureMaster] AS KMD ON KMD.Id=KED.KPAMeasureId
	WHERE  KPAEmployeeId=@KPAEmployeeId AND KPATypeId=1 
	ORDER BY Id
	
	SELECT 
		KED.Id
		,Indicator AS Name
		, KPAMeasureId AS Type
		, IndicatorRemark AS Remarks
		,CONVERT(int,Weightage) AS Weightage
		,KMD.Title AS TypeName 
	FROM [sAppraisal].[tKPAEmployeeDetail] AS KED
		LEFT JOIN [sAppraisal].[tKPAMeasureMaster] AS KMD ON KMD.Id=KED.KPAMeasureId
	WHERE  KPAEmployeeId=@KPAEmployeeId AND KPATypeId=2 
	ORDER BY Id
	
	
	SELECT KPAStatusId,KPS.Title AS KPAStatus 
	FROM [sAppraisal].[tKPAStatus] AS KPS
		INNER JOIN [sAppraisal].[tKPAEmployee]  AS EMP on EMP.KPAStatusId=KPS.Id
	WHERE EMP.id=@KPAEmployeeId






END
GO
PRINT N'Creating [sAppraisal].[pKPAEmployeeGet]...';


GO
/******************************
** Name:  [sAppraisal].[pKPAEmployeeGet]
** Desc:  Get Employee details for set KPA Details
** Auth:  Savan Vaghela
** Date:  18-March-2017
** Page:  /Pages/Hrm/Appraisal/SetKPAForTeam.aspx
************************************************************
** Change History
************************************************************
** PR      Date                Author            Description 
**
** 1    18-March-2017      Savan Vaghela       
************************************************************/
--[sAppraisal].[pKPAEmployeeGet] 1002000000011,0,0,1001
CREATE PROCEDURE [sAppraisal].[pKPAEmployeeGet]
	@rEmployeeManagerId BIGINT,
	@rBatchId int,
	@rOrgId smallint,
	@rOrgGroupId smallint
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 

	select 
		EMP.Id
		,EMP.Code
		,ISNULL(EMP.FirstName,'') +' '+ ISNULL(EMP.LastName,'') AS Employee
		,ISNULL(DEP.Id,'') AS DepartmentId
		,ISNULL(DEP.Title,'') AS DepartmentName
		,ISNULL(DEG.Id,'') AS DesignationId
		,ISNULL(DEG.Title,'') AS DesignationName
		,EMP.ShortName
		,EMP.StatusId
		,EJD.EmployeeManagerId
		,ISNULL(EMD.FirstName,'') +' '+ISNULL(EMD.LastName,'') AS ManagerName
		,EMP.OrgID
		,ORG.DisplayTitle
		,ISNULL(KPAStatus.KPAStatusId,1) AS KPAStatusId
		,(SELECT Title FROM [sAppraisal].[tKPAStatus] WHERE Id=ISNULL(KPAStatus.KPAStatusId,1)) AS KPAStatus
		,CASE WHEN ISNULL(KPAStatus.KPAStatusId,1) in (1,4) THEN CONVERT(BIT,1) ELSE CONVERT(BIT,0) END AS Enabled
	from [sHrm].[tEmployeeMaster]  AS EMP
		LEFT JOIN [sHrm].[tEmployeeJobDetail] AS EJD On EJD.EmployeeId=EMP.Id
		LEFT JOIN [sHrm].[tEmployeeMaster] AS EMD ON EMD.Id= EJD.EmployeeManagerId
		LEFT JOIN [sSetup].[tOrganizationMaster] AS ORG ON Org.id=EMP.OrgID
		LEFT JOIN [sSetup].[tDepartmentMaster] AS DEP ON DEP.Id=EJD.OrganizationDepartmentId
		LEFT JOIN [sHrm].[tEmployeeDesignationMaster] AS DEG ON DEG.Id=EJD.EmployeeDesignationId
		LEFT JOIN (
					SELECT EmployeeId,KPAStatusId 
					FROM [sAppraisal].[tKPAEmployee] 
					Where BatchId=@rBatchId
				  ) AS KPAStatus
				    ON KPAStatus.EmployeeId=EMP.Id
	where 
		ORG.OrgGroupId=@rOrgGroupId 
		AND ((EMP.OrgID=@rOrgId)OR(@rOrgId=0))
		AND	EJD.EmployeeManagerId=@rEmployeeManagerId 
		AND Emp.ID<>@rEmployeeManagerId 
		AND EMP.StatusId=7

	Order by EMP.FirstName, EMP.Code
END
GO
PRINT N'Creating [sAppraisal].[pKPAEmployeeRatingAdd]...';


GO
/******************************
** Name:  [sAppraisal].[pConductTypeMasterAdd]
** Desc:  Create and Update Data in Loan ConductTypeMaster
** Auth:  Savan Vaghela
** Date:  17-March-2017
** Page:  /Pages/Hrm/Appraisal/KPATemplatesMaster.aspx
************************************************************
** Change History
************************************************************
** PR      Date                Author            Description 
**
** 1    17-March-2017      Savan Vaghela       
************************************************************/
--[sAppraisal].[pConductTypeMasterAdd]
CREATE PROCEDURE [sAppraisal].[pKPAEmployeeRatingAdd]
	  	@rOrgId                       SMALLINT,
		@rCreatedUserId				  BIGINT,
		@rAppraisalTypeId			  INT,
		@rKPAEmployeeId				  BIGINT
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
		BEGIN TRANSACTION	
		
		DECLARE @lNextNumber BIGINT 
						 
			BEGIN
				EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAppraisal.tKPAEmployeeRating', 0, 1, 1,@outNextNumber = @lNextNumber output
				INSERT INTO [sAppraisal].[tKPAEmployeeRating]
				(
					Id,
					AppraisalTypeId,
					KPAEmployeeId,
					RatingStatusId,
				 	CreatedUserId,
					CreatedDateTime
					
				)
				VALUES
				(
					@lNextNumber,
					@rAppraisalTypeId,
					@rKPAEmployeeId,
					2,
				 	@rCreatedUserId,
					sCommon.fGetDate()			
				)

				 INSERT INTO [sAppraisal].[tKPAEmployeeRatingDetail](KPAEmployeeRatingId,KPAEmployeeDetailId)
				 SELECT @lNextNumber,Id FROM [sAppraisal].[tKPAEmployeeDetail]  WHERE KPAEmployeeId=@rKPAEmployeeId ORDER BY Id
				
				SELECT 1 AS Result
			END	 
		 
		COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END
GO
PRINT N'Creating [sAppraisal].[pKPAEmployeeRatingStatusChange]...';


GO
/******************************
** Name:  [sAppraisal].[pKPAEmployeeRatingStatusChange]
** Desc:  Employee Rating Status SET
** Auth:  Savan Vaghela
** Date:  22-March-2017
** Page:  /Pages/Hrm/Appraisal/EmployeeRateEntry.aspx
************************************************************
** Change History
************************************************************
** PR      Date                Author            Description 
**
** 1    22-March-2017      Savan Vaghela       
************************************************************/
--[sAppraisal].[pKPAEmployeeRatingStatusChange] 1001000000172,100100114,100100042,3,'7,8,9,10,11,12,','1,1,1,1,1,1,','a,b,c,d,e,f'
CREATE PROCEDURE [sAppraisal].[pKPAEmployeeRatingStatusChange]
	   @rEmployeeId BIGINT,
	   @rBatchId INT ,
	   @rAppraisalTypeId INT,
	   @rRatingStatusId INT,
	   @rKPAEmployeeDetailId NVARCHAR(MAX),
	   @rMyRating NVARCHAR(MAX),
	   @rMyRemark NVARCHAR(MAX),
	   @rRecommendationIncrement DECIMAL(5,2)=null,
	   @rRecommendationDesignation nvarchar(200)=null,
	   @rRecommendationJustification nvarchar(200)=null
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
		BEGIN TRANSACTION	
			
			DECLARE @KPAEmployeeId BIGINT,@KPAEmployeeRatingId BIGINT
			SELECT @KPAEmployeeId =Id FROM [sAppraisal].[tKPAEmployee] WHERE EmployeeId=@rEmployeeId AND BatchId=@rBatchId
			SET @KPAEmployeeId=ISNULL(@KPAEmployeeId,0)
			 
			UPDATE [sAppraisal].[tKPAEmployeeRating] SET RatingStatusId=@rRatingStatusId WHERE AppraisalTypeId=@rAppraisalTypeId AND KPAEmployeeId=@KPAEmployeeId

			IF (@rRatingStatusId=4)
				BEGIN
					UPDATE [sAppraisal].[tKPAEmployeeRating]  
						SET RecommendationIncrement=@rRecommendationIncrement
							,RecommendationDesignation=@rRecommendationDesignation
							,RecommendationJustification=@rRecommendationJustification
						WHERE AppraisalTypeId=@rAppraisalTypeId AND KPAEmployeeId=@KPAEmployeeId
				END


			SELECT @KPAEmployeeRatingId=Id FROM [sAppraisal].[tKPAEmployeeRating] WHERE AppraisalTypeId=@rAppraisalTypeId AND KPAEmployeeId=@KPAEmployeeId
			SET @KPAEmployeeRatingId=ISNULL(@KPAEmployeeRatingId,0)


			
			DECLARE @Counter SMALLINT=(SELECT COUNT(1)FROM scommon.fnSplitRowID(@rKPAEmployeeDetailId,','))
			DECLARE @RatingDetailTable TABLE (RowID int ,DetailId BIGINT,MyRating DECIMAL(10,2),MyRemark NVARCHAR(400))

				
			INSERT INTO @RatingDetailTable
			SELECT DetailId.RowID,DetailId.item,MyRating.item,MyRemark.item FROM scommon.fnSplitRowID(@rKPAEmployeeDetailId,',') AS DetailId
			LEFT JOIN (SELECT * FROM scommon.fnSplitRowID(@rMyRating,',')) AS MyRating
			ON DetailId.RowID= MyRating.RowID
			LEFT JOIN (SELECT * FROM scommon.fnSplitRowID(@rMyRemark,',')) AS MyRemark
			ON DetailId.RowID= MyRemark.RowID
		 
			WHILE (@Counter <>0)
				BEGIN
					DECLARE @KPAEmployeeDetailId BIGINT,@MyRating DECIMAL(10,2),@MyRemark NVARCHAR(400)
					SELECT @KPAEmployeeDetailId=DetailId,@MyRating=MyRating,@MyRemark=MyRemark FROM @RatingDetailTable WHERE RowID=@Counter
					--PRINT 'KPAEmployeeDetailId ' + CONVERT(NVARCHAR(20),@KPAEmployeeDetailId) + ',  MyRating '+ CONVERT(NVARCHAR(20),@MyRating) + ', MyRemark ' ++ CONVERT(NVARCHAR(20),@MyRemark)

					IF (@rRatingStatusId=3)
						BEGIN
							UPDATE [sAppraisal].[tKPAEmployeeRatingDetail] SET MyRating=@MyRating,MyRemark=@MyRemark WHERE KPAEmployeeDetailId=@KPAEmployeeDetailId AND KPAEmployeeRatingId=@KPAEmployeeRatingId
						END
					ELSE IF (@rRatingStatusId=4)
						BEGIN
							UPDATE [sAppraisal].[tKPAEmployeeRatingDetail] SET ManagerRating=@MyRating,ManagerRemark=@MyRemark WHERE KPAEmployeeDetailId=@KPAEmployeeDetailId AND KPAEmployeeRatingId=@KPAEmployeeRatingId
						END

					
					SET @Counter=@Counter-1
				END
		
		SELECT 1 AS Result
			 
		COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END
GO
PRINT N'Creating [sAppraisal].[pKPAEmployeeStatusChange]...';


GO
/******************************
** Name:  [sAppraisal].[pKPATemplateMasterGet]
** Desc:  Create and Update Data in Loan ConductTypeMaster
** Auth:  Savan Vaghela
** Date:  17-March-2017
** Page:  /Pages/Hrm/Appraisal/KPATemplatesMaster.aspx
************************************************************
** Change History
************************************************************
** PR      Date                Author            Description 
**
** 1    17-March-2017      Savan Vaghela       
************************************************************/
-- [sAppraisal].[pKPAEmployeeStatusChange] 1001000000001
CREATE PROCEDURE [sAppraisal].[pKPAEmployeeStatusChange]
	@rEmployeeId BIGINT,
	@rBatchId INT,
	@rKPAStatusId TINYINT
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	BEGIN TRY
		BEGIN TRANSACTION	
			UPDATE [sAppraisal].[tKPAEmployee] SET KPAStatusId=@rKPAStatusId  WHERE EmployeeId=@rEmployeeId AND 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 [sAppraisal].[pKPATemplateDetailGet]...';


GO
/******************************
** Name:  [sAppraisal].[pKPATemplateMasterGet]
** Desc:  Create and Update Data in Loan ConductTypeMaster
** Auth:  Savan Vaghela
** Date:  17-March-2017
** Page:  /Pages/Hrm/Appraisal/KPATemplatesMaster.aspx
************************************************************
** Change History
************************************************************
** PR      Date                Author            Description 
**
** 1    17-March-2017      Savan Vaghela       
************************************************************/
-- [sAppraisal].[pKPATemplateDetailGet] 100100001
CREATE PROCEDURE [sAppraisal].[pKPATemplateDetailGet]
	@KPATemplateId INT

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	SELECT AutoId AS Id, Indicator AS Name, KPAMeasureId AS Type, IndicatorRemark AS Remarks,CONVERT(int,Weightage) AS Weightage FROM [sAppraisal].[tKPATemplateDetail] WHERE  KPATemplateId=@KPATemplateId AND KPATypeId=1 ORDER BY AutoId
	SELECT AutoId AS Id, Indicator AS Name, KPAMeasureId AS Type, IndicatorRemark AS Remarks,CONVERT(int,Weightage) AS Weightage FROM [sAppraisal].[tKPATemplateDetail] WHERE  KPATemplateId=@KPATemplateId AND KPATypeId=2 ORDER BY AutoId
END
GO
PRINT N'Creating [sAppraisal].[pKPATemplateMasterAdd]...';


GO
/******************************
** Name:  [sAppraisal].[pConductTypeMasterAdd]
** Desc:  Create and Update Data in Loan ConductTypeMaster
** Auth:  Savan Vaghela
** Date:  17-March-2017
** Page:  /Pages/Hrm/Appraisal/KPATemplatesMaster.aspx
************************************************************
** Change History
************************************************************
** PR      Date                Author            Description 
**
** 1    17-March-2017      Savan Vaghela       
************************************************************/
--[sAppraisal].[pConductTypeMasterAdd]
CREATE PROCEDURE [sAppraisal].[pKPATemplateMasterAdd]
	    @rId int,
		@rTitle nvarchar(100),
		@rRemark nvarchar(400),
		@rOrgId SmallINT,
		@rOrgGroupId SmallINT,
		@rIsObsolete bit =null,
        @rCreatedUserId bigint,
		@KPATypeId NVARCHAR(MAX),
		@KPAMeasureId NVARCHAR(MAX),
		@Indicator NVARCHAR(MAX),
		@IndicatorRemark NVARCHAR(MAX),
		@Weightage NVARCHAR(MAX)
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY



		IF(@rId = 0)	
				BEGIN
					IF Exists(SELECT Id FROM [sAppraisal].[tKPATemplateMaster]  WHERE Indicator=@rTitle AND OrgGroupId=@rOrgGroupId )
						BEGIN
							SELECT -102 as Result
							RETURN
						END 
				END
		
			ELSE
				BEGIN
					IF  Exists(SELECT Id FROM [sAppraisal].[tKPATemplateMaster]  WHERE Indicator=@rTitle AND OrgGroupId=@rOrgGroupId AND Id<>@rId )
						BEGIN
							SELECT -102 as Result
							RETURN
						END
				END


		BEGIN TRANSACTION	
		
		DECLARE @lNextNumber BIGINT 


		IF(@rId = 0)	
			BEGIN
				EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAppraisal.tKPATemplateMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
				INSERT INTO [sAppraisal].[tKPATemplateMaster]
				(
					Id,
					Indicator,
					Remark,
					OrgGroupId,
					IsObsolete,
					CreatedUserId,
					CreatedDateTime
					
				)
				VALUES
				(
					@lNextNumber,
					@rTitle,
					@rRemark,
					@rOrgGroupId,
					0,
					@rCreatedUserId,
					sCommon.fGetDate()			
				)

				INSERT INTO [sAppraisal].[tKPATemplateDetail](KPATemplateId,KPATypeId,KPAMeasureId,Indicator,IndicatorRemark,Weightage)
				SELECT @lNextNumber,KPATypeId.item,KPAMeasureId.item,ISNULL(Indicator.item,''),ISNULL(IndicatorRemark.item,''),Weightage.item
				FROM scommon.fnSplitRowID(@KPATypeId,',') AS KPATypeId
				LEFT JOIN (SELECT * FROM scommon.fnSplitRowID(@IndicatorRemark,',')) AS IndicatorRemark
				ON KPATypeId.RowID=IndicatorRemark.RowID
				LEFT JOIN (SELECT * FROM scommon.fnSplitRowID(@Weightage,','))AS Weightage
				ON KPATypeId.RowID=Weightage.RowID
				LEFT JOIN (SELECT * FROM scommon.fnSplitRowID(@Indicator,','))AS Indicator
				ON KPATypeId.RowID=Indicator.RowID   
				LEFT JOIN (SELECT * FROM scommon.fnSplitRowID(@KPAMeasureId,','))AS KPAMeasureId
				ON KPATypeId.RowID=KPAMeasureId.RowID  
				
				SELECT 1 AS Result
			END	 
		ELSE
			BEGIN
			SET @lNextNumber = @rId
				UPDATE  [sAppraisal].[tKPATemplateMaster]
				SET
					Indicator=@rTitle,
					Remark=@rRemark,
					IsObsolete=@rIsObsolete,
					UpdatedUserId=@rCreatedUserId,
					UpdatedDateTime=sCommon.fGetDate()
				WHERE Id = @rId
				
				DELETE FROM [sAppraisal].[tKPATemplateDetail] WHERE KPATemplateId=@lNextNumber
				
				INSERT INTO [sAppraisal].[tKPATemplateDetail](KPATemplateId,KPATypeId,KPAMeasureId,Indicator,IndicatorRemark,Weightage)
				
				SELECT @lNextNumber,KPATypeId.item,KPAMeasureId.item,ISNULL(Indicator.item,''),ISNULL(IndicatorRemark.item,''),Weightage.item
				FROM scommon.fnSplitRowID(@KPATypeId,',') AS KPATypeId
				LEFT JOIN (SELECT * FROM scommon.fnSplitRowID(@IndicatorRemark,',')) AS IndicatorRemark
				ON KPATypeId.RowID=IndicatorRemark.RowID
				LEFT JOIN (SELECT * FROM scommon.fnSplitRowID(@Weightage,','))AS Weightage
				ON KPATypeId.RowID=Weightage.RowID
				LEFT JOIN (SELECT * FROM scommon.fnSplitRowID(@Indicator,','))AS Indicator
				ON KPATypeId.RowID=Indicator.RowID   
				LEFT JOIN (SELECT * FROM scommon.fnSplitRowID(@KPAMeasureId,','))AS KPAMeasureId
				ON KPATypeId.RowID=KPAMeasureId.RowID  
				
				
				SELECT 11 AS Result
			END  	
		COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END
GO
PRINT N'Creating [sAppraisal].[pKPATemplateMasterGet]...';


GO
/******************************
** Name:  [sAppraisal].[pKPATemplateMasterGet]
** Desc:  Create and Update Data in Loan ConductTypeMaster
** Auth:  Savan Vaghela
** Date:  17-March-2017
** Page:  /Pages/Hrm/Appraisal/KPATemplatesMaster.aspx
************************************************************
** Change History
************************************************************
** PR      Date                Author            Description 
**
** 1    17-March-2017      Savan Vaghela       
************************************************************/
-- [sAppraisal].[pKPATemplateMasterGet] 1001,''
CREATE PROCEDURE [sAppraisal].[pKPATemplateMasterGet]
	@rOrgGroupId SmallINT,
	@rTitle NVARCHAR(250)
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 

	SET @rTitle = sCommon.fSearchStringGet(@rTitle)
	
	SELECT 
		KTM.Id
		,KTM.Indicator
		,KTM.Remark
		,USR.DisplayTitle
		,KTM.[IsObsolete]
		,CONVERT(VARCHAR,KTM.CreatedDateTime,107)CreatedDateTime
		,CASE KTM.[IsObsolete] WHEN 0 THEN 'Y' ELSE 'N' END AS InActive
	FROM 
		[sAppraisal].[tKPATemplateMaster] AS KTM
		LEFT  JOIN [sSecurity].[tUser]    AS USR ON USR.Id=KTM.CreatedUserId 
	WHERE  (KTM.OrgGroupId = @rOrgGroupId)  AND 
			  ((KTM.Indicator LIKE @rTitle) OR (@rTitle=''))    
	ORDER BY KTM.CreatedDateTime 

END
GO
PRINT N'Creating [sAppraisal].[pRolloutAppraisalsStatusGet]...';


GO
/******************************
** Name:  [sAppraisal].[pKPAEmployeeGet]
** Desc:  Get Employee details for set KPA Details
** Auth:  Savan Vaghela
** Date:  18-March-2017
** Page:  /Pages/Hrm/Appraisal/SetKPAForTeam.aspx
************************************************************
** Change History
************************************************************
** PR      Date                Author            Description 
**
** 1    21-March-2017      Savan Vaghela       
************************************************************/
--[sAppraisal].[pRolloutAppraisalsStatusGet] 1002000000011,0,0,1001,0
--[sAppraisal].[pRolloutAppraisalsStatusGet] 0,100100114,1001,1001,0
CREATE PROCEDURE [sAppraisal].[pRolloutAppraisalsStatusGet]
	@rEmployeeManagerId           BIGINT,
	@rBatchId					  INT,
	@rOrgId						  SMALLINT,
	@rOrgGroupId				  SMALLINT,
	@rAppraisalTypeId			  INT
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 

	SELECT 
		EMP.Id
		,EMP.Code
		,ISNULL(EMP.FirstName,'') +' '+ ISNULL(EMP.LastName,'') AS Employee
		,ISNULL(DEP.Id,'') AS DepartmentId
		,ISNULL(DEP.Title,'') AS DepartmentName
		,ISNULL(DEG.Id,'') AS DesignationId
		,ISNULL(DEG.Title,'') AS DesignationName
		,EMP.ShortName
		,EMP.StatusId
		,EJD.EmployeeManagerId
		,ISNULL(EMD.FirstName,'') +' '+ISNULL(EMD.LastName,'') AS ManagerName
		,EMP.OrgID
		,ORG.DisplayTitle
		,ISNULL(KPAStatus.KPAStatusId,1) AS KPAStatusId
		,(SELECT Title FROM [sAppraisal].[tKPAStatus] WHERE Id=ISNULL(KPAStatus.KPAStatusId,1)) AS KPAStatus
		,ISNULL(RatingStatus.RatingStatusId,1) AS RatingStatusId
		,CASE WHEN ISNULL(KPAStatus.KPAStatusId,1)=3 AND ISNULL(RatingStatus.RatingStatusId,1)=1 THEN CONVERT(BIT,1) ELSE CONVERT(BIT,0) END AS Enable
		--,CONVERT(BIT,1)  AS Enable
		,(SELECT Title FROM [sAppraisal].[tRatingStatus] WHERE Id=ISNULL(RatingStatus.RatingStatusId,1)) AS RattingStatus
		,ISNULL(KPAEmployee.KPAEmployeeId,0) KPAEmployeeId
	FROM [sHrm].[tEmployeeMaster]  AS EMP
		LEFT JOIN [sHrm].[tEmployeeJobDetail] AS EJD On EJD.EmployeeId=EMP.Id
		LEFT JOIN [sHrm].[tEmployeeMaster] AS EMD ON EMD.Id= EJD.EmployeeManagerId
		LEFT JOIN [sSetup].[tOrganizationMaster] AS ORG ON Org.id=EMP.OrgID
		LEFT JOIN [sSetup].[tDepartmentMaster] AS DEP ON DEP.Id=EJD.OrganizationDepartmentId
		LEFT JOIN [sHrm].[tEmployeeDesignationMaster] AS DEG ON DEG.Id=EJD.EmployeeDesignationId
		LEFT JOIN (
					SELECT EmployeeId,KPAStatusId 
					FROM [sAppraisal].[tKPAEmployee] 
					Where BatchId=@rBatchId
				  ) AS KPAStatus
			    ON KPAStatus.EmployeeId=EMP.Id
		LEFT JOIN (
					SELECT ERD.AppraisalTypeId,KPA.EmployeeId,ERD.RatingStatusId FROM [sAppraisal].[tKPAEmployee] AS KPA 
					INNER JOIN [sAppraisal].[tKPAEmployeeRating] AS ERD on ERD.KPAEmployeeId=KPA.Id
					WHERE KPA.BatchId=@rBatchId AND ERD.AppraisalTypeId=@rAppraisalTypeId
		) AS  RatingStatus ON RatingStatus.EmployeeId =EMP.Id  

		LEFT JOIN (
					SELECT Id AS KPAEmployeeId,EmployeeId  FROM [sAppraisal].[tKPAEmployee] Where BatchId=@rBatchId
				  ) AS KPAEmployee ON  KPAEmployee.EmployeeId=EMP.Id
	where 
		ORG.OrgGroupId=@rOrgGroupId 
		AND ((EMP.OrgID=@rOrgId)OR(@rOrgId=0))
		AND	EJD.EmployeeManagerId=@rEmployeeManagerId 
		AND Emp.ID<>@rEmployeeManagerId 
		AND EMP.StatusId=7

	Order by EMP.FirstName, EMP.Code
END
GO
PRINT N'Creating [sAssessment].[pActivityDefaultAdd]...';


GO
 
CREATE PROCEDURE [sAssessment].[pActivityDefaultAdd]
	 @rExamdId int,
	@rClassId int	
AS
BEGIN
 
	SET NOCOUNT ON;
	
    
END
GO
PRINT N'Creating [sAssessment].[pCCEResultOverallGradeUpdate]...';


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

	
		DECLARE @MinimumScore decimal(5,2)
		DECLARE @GradeTitle nvarchar(10)
		DECLARE @GradePoint decimal(6,2)
		DECLARE @lCount int
		DECLARE @lDataSetID INT
		DECLARE @lMaxiMark Decimal(5,2)
		--SELECT @lDataSetID=GradeSetId FROM sAssessment.tExamMaster WHERE Id = @rCCEExamId 
		
		
		 --  Update  D  Set D.FATerm1 = NULL FROM
			--sAssessment.tCCEResultDetail D INNER JOIN sStudent.tAcademic A ON D.AcademicId = A.Id
			----INNER JOIN #tempAcademic TA ON D.AcademicId = TA.AcademicId AND D.ClassSubjectId = TA.ClassSubjectid
			--WHERE A.BatchId = @rBatchId AND A.DivisionId = @rDivisionId AND A.ClassId = @rClassId
			
		 --  Update  D  Set D.Term1Grade = NULL FROM
			--sAssessment.tCCEResultDetail D INNER JOIN sStudent.tAcademic A ON D.AcademicId = A.Id
			----INNER JOIN #tempAcademic TA ON D.AcademicId = TA.AcademicId AND D.ClassSubjectId = TA.ClassSubjectid
			--WHERE A.BatchId = @rBatchId AND A.DivisionId = @rDivisionId AND A.ClassId = @rClassId	
			
			--Update  D  Set D.FATerm2 = NULL FROM
			--sAssessment.tCCEResultDetail D INNER JOIN sStudent.tAcademic A ON D.AcademicId = A.Id
			----INNER JOIN #tempAcademic TA ON D.AcademicId = TA.AcademicId AND D.ClassSubjectId = TA.ClassSubjectid
			--WHERE A.BatchId = @rBatchId AND A.DivisionId = @rDivisionId AND A.ClassId = @rClassId	

			
			--Update  D  Set D.SAGRADE = NULL FROM
			--sAssessment.tCCEResultDetail D INNER JOIN sStudent.tAcademic A ON D.AcademicId = A.Id
			----INNER JOIN #tempAcademic TA ON D.AcademicId = TA.AcademicId AND D.ClassSubjectId = TA.ClassSubjectid
			--WHERE A.BatchId = @rBatchId AND A.DivisionId = @rDivisionId AND A.ClassId = @rClassId			 

			--Update  D  Set D.FAGRADE = NULL FROM
			--sAssessment.tCCEResultDetail D INNER JOIN sStudent.tAcademic A ON D.AcademicId = A.Id
			----INNER JOIN #tempAcademic TA ON D.AcademicId = TA.AcademicId AND D.ClassSubjectId = TA.ClassSubjectid
			--WHERE A.BatchId = @rBatchId AND A.DivisionId = @rDivisionId AND A.ClassId = @rClassId			 

	        
	  --      Update  D  Set D.Term2Grade = NULL FROM
			--sAssessment.tCCEResultDetail D INNER JOIN sStudent.tAcademic A ON D.AcademicId = A.Id
			----INNER JOIN #tempAcademic TA ON D.AcademicId = TA.AcademicId AND D.ClassSubjectId = TA.ClassSubjectid
			--WHERE A.BatchId = @rBatchId AND A.DivisionId = @rDivisionId AND A.ClassId = @rClassId	

			
			--Update  D  Set D.Grade = NULL FROM  
			--sAssessment.tCCEResultDetail D INNER JOIN sStudent.tAcademic A ON D.AcademicId = A.Id
			----INNER JOIN #tempAcademic TA ON D.AcademicId = TA.AcademicId AND D.ClassSubjectId = TA.ClassSubjectid
			--WHERE A.BatchId = @rBatchId AND A.DivisionId = @rDivisionId AND A.ClassId = @rClassId	
	
			
		
	
		 SELECT @lDataSetID=GradeSetId FROM sAssessment.tCCEExamSetting WHERE CCEExamId = @rCCEExamId AND ClassId = @rClassId AND BatchId = @rBatchId
 
		 -- CREATE TABLE #tempAcademic
			--(
			--	AcademicId bigint,
			--	classSubjectId decimal(5,2) 				 
			--) 
		 
		CREATE TABLE #tempGradeSetDetail
		(
		Id INT IDENTITY (1, 1),
		MinimumScore decimal(5,2),
		GradeTitle nvarchar(10),
		GradePoint decimal(6,2) 					 
		) 
			INSERT INTO #tempGradeSetDetail
		SELECT MinimumScore,GradeCode,GradePoint		
		FROM sAssessment.tGradeSetDetail where GradesetId=@lDataSetID
		order by MinimumScore DESC 
SELECT @lCount =  COUNT(Id) FROM #tempGradeSetDetail
while ( @lCount > 0 )
BEGIN
	SELECT
		@MinimumScore =MinimumScore,
		@GradeTitle=GradeTitle,
		@GradePoint=GradePoint
		FROM #tempGradeSetDetail WHERE Id = @lCount
		 
			 
			Update  D  Set D.AnnualGrade = @GradeTitle FROM
			sAssessment.tCCEResult D INNER JOIN sStudent.tAcademic A ON D.AcademicId = A.Id
			WHERE A.BatchId = @rBatchId AND A.DivisionId = @rDivisionId AND A.ClassId = @rClassId
			AND (D.CGPA * 10)>= @MinimumScore
			
			--AND SA2Max > 0
		 Set @lCount=@lCount-1
    END
END
GO
PRINT N'Creating [sAssessment].[pImportCoScholasticIndicator]...';


GO
CREATE PROCEDURE [sAssessment].[pImportCoScholasticIndicator]
    @rOrgId smallint,
	@rXmldoc [nvarchar](max),
	@rUserId bigint
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
BEGIN TRY

DECLARE @lCount INT
DECLARE @lInterrorCode INT,@intDoc INT,@lCoScholasticGroup nvarchar(100),@lCoScholastic nvarchar(100),
		@lTitle nvarchar(100),@lNumber int,@lOrderIndex int,@lCCECSId int
			
EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc
	
	CREATE TABLE #tTable  
	(
		Id bigint identity,	
		CoScholasticGroup nvarchar(100),
		CoScholastic nvarchar(100), 
		Number int, 
		Indicator nvarchar(100),
		OrderIndex int
	)
	INSERT INTO #tTable
	(   
		CoScholasticGroup, 
		CoScholastic,
		Number, 
		Indicator,
		OrderIndex 
	)
	SELECT
		CoScholasticGroup, 
		CoScholastic,
		Number, 
		Indicator,
		OrderIndex 
	FROM OPENXML (@intDoc, '/Table/ImportIndicator', 1)
	WITH
	( 
		CoScholasticGroup nvarchar(100) '@CoScholasticGroup',
		CoScholastic nvarchar(100)  '@CoScholastic',	
		Number Int '@Number',		
		Indicator nvarchar(100) '@Indicator',
		OrderIndex int '@OrderIndex'
	)
EXEC sp_xml_removedocument @intDoc
SELECT @lCount =  COUNT(Id) FROM #tTable

WHILE @lCount > 0 
BEGIN	
		SET @lCoScholasticGroup = ''
		SET @lCoScholastic = ''
		SET @lTitle = ''
		SET @lNumber = 0
		SET @lCCECSId = 0
		SET @lOrderIndex = 0
		
  SELECT		
		@lCoScholasticGroup = CoScholasticGroup,@lCoScholastic=CoScholastic,@lTitle = Indicator,@lNumber = Number,@lOrderIndex = OrderIndex
	  
FROM #tTable WHERE Id = @lCount  
		--BEGIN TRANSACTION
SELECT @lCCECSId=CM.id from sAssessment.tCCECSMaster CM INNER join  sAssessment.tCCECSGroupMaster  CG on CG.Id=CM.CCECAGroupId WHERE 
CM.OrgId=@rOrgId AND CM.Title=@lCoScholastic AND CG.Title=@lCoScholasticGroup

	 --IF NOT EXISTS(select 1 from sAssessment.tCCECSIndicatorMaster where Code=@lCode AND OrgId=@rOrgId)
  BEGIN	
		EXEC [sAssessment].[pCSIndicatorDetailAdd] 0,@lCCECSId,@lTitle,@lNumber,@lOrderIndex,0,@rUserId,0,@rOrgId
	END
		 SET @lCount = @lCount - 1
		--COMMIT TRANSACTION			
END
	SELECT 1
	END TRY
	BEGIN CATCH
	
	SELECT ERROR_MESSAGE(), ERROR_LINE()
	END CATCH
	
END
GO
PRINT N'Creating [sAssessment].[pImportSubjectActivity]...';


GO
CREATE PROCEDURE [sAssessment].[pImportSubjectActivity]
    @rOrgId smallint ,
	@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(100),@lTitle nvarchar(200),@lNumber int,@lGradeSetId int,@lOrderIndex int,	@lClass nvarchar(100),@lGradeSet nvarchar(100),
	    @lSubject nvarchar(100),  @lClassSubjectId int,@lSubCode nvarchar(100),@lSubTitle nvarchar(200),@lSubNumber int,@lSubOrderIndex int,@lSubjectActivityId int=0
EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc
	CREATE TABLE #tTable  
	(
		Id bigint identity,
		Code nvarchar(100), 
		Number int, 
		Name nvarchar(200),
		GradeSet nvarchar(100), 
		OrderIndex int,
	    Class Nvarchar(100),
	    Subject Nvarchar(100),
		SubNumber int, 
		SubCode nvarchar(100), 
		SubName nvarchar(200),
		SubOrderIndex int
	)
	INSERT INTO #tTable
	(  
		Code, Number,Name,GradeSet, OrderIndex ,Class,Subject,SubNumber,SubCode,SubName,SubOrderIndex
	)
	SELECT
		Code, Number, Name, GradeSet, OrderIndex,Class,Subject,SubNumber,SubCode,SubName,SubOrderIndex
	FROM OPENXML (@intDoc, '/Table/ImportSubjectActivity', 1)
	WITH
	(   
		Code nvarchar(100) '@Code',			
		Name nvarchar(200) '@Name',			
		Number int '@Number',			
		GradeSet nvarchar(100) '@GradeSet',			
		OrderIndex int '@OrderIndex',
		Class nvarchar(100) '@Class',
		Subject  nvarchar(100) '@Subject',
		SubNumber int '@SubNumber',
		SubCode nvarchar(100) '@SubCode',			
		SubName nvarchar(200) '@SubName',
		SubOrderIndex int '@SubOrderIndex'
		
	)
EXEC sp_xml_removedocument @intDoc
SELECT @lCount =  COUNT(Id) FROM #tTable
WHILE @lCount > 0 
BEGIN	
		SET @lCode = ''
		SET @lTitle = ''
		SET @lNumber = 0
		SET @lGradeSetId = 0
		SET @lOrderIndex = 0
		SET @lClass=''
		SET @lSubject=''
		SET @lClassSubjectId =0
		SET @lGradeSet=''
		SET @lSubTitle=''
		SET @lSubCode=''
		SET @lSubNumber =0
		SET @lSubOrderIndex =0
		SET @lSubjectActivityId=0
		SET @lSubTitle=''
  SELECT		
		@lCode = Code,@lTitle = Name,@lNumber = Number,@lOrderIndex = OrderIndex,
		@lClass=Class,@lSubject=Subject,@lGradeSet=GradeSet,@lSubNumber=SubNumber,@lSubCode=SubCode,@lSubTitle=SubName,@lSubOrderIndex=SubOrderIndex
FROM #tTable WHERE Id = @lCount  
--BEGIN TRANSACTION
	SELECT  @lClassSubjectId=ClassSubjectId FROM sSetup.vClassSubject  VS
	INNER JOIN  sSetup.tClassMaster CM ON CM.Id=VS.ClassId where VS.IsObsolete=0 AND CM.Title=@lClass  AND Vs.SubjectName=@lSubject AND CM.OrgId=@rOrgId
    SELECT @lGradeSetId=Id FROM sAssessment.tGradeSetMaster WHERE  OrgId=@rOrgId   AND Title=@lGradeSet AND OrgId=@rOrgId
  DECLARE @lNextNumber INT=0
  EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAssessment.tCCESubjectActivityMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
    IF NOT EXISTS(select 1 from sAssessment.tCCESubjectActivityMaster where Code=@lCode AND OrgId=@rOrgId AND ClassSubjectId = @lClassSubjectId)
     BEGIN	
     INSERT INTO sAssessment.tCCESubjectActivityMaster (Id, ClassSubjectId, Number, Code, Title, OrgId, IsObsolete, OrderIndex, UpdatedUserId, UpdatedDateTime, GradeSetId)Values
		(@lNextNumber,@lClassSubjectId,@lNumber,@lCode,@lTitle,@rOrgId,0,@lOrderIndex,@rUserId,sCommon.fGetDate(),@lGradeSetId)
	END
	ELSE
	BEGIN
	SELECT @lSubjectActivityId= ID FROM sAssessment.tCCESubjectActivityMaster WHERE Code=@lCode AND OrgId=@rOrgId AND ClassSubjectId = @lClassSubjectId
	SET @lNextNumber=@lSubjectActivityId
	
	END
IF NOT EXISTS(select 1 from sAssessment.tCCESubjectSubActivityMaster where Code=@lSubCode AND OrgId=@rOrgId AND SubjectActivityId =@lNextNumber )
 BEGIN
SElect @lNextNumber
 EXEC  [sAssessment].[pCSSubjectSubActivityAdd] 0,@lNextNumber,@lSubCode,@lSubNumber,@lSubTitle,0,@lSubOrderIndex,@rOrgId,@rUserId
  END 
		 SET @lCount = @lCount - 1
	--COMMIT TRANSACTION			
END
	SELECT 1
	END TRY
	BEGIN CATCH
	SELECT ERROR_MESSAGE(), ERROR_LINE()
	END CATCH
	
END
GO
PRINT N'Creating [sAssessment].[pImportSubjectActivityIndicator]...';


GO
CREATE PROCEDURE [sAssessment].[pImportSubjectActivityIndicator]
    @rOrgId smallint ,
	@rXmldoc [nvarchar](max),
	@rUserId bigint

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
BEGIN TRY
	
DECLARE @lCount INT
DECLARE @lInterrorCode INT,@intDoc INT,@lActivity nvarchar(200),@lSubActivity nvarchar(200),@lNumber int,@lGradeSetdetailid int,@lOrderIndex int,	
@lGrade nvarchar(100),@lSubActivityId int,@lIndicator nvarchar(100),@lClass nvarchar(100),@lSubject nvarchar(100),@lGradeSetId int
	 
EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc
	CREATE TABLE #tTable  
	(
		Id bigint identity,
		Class nvarchar(100),
		Subject nvarchar(100),
		Activity nvarchar(200), 
		SubActivity nvarchar(200), 
		Number int, 
		Indicator nvarchar(100),
		Grade nvarchar(100), 
		OrderIndex int
	)
	INSERT INTO #tTable
	(  
		Class,Subject,Activity,SubActivity, Number,Indicator,Grade, OrderIndex
	)
	SELECT
		Class,Subject,Activity,SubActivity, Number,Indicator,Grade, OrderIndex
	FROM OPENXML (@intDoc, '/Table/ImportSubjectActivityIndicator', 1)
	WITH
	(   
	    Class nvarchar(100) '@Class',	
	    Subject nvarchar(100) '@Subject',	
		Activity nvarchar(200) '@Activity',			
		SubActivity nvarchar(200) '@SubActivity',			
		Number int '@Number',			
		Indicator nvarchar(100) '@Indicator',
		Grade nvarchar(100) '@Grade',
		OrderIndex int '@OrderIndex'
	)
EXEC sp_xml_removedocument @intDoc
SELECT @lCount =  COUNT(Id) FROM #tTable
WHILE @lCount > 0 
BEGIN	
		SET @lActivity = ''
		SET @lSubActivity = ''
		SET @lClass = ''
		SET @lSubject = ''
		SET @lNumber = 0
		SET @lIndicator = ''
		SET @lOrderIndex = 0
		SET @lGrade=''
		SET @lSubActivityId =0
		SET @lGradeSetdetailid=0 
	
  SELECT		
		@lActivity = Activity,@lSubActivity = SubActivity,@lNumber = Number,@lOrderIndex = OrderIndex,
		@lIndicator=Indicator,@lGrade=Grade,@lClass=Class,@lSubject=Subject
FROM #tTable WHERE Id = @lCount  
--BEGIN TRANSACTION
	SELECT  @lSubActivityId=SA.Id,@lGradeSetId= AM.GradeSetId from sAssessment.tCCESubjectSubActivityMaster SA INNER JOIN  sAssessment.tCCESubjectActivityMaster AM ON SA.SubjectActivityId=AM.Id
    INNER JOIN sSetup.tClassSubject  CS On AM.ClassSubjectId=Cs.Id INNER JOIN sSetup.tClassMaster CM ON CM.Id=Cs.ClassId INNER JOIN  sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId
    WHERE  SA.OrgId=@rOrgId AND SA.Title=@lSubActivity AND AM.Title=@lActivity AND SM.Title=@lSubject AND CM.Title=@lClass AND CS.OrgId=@rOrgId
    SELECT @lGradeSetdetailid=Id FROM sAssessment.tGradeSetDetail WHERE GradeCode=@lGrade  and GradeSetId=@lGradeSetId
   
    IF NOT EXISTS(select 1 from sAssessment.tCCESubjectSubActivityIndicatorMaster  where Title=@lIndicator AND OrgId=@rOrgId AND CCESubjectSubActivityId = @lSubActivity )
     BEGIN	
     EXEC [sAssessment].[pCSSubjectActivityIndicatorAdd] 0,@lSubActivityId,@lIndicator,@lGradeSetdetailid,@rOrgId,@lOrderIndex,@rUserId,@lNumber,@rUserId
  	END
		 SET @lCount = @lCount - 1
	--COMMIT TRANSACTION			
END
	SELECT 1
	END TRY
	BEGIN CATCH
	SELECT ERROR_MESSAGE(), ERROR_LINE()
	END CATCH
	
END
GO
PRINT N'Creating [sAssessment].[pMarkEntryAllExamSubjectGet]...';


GO
CREATE PROCEDURE [sAssessment].[pMarkEntryAllExamSubjectGet]
	 @rClassId int,
	 @rDivisionId int,
	 @rExamId nvarchar(Max),
	 @rBatchId int,
	 @rClassSubjectId int=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 		


DECLARE @ExamIDTable TABLE (ExamID BIGINT)
INSERT INTO @ExamIDTable(ExamID)
SELECT item FROM sCommon.fnSplit(@rExamId,',')



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(E.Id) 
					  From sAssessment.vExamMaster  E
					  --INNER JOIN sAssessment.tExamDetail Ed ON Ed.ExamId =E.Id 
					   Where ClassId = @rClassId AND E.Id in (SELECT ExamID FROM @ExamIDTable)
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')
        --select @cols
set @query = 'SELECT  AcademicId, Name,RollNo,Code,ClassName, ' + @cols + '
FROM
(
Select ISNULL(RD.Obtain,0) AS Obtain, A.AcademicId,ED.ExamId,A.Name,A.RollNo,
A.Code,CM.Title ClassName 
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
INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectID
LEFT JOIN sAssessment.tOptionalSubject OP ON OP.AcademicId=A.AcademicId ANd CS.Id=OP.ClassSubjectId  
WHERE A.StatusId =1   AND A.BatchId = '+ CONVERT(nvarchar(15),@rBatchId) + ' AND A.ClassId= ' + convert(nvarchar(15),@rClassId) +  '  And A.DivisionId= ' + convert(nvarchar(15),@rDivisionId) + ' And  ED.ExamId in( ' + convert(nvarchar(Max),@rExamId) + ') And ED.ClassSubjectId='+convert(nvarchar(14),@rClassSubjectId)+'  AND ((CS.IsOptional = 1 AND  isnull(oP.AcademicId,0) <> 0) OR (CS.IsOptional = 0)) 
 ) MAIN

PIVOT
(
	MAX(obtain )
FOR ExamID IN (' + @cols + ')
)pvt Order by RollNo'
  --print @query
execute(@query)
		
END
GO
PRINT N'Creating [sAssessment].[pMarkEntryAllSubjectCountGet]...';


GO
CREATE PROCEDURE [sAssessment].[pMarkEntryAllSubjectCountGet]
	 
	 @rExamId int,
	 @rBatchId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 		
DECLARE @cols AS NVARCHAR(MAX),
@query  AS NVARCHAR(MAX),@query1  AS NVARCHAR(MAX),@query2  AS NVARCHAR(MAX),@query3 AS NVARCHAR(MAX)
select @cols = STUFF((SELECT  distinct ',' +   QUOTENAME(CS.SubjectCode) 
					  From  
					   sSetup.vExamSubject CS  
					   INNER JOIN sAssessment.tExamMaster E ON E.Id=CS.ExamId
					   AND E.ExamSubGroupId =  @rExamId 
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')
    
set @query = 'SELECT  ClassId,DivisionId,ClassName,ExamId, ' + @cols + '
FROM
(
Select   Cm.Id As ClassId,Dm.Id as DivisionId,CM.Title+'' ''+DM.TItle ClassName,Count(A.AcademicId) AS AcademicId,ED.ExamId, SM.Code as ExamDetailId
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  
INNER JOIN sSetup.tClassSubject CS ON CS.Id = ED.ClassSubjectId
INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = CS.SubjectId
LEFT JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id 
 
WHERE A.StatusId =1 AND A.BatchId = '+ CONVERT(nvarchar(15),@rBatchId) +' And  EM.ExamSubGroupId = ' + convert(nvarchar(15),@rExamId) + 'AND ISNULL(RD.Obtain,0)>0  
Group By ED.ExamId,Ed.Id,CM.Title,DM.TItle,Cm.Id,Dm.Id,SM.Code) 
MAIN
PIVOT
(
	MAX(AcademicId )
FOR ExamDetailId IN (' + @cols + ')
)pvt '
  print (@query)
execute(@query)
		
END
GO
PRINT N'Creating [sAssessment].[pValidateImportCoScholasticIndicator]...';


GO
 CREATE PROCEDURE [sAssessment].[pValidateImportCoScholasticIndicator]
     @rOrgId smallint,
	 @rXmldoc [nvarchar](max)
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
DECLARE @lCount INT
DECLARE @lInterrorCode INT,@intDoc INT,  @lCode nvarchar(50),  @lTitle nvarchar(100), @lNumber int=0,      
        @1ReturnCode int = 1, @1DuplicateCode nvarchar(max) = '',@lCCECSId int,@lCoScholasticGroup nvarchar(100),@lCoScholastic nvarchar(100),
        @1ExistNumber nvarchar(max) = '',@1ExistTitle nvarchar(max) = '',@1DuplicateTitle nvarchar(max) = '',
        @1DuplicateNumber nvarchar(max) = '',@1DuplicateOrderIndex nvarchar(max) = '',@1ExistOrderIndex nvarchar(max)='',@lOrderIndex int=0
EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc
CREATE TABLE #tTable1 
 (
		Id bigint identity,	
		CoScholasticGroup nvarchar(100),
		CoScholastic nvarchar(100), 
		Number int, 
		Indicator nvarchar(100),
		OrderIndex int
  )
  INSERT INTO #tTable1
	(
	  CoScholasticGroup,CoScholastic,Number, Indicator,OrderIndex  
    ) 
   SELECT
        CoScholasticGroup,CoScholastic,Number, Indicator,OrderIndex  
   FROM OPENXML (@intDoc, '/Table/ImportIndicator', 1)
   With
   (
        CoScholasticGroup nvarchar(100) '@CoScholasticGroup',
		CoScholastic nvarchar(100)  '@CoScholastic',	
		Number Int '@Number',		
		Indicator nvarchar(100) '@Indicator',
		OrderIndex int '@OrderIndex'
   ) 
EXEC sp_xml_removedocument @intDoc
    IF EXISTS(SELECT 1 fROM #tTable1 WHERE CoScholasticGroup IS NULL OR CoScholasticGroup COLLATE DATABASE_DEFAULT='' COLLATE DATABASE_DEFAULT)
BEGIN
	SELECT 'CoScholasticGroup Should not be empty' AS ValidateCode
END
 ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE CoScholastic IS NULL OR CoScholastic COLLATE DATABASE_DEFAULT='' COLLATE DATABASE_DEFAULT)
BEGIN
	 SELECT 'CoScholastic Should not be empty' AS ValidateCode
END
ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE Indicator IS NULL OR Indicator COLLATE DATABASE_DEFAULT='' COLLATE DATABASE_DEFAULT)
BEGIN
	 SELECT 'Indicator Should not be empty' AS ValidateCode
END
ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE Number='' OR Number Is NUll )
BEGIN
	SELECT 'Number Should not be empty' AS ValidateCode
END
ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE OrderIndex = '' OR OrderIndex Is NUll )
BEGIN
	SELECT 'OrderIndex Should not be empty' AS ValidateCode
END
ELSE
BEGIN	
SELECT @lCount =  COUNT(Id) FROM #tTable1
WHILE @lCount > 0 
BEGIN
	SELECT @lCoScholasticGroup = CoScholasticGroup,@lCoScholastic=CoScholastic,@lTitle = Indicator,@lNumber = Number,@lOrderIndex = OrderIndex
	FROM #tTable1 WHERE Id = @lCount 
	IF NOT Exists (	SELECT 1 from sAssessment.tCCECSMaster CM INNER join  sAssessment.tCCECSGroupMaster  CG on CG.Id=CM.CCECAGroupId WHERE CM.OrgId=@rOrgId AND CM.Title=@lCoScholastic AND CG.Title=@lCoScholasticGroup)
      BEGIN
   SET    @lCCECSId=0
		 SELECT 'Enter proper value for CoScholasticGroup/CoScholastic : ' + @lCoScholasticGroup+'/'+@lCoScholastic  AS ValidateCode
    END	
    ELSE
    BEGIN
     	  SELECT @lCCECSId=CM.Id from sAssessment.tCCECSMaster CM INNER join  sAssessment.tCCECSGroupMaster  CG on CG.Id=CM.CCECAGroupId WHERE CM.OrgId=@rOrgId AND CM.Title=@lCoScholastic AND CG.Title=@lCoScholasticGroup
    END  
    IF Exists ((select 1 from sAssessment.tCCECSIndicatorMaster where OrgId=@rOrgId AND CCECSId=@lCCECSId AND Title COLLATE DATABASE_DEFAULT = @lTitle COLLATE DATABASE_DEFAULT))         
    BEGIN
		SET @1ExistTitle = @1ExistTitle + @lTitle + ','
    END	  
    IF Exists ((select 1 from sAssessment.tCCECSIndicatorMaster where OrgId=@rOrgId AND CCECSId=@lCCECSId AND convert(varchar,Number) COLLATE DATABASE_DEFAULT = convert(varchar,@lNumber) COLLATE DATABASE_DEFAULT ))         
    BEGIN
		SET @1ExistNumber = @1ExistNumber + convert(varchar,@lNumber )+ ','
    END	 
      IF Exists ((select 1 from sAssessment.tCCECSIndicatorMaster where OrgId=@rOrgId AND CCECSId=@lCCECSId AND convert(varchar,OrderIndex)  COLLATE DATABASE_DEFAULT = convert(varchar,@lOrderIndex) COLLATE DATABASE_DEFAULT ))               
    BEGIN
		SET @1ExistOrderIndex = @1ExistOrderIndex + convert(varchar,@lOrderIndex )+ ','
    END	 
	SET @lCount = @lCount - 1	
	END
SELECT @1DuplicateTitle=COALESCE(@1DuplicateTitle ,'') + Indicator + ',' FROM #tTable1 GROUP BY Indicator,CoScholasticGroup,CoScholastic  HAVING ( COUNT(Indicator) > 1 )	
SELECT @1DuplicateNumber=COALESCE(@1DuplicateNumber ,'') + CONVERT(varchar,Number) + ',' FROM #tTable1 GROUP BY Number,CoScholasticGroup,CoScholastic HAVING ( COUNT(Number) > 1 )	
SELECT @1DuplicateOrderIndex=COALESCE(@1DuplicateOrderIndex ,'') +CONVERT(varchar, OrderIndex) + ',' FROM #tTable1 GROUP BY OrderIndex,CoScholasticGroup,CoScholastic HAVING ( COUNT(OrderIndex) > 1 )	


	IF(@1DuplicateTitle IS NOT NULL AND @1DuplicateTitle != '')
	BEGIN
		SET @1DuplicateTitle = 'Duplicate Indicator : ' + @1DuplicateTitle
	END
	IF(@1DuplicateNumber IS NOT NULL AND @1DuplicateNumber != '')
	BEGIN
		SET @1DuplicateNumber = 'Duplicate Number : ' + @1DuplicateNumber
	END
	IF(@1DuplicateOrderIndex IS NOT NULL AND @1DuplicateOrderIndex != '')
	BEGIN
		SET @1DuplicateOrderIndex = 'Duplicate OrderIndex : ' + @1DuplicateOrderIndex
	END
	 IF (@1ExistTitle IS NOT NULL AND @1ExistTitle != '' )
	BEGIN
		SET @1ExistTitle = 'Exist Indicator : ' + @1ExistTitle
	END
	 IF (@1Existnumber IS NOT NULL AND @1Existnumber != '' )
	BEGIN
		SET @1Existnumber = 'Exist Number : ' + @1Existnumber
	END
	 IF (@1ExistOrderIndex IS NOT NULL AND @1ExistOrderIndex != '' )
	BEGIN
		SET @1ExistOrderIndex = 'Exist OrderIndex : ' + @1ExistOrderIndex
	END
	SELECT isnull(@1ExistTitle,'') +isnull(@1Existnumber,'')+ isnull(@1ExistOrderIndex ,'')+isnull(@1DuplicateTitle,'')+isnull(@1DuplicateNumber,'')+isnull(@1DuplicateOrderIndex,'')  AS ValidateCode 
 
END
END
GO
PRINT N'Creating [sAssessment].[pValidateImportSubjectActivity]...';


GO
CREATE PROCEDURE [sAssessment].[pValidateImportSubjectActivity]
     @rOrgId smallint,
	 @rXmldoc [nvarchar](max)
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
DECLARE @lCount INT
DECLARE @lInterrorCode INT,@intDoc INT, @lCode nvarchar(100),  @lTitle nvarchar(200), @lNumber int,@lClass nvarchar(100), 
        @lSubCode nvarchar(100),  @lSubTitle nvarchar(200), @lSubNumber int,@lSubClass nvarchar(100),@1SubOrderIndex int,
	    @lSubject nvarchar(100), @1OrderIndex int,  @1ReturnCode int = 1,@lGradeSet nvarchar(100),@1SubDuplicateCode nvarchar(max) = '',
        @1ExistCode nvarchar(max) = '',@1DuplicateCode nvarchar(max) = '', @1ExistOrderIndex nvarchar(max) = '',
        @1DuplicateTitle nvarchar(max) = '', @1DuplicateOrderIndex nvarchar(max) = '', @1SubDuplicateTitle nvarchar(max) = '', @1SubDuplicateOrderIndex nvarchar(max) = '',
        @1ExistNumber nvarchar(max) = '',@1ExistTitle nvarchar(max) = '',@lClassSubjectId int,@lOrderIndex int,@1DuplicateNumber nvarchar(max)='',@SubDuplicateNumber nvarchar(max)='',
        @1SubExistNumber nvarchar(max) = '',@1SubExistTitle nvarchar(max) = '', @1SubExistCode nvarchar(max) = '',@1SubExistOrderIndex nvarchar(max) = '',@lSubjectActivityId int=0
EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc
CREATE TABLE #tTable1 
 (
		Id bigint identity,
		Code nvarchar(100), 
		Name nvarchar(200),
		Number int, 
	    OrderIndex int,
		GradeSet nvarchar(100),
	    Class Nvarchar(100),
	    Subject Nvarchar(100),
	    SubNumber int, 
		SubCode nvarchar(100), 
		SubName nvarchar(200),
		SubOrderIndex int
  )
  INSERT INTO #tTable1(Code,Name,Number,OrderIndex,GradeSet,Class,Subject,SubNumber,SubCode,SubName,SubOrderIndex)
    
   SELECT
          Code,Name,Number,OrderIndex,GradeSet,Class,Subject,SubNumber,SubCode,SubName,SubOrderIndex
   FROM OPENXML (@intDoc, '/Table/ImportSubjectActivity', 1)
   With
   (
        Code nvarchar(100) '@Code',			
		Name nvarchar(200) '@Name',			
		Number int '@Number',			
		GradeSet nvarchar(100) '@GradeSet',			
		OrderIndex int '@OrderIndex',
		Class nvarchar(100) '@Class',
		Subject  nvarchar(100) '@Subject',
		SubNumber int '@SubNumber',
		SubCode nvarchar(100) '@SubCode',			
		SubName nvarchar(200) '@SubName',
		SubOrderIndex int '@SubOrderIndex'
   )     
   
EXEC sp_xml_removedocument @intDoc
			
IF EXISTS(SELECT 1 fROM #tTable1 WHERE Code IS NULL OR Code COLLATE DATABASE_DEFAULT='' COLLATE DATABASE_DEFAULT)
BEGIN
	SELECT 'Code Should not be empty' AS ValidateCode
END
 IF EXISTS(SELECT 1 fROM #tTable1 WHERE Name IS NULL OR Name COLLATE DATABASE_DEFAULT='' COLLATE DATABASE_DEFAULT)
BEGIN
	SELECT 'Name Should not be empty' AS ValidateCode
END
 IF EXISTS(SELECT 1 fROM #tTable1 WHERE Class IS NULL OR Class COLLATE DATABASE_DEFAULT='' COLLATE DATABASE_DEFAULT)
BEGIN
	SELECT 'Class Should not be empty' AS ValidateCode
END
 IF EXISTS(SELECT 1 fROM #tTable1 WHERE Subject IS NULL OR Subject COLLATE DATABASE_DEFAULT='' COLLATE DATABASE_DEFAULT)
BEGIN
	SELECT 'Subject Should not be empty' AS ValidateCode
END
IF EXISTS(SELECT 1 fROM #tTable1 WHERE SubName IS NULL OR SubName COLLATE DATABASE_DEFAULT='' COLLATE DATABASE_DEFAULT)
BEGIN
	SELECT 'Sub Name Should not be empty' AS ValidateCode
END
IF EXISTS(SELECT 1 fROM #tTable1 WHERE SubCode IS NULL OR SubCode COLLATE DATABASE_DEFAULT='' COLLATE DATABASE_DEFAULT)
BEGIN
	SELECT 'Sub Code Should not be empty' AS ValidateCode
END
IF EXISTS(SELECT 1 fROM #tTable1 WHERE SubOrderIndex IS NULL OR SubOrderIndex ='')
BEGIN
	SELECT 'Sub OrderIndex Should not be empty' AS ValidateCode
END
IF EXISTS(SELECT 1 fROM #tTable1 WHERE SubNumber IS NULL OR SubNumber ='')
BEGIN
	SELECT 'Sub Number Should not be empty' AS ValidateCode
END
ELSE
BEGIN	
SELECT @lCount =  COUNT(Id) FROM #tTable1
WHILE @lCount > 0 
BEGIN
	SELECT @lCode = Code,@lTitle=Name,@lNumber=Number,@lOrderIndex=OrderIndex,@lSubject=Subject,@lClass=Class,@lGradeSet=GradeSet,
	@lSubCode =SubCode,@lSubTitle=SubName,@1SubOrderIndex=SubOrderIndex,@lSubNumber=SubNumber
	FROM #tTable1 WHERE Id = @lCount  
IF NOT EXists(SELECT  1 FROM sSetup.vClassSubject  VS
	INNER JOIN  sSetup.tClassMaster CM ON CM.Id=VS.ClassId where VS.IsObsolete=0 AND CM.Title=@lClass  AND Vs.SubjectName=@lSubject AND CM.OrgId=@rOrgId)
 BEGIN
     SELECT 'Enter proper value for Class  or Subject  :' + @lClass + '/' + @lSubject AS ValidateCode
    END
    ELSE
    BEGIN
    SET @lClassSubjectId=0
    SELECT @lClassSubjectId= ClassSubjectId FROM sSetup.vClassSubject  VS
	INNER JOIN  sSetup.tClassMaster CM ON CM.Id=VS.ClassId where VS.IsObsolete=0 AND CM.Title=@lClass  AND Vs.SubjectName=@lSubject AND CM.OrgId=@rOrgId 
    END
	 IF NOT EXists( SELECT 1 FROM sAssessment.tGradeSetMaster WHERE  OrgId=@rOrgId  AND Title=@lGradeSet )
  BEGIN
     SELECT 'Enter proper value for Gradeset : ' + @lGradeSet  AS ValidateCode
    END
 IF NOT Exists (select 1  FROM  sAssessment.tCCESubjectActivityMaster where OrgId=@rOrgId AND Code=@lCode AND ClassSubjectId = @lClassSubjectId )
 BEGIN
 SET @lSubjectActivityId=0
 END
 ELSE
 BEGIN
   SELECT @lSubjectActivityId=Id FROM   sAssessment.tCCESubjectActivityMaster   where OrgId=@rOrgId AND Code=@lCode
  IF Exists ((select 1 from sAssessment.tCCESubjectSubActivityMaster where OrgId=@rOrgId AND SubjectActivityId = @lSubjectActivityId AND Code COLLATE DATABASE_DEFAULT = @lSubCode COLLATE DATABASE_DEFAULT))         
    BEGIN
		SET @1SubExistCode = @1SubExistCode + @lSubCode + ','
    END	  
 IF Exists ((select 1 from sAssessment.tCCESubjectSubActivityMaster where OrgId=@rOrgId AND SubjectActivityId = @lSubjectActivityId AND Title COLLATE DATABASE_DEFAULT = @lSubTitle COLLATE DATABASE_DEFAULT))         
    BEGIN
		SET @1SubExistTitle = @1SubExistTitle + @lSubTitle + ','
    END	  
  IF Exists ((select 1 from sAssessment.tCCESubjectSubActivityMaster where OrgId=@rOrgId AND OrderIndex =Convert(varchar,@1SubOrderIndex) AND SubjectActivityId = @lSubjectActivityId AND Convert(varchar,OrderIndex) COLLATE DATABASE_DEFAULT = Convert(varchar,@1SubOrderIndex) COLLATE DATABASE_DEFAULT))         
    BEGIN
		SET @1SubExistOrderIndex= @1SubExistOrderIndex + Convert(varchar,@1SubOrderIndex )+ ','
    END	  
 IF Exists ((select 1 from sAssessment.tCCESubjectSubActivityMaster where OrgId=@rOrgId AND Number =Convert(varchar,@lSubNumber) AND SubjectActivityId = @lSubjectActivityId AND Convert(varchar,Number) COLLATE DATABASE_DEFAULT = Convert(varchar,@lSubNumber) COLLATE DATABASE_DEFAULT))               
    BEGIN
		SET @1SubExistNumber= @1SubExistNumber + Convert(varchar,@lSubNumber) + ','
    END	  
  END
	SET @lCount = @lCount - 1	
 END
	SELECT @1SubDuplicateCode=COALESCE(@1SubDuplicateCode ,'') + SubCode + ',' FROM #tTable1 GROUP BY SubCode,Class,subject,Code,Name HAVING ( COUNT(SubCode) > 1 )	
    SELECT @1SubDuplicateTitle=COALESCE(@1SubDuplicateTitle ,'') + SubName + ',' FROM #tTable1 GROUP BY SubName,Class,subject,Code,Name HAVING ( COUNT(SubName) > 1 )	
  	SELECT @1SubDuplicateOrderIndex=COALESCE(@1SubDuplicateOrderIndex,'')  + convert(varchar,SubOrderIndex) + ',' FROM #tTable1 GROUP BY SubOrderIndex,Class,subject,Code,Name HAVING ( COUNT(SubOrderIndex) > 1 )	
  	SELECT @SubDuplicateNumber=COALESCE(@SubDuplicateNumber,'')  + convert(varchar,SubNumber) + ',' FROM #tTable1 GROUP BY SubNumber,Class,subject,Code,Name HAVING ( COUNT(SubNumber) > 1 )	
	IF(@1SubDuplicateCode IS NOT NULL AND @1SubDuplicateCode != '')
	BEGIN
		SET @1SubDuplicateCode = 'Duplicate Sub Code : ' + @1SubDuplicateCode
	END
	IF(@1SubDuplicateTitle IS NOT NULL AND @1SubDuplicateTitle != '')
	BEGIN
	SET @1SubDuplicateTitle = 'Duplicate Sub Name : ' + @1SubDuplicateTitle
	END
	IF(@1SubDuplicateOrderIndex IS  NOT NULL AND @1SubDuplicateOrderIndex != '')
	BEGIN
	SET @1SubDuplicateOrderIndex = 'Duplicate Sub OrderIndex : ' + @1SubDuplicateOrderIndex
	END
	IF(@SubDuplicateNumber IS NOT NULL AND @SubDuplicateNumber != '')
	BEGIN
	SET @SubDuplicateNumber = 'Duplicate Sub Number : ' + @SubDuplicateNumber
	END
	 IF (@1SubExistCode IS NOT NULL AND @1SubExistCode != '' )
	BEGIN
		SET @1SubExistCode = 'Exist Sub Code : ' + @1SubExistCode
	END
	ELSE IF (@1SubExistCode IS NOT NULL AND @1SubExistCode = '' )
	BEGIN
		SET @1SubExistCode=''
	END
	 IF (@1SubExistTitle IS NOT NULL AND @1SubExistTitle != '' )
	BEGIN
		SET @1SubExistTitle = 'Exist Sub Title : ' + @1SubExistTitle
	END
	
	 IF (@1SubExistOrderIndex IS NOT NULL  AND @1SubExistOrderIndex != '' )
	BEGIN
		SET @1SubExistOrderIndex = 'Exist Sub OrderIndex : ' + @1SubExistOrderIndex
	END
  	 IF (@1SubExistNumber IS NOT NULL AND @1SubExistNumber != '' )
	BEGIN
		SET @1SubExistNumber = 'Exist Sub Number : ' + @1SubExistNumber
	END
	END
	Select Isnull(@1SubDuplicateCode,'')+Isnull(@1SubDuplicateTitle,'')+Isnull(@SubDuplicateNumber,'')+Isnull(@1SubDuplicateOrderIndex,'')+
	Isnull(@1SubExistCode,'') +Isnull(@1SubExistTitle,'')+Isnull(@1SubExistNumber,'')+Isnull(@1SubExistOrderIndex,'')
	  AS ValidateCode
END
GO
PRINT N'Creating [sAssessment].[pValidateImportSubjectActivityIndicator]...';


GO
CREATE PROCEDURE [sAssessment].[pValidateImportSubjectActivityIndicator]
     @rOrgId smallint,
	 @rXmldoc [nvarchar](max)
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
DECLARE @lCount INT
DECLARE @lInterrorCode INT,@intDoc INT, @lActivity nvarchar(200), @lNumber int, 
	    @1OrderIndex int, @lGrade nvarchar(100),@lGradeSetId int=0,
        @1ExistOrderIndex nvarchar(max) = '',@lSubActivity nvarchar(200),@lSubject nvarchar(100),
        @1DuplicateTitle nvarchar(max) = '', @1DuplicateOrderIndex nvarchar(max) = '',@lIndicator nvarchar(100),@lclass nvarchar(100),
        @1ExistNumber nvarchar(max) = '',@1ExistTitle nvarchar(max) = '',@lSubActivityId int=0,@lOrderIndex int,@1DuplicateNumber nvarchar(max)=''
EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc
  CREATE TABLE #tTable1 
 (
	    Id bigint identity,Class nvarchar(100),Subject nvarchar(100),
		Activity nvarchar(200), SubActivity nvarchar(200),Number nvarchar(max), 
		Indicator nvarchar(100),Grade nvarchar(100), OrderIndex  nvarchar(max)
  )
  INSERT INTO #tTable1(Class,Subject,Activity,SubActivity, Number,Indicator,Grade, OrderIndex)
   SELECT
          Class,Subject,Activity,SubActivity, Number,Indicator,Grade, OrderIndex
   FROM OPENXML (@intDoc, '/Table/ImportSubjectActivityIndicator', 1)
   With
   (
        Class nvarchar(100) '@Class',	
	    Subject nvarchar(100) '@Subject',	
		Activity nvarchar(200) '@Activity',			
		SubActivity nvarchar(200) '@SubActivity',			
		Number nvarchar(max) '@Number',			
		Indicator nvarchar(100) '@Indicator',
		Grade nvarchar(100) '@Grade',
		OrderIndex nvarchar(max) '@OrderIndex'
		
   )   
EXEC sp_xml_removedocument @intDoc
IF EXISTS(SELECT 1 fROM #tTable1 WHERE Class IS NULL OR Class COLLATE DATABASE_DEFAULT='' COLLATE DATABASE_DEFAULT)
BEGIN
	SELECT 'Class Should not be empty' AS ValidateCode
END
 IF EXISTS(SELECT 1 fROM #tTable1 WHERE Subject IS NULL OR Subject COLLATE DATABASE_DEFAULT='' COLLATE DATABASE_DEFAULT)
BEGIN
	SELECT 'Subject Should not be empty' AS ValidateCode
END
 IF EXISTS(SELECT 1 fROM #tTable1 WHERE Activity='' OR Activity COLLATE DATABASE_DEFAULT='' COLLATE DATABASE_DEFAULT)
BEGIN
	SELECT 'Activity Should not be empty' AS ValidateCode
END
IF EXISTS(SELECT 1 fROM #tTable1 WHERE SubActivity IS NULL OR SubActivity COLLATE DATABASE_DEFAULT='' COLLATE DATABASE_DEFAULT)
BEGIN
	SELECT 'SubActivity Should not be empty' AS ValidateCode
END
IF EXISTS(SELECT 1 fROM #tTable1 WHERE Number='' OR Number Is NUll )
BEGIN
	SELECT 'Number Should not be empty' AS ValidateCode
END
IF EXISTS(SELECT 1 fROM #tTable1 WHERE Indicator IS NULL OR Indicator COLLATE DATABASE_DEFAULT='' COLLATE DATABASE_DEFAULT)
BEGIN
	SELECT 'Indicator Should not be empty' AS ValidateCode
END
IF EXISTS(SELECT 1 fROM #tTable1 WHERE Grade IS NULL OR Grade COLLATE DATABASE_DEFAULT='' COLLATE DATABASE_DEFAULT)
BEGIN
	SELECT 'Grade Should not be empty' AS ValidateCode
END
 IF EXISTS(SELECT 1 fROM #tTable1 WHERE OrderIndex=''  OR OrderIndex Is NUll)
BEGIN
	SELECT 'OrderIndex Should not be empty' AS ValidateCode
END
IF EXISTS(SELECT 1 fROM #tTable1  Where isnumeric(Number)<>1 )
BEGIN
	SELECT 'Number Must Be Numeric ' AS ValidateCode
END
IF EXISTS(SELECT 1 fROM #tTable1  Where isnumeric(OrderIndex)<>1 )
BEGIN
	SELECT 'OrderIndex Must Be Numeric ' AS ValidateCode
END
ELSE
BEGIN	
SELECT @lCount =  COUNT(Id) FROM #tTable1
WHILE @lCount > 0 
BEGIN
	SELECT 	@lActivity = Activity,@lSubActivity = SubActivity,@lNumber = Number,@lOrderIndex = OrderIndex,
		@lIndicator=Indicator,@lGrade=Grade,@lClass=Class,@lSubject=Subject
	FROM #tTable1 WHERE Id = @lCount  
IF NOT EXists( SELECT  1 from sAssessment.tCCESubjectSubActivityMaster SA INNER JOIN  sAssessment.tCCESubjectActivityMaster AM ON SA.SubjectActivityId=AM.Id
    INNER JOIN sSetup.tClassSubject  CS On AM.ClassSubjectId=Cs.Id INNER JOIN sSetup.tClassMaster CM ON CM.Id=Cs.ClassId INNER JOIN  sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId
    WHERE  
    SA.OrgId=1101 AND SA.Title=@lSubActivity AND AM.Title=@lActivity AND SM.Title=@lSubject AND CM.Title=@lClass AND CS.OrgId=1101)
  BEGIN
     SELECT 'Enter proper value for Activity  or SubActivity  for class subject  : '+ @lclass +''  + @lSubject+ ' '+ @lActivity + '-' + @lSubActivity AS ValidateCode 
    END
    ELSE
    BEGIN
    SET @lSubActivityId=0 
    SET @lGradeSetId=0
    SELECT @lSubActivityId=SA.Id,@lGradeSetId= AM.GradeSetId from sAssessment.tCCESubjectSubActivityMaster SA INNER JOIN  sAssessment.tCCESubjectActivityMaster AM ON SA.SubjectActivityId=AM.Id
    INNER JOIN sSetup.tClassSubject  CS On AM.ClassSubjectId=CS.Id INNER JOIN sSetup.tClassMaster CM ON CM.Id=Cs.ClassId INNER JOIN  sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId
    WHERE  SA.OrgId=@rOrgId AND SA.Title=@lSubActivity AND AM.Title=@lActivity AND SM.Title=@lSubject AND CM.Title=@lClass AND CS.OrgId=@rOrgId

  END
	 IF NOT EXists(SELECT 1 FROM sAssessment.tGradeSetDetail WHERE GradeCode=@lGrade  AND GradeSetId=@lGradeSetId )
  BEGIN
     SELECT 'Enter proper value for Gradeset : ' + @lgrade  AS ValidateCode
    END
  IF Exists ((select 1 from sAssessment.tCCESubjectSubActivityIndicatorMaster where Title=@lIndicator AND OrgId=@rOrgId AND CCESubjectSubActivityId = @lSubActivityId  AND Title COLLATE DATABASE_DEFAULT = @lIndicator COLLATE DATABASE_DEFAULT))         
    BEGIN
		SET @1ExistTitle = @1ExistTitle + @lclass+'-'+@lSubject+'/' +@lIndicator + ','
    END	 
	SET @lCount = @lCount - 1	
 END
	 SELECT @1DuplicateTitle=COALESCE(@1DuplicateTitle,'') +Class+'-'+Subject+'/' + + Indicator + ',' FROM #tTable1  GROUP BY Indicator,Class,Subject,Activity,SubActivity  HAVING ( COUNT(Indicator) > 1 )
	 SELECT @1DuplicateNumber=COALESCE(@1DuplicateNumber,'') +Class+'-'+Subject+'/' + Convert(varchar,Number) + ',' FROM #tTable1   GROUP BY Number,Class,Subject,Activity,SubActivity HAVING ( COUNT(Number) > 1 )
	 SELECT @1DuplicateOrderIndex=COALESCE(@1DuplicateOrderIndex,'') +Class+'-'+Subject+'/' + Convert(Varchar,OrderIndex) + ',' FROM #tTable1 GROUP BY OrderIndex,Class,Subject,Activity,SubActivity  HAVING ( COUNT(OrderIndex) > 1 )	
	IF(@1DuplicateTitle IS NOt NULL AND @1DuplicateTitle != '')
	BEGIN
		SET @1DuplicateTitle = 'Duplicate Indicator : ' + @1DuplicateTitle
	END
  IF(@1DuplicateNumber IS NOt  NULL AND @1DuplicateNumber != '')
	BEGIN
		SET @1DuplicateNumber = 'Duplicate Number : ' + Convert(varchar,@1DuplicateNumber)
		
	END
 IF(@1DuplicateOrderIndex IS  NOt  NULL AND @1DuplicateOrderIndex != '')
	BEGIN
		SET @1DuplicateOrderIndex = 'Duplicate OrderIndex : ' + @1DuplicateOrderIndex
	END
   IF(@1ExistTitle IS NOT NULL AND @1ExistTitle!= '')
	BEGIN
		SET @1ExistTitle = 'Exists  indicator : ' + @1ExistTitle
	END
	END
SELECT @1ExistTitle+''+isnull(@1DuplicateTitle,'') +''+isnull(@1DuplicateNumber,'')+''+isnull(@1DuplicateOrderIndex,'') 
END
GO
PRINT N'Creating [sAttendance].[pAttendanceDataVerifyGet]...';


GO
CREATE PROCEDURE [sAttendance].[pAttendanceDataVerifyGet]
	 	 
		@rClassId int,
		@rDivisionId int,
		@rYear int,
		@rMonth int,
		@rBatchId int
	 	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
		SELECT 
			A.RollNo,
			A.Code,
			A.Name,
			A.AdmissionDate,
			A.LeftDate,
			A.Gender,
			[sAttendance].[fAttendanceTotalDayGet] (A.AcademicId,@rMonth,@rYear,1) + [sAttendance].[fAttendanceTotalDayGet] (A.AcademicId,@rMonth,@rYear,2) AS TotalDays,
			[sAttendance].[fAttendanceTotalDayGet] (A.AcademicId,@rMonth,@rYear,1) AS PresentDays,
			[sAttendance].[fAttendanceTotalDayGet] (A.AcademicId,@rMonth,@rYear,2) AS AbsentDays,
			[sAttendance].[fAbsentDaysGet](@rMonth,@rYear,1,0,A.AcademicId) AS AbsentDate,
			ISNULL(SS.WorkingDays,MS.WorkingDays) AS WorkingDays,
			[sAttendance].[fHolidayForMonthGet] (@rMonth,@rYear,A.BatchId,@rDivisionId) AS HolidayDate,
			LEN([sAttendance].[fHolidayForMonthGet] (@rMonth,@rYear,A.BatchId,@rDivisionId)) - LEN(REPLACE([sAttendance].[fHolidayForMonthGet] (@rMonth,@rYear,A.BatchId,@rDivisionId),',','')) AS  HolidayCount
		FROM 
			sStudent.vStudentAllDetail A
			LEFT JOIN [sAttendance].[tMonthlySetup] MS ON MS.BatchId = A.BatchId AND MS.ClassId = A.ClassId AND MS.ForMonth = @rMonth AND MS.ForYear = @rYear
			LEFT JOIN [sAttendance].[tStudentSetup] SS ON SS.AcademicId = A.AcademicId AND SS.ForMonth = @rMonth AND SS.ForYear = @rYear
		WHERE 
			A.ClassId=@rClassId AND A.DivisionId=@rDivisionId AND A.BatchId=@rBatchId
		ORDER BY A.RollNo
END
GO
PRINT N'Creating [sBiometric].[pBiometricReportData]...';


GO
CREATE PROCEDURE [sBiometric].[pBiometricReportData]

	 @rOrgId int,
	 @rDeptId int,
	 @rForYear int,
	 @rForMonth int	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	
	DECLARE @lATTN_DATE NVARCHAR(20)
	
	
	SET @lATTN_DATE = CONVERT(NVARCHAR(10),@rForYear) + '-' + Right('000000' + CONVERT(NVARCHAR, @rForMonth), 2) + '-01'
	
	
	SELECT 
	T.*,
	E.Code,
	E.ShortName,
	DM.Displaytitle DeptName,
	DM.Code AS DeptCode,
	E.OrgID,
	DM.Id AS DepartmentId,
	EDM.Title AS Designation,
	EDM.Code AS DesignationCode	
	from 
		sBiometric.tMonthTrans T
		LEFT JOIN sHRM.tEmployeeMaster E on E.Id = T.EmployeeId
		LEFT JOIN sHRM.tEmployeeJobDetail ED ON ED.EmployeeId = E.Id
		LEFT JOIN sSetup.tDepartmentMaster DM ON DM.Id = ED.OrganizationDepartmentId
		LEFT JOIN sHRM.tEmployeeDesignationMaster EDM ON EDM.Id = ED.EmployeeDesignationId
	WHERE 
		(E.OrgId=@rOrgId) AND
		(DM.Id = @rDeptId OR @rDeptId = 0)		 AND
		(T.Attn_dt = @lATTN_DATE)
    Order by E.Code,T.Attn_dt
END
GO
PRINT N'Creating [sErp].[pStudentStrengthGet]...';


GO
CREATE PROCEDURE [sErp].[pStudentStrengthGet]
	 	 
		@rCRMLicenceId int,
		@rOrgGroupId smallint,
		@rOrgGroupName nvarchar(200),
		@rCustomerStatusId tinyint
		 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 

		BEGIN
			SET @rOrgGroupName = sCommon.fSearchStringGet(@rOrgGroupName)
		END
		SELECT 
			CM.CRMLicenceId,
			CSM.Title AS CustomerStatus,
			CM.OrgGroupId,
			CM.Title AS OrgGroupName,
			CM.Db AS DatabaseName
		FROM 
			sErp.tCustomerMaster CM
			INNER JOIN sErp.tCustomerStatusMaster CSM ON CSM.Id = CM.CustomerStatusId AND CM.InstallationTypeId = 1
		WHERE 
			(CM.CRMLicenceId = @rCRMLicenceId OR @rCRMLicenceId=0)
			AND (CM.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=0)
			AND (CM.Title LIKE @rOrgGroupName OR ISNULL(@rOrgGroupName,'') = '')		
			AND (CM.CustomerStatusId = @rCustomerStatusId OR @rCustomerStatusId=0)
END
GO
PRINT N'Creating [sFee].[pFeeReceiptListViewGet]...';


GO

		CREATE PROCEDURE [sFee].[pFeeReceiptListViewGet]
		
		
		@rAcademicId bigint,
		@rOrgId int
	    
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 	
	DECLARE @Receiptgrid VARCHAR(max)=''
	SELECT  @Receiptgrid = @Receiptgrid + '<tr>
	<td align="left" scope="col">' + ISNULL(RBM.Title,'') + '</td>
	<td align="left" scope="col">' + convert(varchar,isnull(R.ReceiptNumber,'')) + '</td>
	<td align="left" scope="col">' +  convert(varchar,isnull(R.ReceiptDate,'01/01/0001'),103) + '</td>
	<td align="left" scope="col">' +  ISNULL(PTM.Title,'') + '</td>
	<td align="left" scope="col">' +  isnull(R.ChequeNo,'') + '</td>
	<td align="left" scope="col">' + isnull(R.BankName,'') + '</td>
	<td align="left" scope="col">' +  ISNULL([sFee].[fReceiptFeeDetailGet](R.Id),'') + '</td>
	<td align="left" scope="col">' +  convert(varchar,isnull(R.ReceiptAmount,0)) + '</td>
	</tr>'	
			
  FROM 
			sFee.tReceipt R
		INNER JOIN sStudent.vStudentAcademic SA
			ON SA.AcademicId=R.SourceId AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))
		INNER JOIN sFinanceCommon.tPayTypeMaster PTM
			ON PTM.Id=R.PayTypeId
		LEFT JOIN sSecurity.tUser U
			ON U.Id=R.CreatedUserId
		INNER JOIN sFee.tReceiptBookMaster RBM 
			ON RBM.Id=R.ReceiptBookId
			
WHERE 
	R.SourceTypeId = 2001
	AND SA.AcademicId=@rAcademicId
	--AND ((@rIsDiscount =1 AND R.DiscountAmount!=0) OR (@rIsDiscount=0))
	ORDER BY R.ReceiptNumber
		select isnull(@Receiptgrid,'') as Receiptgrid

END
GO
PRINT N'Creating [sFee].[pImportFee]...';


GO
CREATE PROCEDURE [sFee].[pImportFee]
    @rOrgGroupId smallint,
	@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),@lFeeHead nvarchar(100),
		@lTitle nvarchar(100),@lNumber int,@lFeeHeadId int,@lOrderIndex int
			
EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc
	
	CREATE TABLE #tTable  
	(
		Id bigint identity,	
		Code nvarchar(20), 
		Number int, 
		Name nvarchar(100),
		FeeHead nvarchar(100), 
		OrderIndex int
	)
	INSERT INTO #tTable
	(   
		Code, 
		Number, 
		Name, 
		FeeHead, 
		OrderIndex 
	)
	SELECT
		Code, 
		Number, 
		Name, 
		FeeHead, 
		OrderIndex
	FROM OPENXML (@intDoc, '/Table/ImportFee', 1)
	WITH
	( 
		Code nvarchar(20) '@Code',			
		Name nvarchar(100) '@Name',			
		Number int '@Number',			
		FeeHead nvarchar(100) '@FeeHead',			
		OrderIndex int '@OrderIndex'
	)
EXEC sp_xml_removedocument @intDoc
SELECT @lCount =  COUNT(Id) FROM #tTable

WHILE @lCount > 0 
BEGIN	
		SET @lCode = ''
		SET @lTitle = ''
		SET @lNumber = 0
		SET @lFeeHeadId = 0
		SET @lOrderIndex = 0
		SET @lFeeHead=''
  SELECT		
		@lCode = Code,
		@lTitle = Name,
		@lNumber = Number,
		@lOrderIndex = OrderIndex,
	    @lFeeHead = FeeHead
FROM #tTable WHERE Id = @lCount  
		--BEGIN TRANSACTION
	select @lFeeHeadId=Id  from sFee.tFeeHeadMaster where OrgGroupId=@rOrgGroupId AND Title =@lFeeHead
	 IF NOT EXISTS(select 1 from sFee.tFeeMaster where Code=@lCode AND OrgGroupId=@rOrgGroupId)
  BEGIN	
		EXEC sFee.pFeeMasterAdd 0,@lNumber,@lCode,@lTitle,@lFeeHeadId,@lOrderIndex,0,@rUserId,@rOrgGroupId
	END
	 --ELSE	 
	 --BEGIN	
		--  UPDATE sFee.tFeeMaster	
		--  SET Title=@lTitle,Number=@lNumber,FeeHeadId=@lFeeHeadId,OrderIndex=@lOrderIndex,
		--  UpdatedUserId = @rUserId,UpdatedDateTime= sCommon.fGetDate() 
	 --     WHERE Code=@lCode AND OrgGroupId = @rOrgGroupId
		-- END
		 SET @lCount = @lCount - 1
		--COMMIT TRANSACTION			
END
	SELECT 1
	END TRY
	BEGIN CATCH
	
	SELECT ERROR_MESSAGE(), ERROR_LINE()
	END CATCH
	
END
GO
PRINT N'Creating [sFee].[pValidateImportFee]...';


GO
CREATE PROCEDURE [sFee].[pValidateImportFee]
     @rOrgGroupId smallint,
	 @rXmldoc [nvarchar](max)
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
DECLARE @lCount INT
DECLARE @lInterrorCode INT,@intDoc INT,  @lCode nvarchar(50),  @lTitle nvarchar(100), @lNumber int=0,@lFeeHead nvarchar(100),       
        @1ReturnCode int = 1,@1ExistFeeCode nvarchar(max) = '', @1DuplicateFeeCode nvarchar(max) = '',
        @1ExistFeeNumber nvarchar(max) = '',@1ExistFeeTitle nvarchar(max) = '',@1DuplicateFeeTitle nvarchar(max) = '',
        @1DuplicateFeeNumber nvarchar(max) = '',@1DuplicateOrderIndex nvarchar(max) = '',@1ExistFeeOrderIndex nvarchar(max)='',@lOrderIndex int=0
EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc
CREATE TABLE #tTable1 
 (
		Id bigint identity,
        Code nvarchar(20),
        Name nvarchar(100),
        Number int,FeeHead nvarchar(100),
        OrderIndex int,
  )
  INSERT INTO #tTable1
	(
	    Code, Name, Number,FeeHead ,OrderIndex 
    ) 
   SELECT
        Code,Name,Number,FeeHead,OrderIndex
   FROM OPENXML (@intDoc, '/Table/ImportFee', 1)
   With
   (
        Code nvarchar(20) '@Code',   
        Name nvarchar(100) '@Name' ,
        Number    int '@Number',
        FeeHead Nvarchar(100) '@FeeHead',
        OrderIndex    int '@OrderIndex'
   ) 
EXEC sp_xml_removedocument @intDoc
    IF EXISTS(SELECT 1 fROM #tTable1 WHERE Code IS NULL OR Code COLLATE DATABASE_DEFAULT='' COLLATE DATABASE_DEFAULT)
BEGIN
	SELECT 'Code Should not be empty' AS StudentCode
END
     ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE Name IS NULL OR Name COLLATE DATABASE_DEFAULT='' COLLATE DATABASE_DEFAULT)
BEGIN
	 SELECT 'Name Should not be empty' AS StudentCode
END
ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE Number='' OR Number Is NUll )
BEGIN
	SELECT 'Number Should not be empty' AS StudentCode
END
ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE OrderIndex = '' OR OrderIndex Is NUll )
BEGIN
	SELECT 'OrderIndex Should not be empty' AS StudentCode
END
ELSE 
     IF EXISTS(SELECT 1 fROM #tTable1 WHERE FeeHead IS NULL OR FeeHead COLLATE DATABASE_DEFAULT='' COLLATE DATABASE_DEFAULT)
BEGIN
	SELECT 'FeeHead Should not be empty' AS StudentCode
END
ELSE
BEGIN	
SELECT @lCount =  COUNT(Id) FROM #tTable1
WHILE @lCount > 0 
BEGIN
	SELECT @lCode = Code , @lTitle=Name,@lNumber=Number,@lFeeHead=FeeHead,@lOrderIndex=OrderIndex
	FROM #tTable1 WHERE Id = @lCount 
	IF NOT Exists (select 1 from sFee.tFeeHeadMaster where OrgGroupId=@rOrgGroupId AND Title COLLATE DATABASE_DEFAULT = @lFeeHead COLLATE DATABASE_DEFAULT)         
    BEGIN
		 SELECT 'Enter proper value for Gradeset : ' + @lFeeHead  AS StudentCode
    END	  
	IF Exists ((select 1 from sFee.tFeeMaster where OrgGroupId=@rOrgGroupId AND Code COLLATE DATABASE_DEFAULT = @lCode COLLATE DATABASE_DEFAULT))         
    BEGIN
		SET @1ExistFeeCode = @1ExistFeeCode + @lCode + ',' 
    END	  
    IF Exists ((select 1 from sFee.tFeeMaster where OrgGroupId=@rOrgGroupId AND Title COLLATE DATABASE_DEFAULT = @lTitle COLLATE DATABASE_DEFAULT))         
    BEGIN
		SET @1ExistFeeTitle = @1ExistFeeTitle + @lTitle + ','
    END	  
    IF Exists ((select 1 from sFee.tFeeMaster where OrgGroupId=@rOrgGroupId AND convert(varchar,Number) COLLATE DATABASE_DEFAULT = convert(varchar,@lNumber) COLLATE DATABASE_DEFAULT ))         
    BEGIN
		SET @1ExistFeeNumber = @1ExistFeeNumber + convert(varchar,@lNumber )+ ','
    END	 
      IF Exists ((select 1 from sFee.tFeeMaster where OrgGroupId=@rOrgGroupId AND convert(varchar,OrderIndex)  COLLATE DATABASE_DEFAULT = convert(varchar,@lOrderIndex) COLLATE DATABASE_DEFAULT ))               
    BEGIN
		SET @1ExistFeeOrderIndex = @1ExistFeeOrderIndex + convert(varchar,@lOrderIndex )+ ','
    END	 
	SET @lCount = @lCount - 1	
	END
SELECT @1DuplicateFeeCode=COALESCE(@1DuplicateFeeCode ,'') + Code + ',' FROM #tTable1 GROUP BY Code HAVING ( COUNT(Code) > 1 )	
SELECT @1DuplicateFeeTitle=COALESCE(@1DuplicateFeeTitle ,'') + Name + ',' FROM #tTable1 GROUP BY Name HAVING ( COUNT(Name) > 1 )	
SELECT @1DuplicateFeeNumber=COALESCE(@1DuplicateFeeNumber ,'') + CONVERT(varchar,Number) + ',' FROM #tTable1 GROUP BY Number HAVING ( COUNT(Number) > 1 )	
SELECT @1DuplicateOrderIndex=COALESCE(@1DuplicateOrderIndex ,'') +CONVERT(varchar, OrderIndex) + ',' FROM #tTable1 GROUP BY OrderIndex HAVING ( COUNT(OrderIndex) > 1 )	

	IF(@1DuplicateFeeCode IS NOT NULL AND @1DuplicateFeeCode != '')
	BEGIN
		SET @1DuplicateFeeCode = 'Duplicate Code : ' + @1DuplicateFeeCode
	END
	IF(@1DuplicateFeeTitle IS NOT NULL AND @1DuplicateFeeTitle != '')
	BEGIN
		SET @1DuplicateFeeTitle = 'Duplicate Name : ' + @1DuplicateFeeTitle
	END
	IF(@1DuplicateFeeNumber IS NOT NULL AND @1DuplicateFeeNumber != '')
	BEGIN
		SET @1DuplicateFeeNumber = 'Duplicate Number : ' + @1DuplicateFeeNumber
	END
	IF(@1DuplicateOrderIndex IS NOT NULL AND @1DuplicateOrderIndex != '')
	BEGIN
		SET @1DuplicateOrderIndex = 'Duplicate OrderIndex : ' + @1DuplicateOrderIndex
	END
	 IF (@1ExistFeeCode IS NOT NULL AND @1ExistFeeCode != '' )
	BEGIN
		SET @1ExistFeeCode = 'Exist Code : ' + @1ExistFeeCode
	END
	 IF (@1ExistFeeTitle IS NOT NULL AND @1ExistFeeTitle != '' )
	BEGIN
		SET @1ExistFeeTitle = 'Exist Name : ' + @1ExistFeeTitle
	END
	 IF (@1ExistFeenumber IS NOT NULL AND @1ExistFeenumber != '' )
	BEGIN
		SET @1ExistFeenumber = 'Exist Number : ' + @1ExistFeenumber
	END
	 IF (@1ExistFeeOrderIndex IS NOT NULL AND @1ExistFeeOrderIndex != '' )
	BEGIN
		SET @1ExistFeeOrderIndex = 'Exist OrderIndex : ' + @1ExistFeeOrderIndex
	END
	SELECT isnull(@1DuplicateFeeCode,'')+isnull(@1DuplicateFeeTitle,'')+isnull(@1DuplicateFeeNumber,'')+isnull(@1DuplicateOrderIndex,'')+isnull(@1ExistFeeCode,'')+
isnull(@1ExistFeeTitle,'') +isnull(@1ExistFeenumber,'')+ isnull(@1ExistFeeOrderIndex ,'')  AS StudentCode 
END
END
GO
PRINT N'Creating [sHrm].[pEmployeeTravelModify]...';


GO
CREATE PROCEDURE [sHrm].[pEmployeeTravelModify]
           
        @rId int,
        @rEmployeeId bigint,
      
        @rOrgId smallint,
        @rStatusId int,
        @rStatusReason nvarchar(100)
        --@rLeaveRemark nvarchar(200) 
        
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	
	BEGIN TRANSACTION

	BEGIN
		UPDATE sHrm.tEmployeeTravel
		SET 	 
		  [StatusId]=@rStatusId,
		  StatusReason=@rStatusReason
                            
		WHERE EmployeeId = @rEmployeeId AND Id=@rId
	 END 
	   SELECT @rEmployeeId AS Result	   
	   COMMIT TRANSACTION
	END TRY	
	BEGIN CATCH
		ROLLBACK TRANSACTION
		SELECT -1 AS RESULT
	END CATCH
END
GO
PRINT N'Creating [sHrm].[pImportUser]...';


GO
CREATE PROCEDURE [sHrm].[pImportUser]
    
    @rOrgId int,
	@rXmldoc [nvarchar](max),
	@rCreatedUserId bigint 
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	DECLARE @loXML XML,@lCount int,
			@lUserType nvarchar(100),
			@lEmployeeCode nvarchar(100),
			@lUserName nvarchar(100),
			@lDisplayName nvarchar(100),
			@lPassword nvarchar(500),
			@lRole nvarchar(100),
			@lRoleId bigint
	
	SET @loXML = CAST(@rXmldoc AS XML)
	
	CREATE TABLE #tTable1 (
	Id bigint identity,
	UserType nvarchar(50),
	EmployeeCode nvarchar(100),
	UserName nvarchar(100),
	DisplayName nvarchar(100),
	[Password] nvarchar(500),
	[Role] nvarchar(100),
	RoleId bigint)
	
	INSERT INTO #tTable1(
		UserType,
		EmployeeCode,
		UserName,
		DisplayName, 
		[Password],
		[Role],
		RoleId)      
	SELECT
		 T.c.value('@UserType','nvarchar(50)') AS UserType,
		 T.c.value('@EmployeeCode','nvarchar(100)') AS EmployeeCode,
		 T.c.value('@UserName','nvarchar(100)') AS UserName,
		 T.c.value('@DisplayName','nvarchar(100)') AS DisplayName,
		 T.c.value('@Password','nvarchar(500)') AS [Password],
		 T.c.value('@Role','nvarchar(100)') AS [Role],
		 T.c.value('@RolId','nvarchar(100)') AS RoleId
	FROM @loXML.nodes('/Table/ImportUser')T(c)
  			
BEGIN

	DECLARE @rUserSourceId bigint = NULL, @rUserSourceTypeId bigInt = NULL, @EmployeeId bigint = NULL, @tmp varchar(500)

	SET @tmp = ''
	
	SELECT @tmp = @tmp + T.EmployeeCode + ', '  from #tTable1 T 
	LEFT JOIN  sHrm.tEmployeeMaster EM ON T.EmployeeCode = EM.Code 
	AND EM.OrgId = @rOrgId AND upper(T.UserType) = 'EMPLOYEE' 
	WHERE EM.ID IS NULL AND T.EmployeeCode <> ''
 
	IF @tmp <> ''
	BEGIN
		SELECT -101 AS Result, SUBSTRING(@tmp, 0, LEN(@tmp)) AS ResultDetail
		RETURN
	END

	SELECT @lCount =  COUNT(Id) FROM #tTable1
 
	WHILE @lCount > 0 
	BEGIN		
		SELECT         
			@lUserType = UserType ,
			@lEmployeeCode = EmployeeCode,
			@lUserName = UserName,
			@lDisplayName = DisplayName,
			@lPassword = [Password],
			@lRole = [Role],
			@lRoleId = RoleId
		FROM #tTable1 WHERE Id = @lCount    
	     
		IF UPPER(@lUserType) = 'EMPLOYEE'
		BEGIN
		 SELECT @rUserSourceId = Id FROM sHrm.tEmployeeMaster WHERE Code = @lEmployeeCode AND OrgID=@rOrgId
		 SELECT @rUserSourceTypeId = 95
		END
		ELSE
		BEGIN
			 SELECT @rUserSourceId = 0
			 SELECT @rUserSourceTypeId = 1
		END
							
		IF EXISTS(SELECT Id FROM sSecurity.tUser WHERE LoginTitle = @lUserName AND OrgId=@rOrgId)
		BEGIN
			UPDATE sSecurity.tUser
			SET	
				LoginPassword = @lPassword,				
				IsObsolete = 0,			
				UpdatedUserId = @rCreatedUserId,
				UpdatedDateTime = sCommon.fGetDate(),
				LoginTitle = @lUserName,
				DisplayTitle = @lDisplayName
			WHERE 
				LoginTitle = @lUserName AND OrgId=@rOrgId			
		END
		ELSE
		BEGIN
			DECLARE @lNextNumber BIGINT	
			EXECUTE  sCommon.pTableRowIdGet @rOrgId, 'sSecurity.tUser', 0, 101, 1,@outNextNumber = @lNextNumber output
			INSERT INTO sSecurity.tUser
				(
					Id,		
					DisplayTitle,
					LoginTitle,
					LoginPassword,
					LastLockOutDate,
					NumberOfLogonAttempt,
					IsObsolete,
					CreatedUserId,
					CreatedDateTime,
					UpdatedUserId,
					UpdatedDateTime,
					OrgId,
					SourceId,
					SourceTypeId	
				)
			VALUES
				(
					@lNextNumber,
					@lDisplayName,					
					@lUserName,
					@lPassword,
					sCommon.fGetDate(),
					0,
					0,
					@rCreatedUserId,
					sCommon.fGetDate(),
					@rCreatedUserId,
					sCommon.fGetDate(),
					@rOrgId,
					@rUserSourceId,
					@rUserSourceTypeId
				)
				
			IF NOT EXISTS(Select 1 From [sSecurity].[tUserRole]  WHERE RoleId = @lRoleId AND UserId=@lNextNumber)
			BEGIN
				INSERT INTO 
				[sSecurity].[tUserRole] (RoleId, UserId, IsObsolete, CreatedUserId, CreatedDateTime, UpdatedUserId, UpdatedDateTime, IsPrimary)
				VALUES
				(@lRoleId,@lNextNumber,0,@rCreatedUserId,sCommon.fGetDate(),@rCreatedUserId,sCommon.fGetDate(),1)
			END
		END
		SET @lCount = @lCount-1
	  END 
	SELECT 1 AS Result, '' AS ResultDetail
 END
END
GO
PRINT N'Creating [sHrm].[pRptEmployeeDetailWithExpenseGet]...';


GO
CREATE PROCEDURE [sHrm].[pRptEmployeeDetailWithExpenseGet]
	 
	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='',
	@rEmployeeCode nvarchar (200),
	@rDepartmentId int,
	@rEmployeeGradeId int,
	@rForYear  smallint,
	@rForMonth tinyint,
	@rBatchId int,
	@rOrgId int
	 
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,
			 ISNULL(E.Amount,0) AS Amount
        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
			LEFT JOIN sAccounting.tExpense E ON EM.EmployeeId = E.EmployeeId AND DATEPART(MONTH,E.ExpenseDate)=AT.ForMonth
    	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=''))
    		ORDER BY  EM.EmployeeId,AT.ForYear,AT.ForMonth
    		
END
GO
PRINT N'Creating [sLibrary].[pBookLogListViewGet]...';


GO
CREATE PROCEDURE [sLibrary].[pBookLogListViewGet]
	 @rReaderSourceTypeId smallint=2003,
	 @rAcademicId bigint,
	 @rOrgId smallint,
	 @rBatchId int
	
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
DECLARE @lBookgrid VARCHAR(max)=''

SELECT  @lBookgrid = @lBookgrid + '<tr>
  <td align="left" scope="col">' +  Isnull(LM.Title,'') + '</td>
	<td align="left" scope="col">' + ISNULL(BM.Code,'')+ '</td>
	<td align="left" scope="col">' + isnull(BM.Title,'') + '</td>
	<td align="left" scope="col">' +  convert(varchar,isnull(BL.LogDate,''),103) + '</td>
	<td align="left" scope="col">' +  convert(varchar,isnull(BL.DueDate,''),103) + '</td>
	<td align="left" scope="col">' + isnull(SM.Title,'') + '</td>
</tr>'	
	FROM 
			sLibrary.tBookLog BL
			INNER JOIN sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId
			INNER JOIN sStudent.vStudentLastAcademic SA ON SA.StudentId=BL.ReaderSourceId
			INNER JOIN sLibrary.tIssueSetting IS1 ON IS1.SourceId=SA.ClassId AND IS1.SourceTypeId=2005
			INNER JOIN sCommon.tStatusMaster SM ON SM.Id=BL.StatusId AND SM.IsObsolete = 0 AND SM.StatusTypeId=106
			INNER JOIN sLibrary.tLibraryMaster LM ON LM.Id=BL.LibraryId
	WHERE ((BL.ReaderSourceTypeId=@rReaderSourceTypeId) OR (@rReaderSourceTypeId=0))
		 --(BL.ReaderSourceId=@rReaderSourceId)
		AND BL.IsCurrentStatus=1
		AND ((BL.StatusId=522) OR (BL.StatusId=523))
		AND (BL.OrgId=@rOrgId)
		AND (BL.BatchId=@rBatchId)
		AND SA.AcademicId=@rAcademicId
	select isnull(@lBookgrid,'') as Bookgrid
END
GO
PRINT N'Creating [sOp].[pGatewayProductAdd]...';


GO
CREATE PROCEDURE [sOp].[pGatewayProductAdd]
	 
        @rId int,
	    @rGatewayConfigurationId int,
		@rTitle nvarchar(150),
		@rGatewayURL nvarchar(1000),
		@rServerPort nvarchar(50),
		@rLoginId nvarchar(50),
		@rLoginPassword nvarchar(50),
		@rProductId nvarchar(100),
		@rOrgGroupId int
		
		
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY

	IF(@rId = 0)	
	BEGIN
		IF EXISTS(SELECT Id FROM [sOp].[tGatewayProduct] WHERE GatewayConfigurationId=@rGatewayConfigurationId AND Title=@rTitle AND ProductId = @rProductId)
		BEGIN
			SELECT -101 AS Result
			RETURN
		END 
	END
	ELSE
	BEGIN
		IF  EXISTS(SELECT Id FROM [sOp].[tGatewayProduct] WHERE GatewayConfigurationId=@rGatewayConfigurationId AND Title=@rTitle AND ProductId = @rProductId AND Id<>@rId)
		BEGIN
			SELECT -101 AS Result
			RETURN
		END
	END	

	BEGIN TRANSACTION	
	DECLARE @lNextNumber INT     
	IF(@rId = 0)	
	BEGIN

	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sOp.tGatewayProduct', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO [sOp].[tGatewayProduct]
		(
			[Id],
			[GatewayConfigurationId],
			[Title],
			[GatewayURL],
			[ServerPort],
			[LoginId],
			[LoginPassword],
			[ProductId]
		)
	VALUES
		(
			@lNextNumber,
			@rGatewayConfigurationId,
			@rTitle,
			@rGatewayURL,
			@rServerPort,
			@rLoginId,
			@rLoginPassword,
			@rProductId
		)
		    SELECT 1 AS Result
	END	 
ELSE
	 BEGIN
		SET @lNextNumber = @rId
	    UPDATE  [sOp].[tGatewayProduct]
	    SET
			[GatewayConfigurationId]=@rGatewayConfigurationId,
			[Title]=@rTitle,
			[GatewayURL]=@rGatewayURL,
			[ServerPort]=@rServerPort,
			[LoginId]=@rLoginId,
			[LoginPassword]=@rLoginPassword,
			[ProductId]=@rProductId
	    WHERE Id = @rId
	    SELECT 11 AS Result
	 END  	

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


GO
CREATE PROCEDURE [sOp].[pGatewayProductGet]

	 @rId int,
	 @rGatewayConfigurationId int,
	 @rTitle nvarchar(150),
	 @rOrgGroupId int
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	BEGIN
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
	END
	
	SELECT 
			GP.Id,
			GP.GatewayConfigurationId,
			PGM.Title AS PaymentGatewayName,
			GP.Title AS GatewayProductName,
			ISNULL(GP.GatewayURL,'') AS GatewayURL,
			ISNULL(GP.ServerPort,'') AS ServerPort,
			ISNULL(GP.LoginId,'') AS LoginId,
			ISNULL(GP.LoginPassword,'') AS LoginPassword,
			ISNULL(GP.ProductId,'') AS ProductId
	FROM 
			[sOp].[tGatewayProduct] GP
			INNER JOIN [sOp].[tGatewayConfiguration] GC ON GC.Id = GP.GatewayConfigurationId
			INNER JOIN [sOp].[tPaymentGatewayMaster] PGM ON PGM.Id = GC.PaymentGatewayId
	WHERE 
			(GC.OrgGroupId = @rOrgGroupId)
			AND	((GP.Id = @rId) OR (@rId = 0))
			AND	((GP.GatewayConfigurationId = @rGatewayConfigurationId) OR (@rGatewayConfigurationId = 0))
			AND ((GP.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
END
GO
PRINT N'Creating [sOp].[pGatewayProductReceiptBookMappingAdd]...';


GO
 
CREATE PROCEDURE [sOp].[pGatewayProductReceiptBookMappingAdd]
    
    @rOrgGroupId int,
	@rXmldoc [nvarchar](max),
	@rGatewayConfigurationId int

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
DECLARE @loDoc INT
BEGIN TRY
BEGIN TRANSACTION
			
	DELETE GPRBM FROM [sOp].[tGatewayProductReceiptBookMapping] GPRBM
	INNER JOIN [sOp].[tGatewayProduct] GP ON GP.Id = GPRBM.GatewayProductId
	INNER JOIN [sFee].[tReceiptBookMaster] RBM ON RBM.Id = GPRBM.ReceiptBookId 
	WHERE RBM.OrgGroupId=@rOrgGroupId AND GP.GatewayConfigurationId=@rGatewayConfigurationId
			
	EXEC sp_xml_preparedocument @loDoc OUTPUT, @rXmldoc
		
	INSERT INTO [sOp].[tGatewayProductReceiptBookMapping]
	(
		[GatewayProductId],
		[ReceiptBookId]
	)
	SELECT
		GatewayProductId,
		ReceiptBookId
	FROM OPENXML (@loDoc, '/Table/GatewayProductReceiptBookMapping', 1)
	WITH
	( 
		GatewayProductId int,
		ReceiptBookId int 
	)
	SELECT 1 AS Result	
	EXEC sp_xml_removedocument @loDoc
		
COMMIT TRANSACTION			

END TRY
BEGIN CATCH
ROLLBACK TRANSACTION
SELECT -1 Result
END CATCH
	
END
GO
PRINT N'Creating [sOp].[pGatewayProductReceiptBookMappingGet]...';


GO
 
CREATE PROCEDURE [sOp].[pGatewayProductReceiptBookMappingGet]

	 @rOrgGroupId int,
	 @rGatewayConfigurationId int
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
		
BEGIN 
	SELECT 
			RBM.Id AS ReceiptBookId,
			RBM.Title AS ReceiptBookName,
			ISNULL(A.GatewayProductId,0) AS GatewayProductId
	FROM 
			[sFee].[tReceiptBookMaster] RBM
			LEFT JOIN
			(SELECT RBM.Id,GPRBM.GatewayProductId FROM [sFee].[tReceiptBookMaster] RBM 
			INNER JOIN [sOp].[tGatewayProductReceiptBookMapping] GPRBM ON RBM.Id = GPRBM.ReceiptBookId 
		    INNER JOIN [sOp].[tGatewayProduct] GP ON GP.Id = GPRBM.GatewayProductId AND GP.GatewayConfigurationId = @rGatewayConfigurationId
		    ) A ON A.Id = RBM.Id
			WHERE 
			RBM.OrgGroupId=@rOrgGroupId AND RBM.IsObsolete = 0
			ORDER BY RBM.OrderIndex
END
GO
PRINT N'Creating [sSecurity].[pAddScreenAdd]...';


GO

CREATE PROCEDURE [sSecurity].[pAddScreenAdd]
	 
        @rTitle nvarchar(100), 
		@rIsObsolete bit, 
		@rModuleId tinyint, 
		@rAvailablePermission int , 
		@rOrderIndex int, 
		@rResourceTypeId tinyint,
		@rId smallint
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	--IF(@rId=0)
	--BEGIN
	--	IF EXiSTS (SELECT 1 FROM  sSecurity.tTask WHERE Title=@rTitle AND @rId=0)
	--	BEGIN
	--	select -103 as Result
	--	RETURN  
	--	END
	--END
	--ELSE
	--BEGIN
	--IF EXiSTS (SELECT 1 FROM  sSecurity.tTask WHERE Title=@rTitle AND @rId<>0)
	--Begin
	--	select -103 as Result
	--	RETURN 
	--	END
	--END
	
BEGIN TRANSACTION	
	IF(@rId=0)
	BEGIN 
	DECLARE  @lMaxTaskId smallint
	SELECT @lMaxTaskId=Isnull(MaX(Id),0)+1 FROM sSecurity.tTask
	
	INSERT INTO sSecurity.tTask
		(
		Id,
		Title,
		--TitleResourceKeyId, 
		IsObsolete, 
		ModuleId, 
		AvailablePermission, 
		OrderIndex, 
		ResourceTypeId
			
		)
	VALUES
		(
		@lMaxTaskId,
		@rTitle,
		--@rTitleResourceKeyId, 
		@rIsObsolete, 
		@rModuleId, 
		@rAvailablePermission, 
		@rOrderIndex, 
		@rResourceTypeId
		)
		 SELECT 1,@lMaxTaskId AS Result
	END	
ELSE
	 BEGIN
	  
	    UPDATE  sSecurity.tTask
	    SET
			Title=@rTitle,
			IsObsolete=@rIsObsolete,
			OrderIndex=@rOrderIndex,
		    ModuleId=@rModuleId,
		    AvailablePermission=@rAvailablePermission,
		    ResourceTypeId=@rResourceTypeId
	      WHERE Id = @rId
	      SELECT 11 ,@rId AS Result
	 END  	
	COMMIT TRANSACTION		
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Creating [sSecurity].[pAddScreenGet]...';


GO
CREATE PROCEDURE [sSecurity].[pAddScreenGet]
	 @rId smallint = 0,
	 @rTitle nvarchar(100)='',
	 @rResourceTypeId tinyint=0,
	 @rModuleId tinyint=0
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
			--SET @rTitle = sCommon.fSearchStringGet(@rTitle)
DECLARE @lPermission int
	SELECT 
			T.Id ,
			T.Title AS TaskTitle,
			Isnull(T.IsObsolete,0) AS IsObsolete,
			ISNULL(ModuleId,0) AS ModuleId,
			ISNULL(T.AvailablePermission,0) AS AvailablePermission,
			T.OrderIndex,
			ISNULL(T.ResourceTypeId,0) AS ResourceTypeId,
			Isnull(SR.Title,'') AS ResourceType,
			Isnull(CM.Title,'') AS Module,
			CAST(ISNULL((T.AvailablePermission & 1), 0) AS BIT) AS [Create],
			CAST(ISNULL((T.AvailablePermission & 2)/2, 0) AS BIT) AS [Read],
			CAST(ISNULL((T.AvailablePermission & 4)/4, 0) AS BIT) AS [Update],
			CAST(ISNULL((T.AvailablePermission & 8)/8, 0) AS BIT) AS [Delete],
			CAST(ISNULL((T.AvailablePermission & 16)/16, 0) AS BIT) AS [Search],
			CAST(ISNULL((T.AvailablePermission & 32)/32, 0) AS BIT) AS [Print],
			CAST(ISNULL((T.AvailablePermission & 64)/64, 0) AS BIT) AS [Execute]
      FROM  sSecurity.tTask T
      INNER JOIN sSecurity.tResourceTypeMaster SR ON SR.Id=T.ResourceTypeId
      INNER JOIN sCommon.tModuleMaster CM ON CM.Id=T.ModuleId

  WHERE   
           ((T.Id = @rId) OR (@rId = 0))
	        AND ((T.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
	        AND ((T.ModuleId = @rModuleId) OR (ISNULL(@rModuleId,0) = 0))
	        AND ((T.ResourceTypeId = @rResourceTypeId) OR (ISNULL(@rResourceTypeId,0) = 0))
	        
	    ORDER BY ID desc
END
GO
PRINT N'Creating [sSecurity].[pAddScreenSCreenAdd]...';


GO

CREATE PROCEDURE [sSecurity].[pAddScreenSCreenAdd]
	 
        @rTitle nvarchar(100), 
		@rIsObsolete bit, 
		@rOrderIndex int, 
		@rId smallint,
		@rTaskId smallint,
		@rPage nvarchar(500),
		@rScreenGroupId smallint, 
	    @rScreenTypeId int, 
		@rIsHideInScreenGroup bit
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	--IF(@rId=0)
	--BEGIN
	--IF EXiSTS (SELECT 1 FROM sSecurity.tScreen WHERE Title=@rTitle AND @rId=0)
	--select -103 as Result
	--RETURN 
	--END
	--ELSE
	--BEGIN
	--IF EXiSTS (SELECT 1 FROM sSecurity.tScreen WHERE Title=@rTitle AND @rId<>0)
	--select -103 as Result
	--RETURN 
	--END
	 BEGIN TRANSACTION	
	IF(@rId=0)
	BEGIN 
	DECLARE  @lMaxTaskId smallint
	SELECT @lMaxTaskId=Isnull(MaX(Id),0)+1 FROM sSecurity.tScreen
	
	INSERT INTO sSecurity.tScreen
		(
		   Id,
		   Title,
		   TaskId,
		   Page,
		   IsObsolete, 
		   ScreenGroupId, 
		   OrderIndex, 
		   ScreenTypeId, 
		   --IconPath, 
		   IsHideInScreenGroup
		
		)
	VALUES
		(
		   @lMaxTaskId,
		   @rTitle,
		   @rTaskId,
		   @rPage,
		   @rIsObsolete, 
		   @rScreenGroupId, 
		   @rOrderIndex, 
		   @rScreenTypeId, 
		  -- @rIconPath, 
		   @rIsHideInScreenGroup
		
		)
		 SELECT 1 AS Result
	END	
ELSE
	 BEGIN
	  
	    UPDATE  sSecurity.tScreen
	    SET
			
		   Title=@rTitle,
		   TaskId=@rTaskId,
		   Page= @rPage,
		   IsObsolete=@rIsObsolete, 
		   ScreenGroupId=@rScreenGroupId, 
		   OrderIndex=@rOrderIndex, 
		   ScreenTypeId= @rScreenTypeId, 
		   IsHideInScreenGroup=@rIsHideInScreenGroup
	      WHERE Id = @rId
	      SELECT 11 AS Result
	 END  	
	COMMIT TRANSACTION		
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Creating [sSecurity].[pAddScreenSearchScreenGet]...';


GO
CREATE PROCEDURE [sSecurity].[pAddScreenSearchScreenGet]
	 @rTaskId int = 0,
	 @rTitle nvarchar(100)='',
	 @rScreenGroupId smallint=0,
	 @rScreenId  smallint=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
			--SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		
	SELECT 
			ISNULL(SC.Id,0) AS ScreenId,
		    Isnull(SC.Title,'')AS ScreenTitle,
		    ISNULL(SC.TaskId,0) AS TaskId,
		    Isnull(SC.Page,'') AS Page,
		   Isnull(SC.IsObsolete,0) AS IsObsolete,
		   Isnull(SC.ScreenGroupId,0) AS ScreenGroupId,
	       Isnull(SC.OrderIndex,0) AS ScreenOrderIndex ,
	       Isnull(SC.ScreenTypeId,0) AS  ScreenTypeId,
		   Isnull(SC.IsHideInScreenGroup,0) AS IsHideInScreenGroup,
		   	T.Title AS TaskTitle,
		   	ISNULL(ModuleId,0) AS ModuleId,
			ISNULL(AvailablePermission,0) AS AvailablePermission,
			T.OrderIndex,
			ISNULL(T.ResourceTypeId,0) AS ResourceTypeId,
			CAST(ISNULL((T.AvailablePermission & 1), 0) AS BIT) AS [Create],
			CAST(ISNULL((T.AvailablePermission & 2)/2, 0) AS BIT) AS [Read],
			CAST(ISNULL((T.AvailablePermission & 4)/4, 0) AS BIT) AS [Update],
			CAST(ISNULL((T.AvailablePermission & 8)/8, 0) AS BIT) AS [Delete],
			CAST(ISNULL((T.AvailablePermission & 16)/16, 0) AS BIT) AS [Search],
			CAST(ISNULL((T.AvailablePermission & 32)/32, 0) AS BIT) AS [Print],
			CAST(ISNULL((T.AvailablePermission & 64)/64, 0) AS BIT) AS [Execute]
		   
      FROM  sSecurity.tScreen SC
      INNER JOIN sSecurity.tTask T On T.Id=SC.TaskId 
  WHERE   
	           ((SC.ScreenGroupId = @rScreenGroupId) OR (ISNULL(@rScreenGroupId,0) = 0))
	           AND  ((SC.Id = @rScreenId) OR (ISNULL(@rScreenId,0) = 0))
	            AND  ((SC.TaskId = @rTaskId) OR (ISNULL(@rTaskId,0) = 0))
	           AND ((SC.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
	       ORDER BY SC.Id  DESC
END
GO

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

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

   
END


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