

DELETE from sCommon.tTableRowId WHERE TableTitle like 'sPayroll.%'

GO
DELETE FROM	sPayroll.tPayElement
DELETE FROM	sPayroll.tPaySetupDependent
DELETE FROM	sPayroll.tPayProcessElement
DELETE FROM	sPayroll.tPfProcessCharge
DELETE FROM	sPayroll.tEsiProcess
DELETE FROM	sPayroll.tPfProcess
DELETE FROM	sPayroll.tPayProcessEmployee
DELETE FROM	sPayroll.tPayProcess
DELETE FROM	sPayroll.tPaySetup
DELETE FROM	sPayroll.tEsiSetup
DELETE FROM	sPayroll.tPfSetup
DELETE FROM	sPayroll.tProfessionalTaxRange

GO




 


GO
ALTER TABLE [sAssessment].[tExamMaster]
    ADD [IsPublished]                   BIT        NULL,
        [IsDisplayHighestDivisionMark]  BIT        NULL,
        [IsDisplayHighestDivisionGrade] NCHAR (10) NULL;


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


GO
ALTER TABLE [sHrm].[tEmployeeImages]
    ADD [UpdatedDateTime] DATETIME NULL;


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


GO
ALTER TABLE [sHrm].[tEmployeeStatutoryAndOther]
    ADD [PayrollId]      INT NULL,
        [PayrollGroupId] INT NULL;


GO
PRINT N'Starting rebuilding table [sPayroll].[tEsiSetup]...';


GO
/*
The column [sPayroll].[tEsiSetup].[OrgId] is being dropped, data loss could occur.
*/
GO
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;

SET XACT_ABORT ON;

BEGIN TRANSACTION;

CREATE TABLE [sPayroll].[tmp_ms_xx_tEsiSetup] (
    [ID]                 INT             NOT NULL,
    [PayrollYearId]      INT             NULL,
    [EmployeeEsiPercent] DECIMAL (5, 2)  NOT NULL,
    [EmployerEsiPercent] DECIMAL (5, 2)  NOT NULL,
    [EsiSalaryLimit]     DECIMAL (22, 6) NOT NULL,
    [RoundingTypeId]     TINYINT         NOT NULL,
    [RoundingPrecision]  INT             NOT NULL,
    [EffectiveDate]      DATE            NOT NULL,
    [CreatedUserId]      BIGINT          NOT NULL,
    [CreatedDateTime]    DATETIME        NOT NULL
);

IF EXISTS (SELECT TOP 1 1
           FROM   [sPayroll].[tEsiSetup])
    BEGIN
        INSERT INTO [sPayroll].[tmp_ms_xx_tEsiSetup] ([ID], [EmployeeEsiPercent], [EmployerEsiPercent], [EsiSalaryLimit], [RoundingTypeId], [RoundingPrecision], [EffectiveDate], [CreatedUserId], [CreatedDateTime])
        SELECT [ID],
               [EmployeeEsiPercent],
               [EmployerEsiPercent],
               [EsiSalaryLimit],
               [RoundingTypeId],
               [RoundingPrecision],
               [EffectiveDate],
               [CreatedUserId],
               [CreatedDateTime]
        FROM   [sPayroll].[tEsiSetup];
    END

DROP TABLE [sPayroll].[tEsiSetup];

EXECUTE sp_rename N'[sPayroll].[tmp_ms_xx_tEsiSetup]', N'tEsiSetup';

COMMIT TRANSACTION;

SET TRANSACTION ISOLATION LEVEL READ COMMITTED;


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


GO
ALTER TABLE [sPayroll].[tPayElement] DROP COLUMN [OrgId];


GO
ALTER TABLE [sPayroll].[tPayElement]
    ADD [PayElementDefaultId] INT NULL,
        [PayrollId]           INT NULL;


GO
PRINT N'Creating PK_tPayElement...';


GO
ALTER TABLE [sPayroll].[tPayElement]
    ADD CONSTRAINT [PK_tPayElement] 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'Altering [sPayroll].[tPayProcess]...';


GO
ALTER TABLE [sPayroll].[tPayProcess] DROP COLUMN [AccountingYearId], COLUMN [BatchId];


GO
ALTER TABLE [sPayroll].[tPayProcess]
    ADD [PayrollYearId] INT NULL;


GO
PRINT N'Starting rebuilding table [sPayroll].[tPayProcessEmployee]...';


GO
/*
The column [sPayroll].[tPayProcessEmployee].[GradeId] is being dropped, data loss could occur.

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

SET XACT_ABORT ON;

BEGIN TRANSACTION;

CREATE TABLE [sPayroll].[tmp_ms_xx_tPayProcessEmployee] (
    [ID]             BIGINT          NOT NULL,
    [PayProcessId]   INT             NOT NULL,
    [EmployeeId]     BIGINT          NOT NULL,
    [PayrollGroupId] INT             NOT NULL,
    [TotalEarning]   DECIMAL (22, 2) NOT NULL,
    [TotalDeduction] DECIMAL (22, 2) NOT NULL,
    [NetAmount]      DECIMAL (22, 2) NOT NULL
);

IF EXISTS (SELECT TOP 1 1
           FROM   [sPayroll].[tPayProcessEmployee])
    BEGIN
        INSERT INTO [sPayroll].[tmp_ms_xx_tPayProcessEmployee] ([ID], [PayProcessId], [EmployeeId], [TotalEarning], [TotalDeduction], [NetAmount])
        SELECT [ID],
               [PayProcessId],
               [EmployeeId],
               [TotalEarning],
               [TotalDeduction],
               [NetAmount]
        FROM   [sPayroll].[tPayProcessEmployee];
    END

DROP TABLE [sPayroll].[tPayProcessEmployee];

EXECUTE sp_rename N'[sPayroll].[tmp_ms_xx_tPayProcessEmployee]', N'tPayProcessEmployee';

COMMIT TRANSACTION;

SET TRANSACTION ISOLATION LEVEL READ COMMITTED;


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


GO
ALTER TABLE [sPayroll].[tPaySetup] DROP COLUMN [OrgId];


GO
ALTER TABLE [sPayroll].[tPaySetup]
    ADD [PayrollId] INT NULL;


GO
PRINT N'Starting rebuilding table [sPayroll].[tPfSetup]...';


GO
/*
The column [sPayroll].[tPfSetup].[OrgId] is being dropped, data loss could occur.
*/
GO
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;

SET XACT_ABORT ON;

BEGIN TRANSACTION;

CREATE TABLE [sPayroll].[tmp_ms_xx_tPfSetup] (
    [Id]                       INT             NOT NULL,
    [PayrollYearId]            INT             NULL,
    [PfSalaryLimit]            DECIMAL (22, 6) NULL,
    [FpsSalaryLimit]           DECIMAL (22, 6) NOT NULL,
    [EmployeePfPercent]        DECIMAL (5, 2)  NOT NULL,
    [EmployerPfPercent]        DECIMAL (5, 2)  NOT NULL,
    [EmployerFpsPercent]       DECIMAL (5, 2)  NOT NULL,
    [AdminChargesPercent]      DECIMAL (5, 2)  NOT NULL,
    [EdliPercent]              DECIMAL (5, 2)  NOT NULL,
    [InspectionChargesPercent] DECIMAL (5, 2)  NOT NULL,
    [MaximumAgeForFps]         SMALLINT        NOT NULL,
    [RoundingTypeId]           TINYINT         NOT NULL,
    [RoundingPrecision]        INT             NOT NULL,
    [MaximumVpfPercent]        DECIMAL (5, 2)  NOT NULL,
    [MaximumVpfAmount]         DECIMAL (22, 6) NOT NULL,
    [CreatedUserId]            BIGINT          NOT NULL,
    [CreatedDateTime]          DATETIME        NOT NULL
);

IF EXISTS (SELECT TOP 1 1
           FROM   [sPayroll].[tPfSetup])
    BEGIN
        INSERT INTO [sPayroll].[tmp_ms_xx_tPfSetup] ([Id], [PfSalaryLimit], [FpsSalaryLimit], [EmployeePfPercent], [EmployerPfPercent], [EmployerFpsPercent], [AdminChargesPercent], [EdliPercent], [InspectionChargesPercent], [MaximumAgeForFps], [RoundingTypeId], [RoundingPrecision], [MaximumVpfPercent], [MaximumVpfAmount], [CreatedUserId], [CreatedDateTime])
        SELECT [Id],
               [PfSalaryLimit],
               [FpsSalaryLimit],
               [EmployeePfPercent],
               [EmployerPfPercent],
               [EmployerFpsPercent],
               [AdminChargesPercent],
               [EdliPercent],
               [InspectionChargesPercent],
               [MaximumAgeForFps],
               [RoundingTypeId],
               [RoundingPrecision],
               [MaximumVpfPercent],
               [MaximumVpfAmount],
               [CreatedUserId],
               [CreatedDateTime]
        FROM   [sPayroll].[tPfSetup];
    END

DROP TABLE [sPayroll].[tPfSetup];

EXECUTE sp_rename N'[sPayroll].[tmp_ms_xx_tPfSetup]', N'tPfSetup';

COMMIT TRANSACTION;

SET TRANSACTION ISOLATION LEVEL READ COMMITTED;


GO
PRINT N'Starting rebuilding table [sPayroll].[tProfessionalTaxRange]...';


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

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

SET XACT_ABORT ON;

BEGIN TRANSACTION;

CREATE TABLE [sPayroll].[tmp_ms_xx_tProfessionalTaxRange] (
    [Id]              INT             NOT NULL,
    [Salary]          DECIMAL (22, 6) NOT NULL,
    [Tax]             DECIMAL (22, 6) NOT NULL,
    [PayrollYearId]   INT             NOT NULL,
    [CreatedUserId]   BIGINT          NOT NULL,
    [CreatedDateTime] DATETIME        NOT NULL
);

IF EXISTS (SELECT TOP 1 1
           FROM   [sPayroll].[tProfessionalTaxRange])
    BEGIN
        INSERT INTO [sPayroll].[tmp_ms_xx_tProfessionalTaxRange] ([Id], [Salary], [Tax], [CreatedUserId], [CreatedDateTime])
        SELECT [Id],
               [Salary],
               [Tax],
               [CreatedUserId],
               [CreatedDateTime]
        FROM   [sPayroll].[tProfessionalTaxRange];
    END

DROP TABLE [sPayroll].[tProfessionalTaxRange];

EXECUTE sp_rename N'[sPayroll].[tmp_ms_xx_tProfessionalTaxRange]', N'tProfessionalTaxRange';

COMMIT TRANSACTION;

SET TRANSACTION ISOLATION LEVEL READ COMMITTED;


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


GO
ALTER TABLE [sStudent].[tStudentFamily]
    ADD [MarriageAnniversaryDate] DATE NULL;


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


GO
CREATE TABLE [sPayroll].[tPayElementDefault] (
    [ID]                     INT            NOT NULL,
    [Code]                   NVARCHAR (20)  NOT NULL,
    [Title]                  NVARCHAR (100) NOT NULL,
    [PayElementTypeId]       TINYINT        NOT NULL,
    [PaidCategoryId]         TINYINT        NOT NULL,
    [IsLwp]                  BIT            NULL,
    [IsEmployeeSpecific]     BIT            NULL,
    [IsDepend]               BIT            NULL,
    [IsAvailDuringProbation] BIT            NULL,
    [IsIncludeInPaySlip]     BIT            NULL,
    [SortOrder]              TINYINT        NULL,
    [IsObsolete]             BIT            NOT NULL
);


GO
PRINT N'Creating PK_tPayElementDefault...';


GO
ALTER TABLE [sPayroll].[tPayElementDefault]
    ADD CONSTRAINT [PK_tPayElementDefault] 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 [sPayroll].[tPayrollGroupMaster]...';


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


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


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


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


GO
CREATE TABLE [sPayroll].[tPayrollYearMaster] (
    [Id]              INT            NOT NULL,
    [Code]            NVARCHAR (100) NOT NULL,
    [Title]           NVARCHAR (100) NOT NULL,
    [FromDate]        DATE           NOT NULL,
    [ToDate]          DATE           NOT NULL,
    [CreatedUserId]   BIGINT         NOT NULL,
    [CreatedDateTime] DATETIME       NOT NULL,
    [UpdatedUserId]   BIGINT         NULL,
    [UpdatedDateTime] DATETIME       NULL,
    [PayrollId]       INT            NULL,
    [IsActive]        BIT            NOT NULL,
    [OrgGroupId]      SMALLINT       NULL
);


GO
PRINT N'Creating [sSecurity].[tScreenGroupMapping]...';


GO
CREATE TABLE [sSecurity].[tScreenGroupMapping] (
    [ScreenId]      INT      NULL,
    [ScreenGroupId] SMALLINT NULL
);

 
PRINT N'Creating [sAssessment].[fGetHighestDivisionGrade]...';


GO

CREATE FUNCTION [sAssessment].[fGetHighestDivisionGrade](@rDivisionId int,@rExamDetailId int)
RETURNS nvarchar(10) WITH EXECUTE AS CALLER
AS 
BEGIN
 DECLARE @lResultId nvarchar(10)
 SELECT @lResultId = ISNULL(min(SubjectGrade),'') FROM sAssessment.tResultDetail RD INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId 
 INNER JOIN sStudent.tAcademic A ON R.AcademicId = A.Id
  WHERE RD.ExamDetailId = @rExamDetailId
  AND A.DivisionId = @rDivisionId
  
	RETURN  @lResultId 
END
GO
PRINT N'Creating [sAssessment].[fGetHighestDivisionMark]...';


GO

CREATE FUNCTION [sAssessment].[fGetHighestDivisionMark](@rDivisionId int,@rExamDetailId int)
RETURNS [bigint] WITH EXECUTE AS CALLER
AS 
BEGIN
 DECLARE @lResultId Decimal(8,2)
 SELECT @lResultId = ISNULL(MAX(Obtain),0) FROM sAssessment.tResultDetail RD INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId 
 INNER JOIN sStudent.tAcademic A ON R.AcademicId = A.Id
  WHERE RD.ExamDetailId = @rExamDetailId
  AND A.DivisionId = @rDivisionId
	return  @lResultId 
END
GO
PRINT N'Creating [sPayroll].[fMonthYearForPayrollGet]...';


GO


CREATE FUNCTION [sPayroll].[fMonthYearForPayrollGet](@rPayrollYearId int)
RETURNS  @List TABLE (
		 MonthNumber tinyint,
		 YearNumber smallint,
		 MonthTitle nvarchar(20),
		 NoOfDays tinyint,
		 PayrollYearId int 
)  WITH EXECUTE AS CALLER
AS 
BEGIN

	declare @rFromDate DATE
    declare @rToDate DATE 
	Select @rFromDate=FromDate,@rToDate=ToDate FROM sPayroll.tPayrollYearMaster WHERE Id=@rPayrollYearId 
		 
	WHILE (@rFromDate <= @rToDate)
	BEGIN	
	INSERT INTO @List 
	SELECT 
			DATEPART(MONTH,@rFromDate) AS MonthNumber,
			DATENAME(YEAR,@rFromDate) AS YearNumber,
			DATENAME(MONTH,@rFromDate) AS MonthTitle,
			DATEDIFF(DAY, 
            DATEADD(MONTH, DATEDIFF(MONTH, 0, @rFromDate), 0),
            DATEADD(MONTH, DATEDIFF(MONTH, 0, @rFromDate) + 1, 0)),
			@rPayrollYearId AS PayrollYearId
			SET @rFromDate = DATEADD(M,1,@rFromDate)  
	END 
	 
IF NOT EXISTS(SELECT * FROM @List WHERE MonthNumber = DATEPART(MONTH,@rToDate) AND 
YearNumber = DATENAME(YEAR,@rToDate)
AND PayrollYearId  = @rPayrollYearId)
BEGIN
INSERT INTO @List 
	  SELECT 
			DATEPART(MONTH,@rToDate) AS MonthNumber,
			DATENAME(YEAR,@rToDate) AS YearNumber,
			DATENAME(MONTH,@rToDate) AS MonthTitle,
			DATEDIFF(DAY, 
            DATEADD(MONTH, DATEDIFF(MONTH, 0, @rToDate), 0),
            DATEADD(MONTH, DATEDIFF(MONTH, 0, @rToDate) + 1, 0)),
			@rPayrollYearId AS PayrollYearId 
END
			  

		  
	
	--;with tMonth_Year (CurrentDate,BatchId)
 --   AS
 --   (
 --       SELECT @rFromDate,@rBatchId
 --       UNION ALL
 --       SELECT DATEADD(MONTH,1,CurrentDate),@rBatchId
 --       from tMonth_Year
 --       where DATEADD(MONTH,1,CurrentDate)<= DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,@rToDate)+1,0))
 --   )
    
 --   INSERT INTO @List 
 --   SELECT 
	--		DATEPART(MONTH,CurrentDate) AS MonthNumber,
	--		DATENAME(YEAR,CurrentDate) AS YearNumber,
	--		DATENAME(MONTH,CurrentDate) AS MonthTitle,
	--		@rBatchId AS BatchId
	--FROM 
	--	tMonth_Year 
    
    RETURN  
    
END
GO
PRINT N'Altering [sFee].[vUserChrageReceiptBook]...';


GO












/******************************************************************************  
 Purpose          : To get Batch Wise  Class
 Created date     : 21 Nov 2013
 Author           : Kundan Patel 
 Copyright©       : Copyright © Sapphire Software Solutions
 ******************************************************************************/  
ALTER VIEW [sFee].[vUserChrageReceiptBook]  
  
AS  
  
  SELECT 	
	  CRBM.Id as Id,
	  CRBM.Title,
	  CRBM.OrgGroupId,
	  CRBM.IsObsolete,
	  UA.UserId,
	  CRBM.OrderIndex
	  	   
  FROM 
  
	sFee.tChargeReceiptBookMaster CRBM
	INNER JOIN sSecurity.tUserAccess UA ON UA.SourceId=CRBM.Id AND UA.SourceTypeId=2018
  
--SELECT 	
--	  DISTINCT(RBM.Id) as Id,
--	  RBM.Title,
--	  RBM.OrgGroupId,
--	  RBM.IsObsolete,
--	  UA.UserId,
--	  RBM.OrderIndex
	  	   
--  FROM 
  
--	sFee.tReceiptBookMaster RBM
--	INNER JOIN sSecurity.tUserAccess UA ON UA.SourceId=RBM.Id AND UA.SourceTypeId=2013
--	INNER JOIN sFee.tChargeCategoryMaster CCM ON CCM.ReceiptBookId=RBM.Id
GO
PRINT N'Creating [sPayroll].[vUserPayroll]...';


GO




/******************************************************************************  
 Purpose          : To get Batch Wise  Class
 Created date     : 21 Nov 2013
 Author           : Kundan Patel 
 Copyright©       : Copyright © Sapphire Software Solutions
 ******************************************************************************/  
 
CREATE VIEW [sPayroll].[vUserPayroll]  
  
AS  
  
SELECT 	
	  PM.Id as Id,
	  PM.Title,
	  PM.OrgGroupId,
	  PM.IsActive AS IsObsolete,
	  UA.UserId
  FROM 
	sPayroll.tPayrollMaster PM
	INNER JOIN sSecurity.tUserAccess UA ON UA.SourceId=PM.Id AND UA.SourceTypeId=2019
GO

 


 

ALTER VIEW [sPayroll].[vExtPfSetup]

AS
	 SELECT Id,
			PfSalaryLimit,
			FpsSalaryLimit,
			EmployeePfPercent,
			EmployerPfPercent,
			EmployerFpsPercent,
			AdminChargesPercent,
			EdliPercent,
			InspectionChargesPercent,
			MaximumAgeForFps,
			RoundingTypeId,
			RoundingPrecision,
			MaximumVpfPercent,
			MaximumVpfAmount
			--,
			--EffectiveDate,
			--UpdatedUserId
	   FROM sPayroll.tPfSetup


GO

 


 

ALTER VIEW [sPayroll].[vExtEsiSetup]

AS
	 SELECT ID,
			EmployeeEsiPercent,
			EmployerEsiPercent,
			EsiSalaryLimit,
			RoundingTypeId,
			RoundingPrecision,
			EffectiveDate,
			CreatedUserId
	   FROM sPayroll.tEsiSetup


GO

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


GO
EXECUTE sp_refreshview N'sAssessment.vExamClassDivision';


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


GO
EXECUTE sp_refreshview N'sAssessment.vExamClass';


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


GO
EXECUTE sp_refreshview N'sOmr.vOMRSubject';


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


GO
EXECUTE sp_refreshview N'sAssessment.vGeneralExamCustomSearch';


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


GO
EXECUTE sp_refreshview N'sAssessment.vGeneralExamColumnName';


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


GO
EXECUTE sp_refreshview N'sAssessment.vExamMaster';


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


GO
EXECUTE sp_refreshview N'sAssessment.vExamSubGroupMaster';


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


GO
EXECUTE sp_refreshview N'sHrm.vExtEmployeeMaster';


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


GO
EXECUTE sp_refreshview N'sCommon.vExtEmployeeWithAllUser';


GO
PRINT N'Refreshing [sSecurity].[vExtUser]...';


GO
EXECUTE sp_refreshview N'sSecurity.vExtUser';


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


GO
EXECUTE sp_refreshview N'sCommon.vEmployeeMaster';


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


GO
EXECUTE sp_refreshview N'sHrm.vEmployeeCustomSearch';


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


GO
EXECUTE sp_refreshview N'sHrm.vEmployeeColumnName';


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


GO
EXECUTE sp_refreshview N'sPayroll.vExtEsiSetup';


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


GO
EXECUTE sp_refreshview N'sPayroll.vExtPfSetup';


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


GO
EXECUTE sp_refreshview N'sStudent.vStudentCustomSearch';


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


GO
EXECUTE sp_refreshview N'sStudent.vQualification';


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


GO
EXECUTE sp_refreshview N'sStudent.vOccupation';


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


GO
EXECUTE sp_refreshview N'sStudent.vStudentColumnName';


GO

/*
Deployment script for NetVidyalayaVersionBlank
*/

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


GO
DROP PROCEDURE [sSetup].[pPortalAcademicMasterAdd];


GO
PRINT N'Dropping [sSetup].[pPortalAcademicMasterGet]...';


GO
DROP PROCEDURE [sSetup].[pPortalAcademicMasterGet];


GO
PRINT N'Dropping [sSetup].[pPortalAcademicMasterUpdate]...';


GO
DROP PROCEDURE [sSetup].[pPortalAcademicMasterUpdate];


GO
PRINT N'Dropping [sSetup].[pPortalAcademicMasterUpdateGet]...';


GO
DROP PROCEDURE [sSetup].[pPortalAcademicMasterUpdateGet];


GO
PRINT N'Dropping [sSetup].[pPortalBatchMasterAdd]...';


GO
DROP PROCEDURE [sSetup].[pPortalBatchMasterAdd];


GO
PRINT N'Dropping [sSetup].[pPortalClassMasterAdd]...';


GO
DROP PROCEDURE [sSetup].[pPortalClassMasterAdd];


GO
PRINT N'Dropping [sSetup].[pPortalDepartmentMasterAdd]...';


GO
DROP PROCEDURE [sSetup].[pPortalDepartmentMasterAdd];


GO
PRINT N'Dropping [sSetup].[pPortalDivisionMasterAdd]...';


GO
DROP PROCEDURE [sSetup].[pPortalDivisionMasterAdd];


GO
PRINT N'Dropping [sSetup].[pPortalStudentCommunicationAdd]...';


GO
DROP PROCEDURE [sSetup].[pPortalStudentCommunicationAdd];


GO
PRINT N'Dropping [sSetup].[pPortalStudentCommunicationUpdateGet]...';


GO
DROP PROCEDURE [sSetup].[pPortalStudentCommunicationUpdateGet];


GO
PRINT N'Dropping [sSetup].[pPortalStudentImagesAdd]...';


GO
DROP PROCEDURE [sSetup].[pPortalStudentImagesAdd];


GO
PRINT N'Dropping [sSetup].[pPortalStudentImagesUpdatEGet]...';


GO
DROP PROCEDURE [sSetup].[pPortalStudentImagesUpdatEGet];


GO
PRINT N'Dropping [sSetup].[pPortalStudentMasterAdd]...';


GO
DROP PROCEDURE [sSetup].[pPortalStudentMasterAdd];


GO
PRINT N'Dropping [sSetup].[pPortalStudentMasterUpdateGet]...';


GO
DROP PROCEDURE [sSetup].[pPortalStudentMasterUpdateGet];


GO
PRINT N'Dropping [sSetup].[pPortalStudentOtherAdd]...';


GO
DROP PROCEDURE [sSetup].[pPortalStudentOtherAdd];


GO
PRINT N'Dropping [sSetup].[pPortalStudentOtherUpdateGet]...';


GO
DROP PROCEDURE [sSetup].[pPortalStudentOtherUpdateGet];


GO
PRINT N'Dropping [sSetup].[pPortalSubjectMasterAdd]...';


GO
DROP PROCEDURE [sSetup].[pPortalSubjectMasterAdd];


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


GO
ALTER PROCEDURE [sAcademic].[pClassworkGet]

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

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


GO
ALTER PROCEDURE [sAcademic].[pLessonPlanGet]

	 @rId int,
	 @rClassId int,
	 @rSubjectId int,
	 @rDivisionId int,
	 @rIsCompleted bit,
	 @rOrgId smallint
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	
	SELECT 
			LP.Id,
			TM.ClassId,
			LP.DivisionId,
			TM.SubjectId,
			LP.TopicId,
			LP.NoOfPeriodRequired,
			LP.Objective,
			LP.IndicativeHomework,
			LP.Summary,
			LP.StartDate,
			LP.EndDate,
			LP.IsCompleted,
			LP.EmployeeId,
			LP.BatchId,
			LP.CreatedUserId,
			LP.CreatedDateTime,
			TM.Title AS TopicName,
			CM.Title+' - '+ DM.Title AS ClassDivisionName,
			SM.Title AS SubjectName
	FROM 
			sAcademic.tLessonPlan LP
			INNER JOIN sAcademic.tTopicMaster TM ON TM.Id=LP.TopicId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=LP.DivisionId
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=TM.ClassId
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=TM.SubjectId
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId
	WHERE 
		((LP.Id = @rId) OR (@rId = 0))
		AND ((TM.ClassId = @rClassId) OR (@rClassId = 0))
		AND ((DM.Id = @rDivisionId) OR (@rDivisionId = 0))
		AND ((CM.OrgId = @rOrgId) OR (@rOrgId = 0))
		AND ((SM.Id = @rSubjectId) OR (@rSubjectId = 0))
		AND ((LP.IsCompleted='False') OR (LP.IsCompleted=@rIsCompleted))
		
END
GO
PRINT N'Altering [sActivity].[pAssignClubGet]...';


GO

ALTER PROCEDURE [sActivity].[pAssignClubGet]

			@rAcademicId bigint,
           @rCode nvarchar(20),
           @rClassId int,
           @rDivisionId int,
           @rClubId int,
           @rOrgId int,
           @rBatchId int,
           @rIsSearch bit
          
AS
SET NOCOUNT ON

BEGIN
If(@rIsSearch =1)
BEGIN
	SET @rCode = sCommon.fSearchStringGet(@rCode)
	SELECT  
		SA.AcademicId,
		SA.Code,
		SA.Name,
		SA.RollNo,
		SA.ClassId,
		SA.DivisionId,
		SA.ClassName+'-'+SA.DivisionName AS ClassName,
		ISNULL(CM.Id,0) AS ClubId,
		ISNULL(CM.Title,'') AS Club,
		CASE WHEN AC.ClubId IS NULL THEN 'false' ELSE 'true' END AS IsObsolete
		
  FROM sStudent.vStudentAcademic SA
	INNER JOIN sActivity.tAssignClub AC ON AC.AcademicId=SA.AcademicId 
	LEFT JOIN sActivity.tClubMaster CM ON CM.Id=AC.ClubId
	
  WHERE 
		((SA.Code like @rCode) OR (ISNULL(@rCode,'') = ''))
	AND	(SA.ClassId=@rClassId OR @rClassId=0)
	AND (SA.DivisionId=@rDivisionId OR @rDivisionId=0)
	AND (AC.ClubId=@rClubId OR @rClubId=0)
	AND (SA.OrgId = @rOrgId)
	AND (SA.BatchId=@rBatchId)
	AND (SA.AcademicId=@rAcademicId OR @rAcademicId=0)
	Order by SA.RollNo 
END
ELSE
BEGIN
SELECT  
		SA.AcademicId,
		SA.Code,
		SA.Name,
		SA.RollNo,
		Sa.ClassId,
		SA.DivisionId,
		SA.ClassName+'-'+SA.DivisionName AS ClassName,
		ISNULL(CM.Title,'') AS Club,
		ISNULL(CM.Id,0) AS ClubId,
		CASE WHEN AC.ClubId IS NULL THEN 'false' ELSE 'true' END AS IsObsolete
		
  FROM sStudent.vStudentAcademic SA
	LEFT JOIN sActivity.tAssignClub AC ON AC.AcademicId=SA.AcademicId AND (AC.ClubId=@rClubId OR @rClubId=0)
	LEFT JOIN sActivity.tClubMaster CM ON CM.Id=AC.ClubId
	
  WHERE 
		(SA.ClassId=@rClassId OR @rClassId=0)
	AND (SA.DivisionId=@rDivisionId OR @rDivisionId=0)
	AND (SA.OrgId = @rOrgId)
	AND (SA.BatchId=@rBatchId)
	Order by SA.RollNo
END
END
GO
PRINT N'Altering [sActivity].[pAssignHouseGet]...';


GO

ALTER PROCEDURE [sActivity].[pAssignHouseGet]
          
           @rClassId int,
           @rDivisionId int,
           @rHouseId int,
           @rOrgId int,
           @rBatchId int
          
AS
SET NOCOUNT ON

BEGIN
SELECT  
		SO.StudentId,
		SO.Code,
		SO.Name,
		SO.ClassName+'-'+SO.DivisionName AS ClassName,
		ISNULL(SO.HouseId,0) HouseId
		
  FROM sStudent.vStudentOther SO
	
  WHERE 
		(SO.ClassId=@rClassId OR @rClassId=0)
	AND (SO.DivisionId=@rDivisionId OR @rDivisionId=0)
	AND (SO.HouseId=@rHouseId OR @rHouseId=0)
	AND (SO.OrgId = @rOrgId)
	AND (SO.BatchId=@rBatchId)
	order by SO.ClassId,SO.DivisionId
END
GO
PRINT N'Altering [sAdmission].[pAdmissionInquiryAdd]...';


GO
ALTER PROCEDURE [sAdmission].[pAdmissionInquiryAdd]
		 @rId bigint
		,@rFirstName nvarchar(100)
		,@rMiddleName nvarchar(100)
		,@rLastName nvarchar(100)
		,@rForClassId int
		,@rForBatchId	int =0
		--,@rForBatch	nvarchar(20)
		,@rDateOfBirth date
		,@rOrgId smallint
		,@rStatusId	smallint
		,@rStreetOne nvarchar(50)
		,@rStreetTwo nvarchar(50)
		,@rStreetThree nvarchar(50)
		,@rCountry nvarchar(50)
		,@rState nvarchar(50)
		,@rCity	nvarchar(50)
		,@rZipCode nvarchar(20)
		,@rContactNo nvarchar(20)
		,@rContactEmail	nvarchar(50)
		,@rRemark nvarchar(200)
		,@rInquiryModeId tinyint
		,@rInquiryReferenceId int
		,@rAdmissionCategoryId int
		,@rPreviousSchool nvarchar(200)
		,@rMeritMarks decimal(10,2)
		,@rMeritGrade nvarchar(20)
		,@rMeritMarksBreakup nvarchar(100)
		,@rGenderId tinyint
		,@rFollowupDate date
		,@rFollowupRemark nvarchar(150)
		,@rCreatedUserId bigint
		,@rInquiryDate date
		,@rNumber bigint
		,@rHandledBy nvarchar
		,@rOrgGroupId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
IF(@rId = 0)	
BEGIN
	If Exists(select Id from sAdmission.tAdmissionInquiry where FirstName=@rFirstName AND MiddleName=@rMiddleName AND
	LastName=@rLastName AND ISNULL(DateOfBirth,'')=ISNULL(@rDateOfBirth,'') AND OrgId=@rOrgId)
	BEGIN
		select -103 as Result
		RETURN
	END 
END
ELSE
BEGIN
	If  Exists(select Id from sAdmission.tAdmissionInquiry where FirstName=@rFirstName AND MiddleName=@rMiddleName AND
	LastName=@rLastName AND ISNULL(DateOfBirth,'')=ISNULL(@rDateOfBirth,'') AND OrgId=@rOrgId AND Id<>@rId)
	BEGIN
		select -103 as Result
		RETURN
	END
END
IF(@rId = 0)	
	BEGIN	
 BEGIN TRANSACTION	
 DECLARE @lNextNumber BIGINT 
 EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAdmission.tAdmissionInquiry', 0, 1, 1,@outNextNumber = @lNextNumber output
			
	INSERT INTO sAdmission.tAdmissionInquiry
		(
			 Id
			,FirstName
			,MiddleName
			,LastName
			,ForClassId			 
			,ForBatchId
			,DateOfBirth
			,OrgId
			,StatusId
			,StreetOne
			,StreetTwo
			,StreetThree
			,Country
			,State
			,City
			,ZipCode
			,ContactNo
			,ContactEmail
			,Remark
			,InquiryModeId
			,InquiryReferenceId
			,AdmissionCategoryId
			,PreviousSchool
			,MeritMarks
			,MeritGrade
			,MeritMarksBreakup
			,GenderId
			,FollowupDate
			,FollowupRemark
			,CreatedUserId
			,CreatedDateTime
			,InquiryDate
			,Number
			,HandledBy
			,OrgGroupId
		)
	VALUES
		(
			 @lNextNumber
			,@rFirstName
			,@rMiddleName
			,@rLastName
			,@rForClassId
			,@rForBatchId			 
			,@rDateOfBirth
			,@rOrgId
			,@rStatusId
			,@rStreetOne
			,@rStreetTwo
			,@rStreetThree
			,@rCountry
			,@rState
			,@rCity
			,@rZipCode
			,@rContactNo
			,@rContactEmail
			,@rRemark
			,@rInquiryModeId
			,@rInquiryReferenceId
			,@rAdmissionCategoryId
			,@rPreviousSchool
			,@rMeritMarks
			,@rMeritGrade
			,@rMeritMarksBreakup
			,@rGenderId
			,@rFollowupDate
			,@rFollowupRemark
			,@rCreatedUserId
			,sCommon.fGetDate()
			,@rInquiryDate
			,@rNumber
			,@rHandledBy
			,@rOrgGroupId
		)
		    SELECT 11 AS Result         
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sAdmission.tAdmissionInquiry
	    SET
			 FirstName=@rFirstName
			,MiddleName=@rMiddleName
			,LastName=@rLastName
			,ForClassId=@rForClassId
			,ForBatchId = @rForBatchId		 
			,DateOfBirth=@rDateOfBirth
			,OrgId=@rOrgId
			,StatusId=@rStatusId
			,StreetOne=@rStreetOne
			,StreetTwo=@rStreetTwo
			,StreetThree=@rStreetThree
			,Country=@rCountry
			,State=@rState
			,City=@rCity
			,ZipCode=@rZipCode
			,ContactNo=@rContactNo
			,ContactEmail=@rContactEmail
			,Remark=@rRemark
			,InquiryModeId=@rInquiryModeId
			,InquiryReferenceId=@rInquiryReferenceId 
			,AdmissionCategoryId=@rAdmissionCategoryId
			,PreviousSchool=@rPreviousSchool
			,MeritMarks=@rMeritMarks
			,MeritGrade=@rMeritGrade
			,MeritMarksBreakup=@rMeritMarksBreakup
			,GenderId=@rGenderId
			,FollowupDate=@rFollowupDate
			,FollowupRemark=@rFollowupRemark
			,UpdatedUserId=@rCreatedUserId
			,UpdatedDateTime=sCommon.fGetDate()
			,InquiryDate=@rInquiryDate
			,HandledBy=@rHandledBy
			
	      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].[pAdmissionInquiryGet]...';


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

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


GO



ALTER PROCEDURE [sAdmission].[pRptStudentNewAdmissionListGet]
	
	 @rBatchId int,
	 @rClassId int,
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='',
	 @rFromDate date,
	 @rToDate date,
	 @rOrgId int,
	 @rDepartmentId int,
	 @rDivisionId int
AS
 SET NOCOUNT ON
			 

BEGIN 
	
	select 
	@rBuilder1 AS Builder1,
	@rBuilder2 AS Builder2,
	SM.FirstName+' '+SM.MiddleName+' '+SM.LastName AS Name,
	SA.AdmissionDate,
	SM.Code,
	A.RollNo,
	CM.Title As Class

	
	
	     
  FROM 
				sStudent.tAcademic A INNER JOIN sStudent.tStudentMaster SM ON A.StudentId=SM.Id
				INNER JOIN sStudent.tStudentAdmission SA ON SA.StudentId=SM.Id
				INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId  				 
				INNER JOIN sSetup.tClassMaster CM ON CM.Id=DM.ClassId
				
 WHERE 	
		A.BatchId=@rBatchId
		AND ((ISNULL(SA.AdmissionDate,'') >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((ISNULL(SA.AdmissionDate,'') <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		AND ((CM.DepartmentId=@rDepartmentId) OR (@rDepartmentId = 0))
		AND ((CM.Id=@rClassId) OR (@rClassId = 0))
		AND ((DM.Id=@rDivisionId) OR (@rDivisionId = 0))
END
GO
PRINT N'Altering [sAssessment].[pExamFullGet]...';


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

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


GO

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

	END
	
	
	
	 	
	 DECLARE @lNextNumber BIGINT 

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

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

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


GO


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

BEGIN 

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


 
DECLARE @GradeString nvarchar(1000),
@GradeSetId int , @IsIncludeSubExam bit
SELECT @GradeSetId = GradesetId,
	   @IsIncludeSubExam = ISNULL(IsIncludeSubExam,0)  FROM sAssessment.tExamMaster WHERE Id = @rExamId
SELECT @GradeString = [sAssessment].[fGradeStringGet](@GradeSetId)
 
--#TempAllExam
	CREATE TABLE #TempAllExam
	(
		AcademicIdText nvarchar(20),
		ExamIdText nvarchar(20),
		AcademicId bigint,
		ExamName Nvarchar(150),
		StudCode NVarchar(20),
		StudentName Nvarchar(150),
		RollNo int,
		ResultStatus Nvarchar(20),
		ClassName NVarchar(50),		
		Division NVarchar(50),
		TotalMark decimal(8,2),
		TotalObtain decimal(8,2),
		Percentage decimal(8,2),
		RankNumber int,
		ResultGrade NVarchar(50),
		
		MaximumMark1 decimal(8,2),		
		SubjectGrade1 NVarchar(50),
		Obtain1 decimal(8,2),
		ExamMaximum1 decimal(8,2),				
		MaximumMark2 decimal(8,2),
	
		SubjectGrade2 NVarchar(50),
		Obtain2 decimal(8,2),
		ExamMaximum2 decimal(8,2),		
		MaximumMark3 decimal(8,2),

		SubjectGrade3 NVarchar(50),
		Obtain3 decimal(8,2),
		ExamMaximum3 decimal(8,2),		
		MaximumMark4 decimal(8,2),
	
		SubjectGrade4 NVarchar(50),
		Obtain4 decimal(8,2),
		ExamMaximum4 decimal(8,2),		
		MaximumMark5 decimal(8,2),
		
		SubjectGrade5 NVarchar(50),
		Obtain5 decimal(8,2),
		ExamMaximum5 decimal(8,2),		
		MaximumMark6 decimal(8,2),
		
		SubjectGrade6 NVarchar(50),
		Obtain6 decimal(8,2),
		ExamMaximum6 decimal(8,2),
		MaximumMark7 decimal(8,2),
		
		SubjectGrade7 NVarchar(50),
		Obtain7 decimal(8,2),
		ExamMaximum7 decimal(8,2),
		MaximumMark8 decimal(8,2),
		
	
		SubjectGrade8 NVarchar(50),
		Obtain8 decimal(8,2),
		ExamMaximum8 decimal(8,2),
		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),
		SubjectGroupTypeId smallint
	)	
	 --print 'temp created'    	
	INSERT INTO  #TempAllExam 
	(
	AcademicIdText,
	ExamIdText,
	AcademicId,
	ExamName,
	StudCode,
	StudentName,
	RollNo,
	ResultStatus,
	ClassName,
	Division,
	TotalMark,
	TotalObtain,
	Percentage,
	RankNumber,
	ResultGrade,
	IsMarksInDecimal,
	column_visible,
	--Obtain,
	Percentile,
	--ClassSubject,
	ResultDetailId,
	ResultId,

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


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

		ISNULL(EM.Remark1,'') AS Remark1,
		ISNULL(EM.Remark2,'') AS Remark2,
		ISNULL(EM.Remark3,'') AS Remark3,
		EM.DisplayTitle,
		EM.IsRankNo, 
		EM.IsGrade,
		EM.IsPercentile,
		EM.IsPercentage,
		EM.IsSubjectPercentile,
		EM.IsProcessResult,
		EM.IsNegativeMarks,
		EM.IsIncludeCoScholastic,
		EM.IsOnPrePrinted,
		EM.IsDisplayPhoto,
		EM.IsDisplayBirthDate,
		EM.IsLockForEdit,
		EM.IsDisplaySchoolName,			
		EM.IsDisplayAttendance,
		EM.IsDisplayHeightWeight,
		EM.IsResultStatus,
		REPLICATE(',',EM.FooterAdjustment) AS FooterAdjustmentText,
		REPLICATE(',',EM.DetailAdjustment) AS DetailAdjustmentText,
		EM.FooterAdjustment,
		EM.DetailAdjustment,
		ISNULL(R.ResultRemark,'') AS ResultRemark,
		SO.DateOfBirth,
		AD.HeightTerm1,
		AD.WeightTerm1,
		AD.HeightTerm2,
		AD.WeightTerm2,
		AD.HeightAnnual,
		AD.WeightAnnual,
		AD.PresentDaysTerm1,
		AD.PresentDaysTerm2,
		AD.PresentDaysAnnual,
		AD.TotalDaysTerm1,
		AD.TotalDaysTerm2,
		AD.TotalDaysAnnual,
		EM.TermScopeId,
		SI.StudentPhoto,
		@GradeString AS GradeString,
		EM.IsDisplayGradeString,
		ED.IsDisplayInMarksheet,
		ED.IsShowSubjectGrade,
		ED.IsIncludeInTotal,
		ED.ClassSubjectId,
		CS.Id 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,		
		CASE  WHEN CS.IsOptional = 1 AND CS.IsPractical = 0  THEN 2
		WHEN  CS.IsPractical = 1  THEN 3             
        ELSE 1 END as SubjectGroupTypeId  	
FROM 
	sAssessment.tResultDetail RD
	INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
	INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId			
	INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
	INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId					 
	INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
	INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
	INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
	INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
	INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.EXAMSUBGROUPID
	LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
	LEFT JOIN sStudent.tAcademicDetail AD ON AD.AcademicId=A.Id
	LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=StuM.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=''))		
		 
	 
	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
 	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,					
					 SubjectGrade' + convert(nvarchar(15),@lCount)+ '=RD.SubjectGrade										
					 From
						sAssessment.tResultDetail RD
						INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
						
	
	 execute(@query)
	
						
			set @query ='update T set 
				    TotalMarks' + convert(nvarchar(15),@lCount)+ '=R.TotalMarks,
					TotalObtain' + convert(nvarchar(15),@lCount)+ '=R.TotalObtain,
					Percentage' + convert(nvarchar(15),@lCount)+ '=R.Percentage,
					RankNumber' + convert(nvarchar(15),@lCount)+'=R.RankNumber,
					ResultGrade' + convert(nvarchar(15),@lCount)+'=R.ResultGrade,
					Percentile' + convert(nvarchar(15),@lCount)+'=R.Percentile,
					ResultStatus' + convert(nvarchar(15),@lCount)+'=R.ResultStatus,
					Exam' + convert(nvarchar(15),@lCount)+ 'Name=ESGM.Title,
					ExamMaximum' + convert(nvarchar(15),@lCount)+'=EM.ExamMaximum
					 From						
						sAssessment.tResult R						
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON  T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
						
		execute(@query)
		
		
	set @lCount = @lCount -1
	end
	

	IF (@IsIncludeSubExam = 1)
	BEGIN	
		select @lSubExamId = SubExamId from sAssessment.tExamCombine  Where ExamId  = @rExamId AND ExamOrder = 1
		--select @ExamTitle = Title from sAssessment.tExamMaster Where Id = @lSubExamId	
		set @query ='update T set					 
					SubjectGradeTerm1=RD.SubjectGrade
					,
					TotalMarkTerm1 = R.TotalMarks,
					TotalObtainTerm1=R.TotalObtain,
					PercentageTerm1=R.Percentage,
					RankNumberTerm1=R.RankNumber,
					ResultGradeTerm1=R.ResultGrade,
					PercentileTerm1 = R.Percentile,
					ResultStatusTerm1 = R.ResultStatus				 
					 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)
		
					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
					,
					TotalMarkTerm2 = R.TotalMarks,
					TotalObtainTerm2=R.TotalObtain,
					PercentageTerm2=R.Percentage,
					RankNumberTerm2=R.RankNumber,
					ResultGradeTerm2=R.ResultGrade,
					PercentileTerm2 = R.Percentile,
					ResultStatusTerm2 = R.ResultStatus		
					 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)
	
	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, * FROM #TempAllExam T
	--INNER JOIN SSETUP.TCLASSSUBJECT CS ON CS.ID = T.CLASSSUBJECTID
	--WHERE
	--	((T.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
	--	AND ((T.RollNo <= @rToRollNo) OR (@rToRollNo=0))
	--	AND ((T.RankNumber >= @rFromRank) OR (@rFromRank=0))
	--	AND ((T.RankNumber <= @rToRank) OR (@rToRank=0))
	--	AND ((T.ResultGrade = @rGrade) OR (@rGrade=''))
	--	AND ((T.StudCode=@rCode) OR (@rCode=''))		
		--order by T.RollNo,CS.ORDERINDEX
		
	drop table #tempcombineExam
	Drop table #TempAllExam
END
GO
PRINT N'Altering [sAssessment].[pRptResultSheetStandardGet]...';


GO


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

BEGIN 

DECLARE @GradeString nvarchar(1000),
@GradeSetId int
 
SELECT @GradeSetId = GradesetId FROM sAssessment.tExamMaster WHERE Id = @rExamId
SELECT @GradeString = [sAssessment].[fGradeStringGet](@GradeSetId)  
	SELECT 
			Convert(nvarchar(20),A.Id) AS AcademicIdText,
			Convert(nvarchar(20),@rExamId) AS ExamIdText,
			ESGM.Title AS Exam,
			StuM.Code,
			StuM.FirstName+' '+StuM.MiddleName+' '+StuM.LastName AS Name,
			A.RollNo,
			R.AcademicId,			
			R.ResultStatus,
			CM.DisplayTitle AS Class,
			DM.DisplayTitle AS Division,
			R.TotalMarks,
			R.TotalObtain,
			R.Percentage,
			R.RankNumber,
			R.ResultGrade,
			R.Percentile,			
			RD.Id AS ResultDetailId,		
			ED.IsDisplayInMarksheet,
			ED.IsShowSubjectGrade,
			ED.IsIncludeInTotal,
			RD.Obtain AS SubjectObtain,
			ED.Minimum AS SubjectMinimum,
			ED.Maximum AS SubjectMaximum,
			RD.SubjectGrade,
			SM.Code AS SubjectCode,
			SM.Title AS SubjectName,
			(CASE ISNULL(ED.DisplayOrder,0)
			WHEN 0 THEN CS.OrderIndex
			ELSE ED.DisplayOrder END) AS SubjectOrderIndex,
			R.Id AS ResultId,
			CS.Id AS SubjectId,			 	
			EM.IsMarksInDecimal,
			--SM.OrderIndex AS SubjectCode,
	   
			--CS.OrderIndex AS SubjectOrderIndex,
			ISNULL(EM.Remark1,'') AS Remark1,
			ISNULL(EM.Remark2,'') AS Remark2,
			ISNULL(EM.Remark3,'') AS Remark3,
			EM.DisplayTitle,
			EM.IsRankNo, 
			EM.IsGrade,
			EM.IsPercentile,
			EM.IsPercentage,
			EM.IsSubjectPercentile,
			EM.IsProcessResult,
			EM.IsMarksInDecimal,
			EM.IsNegativeMarks,
			EM.IsIncludeCoScholastic,
			EM.IsOnPrePrinted,
			EM.IsDisplayPhoto,
			EM.IsDisplayBirthDate,
			EM.IsLockForEdit,
			EM.IsDisplaySchoolName,			
			EM.IsDisplayAttendance,
			EM.IsDisplayHeightWeight,
			EM.IsResultStatus,
			REPLICATE(',',EM.FooterAdjustment) AS FooterAdjustmentText,
			REPLICATE(',',EM.DetailAdjustment) AS DetailAdjustmentText,
			EM.FooterAdjustment,
			EM.DetailAdjustment,
			ISNULL(R.ResultRemark,'') AS ResultRemark,
			SO.DateOfBirth,
			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,
			(CASE EM.IsDisplayHighestDivisionMark
			WHEN 1 THEN [sAssessment].[fGetHighestDivisionMark](A.DivisionId ,RD.ExamDetailId)
			ELSE 0 END) AS HighestDivisionMark,
			(CASE EM.IsDisplayHighestDivisionGrade
			WHEN 1 THEN [sAssessment].[fGetHighestDivisionGrade] (A.DivisionId ,RD.ExamDetailId)
			ELSE '' END) AS HighestDivisionGrade
			
			--[sAssessment].[fGetHighestDivisionMark](A.DivisionId ,RD.ExamDetailId) AS HighestDivisionMark,
			--[sAssessment].[fGetHighestDivisionGrade] (A.DivisionId ,RD.ExamDetailId) AS HighestDivisionGrade
			
			
			
	FROM 
			sAssessment.tResultDetail RD
			INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
			INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
			INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId			
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId					 
			INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
			LEFT JOIN sStudent.tAcademicDetail AD ON AD.AcademicId=A.Id
			INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
			LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
			LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=StuM.Id
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.EXAMSUBGROUPID
	WHERE 
			
		(EM.BatchId = @rBatchId) OR  (@rBatchId = 0)
		AND (A.ClassId=@rClassId OR @rClassId=0) 
		AND ((SM.Id=@rSubjectId) OR (@rSubjectId=0))
		AND (A.DivisionId=@rDivisionId OR @rDivisionId=0)
		AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((R.RankNumber >= @rFromRank) OR (@rFromRank=0))
		AND ((R.RankNumber <= @rToRank) OR (@rToRank=0))
		AND ((R.ResultGrade = @rGrade) OR (@rGrade=''))
		AND (R.ExamId = @rExamId)
		AND ((StuM.Code=@rCode) OR (@rCode=''))
		AND (R.Id = @rResultId) OR (@rResultId = 0)
		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
	 --,@rcolumn_visible bit
	 
	
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

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


 
DECLARE @GradeString nvarchar(1000),
@GradeSetId int , @IsIncludeSubExam bit
SELECT @GradeSetId = GradesetId,
	   @IsIncludeSubExam = ISNULL(IsIncludeSubExam,0)  FROM sAssessment.tExamMaster WHERE Id = @rExamId
SELECT @GradeString = [sAssessment].[fGradeStringGet](@GradeSetId)
 
--#TempAllExam
	CREATE TABLE #TempAllExam
	(
		AcademicIdText nvarchar(20),
		ExamIdText nvarchar(20),
		AcademicId bigint,
		ExamName Nvarchar(150),
		StudCode NVarchar(20),
		StudentName Nvarchar(150),
		RollNo int,
		ResultStatus Nvarchar(20),
		ClassName NVarchar(50),		
		Division NVarchar(50),
		TotalMark decimal(8,2),
		TotalObtain decimal(8,2),
		Percentage decimal(8,2),
		RankNumber int,
		ResultGrade NVarchar(50),
		
		MaximumMark1 decimal(8,2),		
		SubjectGrade1 NVarchar(50),
		Obtain1 decimal(8,2),
		ExamMaximum1 decimal(8,2),				
		MaximumMark2 decimal(8,2),
	
		SubjectGrade2 NVarchar(50),
		Obtain2 decimal(8,2),
		ExamMaximum2 decimal(8,2),		
		MaximumMark3 decimal(8,2),

		SubjectGrade3 NVarchar(50),
		Obtain3 decimal(8,2),
		ExamMaximum3 decimal(8,2),		
		MaximumMark4 decimal(8,2),
	
		SubjectGrade4 NVarchar(50),
		Obtain4 decimal(8,2),
		ExamMaximum4 decimal(8,2),		
		MaximumMark5 decimal(8,2),
		
		SubjectGrade5 NVarchar(50),
		Obtain5 decimal(8,2),
		ExamMaximum5 decimal(8,2),		
		MaximumMark6 decimal(8,2),
		
		SubjectGrade6 NVarchar(50),
		Obtain6 decimal(8,2),
		ExamMaximum6 decimal(8,2),
		MaximumMark7 decimal(8,2),
		
		SubjectGrade7 NVarchar(50),
		Obtain7 decimal(8,2),
		ExamMaximum7 decimal(8,2),
		MaximumMark8 decimal(8,2),
		
	
		SubjectGrade8 NVarchar(50),
		Obtain8 decimal(8,2),
		ExamMaximum8 decimal(8,2),
		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)
	)	
	 --print 'temp created'    	
	INSERT INTO  #TempAllExam 
	(
	AcademicIdText,
	ExamIdText,
	AcademicId,
	ExamName,
	StudCode,
	StudentName,
	RollNo,
	ResultStatus,
	ClassName,
	Division,
	TotalMark,
	TotalObtain,
	Percentage,
	RankNumber,
	ResultGrade,
	IsMarksInDecimal,
	column_visible,
	--Obtain,
	Percentile,
	--ClassSubject,
	ResultDetailId,
	ResultId,

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


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

		ISNULL(EM.Remark1,'') AS Remark1,
		ISNULL(EM.Remark2,'') AS Remark2,
		ISNULL(EM.Remark3,'') AS Remark3,
		EM.DisplayTitle,
		EM.IsRankNo, 
		EM.IsGrade,
		EM.IsPercentile,
		EM.IsPercentage,
		EM.IsSubjectPercentile,
		EM.IsProcessResult,
		EM.IsNegativeMarks,
		EM.IsIncludeCoScholastic,
		EM.IsOnPrePrinted,
		EM.IsDisplayPhoto,
		EM.IsDisplayBirthDate,
		EM.IsLockForEdit,
		EM.IsDisplaySchoolName,			
		EM.IsDisplayAttendance,
		EM.IsDisplayHeightWeight,
		EM.IsResultStatus,
		REPLICATE(',',EM.FooterAdjustment) AS FooterAdjustmentText,
		REPLICATE(',',EM.DetailAdjustment) AS DetailAdjustmentText,
		EM.FooterAdjustment,
		EM.DetailAdjustment,
		ISNULL(R.ResultRemark,'') AS ResultRemark,
		SO.DateOfBirth,
		AD.HeightTerm1,
		AD.WeightTerm1,
		AD.HeightTerm2,
		AD.WeightTerm2,
		AD.HeightAnnual,
		AD.WeightAnnual,
		AD.PresentDaysTerm1,
		AD.PresentDaysTerm2,
		AD.PresentDaysAnnual,
		AD.TotalDaysTerm1,
		AD.TotalDaysTerm2,
		AD.TotalDaysAnnual,
		EM.TermScopeId,
		SI.StudentPhoto,
		@GradeString AS GradeString,
		EM.IsDisplayGradeString,
		ED.IsDisplayInMarksheet,
		ED.IsShowSubjectGrade,
		ED.IsIncludeInTotal,
		ED.ClassSubjectId,
		CS.Id 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	
FROM 
	sAssessment.tResultDetail RD
	INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
	INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId			
	INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
	INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId					 
	INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
	INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
	INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
	INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
	INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.EXAMSUBGROUPID
	LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
	LEFT JOIN sStudent.tAcademicDetail AD ON AD.AcademicId=A.Id
	LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=StuM.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)	
		 
	 
	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,					
					 SubjectGrade' + convert(nvarchar(15),@lCount)+ '=RD.SubjectGrade										
					 From
						sAssessment.tResultDetail RD
						INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
						
	
	 execute(@query)
	
						
			set @query ='update T set 
				    TotalMarks' + convert(nvarchar(15),@lCount)+ '=R.TotalMarks,
					TotalObtain' + convert(nvarchar(15),@lCount)+ '=R.TotalObtain,
					Percentage' + convert(nvarchar(15),@lCount)+ '=R.Percentage,
					RankNumber' + convert(nvarchar(15),@lCount)+'=R.RankNumber,
					ResultGrade' + convert(nvarchar(15),@lCount)+'=R.ResultGrade,
					Percentile' + convert(nvarchar(15),@lCount)+'=R.Percentile,
					ResultStatus' + convert(nvarchar(15),@lCount)+'=R.ResultStatus,
					Exam' + convert(nvarchar(15),@lCount)+ 'Name=ESGM.Title,
					ExamMaximum' + convert(nvarchar(15),@lCount)+'=EM.ExamMaximum
					 From						
						sAssessment.tResult R						
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON  T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
						
		execute(@query)
		
		
	set @lCount = @lCount -1
	end
	

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


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

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

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


 SELECT @lOrgGroupId=OrgGroupId from sSetup.tOrganizationMaster where Id=@rOrgId
 
 SELECT @lOrgGroupBatchId=ISNULL(MIN(Id),(Convert(nvarchar(10),Convert(nvarchar(10),@lOrgGroupId))+'00000')+1) 
	FROM sSetup.tOrgGroupBatchMaster WHERE OrgGroupId=@lOrgGroupId
 
 
 INSERT INTO [sCommon].[tTableRowId]
           ([OrgId]
           ,[TableTitle]
           ,[CurrentNumber]
           ,[Seed]
           ,[Increment])
SELECT
		   @rOrgId
		  ,[TableTitle]
		  
		  ,CASE 
      WHEN IdDataType = 'int' THEN sCommon.fGetIntIdForOrg(ISNULL(CurrentNumber,0),@rOrgId) 
      WHEN IdDataType = 'bigint' THEN sCommon.fGetbigIntIdForOrg(ISNULL(CurrentNumber,0),@rOrgId )
		END 
		
		  ,CASE 
      WHEN IdDataType = 'int' THEN sCommon.fGetIntIdForOrg(ISNULL(CurrentNumber,0),@rOrgId) 
      WHEN IdDataType = 'bigint' THEN sCommon.fGetbigIntIdForOrg(ISNULL(CurrentNumber,0),@rOrgId )
		END  
		   ,1
	  FROM [sCommon].[tTableRowIdMaster] where 
	  (tableType = 'Non Static' or tableType = '100Static' )
	  AND iddatatype <> '' AND IdScope <> 'OrgGroup'
	  

 
 INSERT INTO [sSetup].[tBatchMaster]
           ([Id]
           ,[Code]
           ,[Title]
           ,[OrgId]
           ,[IsHistory]
           ,[IsActive]
           ,[IsObsolete]
           ,[OrderIndex]
           ,[FromDate]
           ,[ToDate]
           ,[OrgGroupBatchId]
           ,[CreatedUserId]
           ,[CreatedDateTime]
           ,[UpdatedUserId]
           ,[UpdatedDateTime])
     
      SELECT sCommon.fGetIntIdForOrg(1,@rOrgId)
           ,Code
           ,Title
           ,@rOrgId
           ,0
           ,1
           ,0
           ,1
           ,FromDate
           ,ToDate
           ,@lOrgGroupBatchId
		  ,@lCreatedUserId
		  ,@lCreatedDateTime
		  ,@lCreatedUserId
		  ,@lCreatedDateTime
           FROM [sSetup].[tOrgGroupBatchMaster] WHERE  Id =  @lOrgGroupBatchId

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

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


INSERT INTO [sConfig].[tColorLegendDetail]
           ([OrgId]
           ,[Id]
           ,[Title]
           ,[ColorLegendId]
           ,[configSettingId])
	SELECT
		   @rOrgId
		  ,sCommon.fGetIntIdForOrg(Id,@rOrgId)
		  ,[Title]
		  ,[ColorLegendId]
		  ,[configSettingId]
	  FROM [sConfig].[tColorLegendDetail] WHERE OrgId=1
	  
	  
 







INSERT INTO [sHrm].[tEmployeeTypeMaster]
           ([OrgId]
           ,[Id]
           ,[Code]
           ,[Title]
           ,[IsObsolete]
           ,[CreatedUserId]
           ,[CreatedDateTime]
           ,[UpdatedUserId]
           ,[UpdatedDateTime])			
	 SELECT
			@rOrgId
		   ,sCommon.fGetIntIdForOrg(Id,@rOrgId)
		   ,[Code]
		   ,[Title]
           ,[IsObsolete]
		   ,@lCreatedUserId
		   ,@lCreatedDateTime
		   ,@lCreatedUserId
		   ,@lCreatedDateTime
     FROM [sHrm].[tEmployeeTypeMaster] WHERE OrgId=1
     

           
  -- INSERT INTO [sPayroll].[tPayElement]
  --         (
		--			[ID]
		--		   ,[Code]
		--		   ,[Title]
		--		   ,[PayElementTypeId]
		--		   ,[PaidCategoryId]
		--		   ,[IsLwp]
		--		   ,[IsEmployeeSpecific]
		--		   ,[IsDepend]
		--		   ,[IsAvailDuringProbation]
		--		   ,[IsIncludeInPaySlip]
		--		   ,[SortOrder]
		--		   ,[IsObsolete]
		--		   ,[OrgId]
		--		   ,[CreatedUserId]
		--		   ,[CreatedDateTime]
		--		   ,[UpdatedUserId]
		--		   ,[UpdatedDateTime]
  --         )     
  --         SELECT  sCommon.fGetIntIdForOrg(ID,@rOrgId)
		--		  ,[Code]
		--		  ,[Title]
		--		  ,[PayElementTypeId]
		--		  ,[PaidCategoryId]
		--		  ,[IsLwp]
		--		  ,[IsEmployeeSpecific]
		--		  ,[IsDepend]
		--		  ,[IsAvailDuringProbation]
		--		  ,[IsIncludeInPaySlip]
		--		  ,[SortOrder]
		--		  ,[IsObsolete]
		--		  ,@rOrgId
		--		  ,@lCreatedUserId
		--		  ,@lCreatedDateTime
		--		  ,@lCreatedUserId
		--		  ,@lCreatedDateTime
    
  --FROM  [sPayroll].[tPayElement] Where OrgId = 1 
  --AND Id < 101
           
  INSERT INTO [sSetup].[tDepartmentMaster]
           (
					[ID]
				   ,[Code]
				   ,[Title]
				   ,[DisplayTitle]
				   ,[OrgId]
				   ,[IsObsolete]
				   ,[CreatedUserId]
				   ,[CreatedDateTime]
				   ,[UpdatedUserId]
				   ,[UpdatedDateTime]
           )     
           SELECT  sCommon.fGetIntIdForOrg(1,@rOrgId)
				  ,'Common'
				  ,'Common'
				  ,'Common'
				  ,@rOrgId
				  ,0
				  ,@lCreatedUserId
				  ,@lCreatedDateTime
				  ,@lCreatedUserId
				  ,@lCreatedDateTime
    
  --FROM  [sSetup].[tDepartmentMaster] Where OrgId = 1 
  
  
   --INSERT INTO [sIp].[tStoreLocationMaster]
 --         ([OrgId]
 --          ,[Id]
 --          ,[Code]
 --          ,[Title]
 --          ,[IsObsolete]
 --          ,[CreatedUserId]
 --          ,[CreatedDateTime]
 --          ,[UpdatedUserId]
 --          ,[UpdatedDateTime]
 --          ,[LocationId]
 --          ,[IsShowDependent])
	--SELECT
	--   @rOrgId
 --     ,sCommon.fGetIntIdForOrg(Id,@rOrgId)
 --     ,[Code]
 --     ,[Title]
 --     ,[IsObsolete]
 --     ,@lCreatedUserId
	--  ,@lCreatedDateTime
	--  ,@lCreatedUserId
	--  ,@lCreatedDateTime
 --     ,sCommon.fGetIntIdForOrg(LocationId,@rOrgId)
 --     ,[IsShowDependent]
 -- FROM [sIp].[tStoreLocationMaster] WHERE OrgId =1
  
  
  
--  INSERT INTO  [sCommon].[tCountryMaster]
--           ([OrgId]
--           ,[Title]
--           ,[Nationality]
--           ,[IsObsolete]
--           ,[CreatedUserId]
--           ,[CreatedDateTime]
--           ,[UpdatedUserId]
--           ,[UpdatedDateTime]
--           ,[Id]
--           ,[IsShow])
--     SELECT
--            @rOrgId
--           ,[Title]
--           ,[Nationality]
--           ,[IsObsolete]
--		  ,@lCreatedUserId
--		  ,@lCreatedDateTime
--		  ,@lCreatedUserId
--		  ,@lCreatedDateTime
--           ,sCommon.fGetIntIdForOrg(Id,@rOrgId)
--           ,[IsShow]
--FROM [sCommon].[tCountryMaster] WHERE  OrgId = 1



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




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

--INSERT INTO sSecurity.tModulePermission
--           ([OrgId]
--           ,[ModuleId]
--			)
--			Values
--			(
--		   @rOrgId
--		   ,1
--		   )
 
 --INSERT INTO [sSecurity].[tPermission]
 --          ([TaskId]
 --          ,[RoleId]
 --          ,[Permission]
 --          ,[CreatedUserId]
 --          ,[CreatedDateTime]
 --          ,[UpdatedUserId]
 --          ,[UpdatedDateTime]
 --          ,[IsObsolete]
 --          ,[OrgId])
	--SELECT
	--      [TaskId]
 --          ,sCommon.fGetIntIdForOrg(RoleId,@rOrgId)
 --          ,[Permission]
 --          ,@lCreatedUserId
	--	   ,@lCreatedDateTime
	--	   ,@lCreatedUserId
	--       ,@lCreatedDateTime
 --          ,[IsObsolete]
 --          ,@rOrgId
	--  FROM [sSecurity].[tPermission] WHERE RoleId = 2 AND OrgId = 1
	
	
	--INSERT INTO [sCommon].[tReligionMaster]
--           ([Id]
--           ,[Code]
--           ,[Title]
--           ,[IsObsolete]
--           ,[CreatedUserId]
--           ,[CreatedDateTime]
--           ,[UpdatedUserId]
--           ,[UpdatedDateTime]
--           ,[OrgGroupId])
--     SELECT      
--			 sCommon.fGetIntIdForOrg(Id,@rOrgId)
--			,[Code]
--			,[Title]
--            ,[IsObsolete]
--			,@lCreatedUserId
--		    ,@lCreatedDateTime
--		    ,@lCreatedUserId
--		    ,@lCreatedDateTime
--		    ,@rOrgId
--     FROM [sCommon].[tReligionMaster] WHERE OrgId=1

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

--INSERT INTO sConfig.tCultureConfiguration
--           (
--			OrgId,
--			DateSeparator,
--			Culture,
--			LongDatePattern,
--			LongTimePattern,
--			NumberGroupSeparator,
--			NumberNegativePattern,
--			ShortDatePattern,
--			ShortTimePattern,
--			NumberGroupSizes,
--			UpdatedUserId,
--			UpdatedDateTime
--           )
     
--      SELECT 
--            @rOrgId,
--            DateSeparator,
--			Culture,
--			LongDatePattern,
--			LongTimePattern,
--			NumberGroupSeparator,
--			NumberNegativePattern,
--			ShortDatePattern,
--			ShortTimePattern,
--			NumberGroupSizes,
--		    @lCreatedUserId,
--		    @lCreatedDateTime
--           FROM sConfig.tCultureConfiguration WHERE  OrgId =  1

COMMIT TRANSACTION	 
END TRY
BEGIN CATCH
ROLLBACK TRANSACTION
SELECT ERROR_MESSAGE()
END CATCH
END
GO
PRINT N'Altering [sCommon].[pOrganizationSetupRemove]...';


GO


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

BEGIN
    BEGIN TRY
	
	 BEGIN TRANSACTION
	 
	 EXEC sp_msforeachtable "ALTER TABLE ? NOCHECK CONSTRAINT all"
    
  DELETE FROM sAccounting.tExpense WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAccounting.tExpenseGroupMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAccounting.tReimbursement WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAccounting.tReimbursementDetail WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAccounting.tReimbursementTypeMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sActivity.tActivity WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sActivity.tActivityParticipant WHERE CAST(LEFT(ActivityId, 4) AS INT) = @rOrgId
DELETE FROM sActivity.tAssignClub WHERE CAST(LEFT(ClubId, 4) AS INT) = @rOrgId
DELETE FROM sActivity.tEventAssign WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sActivity.tEventEnrollment WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sActivity.tEventSchedule WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sActivity.tHealthCheckup WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sActivity.tHealthCheckupAssign WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sActivity.tHealthCheckupDetail WHERE CAST(LEFT(HealthCheckupId, 4) AS INT) = @rOrgId
DELETE FROM sActivity.tHealthCheckupParameter WHERE CAST(LEFT(HealthCheckupId, 4) AS INT) = @rOrgId
DELETE FROM sActivity.tHealthCheckupStudent WHERE CAST(LEFT(HealthCheckupId, 4) AS INT) = @rOrgId
DELETE FROM  sActivity.tHealthParameterGroupMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sActivity.tHealthParameterList WHERE CAST(LEFT(HealthParameterId, 4) AS INT) = @rOrgId
DELETE FROM sActivity.tHealthParameterMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sActivity.tHealthTrack WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sActivity.tHouseMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sActivity.tPlacement WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sActivity.tPlacementInvite WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sActivity.tStudentImmunizationStatus WHERE CAST(LEFT(ImmunizationChartId, 4) AS INT) = @rOrgId
DELETE FROM sAdmission.tAdmissionForm WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sAdmission.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 sCommon.tTableRowId WHERE OrgId = @rOrgId AND TableTitle in (select TableTitle from sCommon.tTableRowIdMaster where IdScope = 'Org')
DELETE FROM sCommunication.tAssignment WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sCommunication.tAssignmentScope WHERE CAST(LEFT(AssignmentId, 4) AS BIGINT) = @rOrgId
DELETE FROM sCommunication.tAssignmentView WHERE CAST(LEFT(AssignmentId, 4) AS BIGINT) = @rOrgId
DELETE FROM sCommunication.tAssignTask WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sCommunication.tBehaviour WHERE CAST(LEFT(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.tQuestionMaster WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sEExam.tQuestionOption WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sEExam.tQuestionParagraph WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sEExam.tTestAssign WHERE CAST(LEFT(TestId, 4) AS int) = @rOrgId
DELETE FROM sEExam.tTestMaster WHERE OrgId = @rOrgId
DELETE FROM sEExam.tTestParticipant WHERE CAST(LEFT(TestId, 4) AS BIGINT) = @rOrgId
DELETE FROM sEExam.tTestParticipantAnswer WHERE CAST(LEFT(TestId, 4) AS INT) = @rOrgId
DELETE FROM sEExam.tTestQuestion WHERE CAST(LEFT(TestId, 4) AS INT) = @rOrgId
DELETE FROM sFee.tChargeReceipt WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sFee.tChargeReceiptDetail WHERE CAST(LEFT(ChargeReceiptId, 4) AS BIGINT) = @rOrgId
DELETE FROM sFee.tFeeAllocation WHERE CAST(LEFT(SourceId, 4) AS BIGINT) = @rOrgId
DELETE FROM sFee.tFeeCustomSearch WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sFee.tFeeOptional WHERE CAST(LEFT(SourceId, 4) AS BIGINT) = @rOrgId
DELETE FROM sFee.tFeeSetup WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sFee.tReceipt WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sFee.tReceiptDetail WHERE CAST(LEFT(ReceiptId, 4) AS BIGINT) = @rOrgId
DELETE FROM sFixedAsset.tCategoryMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sFixedAsset.tLocationMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM  sFrontOffice.tVisitorLog WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sGSEB.tActivityIndicatorScore WHERE CAST(LEFT(ActivityId, 4) AS INT) = @rOrgId
DELETE FROM sGSEB.tAnusuchiB WHERE CAST(LEFT(AcademicId, 4) AS BIGINT) = @rOrgId
DELETE FROM sGSEB.tClassActivity WHERE CAST(LEFT(ActivityId, 4) AS INT) = @rOrgId
DELETE FROM sGSEB.tExamSetting WHERE CAST(LEFT(ClassId, 4) AS INT) = @rOrgId
DELETE FROM sGSEB.tGSEBExamMapping WHERE CAST(LEFT(BatchId, 4) AS INT) = @rOrgId
DELETE FROM sGSEB.tHetuMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sGSEB.tAnusuchiB WHERE CAST(LEFT(AcademicId, 4) AS BIGINT) = @rOrgId
DELETE FROM sGSEB.tResult WHERE CAST(LEFT(AcademicId, 4) AS BIGINT) = @rOrgId
DELETE FROM sGSEB.tResultDetail WHERE CAST(LEFT(AcademicId, 4) AS BIGINT) = @rOrgId
DELETE FROM sGSEB.tResultDetailOptional WHERE CAST(LEFT(AcademicId, 4) AS BIGINT) = @rOrgId
DELETE FROM sGSEB.tSubjectIndicatorMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sHostel.tAssignRoom WHERE CAST(LEFT(RoomId, 4) AS INT) = @rOrgId
DELETE FROM sHostel.tHostelWarden WHERE CAST(LEFT(HostelId, 4) AS INT) = @rOrgId
DELETE FROM  sHrm.tEmployeeAttendance WHERE CAST(LEFT(EmployeeId, 4) AS BIGINT) = @rOrgId
DELETE FROM sHrm.tEmployeeCommunications WHERE CAST(LEFT(EmployeeId, 4) AS BIGINT) = @rOrgId
DELETE FROM sHrm.tEmployeeCustomSearch WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sHrm.tEmployeeDesignationMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sHrm.tEmployeeFamilyDetails WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sHrm.tEmployeeGradeMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sHrm.tEmployeeImages WHERE CAST(LEFT(EmployeeId, 4) AS BIGINT) = @rOrgId
DELETE FROM sHrm.tEmployeeJobDetail WHERE CAST(LEFT(EmployeeId, 4) AS BIGINT) = @rOrgId
DELETE FROM sHrm.tEmployeeMaster WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sHrm.tEmployeePersonalDetail WHERE CAST(LEFT(EmployeeId, 4) AS BIGINT) = @rOrgId
DELETE FROM sHrm.tEmployeePreviousEmployment WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM  sHrm.tEmployeeStatutoryAndOther WHERE CAST(LEFT(EmployeeId, 4) AS BIGINT) = @rOrgId
DELETE FROM  sHrm.tEmployeeTypeMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sHrm.tGuestMaster WHERE OrgId = @rOrgId
DELETE FROM  sHrm.tLeave WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM  sHrm.tLeaveTypeGradeSettings WHERE CAST(LEFT(OrgId, 4) AS SMALLINT) = @rOrgId
DELETE FROM  sHrm.tLeaveTypeMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM  sHrm.tWorkingDays WHERE CAST(LEFT(BatchId, 4) AS INT) = @rOrgId
DELETE FROM sIp.tBinMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sIp.tItemStandardPriceLog WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sIp.tStockItemBin WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sIp.tStockItemPlanning WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sIp.tStockItemPurchaseUom WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sIp.tWeightedAverageCostLog WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sLibrary.tAssignOrganization WHERE OrgId = @rOrgId
DELETE FROM sLibrary.tBookLog WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sLibrary.tBookLogPenalty WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sLibrary.tBooksForClass WHERE CAST(LEFT(ClassId, 4) AS INT) = @rOrgId
DELETE FROM sLibrary.tIssueSetting WHERE CAST(LEFT(SourceId, 4) AS BIGINT) = @rOrgId
DELETE FROM sOmr.tAnswerKeySetup WHERE CAST(LEFT(ExamDetailId, 4) AS INT) = @rOrgId
DELETE FROM sOmr.tExamSetup WHERE CAST(LEFT(ExamDetailId, 4) AS INT) = @rOrgId
DELETE FROM  sOmr.tScanHistory WHERE CAST(LEFT(AcademicId, 4) AS BIGINT) = @rOrgId
DELETE FROM sOmr.tSetting WHERE CAST(LEFT(OrgId, 4) AS SMALLINT) = @rOrgId
DELETE FROM sOmr.tSheetCallibration WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sOmr.tTempAnsKeyAnalysis WHERE CAST(LEFT(ExamDetailId, 4) AS INT) = @rOrgId
DELETE FROM sOrderEntry.tIssueReturn WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sOrderEntry.tIssueReturnDetail WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sOrderEntry.tOrderEntry WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sOrderEntry.tOrderEntryBatch WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM  sOrderEntry.tServiceItemTypeMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM  sPayroll.tEsiProcess WHERE CAST(LEFT(PayProcessElementId, 4) AS BIGINT) = @rOrgId
DELETE FROM sPayroll.tEsiSetup WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sPayroll.tPayElement WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM  sPayroll.tPayProcess WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sPayroll.tPayProcessElement WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sPayroll.tPayProcessEmployee WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM  sPayroll.tPaySetup WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM  sPayroll.tPaySetupDependent WHERE CAST(LEFT(PaySetupId, 4) AS INT) = @rOrgId
DELETE FROM  sPayroll.tPfProcess WHERE CAST(LEFT(PayProcessElementId, 4) AS BIGINT) = @rOrgId
DELETE FROM  sPayroll.tPfProcessCharge WHERE CAST(LEFT(PayProcessElementId, 4) AS BIGINT) = @rOrgId
DELETE FROM sPayroll.tPfSetup WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sPayroll.tProfessionalTaxRange WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tFirstAidEmoloyee WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sProcurement.tFirstAidEmployeeDetail WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sProcurement.tFirstAidInspection WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sProcurement.tFirstAidInspectionDetail WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sProcurement.tGoodsReceiptNote WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tGoodsReceiptNoteBatch WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tGoodsReceiptNoteDetail WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tGoodsReceiptNoteReturn WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tGoodsReceiptNoteReturnBatch WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tGoodsReceiptNoteReturnDetail WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tPurchaseOrder WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sProcurement.tPurchaseOrderDetail WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sProcurement.tStockAdjustment WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockAdjustmentBatch WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockAdjustmentDetail WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockAudit WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockAuditDetail WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockBatch WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockFreezeAdjustment WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockFreezeAdjustmentDetail WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockInward WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockInwardBatch WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockInwardDetail WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockInwardRequest WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockInwardRequestDetail WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockInwardReturn WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockInwardReturnBatch WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockIssue WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockIssueBatch WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockIssueDetail WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockIssueRequest WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockIssueRequestDetail WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockItemFreeze WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sProcurement.tStockTransfer WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockTransferBatch WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockTransferDetail WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockTransferRequest WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockTransferRequestDetail WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockVerification WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sProcurement.tStockVerificationApproval WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sSecurity.tConfiguration WHERE CAST(LEFT(OrgId, 4) AS SMALLINT) = @rOrgId
DELETE FROM sSecurity.tDivisionPermission WHERE CAST(LEFT(UserId, 4) AS BIGINT) = @rOrgId
DELETE FROM sSecurity.tLdapUser WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM  sSecurity.tUser WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sSecurity.tUserAccess  WHERE CAST(LEFT(UserId, 4) AS int) = @rOrgId
DELETE FROM sSecurity.tUserFavoriteScreen WHERE CAST(LEFT(UserId, 4) AS BIGINT) = @rOrgId
DELETE FROM sSecurity.tUserLocation WHERE CAST(LEFT(StoreLocationId, 4) AS INT) = @rOrgId
DELETE FROM sSecurity.tUserLog WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sSecurity.tUserOrganization WHERE CAST(LEFT(OrgId, 4) AS SMALLINT) = @rOrgId
DELETE FROM sSecurity.tUserPreference WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sSecurity.tUserProfile WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM  sSecurity.tUserRole WHERE CAST(LEFT(UserId, 4) AS INT) = @rOrgId
DELETE FROM sSetup.tBatchClass WHERE CAST(LEFT(ClassId, 4) AS INT) = @rOrgId
DELETE FROM  sSetup.tBatchMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sSetup.tClassMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sSetup.tClassSubject WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sSetup.tDepartmentMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sSetup.tDivisionMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sSetup.tOrganizationMaster WHERE Id = @rOrgId
DELETE FROM sSetup.tReportConfiguration WHERE OrgId = @rOrgId
DELETE FROM  sSetup.tReportSetting WHERE CAST(LEFT(OrgId, 4) AS SMALLINT) = @rOrgId
DELETE FROM sSetup.tSubjectMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sSetup.tTermMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sStudent.tAcademic WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sStudent.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 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 -1 AS Result
	RETURN
	END
	
	
	 BEGIN TRANSACTION
	 
	 EXEC sp_msforeachtable "ALTER TABLE ? NOCHECK CONSTRAINT all"
    




DELETE FROM sAccounting.tAccountingYearMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sAccounting.tAccountMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sAccounting.tLedgerGroupMaster  WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sAccounting.tLedgerMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sAccounting.tTransaction WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sAccounting.tTransactionDetail WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sActivity.tActivityTypeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sActivity.tClubMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM  sActivity.tImmunizationChart WHERE OrgGroupId = @rOrgGroupId
DELETE FROM 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.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.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  sProcurement.tVendorCategoryMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sProcurement.tVendorMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sSecurity.tModulePermission WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sSecurity.tOrganizationTask WHERE CAST(LEFT(OrgGroupId, 4) AS SMALLINT) = @rOrgGroupId
DELETE FROM  sSecurity.tPermission WHERE OrgGroupId = @rOrgGroupId
DELETE FROM  sSecurity.tRole WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sSetup.tOrgGroupBatchMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sSetup.tOrgGroupMaster WHERE Id=@rOrgGroupId
DELETE FROM sStudent.tAdmissionCategoryMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sTax.tTaxGroupMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sTransport.tBusRouteDestinationMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sTransport.tBusRouteMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sTransport.tVehicleMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM 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




 
		
		
		
		
		
		-- special case will come orgwise and orggroupwise
		
		DELETE FROM sCommon.tTableRowId WHERE OrgId = @rOrgGroupId 
		DELETE FROM sConfig.tConfigurationSetup WHERE SourceTypeId = 2010 AND SourceId = @rOrgGroupId
		
EXEC sp_msforeachtable "ALTER TABLE ? WITH CHECK CHECK CONSTRAINT all"

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


GO
ALTER PROCEDURE [sCommon].[pScreenGroupDataListGet]
          
           @rScreenGroupId int,
           @rUserId bigint   
AS
SET NOCOUNT ON

 
	BEGIN
		Select 
			S.Id AS Id,
			LEFT(S.Title,30) AS Title,
				S.IconPath,
			 CASE WHEN S.Id = 20020 THEN Page+'?MenuID=5310'
			      WHEN S.Id = 20033 THEN Page+'?MenuID=5410'
			      WHEN S.Id = 20037 THEN Page+'?MenuID=5111'
			      WHEN S.Id = 20038 THEN Page+'?MenuID=5112'
			      WHEN S.Id = 9018 THEN Page+'?MenuID=331111'
			      --WHEN S.Id = 297 THEN Page+'?MenuID=181115'
			      --WHEN S.Id = 296 THEN Page+'?MenuID=181116'
			      WHEN S.Id = 449 THEN Page+'?MenuID=221214'
			       WHEN S.Id = 5 THEN Page+'?MenuID=161014'
			         WHEN S.Id = 191 THEN Page+'?MenuID=15101015'
			         WHEN S.Id = 32 THEN Page+'?MenuID=141112'
			           --WHEN S.Id = 57 THEN Page+'?MenuID=312052'
			   ELSE Page 
			   END AS Page,
			   S.OrderIndex			  
			   From sSecurity.tScreen S
	    --INNER JOIN sSecurity.tScreenGroupMapping SGP ON S.ScreenGroupId = SGP.ScreenGroupId
		INNER JOIN sSecurity.tPermission P ON P.TaskId=S.TaskId
		INNER JOIN sSecurity.tUserRole U ON U.RoleId=P.RoleId
		INNER JOIN sSecurity.tTask T ON T.ID = p.TaskId
		INNER JOIN sSecurity.tOrganizationTask OT ON T.Id = OT.TaskId AND OT.OrgGroupId = P.OrgGroupId
	 
		WHERE (P.Permission & 2) =2
		AND ScreenGroupId=@rScreenGroupId AND U.IsObsolete=0
		AND U.UserId=@rUserId 
		AND T.IsObsolete = 0
		AND S.IsHideInScreenGroup = 0
		
		GROUP By S.Title,S.Id,Page,S.OrderIndex,S.IconPath
		Order by S.OrderIndex 
	END
GO
PRINT N'Altering [sEExam].[pDataTopicMasterAdd]...';


GO




ALTER PROCEDURE [sEExam].[pDataTopicMasterAdd]
	 
	@rId int,
	--@rAffiliationId int,
	--@rCode nvarchar(20),
	@rCode nvarchar(100),
	@rNumber int,
	@rTitle nvarchar(100), 
	@rClassGroupId int,
	@rDataTopicTypeId int, 
	@rIsObsolete bit,
	--@rOrderIndex int,
	@rCreatedUserId bigint,  
	@rOrgGroupId int,
	@rDataSubjectId int,
	@rDataBankId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	
		IF(@rId = 0)	
	BEGIN
		If Exists(select Id from sEExam.tDataTopicMaster where Code=@rCode AND DataBankId  = @rDataBankId AND DataSubjectId = @rDataSubjectId AND ClassGroupId =@rClassGroupId )
			BEGIN
			select -103 as Result
			RETURN
		END 
 
	END
	ELSE
	BEGIN
 
		If  Exists(select Id from sEExam.tDataTopicMaster where Code=@rCode AND DataBankId  = @rDataBankId AND DataSubjectId = @rDataSubjectId AND ClassGroupId =@rClassGroupId AND Id<>@rId)
		Begin
			select -103 as Result
			RETURN
		End

	END
	
	
	
	
	 BEGIN TRANSACTION	
 IF(@rId = 0)	
BEGIN

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


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


GO




ALTER PROCEDURE [sEExam].[pDataTopicMasterGet]
	 
	 @rId int = 0,
	 @rDataBankId int,
	 @rDataSubjectId int,
	 @rTitle nvarchar(100), 
	 @rCode nvarchar(120),
	 @rClassGroupId int,
	 @rAffiliationId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	  BEGIN	  
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
	  END
	 
	SELECT 
	DTM.Id,
	--DSM.AffiliationId,
	DTM.Code   AS Code,
	DTM.Number,
	DTM.Title  AS DataTopicName,
	DTM.IsObsolete,
    DCGS.Title AS DataSubject,
    DCGS.Id    AS DataSubjectId,    
	--TTM.OrderIndex,	 
	TTM.Title  AS TopicTypeName,
	TTM.Id     AS TopicTypeId,
	CGM.Title  AS ClassGroupTitle,
	CGM.Id     AS ClassGroupId
	 
  FROM 
		sEExam.tDataTopicMaster DTM
        INNER JOIN sEExam.tDataSubjectMaster DCGS
        ON DTM.DataSubjectId=DCGS.Id         
        INNER JOIN sEExam.tDataTopicTypeMaster TTM
        ON TTM.Id=DTM.DataTopicTypeId
        INNER JOIN sSetup.vAffiliationClassGroup CGM
        ON DTM.ClassGroupId=CGM.ClassGroupId 
        
  WHERE 		
       ((DTM.Id = @rId) OR (@rId = 0))
       AND ((DTM.Title like @rTitle) OR (ISNULL(@rTitle,'') = '')) 
       AND ((DTM.Code like @rCode) OR ISNULL(@rCode,'') = '')
       AND (TTM.DataBankId = @rDataBankId OR @rDataBankId = 0)
       AND (TTM.DataSubjectId = @rDataSubjectId OR @rDataSubjectId = 0)
       AND (DTM.ClassGroupId = @rClassGroupId OR @rClassGroupId = 0)
        --AND  ((TTM.Code like @rCode) OR (ISNULL(@rCode,'') = ''))
       AND CGM.AffiliationId = @rAffiliationId 
       ORDER BY DTM.Number 
		
END
GO
PRINT N'Altering [sFee].[pDepositAddGet]...';


GO

ALTER PROCEDURE [sFee].[pDepositAddGet]
          
		   @rOrgId int,          
           @rDepositHeadId int,
           @rFromAmount decimal(12,2),
           @rToAmount decimal(12,2),
           @rFromDepositDate date,
           @rToDepositDate date,
           @rBatchId int,
           @rCode nvarchar(20)
           
AS
SET NOCOUNT ON

BEGIN
SELECT  
		DHM.Title AS DepositHeadName,
		vSA.OrgId,
		DA.Id,
		DA.DepositHeadId,
		DA.StudentId AS StudentId,
		vSA.AcademicId AS AcademicId,
		DA.Amount,
		DA.DepositDate,
		DA.PayTypeId,
		DA.ChequeNo,
		DA.BankName,
		DA.Remark,
		DA.CreatedDateTime,
		vSA.Code,
        vSA.Name AS StudentName,        
        vSA.ClassName+' - '+vSA.DivisionName AS ClassDivisionName
  FROM 		
		sStudent.vStudentAcademic vSA
		INNER JOIN sFee.tDepositAdd DA ON DA.StudentId = vSA.StudentId
		INNER JOIN sFee.tDepositHeadMaster DHM ON DHM.Id = DA.DepositHeadId 
  WHERE  
		vSA.BatchId = @rBatchId
		AND (vSA.OrgId=@rOrgId OR @rOrgId=0)
		AND (DA.DepositHeadId=@rDepositHeadId OR @rDepositHeadId=0)
		AND ((DA.Amount >= @rFromAmount) OR (@rFromAmount = 0))
		AND ((DA.Amount <= @rToAmount) OR (@rToAmount = 0))
		AND ((DA.DepositDate >= @rFromDepositDate) OR (ISNULL(@rFromDepositDate,'') = ''))
		AND ((DA.DepositDate <= @rToDepositDate) OR (ISNULL(@rToDepositDate,'') = ''))
		AND ((vSA.Code=@rCode) OR (ISNULL(@rCode,'')=''))
		Order By DA.DepositDate
END
GO
PRINT N'Altering [sFee].[pDepositAdjustmentGet]...';


GO

ALTER PROCEDURE [sFee].[pDepositAdjustmentGet]
          
		   @rOrgId int,          
           @rDepositHeadId int,
           @rFromAmount decimal(12,2),
           @rToAmount decimal(12,2),
           @rFromAdjustmentDate date,
           @rToAdjustmentDate date,
           @rBatchId int,
           @rCode nvarchar(20)
           
AS
SET NOCOUNT ON

BEGIN
SELECT  
		DHM.Title AS DepositHeadName,
		vSA.OrgId,
		DA.Id,
		DA.DepositHeadId,
		DA.StudentId AS StudentId,
		vSA.AcademicId AS AcademicId,
		DA.Amount,
		DA.AdjustmentDate,
		DA.Remark,
		DA.CreatedDateTime,
		vSA.Code,
        vSA.Name AS StudentName,        
        vSA.ClassName+' - '+vSA.DivisionName AS ClassDivisionName
  FROM 		
		sStudent.vStudentAcademic vSA
		INNER JOIN sFee.tDepositAdjustment DA ON DA.StudentId = vSA.StudentId
		INNER JOIN sFee.tDepositHeadMaster DHM ON DHM.Id = DA.DepositHeadId
  WHERE  
		vSA.BatchId = @rBatchId 
		AND (vSA.OrgId=@rOrgId OR @rOrgId=0)
		AND (DA.DepositHeadId=@rDepositHeadId OR @rDepositHeadId=0)
		AND ((DA.Amount >= @rFromAmount) OR (@rFromAmount = 0))
		AND ((DA.Amount <= @rToAmount) OR (@rToAmount = 0))
		AND ((DA.AdjustmentDate >= @rFromAdjustmentDate) OR (ISNULL(@rFromAdjustmentDate,'') = ''))
		AND ((DA.AdjustmentDate <= @rToAdjustmentDate) OR (ISNULL(@rToAdjustmentDate,'') = ''))
		AND ((vSA.Code=@rCode) OR (ISNULL(@rCode,'')=''))
		Order By DA.AdjustmentDate
END
GO
PRINT N'Altering [sFee].[pDepositRefundGet]...';


GO

ALTER PROCEDURE [sFee].[pDepositRefundGet]
          
		   @rOrgId int,          
           @rDepositHeadId int,
           @rFromRefundAmount decimal(12,2),
           @rToRefundAmount decimal(12,2),
           @rFromRefundDate date,
           @rToRefundDate date,
           @rBatchId int,
           @rCode nvarchar(20)
           
AS
SET NOCOUNT ON

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


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

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

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


GO

ALTER PROCEDURE [sFee].[pRptDepositAddGet]
          
		   @rOrgId int,          
           @rDepositHeadId int,
           @rFromAmount decimal(12,2),
           @rToAmount decimal(12,2),
           @rFromDepositDate date,
           @rToDepositDate date,
           @rBatchId int,
           @rCode nvarchar(20)
           
AS
SET NOCOUNT ON 

BEGIN
SELECT  
		DHM.Title AS DepositHeadName,
		DA.Id,
		DA.DepositHeadId,
		DA.StudentId AS StudentId,
		vSA.AcademicId AS AcademicId,
		DA.Amount,
		DA.DepositDate,
		DA.PayTypeId,	
		DA.ChequeNo,
		DA.BankName,
		DA.Remark,
		DA.CreatedDateTime,
		vSA.Code,
        vSA.Name AS StudentName,        
        vSA.ClassName+' - '+vSA.DivisionName AS ClassDivisionName,
        OM.Id AS OrgId,
        OM.DisplayTitle AS OrganizationName
  FROM 		
		sStudent.vStudentAcademic vSA
		INNER JOIN sFee.tDepositAdd DA ON DA.StudentId = vSA.StudentId
		INNER JOIN sFee.tDepositHeadMaster DHM ON DHM.Id = DA.DepositHeadId 
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=vSA.OrgId
  WHERE  
		vSA.BatchId = @rBatchId 
		AND (vSA.OrgId=@rOrgId OR @rOrgId=0)
		AND (DA.DepositHeadId=@rDepositHeadId OR @rDepositHeadId=0)
		AND ((DA.Amount >= @rFromAmount) OR (@rFromAmount = 0))
		AND ((DA.Amount <= @rToAmount) OR (@rToAmount = 0))
		AND ((DA.DepositDate >= @rFromDepositDate) OR (ISNULL(@rFromDepositDate,'') = ''))
		AND ((DA.DepositDate <= @rToDepositDate) OR (ISNULL(@rToDepositDate,'') = ''))
		AND ((vSA.Code=@rCode) OR (ISNULL(@rCode,'')=''))
		Order By DA.DepositDate
END
GO
PRINT N'Altering [sFee].[pRptDepositAddReceiptGet]...';


GO

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

BEGIN
SELECT  
		DHM.Title AS DepositHeadName,
		DA.Id,
		DA.DepositHeadId,
		DA.StudentId AS StudentId,
		vSA.AcademicId AS AcademicId,
		DA.Amount,
		DA.DepositDate,
		DA.PayTypeId,
		PTM.Title AS PayType,
		DA.ChequeNo,
		DA.BankName,
		DA.Remark,
		DA.CreatedDateTime,
		vSA.RollNo,
		vSA.Code,
        vSA.Name AS StudentName,        
        vSA.ClassName+' - '+vSA.DivisionName AS ClassDivisionName,
        OM.Id AS OrgId,
        OM.DisplayTitle AS OrganizationName,
        sFinanceCommon.fNumberToWordsWithDecimal(ISNULL(DA.Amount,0.00),0,2) AS ReceiptAmountInWords
        
  FROM 		
		sStudent.vStudentAcademic vSA
		INNER JOIN sFee.tDepositAdd DA ON DA.StudentId = vSA.StudentId
		INNER JOIN sFee.tDepositHeadMaster DHM ON DHM.Id = DA.DepositHeadId 
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=vSA.OrgId
		INNER JOIn sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=DA.PayTypeId
  WHERE  
		vSA.BatchId = @rBatchId 
		AND (vSA.OrgId=@rOrgId OR @rOrgId=0)
		AND (DA.DepositHeadId=@rDepositHeadId OR @rDepositHeadId=0)
		AND (DA.Id=@rId)
		Order By DA.DepositDate
END
GO
PRINT N'Altering [sFee].[pRptDepositAdjustmentGet]...';


GO

ALTER PROCEDURE [sFee].[pRptDepositAdjustmentGet]
          
		   @rOrgId int,          
           @rDepositHeadId int,
           @rFromAmount decimal(12,2),
           @rToAmount decimal(12,2),
           @rFromAdjustmentDate date,
           @rToAdjustmentDate date,
           @rBatchId int,
           @rCode nvarchar(20)
           
AS
SET NOCOUNT ON

BEGIN
SELECT  
		DHM.Title AS DepositHeadName,
		DA.Id,
		DA.DepositHeadId,
		DA.StudentId AS StudentId,
		vSA.AcademicId AS AcademicId,
		DA.Amount,
		DA.AdjustmentDate,
		DA.Remark,
		DA.CreatedDateTime,
		vSA.Code,
        vSA.Name AS StudentName,        
        vSA.ClassName+' - '+vSA.DivisionName AS ClassDivisionName,
        OM.Id AS OrgId,
        OM.DisplayTitle AS OrganizationName
  FROM 		
		sStudent.vStudentAcademic vSA
		INNER JOIN sFee.tDepositAdjustment DA ON DA.StudentId = vSA.StudentId
		INNER JOIN sFee.tDepositHeadMaster DHM ON DHM.Id = DA.DepositHeadId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=vSA.OrgId
  WHERE  
		vSA.BatchId = @rBatchId 
		AND (vSA.OrgId=@rOrgId OR @rOrgId=0)
		AND (DA.DepositHeadId=@rDepositHeadId OR @rDepositHeadId=0)
		AND ((DA.Amount >= @rFromAmount) OR (@rFromAmount = 0))
		AND ((DA.Amount <= @rToAmount) OR (@rToAmount = 0))
		AND ((DA.AdjustmentDate >= @rFromAdjustmentDate) OR (ISNULL(@rFromAdjustmentDate,'') = ''))
		AND ((DA.AdjustmentDate <= @rToAdjustmentDate) OR (ISNULL(@rToAdjustmentDate,'') = ''))
		AND ((vSA.Code=@rCode) OR (ISNULL(@rCode,'')=''))
		Order By DA.CreatedDateTime
END
GO
PRINT N'Altering [sFee].[pRptDepositAdjustmentReceiptGet]...';


GO

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

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


GO

ALTER PROCEDURE [sFee].[pRptDepositRefundGet]
          
		   @rOrgId int,          
           @rDepositHeadId int,
           @rFromRefundAmount decimal(12,2),
           @rToRefundAmount decimal(12,2),
           @rFromRefundDate date,
           @rToRefundDate date,
           @rBatchId int,
           @rCode nvarchar(20)
           
AS
SET NOCOUNT ON

BEGIN
SELECT 
		DHM.Title AS DepositHeadName,
		DR.DepositHeadId,
		DR.StudentId AS StudentId,
		vSA.AcademicId AS AcademicId,
		DR.RefundDate,
		DR.PayTypeId,
		DR.ChequeNo,
		DR.BankName,
		DR.Remark,
		DR.CreatedDateTime,
		vSA.Code,
        vSA.Name AS StudentName,        
        vSA.ClassName+' - '+vSA.DivisionName AS ClassDivisionName,
        
		CASE  WHEN ISNULL(DR.RefundAmount,0) <> 0 THEN ISNULL(DR.RefundAmount,0) ELSE
		(SELECT ISNULL(SUM(D.Amount),0) FROM sFee.tDepositAdd D 
		INNER JOIN sFee.tDepositRefund DR1 ON DR1.DepositHeadId=D.DepositHeadId AND DR1.StudentId=D.StudentId AND D.StudentId = DR.StudentId
		WHERE D.DepositHeadId = DR1.DepositHeadId AND D.StudentId=DR1.StudentId)         
		- (SELECT ISNULL(SUM(DA.Amount),0) AS TotalAmount FROM sFee.tDepositAdjustment DA 
		INNER JOIN sFee.tDepositRefund DR2 ON DR2.DepositHeadId=DA.DepositHeadId AND DR2.StudentId=DA.StudentId AND DA.StudentId= DR.StudentId
		WHERE DA.DepositHeadId = DR2.DepositHeadId AND DA.StudentId=DR2.StudentId) END AS RefundAmount,
		
		OM.Id AS OrgId,
        OM.DisplayTitle AS OrganizationName
        
        
  FROM 		
		sStudent.vStudentAcademic vSA
		INNER JOIN sFee.tDepositRefund DR ON DR.StudentId = vSA.StudentId
		INNER JOIN sFee.tDepositHeadMaster DHM ON DHM.Id = DR.DepositHeadId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=vSA.OrgId
		
  WHERE  
		vSA.BatchId = @rBatchId 
		AND (vSA.OrgId=@rOrgId OR @rOrgId=0)
		AND (DR.DepositHeadId=@rDepositHeadId OR @rDepositHeadId=0)
		AND ((DR.RefundAmount >= @rFromRefundAmount) OR (@rFromRefundAmount = 0))
		AND ((DR.RefundAmount <= @rToRefundAmount) OR (@rToRefundAmount = 0))
		AND ((DR.RefundDate >= @rFromRefundDate) OR (ISNULL(@rFromRefundDate,'') = ''))
		AND ((DR.RefundDate <= @rToRefundDate) OR (ISNULL(@rToRefundDate,'') = ''))
		AND ((vSA.Code=@rCode) OR (ISNULL(@rCode,'')=''))
		
		GROUP BY
		
		DHM.Title,DR.DepositHeadId,DR.StudentId,vSA.AcademicId,DR.RefundAmount,DR.RefundDate,DR.PayTypeId,
		DR.ChequeNo,DR.BankName,DR.Remark,DR.CreatedDateTime,vSA.Code,vSA.Name,vSA.ClassName,vSA.DivisionName,OM.Id,OM.DisplayTitle       
		Order By DR.RefundDate
END
GO
PRINT N'Altering [sHrm].[pEmployeeDataModify]...';


GO


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

BEGIN TRY
BEGIN TRANSACTION

EXEC sp_xml_preparedocument @loDoc OUTPUT,@rXML
BEGIN
	
	IF(@rSubCategoryField = 'Gender' OR @rSubCategoryField = 'Religion' OR @rSubCategoryField = 'BloodGroup' 
			OR @rSubCategoryField = 'CastCategory' OR @rSubCategoryField = 'TransportMode' OR @rSubCategoryField = 'House'
			OR @rSubCategoryField = 'MotherTongue' OR @rSubCategoryField = 'Nationality' OR @rSubCategoryField = 'AdmissionStandard' OR  @rSubCategoryField = 'AdmissionCategory' )
	BEGIN
		SET @rSubCategoryField = @rSubCategoryField + 'Id'
	END
		
	CREATE TABLE ListofData(Id bigint,StudentId bigint,SubCategory nvarchar(100),UpdatedUserId bigint,IsExist bit);
	IF(@rCategoryId= 1)
		BEGIN
		insert into ListofData
		select 0,E.StudentId,E.SubCategory,E.UpdatedUserId,0
		from
		(
				SELECT StudentId,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Students/Students', 2)
				WITH (
						StudentId BIGINT, 
						SubCategory nvarchar(100),
						UpdatedUserId bigint)	
						)E 	
		UPDATE ListofData SET IsExist=1 WHERE StudentId NOT IN(SELECT StudentId FROM sStudent.tStudentCommunication) 
		
		set @sql='INSERT INTO sStudent.tStudentCommunication 
					(StudentId,'+@rSubCategoryField+',CreatedUserId,CreatedDateTime)
					SELECT
						LD.StudentId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
					FROM
						ListofData LD WHERE LD.IsExist=1'
		Exec sp_executesql @sql
		set @sql='UPDATE sStudent.tStudentCommunication set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sStudent.tStudentCommunication SC 
					INNER JOIN ListofData LD ON SC.StudentId=LD.StudentId AND IsExist=0'
		
		Exec sp_executesql @sql
		
		
		
		Drop Table ListofData
			 SELECT 1 AS StatusCode
	    END
	Else IF(@rCategoryId= 2)
		BEGIN
		insert into ListofData
		select 0,E.StudentId,E.SubCategory,E.UpdatedUserId,0
		from
		(
				SELECT StudentId,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Students/Students', 2)
				WITH (
						StudentId BIGINT, 
						SubCategory nvarchar(100),
						UpdatedUserId bigint)	
						)E 	
		UPDATE ListofData SET IsExist=1 WHERE StudentId NOT IN(SELECT StudentId FROM sStudent.tStudentOther) 
		
		IF(@rSubCategoryField = 'DateOfBirth')
		BEGIN			
			set @sql='INSERT INTO sStudent.tStudentOther 
					(StudentId,'+@rSubCategoryField+',CreatedUserId,CreatedDateTime)
					SELECT
						LD.StudentId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
					FROM
						ListofData LD WHERE LD.IsExist=1'
			Exec sp_executesql @sql				
			 				
			set @sql='UPDATE sStudent.tStudentOther set '+@rSubCategoryField+' = LD.SubCategory,
						UpdatedUserId=LD.UpdatedUserId,
						UpdatedDateTime=sCommon.fGetDate()  
						from sStudent.tStudentOther SO 
						INNER JOIN ListofData LD ON SO.StudentId=LD.StudentId'			
			Exec sp_executesql @sql
			set @sql='UPDATE sStudent.tStudentOther SET '+@rSubCategoryField+' = null WHERE DateOfBirth=''1900-01-01'''
			Exec sp_executesql @sql
		END
		ELSE
		BEGIN
			set @sql='INSERT INTO sStudent.tStudentOther 
						(StudentId,'+@rSubCategoryField+',CreatedUserId,CreatedDateTime)
						SELECT
							LD.StudentId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
						FROM
							ListofData LD WHERE LD.IsExist=1'
			Exec sp_executesql @sql				
			 				
			set @sql='UPDATE sStudent.tStudentOther set '+@rSubCategoryField+' = LD.SubCategory,
						UpdatedUserId=LD.UpdatedUserId,
						UpdatedDateTime=sCommon.fGetDate()  
						from sStudent.tStudentOther SO 
						INNER JOIN ListofData LD ON SO.StudentId=LD.StudentId'
			
			Exec sp_executesql @sql
		END
		Drop Table ListofData
			 SELECT 1 AS StatusCode
	    END	
	    
	    
	    
	Else IF(@rCategoryId= 3)
		BEGIN
		insert into ListofData
		select 0,E.StudentId,E.SubCategory,E.UpdatedUserId,0
		from
		(
				SELECT StudentId,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Students/Students', 2)
				WITH (
						StudentId BIGINT, 
						SubCategory nvarchar(100),
						UpdatedUserId bigint)	
						)E 	
						
		 				
		set @sql='UPDATE sStudent.tStudentAdmission set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sStudent.tStudentAdmission SA 
					INNER JOIN ListofData LD ON SA.StudentId=LD.StudentId'
		
		Exec sp_executesql @sql
		Drop Table ListofData
			 SELECT 1 AS StatusCode
	    END	
  Else IF(@rCategoryId= 4)
	BEGIN
		insert into ListofData
		select 0,E.StudentId,E.SubCategory,E.UpdatedUserId,0
		from
		(
				SELECT StudentId,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Students/Students', 2)
				WITH (
						StudentId BIGINT, 
						SubCategory nvarchar(100),
						UpdatedUserId bigint)	
						)E 	
		UPDATE ListofData SET IsExist=1 WHERE StudentId NOT IN(SELECT StudentId FROM sStudent.tStudentFamily) 
		
		set @sql='INSERT INTO sStudent.tStudentFamily 
					(StudentId,'+@rSubCategoryField+',CreatedUserId,CreatedDateTime)
					SELECT
						LD.StudentId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
					FROM
						ListofData LD WHERE LD.IsExist=1'				
		Exec sp_executesql @sql
		set @sql='UPDATE sStudent.tStudentFamily set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sStudent.tStudentFamily SA 
					INNER JOIN ListofData LD ON SA.StudentId=LD.StudentId AND IsExist=0'
		
		Exec sp_executesql @sql
		Drop Table ListofData
			 SELECT 1 AS StatusCode
	    END
	    
    Else IF(@rCategoryId= 5)
	     BEGIN
		insert into ListofData
		select 0,E.StudentId,E.SubCategory,E.UpdatedUserId,0
		from
		(
				SELECT StudentId,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Students/Students', 2)
				WITH (
						StudentId BIGINT, 
						SubCategory nvarchar(100),
						UpdatedUserId bigint)	
						)E 	
		UPDATE ListofData SET IsExist=1 WHERE StudentId NOT IN(SELECT StudentId FROM sStudent.tStudentHealth) 
		
		set @sql='INSERT INTO sStudent.tStudentHealth 
					(StudentId,'+@rSubCategoryField+',UpdatedUserId,UpdatedDateTime)
					SELECT
						LD.StudentId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
					FROM
						ListofData LD WHERE LD.IsExist=1'				
		Exec sp_executesql @sql
		set @sql='UPDATE sStudent.tStudentHealth set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sStudent.tStudentHealth SA 
					INNER JOIN ListofData LD ON SA.StudentId=LD.StudentId AND IsExist=0'
		
		Exec sp_executesql @sql
		Drop Table ListofData
			 SELECT 1 AS StatusCode
	    END		 
	 
	 Else IF(@rCategoryId= 6)
	    BEGIN
		insert into ListofData
		select E.Id,0,E.SubCategory,E.UpdatedUserId,0
		from
		(
				SELECT Id,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Students/Students', 2)
				WITH (
						Id BIGINT, 
						SubCategory nvarchar(100),
						UpdatedUserId bigint)	
						)E 	
		UPDATE ListofData SET IsExist=1 WHERE Id NOT IN(SELECT AcademicId FROM sStudent.tAcademicDetail) 
		
		set @sql='INSERT INTO sStudent.tAcademicDetail 
					(AcademicId,'+@rSubCategoryField+')
					SELECT
						LD.Id,Ld.SubCategory
					FROM
						ListofData LD WHERE LD.IsExist=1'				
		Exec sp_executesql @sql
		set @sql='UPDATE sStudent.tAcademicDetail set '+@rSubCategoryField+' = LD.SubCategory
					from sStudent.tAcademicDetail AD 
					INNER JOIN ListofData LD ON AD.AcademicId=LD.Id AND IsExist=0'
		
		Exec sp_executesql @sql
		Drop Table ListofData
			 SELECT 1 AS StatusCode
	    END	
	    
	Else IF(@rCategoryId= 7)
	     BEGIN
		insert into ListofData
		select 0,E.StudentId,E.SubCategory,E.UpdatedUserId,0
		from
		(
				SELECT StudentId,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Students/Students', 2)
				WITH (
						StudentId BIGINT, 
						SubCategory nvarchar(100),
						UpdatedUserId bigint)	
						)E 	
		UPDATE ListofData SET IsExist=1 WHERE StudentId NOT IN(SELECT Id FROM sStudent.tStudentMaster) 
		
		--set @sql='INSERT INTO sStudent.tStudentMaster 
		--			(StudentId,'+@rSubCategoryField+',UpdatedUserId,UpdatedDateTime)
		--			SELECT
		--				LD.StudentId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
		--			FROM
		--				ListofData LD WHERE LD.IsExist=1'				
		--Exec sp_executesql @sql
		set @sql='UPDATE sStudent.tStudentMaster set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sStudent.tStudentMaster SA 
					INNER JOIN ListofData LD ON SA.Id=LD.StudentId AND IsExist=0'
		
		Exec sp_executesql @sql
		Drop Table ListofData
			 SELECT 1 AS StatusCode
	    END			 
	 
END 
	   COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
GO
PRINT N'Altering [sHrm].[pEmployeeDataUpdateGet]...';


GO
ALTER PROCEDURE [sHrm].[pEmployeeDataUpdateGet]
	 @rCategoryId int,
	 @rSubCategory nvarchar(100),
	 @rOrgId int,
	 @rIsBlank bit,
	 @rStatusId int
	 --@rOrderBy int
	 
AS
SET NOCOUNT ON

BEGIN

		 DECLARE @lDataTypeId nvarchar(1)
		SELECT @lDataTypeId=DataTypeId FROM sCommon.tUpdateFieldMaster WHERE Field=@rSubCategory
		
		IF(@rSubCategory = 'Gender' OR @rSubCategory = 'Religion' OR @rSubCategory = 'BloodGroup' 
			OR @rSubCategory = 'CastCategory' OR @rSubCategory = 'TransportMode' OR @rSubCategory = 'House'
			OR @rSubCategory = 'MotherTongue' OR @rSubCategory = 'Nationality' OR @rSubCategory = 'AdmissionStandard' OR  @rSubCategory = 'AdmissionCategory'
			)
		BEGIN
			SET @rSubCategory = @rSubCategory + 'Id'
		END
		 Declare @Sql nvarchar(max)
		 
		 SET @Sql =  CASE @rCategoryId					  
					 WHEN 1 THEN -- Communication
						'Select EM.EmployeeId,EM.Code,EM.FirstName,EM.LastName,EM.EmployeeGroup,EM.DepartmentId,
						CASE WHEN '+@lDataTypeId+'=1 THEN
						ISNULL(SC.'+@rSubCategory+','''')
						WHEN '+@lDataTypeId+'=2 THEN
						ISNULL(SC.'+@rSubCategory+',''0'')
						WHEN '+@lDataTypeId+'=3 THEN
						ISNULL(SC.'+@rSubCategory+',''False'')
						WHEN '+@lDataTypeId+'=4 THEN
						ISNULL(SC.'+@rSubCategory+',''0001/01/01'')
						WHEN '+@lDataTypeId+'=5 THEN
						ISNULL(SC.'+@rSubCategory+',''0'')
						END AS SubCategory
							FROM 
							sHrm.vExtEmployeeMaster EM
							LEFT JOIN sHrm.tEmployeeCommunications EC ON EC.EmployeeId=EM.EmployeeId
							Where EM.OrgId='+CAST(@rOrgId AS nvarchar(15))
							
							+ 'AND (EM.StatusId='+ CAST(@rStatusId AS nvarchar(15)) +' OR '+CAST(@rStatusId AS nvarchar(15))+'=0)
							
							AND 
							('+CAST(@rIsBlank AS nvarchar(1))+'=0 
								OR ('+@lDataTypeId+'=1 AND ISNULL(SC.'+@rSubCategory+','''')='''')
								OR ('+@lDataTypeId+'=2 AND ISNULL(SC.'+@rSubCategory+',''0'')=''0'')
								OR ('+@lDataTypeId+'=3 AND ISNULL(SC.'+@rSubCategory+',''False'')=''False'')
								OR ('+@lDataTypeId+'=4 AND ISNULL(SC.'+@rSubCategory+',''0001/01/01'')=''0001/01/01'') 
							)'
					 WHEN 2 THEN -- Other
						'Select EM.EmployeeId,EM.Code,EM.FirstName,EM.LastName,EM.EmployeeGroup,EM.DepartmentId,
						CASE WHEN '+@lDataTypeId+'=1 THEN
						ISNULL(SO.'+@rSubCategory+','''')
						WHEN '+@lDataTypeId+'=2 THEN
						ISNULL(SO.'+@rSubCategory+',''0'')
						WHEN '+@lDataTypeId+'=3 THEN
						ISNULL(SO.'+@rSubCategory+',''False'')
						WHEN '+@lDataTypeId+'=4 THEN
						SO.'+@rSubCategory+'
						WHEN '+@lDataTypeId+'=5 THEN
						ISNULL(SO.'+@rSubCategory+',''0'')
						END AS SubCategory
							FROM 
							sHrm.vExtEmployeeMaster EM
							LEFT JOIN sHrm.tEmployeePersonalDetail EP ON EP.EmployeeId=EM.EmployeeId
							Where EM.OrgId='+CAST(@rOrgId AS nvarchar(15))
							+'AND (EM.StatusId='+ CAST(@rStatusId AS nvarchar(15)) +' OR '+CAST(@rStatusId AS nvarchar(15))+'=0)
							
							AND 
							('+CAST(@rIsBlank AS nvarchar(1))+'=0 
								OR ('+@lDataTypeId+'=1 AND ISNULL(SO.'+@rSubCategory+','''')='''')
								OR ('+@lDataTypeId+'=2 AND ISNULL(SO.'+@rSubCategory+',''0'')=''0'')
								OR ('+@lDataTypeId+'=3 AND ISNULL(SO.'+@rSubCategory+',''False'')=''False'')
								OR ('+@lDataTypeId+'=4 AND ISNULL(SO.'+@rSubCategory+',''0001/01/01'')=''0001/01/01'') 
							)'
							
					WHEN 3 THEN -- JobDetail
						'Select EM.EmployeeId,EM.Code,EM.FirstName,EM.LastName,EM.EmployeeGroup,EM.DepartmentId,
						CASE WHEN '+@lDataTypeId+'=1 THEN
						ISNULL(SAD.'+@rSubCategory+','''')
						WHEN '+@lDataTypeId+'=2 THEN
						ISNULL(SAD.'+@rSubCategory+',''0'')
						WHEN '+@lDataTypeId+'=3 THEN
						ISNULL(SAD.'+@rSubCategory+',''False'')
						WHEN '+@lDataTypeId+'=4 THEN
						ISNULL(SAD.'+@rSubCategory+',''0001/01/01'')
						WHEN '+@lDataTypeId+'=5 THEN
						ISNULL(SAD.'+@rSubCategory+',''0'')
						END AS SubCategory 
							FROM 
							sHrm.vExtEmployeeMaster EM
							INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.EmployeeId
							Where EM.OrgId='+CAST(@rOrgId AS nvarchar(15))
							+'AND (EM.StatusId='+ CAST(@rStatusId AS nvarchar(15)) +' OR '+CAST(@rStatusId AS nvarchar(15))+'=0)
							
							AND 
							('+CAST(@rIsBlank AS nvarchar(1))+'=0 
								OR ('+@lDataTypeId+'=1 AND ISNULL(SAD.'+@rSubCategory+','''')='''')
								OR ('+@lDataTypeId+'=2 AND ISNULL(SAD.'+@rSubCategory+',''0'')=''0'')
								OR ('+@lDataTypeId+'=3 AND ISNULL(SAD.'+@rSubCategory+',''False'')=''False'')
								OR ('+@lDataTypeId+'=4 AND ISNULL(SAD.'+@rSubCategory+',''0001/01/01'')=''0001/01/01'') 
							)'
					 
					WHEN 4 THEN --Family
						'Select EM.EmployeeId,EM.Code,EM.FirstName,EM.LastName,EM.EmployeeGroup,EM.DepartmentId,
					    CASE WHEN '+@lDataTypeId+'=1 THEN
						ISNULL(SAF.'+@rSubCategory+','''')
						WHEN '+@lDataTypeId+'=2 THEN
						ISNULL(SAF.'+@rSubCategory+',''0'')
						WHEN '+@lDataTypeId+'=3 THEN
						ISNULL(SAF.'+@rSubCategory+',''False'')
						WHEN '+@lDataTypeId+'=4 THEN
						ISNULL(SAF.'+@rSubCategory+',''0001/01/01'')
						WHEN '+@lDataTypeId+'=5 THEN
						ISNULL(SAF.'+@rSubCategory+',''0'')
						END AS SubCategory
							FROM 
							sHrm.vExtEmployeeMaster EM
							INNER JOIN sHrm.tEmployeeFamilyDetails EFD ON EFD.EmployeeId=EM.EmployeeId
							Where EM.OrgId='+CAST(@rOrgId AS nvarchar(15))
							+'AND (EM.StatusId='+ CAST(@rStatusId AS nvarchar(15)) +' OR '+CAST(@rStatusId AS nvarchar(15))+'=0)
							
							AND 
							('+CAST(@rIsBlank AS nvarchar(1))+'=0 
								OR ('+@lDataTypeId+'=1 AND ISNULL(SAD.'+@rSubCategory+','''')='''')
								OR ('+@lDataTypeId+'=2 AND ISNULL(SAD.'+@rSubCategory+',''0'')=''0'')
								OR ('+@lDataTypeId+'=3 AND ISNULL(SAD.'+@rSubCategory+',''False'')=''False'')
								OR ('+@lDataTypeId+'=4 AND ISNULL(SAD.'+@rSubCategory+',''0001/01/01'')=''0001/01/01'') 
							)'
				   
					WHEN 5 THEN --Previousemployment
					  'Select EM.EmployeeId,EM.Code,EM.FirstName,EM.LastName,EM.EmployeeGroup,EM.DepartmentId,
						CASE WHEN '+@lDataTypeId+'=1 THEN
						ISNULL(SAH.'+@rSubCategory+','''')
						WHEN '+@lDataTypeId+'=2 THEN
						ISNULL(SAH.'+@rSubCategory+',''0'')
						WHEN '+@lDataTypeId+'=3 THEN
						ISNULL(SAH.'+@rSubCategory+',''False'')
						WHEN '+@lDataTypeId+'=4 THEN
						ISNULL(SAH.'+@rSubCategory+',''0001/01/01'')
						WHEN '+@lDataTypeId+'=5 THEN
						ISNULL(SAH.'+@rSubCategory+',''0'')
						END AS SubCategory
							FROM 
							sHrm.vExtEmployeeMaster EM
							LEFT JOIN sHrm.tEmployeePreviousEmployment EPE ON EPE.EmployeeId=EM.EmployeeId
							Where SA.OrgId='+CAST(@rOrgId AS nvarchar(15))
							+'AND (SA.StatusId='+ CAST(@rStatusId AS nvarchar(15)) +' OR '+CAST(@rStatusId AS nvarchar(15))+'=0)
							AND 
							('+CAST(@rIsBlank AS nvarchar(1))+'=0 
								OR ('+@lDataTypeId+'=1 AND ISNULL(SAH.'+@rSubCategory+','''')='''')
								OR ('+@lDataTypeId+'=2 AND ISNULL(SAH.'+@rSubCategory+',''0'')=''0'')
								OR ('+@lDataTypeId+'=3 AND ISNULL(SAH.'+@rSubCategory+',''False'')=''False'')
								OR ('+@lDataTypeId+'=4 AND ISNULL(SAH.'+@rSubCategory+',''0001/01/01'')=''0001/01/01'') 
							)'
					
					END
		print @Sql    
	    
	   EXECUTE  sp_executesql @Sql
END
GO
PRINT N'Altering [sHrm].[pEmployeePreviousEmploymentGet]...';


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

BEGIN
	 SELECT 
			Id,
			EmployeeId,
			CompanyName, 		
			ISNULL(Designation,'') AS Designation,
			ISNULL(Remark,'') AS Remark,
			ISNULL(Duration,'') AS Duration ,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime,
			2 AS OperationState,
			ISNULL(LastSalary,0) AS Lastsalary,
		    ISNULL(ReasonForLeaving,'') AS ReasonForLeaving,
		    ISNULL(JobDescription,'') AS JobDescription,
		    ISNULL(IsInternal,0) AS IsInternal
	 FROM 
			sHrm.tEmployeePreviousEmployment
	 WHERE 
			 (EmployeeId = @rEmployeeId) 
		AND OrgId = @rOrgId
END
GO
PRINT N'Altering [sHrm].[pEmployeeStatutoryDetailAdd]...';


GO
ALTER PROCEDURE [sHrm].[pEmployeeStatutoryDetailAdd]

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

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


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

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


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

BEGIN
     
    DECLARE @1Leave int

	BEGIN TRY
	
	BEGIN TRANSACTION

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


GO
ALTER PROCEDURE [sHrm].[pWorkingDaysListGet]
	 
	@rEmployeeGradeId  bigint,	 
	@rBatchId int
 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
    --SET @rCode = sCommon.fSearchStringGet(@rCode)
    --SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		 
	--SELECT [ForMonth]
	--		,[ForYear]
	--	    ,[TotalDays]
	--	    ,[WorkingDays]
	--	    ,[VacationDays]
	--	    ,[Sundays]
	--	    ,[HoliDays]
	--	    ,[BatchId]
	--	    ,[EmployeeGradeId]
    -- FROM [sHrm].[tWorkingDays]
		   
    	Select 
				MY.MonthTitle AS ForMonthInWord,
				MY.MonthNumber AS ForMonth, 
				MY.YearNumber AS ForYear,
				
				(CASE [WorkingDays] WHEN 0 THEN [TotalDays]-[WorkingDays]
				 ELSE [WorkingDays] END) AS WorkingDay,
				 
				ISNULL([TotalDays],MY.NoOfDays) AS TotalDays,
			    --ISNULL([WorkingDays],0) AS WorkingDay,
			    ISNULL([VacationDays],0) AS VacationDays,
			    ISNULL([WeekOffs],0) AS Sundays,
			    ISNULL([HoliDays],0) AS HoliDays,
			    ISNULL(EmployeeGradeId,0) AS EmployeeGradeId
	 
		From 
				sSetup.fMonthYearForBatchGET(@rBatchId) AS MY
			LEFT JOIN [sHrm].[tWorkingDays] WD ON WD.BatchId=MY.BatchId 
				AND (WD.EmployeeGradeId = @rEmployeeGradeId)
				AND WD.ForMonth = MY.MonthNumber AND WD.ForYear = MY.YearNumber
		WHERE
			(MY.BatchId=@rBatchId)  
END
GO
PRINT N'Altering [sIp].[pBinMaintenanceGet]...';


GO
ALTER PROCEDURE [sIp].[pBinMaintenanceGet]
	@rStoreLocationId [int] = 0,
	@rId [int] = 0,
	@rIsWildCardSearch [bit] = 1
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
/*IF @rIsWildCardSearch = 1
		BEGIN
			SET @rCode = sCommon.fSearchStringGet(@rCode)
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
			SET @rItemCode = sCommon.fSearchStringGet(@rItemCode)	

		END
*/
	 
	 SELECT BM.Id,			
			BM.IsObsolete,
			SIB.Id AS ItemId,
			STM.Code AS ItemCode,
			STM.Title AS ItemName			
	   FROM sIp.tBinMaster BM INNER JOIN  sIp.tStockItemBin SIB
	   ON SIB.BinId = BM.Id   
	   INNER JOIN sIp.tStockItemMaster STM
	   ON STM.Id = SIB.StockItemId
	  WHERE ((BM.Id = @rId) OR (@rId = 0))	   
	  AND BM.StoreLocationId = @rStoreLocationId
END
GO
PRINT N'Altering [sPayroll].[pCalculatePayrollAmount]...';


GO
ALTER PROCEDURE [sPayroll].[pCalculatePayrollAmount] 
	      	        
            @1PaypSetupId int,
            @1Percentage DECIMAl(5,2),
            @1SourceId bigint,
            @1OrgGroupId int,
            @1EmployeeId bigint,
            @lNextNumber bigint,
            @rPayrollId int,
	        @rPayrollYearId int,
            @1Result decimal(22,6) output          
          
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
      DECLARE @lTotalAmount Decimal(22,2)
      DECLARE @1DependPayElementId int   
      DECLARE @1COUNT INT
      DECLARE @1Amount Decimal(22,2)
      DECLARE @1IsDepend bit
      DECLARE @1DependPaySetupId int   
      DECLARE @1DependPercentage decimal(5,2)
      DECLARE @1PayElementTypeId int
          
      BEGIN  
      
    --   DECLARE @lPTPayElementId int    
    --DECLARE @lPFPayElementId int
    DECLARE @lBasicPayElementId int
    --DECLARE @lESIPayElementId int
	
	--SELECT @lPTPayElementId = Id FROM sPayroll.tPayElement WHERE PayrollId = @rPayrollId AND PayElementDefaultId = 57
	--SELECT @lPFPayElementId = Id FROM sPayroll.tPayElement WHERE PayrollId = @rPayrollId AND PayElementDefaultId = 56
	SELECT @lBasicPayElementId = Id FROM sPayroll.tPayElement WHERE PayrollId = @rPayrollId AND PayElementDefaultId = 1
	--SELECT @lESIPayElementId = Id FROM sPayroll.tPayElement WHERE PayrollId = @rPayrollId AND PayElementDefaultId = 55
      
		SET @lTotalAmount = 0   
      
        --For Calculate EmployeeBasic
        IF  EXISTS (Select 1 FROM sPayroll.tPaySetupDependent WHere PaySetupId = @1PaypSetupId AND DependentPayElementId = @lBasicPayElementId) AND   
         EXISTS(Select 1 FROM sPayroll.tPaySetup Where PayElementId = @lBasicPayElementId AND SourceId = @1EmployeeId   AND SourceTypeId = 95)
        BEGIN   
            SELECT @lTotalAmount = ISNULL(Amount,0) from sPayroll.tPayProcessElement Where PayProcessEmployeeId = @lNextNumber AND PayElementId = @lBasicPayElementId
            --select Amount from sPayroll.tPayProcessElement Where PayProcessEmployeeId AND PayElementId
        END
       
		CREATE TABLE #tmpDependPayElementDetail
		(
			Id INT IDENTITY (1, 1),
			DependPayElementId  int,
			ProgressOrder int		 		
		)		
		INSERT INTO #tmpDependPayElementDetail		
		SELECT PayElementId,ProcessOrder from sPayroll.tPaySetupDependent PSD INNER JOIN sPayroll.tPaySetup ON  
        DependentPayElementId = PayElementId WHERE PaySetupId = @1PaypSetupId 
        AND SourceId = @1SourceId
        ORDER BY ProcessOrder DESC  
        
        --Select * from #tmpDependPayElementDetail 
        
        SELECT @1COUNT = COUNT(*) FROM #tmpDependPayElementDetail
	     
	      WHILE @1COUNT > 0
	        BEGIN	   
	          SET @1DependPayElementId = 0
	          SET @1Amount = 0.0
	          SET @1DependPercentage = 0
	          SET @1DependPaySetupId = 0 
	          SET @1PayElementTypeId = 0
	          SET @1PayElementTypeId = 0
	          
	           SELECT @1DependPayElementId = DependPayElementId FROM #tmpDependPayElementDetail WHERE Id = @1COUNT
	           SELECT @1DependPaySetupId = Id,@1DependPercentage = Percentage FROM sPayroll.tPaySetup WHERE PayElementId = @1DependPayElementId 
	            AND SourceId = @1SourceId
	          SELECT @1Amount = AMOUNT from sPayroll.tPayProcessElement Where PayProcessEmployeeId = @lNextNumber AND PayElementId = @1DependPayElementId
	           SELECT @1PayElementTypeId = PayElementTypeId FROM sPayroll.tPayElement Where Id = @1DependPayElementId  
	             
	             --IF(@1PayElementTypeId = 1)
	              BEGIN
	               IF EXISTS (SELECT 1 FROM sPayroll.tPaySetupDependent WHERE PaySetupId = @1DependPaySetupId)
	                BEGIN 	                   
	                   EXECUTE [sPayroll].[pCalculatePayrollAmount] @1DependPaySetupId,@1DependPercentage,@1SourceId,@1OrgGroupId,@1EmployeeId,@lNextNumber,@rPayrollId,@rPayrollYearId,@1Result OUTPUT
	                   SET @lTotalAmount = @lTotalAmount + ISNULL(@1Result,0)
	                END
	               ELSE
	               BEGIN                 
	                    SET @lTotalAmount = ISNULL(@lTotalAmount,0) + ISNULL(@1Amount,0)	                  
	               END  
	             END  
	            SET  @1COUNT = @1COUNT - 1               
	        END	       
	        
	        SET @lTotalAmount = (@lTotalAmount * @1Percentage)/100
	          
		    SET @1Result = @lTotalAmount
	 
      END
    
END
GO
PRINT N'Altering [sPayroll].[pCalculateStaticPayElement]...';


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

BEGIN

	BEGIN TRY
	BEGIN TRANSACTION  
	
	BEGIN
	
	DECLARE @lNextNumber BIGINT 
	DECLARE @1Basic DECIMAl(22,6) 
	DECLARE @1PfSalaryLimit DECIMAL(22,6)
	DECLARE @1PayProcesdsElementId bigint
	DECLARE @1ESISalaryLimit DECIMAL(22,6) 
    DECLARE @1Tax DECIMAL(22,6)
    DECLARE @1EmployeePfAmount Decimal(22,6)
    DECLARE @1EmployeeESIAmount Decimal(22,6)
    DECLARE @1TotalDeductionAmount DECIMAL(22,6)
    DECLARE @1EmployeePfPercent DECIMAL(22,2)
    DECLARE @1EmployerPfPercent DECIMAL(22,2)
    DECLARE @1EmployeeESIPercent DECIMAL(22,2)
    DECLARE @1EmployerESIPercent DECIMAL(22,2)

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


GO
ALTER PROCEDURE [sPayroll].[pCopyPaySetupAdd]
	  
	 @rSourceTypeId smallint,
	 @rSourceId bigint,
	 @rOrgGroupId int,
     @rCopyGradeId bigint,
     @rPayrollId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
       DELETE PSD FROM sPayroll.tPaySetup PS INNER JOIN  sPayroll.tPaySetupDependent PSD ON PSD.PaySetupId = PS.ID
	   WHERE SourceId = @rCopyGradeId AND SourceTypeId = @rSourceTypeId AND PayrollId = @rPayrollId
		
	   DELETE FROM sPayroll.tPaySetup WHERE SourceId = @rCopyGradeId AND SourceTypeId = @rSourceTypeId AND PayrollId = @rPayrollId
		
		DECLARE @1Count int
		DECLARE @1PaySetupId int
		DECLARE @lNextNumber BIGINT
		
		CREATE TABLE #TempTable
		(
		    ID INT IDENTITY(1,1),
		    PaySetupId INT,
		    PayElementId INT,
		    AMOUNT DECIMAL(22,2),
		    Percentage DECIMAL(22,2),
		    ProcessOrder int
		 ) 
       		
       	INSERT INTO #TempTable 
        SELECT  ID, 
         PayElementId
		,[Amount]
		,[Percentage]
        ,[ProcessOrder]  
        
	   FROM [sPayroll].[tPaySetup] PS   
			  
	   WHERE PayrollId = @rPayrollId  AND  PS.SourceTypeId = @rSourceTypeId AND PS.SourceId = @rSourceId
	   
	   SELECT @1Count = COUNT(Id) FROM #TempTable
	   
	   WHILE @1Count > 0	     
	     BEGIN 
	        SET @1PaySetupId = 0
	        EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sPayroll.tPaySetup', 0, 1, 1,@outNextNumber = @lNextNumber output
	        
	        INSERT INTO sPayroll.tPaySetup   
	        SELECT @lNextNumber,
				   @rSourceTypeId,      
                   @rCopyGradeId,
	               PayElementId
				   ,[Amount]
				   ,[Percentage]
				   ,[ProcessOrder]     
	               ,@rPayrollId
	                
	        FROM #TempTable Where Id = @1Count				    
	        
	        SELECT @1PaySetupId = PaySetupId From #TempTable Where Id = @1Count
	        
	        IF EXISTS(SELECT 1 FROM sPayroll.tPaySetupDependent Where PaySetupId = @1PaysetupId)
	          BEGIN  
	          
	                --Select @1PaysetupId
	                INSERT INTO sPayroll.tPaySetupDependent
	                SELECT DependentPayElementId,@lNextNumber FROM sPayroll.tPaySetupDependent Where PaySetupId = @1PaysetupId	               
	          END       
	          
	        SET @1Count = @1Count - 1
	     END
	     
	     DROP TABLE #TempTable
	     
	     SELECT @lNextNumber AS Result
       
END
GO
PRINT N'Altering [sPayroll].[pEsiSetupAdd]...';


GO
ALTER PROCEDURE [sPayroll].[pEsiSetupAdd] 
	      
		   @rId int,
	       @rPayrollYearId int,
           @rEmployeeEsiPercent decimal(5,2),
           @rEmployerEsiPercent decimal(5,2),
           @rEsiSalaryLimit decimal(22,6),
           @rRoundingTypeId tinyint,
           @rRoundingPrecision int,
           @rEffectiveDate date,
           @rCreatedUserId bigint,
           @rOrgGroupId int
           
           
          
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

	BEGIN TRY
	BEGIN TRANSACTION  
	--DECLARE @lNextNumber BIGINT
  
  IF NOT Exists (Select 1 From sPayroll.tEsiSetup Where PayrollYearId = @rPayrollYearId)
    
    BEGIN	
	--EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sPayroll.tEsiSetup', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO  [sPayroll].[tEsiSetup]
           (
            [ID]
           ,[PayrollYearId]
           ,[EmployeeEsiPercent]
           ,[EmployerEsiPercent]
           ,[EsiSalaryLimit]
           ,[RoundingTypeId]
           ,[RoundingPrecision]
           ,[EffectiveDate]
           ,[CreatedUserId]
           ,[CreatedDateTime]
           )
     VALUES
           (
		   @rId,
           @rPayrollYearId,
           @rEmployeeEsiPercent,
           @rEmployerEsiPercent,
           @rEsiSalaryLimit,
           @rRoundingTypeId,
           @rRoundingPrecision,
           @rEffectiveDate,
           @rCreatedUserId,
           sCommon.fGetDate()
          )
         END
    ELSE
		BEGIN    
		     --SET @lNextNumber = @rId
		     UPDATE [sPayroll].[tEsiSetup]
			   SET        
				   EmployeeEsiPercent = @rEmployeeEsiPercent 
				  ,[EmployerEsiPercent] = @rEmployerEsiPercent 
				  ,[EsiSalaryLimit] = @rEsiSalaryLimit 
				  ,[RoundingTypeId] = @rRoundingTypeId 
				  ,[RoundingPrecision] = @rRoundingPrecision 
				  ,[EffectiveDate] = @rEffectiveDate 	
			  Where PayrollYearId = @rPayrollYearId
		END        
	SELECT @rId AS Result	
	COMMIT TRANSACTION
	END TRY
	BEGIN CATCH
	ROLLBACK TRANSACTION
	RAISERROR ('Error Creating Esi Setup Detail', -- Message text.
               16, -- Severity.
               1 -- State.
               );
	--SELECT -1 AS RESULT
	END CATCH	
END
GO
PRINT N'Altering [sPayroll].[pEsiSetupGet]...';


GO
ALTER PROCEDURE [sPayroll].[pEsiSetupGet]
	 @rId int,
	 @rPayrollYearId int 
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN  
	SELECT 
		   [ID] 
		  ,[EmployeeEsiPercent]
		  ,[EmployerEsiPercent]
		  ,[EsiSalaryLimit]
		  ,[RoundingTypeId]
		  ,[RoundingPrecision]
		  ,[EffectiveDate]
		  ,[PayrollYearId]
      
   FROM [sPayroll].[tEsiSetup]
  
  
Where  
     (Id = @rId OR @rId = 0) AND 
     PayrollYearId = @rPayrollYearId
		
END
GO
PRINT N'Altering [sPayroll].[pGetPayProcessEmployeeDetail]...';


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

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

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

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

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


GO
ALTER PROCEDURE [sPayroll].[pPayElementAdd] 
	      
			@rId int
	       ,@rCode nvarchar(20)
           ,@rTitle nvarchar(100)
           ,@rPayElementTypeId tinyint
           ,@rPaidCategoryId tinyint
           ,@rIsLwp bit
           ,@rIsEmployeeSpecific bit
           ,@rIsDepend bit
           ,@rIsAvailDuringProbation bit
           ,@rIsIncludeInPaySlip bit
           ,@rSortOrder tinyint
           ,@rIsObsolete bit
           ,@rOrgGroupId int
           ,@rCreatedUserId bigint
		   ,@rPayElementDefaultId int
		   ,@rPayrollId int
      
        
           
          
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

	BEGIN TRY
	BEGIN TRANSACTION  
	DECLARE @lNextNumber BIGINT
  
  IF (@rId = 0)
    
    BEGIN	
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sPayroll.tPayElement', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO [sPayroll].[tPayElement]
           (
            [ID]
           ,[Code]
           ,[Title]
           ,[PayElementTypeId]
           ,[PaidCategoryId]
           ,[IsLwp]
           ,[IsEmployeeSpecific]
           ,[IsDepend]
           ,[IsAvailDuringProbation]
           ,[IsIncludeInPaySlip]
           ,[SortOrder]
           ,[IsObsolete]
           ,[CreatedUserId]
           ,[CreatedDateTime]
           ,[UpdatedUserId]
           ,[UpdatedDateTime]
           ,[PayElementDefaultId]
           ,[PayrollId]
           )
     VALUES
           (
            @lNextNumber
           ,@rCode 
           ,@rTitle 
           ,@rPayElementTypeId 
           ,@rPaidCategoryId 
           ,@rIsLwp 
           ,@rIsEmployeeSpecific 
           ,@rIsDepend 
           ,@rIsAvailDuringProbation 
           ,@rIsIncludeInPaySlip 
           ,@rSortOrder 
           ,@rIsObsolete 
           ,@rCreatedUserId 
           ,sCommon.fGetDate()  
           ,@rCreatedUserId 
           ,sCommon.fGetDate() 
           ,@rPayElementDefaultId
           ,@rPayrollId
           )
    	END
    ELSE
		BEGIN    
		     SET @lNextNumber = @rId
		    UPDATE  [sPayroll].[tPayElement]
			   SET   
				   [Title] = @rTitle 
				  ,[PayElementTypeId] = @rPayElementTypeId 
				  ,[PaidCategoryId] = @rPaidCategoryId 
				  ,[IsLwp] = @rIsLwp 
				  ,[IsEmployeeSpecific] = @rIsEmployeeSpecific 
				  ,[IsDepend] = @rIsDepend 
				  ,[IsAvailDuringProbation] = @rIsAvailDuringProbation 
				  ,[IsIncludeInPaySlip] = @rIsIncludeInPaySlip 
				  ,[SortOrder] = @rSortOrder 
				  ,[IsObsolete] = @rIsObsolete  
				  ,[UpdatedUserId] = @rCreatedUserId 
				  ,[UpdatedDateTime] = sCommon.fGetDate() 
				  ,[PayElementDefaultId] = @rPayElementDefaultId
				  ,[PayrollId]=@rPayrollId
			   WHERE Id = @rId   		     		    
			END        
	SELECT @lNextNumber AS Result	
	COMMIT TRANSACTION
	END TRY
	BEGIN CATCH
	ROLLBACK TRANSACTION
	 RAISERROR ('Error Creating Pay Element Detail', -- Message text.
               16, -- Severity.
               1 -- State.
               );
	--SELECT -1 AS RESULT
	END CATCH	
END
GO
PRINT N'Altering [sPayroll].[pPayElementGet]...';


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

BEGIN 		

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

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

Where 
	 PE.PayrollId = @rPayrollId  
     AND (PE.Id = @rId OR @rId = 0)
     AND (PE.Code Like @rCode OR ISNULL(@rCode,'') = '')
     AND (PE.Title Like @rTitle OR ISNULL(@rTitle,'') = '')
     AND (PayElementTypeId = @rPayElementTypeId OR @rPayElementTypeId = 0)
     AND (PaidCategoryId = @rPaidCategoryId OR @rPaidCategoryId = 0) 
     ORDER BY PE.SortOrder
END
GO
PRINT N'Altering [sPayroll].[pPayProcessAdd]...';


GO
ALTER PROCEDURE [sPayroll].[pPayProcessAdd] 
	      
	        @rID int
           ,@rSalaryMonth tinyint
           ,@rSalaryYear smallint
           ,@rIsApproved bit
           ,@rStartDateTime datetime           
           ,@rStatusId smallint
           ,@rCreatedUserId bigint        
           ,@rPayrollYearId int
           ,@rOrgGroupId int
           ,@rPayrollId int
            
           
          
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

	BEGIN TRY
	BEGIN TRANSACTION  
	DECLARE @lNextNumber BIGINT
	DECLARE @1PayProcessId int
	DECLARE @1Result bigint
  
  --IF (@rId = 0)
    
     IF EXISTS(Select 1 FROM sPayroll.tPayProcess Where SalaryMonth = @rSalaryMonth AND SalaryYear = @rSalaryYear AND PayrollYearId = @rPayrollYearId)
      BEGIN      
		
		SELECT @1PayProcessId = ID  FROM sPayroll.tPayProcess Where  SalaryMonth = @rSalaryMonth AND SalaryYear = @rSalaryYear AND PayrollYearId = @rPayrollYearId
		 
		DELETE PE from sPayroll.tPayProcessEmployee  PPE
		INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId = PPE.ID
		WHERE PayProcessId = @1PayProcessId 
		
		DELETE FROM sPayroll.tPayProcessEmployee where PayProcessId = @1PayProcessId
        
        DELETE FROM sPayroll.tPayProcess Where  SalaryMonth = @rSalaryMonth AND SalaryYear = @rSalaryYear AND PayrollYearId = @rPayrollYearId        
        
        DELETE FROM sPayroll.tPfProcess Where PayProcessElementId NOT IN (Select ID From sPayroll.tPayProcessElement)
		DELETE FROM sPayroll.tEsiProcess Where PayProcessElementId NOT IN (Select ID From sPayroll.tPayProcessElement)
		 
      END
        
    BEGIN	
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sPayroll.tPayProcess', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO  [sPayroll].[tPayProcess]
           (
            [ID]
           ,[SalaryMonth]
           ,[SalaryYear]
           ,[IsApproved]
           ,[StartDateTime]   
           ,EndDateTime     
           ,[StatusId]
           ,[CreatedUserId]
           ,[CreatedDateTime]
           ,[PayrollYearId]
           )
     VALUES
           (
            @lNextNumber
           ,@rSalaryMonth
           ,@rSalaryYear
           ,@rIsApproved
           ,sCommon.fGetDate()
           ,NULL
           ,@rStatusId
           ,@rCreatedUserId
           ,sCommon.fGetDate()
           ,@rPayrollYearId
           )
    	END
		
    EXECUTE [sPayroll].[pPayProcessEmployeeAdd] @lNextNumber,@rOrgGroupId,@rPayrollId,@rPayrollYearId  
       
	SELECT @lNextNumber AS Result
	COMMIT TRANSACTION
	END TRY
	BEGIN CATCH
	ROLLBACK TRANSACTION
	 RAISERROR ('Error Creating Pay Process Detail', -- Message text.
               16, -- Severity.
               1 -- State.
               );
	--SELECT -1 AS RESULT
	END CATCH	
END
GO
PRINT N'Altering [sPayroll].[pPayProcessEmployeeAdd]...';


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

BEGIN

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


GO
ALTER PROCEDURE [sPayroll].[pPaySetupAdd] 
	      
	        @rID int
           ,@rSourceTypeId smallint
           ,@rSourceId bigint
           ,@rPayElementId int
           ,@rAmount decimal(22,6)
           ,@rPercentage decimal(5,2)
           ,@rProcessOrder tinyint
           ,@rOrgGroupId int
           ,@rIsObsolete bit
           ,@rPayrollId int
          
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

	BEGIN TRY
	BEGIN TRANSACTION  
	DECLARE @lNextNumber BIGINT
	
  IF(@rIsObsolete = 0 AND @rId > 0)
  BEGIN
    SET @lNextNumber = 1
    DELETE FROM sPayroll.tPaySetup Where SourceId = @rSourceId AND SourceTypeId = @rSourceTypeId AND PayElementId = @rPayElementId AND PayrollId = @rPayrollId
      
  END
 
  ELSE	
  
  BEGIN
  IF (@rId = 0 AND @rIsObsolete = 1)
    
    BEGIN	
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sPayroll.tPaySetup', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO [sPayroll].[tPaySetup]
           ([ID]
           ,[SourceTypeId]
           ,[SourceId]
           ,[PayElementId]
           ,[Amount]
           ,[Percentage]
           ,[ProcessOrder]
           ,[PayrollId]
           )
     VALUES
           (
			@lNextNumber 
		   ,@rSourceTypeId 
		   ,@rSourceId 
		   ,@rPayElementId 
		   ,@rAmount 
		   ,@rPercentage 
		   ,@rProcessOrder 
		   ,@rPayrollId
           )
    	END
    ELSE
		BEGIN    
		     SET @lNextNumber = @rId
		     UPDATE  [sPayroll].[tPaySetup]
			   SET       
				  [PayElementId] = @rPayElementId
				  ,[Amount] = @rAmount
				  ,[Percentage] = @rPercentage
				  ,[ProcessOrder] = @rProcessOrder
				  ,[PayrollId] = @rPayrollId
 
			WHERE Id = @rId		     		     		    
		END 
	END       
	SELECT @lNextNumber AS Result	
	COMMIT TRANSACTION
	END TRY
	BEGIN CATCH
	ROLLBACK TRANSACTION
	 RAISERROR ('Error Creating Pay Set Detail', -- Message text.
               16, -- Severity.
               1 -- State.
               );
	--SELECT -1 AS RESULT
	END CATCH	
END
GO
PRINT N'Altering [sPayroll].[pPaySetupDependentGet]...';


GO
ALTER PROCEDURE [sPayroll].[pPaySetupDependentGet]
	 
	 @rPaySetupId int,
	 @rPayrollId int
	  
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 		
    
    Select           
         DependentPayElementId AS DependPayElementId,
         PE.Title AS DependPayElement        
        
    From sPayroll.tPaySetupDependent  PSD
    INNER JOIN sPayroll.tPayElement PE ON PE.ID = PSD.DependentPayElementId	 
    
    WHERE PaysetupId = @rPaySetupId 
	AND PE.PayrollId = @rPayrollId
END
GO
PRINT N'Altering [sPayroll].[pPaySetupElementWiseEmployeeGet]...';


GO
ALTER PROCEDURE [sPayroll].[pPaySetupElementWiseEmployeeGet]
	  
	 @rSourceTypeId smallint,
	 @rSourceId bigint,
	 @rPayrollId int,
	 @rPayElementId int
 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
       		
    SELECT  
      ISNULL(PS.Id,0) AS PaySetupId,
      EM.EmployeeId,
      EM.EmployeeName,
      EM.Code,
      EM.DepartmentName,
      PS.Amount,
      ISNULL([ProcessOrder],0) AS ProcessOrder,
      ISNULL(PS.PayElementId,0) AS PayElementId 

	 FROM sHrm.vEmployeeCommonDetail EM 
	 
	 LEFT JOIN sPayroll.tPaySetup PS 
		ON PS.SourceId = EmployeeId  
		AND SourceTypeId = @rSourceTypeId 
		AND PS.PayElementId = @rPayElementId
		
	 INNER JOIN sHrm.tEmployeeStatutoryAndOther ESO
		ON PS.PayrollId=ESO.PayrollId
		
	 WHERE  ESO.PayrollId = @rPayrollId 
	 
	 ORDER BY  EM.EmployeeName
       
END
GO
PRINT N'Altering [sPayroll].[pPaySetupEmployeeGet]...';


GO
ALTER PROCEDURE [sPayroll].[pPaySetupEmployeeGet]
	  
	 @rSourceTypeId smallint,
	 @rSourceId bigint,
	 @rPayrollId int,
	 @rEmployeeCode nvarchar(100),
	 @rEmployeeName nvarchar(100),
	 @rPayElementId int,
	 @rId int
	 
 WITH EXECUTE AS CALLER
AS
 SET NOCOUNT ON
 
BEGIN 		
	   SELECT 
		   ISNULL(PS.[ID],0) AS PaySetupId	  		  
		  ,PE.Id AS PayElementId
		  ,PS.SourceId
		  ,[Amount]
		  ,[Percentage]
		  ,ISNULL([ProcessOrder],0) AS ProcessOrder
		  ,ISNULL(PS.[PayrollId],0) AS PayrollId
	      ,PE.Title  AS PayElement
	      ,PE.IsDepend
	      ,EM.Code
	      ,EM.EmployeeName
	     
	      
	FROM  sPayroll.tPayElement PE INNER JOIN  [sPayroll].[tPaySetup] PS ON PE.ID = PS.PayElementId  
		   INNER JOIN sHrm.vEmployeeCommonDetail Em ON Em.EmployeeId = PS.SourceId
		  
   WHERE 
         (Ps.ID = @rId OR ISNULL(@rId,0) = 0)
         AND PE.IsObsolete = 0  AND PE.PayrollId = @rPayrollId
         AND  PS.SourceTypeId = @rSourceTypeId
         AND (PS.SourceId = @rSourceId OR @rSourceId = 0)
         AND (EM.Code LIKE @rEmployeeCode + '%' OR ISNULL(@rEmployeeCode,'') = '')
         AND (EmployeeName LIKE @rEmployeeName + '%' OR ISNULL(@rEmployeeName,'') = '')
         AND (SourceId = @rSourceId OR ISNULL(@rSourceId,0) = 0)
         AND (PE.Id = @rPayElementId OR ISNULL(@rPayElementId,0) = 0)
         
		 
END
GO
PRINT N'Altering [sPayroll].[pPaySetupGet]...';


GO
ALTER PROCEDURE [sPayroll].[pPaySetupGet]
	  
	 @rSourceTypeId smallint,
	 @rSourceId bigint,
	 @rPayrollId int
 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
       		
		SELECT 
			   ISNULL(PS.[ID],0) AS PaySetupId	  		  
			  ,PE.Id AS PayElementId
			  ,[Amount]
			  ,[Percentage]
			  ,ISNULL([ProcessOrder],0) AS ProcessOrder
			  ,ISNULL(PS.[PayrollId],0) AS PayrollId
			  ,PE.Title  AS PayElement
			  ,[sPayroll].[fGetPaySetupDependentElement](ISNULL(PS.Id,0)) AS PaysetupDependentElement
			  ,ISNULL(PE.IsDepend,0) AS IsDepend
			  ,PE.PayElementDefaultId
		      
		FROM  sPayroll.tPayElement PE LEFT JOIN  [sPayroll].[tPaySetup] PS ON PE.ID = PS.PayElementId AND
			  PS.SourceTypeId = @rSourceTypeId AND PS.SourceId = @rSourceId
			  
	   WHERE PE.IsObsolete = 0  AND PE.PayrollId = @rPayrollId   
       
END
GO
PRINT N'Altering [sPayroll].[pPaySetupRemove]...';


GO
ALTER PROCEDURE [sPayroll].[pPaySetupRemove]
	 
	 @rSourceTypeId smallint,
	 @rSourceId bigint
 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
       DELETE PSD FROM sPayroll.tPaySetup PS INNER JOIN  sPayroll.tPaySetupDependent PSD ON PSD.PaySetupId = PS.ID
	   WHERE SourceId = @rSourceId AND SourceTypeId = @rSourceTypeId		
	   DELETE FROM sPayroll.tPaySetup WHERE SourceId = @rSourceId AND SourceTypeId = @rSourceTypeId   
    
       SELECT 1 AS Result
END
GO
PRINT N'Altering [sPayroll].[pPfSetupAdd]...';


GO
ALTER PROCEDURE [sPayroll].[pPfSetupAdd] 
	      
		    @rId int
           ,@rPayrollYearId int
           ,@rPfSalaryLimit decimal(22,6)
           ,@rFpsSalaryLimit decimal(22,6)
           ,@rEmployeePfPercent decimal(5,2)
           ,@rEmployerPfPercent decimal(5,2)
           ,@rEmployerFpsPercent decimal(5,2)
           ,@rAdminChargesPercent decimal(5,2)
           ,@rEdliPercent decimal(5,2)
           ,@rInspectionChargesPercent decimal(5,2)
           ,@rMaximumAgeForFps smallint
           ,@rRoundingTypeId tinyint
           ,@rRoundingPrecision int
           ,@rMaximumVpfPercent decimal(5,2)
           ,@rMaximumVpfAmount decimal(22,6)
           ,@rCreatedUserId bigint 
           ,@rOrgGroupId int
          
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

	BEGIN TRY
	BEGIN TRANSACTION  
	DECLARE @lNextNumber BIGINT
  
   IF Not Exists (Select 1 From [sPayroll].[tPfSetup] Where PayrollYearId = @rPayrollYearId)
    
    BEGIN	
	--EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sPayroll.tPfSetup', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO  [sPayroll].[tPfSetup]
           (
            [Id]
           ,[PayrollYearId]
           ,[PfSalaryLimit]
           ,[FpsSalaryLimit]
           ,[EmployeePfPercent]
           ,[EmployerPfPercent]
           ,[EmployerFpsPercent]
           ,[AdminChargesPercent]
           ,[EdliPercent]
           ,[InspectionChargesPercent]
           ,[MaximumAgeForFps]
           ,[RoundingTypeId]
           ,[RoundingPrecision]
           ,[MaximumVpfPercent]
           ,[MaximumVpfAmount]
           ,[CreatedUserId]
           ,[CreatedDateTime]
           )
     VALUES
           (
            @rId 
           ,@rPayrollYearId 
           ,@rPfSalaryLimit 
           ,@rFpsSalaryLimit 
           ,@rEmployeePfPercent 
           ,@rEmployerPfPercent 
           ,@rEmployerFpsPercent 
           ,@rAdminChargesPercent 
           ,@rEdliPercent 
           ,@rInspectionChargesPercent 
           ,@rMaximumAgeForFps 
           ,@rRoundingTypeId 
           ,@rRoundingPrecision 
           ,@rMaximumVpfPercent 
           ,@rMaximumVpfAmount 
           ,@rCreatedUserId 
           ,sCommon.fGetDate()
           )
         END
    ELSE
		BEGIN    
		     --SET @lNextNumber = @rId
		     UPDATE  [sPayroll].[tPfSetup]
			   SET  
				   [PfSalaryLimit] = @rPfSalaryLimit
				  ,[FpsSalaryLimit] = @rFpsSalaryLimit
				  ,[EmployeePfPercent] = @rEmployeePfPercent 
				  ,[EmployerPfPercent] = @rEmployerPfPercent 
				  ,[EmployerFpsPercent] = @rEmployerFpsPercent 
				  ,[AdminChargesPercent] = @rAdminChargesPercent 
				  ,[EdliPercent] = @rEdliPercent 
				  ,[InspectionChargesPercent] = @rInspectionChargesPercent 
				  ,[MaximumAgeForFps] = @rMaximumAgeForFps 
				  ,[RoundingTypeId] = @rRoundingTypeId 
				  ,[RoundingPrecision] = @rRoundingPrecision 
				  ,[MaximumVpfPercent] = @rMaximumVpfPercent 
				  ,[MaximumVpfAmount] = @rMaximumVpfAmount 
      
			  Where PayrollYearId = @rPayrollYearId	     		    
		END        
	SELECT @rId AS Result	
	COMMIT TRANSACTION
	END TRY
	BEGIN CATCH
	ROLLBACK TRANSACTION
	RAISERROR ('Error Creating Pf Setup Detail', -- Message text.
               16, -- Severity.
               1 -- State.
               );
	--SELECT -1 AS RESULT
	END CATCH	
END
GO
PRINT N'Altering [sPayroll].[pPfSetupGet]...';


GO
ALTER PROCEDURE [sPayroll].[pPfSetupGet]
	 @rId int,
	 @rPayrollYearId int 
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN  
	SELECT [Id]
		  ,[PayrollYearId]
		  ,[PfSalaryLimit]
		  ,[FpsSalaryLimit]
		  ,[EmployeePfPercent]
		  ,[EmployerPfPercent]
		  ,[EmployerFpsPercent]
		  ,[AdminChargesPercent]
		  ,[EdliPercent]
		  ,[InspectionChargesPercent]
		  ,[MaximumAgeForFps]
		  ,[RoundingTypeId]
		  ,[RoundingPrecision]
		  ,[MaximumVpfPercent]
		  ,[MaximumVpfAmount]
		 
	FROM  [sPayroll].[tPfSetup] 
  
	Where  
		 (Id = @rId OR @rId = 0) AND 
		 PayrollYearId = @rPayrollYearId
		
END
GO
PRINT N'Altering [sPayroll].[pProfessionalTaxRangeAdd]...';


GO
ALTER PROCEDURE [sPayroll].[pProfessionalTaxRangeAdd] 
	      
		    @rId int
           ,@rSalary decimal(22,6)
           ,@rTax decimal(22,6)
           ,@rPayrollYearId int
           ,@rOrgGroupId smallint
           ,@rCreatedUserId bigint
           
          
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

	BEGIN TRY
	BEGIN TRANSACTION  
	DECLARE @lNextNumber BIGINT
  
  IF (@rId = 0)
    
    BEGIN	
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sPayroll.tProfessionalTaxRange', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO [sPayroll].[tProfessionalTaxRange]
           (
            [Id]
           ,[Salary]
           ,[Tax]
           ,[PayrollYearId]
           ,[CreatedUserId]
           ,[CreatedDateTime]
           )
     VALUES
           (
            @lNextNumber 
           ,@rSalary 
           ,@rTax 
           ,@rPayrollYearId 
           ,@rCreatedUserId 
           ,sCommon.fGetDate()
           )
         END
    ELSE
		BEGIN    
		     SET @lNextNumber = @rId
		     UPDATE  [sPayroll].[tProfessionalTaxRange]
			   SET  
				   [Salary] = @rSalary
				  ,[Tax] = @rTax 
			 
      
			  Where Id = @rId	     		    
		END        
	SELECT @lNextNumber AS Result	
	COMMIT TRANSACTION
	END TRY
	BEGIN CATCH
	ROLLBACK TRANSACTION
	RAISERROR ('Error Creating Professional Tax Range Detail', -- Message text.
               16, -- Severity.
               1 -- State.
               );
	--SELECT -1 AS RESULT
	END CATCH	
END
GO
PRINT N'Altering [sPayroll].[pProfessionalTaxRangeGet]...';


GO
ALTER PROCEDURE [sPayroll].[pProfessionalTaxRangeGet]
	 @rId int,
	 @rPayrollYearId int
	 
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN  

       SELECT   
           [Id]
		  ,[Salary]
		  ,[Tax]
		 
	   FROM  [sPayroll].[tProfessionalTaxRange]
  
  
Where  
     (Id = @rId OR @rId = 0) AND 
     PayrollYearId = @rPayrollYearId
     
     ORDER BY Salary 
		
END
GO
PRINT N'Altering [sPayroll].[pRemoveProfessionalTaxRange]...';


GO
ALTER PROCEDURE [sPayroll].[pRemoveProfessionalTaxRange]
	 
	 @rId int,
	 @rPayrollYearId int
	 
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN  

       DELETE 		 
	   FROM  [sPayroll].[tProfessionalTaxRange]  
  
Where  
     Id = @rId AND 
     PayrollYearId = @rPayrollYearId 
		
END
GO
PRINT N'Altering [sPayroll].[pRptEmployeePaybillDetail]...';


GO


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

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

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

where 
      (PPE.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
      AND ((EM.Code Like '%' +  @rEmployeeCode + '%' ) OR (@rEmployeeCode = ''))
	  AND ((EM.EmployeeName Like '%' + @rEmployeeName  + '%') OR (@rEmployeeName = ''))
	  AND (EM.DepartmentId = @rDepartmentId OR @rDepartmentId = 0)
	  AND (PP.SalaryMonth = @rForMonth OR @rForMonth = 0)
	  AND (PP.SalaryYear = @rForYear OR @rForYear = 0) 
	  AND ((ESO.PayrollId=@rPayrollId) OR (@rPayrollId=0))
	  AND (ESO.PayrollGroupId = @rPayrollGroupId OR @rPayrollGroupId = 0) 
	  AND (PP.PayrollYearId = @rPayrollYearId OR @rPayrollYearId = 0) 
END
GO
PRINT N'Altering [sPayroll].[pRptEmployeeSalaryDetail]...';


GO

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

BEGIN  
	
	
	DECLARE @lBasicPayElementId int
	SELECT @lBasicPayElementId = Id FROM sPayroll.tPayElement WHERE PayrollId = @rPayrollId AND PayElementDefaultId = 1
	
	SET @rEmployeeCode = sCommon.fSearchStringGet(@rEmployeeCode)
    SET @rEmployeeName = sCommon.fSearchStringGet(@rEmployeeName)

	SELECT 
		EM.EmployeeId, 
		PP.ID As PayProcessId,
		PPE.ID AS PayProcessEmployeeId,
		PP.SalaryMonth,
		PP.SalaryYear,
		EM.EmployeeName,
		EM.Code AS EmployeeCode,
		EM.EmployeeDesignation,
		EM.EmployeeGrade,
		ESO.EPFNumber,
		ESO.PanNumber,
		PPE.TotalEarning,		
		PPE.TotalDeduction,
		PPE.NetAmount,
		(CASE WHEN PayElementId = @lBasicPayElementId then PPE.TotalEarning else 0 END) AS TotalEarningTotal,
		(CASE WHEN PayElementId = @lBasicPayElementId then PPE.TotalDeduction else 0 END) AS TotalDeductionTotal,
		(CASE WHEN PayElementId = @lBasicPayElementId then PPE.NetAmount else 0 END) AS NetAmountTotal,
		PE.Amount As PPEAmount,
		P.Title AS PayElementTitle,
		P.ID AS PayElementId,
		P.PayElementTypeId,
		ISNULL(ESO.BankName,'') AS BankName,
		ISNULL(ESO.AccountNumber,'') AS AccountNumber, 
		MM.Title AS MonthName,
		P.Title AS PayElementName,
		EA.TotalWorkingDays,
		EA.LWP
				
		
		

	FROM sPayroll.tPayProcess PP 
	INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId = PP.ID 
	INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = PPE.EmployeeId 
	INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
	INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID 
	LEFT JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.EmployeeId=PPE.EmployeeId	
	INNER JOIN sHrm.tEmployeeAttendance EA ON EA.EmployeeId=EM.EmployeeId AND EA.ForMonth = PP.SalaryMonth AND EA.ForYear = PP.SalaryYear
	INNER JOIN sCommon.tMonthMaster MM ON MM.Id=PP.SalaryMonth
	

where 
      (EM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
      AND (P.IsObsolete=0)
      AND ((EM.Code Like '%' +  @rEmployeeCode + '%' ) OR (@rEmployeeCode = ''))
	  AND ((EM.EmployeeName Like '%' + @rEmployeeName  + '%') OR (@rEmployeeName = ''))
	  AND (EM.DepartmentId = @rDepartmentId OR @rDepartmentId = 0)
	  AND (PP.SalaryMonth = @rForMonth OR @rForMonth = 0)
	  AND (PP.SalaryYear = @rForYear OR @rForYear = 0)
	  AND ((ESO.PayrollId=@rPayrollId) OR (@rPayrollId=0))
	  AND (ESO.PayrollGroupId = @rPayrollGroupId OR @rPayrollGroupId = 0) 
	  AND (PP.PayrollYearId = @rPayrollYearId OR @rPayrollYearId = 0) 
END
GO
PRINT N'Altering [sPayroll].[pRptPayElementwiseSummaryDetail]...';


GO



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

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

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

	from sPayroll.tPayProcessEmployee PPE
		INNER JOIN sPayroll.tPayProcess PP ON PPE.PayProcessId=PP.ID
		INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
		INNER JOIN sPayroll.tPayElement P ON P.ID=PE.PayElementId
		INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId=PPE.EmployeeId
		LEFT JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.EmployeeId=PPE.EmployeeId	
		INNER JOIN sCommon.tMonthMaster MM ON MM.Id=PP.SalaryMonth
where 
      (PPE.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
      
      AND ((P.ID=@rPayElementId) OR (@rPayElementId=0))
      AND ((EM.Code Like  @rEmployeeCode) OR (@rEmployeeCode = ''))
	  AND ((EM.EmployeeName Like @rEmployeeName ) OR (@rEmployeeName = ''))
	  AND (EM.DepartmentId = @rDepartmentId OR @rDepartmentId = 0)
	  AND (PP.SalaryMonth = @rForMonth OR @rForMonth = 0)
	  AND (PP.SalaryYear = @rForYear OR @rForYear = 0)
	  AND ((ESO.PayrollId=@rPayrollId) OR (@rPayrollId=0))
	  AND (ESO.PayrollGroupId = @rPayrollGroupId OR @rPayrollGroupId = 0) 
	  AND (PP.PayrollYearId = @rPayrollYearId OR @rPayrollYearId = 0) 
END
GO
PRINT N'Altering [sProcurement].[pRptGoodsReturnNote]...';


GO
ALTER PROCEDURE [sProcurement].[pRptGoodsReturnNote]
	@rOrgGroupId Int,
	@rGRNNo [nvarchar](20) = '',
	@rGRNId [int] = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
BEGIN 
DECLARE @lSumOfTotalAmountReturned DECIMAL(22,  6)
SELECT	DISTINCT


				
			@lSumOfTotalAmountReturned = 
			(SELECT	
			SUM( 
			/**Sub Total Amount Returned Start**/
			--Amount
			(CASE WHEN (GRND.ReceiptQuantity > 0 AND GRNRB.ReturnQuantity < =  GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice / GRND.ReceiptQuantity)* GRNRB.ReturnQuantity)
			WHEN (GRND.ReceiptQuantity > 0 AND GRNRB.ReturnQuantity > GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice/ GRND.ReceiptQuantity)* GRND.ReceiptQuantity)
			ELSE (GRND.NetUnitPrice* GRNRB.ReturnQuantity) END)
			
			--DiscountAmount
			-	 
			(CASE WHEN SIM.IsBatchWiseTracking =  1 THEN				  
				 CAST((CASE WHEN (GRND.ReceiptQuantity > 0 AND GRNRB.ReturnQuantity < =  GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice / GRND.ReceiptQuantity)* GRNRB.ReturnQuantity)
				 WHEN (GRND.ReceiptQuantity > 0 AND GRNRB.ReturnQuantity > GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice/ GRND.ReceiptQuantity)* GRND.ReceiptQuantity)
				 ELSE (GRND.NetUnitPrice* GRNRB.ReturnQuantity) END)	 * (GRND.DiscountPercentage/100)AS DECIMAL(22,  6))
			 ELSE 
				  CAST(((CASE WHEN (GRND.ReceiptQuantity > 0 AND GRNRD.ReturnQuantity <=  GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice / GRND.ReceiptQuantity) * GRNRD.ReturnQuantity)
					WHEN (GRND.ReceiptQuantity > 0 AND GRNRD.ReturnQuantity > GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice / GRND.ReceiptQuantity) * GRND.ReceiptQuantity)
					ELSE ((GRND.NetUnitPrice) * (GRNRD.ReturnQuantity))  END)
					* (GRND.DiscountPercentage/100)) AS DECIMAL(22,  6))	            
			END)	
			
			--Tax Amount = (netUnitPrice - discountAmount) * (TaxRate / 100);
			+
			
			(--Amount
			((CASE WHEN (GRND.ReceiptQuantity > 0 AND GRNRB.ReturnQuantity < =  GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice / GRND.ReceiptQuantity)* GRNRB.ReturnQuantity)
			WHEN (GRND.ReceiptQuantity > 0 AND GRNRB.ReturnQuantity > GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice/ GRND.ReceiptQuantity)* GRND.ReceiptQuantity)
			ELSE (GRND.NetUnitPrice* GRNRB.ReturnQuantity) END)			
			--Disc. Amount
			- 
			(CASE WHEN SIM.IsBatchWiseTracking =  1 THEN
				  CAST(((CASE WHEN (GRND.ReceiptQuantity > 0 AND GRNRB.ReturnQuantity < =  GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice / GRND.ReceiptQuantity)* GRNRB.ReturnQuantity)
					WHEN (GRND.ReceiptQuantity > 0 AND GRNRB.ReturnQuantity > GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice/ GRND.ReceiptQuantity)* GRND.ReceiptQuantity)
					ELSE (GRND.NetUnitPrice* GRNRB.ReturnQuantity) END) * (GRND.DiscountPercentage/100))  AS DECIMAL(22,  6))		
				  ELSE 
				  --CAST((GRNRD.ReturnQuantity * (GRND.DiscountPercentage/100))  AS DECIMAL(22,  6))	
				  CAST(((CASE WHEN (GRND.ReceiptQuantity > 0 AND GRNRD.ReturnQuantity <=  GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice / GRND.ReceiptQuantity) * GRNRD.ReturnQuantity)
					WHEN (GRND.ReceiptQuantity > 0 AND GRNRD.ReturnQuantity > GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice / GRND.ReceiptQuantity) * GRND.ReceiptQuantity)
					ELSE ((GRND.NetUnitPrice) * (GRNRD.ReturnQuantity))  END)
					* (GRND.DiscountPercentage/100)) AS DECIMAL(22,  6))	            
				  END)	
			)
			--TaxRate
			* (GRND.TaxRate/ 100)
			)
			
			--Other Tax Amount
			+ 
			((GRND.OtherTaxAmount/ GRND.ReceiptQuantity) *
			(CASE WHEN (GRND.ReceiptQuantity > 0 AND GRNRB.ReturnQuantity < =  GRND.ReceiptQuantity) THEN (GRNRB.ReturnQuantity)
			WHEN (GRND.ReceiptQuantity > 0 AND GRNRB.ReturnQuantity > GRND.ReceiptQuantity) THEN (GRND.ReceiptQuantity)
			ELSE (GRNRB.ReturnQuantity) END))
			
			--AddOnCharges
			+ 
			(			
			(GRND.AddOnCharges/ GRND.ReceiptQuantity) *
			(CASE WHEN (GRND.ReceiptQuantity > 0 AND GRNRB.ReturnQuantity < =  GRND.ReceiptQuantity) THEN (GRNRB.ReturnQuantity)
			WHEN (GRND.ReceiptQuantity > 0 AND GRNRB.ReturnQuantity > GRND.ReceiptQuantity) THEN (GRND.ReceiptQuantity)
			ELSE (GRNRB.ReturnQuantity) END)
			)	
			/**Sub Total Amount Returned End**/
			
			
			
			----Amount - Disc. Amount  +  Tax Amount  +  Other tax Amount  +  Add ON
			----Amount
			----CAST(
			--((			
			----CAST(
			--CASE WHEN (GRND.ReceiptQuantity > 0 AND GRNRB.ReturnQuantity < =  GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice / GRND.ReceiptQuantity)* GRNRB.ReturnQuantity)
			--WHEN (GRND.ReceiptQuantity > 0 AND GRNRB.ReturnQuantity > GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice/ GRND.ReceiptQuantity)* GRND.ReceiptQuantity)
			--ELSE (GRND.NetUnitPrice* GRNRB.ReturnQuantity) 
			--END 
			----AS DECIMAL(22,  6))
			
			-- -
			-- --Discount Amount
			--(CASE 
			--	  WHEN SIM.IsBatchWiseTracking =  1 THEN
			--	  CAST(
			--	  ((CASE WHEN (GRND.ReceiptQuantity > 0 AND GRNRB.ReturnQuantity < =  GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice / GRND.ReceiptQuantity)* GRNRB.ReturnQuantity)
			--		WHEN (GRND.ReceiptQuantity > 0 AND GRNRB.ReturnQuantity > GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice/ GRND.ReceiptQuantity)* GRND.ReceiptQuantity)
			--		ELSE (GRND.NetUnitPrice* GRNRB.ReturnQuantity) END) * (GRND.DiscountPercentage/100))  
			--		AS DECIMAL(22, 6))		
			--	  ELSE 
			--	  CAST(
			--	  ((CASE WHEN (GRND.ReceiptQuantity > 0 AND GRNRD.ReturnQuantity <=  GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice / GRND.ReceiptQuantity) * GRNRD.ReturnQuantity)
			--		WHEN (GRND.ReceiptQuantity > 0 AND GRNRD.ReturnQuantity > GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice / GRND.ReceiptQuantity) * GRND.ReceiptQuantity)
			--		ELSE ((GRND.NetUnitPrice) * (GRNRD.ReturnQuantity))  END)
			--		* (GRND.DiscountPercentage/100)) 
			--		AS DECIMAL(22,  6)
			--		)	            
			--	  END)	
			--)
			
			--  +  --Tax Amount			
			--((
			--(CASE WHEN (GRND.ReceiptQuantity > 0 AND GRNRB.ReturnQuantity < =  GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice / GRND.ReceiptQuantity)* GRNRB.ReturnQuantity)
			--WHEN (GRND.ReceiptQuantity > 0 AND GRNRB.ReturnQuantity > GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice/ GRND.ReceiptQuantity)* GRND.ReceiptQuantity)
			--ELSE (GRND.NetUnitPrice* GRNRB.ReturnQuantity) END)			
			-- --Disc. Amount
			--- (CASE 
			--	  WHEN SIM.IsBatchWiseTracking =  1 THEN
			--	  --CAST(
			--	  (GRNRB.ReturnQuantity * (GRND.DiscountPercentage/100))  
			--	  --AS DECIMAL(22,  6))		
			--	  ELSE 
			--	  --CAST(
			--	  ((CASE WHEN (GRND.ReceiptQuantity > 0 AND GRNRD.ReturnQuantity <=  GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice / GRND.ReceiptQuantity) * GRNRD.ReturnQuantity)
			--		WHEN (GRND.ReceiptQuantity > 0 AND GRNRD.ReturnQuantity > GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice / GRND.ReceiptQuantity) * GRND.ReceiptQuantity)
			--		ELSE ((GRND.NetUnitPrice) * (GRNRD.ReturnQuantity))  END)
			--		* (GRND.DiscountPercentage/100)) 
			--		--AS DECIMAL(22,  6))	            
			--	  END)	
			--)	
			--* (GRND.TaxRate/ 100))
			
					 
			--  +  --Other tax Amount
			----CASE WHEN (GRND.ReceiptQuantity > 0 AND GRNRD.ReturnQuantity <= GRND.ReceiptQuantity) THEN ((GRNRD.ReturnQuantity/ GRND.ReceiptQuantity) * (GRND.OtherTaxAmount))
			----WHEN (GRND.ReceiptQuantity > 0 AND GRNRD.ReturnQuantity > GRND.ReceiptQuantity) THEN ((GRND.ReceiptQuantity/ GRND.ReceiptQuantity) * (GRND.OtherTaxAmount))
			----ELSE (GRNRD.ReturnQuantity/ GRND.ReceiptQuantity) * (GRND.OtherTaxAmount) END
			----CAST(
			--(			
			--(GRND.OtherTaxAmount/ GRND.ReceiptQuantity) *
			--(CASE WHEN (GRND.ReceiptQuantity > 0 AND GRNRB.ReturnQuantity < =  GRND.ReceiptQuantity) THEN (GRNRB.ReturnQuantity)
			--WHEN (GRND.ReceiptQuantity > 0 AND GRNRB.ReturnQuantity > GRND.ReceiptQuantity) THEN (GRND.ReceiptQuantity)
			--ELSE (GRNRB.ReturnQuantity) END)
			--)
			----AS DECIMAL(22,  6))
			-- +  --Add ON
			 
			----CASE WHEN (GRND.ReceiptQuantity > 0 AND GRNRD.ReturnQuantity <= GRND.ReceiptQuantity) THEN ((GRND.AddOnCharges / GRND.ReceiptQuantity)* GRNRD.ReturnQuantity)
			----WHEN (GRND.ReceiptQuantity > 0 AND GRNRD.ReturnQuantity > GRND.ReceiptQuantity) THEN ((GRND.AddOnCharges / GRND.ReceiptQuantity)* GRND.ReceiptQuantity)
			----ELSE (GRND.AddOnCharges * GRNRD.ReturnQuantity) END 
			----CAST(
			--(			
			--(GRND.AddOnCharges/ GRND.ReceiptQuantity) *
			--(CASE WHEN (GRND.ReceiptQuantity > 0 AND GRNRB.ReturnQuantity < =  GRND.ReceiptQuantity) THEN (GRNRB.ReturnQuantity)
			--WHEN (GRND.ReceiptQuantity > 0 AND GRNRB.ReturnQuantity > GRND.ReceiptQuantity) THEN (GRND.ReceiptQuantity)
			--ELSE (GRNRB.ReturnQuantity) END)
			--)
			----AS DECIMAL(22,  6))
		
			--)
			----AS DECIMAL(22,  6))	
			) 
			
			
						FROM		sProcurement.tGoodsReceiptNoteReturn GRNR
					INNER JOIN sProcurement.tGoodsReceiptNoteReturnDetail GRNRD
						ON GRNRD.GoodsReceiptNoteReturnId =  GRNR.Id AND GRNRD.ReturnQuantity > 0
					INNER JOIN sProcurement.tGoodsReceiptNoteReturnBatch GRNRB
						ON GRNRB.GoodsReceiptNoteReturnDetailId =  GRNRD.Id	AND GRNRB.ReturnQuantity > 0	
					INNER JOIN sProcurement.tGoodsReceiptNote GRN
						ON GRN.Id =  GRNR.GoodsReceiptNoteId
					INNER JOIN sProcurement.tGoodsReceiptNoteDetail GRND
						ON GRND.GoodsReceiptNoteId =  GRN.Id
							AND GRNRD.GoodsReceiptNoteDetailId =  GRND.Id
					INNER JOIN sProcurement.tGoodsReceiptNoteBatch GRNB
						ON GRNB.GoodsReceiptNoteDetailId =  GRND.Id									
							AND GRNRB.GoodsReceiptNoteBatchId =  GRNB.Id
					INNER JOIN sProcurement.tPurchaseOrder PO
						ON GRN.PurchaseOrderId =  PO.Id
					INNER JOIN sProcurement.tVendorMaster VM
						ON VM.Id =  PO.VendorId
					INNER JOIN sIp.tStoreLocationMaster SLM
						ON SLM.Id =  PO.StoreLocationId
					
					INNER JOIN sProcurement.tPurchaseOrderDetail POD
						ON POD.PurchaseOrderId =  PO.Id
						AND POD.Id =  GRND.PurchaseOrderDetailId
					INNER JOIN sIp.tStockItemMaster SIM
						ON SIM.Id =  POD.ItemSourceId
					--INNER JOIN sIp.tBinMaster BM
						--ON BM.Id =  SIM.BinId
					INNER JOIN sIp.tStockItemPurchaseUom SIPU						
						ON SIPU.Id =  POD.StockItemPurchaseUomId 
					INNER JOIN sFinanceCommon.tStockUomMaster SUOM
						ON SUOM.Id =  SIPU.StockUomId
					INNER JOIN sSecurity.tUser U
						ON U.Id =  GRN.CreatedUserId
					--INNER JOIN sFinanceCommon.tCurrencyMaster CM
					--	ON PO.CurrencyId = CM.Id
					INNER JOIN sCommon.tReasonMaster RM
						ON RM.Id = GRNRD.ReasonId
						
					--LEFT JOIN	sCommon.tAreaMaster AM
					--			ON AM.Id =  VM.AreaId
					--LEFT JOIN	sCommon.tCityMaster CiM
					--			ON CiM.Id =  VM.CityId
					--LEFT JOIN	sCommon.tStateMaster SM
					--			ON SM.Id =  VM.StateId
					--LEFT JOIN	sCommon.tCountryMaster CoM
					--			ON CoM.Id =  VM.CountryId
					
			WHERE ((GRNR.Id =  @rGRNId) OR (ISNULL(@rGRNId,  0) =  0))
			AND ((GRNR.Number =  @rGRNNo) OR (ISNULL(@rGRNNo,  '') =  ''))
																	
			)--AS ParamSumOfTotalAmountReturned, 
			SELECT @lSumOfTotalAmountReturned								AS ParamSumOfTotalAmountReturned, 
			sFinanceCommon.fRoundOff(@lSumOfTotalAmountReturned,  1)			AS ParamRoundedSumOfTotalAmountReturned, 
			
				--For Operation
				 GRNR.Id, 
				 GRNRD.Id, 
				 GRNR.Number, 
				 SIM.IsBatchWiseTracking, 
				 GRND.TaxRate, 
				 --For Display 
				 VM.Title								AS VendorName, 
				 ISNULL(VM.StreetOne,  '')							AS StreetOne,  
				 ISNULL(VM.StreetTwo,  '')							AS StreetTwo,   
				 ISNULL(VM.StreetThree,  '')							AS StreetThree,  
				 ISNULL(VM.StreetFour,  '')							AS StreetFour, 
		
				 --ISNULL(AM.Title,  '')								AS AreaTitle, 
				 --ISNULL(CiM.Title,  ' ')								AS CityTitle, 				 			
				 --ISNULL(SM.Title,  '')								AS StateTitle, 
				 --ISNULL(CoM.Title,  '')								AS CountryTitle, 
				  ISNULL(VM.Area,'') AS AreaTitle,
				  ISNULL(VM.City,'') AS CityTitle,
				  ISNULL(VM.Country,'') AS StateTitle,
				  ISNULL(VM.State,'') AS CountryTitle,	      
				  ISNULL(VM.ZipCode,  '')								AS ZipCode, 
				 
				 GRNR.Number 										AS GoodsReturnNo,  				
				 sCommon.fReportDateGet(GRNR.ReturnDate)			AS GoodsReturnDate1,  
				 
				 
				 GRN.Number											AS GrnNo, 
				 sCommon.fReportDateGet(GRN.CreatedDateTime) 		AS GrnDate1, 
				 PO.Number											AS PoNo, 
				 sCommon.fReportDateGet(	PO.CreatedDateTime)   	AS PoDate1, 
				 GRN.DeliveryOrderNumber							AS DoNo, 
				 sCommon.fReportDateGet(GRNR.DeliveryOrderDate)		AS DoDate1, 
				 SLM.Title											AS ReceivingLocation, 							 
				 
				 SIM.Code											AS ItemNo, 
				 SIM.Title											AS ItemName, 
				 SUOM.Title											AS Uom, 
				 SIPU.ConversionFactor								AS ConversionFactor, 
				(CASE 
					WHEN SIM.IsBatchWiseTracking =  1 THEN
						GRNRB.ReturnQuantity
					ELSE 
						GRNRD.ReturnQuantity
					END)											AS ReturnedQuantity, 
				 (CASE 
					WHEN SIM.IsBatchWiseTracking =  1 THEN
						GRNB.ReceiptBonusQuantity
					ELSE
						GRND.ReceiptBonusQuantity
					END)											AS BonusQty, 
				 (CASE 
					WHEN SIM.IsBatchWiseTracking =  1 THEN
						GRNB.Number
					ELSE
						''
					END)											AS BatchNo, 
				 (CASE 
					WHEN SIM.IsBatchWiseTracking =  1 THEN
						sCommon.fReportDateGet(GRNB.ExpiryDate)	
					ELSE
						''
					END)											AS ExpiryDate1, 
				 ''											AS BinNo, --BM.Code 
				 --CM.Code											AS CurrencyCode,
				 --CM.Title											AS CurrencTitle,
				 RM.Title											AS ReasonTitle,
				 
				 (SELECT ((SUM(ReceiptQuantity)  +  SUM(ReceiptBonusQuantity)) - SUM(ReturnedQuantity)) FROM sProcurement.tGoodsReceiptNoteBatch
				WHERE GoodsReceiptNoteDetailId = GRND.Id) AS BalanceQuantity,			
		
			(SELECT ((SUM(ReceiptQuantity)  +  SUM(ReceiptBonusQuantity)) - SUM(ReturnedQuantity)) FROM sProcurement.tGoodsReceiptNoteBatch
				WHERE GoodsReceiptNoteDetailId = GRND.Id) AS BalanceQuantity,			
		
			CASE WHEN GRND.ReceiptQuantity > 0 THEN (GRND.NetUnitPrice / GRND.ReceiptQuantity)
			ELSE GRND.NetUnitPrice END
			AS UnitPrice,

			(CASE WHEN (GRND.ReceiptQuantity > 0 AND GRNRB.ReturnQuantity < =  GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice / GRND.ReceiptQuantity)* GRNRB.ReturnQuantity)
			WHEN (GRND.ReceiptQuantity > 0 AND GRNRB.ReturnQuantity > GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice/ GRND.ReceiptQuantity)* GRND.ReceiptQuantity)
			ELSE (GRND.NetUnitPrice* GRNRB.ReturnQuantity) END) AS Amount,
				 
				 
				 
				 (CASE 
				  WHEN SIM.IsBatchWiseTracking =  1 THEN
				  --CAST((GRNRB.ReturnQuantity * (GRND.DiscountPercentage/100))  AS DECIMAL(22,  2))	
				  CAST((CASE WHEN (GRND.ReceiptQuantity > 0 AND GRNRB.ReturnQuantity < =  GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice / GRND.ReceiptQuantity)* GRNRB.ReturnQuantity)
					WHEN (GRND.ReceiptQuantity > 0 AND GRNRB.ReturnQuantity > GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice/ GRND.ReceiptQuantity)* GRND.ReceiptQuantity)
					ELSE (GRND.NetUnitPrice* GRNRB.ReturnQuantity) END)	 * (GRND.DiscountPercentage/100)AS DECIMAL(22,  6))
				  ELSE 

				  CAST(((CASE WHEN (GRND.ReceiptQuantity > 0 AND GRNRD.ReturnQuantity <=  GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice / GRND.ReceiptQuantity) * GRNRD.ReturnQuantity)
					WHEN (GRND.ReceiptQuantity > 0 AND GRNRD.ReturnQuantity > GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice / GRND.ReceiptQuantity) * GRND.ReceiptQuantity)
					ELSE ((GRND.NetUnitPrice) * (GRNRD.ReturnQuantity))  END)
					* (GRND.DiscountPercentage/100)) AS DECIMAL(22,  6))	            
				  END)																								AS  DiscountAmount, 
			
			--Tax Amount = (netUnitPrice - discountAmount) * (TaxRate / 100);
			(
			--Amount
			(CASE WHEN (GRND.ReceiptQuantity > 0 AND GRNRB.ReturnQuantity < =  GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice / GRND.ReceiptQuantity)* GRNRB.ReturnQuantity)
			WHEN (GRND.ReceiptQuantity > 0 AND GRNRB.ReturnQuantity > GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice/ GRND.ReceiptQuantity)* GRND.ReceiptQuantity)
			ELSE (GRND.NetUnitPrice* GRNRB.ReturnQuantity) END)			
			 --Disc. Amount
			- (CASE 
				  WHEN SIM.IsBatchWiseTracking =  1 THEN
				  CAST(((CASE WHEN (GRND.ReceiptQuantity > 0 AND GRNRB.ReturnQuantity < =  GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice / GRND.ReceiptQuantity)* GRNRB.ReturnQuantity)
					WHEN (GRND.ReceiptQuantity > 0 AND GRNRB.ReturnQuantity > GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice/ GRND.ReceiptQuantity)* GRND.ReceiptQuantity)
					ELSE (GRND.NetUnitPrice* GRNRB.ReturnQuantity) END) * (GRND.DiscountPercentage/100))  AS DECIMAL(22,  6))		
				  ELSE 
				  --CAST((GRNRD.ReturnQuantity * (GRND.DiscountPercentage/100))  AS DECIMAL(22,  6))	
				  CAST(((CASE WHEN (GRND.ReceiptQuantity > 0 AND GRNRD.ReturnQuantity <=  GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice / GRND.ReceiptQuantity) * GRNRD.ReturnQuantity)
					WHEN (GRND.ReceiptQuantity > 0 AND GRNRD.ReturnQuantity > GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice / GRND.ReceiptQuantity) * GRND.ReceiptQuantity)
					ELSE ((GRND.NetUnitPrice) * (GRNRD.ReturnQuantity))  END)
					* (GRND.DiscountPercentage/100)) AS DECIMAL(22,  6))	            
				  END)	
			)	
			--TaxRate
			* (GRND.TaxRate/ 100)
			AS TaxAmount,
				 
			/*Old Tax Amount	 
				 
			--(netUnitPrice - discountAmount) * (TaxRate / 100);
			--NetUnitPrice
			(CASE WHEN (GRND.ReceiptQuantity > 0 AND GRNRD.ReturnQuantity <= GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice / GRND.ReceiptQuantity)* GRNRD.ReturnQuantity)
			WHEN (GRND.ReceiptQuantity > 0 AND GRNRD.ReturnQuantity > GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice/ GRND.ReceiptQuantity)* GRND.ReceiptQuantity)
			ELSE (GRND.NetUnitPrice* GRNRD.ReturnQuantity) END
			- --Disc. Amount
			(CASE WHEN (GRND.ReceiptQuantity > 0 AND GRNRD.ReturnQuantity <= GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice / GRND.ReceiptQuantity) * GRNRD.ReturnQuantity)
			WHEN (GRND.ReceiptQuantity > 0 AND GRNRD.ReturnQuantity > GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice / GRND.ReceiptQuantity) * GRND.ReceiptQuantity)
			ELSE ((GRND.NetUnitPrice) * (GRNRD.ReturnQuantity))  END)
			* (GRND.DiscountPercentage/100)
			)
			* --(TaxRate / 100)
			(GRND.TaxRate/ 100)
			AS TaxAmount,
			Old Tax Amount*/
			
			--Other Tax Amount
			--CAST(
			(			
			(GRND.OtherTaxAmount/ GRND.ReceiptQuantity) *
			(CASE WHEN (GRND.ReceiptQuantity > 0 AND GRNRB.ReturnQuantity < =  GRND.ReceiptQuantity) THEN (GRNRB.ReturnQuantity)
			WHEN (GRND.ReceiptQuantity > 0 AND GRNRB.ReturnQuantity > GRND.ReceiptQuantity) THEN (GRND.ReceiptQuantity)
			ELSE (GRNRB.ReturnQuantity) END)
			)
			--AS DECIMAL(22,  6))				
			AS OtherTaxAmount,
			
				
			/*Old Other Tax Amount	 
			(
			CASE WHEN (GRND.ReceiptQuantity > 0 AND GRNRD.ReturnQuantity <=  GRND.ReceiptQuantity) THEN ((GRNRD.ReturnQuantity/ GRND.ReceiptQuantity) * (GRND.OtherTaxAmount))
			WHEN (GRND.ReceiptQuantity > 0 AND GRNRD.ReturnQuantity > GRND.ReceiptQuantity) THEN ((GRND.ReceiptQuantity/ GRND.ReceiptQuantity) * (GRND.OtherTaxAmount))
			ELSE (GRNRD.ReturnQuantity/ GRND.ReceiptQuantity) 
			* (GRND.OtherTaxAmount) 
			END)							
			AS OtherTaxAmount, 
			Old Other Tax Amount*/

			-- --Amount - Disc. Amount  +  Tax Amount  +  Other tax Amount  +  Add ON
			-- --Amount
			----CAST(
			--( 
					
			
			----(CASE WHEN (GRND.ReceiptQuantity > 0 AND GRNRB.ReturnQuantity < =  GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice / GRND.ReceiptQuantity)* GRNRB.ReturnQuantity)
			----WHEN (GRND.ReceiptQuantity > 0 AND GRNRB.ReturnQuantity > GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice/ GRND.ReceiptQuantity)* GRND.ReceiptQuantity)
			----ELSE (GRND.NetUnitPrice* GRNRB.ReturnQuantity) END
			--(
			
			----CAST(
			--CASE WHEN (GRND.ReceiptQuantity > 0 AND GRNRB.ReturnQuantity < =  GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice / GRND.ReceiptQuantity)* GRNRB.ReturnQuantity)
			--WHEN (GRND.ReceiptQuantity > 0 AND GRNRB.ReturnQuantity > GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice/ GRND.ReceiptQuantity)* GRND.ReceiptQuantity)
			--ELSE (GRND.NetUnitPrice* GRNRB.ReturnQuantity) 
			--END 
			----AS DECIMAL(22,  6))
			
			-- -
			-- --Discount Amount
			----(CASE WHEN (GRND.ReceiptQuantity > 0 AND GRNRD.ReturnQuantity <= GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice / GRND.ReceiptQuantity) * GRNRD.ReturnQuantity)
			----WHEN (GRND.ReceiptQuantity > 0 AND GRNRD.ReturnQuantity > GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice / GRND.ReceiptQuantity) * GRND.ReceiptQuantity)
			----ELSE ((GRND.NetUnitPrice) * (GRNRD.ReturnQuantity))  END)
			----* (GRND.DiscountPercentage/100)
			--(CASE 
			--	  WHEN SIM.IsBatchWiseTracking =  1 THEN
			--	  --CAST(
			--	  ((CASE WHEN (GRND.ReceiptQuantity > 0 AND GRNRB.ReturnQuantity < =  GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice / GRND.ReceiptQuantity)* GRNRB.ReturnQuantity)
			--		WHEN (GRND.ReceiptQuantity > 0 AND GRNRB.ReturnQuantity > GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice/ GRND.ReceiptQuantity)* GRND.ReceiptQuantity)
			--		ELSE (GRND.NetUnitPrice* GRNRB.ReturnQuantity) END) * (GRND.DiscountPercentage/100)) 
			--		-- AS DECIMAL(22,  6))		
			--	  ELSE 
			--	  --CAST((GRNRD.ReturnQuantity * (GRND.DiscountPercentage/100))  AS DECIMAL(22,  6))	
			--	  --CAST(
			--	  ((CASE WHEN (GRND.ReceiptQuantity > 0 AND GRNRD.ReturnQuantity <=  GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice / GRND.ReceiptQuantity) * GRNRD.ReturnQuantity)
			--		WHEN (GRND.ReceiptQuantity > 0 AND GRNRD.ReturnQuantity > GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice / GRND.ReceiptQuantity) * GRND.ReceiptQuantity)
			--		ELSE ((GRND.NetUnitPrice) * (GRNRD.ReturnQuantity))  END)
			--		* (GRND.DiscountPercentage/100)) 
			--		--AS DECIMAL(22,  6))	            
			--	  END)	
			--)
			
			--  +  --Tax Amount			
			--((
			--(CASE WHEN (GRND.ReceiptQuantity > 0 AND GRNRB.ReturnQuantity < =  GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice / GRND.ReceiptQuantity)* GRNRB.ReturnQuantity)
			--WHEN (GRND.ReceiptQuantity > 0 AND GRNRB.ReturnQuantity > GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice/ GRND.ReceiptQuantity)* GRND.ReceiptQuantity)
			--ELSE (GRND.NetUnitPrice* GRNRB.ReturnQuantity) END)			
			-- --Disc. Amount
			--- (CASE 
			--	  WHEN SIM.IsBatchWiseTracking =  1 THEN
			--	  --CAST(
			--	  (GRNRB.ReturnQuantity * (GRND.DiscountPercentage/100))  
			--	  --AS DECIMAL(22,  6))		
			--	  ELSE 
				  	
			--	  --CAST(
			--	  ((CASE WHEN (GRND.ReceiptQuantity > 0 AND GRNRD.ReturnQuantity <=  GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice / GRND.ReceiptQuantity) * GRNRD.ReturnQuantity)
			--		WHEN (GRND.ReceiptQuantity > 0 AND GRNRD.ReturnQuantity > GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice / GRND.ReceiptQuantity) * GRND.ReceiptQuantity)
			--		ELSE ((GRND.NetUnitPrice) * (GRNRD.ReturnQuantity))  END)
			--		* (GRND.DiscountPercentage/100)) 
			--		--AS DECIMAL(22,  6))	            
			--	  END)	
			--)	
			--* (GRND.TaxRate/ 100))
			
					 
			--  +  --Other tax Amount
			----CASE WHEN (GRND.ReceiptQuantity > 0 AND GRNRD.ReturnQuantity <= GRND.ReceiptQuantity) THEN ((GRNRD.ReturnQuantity/ GRND.ReceiptQuantity) * (GRND.OtherTaxAmount))
			----WHEN (GRND.ReceiptQuantity > 0 AND GRNRD.ReturnQuantity > GRND.ReceiptQuantity) THEN ((GRND.ReceiptQuantity/ GRND.ReceiptQuantity) * (GRND.OtherTaxAmount))
			----ELSE (GRNRD.ReturnQuantity/ GRND.ReceiptQuantity) * (GRND.OtherTaxAmount) END
			----CAST(
			--(			
			--(GRND.OtherTaxAmount/ GRND.ReceiptQuantity) *
			--(CASE WHEN (GRND.ReceiptQuantity > 0 AND GRNRB.ReturnQuantity < =  GRND.ReceiptQuantity) THEN (GRNRB.ReturnQuantity)
			--WHEN (GRND.ReceiptQuantity > 0 AND GRNRB.ReturnQuantity > GRND.ReceiptQuantity) THEN (GRND.ReceiptQuantity)
			--ELSE (GRNRB.ReturnQuantity) END)
			--)
			----AS DECIMAL(22,  6))
			-- +  --Add ON
			 
			----CASE WHEN (GRND.ReceiptQuantity > 0 AND GRNRD.ReturnQuantity <= GRND.ReceiptQuantity) THEN ((GRND.AddOnCharges / GRND.ReceiptQuantity)* GRNRD.ReturnQuantity)
			----WHEN (GRND.ReceiptQuantity > 0 AND GRNRD.ReturnQuantity > GRND.ReceiptQuantity) THEN ((GRND.AddOnCharges / GRND.ReceiptQuantity)* GRND.ReceiptQuantity)
			----ELSE (GRND.AddOnCharges * GRNRD.ReturnQuantity) END 
			----CAST(
			--(			
			--(GRND.AddOnCharges/ GRND.ReceiptQuantity) *
			--(CASE WHEN (GRND.ReceiptQuantity > 0 AND GRNRB.ReturnQuantity < =  GRND.ReceiptQuantity) THEN (GRNRB.ReturnQuantity)
			--WHEN (GRND.ReceiptQuantity > 0 AND GRNRB.ReturnQuantity > GRND.ReceiptQuantity) THEN (GRND.ReceiptQuantity)
			--ELSE (GRNRB.ReturnQuantity) END)
			--)
			----AS DECIMAL(22,  6))
			
			--)
			----AS DECIMAL(22,  6)) 
			--AS TotalAmountReturned1,
			
			/* Old AddOnCharges
			ISNULL((CASE WHEN (GRND.ReceiptQuantity > 0 AND GRNRD.ReturnQuantity <=  GRND.ReceiptQuantity) THEN ((GRND.AddOnCharges / GRND.ReceiptQuantity)* GRNRD.ReturnQuantity)
			WHEN (GRND.ReceiptQuantity > 0 AND GRNRD.ReturnQuantity > GRND.ReceiptQuantity) THEN ((GRND.AddOnCharges / GRND.ReceiptQuantity)* GRND.ReceiptQuantity)
			ELSE (GRND.AddOnCharges * GRNRD.ReturnQuantity) END), 0)																AS AddOnCharges, 
			*/
				
			(			
			(GRND.AddOnCharges/ GRND.ReceiptQuantity) *
			(CASE WHEN (GRND.ReceiptQuantity > 0 AND GRNRB.ReturnQuantity < =  GRND.ReceiptQuantity) THEN (GRNRB.ReturnQuantity)
			WHEN (GRND.ReceiptQuantity > 0 AND GRNRB.ReturnQuantity > GRND.ReceiptQuantity) THEN (GRND.ReceiptQuantity)
			ELSE (GRNRB.ReturnQuantity) END)
			)	
			AS AddOnCharges, 
			
			/**Sub Total Amount Returned Start**/
			--Amount
			(CASE WHEN (GRND.ReceiptQuantity > 0 AND GRNRB.ReturnQuantity < =  GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice / GRND.ReceiptQuantity)* GRNRB.ReturnQuantity)
			WHEN (GRND.ReceiptQuantity > 0 AND GRNRB.ReturnQuantity > GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice/ GRND.ReceiptQuantity)* GRND.ReceiptQuantity)
			ELSE (GRND.NetUnitPrice* GRNRB.ReturnQuantity) END)
			
			--DiscountAmount
			-	 
			(CASE WHEN SIM.IsBatchWiseTracking =  1 THEN				  
				 CAST((CASE WHEN (GRND.ReceiptQuantity > 0 AND GRNRB.ReturnQuantity < =  GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice / GRND.ReceiptQuantity)* GRNRB.ReturnQuantity)
				 WHEN (GRND.ReceiptQuantity > 0 AND GRNRB.ReturnQuantity > GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice/ GRND.ReceiptQuantity)* GRND.ReceiptQuantity)
				 ELSE (GRND.NetUnitPrice* GRNRB.ReturnQuantity) END)	 * (GRND.DiscountPercentage/100)AS DECIMAL(22,  6))
			 ELSE 
				  CAST(((CASE WHEN (GRND.ReceiptQuantity > 0 AND GRNRD.ReturnQuantity <=  GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice / GRND.ReceiptQuantity) * GRNRD.ReturnQuantity)
					WHEN (GRND.ReceiptQuantity > 0 AND GRNRD.ReturnQuantity > GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice / GRND.ReceiptQuantity) * GRND.ReceiptQuantity)
					ELSE ((GRND.NetUnitPrice) * (GRNRD.ReturnQuantity))  END)
					* (GRND.DiscountPercentage/100)) AS DECIMAL(22,  6))	            
			END)	
			
			--Tax Amount = (netUnitPrice - discountAmount) * (TaxRate / 100);
			+
			
			(--Amount
			((CASE WHEN (GRND.ReceiptQuantity > 0 AND GRNRB.ReturnQuantity < =  GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice / GRND.ReceiptQuantity)* GRNRB.ReturnQuantity)
			WHEN (GRND.ReceiptQuantity > 0 AND GRNRB.ReturnQuantity > GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice/ GRND.ReceiptQuantity)* GRND.ReceiptQuantity)
			ELSE (GRND.NetUnitPrice* GRNRB.ReturnQuantity) END)			
			--Disc. Amount
			- 
			(CASE WHEN SIM.IsBatchWiseTracking =  1 THEN
				  CAST(((CASE WHEN (GRND.ReceiptQuantity > 0 AND GRNRB.ReturnQuantity < =  GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice / GRND.ReceiptQuantity)* GRNRB.ReturnQuantity)
					WHEN (GRND.ReceiptQuantity > 0 AND GRNRB.ReturnQuantity > GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice/ GRND.ReceiptQuantity)* GRND.ReceiptQuantity)
					ELSE (GRND.NetUnitPrice* GRNRB.ReturnQuantity) END) * (GRND.DiscountPercentage/100))  AS DECIMAL(22,  6))		
				  ELSE 
				  --CAST((GRNRD.ReturnQuantity * (GRND.DiscountPercentage/100))  AS DECIMAL(22,  6))	
				  CAST(((CASE WHEN (GRND.ReceiptQuantity > 0 AND GRNRD.ReturnQuantity <=  GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice / GRND.ReceiptQuantity) * GRNRD.ReturnQuantity)
					WHEN (GRND.ReceiptQuantity > 0 AND GRNRD.ReturnQuantity > GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice / GRND.ReceiptQuantity) * GRND.ReceiptQuantity)
					ELSE ((GRND.NetUnitPrice) * (GRNRD.ReturnQuantity))  END)
					* (GRND.DiscountPercentage/100)) AS DECIMAL(22,  6))	            
				  END)	
			)
			--TaxRate
			* (GRND.TaxRate/ 100)
			)
			
			--Other Tax Amount
			+ 
			((GRND.OtherTaxAmount/ GRND.ReceiptQuantity) *
			(CASE WHEN (GRND.ReceiptQuantity > 0 AND GRNRB.ReturnQuantity < =  GRND.ReceiptQuantity) THEN (GRNRB.ReturnQuantity)
			WHEN (GRND.ReceiptQuantity > 0 AND GRNRB.ReturnQuantity > GRND.ReceiptQuantity) THEN (GRND.ReceiptQuantity)
			ELSE (GRNRB.ReturnQuantity) END))
			
			--AddOnCharges
			+ 
			(			
			(GRND.AddOnCharges/ GRND.ReceiptQuantity) *
			(CASE WHEN (GRND.ReceiptQuantity > 0 AND GRNRB.ReturnQuantity < =  GRND.ReceiptQuantity) THEN (GRNRB.ReturnQuantity)
			WHEN (GRND.ReceiptQuantity > 0 AND GRNRB.ReturnQuantity > GRND.ReceiptQuantity) THEN (GRND.ReceiptQuantity)
			ELSE (GRNRB.ReturnQuantity) END)
			)	
			
			AS TotalAmountReturned1,
			/**Sub Total Amount Returned End**/
				
		
				GRNR.Remark AS Remarks, 			 
				U.DisplayTitle AS GeneratedBy

							  
		FROM		sProcurement.tGoodsReceiptNoteReturn GRNR
					INNER JOIN sProcurement.tGoodsReceiptNoteReturnDetail GRNRD
						ON GRNRD.GoodsReceiptNoteReturnId =  GRNR.Id  AND GRNRD.ReturnQuantity > 0
					INNER JOIN sProcurement.tGoodsReceiptNoteReturnBatch GRNRB
						ON GRNRB.GoodsReceiptNoteReturnDetailId =  GRNRD.Id	AND GRNRB.ReturnQuantity > 0	
					INNER JOIN sProcurement.tGoodsReceiptNote GRN
						ON GRN.Id =  GRNR.GoodsReceiptNoteId
					INNER JOIN sProcurement.tGoodsReceiptNoteDetail GRND
						ON GRND.GoodsReceiptNoteId =  GRN.Id
							AND GRNRD.GoodsReceiptNoteDetailId =  GRND.Id
					INNER JOIN sProcurement.tGoodsReceiptNoteBatch GRNB
						ON GRNB.GoodsReceiptNoteDetailId =  GRND.Id									
							AND GRNRB.GoodsReceiptNoteBatchId =  GRNB.Id
					INNER JOIN sProcurement.tPurchaseOrder PO
						ON GRN.PurchaseOrderId =  PO.Id
					INNER JOIN sProcurement.tVendorMaster VM
						ON VM.Id =  PO.VendorId
					INNER JOIN sIp.tStoreLocationMaster SLM
						ON SLM.Id =  PO.StoreLocationId
					
					INNER JOIN sProcurement.tPurchaseOrderDetail POD
						ON POD.PurchaseOrderId =  PO.Id
						AND POD.Id =  GRND.PurchaseOrderDetailId
					INNER JOIN sIp.tStockItemMaster SIM
						ON SIM.Id =  POD.ItemSourceId
					--LEFT JOIN sIp.tBinMaster BM
						--ON BM.Id =  SIM.BinId
					INNER JOIN sIp.tStockItemPurchaseUom SIPU						
						ON SIPU.Id =  POD.StockItemPurchaseUomId 
					INNER JOIN sFinanceCommon.tStockUomMaster SUOM
						ON SUOM.Id =  SIPU.StockUomId
					INNER JOIN sSecurity.tUser U
						ON U.Id =  GRN.CreatedUserId
					--INNER JOIN sFinanceCommon.tCurrencyMaster CM
					--	ON PO.CurrencyId = CM.Id
					INNER JOIN sCommon.tReasonMaster RM
						ON RM.Id = GRNRD.ReasonId
					
					--LEFT JOIN	sCommon.tAreaMaster AM
					--			ON AM.Id =  VM.AreaId
					--LEFT JOIN	sCommon.tCityMaster CiM
					--			ON CiM.Id =  VM.CityId
					--LEFT JOIN	sCommon.tStateMaster SM
					--			ON SM.Id =  VM.StateId
					--LEFT JOIN	sCommon.tCountryMaster CoM
					--			ON CoM.Id =  VM.CountryId
					
			WHERE ((GRNR.Id =  @rGRNId) OR (ISNULL(@rGRNId,  0) =  0))
				AND ((GRNR.Number =  @rGRNNo) OR (ISNULL(@rGRNNo,  '') =  ''))
				AND GRNR.OrgGroupId = @rOrgGroupId
		
			ORDER BY GRNRD.Id ASC 
END
GO
PRINT N'Altering [sSecurity].[pModulePermissionReset]...';


GO
ALTER PROCEDURE [sSecurity].[pModulePermissionReset]
          
            @rOrgGroupId smallint,
            @rIsPortal bit  
       
AS
SET NOCOUNT ON
BEGIN
	
	BEGIN TRY
	
	BEGIN TRANSACTION	
	
	DELETE FROM sSecurity.tModulePermission WHERE OrgGroupId=@rOrgGroupId
	
	IF(@rIsPortal=1)
	BEGIN
		INSERT INTO sSecurity.tModulePermission 
		SELECT @rOrgGroupId,Id FROM sCommon.tModuleMaster WHERE IsObsolete=0 
		AND Id IN
		(
-- 	select ID , ', --' + Title from scommon.tModuleMaster order by id	
	1	, --Security
	2	, --Alert
	3	, --Configuration
	135	, --Employee
	136	, --Payroll
	151	, --Setup
	152	, --Student
	153	, --Attendance
	154	, --Fee
	155	, --Timetable
	156	, --Assessment General
	162	, --Communication
	209	, --Activity
	210	, --Library
	211	, --EExam
	--218	, --Placement
	219	, --Gallery
	220	, --Portal Academic
	222	, --Employee Attendance
	225	 --Academic
		 
		)
	END
	ELSE
	BEGIN
		INSERT INTO sSecurity.tModulePermission 
		SELECT @rOrgGroupId,Id FROM sCommon.tModuleMaster WHERE IsObsolete=0 
		AND Id NOT IN
		(
		 
4	,	--Globalization
91	,	--Utilities
106	,	--Order Entry
120	,	--Procurement
137	,	--Asset Management
140	,	--Audit Trail
162	,	--Communication
204	,	--Support
208	,	--BI
210	,	--Library
211	,	--EExam
212	,	--Accounting
213	,	--OMR
214	,	--Biometric
216	,	--Health
218	,	--Placement
219	,	--Gallery
220		--Portal Academic
	
		)
	END
	SELECT 1 AS Result
	COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
	
END
GO
PRINT N'Altering [sSecurity].[pResetParentPermission]...';


GO
ALTER PROCEDURE [sSecurity].[pResetParentPermission]
	
	@rOrgGroupId smallint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN	

BEGIN TRY
BEGIN TRANSACTION	

	DELETE FROM sSecurity.tPermission WHERE OrgGroupId=@rOrgGroupId AND RoleId=sCommon.fGetIntIdForOrg(22,@rOrgGroupId)
	
	INSERT INTO sSecurity.tPermission
		(
			TaskId, 
			RoleId, 
			Permission, 
			IsObsolete, 
			CreatedUserId, 
			CreatedDateTime, 
			UpdatedUserId, 
			UpdatedDateTime,
			OrgGroupId
		)
	SELECT  
			Id,
			sCommon.fGetIntIdForOrg(22,@rOrgGroupId),
			AvailablePermission,
			0,
			1,
			sCommon.fGetDate(),
			1,
			sCommon.fGetDate(),
			@rOrgGroupId
	FROM 
		sSecurity.tTask
	WHERE ID IN(
9128	, -- Video Viewer
9137	, -- Link Viewer
10187	, -- My Profile
20054	, -- Calendar
20085	, -- Circular List
20088	, -- Query List
20089	, -- New Query
20091	, -- Circular View
20093	, -- Assignment List
20095	, -- Assignment View
20097	, -- View Query
20099	, -- Blog List
20101	, -- Blog View
20104	, -- News List
20106	, -- News View
20109	, -- Discussion List
20110	, -- Discussion
20111	, -- Discussion View
20112	, -- Discussion Group
20114	, -- Group Members
20117	, -- Poll View
20118	, -- Poll Vote
20130	, -- Behaviour List
20172	, -- View Task
20180	, -- Student View Result
20182	, -- View Book List
20183	, -- View Category
20190	, -- View Placement
20191	, -- Available Tests
20198	, -- My Event List
20204	, -- My Poll
20209	, -- My Activity List
20241	, -- My Attendance
20563	, -- My Classwork
20564	, -- My Result
20565	, -- My Fee
20566	 -- My Book List
				)
		SELECT 1 AS RESULT
		
		
	--	SELECT TaskId FROM sSecurity.tScreen WHERE ScreenGroupId = 114 
	--	SELECT TaskId FROM sSecurity.tScreen WHERE ScreenGroupId = 172 
COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END
GO
PRINT N'Altering [sSecurity].[pResetPortalUserPermission]...';


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

BEGIN TRY
BEGIN TRANSACTION	

	IF @rUserType = 'AdminPortal'
	BEGIN
		DELETE FROM sSecurity.tPermission WHERE OrgGroupId=@rOrgGroupId AND RoleId=sCommon.fGetIntIdForOrg(2,@rOrgGroupId)
	END
	ELSE IF @rUserType = 'ParentPortal'
	BEGIN
		DELETE FROM sSecurity.tPermission WHERE OrgGroupId=@rOrgGroupId AND RoleId=sCommon.fGetIntIdForOrg(22,@rOrgGroupId)
	END
	ELSE IF @rUserType = 'EmployeePortal'
	BEGIN
		DELETE FROM sSecurity.tPermission WHERE OrgGroupId=@rOrgGroupId AND RoleId=sCommon.fGetIntIdForOrg(10,@rOrgGroupId)
	END
	ELSE IF @rUserType = 'OrganizationPortalTask'
	BEGIN
		DELETE FROM sSecurity.tOrganizationTask WHERE OrgGroupId=@rOrgGroupId 
	END

	 IF @rUserType = 'OrganizationPortalTask'
	BEGIN
	-- 1	, --Security	
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,139,23) --User
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,141,6)  -- Assign Permission
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,142,23) -- Login
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,245,6)  -- Change Password
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20158,3) -- Change Organization
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20175,2) -- Manage Student Login
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20176,2) -- Manage Employee Login
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20250,2) -- Manage Multi Child Login
		
	--	2	, --Alert	
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20170,6) -- Send Predefine Alert
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20195,2) -- SMS History
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20201,2) -- Email Configuration
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20215,2) -- Event Template
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20216,2) -- Send Custom Alert
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20221,2) -- Send Alert Others
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20297,2) -- Custom Template Master
	-- 3	, --Configuration	
		
	-- 135	, --Employee	
	    INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,10097,2) -- Employee List
	    INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,10097,2) -- Employee List
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20222,2) -- Employee Profile
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20223,2) -- View Employee Profile
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20246,2) -- My Profile
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20249,2) -- Employee List
				
				
	--- 151	, --Setup		
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20001,2) -- Organization Master
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20002,2) -- Department Master
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20003,2) -- Class Master
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20004,2) -- Division Master
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20005,2) -- Term Master
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20006,2) -- Subject Master
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20007,2) -- Batch Master
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20008,2) -- Class Subject Master
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20055,2) -- Batch Class
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20285,2) -- Organization Group Batch Master
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20323,2) -- Upload Organization Photo
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20407,2) -- Organization Group Master
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20545,2) -- Org. Main Group Master
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20546,2) -- Org. Sub Group Master	
		
	 --	152	, --Student
		
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20021,2) -- Student List
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,10187,2) -- My Profile
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20147,2) -- Student Custom Search
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20207,2) -- Student Full
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20312,2) -- Student Full Profile
		
	--		153	, --Attendance	
			
	 --154	, --Fee
	 INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20565,2) -- My Fee
	 
	 -- 155	, --Timetable
	 -- 156	, --Assessment General
	 INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20564,2) -- My Result
	 
	-- 162	, --Communication
	
			INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20179,31) -- Upload Result
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20083,31) -- Query Category Master
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20086,31) -- Circular
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20094,31) -- Assignment
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20100,31) -- New blogs
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20105,31) -- News
		--INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20110,31) -- Discussion
		--INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20112,31) -- Discussion Group
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20116,31) -- Poll
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20130,31) -- Behaviour List
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20204,2) -- My Poll
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20180,2) -- Student View Result
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20181,2) -- Employee View Result
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20182,2) -- View Book List
		--INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20171,7) -- Assign Task
		--INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20172,2) -- View Task
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20241,2) -- Student View Presence
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20085,2) -- Circular List
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20088,2) -- Query List
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20089,31) --New Query
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20091,2) -- Circular View
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20093,2) -- Assignment List
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20097,31) -- View Query
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20099,2) -- Blog List
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20101,2) -- Blog View
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20102,2) -- My Blog
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20103,2) -- Blog Activity
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20104,2) -- News List
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20106,2) -- News View
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20107,2) -- Query Queue
		--INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20109,31) -- Discussion List
		--INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20111,2) --  Discussion View
		--INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20113,2) -- Discussion Activities
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20114,2) -- Group Member
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20115,2) -- Poll List
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20117,2) -- Poll View
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20118,2) -- Poll Vote
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20125,31) -- Behaviour type Master
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20126,31) -- Behaviour Entry
	-- 209	, --Activity
	
			INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20154,3) -- Calendar
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20156,31) -- Event Schedule
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20158,31) -- Activity Type Master
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20159,31) -- Activity
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20151,31) -- House Master
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20152,31) -- Club Master
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20153,22) -- Assign Club
		--INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20187,31) -- Placement
		--INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20188,31) -- Placement Invite
		--INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20189,31) -- Placement Registration
		--INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20190,2) -- View Palcement
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20197,2) -- Enrollment List
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20198,2) -- My Event List
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20199,7) -- View Event
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20209,2) -- My Activity List
		
		
	-- 210	, --Library
	-- 211	, --EExam
	--218	, --Placement
	-- 219	, --Gallery
	
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20186,31) -- Add Photo
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20185,3) -- View Photo
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,9136,31) -- Link Master
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,9137,18) -- Link Viewer 
		--INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,9126,31) -- Vedio Master
		--INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,9127,31) -- Vedio Type Master
		--INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,9128,2) -- Vedio Viewer
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20183,2) -- View Category
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20184,31) -- Add Category
		
	-- 220	, --Portal Academic
	-- 222	, --Employee Attendance
	-- 225	 --Academic
	
	END	

	ELSE IF @rUserType = 'AdminPortal'
	BEGIN
	
	
			INSERT INTO sSecurity.tPermission
		(
			TaskId, 
			RoleId, 
			Permission, 
			IsObsolete, 
			CreatedUserId, 
			CreatedDateTime, 
			UpdatedUserId, 
			UpdatedDateTime,
			OrgGroupId
		)
	SELECT  
			TaskId,
			sCommon.fGetIntIdForOrg(2,@rOrgGroupId),
			AvailablePermission,
			0,
			1,
			sCommon.fGetDate(),
			1,
			sCommon.fGetDate(),
			@rOrgGroupId
	FROM 
		sSecurity.tOrganizationTask
	WHERE OrgGroupId = @rOrgGroupId
 
		----User
		--INSERT INTO sSecurity.tPermission (TaskId,RoleId,Permission,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgGroupId)
		--VALUES (139,sCommon.fGetIntIdForOrg(2,@rOrgGroupId),23,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId)  -- User
		---- Assign Permission
		--INSERT INTO sSecurity.tPermission (TaskId,RoleId,Permission,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgGroupId)
		--VALUES (141,sCommon.fGetIntIdForOrg(2,@rOrgGroupId),6,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId)  
		---- Change Organization
		--INSERT INTO sSecurity.tPermission (TaskId,RoleId,Permission,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgGroupId)
		--VALUES (20158,sCommon.fGetIntIdForOrg(2,@rOrgGroupId),3,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId)  
		---- Manage Student Login
		--INSERT INTO sSecurity.tPermission (TaskId,RoleId,Permission,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgGroupId)
		--VALUES (20175,sCommon.fGetIntIdForOrg(2,@rOrgGroupId),2,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId)  
		---- Manage Employee Login
		--INSERT INTO sSecurity.tPermission (TaskId,RoleId,Permission,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgGroupId)
		--VALUES (20176,sCommon.fGetIntIdForOrg(2,@rOrgGroupId),2,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId)  
		---- SMS History
		--INSERT INTO sSecurity.tPermission (TaskId,RoleId,Permission,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgGroupId)
		--VALUES (20195,sCommon.fGetIntIdForOrg(2,@rOrgGroupId),6,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId)  
		---- Login
		--INSERT INTO sSecurity.tPermission (TaskId,RoleId,Permission,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgGroupId)
		--VALUES (142,sCommon.fGetIntIdForOrg(2,@rOrgGroupId),23,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId)  
		---- Change Password
		--INSERT INTO sSecurity.tPermission (TaskId,RoleId,Permission,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgGroupId)
		--VALUES (245,sCommon.fGetIntIdForOrg(2,@rOrgGroupId),6,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId)  
		---- Alert To All
		--INSERT INTO sSecurity.tPermission (TaskId,RoleId,Permission,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgGroupId)
		--VALUES (20216,sCommon.fGetIntIdForOrg(2,@rOrgGroupId),2,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId)  
		---- Alert From Excel
		--INSERT INTO sSecurity.tPermission (TaskId,RoleId,Permission,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgGroupId)
		--VALUES (20221,sCommon.fGetIntIdForOrg(2,@rOrgGroupId),2,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId)  
		---- Employee List
		--INSERT INTO sSecurity.tPermission (TaskId,RoleId,Permission,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgGroupId)
		--VALUES (20249,sCommon.fGetIntIdForOrg(2,@rOrgGroupId),2,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId)  
		---- Student List
		--INSERT INTO sSecurity.tPermission (TaskId,RoleId,Permission,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgGroupId)
		--VALUES (20021,sCommon.fGetIntIdForOrg(2,@rOrgGroupId),2,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId)  
		---- UpLoad Result
		--INSERT INTO sSecurity.tPermission (TaskId,RoleId,Permission,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgGroupId)
		--VALUES (20179,sCommon.fGetIntIdForOrg(2,@rOrgGroupId),31,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId)  
		---- Query Category Master
		--INSERT INTO sSecurity.tPermission (TaskId,RoleId,Permission,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgGroupId)
		--VALUES (20083,sCommon.fGetIntIdForOrg(2,@rOrgGroupId),31,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId)  
		---- Circular
		--INSERT INTO sSecurity.tPermission (TaskId,RoleId,Permission,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgGroupId)
		--VALUES (20086,sCommon.fGetIntIdForOrg(2,@rOrgGroupId),31,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId)  
		---- Assignment
		--INSERT INTO sSecurity.tPermission (TaskId,RoleId,Permission,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgGroupId)
		--VALUES (20094,sCommon.fGetIntIdForOrg(2,@rOrgGroupId),31,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId)  
		---- New Blog
		--INSERT INTO sSecurity.tPermission (TaskId,RoleId,Permission,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgGroupId)
		--VALUES (20100,sCommon.fGetIntIdForOrg(2,@rOrgGroupId),31,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId)  
		---- News
		--INSERT INTO sSecurity.tPermission (TaskId,RoleId,Permission,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgGroupId)
		--VALUES (20105,sCommon.fGetIntIdForOrg(2,@rOrgGroupId),31,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId)  
		---- Discussion
		----INSERT INTO sSecurity.tPermission (TaskId,RoleId,Permission,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgGroupId)
		----VALUES (20110,sCommon.fGetIntIdForOrg(2,@rOrgGroupId),31,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId)  
		---- Discussion Group
		----INSERT INTO sSecurity.tPermission (TaskId,RoleId,Permission,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgGroupId)
		----VALUES (20112,sCommon.fGetIntIdForOrg(2,@rOrgGroupId),31,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId)  
		---- Poll
		--INSERT INTO sSecurity.tPermission (TaskId,RoleId,Permission,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgGroupId)
		--VALUES (20116,sCommon.fGetIntIdForOrg(2,@rOrgGroupId),31,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId)  
		---- Behaviour List
		--INSERT INTO sSecurity.tPermission (TaskId,RoleId,Permission,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgGroupId)
		--VALUES (20130,sCommon.fGetIntIdForOrg(2,@rOrgGroupId),18,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId)  
		---- My Poll
		--INSERT INTO sSecurity.tPermission (TaskId,RoleId,Permission,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgGroupId)
		--VALUES (20204,sCommon.fGetIntIdForOrg(2,@rOrgGroupId),2,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId)  
		------ Assign Task
		----INSERT INTO sSecurity.tPermission (TaskId,RoleId,Permission,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgGroupId)
		----VALUES (20171,sCommon.fGetIntIdForOrg(2,@rOrgGroupId),7,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId)  
		------ View Task
		----INSERT INTO sSecurity.tPermission (TaskId,RoleId,Permission,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgGroupId)
		----VALUES (20172,sCommon.fGetIntIdForOrg(2,@rOrgGroupId),2,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId)  
		---- Circular List
		--INSERT INTO sSecurity.tPermission (TaskId,RoleId,Permission,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgGroupId)
		--VALUES (20085,sCommon.fGetIntIdForOrg(2,@rOrgGroupId),2,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId)  
		---- Query List
		--INSERT INTO sSecurity.tPermission (TaskId,RoleId,Permission,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgGroupId)
		--VALUES (20088,sCommon.fGetIntIdForOrg(2,@rOrgGroupId),31,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId)  
		---- New Query
		--INSERT INTO sSecurity.tPermission (TaskId,RoleId,Permission,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgGroupId)
		--VALUES (20089,sCommon.fGetIntIdForOrg(2,@rOrgGroupId),31,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId)  
		---- Circular View 
		--INSERT INTO sSecurity.tPermission (TaskId,RoleId,Permission,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgGroupId)
		--VALUES (20091,sCommon.fGetIntIdForOrg(2,@rOrgGroupId),2,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId)  
		---- Assignment List
		--INSERT INTO sSecurity.tPermission (TaskId,RoleId,Permission,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgGroupId)
		--VALUES (20093,sCommon.fGetIntIdForOrg(2,@rOrgGroupId),2,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId)  
		---- Assignment View
		--INSERT INTO sSecurity.tPermission (TaskId,RoleId,Permission,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgGroupId)
		--VALUES (20095,sCommon.fGetIntIdForOrg(2,@rOrgGroupId),2,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId)  
		---- View Query
		--INSERT INTO sSecurity.tPermission (TaskId,RoleId,Permission,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgGroupId)
		--VALUES (20097,sCommon.fGetIntIdForOrg(2,@rOrgGroupId),31,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId)  
		---- Blog List
		--INSERT INTO sSecurity.tPermission (TaskId,RoleId,Permission,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgGroupId)
		--VALUES (20099,sCommon.fGetIntIdForOrg(2,@rOrgGroupId),2,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId)  
		---- Blog View
		--INSERT INTO sSecurity.tPermission (TaskId,RoleId,Permission,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgGroupId)
		--VALUES (20101,sCommon.fGetIntIdForOrg(2,@rOrgGroupId),2,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId)  
		---- My Blog
		--INSERT INTO sSecurity.tPermission (TaskId,RoleId,Permission,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgGroupId)
		--VALUES (20102,sCommon.fGetIntIdForOrg(2,@rOrgGroupId),2,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId)  
		---- Blog Activities
		--INSERT INTO sSecurity.tPermission (TaskId,RoleId,Permission,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgGroupId)
		--VALUES (20103,sCommon.fGetIntIdForOrg(2,@rOrgGroupId),2,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId)  
		---- News List
		--INSERT INTO sSecurity.tPermission (TaskId,RoleId,Permission,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgGroupId)
		--VALUES (20104,sCommon.fGetIntIdForOrg(2,@rOrgGroupId),2,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId)  
		---- News View
		--INSERT INTO sSecurity.tPermission (TaskId,RoleId,Permission,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgGroupId)
		--VALUES (20106,sCommon.fGetIntIdForOrg(2,@rOrgGroupId),2,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId)  
		---- Query Queue
		--INSERT INTO sSecurity.tPermission (TaskId,RoleId,Permission,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgGroupId)
		--VALUES (20107,sCommon.fGetIntIdForOrg(2,@rOrgGroupId),31,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId)  
		---- Discussion List
		----INSERT INTO sSecurity.tPermission (TaskId,RoleId,Permission,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgGroupId)
		----VALUES (20109,sCommon.fGetIntIdForOrg(2,@rOrgGroupId),2,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId)  
		------ Discussion View
		----INSERT INTO sSecurity.tPermission (TaskId,RoleId,Permission,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgGroupId)
		----VALUES (20111,sCommon.fGetIntIdForOrg(2,@rOrgGroupId),2,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId)  
		------ Discussion Activities
		----INSERT INTO sSecurity.tPermission (TaskId,RoleId,Permission,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgGroupId)
		----VALUES (20113,sCommon.fGetIntIdForOrg(2,@rOrgGroupId),2,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId)  
		---- Group Members
		--INSERT INTO sSecurity.tPermission (TaskId,RoleId,Permission,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgGroupId)
		--VALUES (20114,sCommon.fGetIntIdForOrg(2,@rOrgGroupId),2,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId)  
		---- Poll List
		--INSERT INTO sSecurity.tPermission (TaskId,RoleId,Permission,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgGroupId)
		--VALUES (20115,sCommon.fGetIntIdForOrg(2,@rOrgGroupId),2,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId)  
		---- Poll View
		--INSERT INTO sSecurity.tPermission (TaskId,RoleId,Permission,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgGroupId)
		--VALUES (20117,sCommon.fGetIntIdForOrg(2,@rOrgGroupId),7,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId)  
		---- Poll Vote
		--INSERT INTO sSecurity.tPermission (TaskId,RoleId,Permission,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgGroupId)
		--VALUES (20118,sCommon.fGetIntIdForOrg(2,@rOrgGroupId),2,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId)  
		---- Behaviour Type Master
		--INSERT INTO sSecurity.tPermission (TaskId,RoleId,Permission,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgGroupId)
		--VALUES (20125,sCommon.fGetIntIdForOrg(2,@rOrgGroupId),31,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId)  
		---- Behaviour Entry
		--INSERT INTO sSecurity.tPermission (TaskId,RoleId,Permission,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgGroupId)
		--VALUES (20126,sCommon.fGetIntIdForOrg(2,@rOrgGroupId),31,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId)  
		---- Add Photo
		--INSERT INTO sSecurity.tPermission (TaskId,RoleId,Permission,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgGroupId)
		--VALUES (20186,sCommon.fGetIntIdForOrg(2,@rOrgGroupId),31,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId)  
		---- View Photo
		--INSERT INTO sSecurity.tPermission (TaskId,RoleId,Permission,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgGroupId)
		--VALUES (20185,sCommon.fGetIntIdForOrg(2,@rOrgGroupId),3,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId)  
		---- Link Master
		--INSERT INTO sSecurity.tPermission (TaskId,RoleId,Permission,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgGroupId)
		--VALUES (9136,sCommon.fGetIntIdForOrg(2,@rOrgGroupId),31,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId)  
		---- Link Viewer
		--INSERT INTO sSecurity.tPermission (TaskId,RoleId,Permission,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgGroupId)
		--VALUES (9137,sCommon.fGetIntIdForOrg(2,@rOrgGroupId),18,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId)  
		---- Vedio Master
		----INSERT INTO sSecurity.tPermission (TaskId,RoleId,Permission,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgGroupId)
		----VALUES (9126,sCommon.fGetIntIdForOrg(2,@rOrgGroupId),31,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId)  
		---- Vedio Type Master
		----INSERT INTO sSecurity.tPermission (TaskId,RoleId,Permission,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgGroupId)
		----VALUES (9127,sCommon.fGetIntIdForOrg(2,@rOrgGroupId),31,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId)  
		---- Vedio Viewer
		----INSERT INTO sSecurity.tPermission (TaskId,RoleId,Permission,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgGroupId)
		----VALUES (9128,sCommon.fGetIntIdForOrg(2,@rOrgGroupId),2,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId)  
		---- View Category
		--INSERT INTO sSecurity.tPermission (TaskId,RoleId,Permission,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgGroupId)
		--VALUES (20183,sCommon.fGetIntIdForOrg(2,@rOrgGroupId),2,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId)  
		---- Add Category
		--INSERT INTO sSecurity.tPermission (TaskId,RoleId,Permission,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgGroupId)
		--VALUES (20184,sCommon.fGetIntIdForOrg(2,@rOrgGroupId),21,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId)  
		---- Calender
		--INSERT INTO sSecurity.tPermission (TaskId,RoleId,Permission,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgGroupId)
		--VALUES (20054,sCommon.fGetIntIdForOrg(2,@rOrgGroupId),3,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId)  
		---- Event Schedule
		--INSERT INTO sSecurity.tPermission (TaskId,RoleId,Permission,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgGroupId)
		--VALUES (20056,sCommon.fGetIntIdForOrg(2,@rOrgGroupId),31,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId)  
		---- Activity Type Master
		--INSERT INTO sSecurity.tPermission (TaskId,RoleId,Permission,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgGroupId)
		--VALUES (20058,sCommon.fGetIntIdForOrg(2,@rOrgGroupId),31,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId)  
		---- Activity
		--INSERT INTO sSecurity.tPermission (TaskId,RoleId,Permission,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgGroupId)
		--VALUES (20059,sCommon.fGetIntIdForOrg(2,@rOrgGroupId),31,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId)  
		---- House Master
		--INSERT INTO sSecurity.tPermission (TaskId,RoleId,Permission,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgGroupId)
		--VALUES (20151,sCommon.fGetIntIdForOrg(2,@rOrgGroupId),31,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId)  
		---- Club Master
		--INSERT INTO sSecurity.tPermission (TaskId,RoleId,Permission,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgGroupId)
		--VALUES (20152,sCommon.fGetIntIdForOrg(2,@rOrgGroupId),31,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId)  
		---- Assign Club
		--INSERT INTO sSecurity.tPermission (TaskId,RoleId,Permission,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgGroupId)
		--VALUES (20153,sCommon.fGetIntIdForOrg(2,@rOrgGroupId),22,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId)  
		---- Placement
		----INSERT INTO sSecurity.tPermission (TaskId,RoleId,Permission,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgGroupId)
		----VALUES (20187,sCommon.fGetIntIdForOrg(2,@rOrgGroupId),31,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId)  
		---- Placement invite
		----INSERT INTO sSecurity.tPermission (TaskId,RoleId,Permission,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgGroupId)
		----VALUES (20188,sCommon.fGetIntIdForOrg(2,@rOrgGroupId),31,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId)  
		---- Placement Registration
		----INSERT INTO sSecurity.tPermission (TaskId,RoleId,Permission,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgGroupId)
		----VALUES (20189,sCommon.fGetIntIdForOrg(2,@rOrgGroupId),31,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId)  
		---- View Placement
		----INSERT INTO sSecurity.tPermission (TaskId,RoleId,Permission,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgGroupId)
		----VALUES (20193,sCommon.fGetIntIdForOrg(2,@rOrgGroupId),2,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId)  
		---- Enrollment List
		--INSERT INTO sSecurity.tPermission (TaskId,RoleId,Permission,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgGroupId)
		--VALUES (20197,sCommon.fGetIntIdForOrg(2,@rOrgGroupId),2,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId)  
		---- My Event List
		--INSERT INTO sSecurity.tPermission (TaskId,RoleId,Permission,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgGroupId)
		--VALUES (20198,sCommon.fGetIntIdForOrg(2,@rOrgGroupId),2,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId)  
		---- View Event
		--INSERT INTO sSecurity.tPermission (TaskId,RoleId,Permission,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgGroupId)
		--VALUES (20199,sCommon.fGetIntIdForOrg(2,@rOrgGroupId),2,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId)  
		---- My Activity List
		--INSERT INTO sSecurity.tPermission (TaskId,RoleId,Permission,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgGroupId)
		--VALUES (20209,sCommon.fGetIntIdForOrg(2,@rOrgGroupId),2,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId)  		
	END	
	
	ELSE IF @rUserType = 'EmployeePortal'
	BEGIN
	
    -- SELECT TaskId, ',-- ' + Title FROM sSecurity.tScreen WHERE ScreenGroupId = 114 
	-- SELECT TaskId, ',-- ' + Title FROM sSecurity.tScreen WHERE ScreenGroupId = 213 
	
	
	
			INSERT INTO sSecurity.tPermission
		(
			TaskId, 
			RoleId, 
			Permission, 
			IsObsolete, 
			CreatedUserId, 
			CreatedDateTime, 
			UpdatedUserId, 
			UpdatedDateTime,
			OrgGroupId
		)
	SELECT  
			Id,
			sCommon.fGetIntIdForOrg(10,@rOrgGroupId),
			AvailablePermission,
			0,
			1,
			sCommon.fGetDate(),
			1,
			sCommon.fGetDate(),
			@rOrgGroupId
	FROM 
		sSecurity.tTask
	WHERE ID IN(
9128	, -- Video Viewer
9137	, -- Link Viewer
10187	, -- My Profile
20054	, -- Calendar
20085	, -- Circular List
20088	, -- Query List
20089	, -- New Query
20091	, -- Circular View
20093	, -- Assignment List
20095	, -- Assignment View
20097	, -- View Query
20099	, -- Blog List
20101	, -- Blog View
20104	, -- News List
20106	, -- News View
20109	, -- Discussion List
20110	, -- Discussion
20111	, -- Discussion View
20112	, -- Discussion Group
20114	, -- Group Members
20117	, -- Poll View
20118	, -- Poll Vote
20130	, -- Behaviour List
20172	, -- View Task
 20181	,-- Result
20246	-- My Profile
				)
	
	
		-- Login
		INSERT INTO sSecurity.tPermission (TaskId,RoleId,Permission,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgGroupId)
		VALUES (142,sCommon.fGetIntIdForOrg(10,@rOrgGroupId),23,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId)  
		-- Change Password
		INSERT INTO sSecurity.tPermission (TaskId,RoleId,Permission,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgGroupId)
		VALUES (245,sCommon.fGetIntIdForOrg(10,@rOrgGroupId),6,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId)  
		
		
		---- Calender
		--INSERT INTO sSecurity.tPermission (TaskId,RoleId,Permission,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgGroupId)
		--VALUES (20054,sCommon.fGetIntIdForOrg(10,@rOrgGroupId),3,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId)  
		---- View Placement
		----INSERT INTO sSecurity.tPermission (TaskId,RoleId,Permission,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgGroupId)
		----VALUES (20193,sCommon.fGetIntIdForOrg(10,@rOrgGroupId),2,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId)  
		---- Enrollment List
		--INSERT INTO sSecurity.tPermission (TaskId,RoleId,Permission,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgGroupId)
		--VALUES (20197,sCommon.fGetIntIdForOrg(10,@rOrgGroupId),2,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId)  
		---- My Event List
		--INSERT INTO sSecurity.tPermission (TaskId,RoleId,Permission,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgGroupId)
		--VALUES (20198,sCommon.fGetIntIdForOrg(10,@rOrgGroupId),2,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId)  
		---- View Event
		--INSERT INTO sSecurity.tPermission (TaskId,RoleId,Permission,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgGroupId)
		--VALUES (20199,sCommon.fGetIntIdForOrg(10,@rOrgGroupId),2,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId)  
		---- My Activity List
		--INSERT INTO sSecurity.tPermission (TaskId,RoleId,Permission,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgGroupId)
		--VALUES (20209,sCommon.fGetIntIdForOrg(10,@rOrgGroupId),2,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId)  		
		---- View Photo
		--INSERT INTO sSecurity.tPermission (TaskId,RoleId,Permission,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgGroupId)
		--VALUES (20185,sCommon.fGetIntIdForOrg(10,@rOrgGroupId),3,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId)  
		---- Link Viewer
		--INSERT INTO sSecurity.tPermission (TaskId,RoleId,Permission,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgGroupId)
		--VALUES (9137,sCommon.fGetIntIdForOrg(10,@rOrgGroupId),18,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId)  
		---- Vedio Viewer
		----INSERT INTO sSecurity.tPermission (TaskId,RoleId,Permission,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgGroupId)
		----VALUES (9128,sCommon.fGetIntIdForOrg(10,@rOrgGroupId),2,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId)  
		---- View Category
		--INSERT INTO sSecurity.tPermission (TaskId,RoleId,Permission,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgGroupId)
		--VALUES (20183,sCommon.fGetIntIdForOrg(10,@rOrgGroupId),2,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId)  
		---- Poll List
		--INSERT INTO sSecurity.tPermission (TaskId,RoleId,Permission,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgGroupId)
		--VALUES (20115,sCommon.fGetIntIdForOrg(10,@rOrgGroupId),2,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId)  
		---- Poll View
		--INSERT INTO sSecurity.tPermission (TaskId,RoleId,Permission,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgGroupId)
		--VALUES (20117,sCommon.fGetIntIdForOrg(10,@rOrgGroupId),7,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId)  
		------ Discussion List
		----INSERT INTO sSecurity.tPermission (TaskId,RoleId,Permission,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgGroupId)
		----VALUES (20109,sCommon.fGetIntIdForOrg(10,@rOrgGroupId),2,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId)  
		------ Discussion View
		----INSERT INTO sSecurity.tPermission (TaskId,RoleId,Permission,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgGroupId)
		----VALUES (20111,sCommon.fGetIntIdForOrg(10,@rOrgGroupId),2,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId)  
		---- News List
		--INSERT INTO sSecurity.tPermission (TaskId,RoleId,Permission,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgGroupId)
		--VALUES (20104,sCommon.fGetIntIdForOrg(10,@rOrgGroupId),2,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId)  
		---- News View
		--INSERT INTO sSecurity.tPermission (TaskId,RoleId,Permission,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgGroupId)
		--VALUES (20106,sCommon.fGetIntIdForOrg(10,@rOrgGroupId),2,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId)  
		---- Circular View 
		--INSERT INTO sSecurity.tPermission (TaskId,RoleId,Permission,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgGroupId)
		--VALUES (20091,sCommon.fGetIntIdForOrg(10,@rOrgGroupId),2,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId)  
		---- Assignment List
		--INSERT INTO sSecurity.tPermission (TaskId,RoleId,Permission,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgGroupId)
		--VALUES (20093,sCommon.fGetIntIdForOrg(10,@rOrgGroupId),2,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId)  
		---- Assignment View
		--INSERT INTO sSecurity.tPermission (TaskId,RoleId,Permission,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgGroupId)
		--VALUES (20095,sCommon.fGetIntIdForOrg(10,@rOrgGroupId),2,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId)  
		---- View Query
		--INSERT INTO sSecurity.tPermission (TaskId,RoleId,Permission,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgGroupId)
		--VALUES (20097,sCommon.fGetIntIdForOrg(10,@rOrgGroupId),31,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId)  
		---- Blog List
		--INSERT INTO sSecurity.tPermission (TaskId,RoleId,Permission,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgGroupId)
		--VALUES (20099,sCommon.fGetIntIdForOrg(10,@rOrgGroupId),2,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId)  
		---- Blog View
		--INSERT INTO sSecurity.tPermission (TaskId,RoleId,Permission,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgGroupId)
		--VALUES (20101,sCommon.fGetIntIdForOrg(10,@rOrgGroupId),2,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId)  
		---- Circular List
		--INSERT INTO sSecurity.tPermission (TaskId,RoleId,Permission,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgGroupId)
		--VALUES (20085,sCommon.fGetIntIdForOrg(10,@rOrgGroupId),2,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId)  
		---- Query List
		--INSERT INTO sSecurity.tPermission (TaskId,RoleId,Permission,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgGroupId)
		--VALUES (20088,sCommon.fGetIntIdForOrg(10,@rOrgGroupId),31,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId)  
		------ View Task
		----INSERT INTO sSecurity.tPermission (TaskId,RoleId,Permission,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgGroupId)
		----VALUES (20172,sCommon.fGetIntIdForOrg(10,@rOrgGroupId),2,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId)  
		---- Behaviour List
		--INSERT INTO sSecurity.tPermission (TaskId,RoleId,Permission,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgGroupId)
		--VALUES (20130,sCommon.fGetIntIdForOrg(10,@rOrgGroupId),18,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId)  
		---- Employee View Result
		--INSERT INTO sSecurity.tPermission (TaskId,RoleId,Permission,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgGroupId)
		--VALUES (20181,sCommon.fGetIntIdForOrg(10,@rOrgGroupId),2,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId)  
	END		

	ELSE IF @rUserType = 'ParentPortal'
	BEGIN
	
    --	SELECT TaskId FROM sSecurity.tScreen WHERE ScreenGroupId = 114 
	--	SELECT TaskId FROM sSecurity.tScreen WHERE ScreenGroupId = 172 
		INSERT INTO sSecurity.tPermission
		(
			TaskId, 
			RoleId, 
			Permission, 
			IsObsolete, 
			CreatedUserId, 
			CreatedDateTime, 
			UpdatedUserId, 
			UpdatedDateTime,
			OrgGroupId
		)
	SELECT  
			Id,
			sCommon.fGetIntIdForOrg(22,@rOrgGroupId),
			AvailablePermission,
			0,
			1,
			sCommon.fGetDate(),
			1,
			sCommon.fGetDate(),
			@rOrgGroupId
	FROM 
		sSecurity.tTask
	WHERE ID IN(
9128	, -- Video Viewer
9137	, -- Link Viewer
10187	, -- My Profile
20054	, -- Calendar
20085	, -- Circular List
20088	, -- Query List
20089	, -- New Query
20091	, -- Circular View
20093	, -- Assignment List
20095	, -- Assignment View
20097	, -- View Query
20099	, -- Blog List
20101	, -- Blog View
20104	, -- News List
20106	, -- News View
20109	, -- Discussion List
20110	, -- Discussion
20111	, -- Discussion View
20112	, -- Discussion Group
20114	, -- Group Members
20117	, -- Poll View
20118	, -- Poll Vote
20130	, -- Behaviour List
20172	, -- View Task
20180	, -- Student View Result
20182	, -- View Book List
20183	, -- View Category
20190	, -- View Placement
20191	, -- Available Tests
20198	, -- My Event List
20204	, -- My Poll
20209	, -- My Activity List
20241	, -- My Attendance
20563	, -- My Classwork
20564	, -- My Result
20565	, -- My Fee
20566	 -- My Book List
				)
	
	
	
	
		-- Login
		INSERT INTO sSecurity.tPermission (TaskId,RoleId,Permission,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgGroupId)
		VALUES (142,sCommon.fGetIntIdForOrg(22,@rOrgGroupId),23,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId)  
		-- Change Password
		INSERT INTO sSecurity.tPermission (TaskId,RoleId,Permission,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgGroupId)
		VALUES (245,sCommon.fGetIntIdForOrg(22,@rOrgGroupId),6,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId)  
		---- Calender
		--INSERT INTO sSecurity.tPermission (TaskId,RoleId,Permission,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgGroupId)
		--VALUES (20054,sCommon.fGetIntIdForOrg(22,@rOrgGroupId),3,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId)  
		---- View Placement
		----INSERT INTO sSecurity.tPermission (TaskId,RoleId,Permission,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgGroupId)
		----VALUES (20193,sCommon.fGetIntIdForOrg(22,@rOrgGroupId),2,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId)  
		---- Enrollment List
		--INSERT INTO sSecurity.tPermission (TaskId,RoleId,Permission,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgGroupId)
		--VALUES (20197,sCommon.fGetIntIdForOrg(22,@rOrgGroupId),2,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId)  
		---- My Event List
		--INSERT INTO sSecurity.tPermission (TaskId,RoleId,Permission,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgGroupId)
		--VALUES (20198,sCommon.fGetIntIdForOrg(22,@rOrgGroupId),2,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId)  
		---- View Event
		--INSERT INTO sSecurity.tPermission (TaskId,RoleId,Permission,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgGroupId)
		--VALUES (20199,sCommon.fGetIntIdForOrg(22,@rOrgGroupId),2,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId)  
		---- My Activity List
		--INSERT INTO sSecurity.tPermission (TaskId,RoleId,Permission,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgGroupId)
		--VALUES (20209,sCommon.fGetIntIdForOrg(22,@rOrgGroupId),2,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId)  		
		---- View Photo
		--INSERT INTO sSecurity.tPermission (TaskId,RoleId,Permission,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgGroupId)
		--VALUES (20185,sCommon.fGetIntIdForOrg(22,@rOrgGroupId),3,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId)  
		---- Link Viewer
		--INSERT INTO sSecurity.tPermission (TaskId,RoleId,Permission,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgGroupId)
		--VALUES (9137,sCommon.fGetIntIdForOrg(22,@rOrgGroupId),18,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId)  
		---- Vedio Viewer
		----INSERT INTO sSecurity.tPermission (TaskId,RoleId,Permission,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgGroupId)
		----VALUES (9128,sCommon.fGetIntIdForOrg(22,@rOrgGroupId),2,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId)  
		---- View Category
		--INSERT INTO sSecurity.tPermission (TaskId,RoleId,Permission,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgGroupId)
		--VALUES (20183,sCommon.fGetIntIdForOrg(22,@rOrgGroupId),2,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId)  
		---- Poll List
		--INSERT INTO sSecurity.tPermission (TaskId,RoleId,Permission,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgGroupId)
		--VALUES (20115,sCommon.fGetIntIdForOrg(22,@rOrgGroupId),2,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId)  
		---- Poll View
		--INSERT INTO sSecurity.tPermission (TaskId,RoleId,Permission,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgGroupId)
		--VALUES (20117,sCommon.fGetIntIdForOrg(22,@rOrgGroupId),7,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId)  
		------ Discussion List
		----INSERT INTO sSecurity.tPermission (TaskId,RoleId,Permission,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgGroupId)
		----VALUES (20109,sCommon.fGetIntIdForOrg(22,@rOrgGroupId),2,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId)  
		------ Discussion View
		----INSERT INTO sSecurity.tPermission (TaskId,RoleId,Permission,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgGroupId)
		----VALUES (20111,sCommon.fGetIntIdForOrg(22,@rOrgGroupId),2,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId)  
		---- News List
		--INSERT INTO sSecurity.tPermission (TaskId,RoleId,Permission,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgGroupId)
		--VALUES (20104,sCommon.fGetIntIdForOrg(22,@rOrgGroupId),2,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId)  
		---- News View
		--INSERT INTO sSecurity.tPermission (TaskId,RoleId,Permission,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgGroupId)
		--VALUES (20106,sCommon.fGetIntIdForOrg(22,@rOrgGroupId),2,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId)  
		---- Circular View 
		--INSERT INTO sSecurity.tPermission (TaskId,RoleId,Permission,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgGroupId)
		--VALUES (20091,sCommon.fGetIntIdForOrg(22,@rOrgGroupId),2,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId)  
		---- Assignment List
		--INSERT INTO sSecurity.tPermission (TaskId,RoleId,Permission,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgGroupId)
		--VALUES (20093,sCommon.fGetIntIdForOrg(22,@rOrgGroupId),2,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId)  
		---- Assignment View
		--INSERT INTO sSecurity.tPermission (TaskId,RoleId,Permission,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgGroupId)
		--VALUES (20095,sCommon.fGetIntIdForOrg(22,@rOrgGroupId),2,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId)  
		---- View Query
		--INSERT INTO sSecurity.tPermission (TaskId,RoleId,Permission,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgGroupId)
		--VALUES (20097,sCommon.fGetIntIdForOrg(22,@rOrgGroupId),31,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId)  
		---- Blog List
		--INSERT INTO sSecurity.tPermission (TaskId,RoleId,Permission,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgGroupId)
		--VALUES (20099,sCommon.fGetIntIdForOrg(22,@rOrgGroupId),2,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId)  
		---- Blog View
		--INSERT INTO sSecurity.tPermission (TaskId,RoleId,Permission,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgGroupId)
		--VALUES (20101,sCommon.fGetIntIdForOrg(22,@rOrgGroupId),2,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId)  
		---- Circular List
		--INSERT INTO sSecurity.tPermission (TaskId,RoleId,Permission,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgGroupId)
		--VALUES (20085,sCommon.fGetIntIdForOrg(22,@rOrgGroupId),2,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId)  
		---- Query List
		--INSERT INTO sSecurity.tPermission (TaskId,RoleId,Permission,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgGroupId)
		--VALUES (20088,sCommon.fGetIntIdForOrg(22,@rOrgGroupId),31,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId)  
		------ View Task
		----INSERT INTO sSecurity.tPermission (TaskId,RoleId,Permission,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgGroupId)
		----VALUES (20172,sCommon.fGetIntIdForOrg(22,@rOrgGroupId),2,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId)  
		---- Behaviour List
		--INSERT INTO sSecurity.tPermission (TaskId,RoleId,Permission,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgGroupId)
		--VALUES (20130,sCommon.fGetIntIdForOrg(22,@rOrgGroupId),18,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId)  
		---- Student View Result
		--INSERT INTO sSecurity.tPermission (TaskId,RoleId,Permission,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgGroupId)
		--VALUES (20180,sCommon.fGetIntIdForOrg(22,@rOrgGroupId),2,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId)  
		---- Student View Book List
		--INSERT INTO sSecurity.tPermission (TaskId,RoleId,Permission,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgGroupId)
		--VALUES (20182,sCommon.fGetIntIdForOrg(22,@rOrgGroupId),2,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId)  
		---- Student View Presence
		--INSERT INTO sSecurity.tPermission (TaskId,RoleId,Permission,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgGroupId)
		--VALUES (20241,sCommon.fGetIntIdForOrg(22,@rOrgGroupId),2,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId)  
	END		

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


GO


ALTER PROCEDURE [sSecurity].[pUserAccessGet]
	 
	@rUserId bigint,
	@rOrgGroupId smallint
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 
	SELECT
				113 AS SourceTypeId,
				AM.Id AS SourceId,
				AM.Title AS SourceName,
				CASE WHEN UA.UserId IS NULL THEN 'False' ELSE 'True' END AS IsObsolete
	FROM
			sAccounting.tAccountMaster AM
		LEFT JOIN sSecurity.tUserAccess UA ON UA.SourceId=AM.Id AND UA.SourceTypeId=113 AND UA.UserId=@rUserId
	WHERE
		AM.OrgGroupId=@rOrgGroupId
		
	UNION ALL	
		
	SELECT
				2019 AS SourceTypeId,
				PM.Id AS SourceId,
				PM.Title AS SourceName,
				CASE WHEN UA.UserId IS NULL THEN 'False' ELSE 'True' END AS IsObsolete
	FROM
			sPayroll.tPayrollMaster PM
		LEFT JOIN sSecurity.tUserAccess UA ON UA.SourceId=PM.Id AND UA.SourceTypeId=2019 AND UA.UserId=@rUserId
	WHERE
		PM.OrgGroupId=@rOrgGroupId	
		
	UNION ALL
	
	SELECT
				1014 AS SourceTypeId,
				SLM.Id AS SourceId,
				SLM.Title AS SourceName,
				CASE WHEN UA.UserId IS NULL THEN 'False' ELSE 'True' END AS IsObsolete
	FROM
			sIp.tStoreLocationMaster SLM
		LEFT JOIN sSecurity.tUserAccess UA ON UA.SourceId=SLM.Id AND UA.SourceTypeId=1014 AND UA.UserId=@rUserId
	WHERE
		SLM.OrgGroupId=@rOrgGroupId
		
	UNION ALL
	
	SELECT
				2011 AS SourceTypeId,
				LM.Id AS SourceId,
				LM.Title AS SourceName,
				CASE WHEN UA.UserId IS NULL THEN 'False' ELSE 'True' END AS IsObsolete
	FROM
			sLibrary.tLibraryMaster LM
		LEFT JOIN sSecurity.tUserAccess UA ON UA.SourceId=LM.Id AND UA.SourceTypeId=2011 AND UA.UserId=@rUserId
	WHERE
		LM.OrgGroupId=@rOrgGroupId
		
	UNION ALL
	
	SELECT
				2012 AS SourceTypeId,
				DBM.Id AS SourceId,
				DBM.Title AS SourceName,
				CASE WHEN UA.UserId IS NULL THEN 'False' ELSE 'True' END AS IsObsolete
	FROM
			sEExam.tDataBankMaster DBM
		LEFT JOIN sSecurity.tUserAccess UA ON UA.SourceId=DBM.Id AND UA.SourceTypeId=2012 AND UA.UserId=@rUserId
	WHERE
		DBM.OrgGroupId=@rOrgGroupId
		
	UNION ALL
	
	SELECT
				2013 AS SourceTypeId,
				RBM.Id AS SourceId,
				RBM.Title AS SourceName,
				CASE WHEN UA.UserId IS NULL THEN 'False' ELSE 'True' END AS IsObsolete
	FROM
			sFee.tReceiptBookMaster RBM
		LEFT JOIN sSecurity.tUserAccess UA ON UA.SourceId=RBM.Id AND UA.SourceTypeId=2013 AND UA.UserId=@rUserId
	WHERE
		RBM.OrgGroupId=@rOrgGroupId
		
	UNION ALL
	
	SELECT
				2018 AS SourceTypeId,
				CRBM.Id AS SourceId,
				CRBM.Title AS SourceName,
				CASE WHEN UA.UserId IS NULL THEN 'False' ELSE 'True' END AS IsObsolete
	FROM
			sFee.tChargeReceiptBookMaster CRBM
		LEFT JOIN sSecurity.tUserAccess UA ON UA.SourceId=CRBM.Id AND UA.SourceTypeId=2018 AND UA.UserId=@rUserId
	WHERE
		CRBM.OrgGroupId=@rOrgGroupId
		
	UNION ALL
	
	SELECT
				2014 AS SourceTypeId,
				HM.Id AS SourceId,
				HM.Title AS SourceName,
				CASE WHEN UA.UserId IS NULL THEN 'False' ELSE 'True' END AS IsObsolete
	FROM
			sHostel.tHostelMaster HM
		LEFT JOIN sSecurity.tUserAccess UA ON UA.SourceId=HM.Id AND UA.SourceTypeId=2014 AND UA.UserId=@rUserId
	WHERE
		HM.OrgGroupId=@rOrgGroupId
		
		UNION ALL
			
	SELECT
				2017 AS SourceTypeId,
				DM.Id AS SourceId,
				OM.DisplayTitle + ' - ' + DM.Title AS SourceName,
				CASE WHEN UA.UserId IS NULL THEN 'False' ELSE 'True' END AS IsObsolete
	FROM
			sSetup.tDepartmentMaster DM INNER JOIN sSetup.tOrganizationMaster OM
			ON DM.OrgId = OM.Id
		LEFT JOIN sSecurity.tUserAccess UA ON UA.SourceId=DM.Id AND UA.SourceTypeId=2017 AND UA.UserId=@rUserId
	WHERE
		DM.OrgId IN (SELECT Id FROM sSetup.tOrganizationMaster WHERE OrgGroupId = @rOrgGroupId)
	 
			
END
GO
PRINT N'Altering [sSetup].[pOrgGroupMasterAdd]...';


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

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

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

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

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


GO


ALTER PROCEDURE [sSetup].[pPortalMasterBatchClassUpdate]
	 
	
	@rStrXml [nvarchar](max),
	@rBatchId int
	
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET @rStrXml=REPLACE(@rStrXml,'&','AND')
DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml
BEGIN
	BEGIN TRY
	EXEC sp_msforeachtable "ALTER TABLE ? NOCHECK CONSTRAINT all"
	
	 BEGIN TRANSACTION 
	 BEGIN	
	 DELETE FROM sSetup.tBatchClass WHERE BatchId=@rBatchId
	
	 INSERT INTO sSetup.tBatchClass
		(
			BatchId,
			ClassId
			)
		SELECT		
			BatchId,
			ClassId
						
		FROM OPENXML (@loDoc, '/Table/RowData', 1)
		WITH ( 
				BatchId int,
				ClassId int
			  ) 
		
        SELECT 1 AS Result
	 END	
	
		COMMIT TRANSACTION
		EXEC sp_msforeachtable "ALTER TABLE ? WITH CHECK CHECK CONSTRAINT all"
	END TRY
	
	BEGIN CATCH 
	EXEC sp_msforeachtable "ALTER TABLE ? WITH CHECK CHECK CONSTRAINT all"
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sSetup].[pPortalMasterBatchUpdate]...';


GO


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

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

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


GO


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

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

	 BEGIN	

IF EXISTS(SELECT 1 FROM sSetup.tOrganizationMaster WHERE Id = 	@rOrgId)
BEGIN
	UPDATE sSetup.tOrganizationMaster
		SET
			Code = A.Code,
			Title = A.Title,
			DisplayTitle = A.DisplayTitle,
			AffiliationId = A.AffiliationId,
			LanguageId = A.LanguageId,
			StreetOne = A.StreetOne,
			StreetTwo = A.StreetTwo,
			StreetThree = A.StreetThree,
			CityName = A.CityName,
			StateName = A.StateName,
			CountryName = A.CountryName,
			ZipCode = A.ZipCode,
			HomePage = A.HomePage,
			PhoneNo = A.PhoneNo,
			FaxNo = A.FaxNo,
			ReportOrgTitle = A.ReportOrgTitle,
			SmallAddress1 = A.SmallAddress1,
			SmallAddress2 = A.SmallAddress2,
			RegistrationDetail = A.RegistrationDetail,
			CreatedUserId = A.CreatedUserId,
			CreatedDateTime = A.CreatedDateTime,
			UpdatedUserId = A.UpdatedUserId,
			UpdatedDateTime = A.UpdatedDateTime,
			IsObsolete = A.IsObsolete,
			OrgGroupId = A.OrgGroupId,
			OrgLogo = A.OrgLogo,
			EmployeeId = A.EmployeeId,
			OrderIndex = A.OrderIndex,
			PrincipalSignature = A.PrincipalSignature,
			ICardBackBackGround = A.ICardBackBackGround,
			ICardOrgTitle = A.ICardOrgTitle,
			ICardAddress1 = A.ICardAddress1,
			ICardAddress2 = A.ICardAddress2,
			ICardAddress3 = A.ICardAddress3,
			LabelColor = A.LabelColor,
			DetailColor = A.DetailColor,
			HeaderColor = A.HeaderColor,
			OrgSubGroupId = A.OrgSubGroupId
		 FROM
		 (
		SELECT		
			Id,
			Code,
			Title,
			DisplayTitle,
			AffiliationId,
			LanguageId,
			StreetOne,
			StreetTwo,
			StreetThree,
			CityName,
			StateName,
			CountryName,
			ZipCode,
			HomePage,
			PhoneNo,
			FaxNo,
			ReportOrgTitle,
			SmallAddress1,
			SmallAddress2,
			RegistrationDetail,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime,
			IsObsolete,
			OrgGroupId,
			OrgLogo,
			EmployeeId,
			OrderIndex,
			PrincipalSignature,
			ICardBackBackGround,
			ICardOrgTitle,
			ICardAddress1,
			ICardAddress2,
			ICardAddress3,
			LabelColor,
			DetailColor,
			HeaderColor,
			OrgSubGroupId
						
		FROM OPENXML (@loDoc, '/Table/RowData', 1)
		WITH ( 
				[Id] [smallint],
				[Code] [nvarchar](20),
				[Title] [nvarchar](100),
				[DisplayTitle] [nvarchar](100),
				[AffiliationId] [smallint],
				[LanguageId] [smallint],
				[StreetOne] [nvarchar](50),
				[StreetTwo] [nvarchar](50),
				[StreetThree] [nvarchar](50),
				[CityName] [nvarchar](100),
				[StateName] [nvarchar](100),
				[CountryName] [nvarchar](100),
				[ZipCode] [nvarchar](20),
				[HomePage] [nvarchar](100),
				[PhoneNo] [nvarchar](50),
				[FaxNo] [nvarchar](50),
				[ReportOrgTitle] [nvarchar](200),
				[SmallAddress1] [nvarchar](200),
				[SmallAddress2] [nvarchar](200),
				[RegistrationDetail] [nvarchar](200),
				[CreatedUserId] [bigint],
				[CreatedDateTime] [datetime],
				[UpdatedUserId] [bigint],
				[UpdatedDateTime] [datetime],
				[IsObsolete] [bit],
				[OrgGroupId] [smallint],
				[OrgLogo] [varbinary](max),
				[EmployeeId] [bigint],
				[OrderIndex] [int],
				[PrincipalSignature] [varbinary](max),
				[ICardBackground] [varbinary](max),
				[ICardBackBackGround] [varbinary](max),
				[ICardOrgTitle] [nvarchar](200),
				[ICardAddress1] [nvarchar](200),
				[ICardAddress2] [nvarchar](200),
				[ICardAddress3] [nvarchar](200),
				[LabelColor] [nvarchar](20),
				[DetailColor] [nvarchar](20),
				[HeaderColor] [nvarchar](20),
				[OrgSubGroupId] [int]
			  )) A
			  WHERE sSetup.tOrganizationMaster.Id = A.Id
		
END
ELSE
BEGIN		
		
		 INSERT INTO sSetup.tOrganizationMaster
		(
			Id,
			Code,
			Title,
			DisplayTitle,
			AffiliationId,
			LanguageId,
			StreetOne,
			StreetTwo,
			StreetThree,
			CityName,
			StateName,
			CountryName,
			ZipCode,
			HomePage,
			PhoneNo,
			FaxNo,
			ReportOrgTitle,
			SmallAddress1,
			SmallAddress2,
			RegistrationDetail,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime,
			IsObsolete,
			OrgGroupId,
			OrgLogo,
			EmployeeId,
			OrderIndex,
			PrincipalSignature,
			ICardBackBackGround,
			ICardOrgTitle,
			ICardAddress1,
			ICardAddress2,
			ICardAddress3,
			LabelColor,
			DetailColor,
			HeaderColor,
			OrgSubGroupId
			)
		SELECT		
			A.Id,
			A.Code,
			A.Title,
			A.DisplayTitle,
			A.AffiliationId,
			A.LanguageId,
			A.StreetOne,
			A.StreetTwo,
			A.StreetThree,
			A.CityName,
			A.StateName,
			A.CountryName,
			A.ZipCode,
			A.HomePage,
			A.PhoneNo,
			A.FaxNo,
			A.ReportOrgTitle,
			A.SmallAddress1,
			A.SmallAddress2,
			A.RegistrationDetail,
			A.CreatedUserId,
			A.CreatedDateTime,
			A.UpdatedUserId,
			A.UpdatedDateTime,
			A.IsObsolete,
			A.OrgGroupId,
			A.OrgLogo,
			A.EmployeeId,
			A.OrderIndex,
			A.PrincipalSignature,
			A.ICardBackBackGround,
			A.ICardOrgTitle,
			A.ICardAddress1,
			A.ICardAddress2,
			A.ICardAddress3,
			A.LabelColor,
			A.DetailColor,
			A.HeaderColor,
			A.OrgSubGroupId
						
		FROM OPENXML (@loDoc, '/Table/RowData', 1)
		WITH ( 
				[Id] [smallint],
				[Code] [nvarchar](20),
				[Title] [nvarchar](100),
				[DisplayTitle] [nvarchar](100),
				[AffiliationId] [smallint],
				[LanguageId] [smallint],
				[StreetOne] [nvarchar](50),
				[StreetTwo] [nvarchar](50),
				[StreetThree] [nvarchar](50),
				[CityName] [nvarchar](100),
				[StateName] [nvarchar](100),
				[CountryName] [nvarchar](100),
				[ZipCode] [nvarchar](20),
				[HomePage] [nvarchar](100),
				[PhoneNo] [nvarchar](50),
				[FaxNo] [nvarchar](50),
				[ReportOrgTitle] [nvarchar](200),
				[SmallAddress1] [nvarchar](200),
				[SmallAddress2] [nvarchar](200),
				[RegistrationDetail] [nvarchar](200),
				[CreatedUserId] [bigint],
				[CreatedDateTime] [datetime],
				[UpdatedUserId] [bigint],
				[UpdatedDateTime] [datetime],
				[IsObsolete] [bit],
				[OrgGroupId] [smallint],
				[OrgLogo] [varbinary](max),
				[EmployeeId] [bigint],
				[OrderIndex] [int],
				[PrincipalSignature] [varbinary](max),
				[ICardBackground] [varbinary](max),
				[ICardBackBackGround] [varbinary](max),
				[ICardOrgTitle] [nvarchar](200),
				[ICardAddress1] [nvarchar](200),
				[ICardAddress2] [nvarchar](200),
				[ICardAddress3] [nvarchar](200),
				[LabelColor] [nvarchar](20),
				[DetailColor] [nvarchar](20),
				[HeaderColor] [nvarchar](20),
				[OrgSubGroupId] [int]
			  ) A LEFT JOIN sSetup.tOrganizationMaster OM
			  ON A.Id = OM.Id WHERE OM.Id IS NULL
			  
	EXECUTE [sCommon].[pOrganizationSetupAdd]  @rOrgId
			  
	END	
		 EXEC sp_xml_removedocument @loDoc
        SELECT 1 AS Result
	 END	
	
	END TRY
	
	BEGIN CATCH 
		
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sSetup].[pPortalMasterOrgGroupUpdate]...';


GO


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

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

	 BEGIN	
	 
	 if EXISTS (SELECT 1 FROM sSetup.tOrgGroupMaster WHERE Id = @rOrgGroupId)
	BEGIN
	UPDATE sSetup.tOrgGroupMaster
		SET
			Code = A.Code,
			Title = A.Title,
			PunchLine = A.PunchLine,
			CRMLicenceNo = A.CRMLicenceNo
		 FROM
		 (
		SELECT		
			Id,
			Code,
			Title,
			PunchLine,
			CRMLicenceNo
						
		FROM OPENXML (@loDoc, '/Table/RowData', 1)
		WITH ( 
				Id int,
				Code nvarchar(20),
				Title nvarchar(100),					
				PunchLine nvarchar(200),
				CRMLicenceNo int
			  )) A
			  WHERE sSetup.tOrgGroupMaster.Id = A.Id
		
		END
		ELSE
		BEGIN
	
	
	
	EXECUTE	[sSetup].[pOrgGroupMasterAdd] 0,@rOrgGroupId,@rOrgGroupId,@rOrgGroupId,'','','2001-01-01','2002-01-01'
	
	exec   [sSecurity].[pModulePermissionReset] @rOrgGroupId,1
	exec   [sSecurity].[pResetPortalUserPermission] @rOrgGroupId,'OrganizationPortalTask'
	exec   [sSecurity].[pResetPortalUserPermission] @rOrgGroupId,'AdminPortal'
	exec   [sSecurity].[pResetPortalUserPermission] @rOrgGroupId,'ParentPortal'
	exec  [sSecurity].[pResetPortalUserPermission] @rOrgGroupId,'EmployeePortal'	
		-- INSERT INTO sSetup.tOrgGroupMaster
		--(
		--	Id,
		--	Code,
		--	Title,
		--	PunchLine,
		--	CRMLicenceNo
		--	)
		--SELECT		
		--	A.Id,
		--	A.Code,
		--	A.Title,
		--	A.PunchLine,
		--	A.CRMLicenceNo
						
		--FROM OPENXML (@loDoc, '/Table/RowData', 1)
		--WITH ( 
		--		Id int,
		--		Code nvarchar(20),
		--		Title nvarchar(100),					
		--		PunchLine nvarchar(200),
		--		CRMLicenceNo int
		--	  ) A LEFT JOIN sSetup.tOrgGroupMaster OGM
		--	  ON A.Id = OGM.Id WHERE OGM.Id IS NULL
			  
		UPDATE sSetup.tOrgGroupMaster
		SET
			Code = A.Code,
			Title = A.Title,
			PunchLine = A.PunchLine,
			CRMLicenceNo = A.CRMLicenceNo
		 FROM
		 (
		SELECT		
			Id,
			Code,
			Title,
			PunchLine,
			CRMLicenceNo
						
		FROM OPENXML (@loDoc, '/Table/RowData', 1)
		WITH ( 
				Id int,
				Code nvarchar(20),
				Title nvarchar(100),					
				PunchLine nvarchar(200),
				CRMLicenceNo int
			  )) A
			  WHERE sSetup.tOrgGroupMaster.Id = A.Id	
			  
		END
		 EXEC sp_xml_removedocument @loDoc
        SELECT 1 AS Result
	 END	
	
	END TRY
	
	BEGIN CATCH 
		
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [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(50),
			@lPresentStreetTwo nvarchar(50),
			@lPresentStreetThree nvarchar(50),
			@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)
			
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(50),
		PresentStreetTwo nvarchar(50),
		PresentStreetThree nvarchar(50),
		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),
		CreatedUserId bigint
	)
		
	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,
		CreatedUserId			
	)
	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,
		CreatedUserId	
	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(50) '@PresentStreetOne',
		PresentStreetTwo nvarchar(50) '@PresentStreetTwo',
		PresentStreetThree nvarchar(50) '@PresentStreetThree',
		PresentCity nvarchar(50) '@PresentCity',
		PresentZipCode nvarchar(20) '@PresentZipCode',
		PresentState nvarchar(50) '@PresentState',
		PresentCountry nvarchar(50) '@PresentCountry',
		PresentContactNo nvarchar(20) '@PresentContactNo',
		--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',
		CreatedUserId bigint '@CreatedUserId'
	)
	
	--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 @OutClassId = null
		--SET @OutDivisionId = null
		SET @OutStudentId = null
		--SET @OutAdmissionStandardId = null
		--SET @OutReligionId = 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
											 	 
FROM #tTable WHERE Id = @lCount  

	SELECT	@lGenderId = ID FROM sCommon.tGenderMaster WHERE Title = @lGender
	SELECT	@lClassId  = ID FROM sSetup.tClassMaster WHERE Title = @lClass AND OrgId = @rOrgId
	SELECT	@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
	
	IF(@lGenderId IS NULL)
		SET @lGenderId = 0
	IF(@lBloodGroupId IS NULL)
		SET	@lBloodGroupId = 0
	IF(@lCastCategoryId IS NULL)
		SET	@lCastCategoryId = 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

EXEC sStudent.pStudentMasterAdd 0,@lCode,@lRegistrationNumber,@lNumber,@lFirstName,@lMiddleName,@lLastName,@rOrgId,@lAdmissionCategoryId,1,0,@rUserId,@rUserId,@OutStudentId OUTPUT

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,NULL,@lDOB,@lGenderId,@lReligionId,@lBloodGroupId,@lBirthPlace,@lBirthTaluka,@lBirthDistrict,NULL,
			@lFamilyCast,@lFamilySubCast,@lCastCategoryId,NULL,NULL,NULL,NULL,NULL,'',@rUserId,@rUserId
  
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

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


GO

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

BEGIN TRY
BEGIN TRANSACTION

EXEC sp_xml_preparedocument @loDoc OUTPUT,@rXML
BEGIN
	
	IF(@rSubCategoryField = 'Gender' OR @rSubCategoryField = 'Religion' OR @rSubCategoryField = 'BloodGroup' 
			OR @rSubCategoryField = 'CastCategory' OR @rSubCategoryField = 'TransportMode' OR @rSubCategoryField = 'House'
			OR @rSubCategoryField = 'MotherTongue' OR @rSubCategoryField = 'Nationality' OR @rSubCategoryField = 'AdmissionStandard' OR  @rSubCategoryField = 'AdmissionCategory' )
	BEGIN
		SET @rSubCategoryField = @rSubCategoryField + 'Id'
	END
		
	CREATE TABLE ListofData(Id bigint,StudentId bigint,SubCategory nvarchar(100),UpdatedUserId bigint,IsExist bit);
	IF(@rCategoryId= 1)
		BEGIN
		insert into ListofData
		select 0,E.StudentId,E.SubCategory,E.UpdatedUserId,0
		from
		(
				SELECT StudentId,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Students/Students', 2)
				WITH (
						StudentId BIGINT, 
						SubCategory nvarchar(100),
						UpdatedUserId bigint)	
						)E 	
		UPDATE ListofData SET IsExist=1 WHERE StudentId NOT IN(SELECT StudentId FROM sStudent.tStudentCommunication) 
		
		set @sql='INSERT INTO sStudent.tStudentCommunication 
					(StudentId,'+@rSubCategoryField+',CreatedUserId,CreatedDateTime)
					SELECT
						LD.StudentId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
					FROM
						ListofData LD WHERE LD.IsExist=1'
		Exec sp_executesql @sql
		set @sql='UPDATE sStudent.tStudentCommunication set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sStudent.tStudentCommunication SC 
					INNER JOIN ListofData LD ON SC.StudentId=LD.StudentId AND IsExist=0'
		
		Exec sp_executesql @sql
		
		
		
		Drop Table ListofData
			 SELECT 1 AS StatusCode
	    END
	Else IF(@rCategoryId= 2)
		BEGIN
		insert into ListofData
		select 0,E.StudentId,E.SubCategory,E.UpdatedUserId,0
		from
		(
				SELECT StudentId,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Students/Students', 2)
				WITH (
						StudentId BIGINT, 
						SubCategory nvarchar(100),
						UpdatedUserId bigint)	
						)E 	
		UPDATE ListofData SET IsExist=1 WHERE StudentId NOT IN(SELECT StudentId FROM sStudent.tStudentOther) 
		
		IF(@rSubCategoryField = 'DateOfBirth')
		BEGIN			
			set @sql='INSERT INTO sStudent.tStudentOther 
					(StudentId,'+@rSubCategoryField+',CreatedUserId,CreatedDateTime)
					SELECT
						LD.StudentId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
					FROM
						ListofData LD WHERE LD.IsExist=1'
			Exec sp_executesql @sql				
			 				
			set @sql='UPDATE sStudent.tStudentOther set '+@rSubCategoryField+' = LD.SubCategory,
						UpdatedUserId=LD.UpdatedUserId,
						UpdatedDateTime=sCommon.fGetDate()  
						from sStudent.tStudentOther SO 
						INNER JOIN ListofData LD ON SO.StudentId=LD.StudentId'			
			Exec sp_executesql @sql
			set @sql='UPDATE sStudent.tStudentOther SET '+@rSubCategoryField+' = null WHERE DateOfBirth=''1900-01-01'''
			Exec sp_executesql @sql
		END
		ELSE
		BEGIN
			set @sql='INSERT INTO sStudent.tStudentOther 
						(StudentId,'+@rSubCategoryField+',CreatedUserId,CreatedDateTime)
						SELECT
							LD.StudentId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
						FROM
							ListofData LD WHERE LD.IsExist=1'
			Exec sp_executesql @sql				
			 				
			set @sql='UPDATE sStudent.tStudentOther set '+@rSubCategoryField+' = LD.SubCategory,
						UpdatedUserId=LD.UpdatedUserId,
						UpdatedDateTime=sCommon.fGetDate()  
						from sStudent.tStudentOther SO 
						INNER JOIN ListofData LD ON SO.StudentId=LD.StudentId'
			
			Exec sp_executesql @sql
		END
		Drop Table ListofData
			 SELECT 1 AS StatusCode
	    END	
	    
	    
	    
	Else IF(@rCategoryId= 3)
		BEGIN
		insert into ListofData
		select 0,E.StudentId,E.SubCategory,E.UpdatedUserId,0
		from
		(
				SELECT StudentId,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Students/Students', 2)
				WITH (
						StudentId BIGINT, 
						SubCategory nvarchar(100),
						UpdatedUserId bigint)	
						)E 	
						
		 				
		set @sql='UPDATE sStudent.tStudentAdmission set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sStudent.tStudentAdmission SA 
					INNER JOIN ListofData LD ON SA.StudentId=LD.StudentId'
		
		Exec sp_executesql @sql
		Drop Table ListofData
			 SELECT 1 AS StatusCode
	    END	
  Else IF(@rCategoryId= 4)
	BEGIN
		insert into ListofData
		select 0,E.StudentId,E.SubCategory,E.UpdatedUserId,0
		from
		(
				SELECT StudentId,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Students/Students', 2)
				WITH (
						StudentId BIGINT, 
						SubCategory nvarchar(100),
						UpdatedUserId bigint)	
						)E 	
		UPDATE ListofData SET IsExist=1 WHERE StudentId NOT IN(SELECT StudentId FROM sStudent.tStudentFamily) 
		
		set @sql='INSERT INTO sStudent.tStudentFamily 
					(StudentId,'+@rSubCategoryField+',CreatedUserId,CreatedDateTime)
					SELECT
						LD.StudentId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
					FROM
						ListofData LD WHERE LD.IsExist=1'				
		Exec sp_executesql @sql
		set @sql='UPDATE sStudent.tStudentFamily set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sStudent.tStudentFamily SA 
					INNER JOIN ListofData LD ON SA.StudentId=LD.StudentId AND IsExist=0'
		
		Exec sp_executesql @sql
		Drop Table ListofData
			 SELECT 1 AS StatusCode
	    END
	    
    Else IF(@rCategoryId= 5)
	     BEGIN
		insert into ListofData
		select 0,E.StudentId,E.SubCategory,E.UpdatedUserId,0
		from
		(
				SELECT StudentId,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Students/Students', 2)
				WITH (
						StudentId BIGINT, 
						SubCategory nvarchar(100),
						UpdatedUserId bigint)	
						)E 	
		UPDATE ListofData SET IsExist=1 WHERE StudentId NOT IN(SELECT StudentId FROM sStudent.tStudentHealth) 
		
		set @sql='INSERT INTO sStudent.tStudentHealth 
					(StudentId,'+@rSubCategoryField+',UpdatedUserId,UpdatedDateTime)
					SELECT
						LD.StudentId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
					FROM
						ListofData LD WHERE LD.IsExist=1'				
		Exec sp_executesql @sql
		set @sql='UPDATE sStudent.tStudentHealth set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sStudent.tStudentHealth SA 
					INNER JOIN ListofData LD ON SA.StudentId=LD.StudentId AND IsExist=0'
		
		Exec sp_executesql @sql
		Drop Table ListofData
			 SELECT 1 AS StatusCode
	    END		 
	 
	 Else IF(@rCategoryId= 6)
	    BEGIN
		insert into ListofData
		select E.Id,0,E.SubCategory,E.UpdatedUserId,0
		from
		(
				SELECT Id,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Students/Students', 2)
				WITH (
						Id BIGINT, 
						SubCategory nvarchar(100),
						UpdatedUserId bigint)	
						)E 	
		UPDATE ListofData SET IsExist=1 WHERE Id NOT IN(SELECT AcademicId FROM sStudent.tAcademicDetail) 
		
		set @sql='INSERT INTO sStudent.tAcademicDetail 
					(AcademicId,'+@rSubCategoryField+')
					SELECT
						LD.Id,Ld.SubCategory
					FROM
						ListofData LD WHERE LD.IsExist=1'				
		Exec sp_executesql @sql
		set @sql='UPDATE sStudent.tAcademicDetail set '+@rSubCategoryField+' = LD.SubCategory
					from sStudent.tAcademicDetail AD 
					INNER JOIN ListofData LD ON AD.AcademicId=LD.Id AND IsExist=0'
		
		Exec sp_executesql @sql
		Drop Table ListofData
			 SELECT 1 AS StatusCode
	    END	
	    
	Else IF(@rCategoryId= 7)
	     BEGIN
		insert into ListofData
		select 0,E.StudentId,E.SubCategory,E.UpdatedUserId,0
		from
		(
				SELECT StudentId,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Students/Students', 2)
				WITH (
						StudentId BIGINT, 
						SubCategory nvarchar(100),
						UpdatedUserId bigint)	
						)E 	
		UPDATE ListofData SET IsExist=1 WHERE StudentId NOT IN(SELECT Id FROM sStudent.tStudentMaster) 
		
		--set @sql='INSERT INTO sStudent.tStudentMaster 
		--			(StudentId,'+@rSubCategoryField+',UpdatedUserId,UpdatedDateTime)
		--			SELECT
		--				LD.StudentId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
		--			FROM
		--				ListofData LD WHERE LD.IsExist=1'				
		--Exec sp_executesql @sql
		set @sql='UPDATE sStudent.tStudentMaster set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sStudent.tStudentMaster SA 
					INNER JOIN ListofData LD ON SA.Id=LD.StudentId AND IsExist=0'
		
		Exec sp_executesql @sql
		Drop Table ListofData
			 SELECT 1 AS StatusCode
	    END			 
	 
END 
	   COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
GO
PRINT N'Altering [sStudent].[pStudentDataUpdateGet]...';


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

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

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

  --ORDER BY  SF.RelationshipId ASC  
		
END
GO
PRINT N'Creating [sAcademic].[pClassworkStudentGet]...';


GO
CREATE PROCEDURE [sAcademic].[pClassworkStudentGet]
	 @rStudentId bigint,
	 @rBatchId int,	 
	 @rFromDate datetime,
     @rToDate datetime	 
	 
	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.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
	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,'')='')
		order by  AC.CreatedDateTime desc
END
GO
PRINT N'Creating [sAssessment].[pMyResultGet]...';


GO


CREATE PROCEDURE [sAssessment].[pMyResultGet]
	 
	@rExamSubGroupId int = 0,
	@rStudentId bigint =0,
	@rAcademicId bigint = 0,
	@rBatchId int = 0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
SELECT
		R.Id AS ResultId, 
		R.ExamId,
		ISNULL(E.ReportId,0) AS ReportId,
		ESGM.Title AS ExamName,
		StuM.FirstName+' '+StuM.LastName AS StudentName,
		StuM.Id AS StudentId,
		A.RollNo,
		DM.DisplayTitle AS Division,
		R.TotalMarks,
		R.TotalObtain AS Obtain,
		R.ResultStatus,
		R.ResultGrade,
		R.RankNumber,
		R.Percentage,
		R.Percentile,	
		ESGM.Id AS ExamSubGroupId,
		BM.Id AS BatchId,
		BM.Title AS BatchName
		
		
FROM 
			sAssessment.tResult R 
			INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
			INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
			INNER JOIN sAssessment.tExamMaster E ON R.ExamId = E.Id
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = E.ExamSubGroupId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
		
			
	WHERE 
	
			(ESGM.Id=@rExamSubGroupId OR @rExamSubGroupId=0)
		--AND ((ESGM.Id = @rExamSubGroupId) OR (@rExamSubGroupId =0))
		AND  StuM.Id = @rStudentId 
		AND ((A.Id = @rAcademicId) OR (@rAcademicId =0))
		AND ((BM.Id = @rBatchId) OR (@rBatchId =0))
		AND (E.IsPublished = 1)
	
		 order by ESGM.OrderIndex desc
		
		
		 
		 
		
	
	
		
END
GO
PRINT N'Creating [sHrm].[pEmployeeBulkDataUpdateGet]...';


GO
CREATE PROCEDURE [sHrm].[pEmployeeBulkDataUpdateGet]
	 
	 @rEmployeeDataTypeId int,
	 @rLocationId nvarchar(50)  
	 
AS
SET NOCOUNT ON

BEGIN
		 Declare @Sql nvarchar(max)
		 
		 SET @Sql =  CASE @rEmployeeDataTypeId					  
					 WHEN 1 THEN -- ProcessType
					  'SELECT EJD.EmployeeId,ISNULL(EM.FirstName,'''')+'' ''+ISNULL(EM.MiddleName,'''')+'' ''+ISNULL(EM.LastName,'''') AS Name,EM.Code,ISNULL(EJD.ProcessTypeId,''0'') AS SelectedValue
					   FROM sHrm.tEmployeeMaster EM INNER JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id = EJD.EmployeeId WHERE EmployeeLocationId = '+@rLocationId+' Order By EM.Code ASC'
				 	
				 	 WHEN 2 THEN -- Company
					  'SELECT EJD.EmployeeId,ISNULL(EM.FirstName,'''')+'' ''+ISNULL(EM.MiddleName,'''')+'' ''+ISNULL(EM.LastName,'''') AS Name,EM.Code,ISNULL(EJD.EmployeeCompanyId,0) AS SelectedValue
					   FROM sHrm.tEmployeeMaster EM INNER JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id = EJD.EmployeeId WHERE EmployeeLocationId = '+@rLocationId+' Order By EM.Code ASC'
				 				  
					 WHEN 3 THEN -- Contractor
					  'SELECT EJD.EmployeeId,ISNULL(EM.FirstName,'''')+'' ''+ISNULL(EM.MiddleName,'''')+'' ''+ISNULL(EM.LastName,'''') AS Name,EM.Code,ISNULL(EJD.ContractorId,'''') AS SelectedValue
					   FROM sHrm.tEmployeeMaster EM INNER JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id = EJD.EmployeeId WHERE EmployeeLocationId = '+@rLocationId+' Order By EM.Code ASC'				  
					 				  
					 WHEN 4 THEN --Designation
					 'SELECT EJD.EmployeeId,ISNULL(EM.FirstName,'''')+'' ''+ISNULL(EM.MiddleName,'''')+'' ''+ISNULL(EM.LastName,'''') AS Name,EM.Code,ISNULL(EJD.EmployeeDesignationId,'''') AS SelectedValue
					FROM sHrm.tEmployeeMaster EM INNER JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id = EJD.EmployeeId WHERE EmployeeLocationId = '+@rLocationId+' Order By EM.Code ASC'			 
		 				  
					 WHEN 5 THEN --EsiNumber
					 'SELECT EJD.EmployeeId,ISNULL(EM.FirstName,'''')+'' ''+ISNULL(EM.MiddleName,'''')+'' ''+ISNULL(EM.LastName,'''') AS Name,EM.Code,ISNULL(EJD.ESINumber,'''') AS SelectedValue
					FROM sHrm.tEmployeeMaster EM INNER JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id = EJD.EmployeeId WHERE EmployeeLocationId = '+@rLocationId+' Order By EM.Code ASC'				   
				 				  
					 WHEN 6 THEN --BloodGroup
					 'SELECT EPD.EmployeeId,ISNULL(EM.FirstName,'''')+'' ''+ISNULL(EM.MiddleName,'''')+'' ''+ISNULL(EM.LastName,'''') AS Name,EM.Code,ISNULL(EPD.BloodGroupId,'''') AS SelectedValue
					FROM sHrm.tEmployeeMaster EM INNER JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id = EJD.EmployeeId INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EM.Id = EPD.EmployeeId WHERE EmployeeLocationId = '+@rLocationId+' Order By EM.Code ASC'					   
				 				  
					 WHEN 7 THEN --MaritalStatus
					 'SELECT EPD.EmployeeId,ISNULL(EM.FirstName,'''')+'' ''+ISNULL(EM.MiddleName,'''')+'' ''+ISNULL(EM.LastName,'''') AS Name,EM.Code,ISNULL(EPD.MaritalStatusId,'''') AS SelectedValue
					  FROM sHrm.tEmployeeMaster EM INNER JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id = EJD.EmployeeId INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EM.Id = EPD.EmployeeId WHERE EmployeeLocationId = '+@rLocationId+' Order By EM.Code ASC' 
				 				  
					 WHEN 8 THEN --Religion
					 'SELECT EPD.EmployeeId,ISNULL(EM.FirstName,'''')+'' ''+ISNULL(EM.MiddleName,'''')+'' ''+ISNULL(EM.LastName,'''') AS Name,EM.Code,ISNULL(EPD.ReligionId,'''') AS SelectedValue
					FROM sHrm.tEmployeeMaster EM INNER JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id = EJD.EmployeeId INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EM.Id = EPD.EmployeeId WHERE EmployeeLocationId = '+@rLocationId+' Order By EM.Code ASC'					   
				 				  
					 WHEN 9 THEN --Idmark1
					 'SELECT EPD.EmployeeId,ISNULL(EM.FirstName,'''')+'' ''+ISNULL(EM.MiddleName,'''')+'' ''+ISNULL(EM.LastName,'''') AS Name,EM.Code,ISNULL(EPD.IdentificationMark1,'''') AS SelectedValue
					FROM sHrm.tEmployeeMaster EM INNER JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id = EJD.EmployeeId INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EM.Id = EPD.EmployeeId WHERE EmployeeLocationId = '+@rLocationId+' Order By EM.Code ASC'	   
			 				  
					 WHEN 10 THEN --IdMark2
					 'SELECT EPD.EmployeeId,ISNULL(EM.FirstName,'''')+'' ''+ISNULL(EM.MiddleName,'''')+'' ''+ISNULL(EM.LastName,'''') AS Name,EM.Code,ISNULL(EPD.IdentificationMark2,'''') AS SelectedValue
					FROM sHrm.tEmployeeMaster EM INNER JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id = EJD.EmployeeId  INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EM.Id = EPD.EmployeeId WHERE EmployeeLocationId = '+@rLocationId+' Order By EM.Code ASC' 	
				END 
				
		
	   EXECUTE  sp_executesql @Sql
END
GO
PRINT N'Creating [sLibrary].[pMyBookLogListGet]...';


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


GO
CREATE PROCEDURE [sPayroll].[pEmployeePayrollListGet]

	@rPayrollId int,
	@rPayrollGroupId int
 
AS
SET NOCOUNT ON

BEGIN
		SELECT 
				EM.Code AS Code,
				ISNULL(EM.FirstName, '') + ' ' + ISNULL(EM.MiddleName, '') + ' ' + ISNULL(EM.LastName, '') AS Name,
				ISNULL(ETM.Title,'') As EmployeeType,
				OM.Title AS OrganizationName,
				ODM.Title AS OrganizationDepartmentName,
				PGM.Title AS PayrollGroupName
		FROM 
				sHrm.tEmployeeMaster EM
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=EM.OrgId
			INNER JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.EmployeeId = EM.Id  
			INNER JOIN sPayroll.tPayrollGroupMaster PGM ON ESO.PayrollGroupId = PGM.ID
			INNER JOIN sSetup.tDepartmentMaster ODM ON ODM.Id = EJD.OrganizationDepartmentId
			LEFT JOIN sHrm.tEmployeeTypeMaster ETM ON ETM.Id = EJD.EmployeeTypeId
		WHERE 
				ESO.PayrollId = @rPayrollId 
				AND ((ESO.PayrollGroupId=@rPayrollGroupId) OR (@rPayrollGroupId=0))
END
GO
PRINT N'Creating [sPayroll].[pPayrollGroupMasterAdd]...';


GO

CREATE PROCEDURE [sPayroll].[pPayrollGroupMasterAdd]
	 
	        @rId int,
			@rCode nvarchar(100),
			@rTitle nvarchar(100),
			@rCreatedUserId bigint,       
			@rIsObsolete bit,
			@rPayrollId int,
			@rOrgGroupId smallint    
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	 
	 BEGIN TRANSACTION	
 IF(@rId = 0)	
BEGIN
    
	DECLARE @lNextNumber INT     

EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sPayroll.tPayrollGroupMaster',@lNextNumber = @lNextNumber output
 
INSERT INTO [sPayroll].[tPayrollGroupMaster]
           (
			[Id],
           [Code],
           [Title],
           [CreatedUserId],
           [CreatedDateTime],
            [IsObsolete],
           [PayrollId],
           [OrgGroupId]
           )
     VALUES
           (
           @lNextNumber,
           @rCode ,
           @rTitle ,
           @rCreatedUserId, 
           sCommon.fGetDate(),
           @rIsObsolete,
           ISNULL(@rPayrollId,''),
           @rOrgGroupId 
           ) 
           SELECT 1 AS Result
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE [sPayroll].[tPayrollGroupMaster]
	    SET
			code = @rCode,
			Title = @rTitle,
			UpdatedUserId= @rCreatedUserId,
			UpdatedDateTime =sCommon.fGetDate(),
			IsObsolete = @rIsObsolete,
			PayrollId = @rPayrollId,	
			OrgGroupId = @rOrgGroupId
	      
	      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 [sPayroll].[pPayrollGroupMasterGet]...';


GO

CREATE PROCEDURE [sPayroll].[pPayrollGroupMasterGet]
	 
	 @rId int = 0,
	 @rTitle nvarchar(100),
	 @rCode nvarchar(100),
	 @rOrgGroupId smallint
		
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	  --BEGIN 
			--SET @rTitle = sCommon.fSearchStringGet(@rTitle)
			--SET @rCode = sCommon.fSearchStringGet(@rCode)
	  --END	 
	SELECT 
		PGM.Id,
		PGM.Code,
		PGM.Title,
		PGM.IsObsolete
		--PGM.PayrollId,
		--PM.Title
  FROM 
      sPayroll.tPayrollGroupMaster PGM
      -- INNER JOIN sAccounting.tAccountMaster AM ON AM.Id = AYM.AccountId
        --INNER JOIN sSetup.tAffiliationMaster AM
        --ON DSM.AffiliationId= AM.Id 
  WHERE  
             ((PGM.Id = @rId) OR (@rId = 0))
        AND  ((PGM.Title=@rTitle) OR (ISNULL(@rTitle,'') = '')) 
        AND  ((PGM.Code=@rCode) OR (ISNULL(@rCode,'') = ''))
		AND PGM.OrgGroupId = @rOrgGroupId
		order by PGM.CreatedDateTime desc
		
END
GO
PRINT N'Creating [sPayroll].[pPayrollMasterAdd]...';


GO




CREATE PROCEDURE [sPayroll].[pPayrollMasterAdd]
	 
	        @rId int,
			@rCode nvarchar(100),
			@rTitle nvarchar(100),
			@rCreatedUserId bigint,       
			@rOrgGroupId smallint,
			@rIsActive bit
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	 
	 BEGIN TRANSACTION	
 IF(@rId = 0)	
BEGIN
    
	DECLARE @lNextNumber INT     

EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sPayroll.tPayrollMaster',@lNextNumber = @lNextNumber output
 
INSERT INTO [sPayroll].[tPayrollMaster]
           (
			[Id],
           [Code],
           [Title],
           [CreatedUserId],
           [CreatedDateTime],
           --[UpdatedUserId],
           --[UpdatedDateTime],
           [OrgGroupId],
           [IsActive]
           )
     VALUES
           (
            @lNextNumber,
           @rCode ,
           @rTitle ,
           @rCreatedUserId, 
           sCommon.fGetDate(),
           --@rCreatedUserId,
           --sCommon.fGetDate(), 
           @rOrgGroupId, 
           @rIsActive
           ) 
           SELECT 1 AS Result
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE [sPayroll].[tPayrollMaster]
	    SET
			code = @rCode,
			Title = @rTitle,
			UpdatedUserId= @rCreatedUserId,
			UpdatedDateTime =sCommon.fGetDate(),	
			IsActive = @rIsActive
	      
	      WHERE Id = @rId 	 
	       SELECT 11 AS Result  
	 END  
		 
	
		  COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Creating [sPayroll].[pPayrollMasterGet]...';


GO

CREATE PROCEDURE [sPayroll].[pPayrollMasterGet]
	 
	 @rId int = 0,
	 --@rAffiliationId int,
	 @rTitle nvarchar(100),
	 @rCode nvarchar(100),
	 @rOrgGroupId smallint
		
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	  --BEGIN 
			--SET @rTitle = sCommon.fSearchStringGet(@rTitle)
			--SET @rCode = sCommon.fSearchStringGet(@rCode)
	  --END	 
	SELECT 
		PM.Id,
		PM.Code,
		PM.Title,
		PM.IsActive     
  FROM 
      sPayroll.tPayrollMaster PM
       --INNER JOIN sAccounting.tAccountMaster AM ON AM.Id = AYM.AccountId
        --INNER JOIN sSetup.tAffiliationMaster AM
        --ON DSM.AffiliationId= AM.Id 
  WHERE  
             ((PM.Id = @rId) OR (@rId = 0))
        AND  ((PM.Title=@rTitle) OR (ISNULL(@rTitle,'') = '')) 
        AND  ((PM.Code=@rCode) OR (ISNULL(@rCode,'') = ''))
		AND PM.OrgGroupId = @rOrgGroupId
		order by PM.CreatedDateTime desc
		
END
GO
PRINT N'Creating [sPayroll].[pPayrollYearMasterAdd]...';


GO

CREATE PROCEDURE [sPayroll].[pPayrollYearMasterAdd]
	 
	        @rId int,
			@rCode nvarchar(100),
			@rTitle nvarchar(100),
			@rFromDate date,
			@rToDate date,
			@rCreatedUserId bigint,
			@rPayrollId int,     
			@rOrgGroupId smallint,
			@rIsActive bit
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	 
	 BEGIN TRANSACTION	
 IF(@rId = 0)	
BEGIN
    
	DECLARE @lNextNumber INT     

EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sPayroll.tPayrollYearMaster',@lNextNumber = @lNextNumber output
 
INSERT INTO [sPayroll].[tPayrollYearMaster]
           (
			[Id],
           [Code],
           [Title],
           [FromDate],
           [ToDate],
           [CreatedUserId],
           [CreatedDateTime],
           [PayrollId],
           --[UpdatedUserId],
           --[UpdatedDateTime],
           [IsActive],
           [OrgGroupId]
         
           )
     VALUES
           (
            @lNextNumber,
           @rCode ,
           @rTitle ,
           @rFromDate,
           @rToDate,
           @rCreatedUserId, 
           sCommon.fGetDate(),
           @rPayrollId,
           --@rCreatedUserId,
           --sCommon.fGetDate(), 
           @rIsActive,
           @rOrgGroupId 
           
           ) 
           SELECT 1 AS Result
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE [sPayroll].[tPayrollYearMaster]
	    SET
			code = @rCode,
			Title = @rTitle,
			FromDate =@rFromDate,
			ToDate = @rToDate,
			UpdatedUserId= @rCreatedUserId,
			UpdatedDateTime =sCommon.fGetDate(),
			PayrollId = @rPayrollId,	
			IsActive = @rIsActive,
			OrgGroupId = @rOrgGroupId
	      
	      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 [sPayroll].[pPayrollYearMasterGet]...';


GO

CREATE PROCEDURE [sPayroll].[pPayrollYearMasterGet]
	 
	 @rId int = 0,
	 @rTitle nvarchar(100),
	 @rCode nvarchar(100),
	 @rOrgGroupId smallint
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	  --BEGIN 
			--SET @rTitle = sCommon.fSearchStringGet(@rTitle)
			--SET @rCode = sCommon.fSearchStringGet(@rCode)
	  --END	 
	SELECT 
		PYM.Id,
		PYM.Code,
		PYM.Title,
		PYM.IsActive,
		PYM.PayrollId,
		PM.Title,
		PYM.FromDate,
		PYM.ToDate
		     
  FROM 
      sPayroll.tPayrollYearMaster PYM
      INNER JOIN sPayroll.tPayrollMaster PM ON PM.Id = PYM.PayrollId
        --INNER JOIN sSetup.tAffiliationMaster AM
        --ON DSM.AffiliationId= AM.Id 
  WHERE  
             ((PYM.Id = @rId) OR (@rId = 0))
        AND  ((PYM.Title=@rTitle) OR (ISNULL(@rTitle,'') = '')) 
        AND  ((PYM.Code=@rCode) OR (ISNULL(@rCode,'') = ''))
  --      AND  ((PYM.FromDate >= @rFromDate) OR (ISNULL (@rFromDate,'')=''))
		--AND ((PYM.ToDate <= @rToDate) OR (ISNULL (@rToDate,'')=''))
		AND   PYM.OrgGroupId = @rOrgGroupId
		
		Order By PYM.CreatedDateTime Desc
		
END
GO
PRINT N'Creating [sPayroll].[pSelectPayElementAdd]...';


GO
CREATE PROCEDURE [sPayroll].[pSelectPayElementAdd] 
	      
			@rId int
	       ,@rCode nvarchar(20)
           ,@rTitle nvarchar(100)
           ,@rPayElementTypeId tinyint
           ,@rPaidCategoryId tinyint
           ,@rIsLwp bit
           ,@rIsEmployeeSpecific bit
           ,@rIsDepend bit
           ,@rIsAvailDuringProbation bit
           ,@rIsIncludeInPaySlip bit
           ,@rSortOrder tinyint
           ,@rIsObsolete bit
           ,@rOrgGroupId int
           ,@rCreatedUserId bigint
           ,@rPayElementDefaultId int
		   ,@rPayrollId int
          
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

	BEGIN TRY
	BEGIN TRANSACTION  
	DECLARE @lNextNumber BIGINT
  
	IF (@rId = 0)
    
    BEGIN	
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sPayroll.tPayElement', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO [sPayroll].[tPayElement]
           (
            [ID]
           ,[Code]
           ,[Title]
           ,[PayElementTypeId]
           ,[PaidCategoryId]
           ,[IsLwp]
           ,[IsEmployeeSpecific]
           ,[IsDepend]
           ,[IsAvailDuringProbation]
           ,[IsIncludeInPaySlip]
           ,[SortOrder]
           ,[IsObsolete]
           ,[CreatedUserId]
           ,[CreatedDateTime]
           ,[UpdatedUserId]
           ,[UpdatedDateTime]
           ,[PayElementDefaultId]
           ,[PayrollId]
           )
     VALUES
           (
            @lNextNumber
           ,@rCode 
           ,@rTitle 
           ,@rPayElementTypeId 
           ,@rPaidCategoryId 
           ,@rIsLwp 
           ,@rIsEmployeeSpecific 
           ,@rIsDepend 
           ,@rIsAvailDuringProbation 
           ,@rIsIncludeInPaySlip 
           ,@rSortOrder 
           ,@rIsObsolete 
           ,@rCreatedUserId 
           ,sCommon.fGetDate()  
           ,@rCreatedUserId 
           ,sCommon.fGetDate()
           ,@rPayElementDefaultId
           ,@rPayrollId
           )
        SELECT 1 AS RESULT
    	END
    ELSE
		BEGIN    
		    SET @lNextNumber = @rId
		    UPDATE  [sPayroll].[tPayElement]
			   SET   
				   [Title] = @rTitle 
				  ,[PayElementTypeId] = @rPayElementTypeId 
				  ,[PaidCategoryId] = @rPaidCategoryId 
				  ,[IsLwp] = @rIsLwp 
				  ,[IsEmployeeSpecific] = @rIsEmployeeSpecific 
				  ,[IsDepend] = @rIsDepend 
				  ,[IsAvailDuringProbation] = @rIsAvailDuringProbation 
				  ,[IsIncludeInPaySlip] = @rIsIncludeInPaySlip 
				  ,[SortOrder] = @rSortOrder 
				  ,[IsObsolete] = @rIsObsolete  
				  ,[UpdatedUserId] = @rCreatedUserId 
				  ,[UpdatedDateTime] = sCommon.fGetDate()
				  ,[PayElementDefaultId] = @rPayElementDefaultId
				  ,[PayrollId]=@rPayrollId
			   WHERE Id = @rId   		     		    
			END        
	SELECT @lNextNumber AS Result	
	COMMIT TRANSACTION
	END TRY
	BEGIN CATCH
	ROLLBACK TRANSACTION
		SELECT -1 AS RESULT
	END CATCH	
END
GO
PRINT N'Creating [sPayroll].[pSelectPayElementGet]...';


GO
CREATE PROCEDURE [sPayroll].[pSelectPayElementGet]

           @rPayrollId int
           
AS
SET NOCOUNT ON

BEGIN

	SELECT  
			ISNULL(PE.ID,0) AS ID,
			PED.Code,
			PED.Title,
			PED.PayElementTypeId,
			PED.PaidCategoryId,
			ISNULL(PE.IsLwp,0) AS IsLwp,
			ISNULL(PE.IsEmployeeSpecific,0) AS IsEmployeeSpecific,
			ISNULL(PE.IsDepend,0) AS IsDepend,
			ISNULL(PE.IsAvailDuringProbation,0) AS IsAvailDuringProbation,
			ISNULL(PE.IsIncludeInPaySlip,0) AS IsIncludeInPaySlip,
			CASE ISNULL(PE.SortOrder,0)
				WHEN 0 THEN PED.SortOrder
				ELSE PE.SortOrder
			END AS SortOrder,
			--ISNULL(PE.SortOrder,0) AS SortOrder,
			ISNULL(PE.IsObsolete,0) AS IsObsolete,
			PE.CreatedUserId,
			PE.CreatedDateTime,
			PE.UpdatedUserId,
			PE.UpdatedDateTime,
			PED.ID AS PayElementDefaultId,
			PE.PayrollId,
			PET.Title AS PayElementType
	FROM
			sPayroll.tPayElementDefault PED 
				INNER JOIN sPayroll.tPayElementType PET 
			ON PET.Id=PED.PayElementTypeId
				LEFT JOIN sPayroll.tPayElement PE 
			ON PED.ID = PE.PayElementDefaultId AND PE.PayrollId=@rPayrollId 
			ORDER BY PED.SortOrder
END
GO
PRINT N'Creating [sSetup].[pPortalAttendanceMaxDateGet]...';


GO
CREATE PROCEDURE [sSetup].[pPortalAttendanceMaxDateGet]
	 
	 @rOrgId int,
	 @rBatchId int,
	 @rDivisionId int
		 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
		   
BEGIN 
	
DECLARE
	
	@lMonthlyRegisterUpdatedDate AS Datetime

 	SELECT @lMonthlyRegisterUpdatedDate = MAX(MR.UpdatedDateTime)			 
	FROM	sAttendance.tMonthlyRegister MR
	INNER JOIN sStudent.tAcademic A ON A.Id=MR.AcademicId
		WHERE A.BatchId = @rBatchId AND A.DivisionId=@rDivisionId

 SELECT 
	
	ISNULL(@lMonthlyRegisterUpdatedDate,'1900-01-01') AS MonthlyRegisterUpdatedDate
	
 END
GO
PRINT N'Creating [sSetup].[pPortalEmployeeDesignationMasterUpdate]...';


GO


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

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

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


GO


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

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

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


GO


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

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

	 BEGIN	
	
	UPDATE sHrm.tEmployeeImages
		SET
			EmployeePhoto = A.EmployeePhoto,
			UpdatedDateTime = A.UpdatedDateTime
		 FROM
		 (
		SELECT		
		EmployeeId,
		EmployeePhoto,
		UpdatedDateTime
						
		FROM OPENXML (@loDoc, '/Table/RowData', 1)
		WITH ( 
				[EmployeeId] [bigint],
				[EmployeePhoto] [varbinary](max),
				[UpdatedDateTime] [datetime]
			  )) A
			  WHERE sHrm.tEmployeeImages.EmployeeId = A.EmployeeId
		
		
		
		 INSERT INTO sHrm.tEmployeeImages
		(
			EmployeeId,
			EmployeePhoto,
			UpdatedDateTime
			)
		SELECT		
			A.EmployeeId,
			A.EmployeePhoto,
			A.UpdatedDateTime
						
		FROM OPENXML (@loDoc, '/Table/RowData', 1)
		WITH ( 
				[EmployeeId] [bigint],
				[EmployeePhoto] [varbinary](max),
				[UpdatedDateTime] [datetime]
			  ) A LEFT JOIN sHrm.tEmployeeImages EI
			  ON A.EmployeeId = EI.EmployeeId WHERE EI.EmployeeId IS NULL
		
		 EXEC sp_xml_removedocument @loDoc
        SELECT 1 AS Result
	 END	
	
	END TRY
	
	BEGIN CATCH 
		
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Creating [sSetup].[pPortalEmployeeJobDetailUpdate]...';


GO


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

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

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


GO


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

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

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


GO
CREATE PROCEDURE [sSetup].[pPortalEmployeeMaxDateGet]
	 
	 @rOrgId int,
	 @rBatchId int=0
		 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
		   
BEGIN 
	
DECLARE
	
	@lEmployeeMasterCreatedDate AS Datetime,	
	@lEmployeeMasterUpdatedDate AS Datetime,	
	
	@lEmployeePersonalDetailUpdatedDate AS Datetime,	
	
	@lEmployeeJobDetailUpdatedDate AS Datetime,
	
	@lEmployeeImagesUpdatedDate AS Datetime,
	
	@lEmployeeGradeMasterCreatedDate AS Datetime,	
	@lEmployeeGradeMasterUpdatedDate AS Datetime,	
	
	@lEmployeeDesignationMasterCreatedDate AS Datetime,	
	@lEmployeeDesignationMasterUpdatedDate AS Datetime,
	
	@lEmployeeTypeMasterCreatedDate AS Datetime,	
	@lEmployeeTypeMasterUpdatedDate AS Datetime
	
	SELECT @lEmployeeMasterCreatedDate = MAX(EM.CreatedDateTime),
		   @lEmployeeMasterUpdatedDate = MAX(EM.UpdatedDateTime)       	 
	FROM	sHrm.tEmployeeMaster EM 
		WHERE   EM.OrgID = @rOrgId

 	SELECT @lEmployeePersonalDetailUpdatedDate = MAX(EPD.UpdatedDateTime)			 
	FROM	sHrm.tEmployeePersonalDetail EPD
		WHERE   EPD.OrgId = @rOrgId 
		
	SELECT @lEmployeeJobDetailUpdatedDate = MAX(EJD.UpdatedDateTime)			 
	FROM	sHrm.tEmployeeJobDetail EJD
		WHERE   EJD.OrgId = @rOrgId
		
	SELECT @lEmployeeImagesUpdatedDate = MAX(EI.UpdatedDateTime)			 
	FROM	sHrm.tEmployeeImages EI
		INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = EI.EmployeeId
		WHERE   EM.OrgId = @rOrgId 	 
 
 	SELECT @lEmployeeGradeMasterCreatedDate = MAX(EGM.CreatedDateTime),
	       @lEmployeeGradeMasterUpdatedDate = MAX(EGM.UpdatedDateTime)			 
	FROM	sHrm.tEmployeeGradeMaster EGM
		WHERE   EGM.OrgId = @rOrgId 
		
	SELECT @lEmployeeDesignationMasterCreatedDate = MAX(EDM.CreatedDateTime),
	       @lEmployeeDesignationMasterUpdatedDate = MAX(EDM.UpdatedDateTime)			 
	FROM	sHrm.tEmployeeDesignationMaster EDM
		WHERE   EDM.OrgId = @rOrgId 	
	
	SELECT @lEmployeeTypeMasterCreatedDate = MAX(ETM.CreatedDateTime),
	       @lEmployeeTypeMasterUpdatedDate = MAX(ETM.UpdatedDateTime) 			 
	FROM	sHrm.tEmployeeTypeMaster  ETM
		WHERE   ETM.OrgId = @rOrgId 


 SELECT 
	ISNULL(@lEmployeeMasterCreatedDate,'1900-01-01') AS EmployeeMasterCreatedDate,
	ISNULL(@lEmployeeMasterUpdatedDate,'1900-01-01') AS EmployeeMasterUpdatedDate,
	
	ISNULL(@lEmployeePersonalDetailUpdatedDate,'1900-01-01') AS EmployeePersonalDetailUpdatedDate,
	
	ISNULL(@lEmployeeJobDetailUpdatedDate,'1900-01-01') AS EmployeeJobDetailUpdatedDate,
	
	ISNULL(@lEmployeeImagesUpdatedDate,'1900-01-01') AS EmployeeImagesUpdatedDate,
		
	ISNULL(@lEmployeeGradeMasterCreatedDate,'1900-01-01') AS EmployeeGradeMasterCreatedDate,
	ISNULL(@lEmployeeGradeMasterUpdatedDate,'1900-01-01') AS EmployeeGradeMasterUpdatedDate,	
	
	ISNULL(@lEmployeeDesignationMasterCreatedDate,'1900-01-01') AS EmployeeDesignationMasterCreatedDate,
	ISNULL(@lEmployeeDesignationMasterUpdatedDate,'1900-01-01') AS EmployeeDesignationMasterUpdatedDate,
	
	ISNULL(@lEmployeeTypeMasterCreatedDate,'1900-01-01') AS EmployeeTypeMasterCreatedDate,
	ISNULL(@lEmployeeTypeMasterUpdatedDate,'1900-01-01') AS EmployeeTypeMasterUpdatedDate
 END
GO
PRINT N'Creating [sSetup].[pPortalEmployeePersonalDetailUpdate]...';


GO


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

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

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


GO


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

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

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


GO


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

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

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


GO
CREATE PROCEDURE [sSetup].[pPortalStudentAcademicMasterGet]
	 
	 @rOrgId int,
	 @rDivisionId int = 0,
	 @rBatchId int,	
	 @rStudentAcademicCreatedDate DateTime,
	 @rStudentAcademicUpdatedDate DateTime,	 
	 @rStudentMaxId bigint
		 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	 
BEGIN 	
	SELECT  
			Id,
			StudentId,
			ClassId,
			DivisionId,
			RollNo,
			OrgId,
			BatchId,
			CreatedUserId,
		 ISNULL(CreatedDateTime,GETDATE()) AS CreatedDateTime,	
			isnull(UpdatedUserId,0) AS UpdatedUserId,
		   ISNULL(UpdatedDateTime,getdate()) AS UpdatedDateTime
  FROM 
           sStudent.tAcademic
             
  WHERE   oRGiD = @rOrgId and
   DivisionId = @rDivisionId 
  And BatchId=@rBatchId 
  --AND StudentId > @rStudentMaxId
  --AND ( Convert(datetime,CreatedDatetime,120) > @rStudentAcademicCreatedDate OR  Convert(datetime,UpdatedDatetime,120) > @rStudentAcademicUpdatedDate)
     AND  (CONVERT(DATETIME,CONVERT(VARCHAR(20),CONVERT(DATETIME,  CreatedDateTime), 120)) > @rStudentAcademicCreatedDate OR 
       CONVERT(DATETIME,CONVERT(VARCHAR(20),CONVERT(DATETIME,  UpdatedDateTime), 120)) > @rStudentAcademicUpdatedDate )
  
  END
GO
PRINT N'Creating [sSetup].[pPortalStudentAcademicMasterUpdate]...';


GO


CREATE PROCEDURE [sSetup].[pPortalStudentAcademicMasterUpdate]
	 
	
	@rStrXml [nvarchar](max),
	@rDivisionId int
	
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET @rStrXml=REPLACE(@rStrXml,'&','AND')
DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml
BEGIN
	--BEGIN TRY
	
	 BEGIN	
	 --DELETE FROM sStudent.tAcademic WHERE DivisionId = @rDivisionId
	
	 UPDATE sStudent.tAcademic
		SET
			StudentId = A.StudentId,
			ClassId = A.ClassId,
			DivisionId = A.DivisionId,
			RollNo = A.RollNo,
			OrgId = A.OrgId,
			BatchId = A.BatchId,
			UpdatedUserId = A.UpdatedUserId,
			UpdatedDateTime = A.UpdatedDateTime,
			CreatedDateTime = A.CreatedDateTime 
		FROM
		(
		SELECT		
			Id,
			StudentId,
			ClassId,
			DivisionId,
			RollNo,
			OrgId,
			BatchId,
			UpdatedUserId,
			UpdatedDateTime,
			CreatedDateTime
						
		FROM OPENXML (@loDoc, '/Table/Academic', 1)
		WITH ( 
				Id bigint,
				StudentId bigint,
				ClassId int,					
				DivisionId int,
				RollNo int,
				OrgId int,
				BatchId int,
				UpdatedUserId bigint,
				UpdatedDateTime DateTime,
				CreatedDateTime DateTime
			  )) A
			  Where sStudent.tAcademic.Id = A.Id
			  
			  
	   INSERT INTO sStudent.tAcademic
		(
			Id,
			StudentId,
			ClassId,
			DivisionId,
			RollNo,
			OrgId,
			BatchId,
			CreatedUserId,
			UpdatedUserId,
			UpdatedDateTime,
			CreatedDateTime
			)
		SELECT		
			A.Id,
			A.StudentId,
			A.ClassId,
			A.DivisionId,
			A.RollNo,
			A.OrgId,
			A.BatchId,
			A.CreatedUserId,
			A.UpdatedUserId,
			A.UpdatedDateTime,
			A.CreatedDateTime
						
		FROM OPENXML (@loDoc, '/Table/Academic', 1)
		WITH ( 
				Id bigint,
				StudentId bigint,
				ClassId int,					
				DivisionId int,
				RollNo int,
				OrgId int,
				BatchId int,
				CreatedUserId bigint,
				UpdatedUserId bigint,
				UpdatedDateTime DateTime,
				CreatedDateTime DateTime		
			  ) A LEFT JOIN sStudent.tAcademic AC ON A.Id = AC.Id
			  WHERE AC.Id IS NULL
			  
			  EXEC sp_xml_removedocument @loDoc
		
        SELECT 1 AS Result
	 END	
	
		
	--END TRY
	
	--BEGIN CATCH 
	
	--	SELECT -1 AS Result
	--END CATCH	
		
END
GO
PRINT N'Creating [sSetup].[pPortalUploadBookLogUpdate]...';


GO


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

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

	 BEGIN	
	
	UPDATE sCommunication.tUploadBookLog
		SET
			BookTitle = A.BookTitle,
			IssueDate = A.IssueDate,
			ReaderSourceTypeId = A.ReaderSourceTypeId,
			ReaderSourceId = A.ReaderSourceId,
			BatchId = A.BatchId
		 FROM
		 (
		SELECT		
		BookLogId,
		BookTitle,
		IssueDate,
		ReaderSourceTypeId,
		ReaderSourceId,
		BatchId
			
		FROM OPENXML (@loDoc, '/Table/RowData', 1)
		WITH ( 
				[BookLogId] [bigint],
				[BookTitle] [nvarchar](100),
				[IssueDate] [date],
				[ReaderSourceTypeId] [smallint],
				[ReaderSourceId] [bigint],
				[BatchId] [int]
			  )) A
			  WHERE sCommunication.tUploadBookLog.BookLogId = A.BookLogId
		
		
		
		 INSERT INTO sCommunication.tUploadBookLog
		(
			BookLogId,
			BookTitle,
			IssueDate,
			ReaderSourceTypeId,
			ReaderSourceId,
			BatchId
			)
		SELECT		
			A.BookLogId,
			A.BookTitle,
			A.IssueDate,
			A.ReaderSourceTypeId,
			A.ReaderSourceId,
			A.BatchId
						
		FROM OPENXML (@loDoc, '/Table/RowData', 1)
		WITH ( 
				[BookLogId] [bigint],
				[BookTitle] [nvarchar](100),
				[IssueDate] [date],
				[ReaderSourceTypeId] [smallint],
				[ReaderSourceId] [bigint],
				[BatchId] [int]
			  ) A LEFT JOIN sCommunication.tUploadBookLog UBL
			  ON A.BookLogId = UBL.BookLogId WHERE UBL.BookLogId IS NULL
		
		 EXEC sp_xml_removedocument @loDoc
        SELECT 1 AS Result
	 END	
	
	END TRY
	
	BEGIN CATCH 
		
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Creating [sStudent].[pImportStudentFamilyDetail]...';


GO


CREATE PROCEDURE [sStudent].[pImportStudentFamilyDetail]

	@rOrgGroupId smallint,
    @rOrgId smallint,
	@rXmlDoc [nvarchar](max),
	@rUserId bigint,
	@rBatchId int
	
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET @rXmlDoc=REPLACE(@rXmlDoc,'&','AND')

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

	 UPDATE  F
		SET
--Code = A.Code,
 F.FatherName	=	A.FatherName		,
F.FatherDateOfBirth	=	A.FatherDateOfBirth		,
F.FatherOccupation	=	A.FatherOccupation		,
F.FatherQualification	=	A.FatherQualification		,
F.FatherContactNo	=	A.FatherContactNo		,
F.FatherMail	=	A.FatherMail		,
F.FatherOfficeAddress	=	A.FatherOfficeAddress		,
F.FatherIncome	=	A.FatherIncome		,
F.MotherName	=	A.MotherName		,
F.MotherDateOfBirth	=	A.MotherDateOfBirth		,
F.MotherOccupation	=	A.MotherOccupation		,
F.MotherQualification	=	A.MotherQualification		,
F.MotherContactNo	=	A.MotherContactNo		,
F.MotherMail	=	A.MotherMail		,
F.MotherOfficeAddress	=	A.MotherOfficeAddress		,
F.MotherIncome	=	A.MotherIncome		,
F.RelationshipName	=	A.RelationshipName		,
F.RelativeName	=	A.RelativeName		,
F.RelativeDateOfBirth	=	A.RelativeDateOfBirth		,
F.RelativeOccupation	=	A.RelativeOccupation		,
F.RelativeQualification	=	A.RelativeQualification		,
F.RelativeContactNo	=	A.RelativeContactNo		,
F.RelativeMail	=	A.RelativeMail		,
F.RelativeOfficeAddress	=	A.RelativeOfficeAddress		,
F.RelativeIncome	=	A.RelativeIncome		,
F.MarriageAnniversaryDate	=	A.MarriageAnniversaryDate,
F.UpdatedUserId = A.CreatedUserId,
F.UPdatedDateTime = GETDATE()	
 
		FROM
		(
 	SELECT
Code,		
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		,
MarriageAnniversaryDate,
CreatedUserId	 
					
FROM OPENXML (@loDoc, '/Table/ImportStudent', 1)
WITH ( 
Code		nvarchar(20),
FatherName		nvarchar(100),
FatherDateOfBirth		date,
FatherOccupation		nvarchar(50),
FatherQualification		nvarchar(50)	,
FatherContactNo		nvarchar(50)	,
FatherMail		nvarchar(50)	,
FatherOfficeAddress		nvarchar(50)	,
FatherIncome		int	,
MotherName		nvarchar(100)	,
MotherDateOfBirth		date	,
MotherOccupation		nvarchar(50)	,
MotherQualification		nvarchar(50)	,
MotherContactNo		nvarchar(50)	,
MotherMail		nvarchar(50)	,
MotherOfficeAddress		nvarchar(50)	,
MotherIncome		int	,
RelationshipName		nvarchar(100)	,
RelativeName		nvarchar(100)	,
RelativeDateOfBirth		date	,
RelativeOccupation		nvarchar(50)	,
RelativeQualification		nvarchar(50)	,
RelativeContactNo		nvarchar(50)	,
RelativeMail		nvarchar(50)	,
RelativeOfficeAddress		nvarchar(50)	,
RelativeIncome		int	,
MarriageAnniversaryDate		date,
CreatedUserID		bigint


			  )) A
			  INNER JOIN sStudent.tStudentMaster M ON A.Code = M.Code AND M.OrgId = @rOrgId
			  INNER JOIN sStudent.tStudentFamily F ON F.StudentId = M.Id
	 

	 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		,
MarriageAnniversaryDate,
CreatedUserId,
CreatedDateTime
			)
SELECT	
M.Id,	
A.FatherName		,
A.FatherDateOfBirth		,
A.FatherOccupation		,
A.FatherQualification		,
A.FatherContactNo		,
A.FatherMail		,
A.FatherOfficeAddress		,
A.FatherIncome		,
A.MotherName		,
A.MotherDateOfBirth		,
A.MotherOccupation		,
A.MotherQualification		,
A.MotherContactNo		,
A.MotherMail		,
A.MotherOfficeAddress		,
A.MotherIncome		,
A.RelationshipName		,
A.RelativeName		,
A.RelativeDateOfBirth		,
A.RelativeOccupation		,
A.RelativeQualification		,
A.RelativeContactNo		,
A.RelativeMail		,
A.RelativeOfficeAddress		,
A.RelativeIncome		,
A.MarriageAnniversaryDate,
A.CreatedUserId,
GetDate()	

			
						
	FROM OPENXML (@loDoc, '/Table/ImportStudent', 1)
	WITH ( 
Code		nvarchar(20), 
FatherName		nvarchar(100),
FatherDateOfBirth		date,
FatherOccupation		nvarchar(50),
FatherQualification		nvarchar(50)	,
FatherContactNo		nvarchar(50)	,
FatherMail		nvarchar(50)	,
FatherOfficeAddress		nvarchar(50)	,
FatherIncome		int	,
MotherName		nvarchar(100)	,
MotherDateOfBirth		date	,
MotherOccupation		nvarchar(50)	,
MotherQualification		nvarchar(50)	,
MotherContactNo		nvarchar(50)	,
MotherMail		nvarchar(50)	,
MotherOfficeAddress		nvarchar(50)	,
MotherIncome		int	,
RelationshipName		nvarchar(100)	,
RelativeName		nvarchar(100)	,
RelativeDateOfBirth		date	,
RelativeOccupation		nvarchar(50)	,
RelativeQualification		nvarchar(50)	,
RelativeContactNo		nvarchar(50)	,
RelativeMail		nvarchar(50)	,
RelativeOfficeAddress		nvarchar(50)	,
RelativeIncome		int	,
MarriageAnniversaryDate		date,
CreatedUserId		bigint
				
			  ) A 
			  
			  INNER JOIN sStudent.tStudentMaster M ON A.Code = M.Code AND M.OrgId = @rOrgId
			  LEFT JOIN sStudent.tStudentFamily F ON F.StudentId = M.Id 
			  WHERE F.StudentId IS NULL
			  
			  --LEFT JOIN sStudent.tStudentCommunication C
			  --ON A.StudentId = C.StudentId WHERE C.StudentId IS NULL
			  
		
		
 EXEC sp_xml_removedocument @loDoc
		
        SELECT 1 AS Result
	 END	

	--END TRY
	
	--BEGIN CATCH 
		
	--	SELECT -1 AS Result
	--END CATCH	
		
END
GO

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

END

