/*
Deployment script for NetVidyalayaVersionBlank
*/

 

 
PRINT N'Altering [sActivity].[tEventSchedule]...';


GO
ALTER TABLE [sActivity].[tEventSchedule]
    ADD [EventTypeId] INT NULL;


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


GO
ALTER TABLE [sEExam].[tTestMaster]
    ADD [BatchId] INT NULL;


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


GO
ALTER TABLE [sLibrary].[tBookMaster]
    ADD [BookDepartment] NVARCHAR (150) NULL,
        [ClassNumber]    NVARCHAR (50)  NULL,
        [BookVolume]     SMALLINT       NULL,
        [NoOfCopies]     SMALLINT       NULL;


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


GO
ALTER TABLE [sPayroll].[tPaySetup]
    ADD [OrderIndex]    INT NULL,
        [PayrollYearId] INT NULL;


GO
PRINT N'Altering [sScholarship].[tScholarshipEligibleStudent]...';


GO
ALTER TABLE [sScholarship].[tScholarshipEligibleStudent]
    ADD [EligibleAmount] DECIMAL (10, 2) NULL;


GO
PRINT N'Altering [sScholarship].[tScholarshipMaster]...';


GO
ALTER TABLE [sScholarship].[tScholarshipMaster]
    ADD [Remark] NVARCHAR (200) NULL;


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


GO
ALTER TABLE [sSetup].[tOrganizationMaster] DROP COLUMN [DetailColor], COLUMN [HeaderColor], COLUMN [ICardAddress1], COLUMN [ICardAddress2], COLUMN [ICardAddress3], COLUMN [ICardBackBackGround], COLUMN [ICardBackground], COLUMN [ICardOrgTitle], COLUMN [LabelColor];


GO
ALTER TABLE [sSetup].[tOrganizationMaster]
    ADD [LoginBG]  VARBINARY (MAX) NULL
    ,   [WeekOffs] NVARCHAR (50)   NULL;


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


GO
ALTER TABLE [sSetup].[tOrgGroupMaster]
    ADD [IsWindowSupport] INT NULL;


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


GO
ALTER TABLE [sTransport].[tBusRouteDestinationMaster]
    ADD [PickupTime] NVARCHAR (50) NULL,
        [DropTime]   NVARCHAR (50) NULL;


GO
PRINT N'Creating [sAcademic].[tTeacherSubject]...';


GO
CREATE TABLE [sAcademic].[tTeacherSubject] (
    [EmployeeId] BIGINT NOT NULL,
    [SubjectId]  INT    NOT NULL
);


GO
PRINT N'Creating [sAcademic].[tTeacherSubjectDivision]...';


GO
CREATE TABLE [sAcademic].[tTeacherSubjectDivision] (
    [EmployeeId] BIGINT NOT NULL,
    [SubjectId]  INT    NOT NULL,
    [DivisionId] INT    NOT NULL
);


GO
PRINT N'Creating [sActivity].[tEventTypeMaster]...';


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


GO
PRINT N'Creating [sAdmission].[tAdmissionCriteriaMaster]...';


GO
CREATE TABLE [sAdmission].[tAdmissionCriteriaMaster] (
    [Id]              INT           NOT NULL,
    [Code]            NVARCHAR (50) NOT NULL,
    [Title]           NVARCHAR (50) NOT NULL,
    [IsObsolete]      BIT           NULL,
    [CreatedUserId]   BIGINT        NULL,
    [CreatedDateTime] DATETIME      NULL,
    [UpdatedUserId]   BIGINT        NULL,
    [UpdatedDateTime] DATETIME      NULL,
    [OrgId]           SMALLINT      NULL
);


GO
PRINT N'Creating [sAdmission].[tAdmissionCriteriaStudent]...';


GO
CREATE TABLE [sAdmission].[tAdmissionCriteriaStudent] (
    [AdmissionFormId]  BIGINT          NOT NULL,
    [AdmissionSetupId] INT             NOT NULL,
    [ObtainMark]       DECIMAL (12, 2) NOT NULL
);


GO
PRINT N'Creating [sAdmission].[tAdmissionFormSelected]...';


GO
CREATE TABLE [sAdmission].[tAdmissionFormSelected] (
    [AdmissionFormId]   BIGINT          NOT NULL,
    [TotalObtainMark]   DECIMAL (12, 2) NULL,
    [AdmissionStatusId] SMALLINT        NULL
);


GO
PRINT N'Creating [sAdmission].[tAdmissionSetup]...';


GO
CREATE TABLE [sAdmission].[tAdmissionSetup] (
    [Id]                  INT             NOT NULL,
    [AdmissionCriteriaId] INT             NOT NULL,
    [ClassId]             INT             NOT NULL,
    [TotalMark]           DECIMAL (12, 2) NOT NULL,
    [BatchId]             INT             NOT NULL
);


GO
PRINT N'Creating [sAdmission].[tAdmissionStatusMaster]...';


GO
CREATE TABLE [sAdmission].[tAdmissionStatusMaster] (
    [Id]         TINYINT       NOT NULL,
    [Code]       NVARCHAR (10) NOT NULL,
    [Title]      NVARCHAR (50) NOT NULL,
    [IsObsolete] BIT           NOT NULL
);


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


GO
CREATE TABLE [sAssessment].[tCCERptGroup] (
    [Id] INT NOT NULL
);


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


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


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


GO
CREATE TABLE [sAttendance].[tFilterCriteriaDetail] (
    [Id]               INT            NOT NULL,
    [FilterCriteriaId] INT            NOT NULL,
    [MinimumScore]     DECIMAL (6, 2) NOT NULL,
    [GradeCode]        NVARCHAR (20)  NOT NULL,
    [GradeTitle]       NVARCHAR (50)  NOT NULL,
    [GradePoint]       DECIMAL (6, 2) NULL,
    [HighlightColor]   NVARCHAR (50)  NULL
);


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


GO
CREATE TABLE [sAttendance].[tYearlyRegister] (
    [AcademicId]       BIGINT         NOT NULL,
    [Month1]           NVARCHAR (20)  NULL,
    [TotalDays1]       INT            NULL,
    [PresentDays1]     INT            NULL,
    [Month2]           NVARCHAR (20)  NULL,
    [TotalDays2]       INT            NULL,
    [PresentDays2]     INT            NULL,
    [Month3]           NVARCHAR (20)  NULL,
    [TotalDays3]       INT            NULL,
    [PresentDays3]     INT            NULL,
    [Month4]           NVARCHAR (20)  NULL,
    [TotalDays4]       INT            NULL,
    [PresentDays4]     INT            NULL,
    [Month5]           NVARCHAR (20)  NULL,
    [TotalDays5]       INT            NULL,
    [PresentDays5]     INT            NULL,
    [Month6]           NVARCHAR (20)  NULL,
    [TotalDays6]       INT            NULL,
    [PresentDays6]     INT            NULL,
    [Month7]           NVARCHAR (20)  NULL,
    [TotalDays7]       INT            NULL,
    [PresentDays7]     INT            NULL,
    [Month8]           NVARCHAR (20)  NULL,
    [TotalDays8]       INT            NULL,
    [PresentDays8]     INT            NULL,
    [Month9]           NVARCHAR (20)  NULL,
    [TotalDays9]       INT            NULL,
    [PresentDays9]     INT            NULL,
    [Month10]          NVARCHAR (20)  NULL,
    [TotalDays10]      INT            NULL,
    [PresentDays10]    INT            NULL,
    [Month11]          NVARCHAR (20)  NULL,
    [TotalDays11]      INT            NULL,
    [PresentDays11]    INT            NULL,
    [Month12]          NVARCHAR (20)  NULL,
    [TotalDays12]      INT            NULL,
    [PresentDays12]    INT            NULL,
    [AvergeAttendance] DECIMAL (6, 2) NULL,
    [TotalDays]        INT            NULL,
    [PresentDays]      INT            NULL
);


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


GO
CREATE TABLE [sFee].[tWinfeeDetail] (
    [feeChoiceId]     BIGINT          NOT NULL,
    [AcademicId]      BIGINT          NULL,
    [feeName]         NVARCHAR (100)  NULL,
    [choice]          TINYINT         NULL,
    [Amount]          DECIMAL (12, 2) NULL,
    [exemption]       DECIMAL (12, 2) NULL,
    [paid]            DECIMAL (12, 2) NULL,
    [scheduleDate]    BIGINT          NULL,
    [ReceiptBookName] NVARCHAR (100)  NULL,
    [UpdatedDateTime] DATETIME        NOT NULL,
    [BatchId]         INT             NULL
);


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


GO
CREATE TABLE [sHrm].[tEmployeeAttendanceRegister] (
    [EmployeeId]      BIGINT   NULL,
    [AttendanceDate]  DATE     NOT NULL,
    [IsPresent]       BIT      NOT NULL,
    [AbsentReasonId]  INT      NULL,
    [UpdatedUserId]   BIGINT   NULL,
    [UpdatedDateTime] DATETIME NULL,
    [BatchId]         INT      NULL
);


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


GO
CREATE TABLE [sHrm].[tEmployeeICardOrg] (
    [EmployeeIcardTemplateId] INT             NOT NULL,
    [OrgId]                   INT             NOT NULL,
    [ICardBackground]         VARBINARY (MAX) NULL,
    [ICardBackBackGround]     VARBINARY (MAX) NULL,
    [LabelColor]              NVARCHAR (50)   NULL,
    [DetailColor]             NVARCHAR (50)   NULL,
    [HeaderColor]             NVARCHAR (50)   NULL,
    [ICardOrgTitle]           NVARCHAR (200)  NULL,
    [ICardAddress1]           NVARCHAR (200)  NULL,
    [ICardAddress2]           NVARCHAR (200)  NULL,
    [ICardAddress3]           NVARCHAR (200)  NULL
);


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


GO
CREATE TABLE [sHrm].[tEmployeeICardTemplate] (
    [Id]             INT            NOT NULL,
    [Title]          NVARCHAR (100) NULL,
    [Remark]         NVARCHAR (200) NULL,
    [DesignTemplate] NVARCHAR (200) NULL,
    [ICardImage]     NVARCHAR (200) NULL,
    [ReportId]       INT            NULL
);


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


GO
CREATE TABLE [sSecurity].[tDashletMaster] (
    [Id]         INT           NOT NULL,
    [Title]      NVARCHAR (30) NOT NULL,
    [IsObsolete] BIT           NOT NULL,
    [TaskId]     INT           NULL
);


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


GO
CREATE TABLE [sSecurity].[tRoleDashlet] (
    [RoleId]    INT NOT NULL,
    [DashletId] INT NOT NULL
);


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


GO
CREATE TABLE [sSecurity].[tUserDashlet] (
    [UserId]    BIGINT NOT NULL,
    [DashletId] INT    NOT NULL
);


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


GO
CREATE TABLE [sStudent].[tICardOrg] (
    [IcardTemplateId]     INT             NOT NULL,
    [OrgId]               INT             NOT NULL,
    [ICardBackground]     VARBINARY (MAX) NULL,
    [ICardBackBackGround] VARBINARY (MAX) NULL,
    [LabelColor]          NVARCHAR (50)   NULL,
    [DetailColor]         NVARCHAR (50)   NULL,
    [HeaderColor]         NVARCHAR (50)   NULL,
    [ICardOrgTitle]       NVARCHAR (200)  NULL,
    [ICardAddress1]       NVARCHAR (200)  NULL,
    [ICardAddress2]       NVARCHAR (200)  NULL,
    [ICardAddress3]       NVARCHAR (200)  NULL
);


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


GO
CREATE TABLE [sStudent].[tICardTemplate] (
    [Id]             INT            NOT NULL,
    [Title]          NVARCHAR (100) NULL,
    [Remark]         NVARCHAR (200) NULL,
    [DesignTemplate] NVARCHAR (200) NULL,
    [ICardImage]     NVARCHAR (200) NULL,
    [ReportId]       INT            NULL
);


GO
PRINT N'Creating [sSystem].[tCustomQuery]...';


GO
CREATE TABLE [sSystem].[tCustomQuery] (
    [Id]         INT             NOT NULL,
    [Title]      NVARCHAR (1000) NOT NULL,
    [SqlQuery]   NVARCHAR (MAX)  NOT NULL,
    [IsObsolete] BIT             NOT NULL
);


GO
PRINT N'Creating [dbo].[TempPendingFee]...';


GO
CREATE TYPE [dbo].[TempPendingFee] AS  TABLE (
    [AcademicId]        BIGINT          NULL,
    [RollNo]            INT             NULL,
    [Name]              NVARCHAR (200)  NULL,
    [Code]              NVARCHAR (20)   NULL,
    [ClassId]           INT             NULL,
    [DivisionId]        INT             NULL,
    [ClassName]         NVARCHAR (100)  NULL,
    [DivisionName]      NVARCHAR (100)  NULL,
    [ClassDivision]     NVARCHAR (100)  NULL,
    [FeeSetupId]        INT             NULL,
    [IsVariable]        INT             NULL,
    [Amount]            DECIMAL (12, 2) NULL,
    [StartDate]         DATE            NULL,
    [EndDate]           DATE            NULL,
    [FAAmount]          DECIMAL (12, 2) NULL,
    [DiscountAmount]    DECIMAL (12, 2) NULL,
    [AdditionalAmount]  DECIMAL (12, 2) NULL,
    [PaidAmount]        DECIMAL (12, 2) NULL,
    [PendingAmount]     DECIMAL (12, 2) NULL,
    [Remark]            NVARCHAR (200)  NULL,
    [ReceiptBookId]     INT             NULL,
    [FeeName]           NVARCHAR (100)  NULL,
    [FeeCode]           NVARCHAR (100)  NULL,
    [OrgId]             INT             NULL,
    [OrgName]           NVARCHAR (200)  NULL,
    [OrgOrderIndex]     INT             NULL,
    [ReceiptBookTitle]  NVARCHAR (200)  NULL,
    [ReceiptOrderIndex] INT             NULL,
    [BatchId]           INT             NULL,
    [BatchName]         NVARCHAR (100)  NULL);


GO



-----------------------------  view Function ---------------------------

/*
Deployment script for NetVidyalayaVersionBlank
*/

 
PRINT N'Altering [sFinanceCommon].[fNumberToWordsWithDecimal]...';


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

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

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

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


GO

CREATE
 FUNCTION [sAssessment].[fGetAverageDivisionMark](@rDivisionId int,@rExamDetailId int)
RETURNS [bigint] WITH EXECUTE AS CALLER
AS 
BEGIN
 DECLARE @lResultId Decimal(8,2)
 SELECT @lResultId = ISNULL(AVG(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 [sFee].[fPendingFeeNamesGet]...';


GO

CREATE FUNCTION [sFee].[fPendingFeeNamesGet](@rAcademicId bigint,@rReceiptBookId bigint
,@Fee TempPendingFee readonly
)
RETURNS nvarchar(2000) WITH EXECUTE AS CALLER
AS 
BEGIN

DECLARE @rFeeDetail nvarchar(2000)
(SELECT 
			@rFeeDetail=COALESCE(@rFeeDetail+',','') +  F.FeeCode
			 FROM
			 @Fee F			  
			 WHERE AcademicId = @rAcademicId  
			 AND ReceiptBookId = @rReceiptBookId
			 
			  )
			 		
			
    RETURN ISNULL(@rFeeDetail,'') 
 
END
GO
PRINT N'Creating [sHrm].[fEmployeeSubjectGet]...';


GO

CREATE FUNCTION [sHrm].[fEmployeeSubjectGet](@rEmployeeId bigint)
RETURNS nvarchar(2000) WITH EXECUTE AS CALLER
AS 
BEGIN

DECLARE @rSubject nvarchar(2000)
(SELECT 
			@rSubject=COALESCE(@rSubject+', ','') +  SM.Title
			 FROM
			 sAcademic.tTeacherSubject TS
			 INNER JOIN sSetup.tSubjectMaster SM
			 ON TS.SubjectId = SM.Id			   
			 WHERE TS.EmployeeId = @rEmployeeId  
			 
			 
			  )
			 		
			
    RETURN ISNULL(@rSubject,'') 
 
END
GO
PRINT N'Altering [sAssessment].[vGeneralExamCustomSearch]...';


GO

















/******************************************************************************  
 Purpose          : To get Batch Wise  Class
 Created date     : 21 Nov 2013
 Author           : Kundan Patel 
 Copyright©       : Copyright © Sapphire Software Solutions
 ******************************************************************************/  
ALTER VIEW [sAssessment].[vGeneralExamCustomSearch]  
  
AS  
  
SELECT 	
		 SA.AcademicId,	  
		 SA.ClassId,
		 SA.DivisionId,
		 SA.RollNo,
		 SA.OrgId,
		 SA.BatchId,
		 OM.Title AS Organization,
		 BM.Title AS Batch,
		 SA.StudentId,
		 SA.Code,
		 SA.Number,
		 SA.FirstName,
		 SA.LastName,
		 SA.Name,
		 SA.StatusId,
		 SA.ClassName,
		 SA.DivisionName,
		 SA.StatusName,
		 R.Id AS ResultId,
		 R.ExamId AS ExamId,
		 R.TotalMarks,
		 R.TotalObtain,
		 R.ResultStatus,
		 R.ResultGrade,
		 R.ResultGradePoint,
		 R.RankNumber,
		 R.Percentage,
		 R.Percentile,
		 R.ResultRemark,
		 R.OtherRemark1,
		 ESGM.Code AS ExamCode,
		 ESGM.Title AS ExamName,
	     U.Id AS CreatedUserId,
	     U.DisplayTitle AS CreatedUserName,
	     EM.ExamSubGroupId
	  	  	   
FROM 
		sStudent.vStudentAcademic SA
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=SA.OrgId
	INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA.BatchId
	INNER JOIN sAssessment.tResult R ON R.AcademicId=SA.AcademicId
	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
	LEFT JOIN sSecurity.tUser U ON U.Id=R.UpdatedUserId
	INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId
GO
PRINT N'Altering [sHrm].[vExtEmployee]...';


GO




/******************************************************************************    
 Purpose          : External view to get data from sHrm.tEmployeeJobDetail table    
 Created date     : 03 Sep 2010    
 Author           : Rajendra Patel   
 Copyright©       : Copyright © Sapphire Software    
 Last Change Desc : EJD Added in Select
 *******************************************************************************/    
ALTER VIEW [sHrm].[vExtEmployee]  AS     
 
SELECT 
		EM.Id As EmployeeId,
		EM.Code AS EmployeeCode,  	 
		ISNULL(ISNULL(EM.FirstName, ' ') + ' ' + ISNULL(EM.LastName, ' '), ' ') AS EmployeeName,
		EM.OrgID,
		EM.StatusId, 
		EJD.EmployeeGroupId  
 FROM  
	  sHrm.tEmployeeMaster EM
	  INNER JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id = EJD.EmployeeId
GO
PRINT N'Altering [sSetup].[vExamSubject]...';


GO









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


GO


/******************************************************************************  
 Purpose          : To get Batch Wise  Class
 Created date     : 21 Nov 2013
 Author           : Kundan Patel 
 Copyright©       : Copyright © Sapphire Software Solutions
 ******************************************************************************/  
CREATE VIEW [sAcademic].[vTeacherSubject]  
  
AS  
  
SELECT 	
	  SM.Id AS SubjectId,
	  SM.Code AS SubjectCode,
	  SM.Title AS SubjectName,
	  SM.Number,
	  SM.OrderIndex,
	  SM.OrgId,
	  SM.IsObsolete,
	  TS.EmployeeId
  FROM 
	sSetup.tSubjectMaster SM
	INNER JOIN sAcademic.tTeacherSubject TS ON TS.SubjectId= SM.Id
GO
PRINT N'Creating [sFee].[vOptionalFeeHeadSetup]...';


GO














/******************************************************************************  
 Purpose          : To get Batch Wise  Class
 Created date     : 21 Nov 2013
 Author           : Kundan Patel 
 Copyright©       : Copyright © Sapphire Software Solutions
 ******************************************************************************/  
CREATE VIEW [sFee].[vOptionalFeeHeadSetup]  
  
AS  
  
SELECT 	    DISTINCT
			FS.ClassId,
			FS.AdmissionCategoryId,			 
			FHM.OrderIndex,
			FHM.IsObsolete,
			FS.BatchId,
			FHM.OrgGroupId,
			FS.IsVariable,			
			FHM.Id AS FeeHeadId,
			FHM.Title AS FeeHeadName
			 
FROM 
			sFee.tFeeSetup FS
	INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS.FeeId
	INNER JOIN sFee.tFeeHeadMaster FHM ON FM.FeeHeadId = FHM.Id
WHERE
			IsOptional=1
GO
PRINT N'Creating [sLibrary].[vBookDepartment]...';


GO

/******************************************************************************  
 Purpose          : To get Batch Wise  Class
 Created date     : 21 Nov 2013
 Author           : Kundan Patel 
 Copyright©       : Copyright © Sapphire Software Solutions
 ******************************************************************************/  
CREATE VIEW [sLibrary].[vBookDepartment]  
  
AS  
  
SELECT 	
	  DISTINCT 
	  ISNULL(BM.BookDepartment,'') AS BookDepartment,
	  BM.LibraryId
  FROM 
	  sLibrary.tBookMaster BM
GO
PRINT N'Creating [sPayroll].[vPayElement]...';


GO



/******************************************************************************  
 Purpose          : To get Batch Wise  Class
 Created date     : 21 Nov 2013
 Author           : Kundan Patel 
 Copyright©       : Copyright © Sapphire Software Solutions
 ******************************************************************************/  
 
CREATE VIEW [sPayroll].[vPayElement]  
  
AS  
  
 SELECT 	
 DISTINCT
	  PE.Id,
	  PE.Title,
	  PE.IsObsolete,
	  PE.IsEmployeeSpecific,
	  PE.IsDepend,
	  PE.SortOrder,
	  PE.PayrollId,
	  PE.PayElementTypeId
  FROM 
	sPayroll.tPayElement PE
	INNER JOIN sPayroll.tPaySetup PS ON PE.ID=PS.PayElementId
GO

--------------------------- SP --------------------------------



PRINT N'Altering [sActivity].[pActivityParticipantGet]...';


GO
ALTER PROCEDURE [sActivity].[pActivityParticipantGet]
	 
	 @rActivityId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 		
	SELECT   
		AP.ActivityId,
		'Student' AS SourceType,
		2003 AS SourceTypeId,
		SA.StudentId as SourceId,
		SA.Code as SourceCode,
		SA.Name as SourceName,
		SA.ClassName+'-'+SA.DivisionName as DivDept
		
  FROM sStudent.vStudentAcademic SA
	INNER JOIN sActivity.tActivityParticipant AP ON AP.SourceId=SA.StudentId 
	INNER JOIN sActivity.tActivity A ON A.Id = AP.ActivityId AND A.BatchId = SA.BatchId
	
  WHERE 
		(AP.ActivityId=@rActivityId OR @rActivityId=0)
	  AND AP.SourceTypeId=2003
	
	UNION
	
	SELECT  
		AP.ActivityId,
		'Employee' AS SourceType,
		95 AS SourceTypeId,
		EM.Id as SourceId,
		EM.Code as SourceCode,
		EM.FirstName+' '+EM.LastName as SourceName,
		DM.Title as DivDept
		
  FROM sHrm.tEmployeeMaster EM	
	INNER JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id = EJD.EmployeeId
    INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id = EJD.OrganizationDepartmentId
    INNER JOIN sActivity.tActivityParticipant AP ON AP.SourceId=EM.Id 
  WHERE 
		(AP.ActivityId=@rActivityId OR @rActivityId=0)
	  AND AP.SourceTypeId=95	
END
GO
PRINT N'Altering [sActivity].[pEventScheduleAdd]...';


GO

ALTER PROCEDURE [sActivity].[pEventScheduleAdd]
	 
        @rId int,
		@rTitle nvarchar(100),
		@rFromDate date,
		@rToDate date,
		@rRemark nvarchar(200),
		@rIsCommonForAll bit,
		@rIsHoliday bit,
		@rIsEnrollment bit,
		@rCreatedUserId bigint,
		@rBatchId int,
		@rOrgId int,
		@rEventTypeId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	IF(@rId = 0)	
	BEGIN
		--If Exists(select Id from sActivity.tEventSchedule where Code=@rCode AND BatchId=@rBatchId)
		--	BEGIN
		--	select -102 as Result
		--	RETURN
		--END 
	
		If Exists(select Id from sActivity.tEventSchedule where Title=@rTitle AND BatchId=@rBatchId)
			BEGIN
			select -103 as Result
			RETURN
		END 
	END
	ELSE
	BEGIN
		--If Exists(select Id from sActivity.tEventSchedule where Code=@rCode AND BatchId=@rBatchId AND Id<>@rId)
		--Begin
		--	select -102 as Result
		--	RETURN
		--End
		If  Exists(select Id from sActivity.tEventSchedule where Title=@rTitle AND BatchId=@rBatchId AND Id<>@rId)
		Begin
			select -103 as Result
			RETURN
		End

	END
	
	
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sActivity.tEventSchedule', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sActivity.tEventSchedule
		(
			Id,
			Title,
			FromDate,
			ToDate,
			Remark,
			IsCommonForAll,
			IsHoliday,
			IsEnrollment,
			CreatedUserId,
			CreatedDateTime,
			BatchId,
			EventTypeId
			
		)
	VALUES
		(
			@lNextNumber,
			@rTitle,
			@rFromDate,
			@rToDate,
			@rRemark,
			@rIsCommonForAll,
			@rIsHoliday,
			@rIsEnrollment,
			@rCreatedUserId,
			sCommon.fGetDate(), 
			@rBatchId,
			@rEventTypeId
		)
		    SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION         
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sActivity.tEventSchedule
	    SET
			Title=@rTitle,
			FromDate=@rFromDate,
			ToDate=@rToDate,
			Remark=@rRemark,
			IsCommonForAll=@rIsCommonForAll,
			IsHoliday=@rIsHoliday,
			IsEnrollment=@rIsEnrollment,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate(),
			EventTypeId=@rEventTypeId
	      
	      
	      WHERE Id = @rId
	      SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION
	 END  	

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


GO
ALTER PROCEDURE [sActivity].[pEventScheduleGet]

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

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


GO

ALTER PROCEDURE [sActivity].[pMyActivityGet]
	 
	 @rSourceTypeId smallint,
	 @rSourceId bigint,
	 @rOrgId smallint,
	 @rBatchId int
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON


BEGIN 
	IF(@rSourceTypeId=2003)
	BEGIN
		SELECT
				ISNULL(A.Id,0) as ActivityId,
				A.Title,
				A.ActivityTypeId,
				ATM.Title AS ActivityType,
				A.FromDate,
				A.ToDate,
				A.Remark,
				A.IsGroup
		FROM 
				sActivity.tActivity A 
				INNER JOIN sActivity.tActivityTypeMaster ATM ON ATM.Id=A.ActivityTypeId
				INNER JOIN sStudent.vStudentAcademic SA ON SA.StudentId=@rSourceId AND SA.BatchId = @rBatchId
			    INNER JOIN sActivity.tActivityParticipant AP ON AP.ActivityId=A.Id AND AP.SourceTypeId=2003
			
		WHERE 
				AP.SourceTypeId = 2003 AND AP.SourceId = @rSourceId  AND A.BatchId=@rBatchId
		--	(A.Id IN(SELECT ActivityId FROM sActivity.tActivityParticipant WHERE SourceTypeId=2003) AND 
		--		SourceId=(SELECT AcademicId FROM sStudent.vStudentAcademic WHERE StudentId=@rSourceId 
		--			AND OrgId=@rOrgId AND BatchId=@rBatchId))
		--AND (A.BatchId=@rBatchId)
	END
	ELSE
	BEGIN
		SELECT 
				ISNULL(A.Id,0) as ActivityId,
				A.Title,
				A.ActivityTypeId,
				ATM.Title AS ActivityType,
				A.FromDate,
				A.ToDate,
				A.Remark,
				A.IsGroup
		FROM 
				sActivity.tActivity A 
				INNER JOIN sActivity.tActivityTypeMaster ATM ON ATM.Id=A.ActivityTypeId
			LEFT JOIN sActivity.tActivityParticipant AP ON AP.ActivityId=A.Id AND AP.SourceId=@rSourceId AND AP.SourceTypeId=95
		WHERE 
	  
			(A.Id IN(SELECT ActivityId FROM sActivity.tActivityParticipant WHERE SourceTypeId=95 AND 
				SourceId=(SELECT Id FROM sHrm.vExtEmployeeJobDetail WHERE EmployeeId=@rSourceId)))
		AND (A.BatchId=@rBatchId)
	END
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,
	 @rStatusId 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+'-'+DM.DisplayTitle As ClassDivision,
	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))
		AND ((SM.StatusId=@rStatusId) OR (@rStatusId = 0))
END
GO
PRINT N'Altering [sAlert].[pAllBirthdayWishListGet]...';


GO
ALTER PROCEDURE [sAlert].[pAllBirthdayWishListGet]
	 	 
     @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rOrgId smallint,
	 @rBatchId int,
	 @rStrStudentId nvarchar(max),
	 @rStrCode nvarchar(max),
	 @rClassId int,
	 @rDivisionId int,
	 @rStudentId bigint,
	 @rFromRollNo int,
	 @rToRollNo int,
	 @rStatusId int,
	 @rDateOfBirth int,
	 @rDepartmentId int,
	 @rDayOfBirth int=0,
	 @rTemp int=0,
	 @rIsStudent int=1,
	 @rIsEmployee int=1
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
		
	Select 
			
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			SC.AcademicId,
			SC.Code,
			SC.FirstName + ' ' + SC.MiddleName + ' ' + SC.LastName AS Name,
			SC.RollNo,
			SC.ParentContactNo AS MobileNo,			 
			'Student' AS CategoryName,
			'' AS PersonName,
			SC.DateOfBirth,
			MONTH(SC.DateOfBirth),
			ISNULL(SC.StudentPhoto,CONVERT(VARBINARY(MAX), 0)) AS Photo,
		    SC.ClassName+' '+SC.DivisionName AS ClassName
	From 
		sStudent.vStudentAllDetail SC
		
	WHERE
			((SC.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SC.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND (SC.OrgId=@rOrgId)
		AND (SC.BatchId=@rBatchId)
		AND (MONTH(SC.DateOfBirth) = @rDateOfBirth )
		AND ((DAY(SC.DateOfBirth) = @rDayOfBirth) OR (@rDayOfBirth = 0 ))
		AND (SC.StatusId=1)
		AND (@rIsStudent=1)
		
	 	
			
UNION ALL

Select 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			
			SC.AcademicId,
			SC.Code,
			SC.FirstName + ' ' + SC.MiddleName + ' ' + SC.LastName AS Name,
			SC.RollNo,
			SF.FatherContactNo AS MobileNo,			 
			'Father' AS CategoryName,
			SF.FatherName AS PersonName,
			SF.FatherDateOfBirth AS DateOfBirth,
			MONTH(SF.FatherDateOfBirth),
			SC.FatherPhoto AS Photo,
				SC.ClassName+' '+SC.DivisionName AS ClassName
	From 
		sStudent.vStudentAllDetail SC
		INNER JOIN sStudent.tStudentFamily SF ON SC.StudentId = SF.StudentId
	WHERE
			((SC.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SC.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND (SC.OrgId=@rOrgId)
		AND (SC.BatchId=@rBatchId)
		--AND (DAY(SF.FatherDateOfBirth) = DAY(@rDateOfBirth))
		AND  (@rDayOfBirth = 0)
		AND (MONTH(SF.FatherDateOfBirth) = @rDateOfBirth)
		AND (SC.StatusId=1)		
		AND(@rTemp=0)
		
		UNION ALL

Select 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,			
			SC.AcademicId,
			SC.Code,
			SC.FirstName + ' ' + SC.MiddleName + ' ' + SC.LastName AS Name,
			SC.RollNo,
			SF.MotherContactNo AS MobileNo,			 
			'Mother' AS CategoryName,
			SF.MotherName AS PersonName,
			SF.MotherDateOfBirth AS DateOfBirth,
			MONTH(SF.MotherDateOfBirth),
			ISNULL(SC.MotherPhoto,CONVERT(VARBINARY(MAX), 0)) AS Photo,
				SC.ClassName+' '+SC.DivisionName AS ClassName
	From 
		sStudent.vStudentAllDetail SC
		INNER JOIN sStudent.tStudentFamily SF ON SC.StudentId = SF.StudentId
	WHERE
			((SC.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SC.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND (SC.OrgId=@rOrgId)
		AND (SC.BatchId=@rBatchId)
		--AND (DAY(SF.MotherDateOfBirth) = DAY(@rDateOfBirth))
		AND  (@rDayOfBirth = 0)
		AND (MONTH(SF.MotherDateOfBirth) = @rDateOfBirth)
		AND (SC.StatusId=1)		
		AND(@rTemp=0)
		
			UNION ALL

Select 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			
			SC.AcademicId,
			SC.Code,
			SC.FirstName + ' ' + SC.MiddleName + ' ' + SC.LastName AS Name,
			SC.RollNo,
			SF.RelativeContactNo AS MobileNo,			 
			SF.RelationshipName AS CategoryName,
			SF.RelativeName AS PersonName,
			SF.RelativeDateOfBirth AS DateOfBirth,
			MONTH(SF.RelativeDateOfBirth),
			ISNULL(SC.RelativePhoto,CONVERT(VARBINARY(MAX), 0)) AS Photo,
			SC.ClassName+' '+SC.DivisionName AS ClassName
			
	From 
		sStudent.vStudentAllDetail SC
		INNER JOIN sStudent.tStudentFamily SF ON SC.StudentId = SF.StudentId
	WHERE
			((SC.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SC.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND (SC.OrgId=@rOrgId)
		AND (SC.BatchId=@rBatchId)
		--AND (DAY(SF.RelativeDateOfBirth) = DAY(@rDateOfBirth))
		AND  (@rDayOfBirth = 0)
		AND (MONTH(SF.RelativeDateOfBirth) = @rDateOfBirth)
		AND (SC.StatusId=1)	
		AND(@rTemp=0)
		
		UNION ALL
		
	SELECT
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			EM.Id AS AcademicId,
			EM.Code,
			EM.FirstName + ' ' + EM.MiddleName + ' ' + EM.LastName AS Name,
	        '' AS RollNo,
	        EM.MobileNumber AS MobileNo,
	        'Employee' AS CategoryName,
	        '' AS PersonName,
			EM.DateOfBirth,
			MONTH(EM.DateOfBirth) ,
			ISNULL(EM.EmployeePhoto,CONVERT(VARBINARY(MAX), 0)) AS Photo,
			EM.DepartmentName AS ClassName
	FROM 
			[sHrm].[vExtEmployeeMaster] EM	
				
	WHERE  	    
	     (EM.OrgId = @rOrgId)
		AND ((MONTH(EM.DateOfBirth) = @rDateOfBirth) )
	     AND ((DAY(EM.DateOfBirth) = @rDayOfBirth) OR (@rDayOfBirth = 0 ))
	     AND (@rIsEmployee=1)
		
		

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


GO


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

BEGIN 

	SELECT 
			
			cceCSS.AcademicId,
			convert(nvarchar,cceCSS.AcademicId) AS AcademicIdText,
			CONVERT(NVARCHAR,EM.Id)AS ExamIdText,
			cceCSS.Grade,
			cceCSS.DescriptiveIndicator AS DiscriptiveIndicators,
			cceCSM.Title AS LifeSkills,
			cceCSGM.Code AS GrpLifeSkillsCode,
			cceCSGM.Title AS GrpLifeSkills,			
			cceCSGTM.Title AS CoScholasticGroupType,
			CM.DisplayTitle AS Class,
			DM.DisplayTitle AS Division
	
			
      
	FROM 
			sAssessment.tCCECSExamScore cceCSS
			--INNER JOIN sAssessment.tCCECSIndicatorMaster cceCSIM ON cceCSIM.Id=cceCSS.CCECSIndicatorId
			LEFT JOIN sAssessment.tCCECSMaster cceCSM ON cceCSM.Id=cceCSS.CCECSId
			INNER JOIN sAssessment.tCCECSGroupMaster cceCSGM ON cceCSGM.Id=cceCSM.CCECAGroupId
			LEFT JOIN sAssessment.tCCECSGroupTypeMaster cceCSGTM ON cceCSGM.CCECSGroupTypeId=cceCSGTM.Id
			INNER JOIN sStudent.tAcademic A ON cceCSS.AcademicId=A.Id
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId  
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
			INNER JOIN sAssessment.tCCEExamSetting CE ON CE.ClassId = CM.Id AND CE.CCEExamId = @rCCEExamId AND CE.BatchId = @rBatchId
			INNER JOIN sAssessment.tExamMaster EM ON EM.ExamSubGroupId = CE.ExamSubGroupId AND EM.ClassId = CE.ClassId AND EM.BatchId = @rBatchId
			
			
	WHERE 
			     (A.BatchId=@rBatchId)
			     AND (A.OrgId=@rOrgId)
		    AND (A.ClassId=@rClassId  OR @rClassId=0)
		    AND (A.DivisionId=@rDivisionId  OR @rDivisionId=0)
		   AND (SM.StatusId=@rStatus OR @rStatus=0) 
	AND ((SM.Code=@rCode) OR (@rCode=''))
		
	
		
		
END
GO
PRINT N'Altering [sAssessment].[pCCERptFAIndicatiorListGet]...';


GO



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

BEGIN 

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


GO


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

	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	SELECT 
			--@rBuilder1 AS Builder1,
			--@rBuilder2 AS Builder2,
			
			SM.Code,
			ISNULL(SM.FirstName,'')+' '+ISNULL(SM.LastName,'') AS Name,
			ISNULL(SF.FatherName,'') AS FatherName,
			ISNULL(SF.MotherName,'')AS MotherName,
			A.RollNo,
			CCER.AcademicId,
			CONVERT(NVARCHAR,CCER.AcademicId) AS AcademicIdText,
			CONVERT(NVARCHAR,EM.Id)AS ExamIdText,
			CONVERT(NVARCHAR,@rCCEExamId) AS CCEExamIdText,
			 
			 
			ISNULL(SC.ParentContactNo,'') AS ContactNo,
			ISNULL(SC.PresentStreetThree,'')+' '+ISNULL(SC.PresentStreetTwo,'')+' '+ISNULL(SC.PresentStreetThree,'')+' '+ISNULL(SC.PresentCity,'')+' '+ISNULL(SC.PresentState,'') AS PresentAddress,
			--SO.DateOfBirth,
			CONVERT(VARCHAR(10),SO.DateOfBirth,103) AS DateOfBirth,
			CM.DisplayTitle AS Class,
			DM.DisplayTitle AS Division,
			ISNULL(HM.Title,'') AS House,
			ISNULL(CCERD.GradeFA1,'') AS GradeFA1,
			ISNULL(CCERD.GradeFA2,'') AS GradeFA2,
			ISNULL(CCERD.GradeFA3,'')AS GradeFA3,
			ISNULL(CCERD.GradeFA4,'') AS GradeFA4,
			ISNULL(CCERD.GradeSA1,'') AS GradeSA1,
			ISNULL(CCERD.GradeSA2,'') AS GradeSA2,
			ISNULL(CCERD.FAGrade,'') AS FAGrade,
			ISNULL(CCERD.SAGrade,'') AS SAGrade,
			ISNULL(CCERD.GradePoint,0) AS OverallGrade,
			ISNULL(CCERD.Grade,'') AS Grade,
			ISNULL(CCER.AttendanceTerm1,0) AS AttendanceTerm1,
			ISNULL(CCER.AttendanceTerm2,0) AS AttendanceTerm2,
			ISNULL(CCER.WorkingDaysTerm1,0) AS WorkingDaysTerm1,
			ISNULL(CCER.WorkingDaysTerm2,0) AS WorkingDaysTerm2,
			ISNULL(CCER.Height,0) AS Height,
			ISNULL(CCER.Weight,0) AS Weight,
			ISNULL(CCER.VisionLeft,'') AS VisionLeft,
			ISNULL(CCER.VisionRight,'') AS VisionRight,
			ISNULL(CCER.DentalHygiene,'') AS DentalHygiene,
			SubM.Title As ClassSubject,
			ISNULL(BGM.Title,'') AS BloodGroup,
			ISNULL(CCERD.Term1GradePoint,0) AS Term1GradePoint,
			ISNULL(CCERD.Term1Grade,'') AS Term1Grade,
			ISNULL(CCERD.Term2GradePoint,0) AS Term2GradePoint,
			ISNULL(CCERD.Term2Grade,'') AS Term2Grade,
			--ISNULL(SI.StudentPhoto,CONVERT(varbinary(max),SI.StudentPhoto,1)) AS StudentPhoto
			--SI.StudentPhoto AS StudentPhoto 
		--CASE WHEN ISNULL(IsResultStatus,0) = 0 THEN 'No' ELSE 'Yes' END AS IsDisplayResultStatus,
			CCERD.FA1,
			CCERD.FA2,
			CCERD.FA3,
			CCERD.FA4,
			CCERD.SA1,
			CCERD.SA2,
			CCERD.TERM1,
			CCERD.TERM2,
			CCERD.TOTAL,
			EM.IsOnPrePrinted,
			EM.IsDisplayBirthDate,
			EM.IsDisplayPhoto,
			EM.IsDisplaySchoolName,			
			EM.IsLockForEdit,
			EM.IsIncludeCoScholastic,
			EM.IsDisplayAttendance,
			EM.IsDisplayHeightWeight,
			EM.IsResultStatus,
			EM.Remark1,
			EM.Remark2,
			EM.Remark3,
			EM.ExamSubGroupId,
			ESM.Code AS ExamSubGroupTitle,	
			EM.DisplayTitle,
			SI.StudentPhoto,
			ISNULL(EM.ExamMaximum,0) AS ExamMaximum,
			ISNULL(EM.FooterAdjustment,0) AS FooterAdjustment,
			ISNULL(EM.DetailAdjustment,0) AS DetailAdjustment,
			ISNULL(EM.TermScopeId,0) AS TermScopeId,	
			TSM.Title AS TermScopeTitle,
		ISNULL(EM.ReportId,0) as ReportId,
			'' AS GradeString,
			A.BatchId,
			BM.Title
			
			
			--CASE WHEN ED.ClassSubjectId=CS.Id THEN 'Yes' ELSE 'false' END AS Selected
      
	FROM 
	
			sAssessment.tCCEResultDetail CCERD
			
			INNER JOIN sAssessment.tCCEResult CCER  ON CCERD.AcademicId=CCER.AcademicId
			INNER JOIN sStudent.tAcademic A ON CCER.AcademicId=A.Id
		
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId
			left Join sStudent.tStudentFamily SF ON SF.StudentId =SM.Id
			LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=A.StudentId
			
			LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
			LEFT JOIN sActivity.tHouseMaster HM ON HM.Id=SO.HouseId
			LEFT JOIN sSetup.tClassSubject CS ON CS.Id=CCERD.ClassSubjectId
			INNER JOIN sSetup.tSubjectMaster SubM ON SubM.Id=CS.SubjectId
			LEFT JOIN sCommon.tBloodGroupMaster BGM ON BGM.Id=SO.BloodGroupId
			LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=SM.Id
			INNER JOIN sAssessment.tCCEExamSetting CE ON CE.ClassId = CM.Id AND CE.CCEExamId = @rCCEExamId AND CE.BatchId = @rBatchId 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ExamSubGroupId = CE.ExamSubGroupId AND EM.ClassId = CE.ClassId AND EM.BatchId = @rBatchId 
			Inner Join sAssessment.tExamSubGroupMaster ESM ON ESM.Id=EM.ExamSubGroupId
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id
			LEFT JOIN sSetup.tTermScopeMaster TSM ON TSM.Id = EM.TermScopeId

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


GO




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

BEGIN 

	SELECT 
			
			cceR.MyGoal,
			cceR.MyStrength,
			cceR.MyInterestHobby,
			cceR.Achievements,
			cceR.AcademicId,
			Convert(nvarchar,cceR.AcademicId) AS AcademicIdText,
			Convert(nvarchar,EM.Id)AS ExamIdText,
			Convert(nvarchar,@rCCEExamId) AS CCEExamIdText
		
	FROM 
			 
			
			 sAssessment.tCCEResult CCER 
			INNER JOIN sStudent.tAcademic A ON CCER.AcademicId=A.Id
		
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId
			left Join sStudent.tStudentFamily SF ON SF.StudentId =SM.Id
			LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=A.StudentId
			
			LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
			LEFT JOIN sActivity.tHouseMaster HM ON HM.Id=SO.HouseId
			INNER JOIN sAssessment.tCCEExamSetting CE ON CE.ClassId = CM.Id AND CE.CCEExamId = @rCCEExamId AND CE.BatchId = @rBatchId 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ExamSubGroupId = CE.ExamSubGroupId AND EM.ClassId = CE.ClassId AND EM.BatchId = @rBatchId 
			Inner Join sAssessment.tExamSubGroupMaster ESM ON ESM.Id=EM.ExamSubGroupId
	where
	 A.BatchId = @rBatchId 
		
		AND(CE.CCEExamId = @rCCEExamId OR @rCCEExamId=0)
	AND ( CCER.AcademicId=@rAcademicId OR @rAcademicId=0)	
	AND (SM.StatusId=@rStatus OR @rStatus=0) 
	AND ((SM.Code=@rCode) OR (@rCode=''))	
END
GO
PRINT N'Altering [sAssessment].[pExamSubGroupMasterAdd]...';


GO

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

	END
	
	
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAssessment.tExamSubGroupMaster', 0, 1, 1,@outNextNumber = @lNextNumber output

	INSERT INTO [sAssessment].[tExamSubGroupMaster]
			   (
			    [Id]
			   ,[Code]
			   ,[Title]
			   ,[ExamGroupId]
			   ,[IsObsolete]
			   ,[CreatedUserId]
			   ,[CreatedDateTime]
			   ,[UpdatedUserId]
			   ,[UpdatedDateTime]
			   ,[OrgId],
			   [Number],
			   [OrderIndex]
		
			   )
		 VALUES
			   (
				@lNextNumber
			   ,@rCode
			   ,@rTitle
			   ,@rExamGroupId
			   ,@rIsObsolete
			   ,@rCreatedUserId
			   ,sCommon.fGetDate()
			   ,0
			   ,sCommon.fGetDate()
			   ,@rOrgId,
			   @rNumber,
			   @rOrderIndex
			   
			   )
		    SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION         
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  [sAssessment].[tExamSubGroupMaster]
	    SET
			  Code=@rCode
	         ,Title=@rTitle
	         ,ExamGroupId = @rExamGroupId,
	         Number=@rNumber,
	         OrderIndex=@rOrderIndex
	         
	         ,[IsObsolete] = @rIsObsolete                          
             ,[UpdatedUserId] = @rCreatedUserId
             ,[UpdatedDateTime] = sCommon.fGetDate()          
             
	      WHERE Id = @rId 	   
	      SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION
	 END  	

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


GO

ALTER PROCEDURE [sAssessment].[pExamSubGroupMasterGet]
          
           @rId int,
           @rExamGroupId int,
           @rTitle nvarchar(100),
           @rOrgId int           
          
AS
SET NOCOUNT ON

			SET @rTitle = sCommon.fSearchStringGet(@rTitle)

BEGIN
SELECT ESGM.Id as Id
	  ,ESGM.Title as Title
	  ,ESGM.Code as Code
	  ,EGM.Title AS ExamGroupTitle
	  ,ESGM.ExamGroupId as ExamGroupId,
	  ESGM.Number AS Number,
	  ESGM.OrderIndex AS OrderIndex
      ,ESGM.IsObsolete as IsObsolete
      
     
  FROM [sAssessment].[tExamSubGroupMaster] ESGM 
  INNER JOIN [sAssessment].[tExamGroupMaster] EGM ON EGM.Id = ESGM.ExamGroupId
        
  WHERE 
	((ESGM.Title Like @rTitle)OR(ISNULL(@rTitle,'') = ''))
	AND (ESGM.ExamGroupId=@rExamGroupId OR @rExamGroupId=0)
		AND ESGM.OrgId = @rOrgId
		AND (ESGM.Id = @rId  OR @rId = 0)
         
END
GO
PRINT N'Altering [sAssessment].[pGeneralExamCustomSearchGet]...';


GO
ALTER PROCEDURE [sAssessment].[pGeneralExamCustomSearchGet]
(
	@rOrgId smallint,
	@rBatchId int,
	@rOrderBy nvarchar(max) = 'RollNo',
	@rCode [nvarchar](20) = '',
	@rFirstName [nvarchar](50) = '',	
	@rLastName [nvarchar](50) = '',
	--@rClassId nvarchar(max) = '',
	@rDivisionId nvarchar(max) = '',
	@rExamId nvarchar(max) = '',
	@rFromMarks decimal(5,2),
	@rToMarks decimal(5,2),
	@rFromGradePoint decimal(6,2),
	@rToGradePoint decimal(6,2),
	@rFromRankNumber int,
	@rToRankNumber int,
	@rFromPercentage decimal(5,2),
	@rToPercentage decimal(5,2),
	@rFromPercentile decimal(5,2),
	@rToPercentile decimal(5,2),
	@rResultGrade nvarchar(10),
	@rCreatedUserId bigint,
	@rDropDownStatusId int,
	@rDropDownClassId int,
	@rDropDownDivisionId int,
	@rDropDownExamSubGroupId int
 )
AS
SET NOCOUNT ON

BEGIN
		DECLARE @Sql nvarchar(MAX)
		
		SET @rCode = sCommon.fSearchStringGet(@rCode)
		SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
		SET @rLastName = sCommon.fSearchStringGet(@rLastName)
		SET @rResultGrade = sCommon.fSearchStringGet(@rResultGrade)
		
		SELECT 
				*
		into sAssessment.tTempGeneralExam1
		FROM sAssessment.vGeneralExamCustomSearch ECS
		WHERE 
				(ECS.OrgId = @rOrgId)
			AND (ECS.BatchId = @rBatchId)
			AND ((ECS.Code Like @rCode + '%') OR (@rCode = ''))
			AND ((ECS.FirstName Like @rFirstName  + '%') OR (@rFirstName = ''))	 			 
			AND ((ECS.LastName Like @rLastName + '%')OR(@rLastName = ''))
			AND ((ECS.TotalObtain >= @rFromMarks) OR (@rFromMarks=0))
			AND ((ECS.TotalObtain <= @rToMarks) OR (@rToMarks=0))
			AND ((ECS.ResultGradePoint >= @rFromGradePoint) OR (@rFromGradePoint=0))
			AND ((ECS.ResultGradePoint <= @rToGradePoint) OR (@rToGradePoint=0))
			AND ((ECS.RankNumber >= @rFromRankNumber) OR (@rFromRankNumber=0))
			AND ((ECS.RankNumber <= @rToRankNumber) OR (@rToRankNumber=0))
			AND ((ECS.Percentage >= @rFromPercentage) OR (@rFromPercentage=0))
			AND ((ECS.Percentage <= @rToPercentage) OR (@rToPercentage=0))
			AND ((ECS.Percentile >= @rFromPercentile) OR (@rFromPercentile=0))
			AND ((ECS.Percentile <= @rToPercentile) OR (@rToPercentile=0))
			AND ((ECS.ResultGrade Like @rResultGrade + '%')OR(@rResultGrade = ''))
			--AND (FCS.ClassId In( SELECT item FROM  sCommon.fnsplit(@rClassId,','))OR @rClassId=''))
		    
		    AND (ECS.DivisionId In( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionId,','))OR @rDivisionId='')
		         	          
			AND (ECS.ExamId In( SELECT cast(item as int) FROM  sCommon.fnsplit(@rExamId,','))OR @rExamId='')	
	        AND ((ECS.CreatedUserId=@rCreatedUserId) OR (@rCreatedUserId=0))
	        AND ((ECS.StatusId = @rDropDownStatusId) OR (@rDropDownStatusId=0))
			AND ((ECS.ClassId = @rDropDownClassId) OR (@rDropDownClassId=0))
			AND ((ECS.DivisionId = @rDropDownDivisionId) OR (@rDropDownDivisionId=0))
	        AND ((ECS.ExamSubGroupId = @rDropDownExamSubGroupId) OR (@rDropDownExamSubGroupId=0))
		SET @sql=
		'SELECT 
				Code AS Code,
				Name,
				RollNo,
				TotalMarks,
				TotalObtain,
				ResultStatus,
				ResultGrade,
				ResultGradePoint,
				RankNumber,
				Percentage,
				Percentile,
				ResultReMark,
				OtherRemark1
		FROM sAssessment.tTempGeneralExam1 ORDER BY '+@rOrderBy
		exec(@Sql)
		
		DROP Table sAssessment.tTempGeneralExam1
END
GO
PRINT N'Altering [sAssessment].[pGeneralExamGenerateReport]...';


GO
ALTER PROCEDURE [sAssessment].[pGeneralExamGenerateReport]
	@rId bigint,
	@rTitle nvarchar(50),
	@rColumnName nvarchar(max) = '',
	@rOrderBy nvarchar(max) = 'RollNo',
	@rOrgId smallint,
	@rBatchId int,
	@rCode [nvarchar](20) = '',
	@rFirstName [nvarchar](50) = '',	
	@rLastName [nvarchar](50) = '',
	--@rClassId nvarchar(max) = '',
	@rDivisionId nvarchar(max) = '',
	@rExamId nvarchar(max) = '',
	@rFromMarks decimal(5,2),
	@rToMarks decimal(5,2),
	@rFromGradePoint decimal(6,2),
	@rToGradePoint decimal(6,2),
	@rFromRankNumber int,
	@rToRankNumber int,
	@rFromPercentage decimal(5,2),
	@rToPercentage decimal(5,2),
	@rFromPercentile decimal(5,2),
	@rToPercentile decimal(5,2),
	@rResultGrade nvarchar(10),
	@rIsCommon bit,
	@rCreatedUserId bigint,
	@rDropDownStatusId int,
	@rDropDownClassId int,
	@rDropDownDivisionId int,
	@rDropDownExamSubGroupId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	
	IF(@rTitle != '' AND @rId = 0)
	BEGIN
	DECLARE @lNextNumber BIGINT     
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAssessment.tGeneralExamCustomSearch', 0, 1, 1,@outNextNumber = @lNextNumber output


	INSERT INTO sAssessment.tGeneralExamCustomSearch
		(
			Id,
			Title,
			ColumnName,
			OrderBy,
			OrgId,
			BatchId,
			Code,
			FirstName,	
			LastName,
			DivisionId,
			ExamId,
			FromMarks,
			ToMarks,
			FromGradePoint,
			ToGradePoint,
			FromRankNumber,
			ToRankNumber,
			FromPercentage,
			ToPercentage,
			FromPercentile,
			ToPercentile,
			ResultGrade,
			IsCommon,
			CreatedUserId,
			CreatedDateTime
		)
	VALUES
		(
			@lNextNumber,
			@rTitle,
			@rColumnName,
			@rOrderBy,
			@rOrgId,
			@rBatchId,
			@rCode,
			@rFirstName,	
			@rLastName,
			@rDivisionId,
			@rExamId,
			@rFromMarks,
			@rToMarks,
			@rFromGradePoint,
			@rToGradePoint,
			@rFromRankNumber,
			@rToRankNumber,
			@rFromPercentage,
			@rToPercentage,
			@rFromPercentile,
			@rToPercentile,
			@rResultGrade,
			@rIsCommon,
			@rCreatedUserId,
			sCommon.fGetDate()
		)
		--SELECT @lNextNumber AS Result
	END
	SET @rColumnName=Replace(@rColumnName,'ID No','Code')
	SET @rOrderBy=Replace(@rOrderBy,'ID No','Code')
	IF(@rId > 0)
	BEGIN
		Select
				@rColumnName=ColumnName,
				@rOrderBy=OrderBy,
				@rOrgId=OrgId,
				@rCode=Code,
				@rFirstName=FirstName,	
				@rLastName=LastName,
				@rDivisionId=DivisionId,
				@rExamId=ExamId,
				@rFromMarks=FromMarks,
				@rToMarks=ToMarks,
				@rFromGradePoint=FromGradePoint,
				@rToGradePoint=ToGradePoint,
				@rFromRankNumber=FromRankNumber,
				@rToRankNumber=ToRankNumber,
				@rFromPercentage=FromPercentage,
				@rToPercentage=ToPercentage,
				@rFromPercentile=FromPercentile,
				@rToPercentile=ToPercentile,
				@rResultGrade=ResultGrade
		FROM
			sAssessment.tGeneralExamCustomSearch
		WHERE
			Id=@rId
	END
	
	DECLARE @Sql nvarchar(MAX)
	
	SET @rCode = sCommon.fSearchStringGet(@rCode)
	SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
	SET @rLastName = sCommon.fSearchStringGet(@rLastName)
	SET @rResultGrade = sCommon.fSearchStringGet(@rResultGrade)
	
		SELECT 
				*
		into sAssessment.tTempGeneralExam
		FROM sAssessment.vGeneralExamCustomSearch ECS
		WHERE 
				(ECS.OrgId = @rOrgId)
			AND (ECS.BatchId = @rBatchId)
			AND ((ECS.Code Like @rCode + '%') OR (@rCode = ''))
			AND ((ECS.FirstName Like @rFirstName  + '%') OR (@rFirstName = ''))	 			 
			AND ((ECS.LastName Like @rLastName + '%')OR(@rLastName = ''))
			--AND (FCS.ClassId In( SELECT item FROM  sCommon.fnsplit(@rClassId,','))OR @rClassId=''))
		    AND ((ECS.TotalObtain >= @rFromMarks) OR (@rFromMarks=0))
			AND ((ECS.TotalObtain <= @rToMarks) OR (@rToMarks=0))
			AND ((ECS.ResultGradePoint >= @rFromGradePoint) OR (@rFromGradePoint=0))
			AND ((ECS.ResultGradePoint <= @rToGradePoint) OR (@rToGradePoint=0))
			AND ((ECS.RankNumber >= @rFromRankNumber) OR (@rFromRankNumber=0))
			AND ((ECS.RankNumber <= @rToRankNumber) OR (@rToRankNumber=0))
			AND ((ECS.Percentage >= @rFromPercentage) OR (@rFromPercentage=0))
			AND ((ECS.Percentage <= @rToPercentage) OR (@rToPercentage=0))
			AND ((ECS.Percentile >= @rFromPercentile) OR (@rFromPercentile=0))
			AND ((ECS.Percentile <= @rToPercentile) OR (@rToPercentile=0))
			AND ((ECS.ResultGrade Like @rResultGrade + '%')OR(@rResultGrade = ''))
			
		    AND (ECS.DivisionId In( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionId,','))OR @rDivisionId='')
		         	          
			AND (ECS.ExamId In( SELECT cast(item as int) FROM  sCommon.fnsplit(@rExamId,','))OR @rExamId='')	
	        AND ((ECS.CreatedUserId=@rCreatedUserId) OR (@rCreatedUserId=0))
	        AND ((ECS.StatusId = @rDropDownStatusId) OR (@rDropDownStatusId=0))
			AND ((ECS.ClassId = @rDropDownClassId) OR (@rDropDownClassId=0))
			AND ((ECS.DivisionId = @rDropDownDivisionId) OR (@rDropDownDivisionId=0))
			AND ((ECS.ExamSubGroupId = @rDropDownExamSubGroupId) OR (@rDropDownExamSubGroupId=0))
	       
	    SET @rColumnName=Replace(@rColumnName,',Code',',Code AS [ID No]')
		SET @rOrderBy=Replace(@rOrderBy,',Code',',Code AS [ID No]')     
		SET @sql=
		'SELECT '+
		@rColumnName+' 
		FROM sAssessment.tTempGeneralExam ORDER BY '+@rOrderBy
		exec(@Sql)
		
		DROP Table sAssessment.tTempGeneralExam
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		--SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sAssessment].[pMarkEntryMasterAdd]...';


GO

ALTER PROCEDURE [sAssessment].[pMarkEntryMasterAdd]	 
	        @rId bigint
	       ,@rAcademicId bigint
           ,@rExamId int
           ,@rCreatedUserId bigint
           ,@rOrgId int
          
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

	IF NOT EXISTS(SELECT 1 FROM sAssessment.tResult WHERE AcademicId = @rAcademicId AND ExamId = @rExamId)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAssessment.tResult', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO [sAssessment].[tResult]
			   (
			    [Id]
			   ,[AcademicId]
			   ,[ExamId]
			   ,[TotalMarks]
			   ,[TotalObtain]
			   ,[ResultStatus]
			   ,[ResultGrade]
			   ,[ResultGradePoint]
			   ,[RankNumber]
			   ,[Percentage]
			   ,[Percentile]
			   ,[ResultRemark]
			   ,[OtherRemark1]
			   ,[UpdatedUserId]
			   ,[UpdatedDateTime]
			   )
		 VALUES
			   (
				@lNextNumber
			   ,@rAcademicId
			   ,@rExamId
			   ,0
			   ,0
			   ,''
			   ,''
			   ,0
			   ,0
			   ,0.0
			   ,0.0
			   ,''
			   ,''
			   ,@rCreatedUserId
			   ,sCommon.fGetDate()
			   )
		    SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION         
	END	 

ELSE
	 BEGIN
	 IF (@rId = 0)
		SELECT @lNextNumber = ID FROM sAssessment.tResult WHERE AcademicId = @rAcademicId AND ExamId = @rExamId	 
	 ELSE	  
	 SET @lNextNumber = @rId
	 
	    UPDATE  [sAssessment].[tResult]
	    SET
			  AcademicId=@rAcademicId
	         ,ExamId=@rExamId
             ,[UpdatedUserId] = @rCreatedUserId
             ,[UpdatedDateTime] = sCommon.fGetDate()          
             
	      WHERE Id = @rId 	   
	      SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION
	 END  	

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


GO


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

BEGIN 

	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			Convert(nvarchar(20),A.Id) AS   AcademicIdText,	
	CONVERT (nvarchar(20),@rExamId) AS ExamIdText,
			
			ESGM.Title AS Exam,
			SM.Code,
			SM.FirstName+' '+SM.LastName AS Name,
			A.RollNo,
			R.AcademicId,
			CM.DisplayTitle+'/'+DM.DisplayTitle AS Class,
			--DM.DisplayTitle AS Division,
			DM.Id AS DivisionId,
			DM.OrderIndex AS DivisinOrderIndex,
			R.TotalMarks,
			R.TotalObtain,
			R.Percentage,
			R.RankNumber,
			R.ResultGrade,
			EM.IsMarksInDecimal
			
      
	FROM 
			sAssessment.tExamMaster EM
			INNER JOIN sAssessment.tResult R ON EM.Id=R.ExamId
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId
			INNER JOIN sStudent.tAcademic A ON R.AcademicId=A.Id
			INNER JOIN sStudent.tStudentMaster SM ON A.StudentId=SM.Id
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=EM.ClassId
			INNER JOIN sSetup.tDivisionMaster DM ON A.DivisionId=DM.Id
			
	WHERE 
			
		      EM.BatchId = @rBatchId 
		AND (EM.ClassId=@rClassId OR @rClassId=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 ((ESGM.Id=@rExamSubGroupId )	OR (@rExamSubGroupId = 0))
		AND ((EM.Id=@rExamId )	OR (@rExamId = 0))
		AND ((SM.Code=@rCode) OR (@rCode=''))
		AND ((A.Id =@rAcademicId) OR (@rAcademicId=0))
		
END
GO
PRINT N'Altering [sAssessment].[pRptResultSheetCoScholasticSubSingleGet]...';


GO




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

BEGIN 

DECLARE @lIsCoScholasticGrade	bit,@lIsCoScholasticGradeIndicator bit, @lIsCoScholasticGradeDesIndicator bit	 

 
SELECT @lIsCoScholasticGrade = IsCoScholasticGrade,
@lIsCoScholasticGradeIndicator=IsCoScholasticGradeIndicator,
@lIsCoScholasticGradeDesIndicator=IsCoScholasticGradeDesIndicator
FROM sAssessment.tExamMaster WHERE Id = @rExamId
	SELECT		
			Convert(nvarchar(10),@rExamId) AS ExamIdText,
			Convert(nvarchar(20),@rAcademicId) AS   AcademicIdText,	
			cceCSS.AcademicId,
			cceCSS.ExamId,
			cceCSS.Grade,
			cceCSS.GradeIndicator, 
			cceCSS.DescriptiveIndicator,
			cceCSM.Title AS CoSubject,
			cceCSGM.Title AS CoSubjectGroup,
			cceCSM.OrderIndex AS CoSujbectOrderIndex,
			cceCSGM.OrderIndex AS CoSubjectGroupOrderIndex,
			@lIsCoScholasticGrade AS IsCoScholasticGrade,
			@lIsCoScholasticGradeIndicator AS IsCoScholasticGradeIndicator,
			@lIsCoScholasticGradeDesIndicator AS IsCoScholasticGradeDesIndicator,
			cceCSGM.CCECSGroupTypeId,
			cceCSGM.Code
	FROM 
			sAssessment.tCCECSExamScore cceCSS		 
			INNER JOIN sAssessment.tCCECSMaster cceCSM ON cceCSM.Id=cceCSS.CCECSId
			INNER JOIN sAssessment.tCCECSGroupMaster cceCSGM ON cceCSGM.Id=cceCSM.CCECAGroupId
			INNER JOIN sStudent.tAcademic A ON A.Id = cceCSS.AcademicId 
			INNER JOIN sAssessment.tCCECSClass CCC ON CCC.ClassId = A.ClassId AND CCC.CCECSGroupId = cceCSGM.Id 
	WHERE 
		     cceCSS.ExamId=@rExamId
		     AND cceCSS.AcademicId=@rAcademicId	
		     --AND (cceCSGM.CCECSGroupTypeId = @rCCECSGroupTypeId OR @rCCECSGroupTypeId = 0)
END

--exec sAssessment.pRptResultSheetCoScholasticSubSingleGet @rAcademicId=1030000000003,@rExamId=103000098

--SELECT * FROM sAssessment.tCCECSClass where ClassId = 
GO
PRINT N'Altering [sAssessment].[pRptResultSheetStandardMultiExamGet]...';


GO


ALTER PROCEDURE [sAssessment].[pRptResultSheetStandardMultiExamGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rSubjectId int = 0,
	 @rBatchId int=0,
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rExamId int,
	 @rCode nvarchar(20)='',
	 @rFromRollNo int=0,
	 @rToRollNo int=0,
	 @rFromRank int=0,
	 @rToRank int=0,
	 @rGrade nvarchar(20)='',
	 @rResultId bigint=0,
	 @rStatusId int=0
	 --,@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=StuM.Id
	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))	
		AND ((StuM.StatusId=@rStatusId)OR(@rStatusId=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 [sAssessment].[pRptResultWithSubjectListGet]...';


GO


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

BEGIN 

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


GO


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

BEGIN 
SELECT
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		R.AcademicId,
		ESGM.Title AS Exam,
		StuM.FirstName+' '+StuM.LastName AS Name,
		A.RollNo,
		CM.DisplayTitle AS Class,
		DM.DisplayTitle AS Division,
		R.Percentage,
		StuM.Code,
		CM.Title,
		DM.Title
	
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
	WHERE 
			
		E.BatchId = @rBatchId 
		AND (A.ClassId=@rClassId OR @rClassId=0) 
		--AND ((SM.Id=@rSubjectId) OR (@rSubjectId=0))
		AND (A.DivisionId=@rDivisionId OR @rDivisionId=0)
		AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((R.RankNumber >= @rFromRank) OR (@rFromRank=0))
		AND ((R.RankNumber <= @rToRank) OR (@rToRank=0))
		AND E.IsProcessResult = 1
		--AND ((R.ResultGrade = @rGrade) OR (@rGrade=''))
		
		--AND ((R.ExamId = @rExamId) OR (@rExamId =0))
		AND ((ESGM.Id=@rExamSubGroupId) OR (@rExamSubGroupId=0))
		AND ((E.Id=@rExamId )	OR (@rExamId = 0))
		
		
		--AND ((StuM.Code=@rCode) OR (@rCode=''))
		
		--order by A.RollNo,CS.OrderIndex 
		--AND A.id = 1005000000007
		
END
GO
PRINT N'Altering [sAttendance].[pAttenanceRegisterGet]...';


GO

ALTER PROCEDURE [sAttendance].[pAttenanceRegisterGet]

	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rAttendanceTypeId smallint,
	 @rOrgId int,
	 @rForMonth smallint,
	 @rForYear smallint,
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rBatchId int = 0,
	 @rStudentCode nvarchar(20)='',
	 @rDepartmentId int = 0,
	 @rAcademicId bigint = 0
	 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

SELECT  
	
		
  @rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,AcademicId,ClassDivisionTitle,Code,RollNo,Name,AttendanceTypeId ,ForYear,ForMonth,ClassId,ClassName,DivisionId,DivisionName,ForMonthInWord,TotalCount,ISNULL(PresentCount,0) AS PresentCount,AbsentCount,AveragePresence,
			(select ISNULL(SUM(presentcount),0) FROM sAttendance.tMonthlyRegister M
		WHERE M.AcademicId = PivotTable.AcademicId AND 
			[sCommon].[fGetYearMonthNumber](M.ForYear,M.ForMonth) < [sCommon].[fGetYearMonthNumber](@rForYear,@rForMonth)) AS PresentUpto,
			--0 AS PresentUpto,
			0 AS TotalPresent,
[1] AS P1, [2] AS P2, [3] AS P3, [4] AS P4,[5] AS P5,[6] AS P6,[7] AS P7,[8] AS P8,[9] AS P9,[10] AS P10,[11] AS P11,[12] AS P12,[13] AS P13,[14] AS P14,[15] AS P15,[16] AS P16,[17] AS P17,[18] AS P18,[19] AS P19,[20] AS P20,[21] AS P21,[22] AS P22,[23] AS P23,[24] AS P24,[25] AS P25,[26] AS P26,[27] AS P27,[28] AS P28,[29] AS P29,[30] AS P30,[31] AS P431
FROM
(Select   ISNULL(SA.ClassName + '-' + SA.DivisionName,'') AS ClassDivisionTitle,SA.Code,SA.RollNo,SA.AcademicId,
 SA.Name,SR.AttendanceTypeId ,YEAR(SR.AttendanceDate) AS ForYear,MONTH(SR.AttendanceDate) AS ForMonth,DATENAME(month, SR.AttendanceDate) AS ForMonthInWord,SA.ClassId,SA.DivisionId,SA.ClassName,Sa.DivisionName, MR.TotalCount,MR.PresentCount,MR.AbsentCount,MR.AveragePresence,
(CASE SR.IsPresent WHEN 1 THEN 'P' 
	WHEN 0 THEN 'A'
	ELSE  ' ' END )AS  IsPresent,
	 day(SR.AttendanceDate) AS DayPart
	 
    from
            sStudent.vStudentAcademic SA
            INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.AcademicId
            LEFT JOIN sAttendance.tMonthlyRegister MR ON MR.AcademicId = SA.AcademicId 
            AND MR.ForMonth =MONTH(SR.AttendanceDate) AND MR.ForYear = YEAR(SR.AttendanceDate)
            INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=SA.DivisionId
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId
			
            
             WHERE 
               (SA.StatusId = 1)
	        AND ((SR.AttendanceTypeId=@rAttendanceTypeId) OR (@rAttendanceTypeId= 0))
	         AND ((SA.OrgId=@rOrgId) OR (@rOrgId= 0))
	          AND ((SA.BatchId=@rBatchId) OR (@rBatchId= 0))
	          AND ((YEAR(SR.AttendanceDate)=@rForYear) OR (@rForYear= 0))
	          AND ((MONTH(SR.AttendanceDate)=@rForMonth) OR (@rForMonth= 0))
	           AND ((SA.ClassId=@rClassId) OR (@rClassId= 0))
	           AND ((SA.Code=@rStudentCode) OR (@rStudentCode=''))
	           AND ((SA.AcademicId=@rAcademicId) OR (@rAcademicId=0))	           
				AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
				
	           AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId= 0))) AS SourceTable
	          
PIVOT
(	
MIN(ispresent)
FOR DayPart IN ([0], [1], [2], [3], [4],[5],[6],[7],[8],[9],[10],[11],[12],[13],[14],[15],[16],[17],[18],[19],[20],[21],[22],[23],[24],[25],[26],[27],[28],[29],[30],[31])
) AS PivotTable
order by RollNo;
	
END
GO
PRINT N'Altering [sAttendance].[pMonthlyRegisterGet]...';


GO
ALTER PROCEDURE [sAttendance].[pMonthlyRegisterGet]
	 	 
	 	 @rBatchId int,
	 	 @rClassId int,
	 	 @rDivisionId int,
	 	 @rForMonth tinyint,
	 	 @rForYear smallint,
	 	 @rAttendanceTypeId tinyint,
	 	 @rSubjectId int,
	 	 @rIsImport bit
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

if (@rIsImport = 1)
BEGIN
	Select 
		SN.AcademicId,
		SN.Code,
		SN.FirstName + ' ' + SN.MiddleName + ' ' + SN.LastName AS Name,
		SN.RollNo,
		MY.MonthTitle AS ForMonthInWord,
		MY.MonthNumber AS ForMonth, 
		MY.YearNumber AS ForYear,
		CASE WHEN SS.WorkingDays IS NOT NULL
			THEN ISNULL(SS.WorkingDays,0)			 
			ELSE ISNULL(MS.WorkingDays,0) END AS TotalCount,		
		ISNULL(MS.WorkingDays,0)  AS TotalCount,
		(Select COUNT(1) FROM sAttendance.tStudentRegister SR1 
			WHERE SR1.AcademicId=SN.AcademicId 
				AND SR1.IsPresent=1 
				AND SR1.AttendanceTypeId=@rAttendanceTypeId
				AND ((SR1.SubjectId=@rSubjectId) OR (ISNULL(@rSubjectId,0)=0))
				AND DATEPART(MONTH,SR1.AttendanceDate)=@rForMonth 
				AND DATENAME(YEAR,SR1.AttendanceDate)=@rForYear)  AS PresentCount,
		 (Select COUNT(1) FROM sAttendance.tStudentRegister SR2
			WHERE SR2.AcademicId=SN.AcademicId 
			AND SR2.IsPresent=0 
			AND SR2.AttendanceTypeId=@rAttendanceTypeId
			AND ((SR2.SubjectId=@rSubjectId) OR (ISNULL(@rSubjectId,0)=0))
			AND DATEPART(MONTH,SR2.AttendanceDate)=@rForMonth 
			AND DATENAME(YEAR,SR2.AttendanceDate)=@rForYear)  AS AbsentCount,
		
		(SELECT [sAttendance].[fAbsentDaysGet](@rForMonth,@rForYear, @rAttendanceTypeId,@rSubjectId,SN.AcademicId) AS MyResult)  AS AbsentDays
		
		
	From 
		sStudent.vStudentName SN 
	LEFT JOIN sSetup.fMonthYearForBatchGET(@rBatchId) AS MY ON MY.BatchId=SN.BatchId
		AND MY.MonthNumber=@rForMonth AND MY.YearNumber=@rForYear
	LEFT JOIN sAttendance.tMonthlyRegister MR ON MR.AcademicId=SN.AcademicId 
		AND (MR.AttendanceTypeId=@rAttendanceTypeId) AND ((MR.SubjectId=@rSubjectId) OR (@rSubjectId=0))
		AND MR.ForMonth=MY.MonthNumber AND MR.ForYear=MY.YearNumber
	LEFT JOIN sAttendance.tMonthlySetup MS ON MS.ClassId=SN.ClassId
		AND MS.ForMonth=MY.MonthNumber AND MS.ForYear=MY.YearNumber
	LEFT JOIN sAttendance.tStudentSetup SS ON SS.AcademicId=SN.AcademicId
		AND SS.ForMonth=MY.MonthNumber AND SS.ForYear=MY.YearNumber
		
	WHERE
		(MY.BatchId=@rBatchId)
	AND (SN.ClassId=@rClassId)
	AND (SN.DivisionId=@rDivisionId)
	AND SN.BatchId = @rBatchId
	ORDER BY SN.RollNo
END
ELSE
BEGIN	
	Select 
		SN.AcademicId,
		SN.Code,
		SN.FirstName + ' ' + SN.MiddleName + ' ' + SN.LastName AS Name,
		SN.RollNo,
		MY.MonthTitle AS ForMonthInWord,
		MY.MonthNumber AS ForMonth, 
		MY.YearNumber AS ForYear,
		ISNULL(MR.TotalCount,0) AS  TotalCount,
		ISNULL(MR.PresentCount,0) PresentCount,
		ISNULL(MR.AbsentCount,0) AS AbsentCount,		 
		ISNULL(MR.AbsentDays,'') AS AbsentDays
		
		
	From 
		sStudent.vStudentName SN 
	LEFT JOIN sSetup.fMonthYearForBatchGET(@rBatchId) AS MY ON MY.BatchId=SN.BatchId
		AND MY.MonthNumber=@rForMonth AND MY.YearNumber=@rForYear
	LEFT JOIN sAttendance.tMonthlyRegister MR ON MR.AcademicId=SN.AcademicId 
		AND (MR.AttendanceTypeId=@rAttendanceTypeId) AND ((MR.SubjectId=@rSubjectId) OR (@rSubjectId=0))
		AND MR.ForMonth=MY.MonthNumber AND MR.ForYear=MY.YearNumber
	--LEFT JOIN sAttendance.tMonthlySetup MS ON MS.ClassId=SN.ClassId
	--	AND MS.ForMonth=MY.MonthNumber AND MS.ForYear=MY.YearNumber
	--LEFT JOIN sAttendance.tStudentSetup SS ON SS.AcademicId=SN.AcademicId
	--	AND SS.ForMonth=MY.MonthNumber AND SS.ForYear=MY.YearNumber
		
	WHERE
		(MY.BatchId=@rBatchId)
	AND (SN.ClassId=@rClassId)
	AND (SN.DivisionId=@rDivisionId)
	AND SN.BatchId = @rBatchId
	ORDER BY SN.RollNo
	END
END
GO
PRINT N'Altering [sAttendance].[pRptStudentMonthlyRegisterGet]...';


GO

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

BEGIN 

	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			SA.AcademicId,
			SA.ClassId,
			SA.DivisionId,
			SA.ClassName,
			SA.DivisionName,
			SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
			SA.Code,
			SA.RollNo,			
			SA.Name,
			MR.ForMonth,
			MR.ForYear,
			M.Code +' - '+Convert(nvarchar(4),MR.ForYear) AS ForMonthYear,
			MR.TotalCount,
			MR.PresentCount,
			MR.AbsentCount,
			MR.AveragePresence,
			MR.AbsentDays,
			ISNULL(SO.DateOfBirth,NULL) AS DateOfBirth,
			SM.Title AS SubjectName,
			SA.DivisionOrder
			 
			
	FROM 
			sStudent.vStudentAcademic SA
        INNER JOIN sStudent.tStudentOther SO ON SA.StudentId = SO.StudentId 			
		INNER JOIN sAttendance.tMonthlyRegister MR ON MR.AcademicId=SA.AcademicId
		LEFT JOIN sSetup.tSubjectMaster SM ON SM.Id=MR.SubjectId
		INNER JOIN sCommon.tMonthMaster M ON MR.ForMonth = M.Id
	WHERE 
			(SA.OrgId=@rOrgId)
		AND	(SA.BatchId = @rBatchId) 
		AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((MR.AttendanceTypeId=@rAttendanceTypeId) OR (@rAttendanceTypeId=0))
		AND ((MR.SubjectId=@rSubjectId) OR (@rSubjectId=0))
		AND ((MR.ForYear=@rForYear) OR (@rForYear=0))
		AND ((MR.ForMonth=@rForMonth) OR (@rForMonth=0))
		AND (SA.StatusId != 3)
		AND ((SA.Code=@rStudentCode) OR (@rStudentCode=''))
		AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		AND ((MR.AveragePresence >=@rFromAverage)OR (@rFromAverage=0))
		AND ((MR.AveragePresence <= @rToAverage) OR (@rToAverage=0))
END
GO
PRINT N'Altering [sAttendance].[pStudentRegisterBulkAdd]...';


GO
ALTER PROCEDURE [sAttendance].[pStudentRegisterBulkAdd]
	 
	@rDivisionId int,
	@rEmployeeId bigint,
	@rAttendanceTypeId tinyint,
	@rAttendanceDate date,
	@rSubjectId int,
	@rstrRollNo nvarchar(max),
	@rRepeatCount tinyint,
	@rIsPresent bit,
	--@rLeaveReasonId int,
	@rCreatedUserId bigint,
	@rOrgId smallint,
	@rBatchId int
	--@rIsDeleted bit
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	 DECLARE @lCount INT
	 DECLARE @rAcademicId bigint
	 DECLARE @lIsPresent bit
	
	
DELETE   sAttendance.tStudentRegister 
FROM sAttendance.tStudentRegister R
INNER JOIN sStudent.tAcademic A ON R.AcademicId = A.Id
WHERE  A.BatchId = @rBatchId
AND A.DivisionId = @rDivisionId
AND AttendanceTypeId=@rAttendanceTypeId 
AND AttendanceDate=@rAttendanceDate
	
--	DELETE FROM sAttendance.tStudentRegister R WHERE 
--			--AcademicId IN(Select AcademicId FROM sAttendance.tPresentTempRegister) 
--	AND AttendanceTypeId=@rAttendanceTypeId 
--AND AttendanceDate=@rAttendanceDate		
		
	
	
	SELECT 
		row_number() over(order by AcademicId) AS RowId, AcademicId,1 AS IsPresent into sAttendance.tPresentTempRegister 
	FROM sStudent.vStudentName SN
	WHERE 
			SN.DivisionId=@rDivisionId
		AND SN.OrgId=@rOrgId
		AND SN.BatchId=@rBatchId
		AND SN.StatusId!=3
		AND (SN.RollNo NOT IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rstrRollNo,'.'))OR (@rstrRollNo=''))
	
	
	
	IF (@rstrRollNo<>'')
	BEGIN
	SELECT 
		row_number() over(order by AcademicId) AS RowId, AcademicId,0 AS IsPresent into sAttendance.tAbsentTempRegister 
	FROM sStudent.vStudentName SN
	WHERE 
			SN.DivisionId=@rDivisionId
		AND SN.OrgId=@rOrgId
		AND SN.BatchId=@rBatchId
		AND SN.StatusId!=3
		AND (SN.RollNo IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rstrRollNo,'.'))OR (@rstrRollNo=''))
		
	--DELETE FROM sAttendance.tStudentRegister WHERE 
	--		AcademicId IN(Select AcademicId FROM sAttendance.tAbsentTempRegister) 
	--	AND AttendanceTypeId=@rAttendanceTypeId 
	--	AND AttendanceDate=@rAttendanceDate
	END
	
	SELECT @lCount =  COUNT(AcademicId) FROM sAttendance.tPresentTempRegister 

	WHILE @lCount > 0 
	BEGIN
	
	SELECT @rAcademicId=AcademicId,@lIsPresent=IsPresent FROM sAttendance.tPresentTempRegister WHERE RowId=@lCount
	
		INSERT INTO sAttendance.tStudentRegister
		(
			AcademicId,
			EmployeeId,
			AttendanceTypeId,
			AttendanceDate,
			SubjectId,
			RepeatCount,
			IsPresent,
			--LeaveReasonId,
			CreatedUserId,
			CreatedDateTime
		)
		VALUES
		(
			@rAcademicId,
			@rEmployeeId,
			@rAttendanceTypeId,
			@rAttendanceDate,
			@rSubjectId,
			@rRepeatCount,
			@lIsPresent,
			--@rLeaveReasonId,
			@rCreatedUserId,
			sCommon.fGetDate()
		)	
		
	 	 SELECT @rAcademicId AS Result
	 	 SET @lCount = @lCount - 1	
	 END
		DROP TABLE sAttendance.tPresentTempRegister 
		
	IF (@rstrRollNo<>'')
	BEGIN	
	SELECT @lCount =  COUNT(AcademicId) FROM sAttendance.tAbsentTempRegister 

	WHILE @lCount > 0 
	BEGIN
	
	SELECT @rAcademicId=AcademicId,@lIsPresent=IsPresent FROM sAttendance.tAbsentTempRegister WHERE RowId=@lCount
	
		INSERT INTO sAttendance.tStudentRegister
		(
			AcademicId,
			EmployeeId,
			AttendanceTypeId,
			AttendanceDate,
			SubjectId,
			RepeatCount,
			IsPresent,
			--LeaveReasonId,
			CreatedUserId,
			CreatedDateTime
		)
		VALUES
		(
			@rAcademicId,
			@rEmployeeId,
			@rAttendanceTypeId,
			@rAttendanceDate,
			@rSubjectId,
			@rRepeatCount,
			@lIsPresent,
			--@rLeaveReasonId,
			@rCreatedUserId,
			sCommon.fGetDate()
		)	
		
	 	 SELECT @rAcademicId AS Result
	 	 SET @lCount = @lCount - 1	
	 END
		DROP TABLE sAttendance.tAbsentTempRegister 
	END
		SELECT 1 AS Result
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sCommon].[pEmployeeSearchGet]...';


GO
ALTER PROCEDURE [sCommon].[pEmployeeSearchGet]
	@rOrgId [int],
	@rEmployeeCode [nvarchar](20) = '',
	@rFirstName [nvarchar](30) = '',
	@rMobileNumber [nvarchar](20) = '',
	@rDOB [datetime] = '1/1/1900',
	--@rEmployeeLocationId int,
	@rLastName [nvarchar](30) = '',
	@rParticipantSourceTypeId int = 0,
	@rDepartmentId int = 0,
	@rEmployeeId bigint = 0,
	@rStatusId smallint
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
 --SET @rEmployeeCode = sCommon.fSearchStringGet(@rEmployeeCode)
IF(@rParticipantSourceTypeId = 95 OR @rParticipantSourceTypeId = 0 )
BEGIN
SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
SET @rLastName = sCommon.fSearchStringGet(@rLastName)
 SET @rMobileNumber = sCommon.fSearchStringGet(@rMobileNumber) 
 
 	 SELECT OrgID,
			Id,
			EmployeeId,
			Code,
			FirstName,
			MiddleName,
			LastName,
		    EmployeeName,	 			
			GenderId,
			ISNULL(DateOfBirth,'1900/01/01') AS DateOfBirth,
			ISNULL(DateOfJoining,'1900/01/01') AS DateOfJoining,
			'' AS Gender,
			--PermanentAddressId,
			--PresentAddressId AS CommunicationAddressId,
			--PresentContactId AS CommunicationContactId,
			StatusId,
			EM.IsObsolete,
			PhoneNoCompany,
			CompanyEmail,
			ExtensionNo,			
			DepartmentId,  
			DepartmentCode,  
			DepartmentName,
		    ISNULL (MobileNumber,0) AS MobileNumber,
			--EmployeeJobTitleId,
			--EmployeeTypeId,
			--EmployeeJobTitle,
			--EmployeeLocationId,
			ISNULL(DATEDIFF(yy,DateOfBirth,GETDATE()),0) AS Age,
			DesignationId,
			--ProcessTypeId,
			ParticipantSourceTypeId
			
 
	 FROM sHrm.vExtEmployeeMaster EM
	 
		 WHERE 
		    
		      ((EM.Code = @rEmployeeCode) OR (@rEmployeeCode = ''))
			  AND ((EM.FirstName Like  @rFirstName)  OR (ISNULL(@rFirstName,'') = ''))
			  AND ((EM.LastName Like  @rLastName)  OR (ISNULL(@rLastName,'') = ''))
			  AND ((EM.MobileNumber Like @rMobileNumber) OR(ISNULL(@rMobileNumber,'') = ''))				 
			  AND EM.IsObsolete = 0
			  --AND EM.EmployeeGroupId=1
			  AND EM.OrgId = @rOrgId 
			  --AND ((EM.EmployeeLocationId = @rEmployeeLocationId) OR (ISNULL(@rEmployeeLocationId,0) = 0) )		  			  
			  AND ((EM.DepartmentId = @rDepartmentId) OR (@rDepartmentId = 0) )	
			  AND ((EM.StatusId=@rStatusId) OR (@rStatusId=0))	 
		END
		
   ELSE IF(@rParticipantSourceTypeId = 1001) 
	  BEGIN
	  SELECT
		 OrgId,
	     DependentId,
	     EmployeeCode AS Code,
	     EmployeeId AS Id,
	     Name AS EmployeeName,
	     DateOfBirth,
	     AGE,
	     0 AS GenderId,
	     DepartmentId,
	     DepartmentName,
	     0 AS MobileNumber,
	     DesignationId,
	     '' AS FirstName,
	     '' AS LastName,
	     1001 AS ParticipantSourceTypeId
	     
	     FROM sHrm.vExtEmployeeFamilyDetail  Where 
	      (EmployeeCode Like @rEmployeeCode) AND DependentId = @rEmployeeId 
			   	AND OrgId = @rOrgId 
			 
			   	--AND EmployeeLocationId = @rEmployeeLocationId 
	      
	  END	
		
   --ELSE IF(@rParticipantSourceTypeId = 1009)       
   --    BEGIN 
   --      SELECT 
	  --      OrgId,
	  --      EmployeeId AS Id,     
	  --      EmployeeId,
			--Code,
			--FirstName,	 
			--LastName,
			--EmployeeName,
			--GenderId,
			--ISNULL(DateOfBirth,'') AS DateOfBirth, 
			--'' AS DepartmentName,
			--1009 AS ParticipantSourceTypeId,		 			 
			--0 AS  DepartmentId,	 
			--0 AS DesignationId,	 		
			--ISNULL(DATEDIFF(yy,DateOfBirth,GETDATE()),0) AS Age
			----0 AS ProcessTypeId
			--,OrgId
			----,LocationId
			--,'' AS MobileNumber 
	       
			
	  --FROM  sHrm.vExtCsrBenefiterMaster          
   --     WHERE   (Code Like @rEmployeeCode)
			--   	AND OrgId = @rOrgId 
			--   	--AND LocationId = @rEmployeeLocationId
 		-- END
END
GO
PRINT N'Altering [sCommon].[pOrganizationSetupRemove]...';


GO


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

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


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

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

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




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

DELETE FROM 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.tNewsComment WHERE CAST(LEFT(NewsId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sCommunication.tNewsScope WHERE CAST(LEFT(NewsId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sCommunication.tPhotoCategoryMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommunication.tPoll WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommunication.tPollAnswer WHERE CAST(LEFT(PollId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sCommunication.tPollMember WHERE CAST(LEFT(PollId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sCommunication.tPollResult WHERE CAST(LEFT(PollId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sCommunication.tQuery WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommunication.tQueryCategoryAssignedTo WHERE CAST(LEFT(QueryCategoryId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sCommunication.tQueryCategoryMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommunication.tQueryComment WHERE CAST(LEFT(QueryId, 4) AS BIGINT) =  @rOrgGroupId
DELETE FROM sEExam.tDataBankMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sEExam.tDataSubjectMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sEExam.tDataTopicMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sEExam.tDataTopicTypeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sEExam.tQuestionMaster WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sEExam.tQuestionOption WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sEExam.tQuestionParagraph WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sEExam.tTestTemplateMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sEExam.tTestTemplateQuestion WHERE CAST(LEFT(TestTemplateId, 4) AS INT) = @rOrgGroupId
DELETE FROM sFee.tChargeCategoryMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sFee.tChargeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sFee.tFeeHeadMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sFee.tFeeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sFee.tReceiptBookMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sFinanceCommon.tBankMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM  sFinanceCommon.tStockUomMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sGSEB.tActivityGroupMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sGSEB.tActivityIndicatorMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sGSEB.tActivityMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sHostel.tHostelMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sHostel.tRoomCategoryMaster WHERE CAST(LEFT(HostelId, 4) AS int) = @rOrgGroupId
DELETE FROM sHostel.tRoomMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sHrm.tQualificationMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM  sIp.tItemMainGroupMaster WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM  sIp.tItemSubGroupMaster WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM  sIp.tStockItemCategoryMaster WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sIp.tStockItemMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM  sIp.tStoreLocationMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sLibrary.tBookAgeGroupMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sLibrary.tBookAuthorMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sLibrary.tBookLanguageMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sLibrary.tBookLocationMaster WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sLibrary.tBookMaster WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sLibrary.tBookPublisherMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sLibrary.tBookSubjectMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sLibrary.tBookSupplierMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sLibrary.tBookTagMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sLibrary.tLibraryMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM  sPayroll.tEsiProcess WHERE CAST(LEFT(PayProcessElementId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sPayroll.tEsiSetup WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sPayroll.tPayElement WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM  sPayroll.tPayProcess WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sPayroll.tPayProcessElement WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sPayroll.tPayProcessEmployee WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM  sPayroll.tPaySetup WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM  sPayroll.tPaySetupDependent WHERE CAST(LEFT(PaySetupId, 4) AS INT) = @rOrgGroupId
DELETE FROM  sPayroll.tPfProcess WHERE CAST(LEFT(PayProcessElementId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM  sPayroll.tPfProcessCharge WHERE CAST(LEFT(PayProcessElementId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sPayroll.tPfSetup WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sPayroll.tProfessionalTaxRange WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM  sProcurement.tVendorCategoryMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sProcurement.tVendorMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sSecurity.tModulePermission WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sSecurity.tOrganizationTask WHERE CAST(LEFT(OrgGroupId, 4) AS SMALLINT) = @rOrgGroupId
DELETE FROM  sSecurity.tPermission WHERE OrgGroupId = @rOrgGroupId
DELETE FROM  sSecurity.tRole WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId

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

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






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

	-- special case will come orgwise and orggroupwise

DELETE FROM sCommon.tTableRowId WHERE OrgId = @rOrgGroupId 
DELETE FROM sConfig.tConfigurationSetup WHERE SourceTypeId = 2010 AND SourceId = @rOrgGroupId
DELETE FROM sSetup.tOrgGroupBatchMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sSetup.tOrgGroupMaster WHERE Id=@rOrgGroupId
	
EXEC sp_msforeachtable "ALTER TABLE ? WITH CHECK CHECK CONSTRAINT all"

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


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


GO
ALTER PROCEDURE [sCommunication].[pBlogCommentGet]
	   
	   @rBlogId bigint,
	 --@rBatchId bigint
	   --@rSyncedBlogCommentId bigint=0,
	   @rOrgGroupBatchId int=0,
	   @rOrgId smallint=0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			
BEGIN 
	 
IF(@rOrgId>0)	 
BEGIN
	SELECT 
			BC.Id,
			BC.BlogId,
			B.Title,
			B.Remark AS BlogRemark,
			--B.BatchId,
		 --   BM.Title AS Batch,
		    BC.Remark,
		    U1.DisplayTitle as BlogCreatedUserName,
		    B.CreatedDateTime as BlogCreatedDateTime,
		    U2.DisplayTitle as CommentCreatedUserName,
		    BC.CreatedDateTime as CommentCreatedDateTime,
		    TotalBlogFavorite=(Select Count(*) from sCommunication.tBlogFavorite where BlogId=@rBlogId),
		    B.CreatedUserId AS BlogCreatedUserId,
		    BC.CreatedUserId AS CommentCreatedUserId
  FROM 
            sCommunication.tBlogComment BC
            INNER JOIN sCommunication.tBlog B ON B.Id=BC.BlogId
            INNER JOIN sSecurity.tUser U1 ON U1.Id=B.CreatedUserId
            INNER JOIN sSecurity.tUser U2 ON U2.Id=BC.CreatedUserId
            INNER JOIN sCommunication.tBlogScope BS ON BS.BlogId=B.Id AND ((BS.SourceId=@rOrgId)OR (@rOrgId=0))
  WHERE 
  
       ((B.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0)) 
       AND (( BC.BlogId = @rBlogId) OR (@rBlogId = 0))
	--AND ( BC.Id > @rSyncedBlogCommentId OR @rSyncedBlogCommentId = 0)
	Order by BC.CreatedDateTime DESC

END
ELSE IF(@rOrgId=0)
BEGIN
	SELECT 
			BC.Id,
			BC.BlogId,
			B.Title,
			B.Remark AS BlogRemark,
			--B.BatchId,
		 --   BM.Title AS Batch,
		    BC.Remark,
		    U1.DisplayTitle as BlogCreatedUserName,
		    B.CreatedDateTime as BlogCreatedDateTime,
		    U2.DisplayTitle as CommentCreatedUserName,
		    BC.CreatedDateTime as CommentCreatedDateTime,
		    TotalBlogFavorite=(Select Count(*) from sCommunication.tBlogFavorite where BlogId=@rBlogId),
		    B.CreatedUserId AS BlogCreatedUserId,
		    BC.CreatedUserId AS CommentCreatedUserId
  FROM 
            sCommunication.tBlogComment BC
            INNER JOIN sCommunication.tBlog B ON B.Id=BC.BlogId
            INNER JOIN sSecurity.tUser U1 ON U1.Id=B.CreatedUserId
            INNER JOIN sSecurity.tUser U2 ON U2.Id=BC.CreatedUserId
  WHERE 
  
      ((BC.BlogId = @rBlogId) OR (@rBlogId = 0))
	--AND ((B.BatchId=@rBatchId) OR (@rBatchId=0)) 
	Order by BC.CreatedDateTime DESC
END	 
	
END
GO
PRINT N'Altering [sCommunication].[pCircularListGet]...';


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

BEGIN 
	
	if @rUserSourceTypeId   = 95 -- For Employee Login
	
	BEGIN
	SELECT 	
			C.Id as CircularId,
			C.Title,
			C.Remark,
			C.StartDate,
			CV.UserId,
			U.DisplayTitle as CreatedUserName
			  
	 FROM 
            sCommunication.tCircular C 
            LEFT JOIN sCommunication.tCircularView CV ON CV.CircularId=C.Id AND UserId=@rUserId           
            INNER JOIN sCommunication.tCircularScope CS ON CS.CircularId=C.Id 
            INNER JOIN ( SELECT EJD.OrganizationDepartmentId FROM sHrm.tEmployeeMaster EM
            INNER JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id = EJD.EmployeeId WHERE EM.Id = @rUserSourceId) D
						ON D.OrganizationDepartmentId =  CS.SourceId AND CS.SourceTypeId = 2004
            INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=C.OrgGroupBatchId AND OGBM.Id=@rOrgGroupBatchId
            INNER JOIN sSecurity.tUser U ON U.Id=C.CreatedUserId
            WHERE ( c.Id > @rSyncedCircularId OR @rSyncedCircularId = 0)
           	Order by C.CreatedDateTime DESC
			
	
 END
 ELSE IF @rUserSourceTypeId   = 2003 -- For Student Login
 BEGIN
 	SELECT 	
			C.Id as CircularId,
			C.Title,
			C.Remark,
			C.StartDate,
			CV.UserId,
			U.DisplayTitle as CreatedUserName	    
	 FROM 
            sCommunication.tCircular C       
            LEFT JOIN sCommunication.tCircularView CV ON CV.CircularId=C.Id AND UserId=@rUserId     
            INNER JOIN sCommunication.tCircularScope CS ON CS.CircularId=C.Id 
            INNER JOIN (SELECT A.DivisionId FROM sStudent.tAcademic A INNER JOIN sSetup.tBatchMaster BM
            ON A.BatchId = BM.Id  
            WHERE A.StudentId=@rUserSourceId AND BM.IsActive = 1) D
            ON D.DivisionId =  CS.SourceId AND CS.SourceTypeId = 2005
            INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=C.OrgGroupBatchId AND OGBM.Id=@rOrgGroupBatchId
            INNER JOIN sSecurity.tUser U ON U.Id=C.CreatedUserId
            WHERE ( c.Id > @rSyncedCircularId OR @rSyncedCircularId = 0)
            Order by C.CreatedDateTime DESC


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


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


GO
ALTER PROCEDURE [sCommunication].[pNewsCommentGet]
	   @rNewsId bigint,
	 --@rBatchId bigint
	   --@rSyncedNewsCommentId bigint=0,
	   @rOrgGroupBatchId int=0,
	   @rOrgId smallint=0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			
BEGIN 
	 
IF(@rOrgId>0)	 
BEGIN
	SELECT 
			NC.Id,
			NC.NewsId,
			N.Title,
			N.Remark AS NewsRemark,
			--N.BatchId,
		 --   BM.Title AS Batch,
		    NC.Remark,
		    U1.DisplayTitle as NewsCreatedUserName,
		    N.CreatedDateTime as NewsCreatedDateTime,
		    U2.DisplayTitle as CommentCreatedUserName,
		    NC.CreatedDateTime as CommentCreatedDateTime,
		    N.CreatedUserId AS NewsCreatedUserId,
		    NC.CreatedUserId AS CommentCreatedUserId
  FROM 
            sCommunication.tNewsComment NC
            INNER JOIN sCommunication.tNews N ON N.Id=NC.NewsId
            INNER JOIN sSecurity.tUser U1 ON U1.Id=N.CreatedUserId
            INNER JOIN sSecurity.tUser U2 ON U2.Id=NC.CreatedUserId
            INNER JOIN sCommunication.tNewsScope NS ON NS.NewsId=N.Id AND ((NS.SourceId=@rOrgId)OR (@rOrgId=0))
  WHERE 
  
     ((N.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0)) 
     AND (( NC.NewsId = @rNewsId) OR (@rNewsId = 0))
	--AND ( NC.Id > @rSyncedNewsCommentId OR @rSyncedNewsCommentId = 0)
	Order by NC.CreatedDateTime DESC
END

ELSE IF(@rOrgId=0)	
BEGIN

SELECT 
			NC.Id,
			NC.NewsId,
			N.Title,
			N.Remark AS NewsRemark,
			--N.BatchId,
		 --   BM.Title AS Batch,
		    NC.Remark,
		    U1.DisplayTitle as NewsCreatedUserName,
		    N.CreatedDateTime as NewsCreatedDateTime,
		    U2.DisplayTitle as CommentCreatedUserName,
		    NC.CreatedDateTime as CommentCreatedDateTime,
		    N.CreatedUserId AS NewsCreatedUserId,
		    NC.CreatedUserId AS CommentCreatedUserId
  FROM 
            sCommunication.tNewsComment NC
            INNER JOIN sCommunication.tNews N ON N.Id=NC.NewsId
            INNER JOIN sSecurity.tUser U1 ON U1.Id=N.CreatedUserId
            INNER JOIN sSecurity.tUser U2 ON U2.Id=NC.CreatedUserId
  WHERE 
  
      ((NC.NewsId = @rNewsId) OR (@rNewsId = 0))
	Order by NC.CreatedDateTime DESC
END
	
	
END
GO
PRINT N'Altering [sCommunication].[pPhotoCategoryMasterGet]...';


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

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


GO
ALTER PROCEDURE [sCommunication].[pStudentResultGet]
	 
	 --@rSourceTypeId smallint,
	 @rSourceId bigint,
	 @rDivisionId int,
	 @rBatchId int,
	 @rSyncedUploadResultId int=0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	IF (@rSourceId!=0)
	BEGIN
		SELECT @rDivisionId=DivisionId FROM sStudent.tAcademic		
		 WHERE StudentId=@rSourceId AND BatchId = @rBatchId
	END
		SELECT 
			@rSourceId AS SourceId,
			UR.Id,
			UR.Title,
			UR.ExamDate,
			S.Code
		FROM 
			sCommunication.tUploadResult UR  
			INNER JOIN sStudent.vStudentAcademic S ON S.DivisionId = UR.DivisionId AND 
			S.StudentId = @rSourceId AND S.BatchId = @rBatchId
		WHERE 
				UR.DivisionId=@rDivisionId
			AND UR.BatchId=@rBatchId
			AND UR.IsObsolete=0
			AND ( UR.Id > @rSyncedUploadResultId OR @rSyncedUploadResultId = 0)
				order by UR.ExamDate,S.RollNo,S.Code DESC
END
GO
PRINT N'Altering [sEExam].[pDeactiveTestParticipant]...';


GO
ALTER PROCEDURE [sEExam].[pDeactiveTestParticipant]
	 
	 @rTestId bigint,
	 @rSourceId bigint,
	 @rSourceTypeId int,
	 @rBatchId int	
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	BEGIN TRY
		BEGIN TRANSACTION			
		    IF(@rSourceTypeId = 2005)
			   BEGIN           
					 UPDATE  TP 
					 SET TP.TestStatusId = 0
					 FROM sEExam.tTestParticipant TP INNER JOIN sStudent.vStudentAcademic VSA 
					 ON TP.SourceId = VSA.StudentId 
					 Where DivisionId = @rSourceId  AND TP.TestId = @rTestId AND VSA.BatchId = @rBatchId
					 --INSERT INTO sEExam.tTestParticipant
					 --Select @rTestId,2003,StudentId,@rTestDate,@rStartTime,@rEndTime,1,@rTotalMarks,@rScoredMarks,@rTotalQuestions,@rRightQuestions,@rWrongQuestions,@rNotAttemptedQuestions
					 --FROM sStudent.vStudentAcademic VSA Where DivisionId = @rSourceId  
			           
			         UPDATE  TA 
					 SET TA.TestStatusId = 0
					 FROM sEExam.tTestAssign TA INNER JOIN sStudent.vStudentAcademic VSA 
					 ON TA.SourceId = VSA.StudentId 
					 Where DivisionId = @rSourceId AND TA.TestId = @rTestId AND VSA.BatchId = @rBatchId
				     
				  --   UPDATE  TP 
					 --SET TA.TestStatusId = 0
					 --FROM sEExam.tTestParticipant TP INNER JOIN sEExam.tTestAssign TA ON TP.SourceId = TA.SourceId					  
					 --WHERE  TP.SourceTypeId = 2003 AND TA.TestStatusId = 1 
			          
					SELECT 1 AS Result 
               END 
			ELSE 
			   BEGIN
			      UPDATE sEExam.tTestParticipant SET TestStatusId = 0 WHERE   SourceId = @rSourceId AND SourceTypeId = @rSourceTypeId AND TestId = @rTestId
			   END			   
			   -- When I Deactive Div Then Also Deactive Student Which Is Active 
			    UPDATE sEExam.tTestAssign SET TestStatusId = 0 Where SourceId = @rSourceId AND SourceTypeId = @rSourceTypeId AND TestId = @rTestId
		  
			SELECT 1 AS Result 
			
		COMMIT TRANSACTION	
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END
GO
PRINT N'Altering [sEExam].[pTestMasterAdd]...';


GO

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

	END
	
	 BEGIN TRANSACTION	
 IF(@rId = 0)	
BEGIN

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

	INSERT INTO sEExam.tTestMaster
		(
			Id,
			Code,
			Title,
			DataSubjectId,
			TestDate,
			FromTime,
			ToTime,
			IsDisplayResultOnComplete,
			IsSMSResultOnComplete,
			IsAllowReview,
			IsAutoPostResultToExam,
			IsObsolete,
			TotalMarks,
			CreatedUserId,
			CreatedDateTime,
			OrgId,
			DataBankId,
			ClassGroupId,
			ClassId,
			ClassSubjectId,
			TestTemplateId,
			AssignedSourceTypeId,
			TestDuration,
			IsTestLock,
			TestQuestion,
			IsMarkInDecimal,
			IsAutoFinishOnTime,
			BatchId
		)
	VALUES
		(
			@lNextNumber,
			@rCode,
			@rTitle,
			@rDataSubjectId,
			@rTestDate,
			@rFromTime,
			@rToTime,
			@rIsDisplayResultOnComplete,
			@rIsSMSResultOnComplete,
			@rIsAllowReview,
			@rIsAutoPostResultToExam,
			@rIsObsolete,
			@rTotalMarks,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rOrgId,
			@rDataBankId,
			@rClassGroupId,
			@rClassId,
			@rClassSubjectId,
			@rTestTemplateId,
			@rAssignedSourceTypeId,
			@rTestDuration,
			0,
			@rTestQuestion,
			@rIsMarkInDecimal,
			@rIsAutoFinishOnTime,
			@rBatchId
		)
		             
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE sEExam.tTestMaster
	    SET
	      Code=@rCode,
	      Title=@rTitle,
	      DataSubjectId=@rDataSubjectId,
	      ClassGroupId = @rClassGroupId,
	      TestDate=@rTestDate,
	      FromTime=@rFromTime,
	      ToTime=@rToTime,
	      IsDisplayResultOnComplete=@rIsDisplayResultOnComplete,
	      IsSMSResultOnComplete=@rIsSMSResultOnComplete,
	      IsAllowReview=@rIsAllowReview,
	      IsAutoPostResultToExam=@rIsAutoPostResultToExam,
	      IsObsolete=@rIsObsolete,
	      TotalMarks =@rTotalMarks,
	      UpdatedUserId=@rUpdatedUserId,
	      UpdatedDateTime= sCommon.fGetDate(),
	      classId = @rClassId,
	      ClassSubjectId = @rClassSubjectId,
	      TestTemplateId = @rTestTemplateId,
	      AssignedSourceTypeId = @rAssignedSourceTypeId,
	      TestDuration = @rTestDuration,
	      IsTestLock = @rIsTestLock,
	      TestQuestion = @rTestQuestion,
	      IsMarkInDecimal=@rIsMarkInDecimal,
	      IsAutoFinishOnTime=@rIsAutoFinishOnTime,      
	      BatchId=@rBatchId
	      
	      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].[pTestParticipantAdd]...';


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


GO


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

DECLARE @1TestAssignStatusId int

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


GO
ALTER PROCEDURE [sFee].[pFeeAllocationClassGet]
	 
		@rFeeSetupId int,
		@rDivisionId int,
		@rClassId int,
		@rAdmissionCategoryId int
		
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 	

DECLARE @rBatchId int

SELECT @rBatchId = BatchId FROM sFee.tFeeSetup WHERE id = @rFeeSetupId	
	
	SELECT 
			SA.AcademicId AS SourceId,
			SA.Name,
			SA.Code,
			SA.RollNo,
			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.NotApplicableAmount,0.00)AS NotApplicableAmount,
			ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
			ISNULL(R.PaidAmount,0) AS PaidAmount,
			ISNULL(FS.Amount,0.00) + ISNULL(FA.VariableAmount,0.00) + ISNULL(FA.AdditionalAmount,0.00) - ISNULL(FA.DiscountAmount,0.00) - ISNULL(FA.NotApplicableAmount,0.00) - ISNULL(R.PaidAmount,0.00) AS PendingAmount,
			ISNULL(FA.Remark,'') AS Remark
	  FROM 
			 sStudent.vStudentAcademic SA
		INNER JOIN 
		(
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId
			FROM sFee.tFeeSetup FS1
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId
				WHERE FS1.ClassId=@rClassId AND 
				FS1.AdmissionCategoryId=@rAdmissionCategoryId AND 
				FS1.Id=@rFeeSetupId AND IsOptional=0 AND
				SA1.BatchId = @rBatchId AND
				FS1.BatchId = @rBatchId
				
				UNION ALL
				
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId
			FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO
			ON FO.FeeSetupId=FS1.Id
		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND 
		SA1.ClassId=@rClassId  AND SA1.AdmissionCategoryId=@rAdmissionCategoryId AND SA1.BatchId = @rBatchId
		WHERE
		 FS1.Id=@rFeeSetupId AND
		 FS1.ClassId=@rClassId AND FS1.AdmissionCategoryId=@rAdmissionCategoryId 
		 AND IsOptional=1
		 AND FS1.BatchId = @rBatchId
		 
				
		) FS ON FS.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
		LEFT JOIN
		(
		    SELECT 
					ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
		    FROM
				sFee.tReceipt R 
				INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId AND R.SourceTypeId = 2001				
				AND (SA1.ClassId=@rClassId OR @rClassId=0) AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
			WHERE			 		
				 (R.IsObsolete = 0) 
				AND RD.FeeSetupId = @rFeeSetupId
				AND (R.BatchId = @rBatchId) 
					GROUP BY FeeSetupId,R.SourceId
		
		) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId 
		--AND SA.StatusId=1	
		WHERE
				(SA.ClassId=@rClassId)
			AND (SA.DivisionId=@rDivisionId)
			AND (SA.AdmissionCategoryId=@rAdmissionCategoryId)
			AND (FS.Id=@rFeeSetupId)	
			AND SA.BatchId = @rBatchId
ORDER BY SA.RollNo
	
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
				AND FS1.BatchId = @rBatchId
				UNION ALL
				
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId
			FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO
			ON FO.FeeSetupId=FS1.Id AND (FO.SourceId=@rSourceId) AND(FO.SourceTypeId=@rSourceTypeId)
			WHERE
			 FS1.BatchId = @rBatchId
			AND	FS1.ClassId=@lClassId AND FS1.AdmissionCategoryId=@lAdmissionCategoryId AND IsOptional=1
		) FS ON FS.FeeId=FM.Id
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=FS.Id AND (FA.SourceId=@rSourceId) AND(FA.SourceTypeId=@rSourceTypeId)
		LEFT JOIN
		(
		    SELECT ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId
		    FROM
		    sFee.tReceipt R INNER JOIN sFee.tReceiptDetail RD ON	RD.ReceiptId = R.Id 		
			WHERE						
			 R.SourceId= @rSourceId
			AND R.SourceTypeId = @rSourceTypeId
			AND R.IsObsolete = 0 
			AND R.BatchId = @rBatchId
			 GROUP BY FeeSetupId
		) R ON R.FeeSetupId = FS.Id	
WHERE 
	FS.BatchId=@rBatchId
ORDER BY FS.StartDate ASC,FM.OrderIndex ASC

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


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

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


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

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


GO
/****** Object:  StoredProcedure [sSupport].[pClaimAdd]    Script Date: 08/27/2013 10:32:12 ******/


ALTER PROCEDURE [sFee].[pReceiptAdd]
	
		   @rId bigint,
		   @rSourceTypeId smallint,
		   @rSourceId bigint,
		   @rReceiptNumber int,
		   @rReceiptDate date,
		   @rReceiptAmount decimal(12,2),
		   @rTotalReceiptAmount decimal(12,2),
		   @rDiscountAmount decimal(12,2),
		   @rPayTypeId tinyint,
		   @rChequeNo nvarchar(20),
		   @rBankName nvarchar(200),
		   @rReceiptBookId int,
		   @rIsObsolete bit,
		   @rCreatedUserId bigint,
		   @rOrgId int,
		   @rBatchId int,
		   @rOrgGroupBatchId int,
		   @rRemark nvarchar(200),
		   @rReceiptDetailXml [nvarchar](max),
		   @rChequeDate date,
		   @rCharge decimal(12,2)=0
		   

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

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

BEGIN
	BEGIN TRY

	  SELECT @rOrgGroupBatchId = OrgGroupBatchId FROM sSetup.tBatchMaster where Id = @rBatchId
	
	IF(@rReceiptNumber <> 0)
	BEGIN
		IF EXISTS(SELECT 1 from sFee.tReceipt where ReceiptNumber=@rReceiptNumber AND ReceiptBookId=@rReceiptBookId AND OrgGroupBatchId = @rOrgGroupBatchId)
		BEGIN
			SELECT -102 AS Result
			RETURN
		END
	END
	ELSE	
		SET @rReceiptNumber = sFee.fReceiptNumberGet(@rReceiptBookId,@rOrgGroupBatchId)

	
	 BEGIN TRANSACTION	
 IF(@rId = 0)	
BEGIN

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


	INSERT INTO sFee.tReceipt
		(
		   Id,
		   SourceTypeId,
		   SourceId,
		   ReceiptNumber,
		   ReceiptDate,
		   ReceiptAmount,
		   TotalReceiptAmount,
		   DiscountAmount,
		   PayTypeId,
		   ChequeNo,
		   BankName,
		   ReceiptBookId,
		   Remark,
		   IsObsolete,
		   BatchId,
		   CreatedUserId,
		   CreatedDateTime,
		   OrgGroupBatchId,
		   ChequeDate
        )
	VALUES
		(
			@lNextNumber,
			@rSourceTypeId,
			@rSourceId,
		    @rReceiptNumber,
		    @rReceiptDate,
		    @rReceiptAmount,
		    @rTotalReceiptAmount,
		    @rDiscountAmount,
		    @rPayTypeId,
		    @rChequeNo,
		    @rBankName,
		    @rReceiptBookId,
		    @rRemark,
		    @rIsObsolete,
		    @rBatchId,
		    @rCreatedUserId,
		    sCommon.fGetDate(),
		    @rOrgGroupBatchId,
		    @rChequeDate
		)
		
		INSERT INTO sFee.tReceiptDetail
		(
		   ReceiptId,
		   FeeSetupId,
		   Amount
        )
        SELECT  	
		  @lNextNumber,
		  FeeSetupId,
		  Amount
		
	FROM OPENXML (@loDoc, '/Table/ReceiptDetail', 1)
		WITH ( 
				FeeSetupId int,
				Amount decimal(12,2)
			  ) 
		
		SELECT @lNextNumber AS Result
		EXEC sp_xml_removedocument @loDoc
		
		IF (@rCharge > 0)
		BEGIN
		EXEC [sFee].[pReceiptChargeAdd] @rSourceTypeId,@rSourceId,@lNextNumber,@rCreatedUserId,@rOrgId,@rBatchId,@rCharge
		END
	
		DECLARE @lIsServiceTaxApplicable bit
	    DECLARE @lServiceTaxPercentage decimal(6,2)
	
	    SELECT @lIsServiceTaxApplicable = ISNULL(IsServiceTaxApplicable,0),@lServiceTaxPercentage = ISNULL(ServiceTaxPercentage,0) FROM sFee.tReceiptBookMaster where Id = @rReceiptBookId
		
		IF (@lIsServiceTaxApplicable > 0 AND @lServiceTaxPercentage > 0)
		BEGIN
		EXEC [sFee].[pReceiptServiceTaxAdd] @rSourceTypeId,@rSourceId,@lNextNumber,@rCreatedUserId,@rOrgId,@rBatchId,@lServiceTaxPercentage
		END
 END 
	ELSE
	BEGIN
		UPDATE sFee.tReceipt SET
			ReceiptDate=@rReceiptDate,
			PayTypeId=@rPayTypeId,
			ChequeDate=@rChequeDate,
		    ChequeNo=@rChequeNo,
		    BankName=@rBankName,
		    Remark=@rRemark
		WHERE Id=@rId
	SELECT @rId AS RESULT
	
	END 
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sFee].[pRptFeePendingDetailListGet]...';


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


GO


ALTER PROCEDURE [sFee].[pRptFeePendingDetailWithScholarshipListGet]
		@rReportId int,
		@rReceiptBookId int,
		@rAdmissionCategoryId int,
		@rClassId int,
		@rDivisionId int,
		@rUptoDate date,
		@rBatchId int,
		@rUserId bigint,
		@rBuilder1 nvarchar(max),
		@rBuilder2 nvarchar(max),
		@rOrgId int,
		@rOrgGroupBatchId int,
		@rStatusId int,
		@rCommonBatch nvarchar(100),
		@rDepartmentId int,
		@rFromRollNo int,
	    @rToRollNo int,
	    @rCode nvarchar(20),
	    @rIsFilter bit,
		@rIsHeader bit,
		@rCreatedUserName nvarchar(100)=''
	    
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 	

	DECLARE @p as TempPendingFee
	
	INSERT INTO  @p 
	 
	SELECT 
		SA.AcademicId,
		SA.RollNo,
		SA.Name,
		SA.Code,
		SA.ClassId,
		SA.DivisionId,
		SA.ClassName,
		SA.DivisionName,
		SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
		0 AS FeeSetupId,		
		0 AS IsVariable,
		0 AS Amount,
		'1900-01-01' AS StartDate,
		'1900-01-01' AS EndDate,
	    0.00 AS FAAmount,
		0.00 AS DiscountAmount,
		0.00 AS AdditionalAmount,
		0 AS PaidAmount,
		SUM(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,
		'' AS Remark,
		0 ReceiptBookId,
		'' AS FeeName,
		'' AS FeeCode,
		SA.OrgId,
		O.Title AS OrgName,
		O.OrderIndex AS OrgOrderIndex,
		'' AS ReceiptBookTitle,
		0 AS ReceiptOrderIndex,
		0 AS BatchId,
		'' AS BatchName
			
  FROM 
  
			 sStudent.vStudentAcademic SA
		INNER JOIN 
		(
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName,
				FM.Code AS FeeCode
			FROM sFee.tFeeSetup FS1
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
				AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0))
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			WHERE 
			     (SA1.OrgGroupBatchId = @rOrgGroupBatchId)
				AND	((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=0)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				
				UNION ALL
				
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName,
				FM.Code AS FeeCode
			FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO
			ON FO.FeeSetupId=FS1.Id
	    INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
			AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) 
			AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
		WHERE
		       (SA1.OrgGroupBatchId = @rOrgGroupBatchId)
				AND ((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=1)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				
		) FS ON FS.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
		LEFT JOIN
		(
		    SELECT 
					ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
		    FROM
				sFee.tReceipt R 
				INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId				
				AND (SA1.ClassId=@rClassId OR @rClassId=0) 
				AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
				
			WHERE		
				(R.SourceTypeId = 2001)
				AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND (R.IsObsolete = 0) 
				AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId)  )
				AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				GROUP BY FeeSetupId,R.SourceId
				
				
		
		) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
		 INNER JOIN sSetup.tOrganizationMaster O ON
		 SA.OrgId = O.Id
		 INNER JOIN sFee.tReceiptBookMaster RBM 
			ON FS.ReceiptBookId=RBM.Id
	   
		 
		
	WHERE	
			(SA.OrgGroupBatchId = @rOrgGroupBatchId)
			AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0)) 
			AND (SA.StatusId = @rStatusId OR @rStatusId=0)
			AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
			AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
			AND ((SA.Code=@rCode) OR (@rCode=''))
			AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
			AND (ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00) -ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00) != 0)	
			GROUP BY 
			SA.AcademicId,
			SA.RollNo,
			SA.Name,
			SA.Code,
			SA.ClassId,
			SA.DivisionId,
			SA.ClassName,
			SA.DivisionName,
			SA.ClassName,
			SA.DivisionName,
			OrgId,
			O.Title,
			O.OrderIndex,
			BatchName
				
			Order by SA.RollNo

			SELECT
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			@rIsFilter AS IsFilter, 
			OrgId,			 
			p.AcademicId,
			DivisionId,
			ClassDivision,
			RollNo, 
			Name,
			Code,
			OrgName,
			ISNULL(SUM(PendingAmount),0) AS PendingAmount, 
			ISNULL(SUM(SS.ScholarshipPaid),0) AS ScholarshipPaid,
			ISNULL(SUM(SS.EligibleAmount),0) AS EligibleAmount,
			ISNULL(SS.ReferenceRemark,'')   AS ReferenceRemark
			--,
			--CASE ISNULL(SS.AcademicId,0) WHEN 0 THEN 0 ELSE 1 END AS IsScholarshipEligible		
			FROM @p p 
			
		LEFT JOIN				
		(SELECT  SE.AcademicId,Sum(PaidAmount) AS ScholarshipPaid,SUM(SE.EligibleAmount) AS EligibleAmount, SO.ReferenceRemark FROM 
		sScholarship.tScholarshipEligibleStudent SE
		LEFT JOIN sScholarship.tScholarshipStudentPaid SP on SE.AcademicId = SP.AcademicId
		INNER JOIN sStudent.vStudentAcademic SA1  ON SE.AcademicId = SA1.AcademicId 
		INNER JOIN sStudent.tStudentOther SO ON SA1.StudentId = SO.StudentId
		WHERE
		    (SA1.OrgGroupBatchId = @rOrgGroupBatchId)
		 	AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
		 	AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
		 	AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
		 	AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = @rOrgGroupBatchId))
		 	AND ((SA1.ClassId=@rClassId) OR (@rClassId=0))
		 	GROUP BY SE.AcademicId,ReferenceRemark
		 ) SS ON p.AcademicId=SS.AcademicId
			GROUP By 
			OrgId,			
			p.AcademicId,
			--SS.AcademicId,
			DivisionId,
			ClassDivision,
			RollNo, 
			Name,
			Code,
			OrgName,
			ReferenceRemark
			ORDER BY AcademicId
END
GO
PRINT N'Altering [sFee].[pRptFeeReceiptDetailListGet]...';


GO

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

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


GO

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


GO


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


GO


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


GO
ALTER PROCEDURE [sHostel].[pHostelStudentSearchGet]
	 
	 @rOrgId int,
	 @rHostelId int,
	 @rRoomId int,
	 @rStudentId bigint,
	 @rStudentName nvarchar(100),
	 @rStudentCode nvarchar(100),
	 @rClassId int,
	 @rDivisionId int,
	 @rOrgGroupBatchId int
	 	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON 
BEGIN 		
			SELECT 			 
			O.DisplayTitle AS Organization,
			HM.Title AS Hostel,
			RM.Title AS Room,
			SD.Code AS StudentCode,
			SD.Name AS StudentName,
			SD.ClassDivision AS Class,
			SD.DivisionName AS Division,
			SD.StudentId,
			SD.ClassId,
			SD.DivisionId,
			HM.Id AS HostelId,
			RM.Id AS RoomId,
			O.Id AS OrgId,
			ISNULL(AR.BedNumber,'') AS BedNumber 

			FROM sHostel.tAssignRoom AR 
			INNER JOIN sStudent.vStudentAllDetail SD ON SD.StudentId = AR.SourceId AND AR.SourceTypeId = 2003
			INNER JOIN sHostel.tRoomMaster RM ON AR.RoomId = RM.Id 
			INNER JOIN sHostel.tHostelMaster HM ON HM.Id = RM.HostelId
			INNER JOIN sSetup.vUserOrganization O ON O.Id = SD.OrgId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=SD.OrgGroupBatchId AND (ISNULL(OGBM.IsActive,0) = 1)

			Where 
			
			SourceTypeId = 2003
			AND (SD.OrgGroupBatchId=@rOrgGroupBatchId)
			AND (O.Id = @rOrgId OR ISNULL(@rOrgId,0) = 0)
			AND (HM.Id = @rHostelId OR ISNULL(@rHostelId,0) = 0)
			AND (RM.Id = @rRoomId OR ISNULL(@rRoomId,0) = 0)
			AND (SD.StudentId = @rStudentId OR ISNULL(@rStudentId,0) = 0)
			AND (SD.ClassId = @rClassId OR ISNULL(@rClassId,0) = 0)
			AND (SD.DivisionId = @rDivisionId OR ISNULL(@rDivisionId,0) = 0)
			AND (SD.Code Like @rStudentCode OR ISNULL(@rStudentCode,'')='')
			AND (SD.Name like @rStudentName + '%' OR ISNULL(@rStudentName,'') = '')
END
GO
PRINT N'Altering [sHostel].[pRptRoomwiseStudentListGet]...';


GO


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

BEGIN 

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


GO
ALTER 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'Altering [sHrm].[pEmployeeCustomSearchGet]...';


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

BEGIN
		DECLARE @Sql nvarchar(MAX)

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


GO


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

BEGIN TRY
BEGIN TRANSACTION

EXEC sp_xml_preparedocument @loDoc OUTPUT,@rXML
BEGIN
	
	IF(@rSubCategoryField = 'Gender' OR @rSubCategoryField = 'Religion' OR @rSubCategoryField = 'BloodGroup'
	OR @rSubCategoryField = 'MaritalStatus' OR @rSubCategoryField = 'OrganizationDepartment' OR @rSubCategoryField = 'EmployeeType'
			OR @rSubCategoryField = 'EmployeeGroup' OR @rSubCategoryField = 'EmployeeGrade' OR @rSubCategoryField = 'Relationship' OR  @rSubCategoryField = 'EmployeeDesignation'
			OR  @rSubCategoryField = 'Payroll' OR  @rSubCategoryField = 'PayrollGroup'
			)
	BEGIN
		SET @rSubCategoryField = @rSubCategoryField + 'Id'
	END
	--ELSE IF (@rSubCategoryField = 'MaritalStatusId' OR @rSubCategoryField = 'OrganizationDepartmentId' OR @rSubCategoryField = 'EmployeeTypeId'
	--		OR @rSubCategoryField = 'EmployeeGroupId' OR @rSubCategoryField = 'EmployeeGradeId' OR @rSubCategoryField = 'RelationshipId'  )
	--	BEGIN
	--		SET @rSubCategoryField = @rSubCategoryField 
	--	END
			
	CREATE TABLE ListofData(Id bigint,EmployeeId bigint,SubCategory nvarchar(100),UpdatedUserId bigint,IsExist bit);
	IF(@rCategoryId= 1)
		BEGIN
		insert into ListofData
		select 0,E.EmployeeId,E.SubCategory,E.UpdatedUserId,0
		from
		(
				SELECT EmployeeId,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Employees/Employees', 2)
				WITH (
						EmployeeId BIGINT, 
						SubCategory nvarchar(100),
						UpdatedUserId bigint)	
						)E 	
		UPDATE ListofData SET IsExist=1 WHERE EmployeeId NOT IN(SELECT EmployeeId FROM sHrm.tEmployeeCommunications) 
		
		set @sql='INSERT INTO sHrm.tEmployeeCommunications 
					(EmployeeId,'+@rSubCategoryField+',CreatedUserId,CreatedDateTime)
					SELECT
						LD.EmployeeId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
					FROM
						ListofData LD WHERE LD.IsExist=1'
		Exec sp_executesql @sql
		set @sql='UPDATE sHrm.tEmployeeCommunications set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sHrm.tEmployeeCommunications EC 
					INNER JOIN ListofData LD ON EC.EmployeeId=LD.EmployeeId AND IsExist=0'
		
		Exec sp_executesql @sql
		
		
		
		Drop Table ListofData
			 SELECT 1 AS StatusId
	    END
	    
	Else IF(@rCategoryId= 2)
		BEGIN
		insert into ListofData
		select 0,E.EmployeeId,E.SubCategory,E.UpdatedUserId,0
		from
		(
				SELECT EmployeeId,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Employees/Employees', 2)
				WITH (
						EmployeeId BIGINT, 
						SubCategory nvarchar(100),
						UpdatedUserId bigint)	
						)E 	
		UPDATE ListofData SET IsExist=1 WHERE EmployeeId NOT IN(SELECT EmployeeId FROM sHrm.tEmployeePersonalDetail) 
		
		IF(@rSubCategoryField = 'DateOfBirth')
		BEGIN			
					
			 				
			set @sql='UPDATE sHrm.tEmployeePersonalDetail set '+@rSubCategoryField+' = LD.SubCategory,
						UpdatedUserId=LD.UpdatedUserId,
						UpdatedDateTime=sCommon.fGetDate()  
						from sHrm.tEmployeePersonalDetail EPD 
						INNER JOIN ListofData LD ON EPD.EmployeeId=LD.EmployeeId'			
			Exec sp_executesql @sql
			set @sql='UPDATE sHrm.tEmployeePersonalDetail SET '+@rSubCategoryField+' = null WHERE DateOfBirth=''1900-01-01'''
			Exec sp_executesql @sql
		END
		ELSE
		BEGIN
			
			 				
			set @sql='UPDATE sHrm.tEmployeePersonalDetail set '+@rSubCategoryField+' = LD.SubCategory,
						UpdatedUserId=LD.UpdatedUserId,
						UpdatedDateTime=sCommon.fGetDate()  
						from sHrm.tEmployeePersonalDetail EPD 
						INNER JOIN ListofData LD ON EPD.EmployeeId=LD.EmployeeId'
			
			Exec sp_executesql @sql
		END
		Drop Table ListofData
			 SELECT 1 AS StatusId
	    END	
	    
	Else IF(@rCategoryId= 3)
		BEGIN
		insert into ListofData
		select 0,E.EmployeeId,E.SubCategory,E.UpdatedUserId,0
		from
		(
				SELECT EmployeeId,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Employees/Employees', 2)
				WITH (
						EmployeeId BIGINT, 
						SubCategory nvarchar(100),
						UpdatedUserId bigint)	
						)E 	
	
		set @sql='UPDATE sHrm.tEmployeeJobDetail set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sHrm.tEmployeeJobDetail EJ 
					INNER JOIN ListofData LD ON EJ.EmployeeId=LD.EmployeeId'
		
		Exec sp_executesql @sql
		Drop Table ListofData
			 SELECT 1 AS StatusId
	    END	
  Else IF(@rCategoryId= 4)
	BEGIN
		insert into ListofData
		select 0,E.EmployeeId,E.SubCategory,E.UpdatedUserId,0
		from
		(
				SELECT EmployeeId,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Employees/Employees', 2)
				WITH (
						EmployeeId BIGINT, 
						SubCategory nvarchar(100),
						UpdatedUserId bigint)	
						)E 	
		UPDATE ListofData SET IsExist=1 WHERE EmployeeId NOT IN(SELECT EmployeeId FROM sHrm.tEmployeeMaster) 
		
		
		set @sql='UPDATE sHrm.tEmployeeMaster set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sHrm.tEmployeeMaster HEM 
					INNER JOIN ListofData LD ON HEM.Id=LD.EmployeeId AND IsExist=0'
		
		Exec sp_executesql @sql
		Drop Table ListofData
			SELECT 1 AS StatusId
	    END
	    
	    Else IF(@rCategoryId= 5)
		BEGIN
		insert into ListofData
		select 0,E.EmployeeId,E.SubCategory,E.UpdatedUserId,0
		from
		(
				SELECT EmployeeId,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Employees/Employees', 2)
				WITH (
						EmployeeId BIGINT, 
						SubCategory nvarchar(100),
						UpdatedUserId bigint)	
						)E 	
						
		
		set @sql='UPDATE sHrm.tEmployeeStatutoryAndOther set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sHrm.tEmployeeStatutoryAndOther ESO 
					INNER JOIN ListofData LD ON ESO.EmployeeId=LD.EmployeeId'
		
		Exec sp_executesql @sql
		Drop Table ListofData
			 SELECT 1 AS StatusId
	    END	
	    
	    
END 
	   COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		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,
	 @rDepartmentId int,
	 @rGroupId int,
	 @rTypeId int,
	 @rGradeId int
	 --@rOrderBy int
	 
AS
SET NOCOUNT ON

BEGIN

		 DECLARE @lDataTypeId nvarchar(1)
		SELECT @lDataTypeId=DataTypeId FROM sCommon.tUpdateFieldMaster WHERE Field=@rSubCategory
		
		IF(@rSubCategory = 'MaritalStatus' OR @rSubCategory = 'Gender' OR @rSubCategory = 'Religion' OR @rSubCategory = 'BloodGroup'
		OR	@rSubCategory = 'OrganizationDepartment' OR @rSubCategory = 'EmployeeType' 
			OR @rSubCategory = 'EmployeeGroup' OR @rSubCategory = 'EmployeeGrade' OR @rSubCategory = 'EmployeeDesignation' OR @rSubCategory='Payroll' OR @rSubCategory='PayrollGroup')
		BEGIN
			SET @rSubCategory = @rSubCategory + 'Id'
		END
		--ELSE IF ( @rSubCategory = 'OrganizationDepartmentId' OR @rSubCategory = 'EmployeeTypeId'
		--	OR @rSubCategory = 'EmployeeGroupId' OR @rSubCategory = 'EmployeeGradeId' OR @rSubCategory = 'RelationshipId' OR @rSubCategory='PayrollId' OR @rSubCategory='PayrollGroupId'  )
		--BEGIN
		--	SET @rSubCategory = @rSubCategory 
		--END
		
		 Declare @Sql nvarchar(max)
		 
		 SET @Sql =  CASE @rCategoryId					  
					 WHEN 1 THEN -- EmployeeCommunication
						'Select EM.Id,EM.EmployeeId,EM.Code,EM.EmployeeName,EM.LastName,EM.EmployeeGroup,EM.DepartmentName,
						CASE WHEN '+@lDataTypeId+'=1 THEN
						ISNULL(EC.'+@rSubCategory+','''')
						WHEN '+@lDataTypeId+'=2 THEN
						ISNULL(EC.'+@rSubCategory+',''0'')
						WHEN '+@lDataTypeId+'=3 THEN
						ISNULL(EC.'+@rSubCategory+',''False'')
						WHEN '+@lDataTypeId+'=4 THEN
						ISNULL(EC.'+@rSubCategory+',''0001/01/01'')
						WHEN '+@lDataTypeId+'=5 THEN
						ISNULL(EC.'+@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 (EM.DepartmentId='+ CAST(@rDepartmentId AS nvarchar(15)) +' OR '+CAST(@rDepartmentId AS nvarchar(15))+'=0)
							AND (EM.EmployeeGroupId='+ CAST(@rGroupId AS nvarchar(15)) +' OR '+CAST(@rGroupId AS nvarchar(15))+'=0)
							AND (EM.EmployeeGradeId='+ CAST(@rGradeId AS nvarchar(15)) +' OR '+CAST(@rGradeId AS nvarchar(15))+'=0)
							AND (EM.EmployeeTypeId='+ CAST(@rTypeId AS nvarchar(15)) +' OR '+CAST(@rTypeId AS nvarchar(15))+'=0)
							AND 
							('+CAST(@rIsBlank AS nvarchar(1))+'=0 
								OR ('+@lDataTypeId+'=1 AND ISNULL(EC.'+@rSubCategory+','''')='''')
								OR ('+@lDataTypeId+'=2 AND ISNULL(EC.'+@rSubCategory+',''0'')=''0'')
								OR ('+@lDataTypeId+'=3 AND ISNULL(EC.'+@rSubCategory+',''False'')=''False'')
								OR ('+@lDataTypeId+'=4 AND ISNULL(EC.'+@rSubCategory+',''0001/01/01'')=''0001/01/01'') 
							)'
					 WHEN 2 THEN -- Other
						'Select EM.Id,EM.EmployeeId,EM.Code,EM.EmployeeName,EM.LastName,EM.EmployeeGroup,EM.DepartmentName,
						CASE WHEN '+@lDataTypeId+'=1 THEN
						ISNULL(EP.'+@rSubCategory+','''')
						WHEN '+@lDataTypeId+'=2 THEN
						ISNULL(EP.'+@rSubCategory+',''0'')
						WHEN '+@lDataTypeId+'=3 THEN
						ISNULL(EP.'+@rSubCategory+',''False'')
						WHEN '+@lDataTypeId+'=4 THEN
						ISNULL(EP.'+@rSubCategory+',''0001/01/01'')
						WHEN '+@lDataTypeId+'=5 THEN
						ISNULL(EP.'+@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 (EM.DepartmentId='+ CAST(@rDepartmentId AS nvarchar(15)) +' OR '+CAST(@rDepartmentId AS nvarchar(15))+'=0)
							AND (EM.EmployeeGroupId='+ CAST(@rGroupId AS nvarchar(15)) +' OR '+CAST(@rGroupId AS nvarchar(15))+'=0)
							AND (EM.EmployeeGradeId='+ CAST(@rGradeId AS nvarchar(15)) +' OR '+CAST(@rGradeId AS nvarchar(15))+'=0)
							AND (EM.EmployeeTypeId='+ CAST(@rTypeId AS nvarchar(15)) +' OR '+CAST(@rTypeId AS nvarchar(15))+'=0)
							AND 
							('+CAST(@rIsBlank AS nvarchar(1))+'=0 
								OR ('+@lDataTypeId+'=1 AND ISNULL(EP.'+@rSubCategory+','''')='''')
								OR ('+@lDataTypeId+'=2 AND ISNULL(EP.'+@rSubCategory+',''0'')=''0'')
								OR ('+@lDataTypeId+'=3 AND ISNULL(EP.'+@rSubCategory+',''False'')=''False'')
								OR ('+@lDataTypeId+'=4 AND ISNULL(EP.'+@rSubCategory+',''0001/01/01'')=''0001/01/01'') 
							)'
							
					WHEN 3 THEN -- JobDetail
						'Select EM.Id,EM.EmployeeId,EM.Code,EM.EmployeeName,EM.LastName,EM.EmployeeGroup,EM.DepartmentName,
						CASE WHEN '+@lDataTypeId+'=1 THEN
						ISNULL(EJD.'+@rSubCategory+','''')
						WHEN '+@lDataTypeId+'=2 THEN
						ISNULL(EJD.'+@rSubCategory+',''0'')
						WHEN '+@lDataTypeId+'=3 THEN
						ISNULL(EJD.'+@rSubCategory+',''False'')
						WHEN '+@lDataTypeId+'=4 THEN
						ISNULL(EJD.'+@rSubCategory+',''0001/01/01'')
						WHEN '+@lDataTypeId+'=5 THEN
						ISNULL(EJD.'+@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 (EM.DepartmentId='+ CAST(@rDepartmentId AS nvarchar(15)) +' OR '+CAST(@rDepartmentId AS nvarchar(15))+'=0)
							AND (EM.EmployeeGroupId='+ CAST(@rGroupId AS nvarchar(15)) +' OR '+CAST(@rGroupId AS nvarchar(15))+'=0)
							AND (EM.EmployeeGradeId='+ CAST(@rGradeId AS nvarchar(15)) +' OR '+CAST(@rGradeId AS nvarchar(15))+'=0)
							AND (EM.EmployeeTypeId='+ CAST(@rTypeId AS nvarchar(15)) +' OR '+CAST(@rTypeId AS nvarchar(15))+'=0)
							AND 
							('+CAST(@rIsBlank AS nvarchar(1))+'=0 
								OR ('+@lDataTypeId+'=1 AND ISNULL(EJD.'+@rSubCategory+','''')='''')
								OR ('+@lDataTypeId+'=2 AND ISNULL(EJD.'+@rSubCategory+',''0'')=''0'')
								OR ('+@lDataTypeId+'=3 AND ISNULL(EJD.'+@rSubCategory+',''False'')=''False'')
								OR ('+@lDataTypeId+'=4 AND ISNULL(EJD.'+@rSubCategory+',''0001/01/01'')=''0001/01/01'') 
							)'
					 
					WHEN 4 THEN --General
						'Select EM.Id,EM.EmployeeId,EM.Code,EM.EmployeeName,EM.LastName,EM.EmployeeGroup,EM.DepartmentName,
					    CASE WHEN '+@lDataTypeId+'=1 THEN
						ISNULL(HEM.'+@rSubCategory+','''')
						WHEN '+@lDataTypeId+'=2 THEN
						ISNULL(HEM.'+@rSubCategory+',''0'')
						WHEN '+@lDataTypeId+'=3 THEN
						ISNULL(HEM.'+@rSubCategory+',''False'')
						WHEN '+@lDataTypeId+'=4 THEN
						ISNULL(HEM.'+@rSubCategory+',''0001/01/01'')
						WHEN '+@lDataTypeId+'=5 THEN
						ISNULL(HEM.'+@rSubCategory+',''0'')
						END AS SubCategory
							FROM 
							sHrm.vExtEmployeeMaster EM
							INNER JOIN sHrm.tEmployeeMaster HEM ON HEM.Id=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 (EM.DepartmentId='+ CAST(@rDepartmentId AS nvarchar(15)) +' OR '+CAST(@rDepartmentId AS nvarchar(15))+'=0)
							AND (EM.EmployeeGroupId='+ CAST(@rGroupId AS nvarchar(15)) +' OR '+CAST(@rGroupId AS nvarchar(15))+'=0)
							AND (EM.EmployeeGradeId='+ CAST(@rGradeId AS nvarchar(15)) +' OR '+CAST(@rGradeId AS nvarchar(15))+'=0)
							AND (EM.EmployeeTypeId='+ CAST(@rTypeId AS nvarchar(15)) +' OR '+CAST(@rTypeId AS nvarchar(15))+'=0)
							AND 
							('+CAST(@rIsBlank AS nvarchar(1))+'=0 
								OR ('+@lDataTypeId+'=1 AND ISNULL(HEM.'+@rSubCategory+','''')='''')
								OR ('+@lDataTypeId+'=2 AND ISNULL(HEM.'+@rSubCategory+',''0'')=''0'')
								OR ('+@lDataTypeId+'=3 AND ISNULL(HEM.'+@rSubCategory+',''False'')=''False'')
								OR ('+@lDataTypeId+'=4 AND ISNULL(HEM.'+@rSubCategory+',''0001/01/01'')=''0001/01/01'') 
							)'
				   
					
					
					WHEN 5 THEN --Statutory
						'Select EM.Id,EM.EmployeeId,EM.Code,EM.EmployeeName,EM.LastName,EM.EmployeeGroup,EM.DepartmentName,
					    CASE WHEN '+@lDataTypeId+'=1 THEN
						ISNULL(ESO.'+@rSubCategory+','''')
						WHEN '+@lDataTypeId+'=2 THEN
						ISNULL(ESO.'+@rSubCategory+',''0'')
						WHEN '+@lDataTypeId+'=3 THEN
						ISNULL(ESO.'+@rSubCategory+',''False'')
						WHEN '+@lDataTypeId+'=4 THEN
						ISNULL(ESO.'+@rSubCategory+',''0001/01/01'')
						WHEN '+@lDataTypeId+'=5 THEN
						ISNULL(ESO.'+@rSubCategory+',''0'')
						END AS SubCategory
							FROM 
							sHrm.vExtEmployeeMaster EM
							INNER JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.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 (EM.DepartmentId='+ CAST(@rDepartmentId AS nvarchar(15)) +' OR '+CAST(@rDepartmentId AS nvarchar(15))+'=0)
							AND (EM.EmployeeGroupId='+ CAST(@rGroupId AS nvarchar(15)) +' OR '+CAST(@rGroupId AS nvarchar(15))+'=0)
							AND (EM.EmployeeGradeId='+ CAST(@rGradeId AS nvarchar(15)) +' OR '+CAST(@rGradeId AS nvarchar(15))+'=0)
							AND (EM.EmployeeTypeId='+ CAST(@rTypeId AS nvarchar(15)) +' OR '+CAST(@rTypeId AS nvarchar(15))+'=0)
							AND 
							('+CAST(@rIsBlank AS nvarchar(1))+'=0 
								OR ('+@lDataTypeId+'=1 AND ISNULL(ESO.'+@rSubCategory+','''')='''')
								OR ('+@lDataTypeId+'=2 AND ISNULL(ESO.'+@rSubCategory+',''0'')=''0'')
								OR ('+@lDataTypeId+'=3 AND ISNULL(ESO.'+@rSubCategory+',''False'')=''False'')
								OR ('+@lDataTypeId+'=4 AND ISNULL(ESO.'+@rSubCategory+',''0001/01/01'')=''0001/01/01'') 
							)'
				   
					END
		print @Sql    
	    
	   EXECUTE  sp_executesql @Sql
END
GO
PRINT N'Altering [sHrm].[pEmployeeGenerateReport]...';


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

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


GO
ALTER PROCEDURE [sHrm].[pEmployeeJobDetailAdd]
    
    @rOrgId smallint,
	@rEmployeeId [bigint], 
	@rEmployeeDesignationId [int],
	@rOrganizationDepartmentId [int],
	@rDateOfJoining Date,
	@rCreatedUserId [bigint],
	@rEmployeeTypeId int,
	@rEmployeeGradeId int,
	@rEmployeeGroupId int,
	@rJobRemark nvarchar(200) = '',
	@rEmployeeManagerId bigint=0
	

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

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


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

BEGIN 
 
 --SELECT     
 -- WorkingDays,
 -- EmployeeId,
 -- SUM(NoOfLEave) AS NoOfLeave
  
 --FROM (	 	
 
 SELECT   
         --EM.EmployeeId,           
         --ISNULL(WD.WorkingDays,0) AS WorkingDays,       
         
        ISNULL(SUM(ISNULL([sHrm].[fMonthWiseNoOfLeave](L.FromDate,L.ToDate,@rForMonth,@rForYear,L.LeavePeriodId,L.LeaveTypeId),0)),0) AS NoOfLeave
		 
        FROM 
		sHrm.vEmployeeCommonDetail EM 
		LEFT JOIN
		sHrm.tLeave L 
	    ON L.EmployeeId = EM.EmployeeId	 AND L.BatchId = @rBatchId 	AND L.StatusId = 550 -- apporved 
    	WHERE EM.EmployeeId = @rEmployeeId  
 
END
GO
PRINT N'Altering [sHrm].[pEmployeeProfileGet]...';


GO

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

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


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

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
BEGIN TRY

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

WHILE @lCount > 0 

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

--select * from #tTable

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

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

IF 	@lDesignationId IS NULL  AND @lDesignation != ''
BEGIN
 EXEC [sHrm].[pEmployeeDesignationMasterAdd] @rOrgId,@lDesignation,@lDesignation,0,@rUserId,@OutDesignationId = @OutDesignationId OUTPUT
END
ELSE
SET @OutDesignationId = @lDesignationId

--UPDATE #tTable SET
--		GenderId = @lGenderId ,
--		EmpTypeId = @lEmpTypeId,
--		DepartmentId = @OutDepartmentId,
--		DesignationId = @lDesignationId,
--		ContractorId = @OutContractorId,
--		BloodGroupId = @lBloodGroupId WHERE Id = @lCount
 	
	
 
EXEC [sHrm].[pEmployeeMasterAdd] @rOrgId,@lCode,@lFirstName,@lMiddleName,@lLastName,@lEmployeeTypeId,
@lDepartmentId,@lDOB,@lDOJ,@lGenderId,@lReligionId,7,0,@rUserId,@OutEmployeeId OUTPUT,
@lDesignationId,NULL,@lQualification,@lEmployeeGradeId,@lEmployeeGroupId,@lShortName
 
EXEC [sHrm].[pEmployeeCommunicationsAdd] @OutEmployeeId,@lPresentStreetOne,@lPresentStreetTwo,@lPresentStreetThree,
@lPresentCountry,@lPresentState,@lPresentCity,@lPresentZipCode,@lPresentContactNo,NULL,Null,Null,NULL,NULL,NULL,NULL,Null,
Null,NULL,NULL,NULL,NULL,NULL,NULL,NULL,@lCompanyPhoneNo,@lExtentionNo,@lCompanyEmailId,@lPersonalEmailId,@lMobileNo,@rUserId
		
EXEC [sHrm].[pEmployeeStatutoryDetailAdd] @OutEmployeeId,@lAccountNumber,@lBankName,@lBranch,@lEPFNumber,@lPanNumber,
 0,NULL,NULL,0,0,NULL,NULL,NULL,@rUserId,NULL,0,NULL,NULL					

		SET @lCount = @lCount - 1	
		COMMIT TRANSACTION	
END
		SELECT 1 Result		
	END TRY
	BEGIN CATCH
	
	SELECT ERROR_MESSAGE(), ERROR_LINE()
	END CATCH
	
END
GO
PRINT N'Altering [sHrm].[pRptEmployeeAllDetailList]...';


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

BEGIN
DECLARE @lIsOnPrePrinted bit = 0

DECLARE @lConfigValue nvarchar(50)

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


GO
ALTER PROCEDURE [sHrm].[pRptEmployeeIcardGet]
	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='',
	@rReportId smallint,
	@rOrgId smallint,
	@rStrEmployeeId nvarchar(max),
	@rEmployeeTypeId [int],
	@rDepartmentId [int]= 0,
	@rGradeId [int]= 0,
	@rDesignationId [int]= 0,
	@rGenderId [int]= 0,		
	@rEmployeeId [bigint]= 0,
	@rAgeFrom nvarchar(10),
	@rAgeTo nvarchar(10),
	@rEmployeeCode nvarchar(50)='',
	@rEmployeeGroupId smallint,
	@rEmployeeStatusId smallint
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	SELECT		
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			ECD.EmployeeId,
	        ECD.Code,	      	
			ECD.EmployeeName, 	 								 
			ECD.DepartmentId,  			
			ECD.DepartmentName,
		    ECD.MobileNumber,
		    ECD.EmployeeDesignation,
		    ECD.PhoneNoCompany,
		    ECD.BloodGroup,
		    ECD.DateOfBirth,
			EI.EmployeePhoto,
		    OM.Title AS OrgName,
		    OM.PrincipalSignature,
			ISNULL(ICO.ICardOrgTitle,'') AS ICardOrgTitle,
			ISNULL(ICO.ICardAddress1,'') AS ICardAddress1,
			ISNULL(ICO.ICardAddress2,'') AS ICardAddress2,
			ISNULL(ICO.ICardAddress3,'') AS ICardAddress3,	
		    OM.OrgLogo AS ICardLogo,
			ICO.ICardBackground,	
			ICO.ICardBackBackground,						
			ISNULL(ICO.LabelColor,'Black') AS LabelColor,
			ISNULL(ICO.DetailColor,'Black') AS DetailColor,
			ISNULL(ICO.HeaderColor,'Black') AS HeaderColor,
			ISNULL(EC.PresentStreetOne,'') AS PresentStreetOne,
			ISNULL(EC.PresentStreetTwo,'') AS PresentStreetTwo,
			ISNULL(EC.PresentStreetThree,'') AS PresentStreetThree,
			ISNULL(EC.PresentCity,'') AS PresentCity,
			ISNULL(EC.PresentState,'') AS PresentState,
			ISNULL(EC.PresentCountry,'') AS PresentCountry,
			ISNULL(EC.PresentZipCode,'') AS PresentZipCode
		FROM 
			sHrm.vEmployeeCommonDetail ECD
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=ECD.OrgID
			LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId=ECD.EmployeeId
			LEFT JOIN sHrm.tEmployeeICardOrg ICO ON ECD.OrgId = ICO.OrgId
			LEFT JOIN tEmployeeCommunications EC ON ECD.EmployeeId = EC.EmployeeId
			
		WHERE
		((ECD.Code LIKE @rEmployeeCode)OR @rEmployeeCode = '' )
	   AND (ISNULL(ECD.EmployeeId,0) NOT IN( SELECT cast(item as bigint) FROM  sCommon.fnsplit(@rStrEmployeeId,',')) OR @rStrEmployeeId='') 
	   AND (ECD.EmployeeTypeId = @rEmployeeTypeId OR @rEmployeeTypeId = 0)
	   AND (ECD.OrganizationDepartmentId = @rDepartmentId OR @rDepartmentId = 0)
	   AND (ECD.EmployeeStatusId = @rEmployeeStatusId OR @rEmployeeStatusId = 0)
	   AND (ECD.EmployeeGroupId=@rEmployeeGroupId OR @rEmployeeGroupId=0)
	   AND (ECD.EmployeeGradeId = @rGradeId OR @rGradeId = 0)
	   AND (ECD.EmployeeDesignationId = @rDesignationId OR @rDesignationId = 0)	 	   
	   AND (ECD.GenderId = @rGenderId OR @rGenderId = 0)  	    
	   AND (ECD.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)	   
	   --AND ((DATEDIFF(yy,ECD.DateOfBirth,GETDATE()) <= @rAgeTo) OR (ISNULL(@rAgeTo,0)=0))
	   --AND ((DATEDIFF(yy,ECD.DateOfBirth,GETDATE()) >= @rAgeFrom)OR (ISNULL(@rAgeFrom,0)=0))
	   AND  ECD.OrgId = @rOrgId
END
GO
PRINT N'Altering [sHrm].[pValidateImportEmployee]...';


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


GO

ALTER PROCEDURE [sLibrary].[pBookMasterAdd]
	 
	
	@rId bigint,
	@rCode nvarchar(25),
	@rTitle nvarchar(100),
	@rPublisher nvarchar(200),
	@rSupplier nvarchar(200),
	@rAuthor nvarchar(200),
	@rSubject nvarchar(200),
	@rLanguage nvarchar(200),
	@rLocation nvarchar(200),
	@rEdition nvarchar(50),
	@rISBNNumber nvarchar(100),
	@rPrice decimal(12,2),
	@rCurrency nvarchar(100),
	@rBookTag nvarchar(200),
	@rBookCustomTag nvarchar(200),
	@rBookAgeGroupId int,
	@rResourceTypeId int,
	@rOrgGroupId int,
	@rBatchId int,
	@rLibraryId int,
	@rCreatedUserId bigint,
	@rUpdatedUserId bigint,
	@rBookDepartment nvarchar(150),
	@rClassNumber nvarchar(50),
	@rBookVolume smallint,
	@rNoOfCopies smallint
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	 

				
BEGIN TRANSACTION

IF(@rId = 0)



    BEGIN
    
    	IF Exists(Select @rCode from sLibrary.tBookMaster where Code=@rCode AND LibraryId = @rLibraryId )
		BEGIN
			Select -103 AS Result
			RETURN
		END
    
    
DECLARE @lNextNumber BIGINT   
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sLibrary.tBookMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	
	INSERT INTO sLibrary.tBookMaster
		(
			Id,
			Code,
			Title,
			Publisher,
			Supplier,
			Author,
			BookSubject,
			BookLanguage,
			Location,
			Edition,
			ISBNNumber,
			Price,
			Currency,
			BookTag,
			BookCustomTag,
			BookAgeGroupId,
			ResourceTypeId,
			CreatedUserId,
			CreatedDateTime,
			LibraryId,
			BookDepartment,
			ClassNumber,
			BookVolume,
			NoOfCopies
		)
	VALUES
		(
			@lNextNumber,
			@rCode,
			@rTitle,
		    @rPublisher,
		    @rSupplier,
			@rAuthor,
			@rSubject,
			@rLanguage,
			@rLocation,
			@rEdition,
			@rISBNNumber,
			@rPrice,
			@rCurrency,
			@rBookTag,
			@rBookCustomTag,
			@rBookAgeGroupId,
			@rResourceTypeId,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rLibraryId,
			@rBookDepartment,
			@rClassNumber,
			@rBookVolume,
			@rNoOfCopies
		)
		
	  EXECUTE sLibrary.pBookLogAdd NULL,NULL,2009,@lNextNumber,null,null,521,NULL,1,@rOrgGroupId,@rBatchId,@rCreatedUserId,@rLibraryId
		   
		   Select @lNextNumber AS Result
	END
	
		
	ELSE
	
	 BEGIN
	 
	 	IF Exists(Select @rCode from sLibrary.tBookMaster where Code=@rCode AND LibraryId = @rLibraryId  AND Id!=@rId)
		BEGIN
			Select -103 AS Result
			RETURN
		END
	 
	 SET @lNextNumber = @rId
	    UPDATE  sLibrary.tBookMaster
	    SET
			Code=@rCode,
			Title=@rTitle,
			Publisher=@rPublisher,
			Supplier=@rSupplier,
			Author=@rAuthor,
			BookSubject=@rSubject,
			BookLanguage=@rLanguage,
			Location=@rLocation,
			Edition=@rEdition,
			ISBNNumber=@rISBNNumber,
			Price=@rPrice,
			Currency=@rCurrency,
			BookTag=@rBookTag,
			BookCustomTag=@rBookCustomTag,
			BookAgeGroupId=@rBookAgeGroupId,
			ResourceTypeId=@rResourceTypeId,						
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate(),
			BookDepartment=@rBookDepartment,
			ClassNumber=@rClassNumber,
			BookVolume=@rBookVolume,
			NoOfCopies=@rNoOfCopies
			
	      
	      WHERE Id = @rId 
	      --AND Code=@rCode
	      SELECT @lNextNumber AS Result
	
END	
		
	COMMIT TRANSACTION
END TRY
	
	
	BEGIN CATCH
	    ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH  
END        
GO
PRINT N'Altering [sLibrary].[pBookMasterGet]...';


GO

ALTER PROCEDURE [sLibrary].[pBookMasterGet]
	 
	 @rId bigint = 0,
	 @rCode nvarchar(200),
	 @rTitle nvarchar(100),
	 @rOrgId int,
	 @rPublisher nvarchar(200),
	 @rSupplier nvarchar(200),
	 @rAuthor nvarchar(200),
	 @rSubject nvarchar(200),
	 @rLanguage nvarchar(200),
	 @rLocation nvarchar(200),
	 @rEdition nvarchar(50),
	 @rPrice decimal=0,
	 @rCurrency nvarchar(100),
	 @rISBNNumber nvarchar(100),
	 @rBookTag nvarchar(200),
	 @rBookCustomTag nvarchar(200),
	 @rBookAgeGroupId int,
	 @rResourceTypeId int,
	 @rStatusId smallint,
	 @rCreatedUserId bigint,
	 @rLibraryId int,
	 @rBookDepartment nvarchar(150)
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	  --BEGIN
			--SET @rCode = sCommon.fSearchStringGet(@rCode)
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
			SET @rPublisher = sCommon.fSearchStringGet(@rPublisher)
			SET @rSupplier = sCommon.fSearchStringGet(@rSupplier)
			SET @rAuthor = sCommon.fSearchStringGet(@rAuthor)
			SET @rSubject = sCommon.fSearchStringGet(@rSubject)
			SET @rLanguage = sCommon.fSearchStringGet(@rLanguage)
			SET @rLocation = sCommon.fSearchStringGet(@rLocation)
			SET @rEdition = sCommon.fSearchStringGet(@rEdition)
			SET @rCurrency = sCommon.fSearchStringGet(@rCurrency)
			SET @rISBNNumber = sCommon.fSearchStringGet(@rISBNNumber)
			SET @rBookTag = sCommon.fSearchStringGet(@rBookTag)
			SET @rBookCustomTag = sCommon.fSearchStringGet(@rBookCustomTag)
	  --END
	 
	SELECT 
	BM.Code,
	BM.Title,
	ISNULL(BM.Publisher,'')AS Publisher,
	ISNULL(BM.Supplier,'')AS Supplier,
	ISNULL(BM.Author,'')AS Author,
	ISNULL(BM.BookSubject,'') AS BookSubject,
	ISNULL(BM.BookLanguage,'') AS BookLanguage,
	ISNULL(BM.Location,'') AS Location,
	ISNULL(BM.Edition,'')AS Edition,
	ISNULL(BM.ISBNNumber,'') AS ISBNNumber,
	ISNULL(BM.Price,0) AS Price,
	ISNULL(BM.Currency,'') AS Currency,
	ISNULL(BM.BookTag,'')AS BookTag,
	ISNULL(BM.BookCustomTag,'') AS BookCustomTag,
	ISNULL(BM.BookDepartment,'') AS BookDepartment,
	ISNULL(BM.ClassNumber,'') AS ClassNumber,
	ISNULL(BM.BookVolume,1) AS BookVolume,
	ISNULL(BM.NoOfCopies,1) AS NoOfCopies,
	BM.Id,
	ISNULL(AGM.Id,0)AS BookAgeGroupId,
	ISNULL(RTM.Id,0) AS ResourceTypeId,
	BM.CreatedUserId,
	BM.CreatedDateTime,
	ISNULL(BM.UpdatedUserId,0) AS UpdatedUserId,
	ISNULL(BM.UpdatedDateTime,'') AS UpdatedDateTime,
	BM.LibraryId,
	SM.Id AS StatusId,
	SM.Title AS StatusName
	
  FROM 
        sLibrary.tBookMaster BM
         LEFT JOIN sLibrary.tBookAgeGroupMaster AGM
         ON BM.BookAgeGroupId=AGM.Id
         LEFT JOIN sLibrary.tResourceTypeMaster RTM
         ON BM.ResourceTypeId=RTM.Id
         INNER JOIN sLibrary.tBookLog BL
         ON BL.ResourceSourceId=BM.Id AND IsCurrentStatus=1
         INNER JOIN sCommon.tStatusMaster SM
         ON SM.Id=BL.StatusId
           
  WHERE 
  
      ((BM.Id = @rId) OR (@rId = 0))
      ANd ((BM.Code = @rCode) OR (ISNULL(@rCode,'') = ''))
       AND  ((BM.Title like @rTitle) OR (ISNULL(@rTitle,'') = '')) 
        AND  ((BM.Publisher like @rPublisher) OR (ISNULL(@rPublisher,'') = '')) 
         AND  ((BM.Supplier like @rSupplier) OR (ISNULL(@rSupplier,'') = '')) 
          AND  ((BM.Author like @rAuthor) OR (ISNULL(@rAuthor,'') = '')) 
           AND  ((BM.BookSubject like @rSubject) OR (ISNULL(@rSubject,'') = ''))  
            AND  ((BM.BookLanguage like @rLanguage) OR (ISNULL(@rLanguage,'') = ''))  
             AND  ((BM.Location like @rLocation) OR (ISNULL(@rLocation,'') = ''))  
              AND  ((BM.Edition like @rEdition) OR (ISNULL(@rEdition,'') = ''))  
               AND  ((BM.ISBNNumber like @rISBNNumber) OR (ISNULL(@rISBNNumber,'') = ''))  
                AND  ((BM.BookTag like @rBookTag) OR (ISNULL(@rBookTag,'') = ''))
                 AND  ((BM.BookCustomTag like @rBookCustomTag) OR (ISNULL(@rBookCustomTag,'') = ''))
                  AND  ((BM.BookAgeGroupId = @rBookAgeGroupId) OR(@rBookAgeGroupId=0))
                   AND  ((BM.ResourceTypeId = @rResourceTypeId) OR (@rResourceTypeId=0))
                    AND  ((BM.Price = @rPrice) OR (@rPrice=0))
                     AND  ((BM.Currency like @rCurrency) OR (ISNULL(@rCurrency,'') = ''))
                      AND  ((BL.StatusId = @rStatusId) OR (@rStatusId=0))
                      ANd ((BM.BookDepartment like @rBookDepartment) OR (ISNULL(@rBookDepartment,'') = ''))
						--AND ((BL.OrgId=@rOrgId) OR (@rOrgId=0))
	  AND BM.LibraryId = @rLibraryId	
		
END
GO
PRINT N'Altering [sLibrary].[pImportBook]...';


GO
ALTER PROCEDURE [sLibrary].[pImportBook]
    @rOrgGroupId smallint,
	@rXmldoc [nvarchar](max),
	@rUserId bigint,
	@rBatchId int,
	@rLibraryId int

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
--BEGIN TRY

DECLARE @lCount INT
DECLARE @lInterrorCode INT,
		@intDoc INT,
		@lCode nvarchar(25),
		@lTitle nvarchar(100),
		@lPublisher nvarchar(200),
		@lSupplier nvarchar(200),
		@lAuthor nvarchar(200),
		@lBookSubject nvarchar(200),
		@lBookLanguage nvarchar(200),
		@lLocation nvarchar(200),
		@lEdition nvarchar(50),
		@lISBNNumber nvarchar(100),
		@lPrice decimal(12,2),
		@lCurrency nvarchar(100),
		@lBookTag nvarchar(200),
		@lBookCustomTag nvarchar(200),
		@lBookDepartment nvarchar(150),
		@lClassNumber nvarchar(50),
		@lBookVolume int,
		@lNoOfCopies int
			
EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc
	
	CREATE TABLE #tTable  
	(
		Id bigint identity,	 
		Code nvarchar(25),
		Title nvarchar(100),
		Publisher nvarchar(200),
		Supplier nvarchar(200),
		Author nvarchar(200),
		BookSubject nvarchar(200),
		BookLanguage nvarchar(200),
		Location nvarchar(200),
		Edition nvarchar(50),
		ISBNNumber nvarchar(100),
		Price decimal(12,2),
		Currency nvarchar(100),
		BookTag nvarchar(200),
		BookCustomTag nvarchar(200),
		BookDepartment nvarchar(150),
		ClassNumber nvarchar(50),
		BookVolume int,
		NoOfCopies int
	)
		
	INSERT INTO #tTable
	(
		Code,
		Title,
		Publisher,
		Supplier,
		Author,
		BookSubject,
		BookLanguage,
		Location,
		Edition,
		ISBNNumber,
		Price,
		Currency,
		BookTag,
		BookCustomTag,
		BookDepartment,
		ClassNumber,
		BookVolume,
		NoOfCopies
	)
	SELECT
		Code,
		Title,
		Publisher,
		Supplier,
		Author,
		BookSubject,
		BookLanguage,
		Location,
		Edition,
		ISBNNumber,
		Price,
		Currency,
		BookTag,
		BookCustomTag,
		BookDepartment,
		ClassNumber,
		BookVolume,
		NoOfCopies
	FROM OPENXML (@intDoc, '/Table/ImportBook', 1)
	WITH
	( 
		Code nvarchar(25) '@Code',			
		Title nvarchar(100) '@Title',			
		Publisher nvarchar(200) '@Publisher',			
		Supplier nvarchar(200) '@Supplier',			
		Author nvarchar(200) '@Author',			
		BookSubject nvarchar(200) '@BookSubject',			
		BookLanguage nvarchar(200) '@BookLanguage',			
		Location nvarchar(200) '@Location',			
		Edition nvarchar(50) '@Edition',			
		ISBNNumber nvarchar(100) '@ISBNNumber',			
		Price decimal(12,2) '@Price',			
		Currency nvarchar(100) '@Currency',			
		BookTag nvarchar(200) '@BookTag',			
		BookCustomTag nvarchar(200) '@BookCustomTag',
		BookDepartment nvarchar(150) '@BookDepartment',
		ClassNumber nvarchar(50) '@ClassNumber',
		BookVolume int '@BookVolume',
		NoOfCopies int '@NoOfCopies'
	)
	
EXEC sp_xml_removedocument @intDoc
			
SELECT @lCount =  COUNT(Id) FROM #tTable

WHILE @lCount > 0 

BEGIN
		SET @lCode = ''
		SET @lTitle = ''
		SET @lPublisher = ''
		SET @lSupplier = ''
		SET @lAuthor = ''
		SET @lBookSubject = ''
		SET @lBookLanguage = ''
		SET @lLocation = ''
		SET @lEdition = ''
		SET @lISBNNumber = ''
		SET @lPrice = 0
		SET @lCurrency = ''
		SET @lBookTag = ''
		SET @lBookCustomTag = ''
		SET @lBookDepartment = ''
		SET @lClassNumber = ''
		SET @lBookVolume = 0
		SET @lNoOfCopies = 0
		

SELECT		
		@lCode = Code,
		@lTitle = Title,
		@lPublisher = Publisher,
		@lSupplier = Supplier,
		@lAuthor = Author,
		@lBookSubject = BookSubject,
		@lBookLanguage = BookLanguage,
		@lLocation = Location,
		@lEdition = Edition,
		@lISBNNumber = ISBNNumber,
		@lPrice = Price,
		@lCurrency = Currency,
		@lBookTag = BookTag,
		@lBookCustomTag = BookCustomTag,
		@lBookDepartment = BookDepartment,
		@lClassNumber = ClassNumber,
		@lBookVolume = BookVolume,
		@lNoOfCopies = NoOfCopies
			
											 	 
FROM #tTable WHERE Id = @lCount  

	
		--BEGIN TRANSACTION

		EXEC [sLibrary].[pBookMasterAdd] 0,@lCode,@lTitle,@lPublisher,@lSupplier,@lAuthor,@lBookSubject,
		@lBookLanguage,@lLocation,@lEdition,@lISBNNumber,@lPrice,@lCurrency,@lBookTag,@lBookCustomTag,		
		NULL,1,@rOrgGroupId,@rBatchId,@rLibraryId,@rUserId,@rUserId,
		@lBookDepartment,@lClassNumber,@lBookVolume,@lNoOfCopies

		SET @lCount = @lCount - 1	
		--COMMIT TRANSACTION			
END

	SELECT 1
	--END TRY
	--BEGIN CATCH
	
	--SELECT ERROR_MESSAGE(), ERROR_LINE()
	--END CATCH
	
END

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


GO

ALTER PROCEDURE [sLibrary].[pIssueSettingAdd]
	 
        @rSourceTypeId smallint,
        @rSourceId bigint,
		@rNoOfBookIssuable smallint,
		@rIssueDays smallint,
		@rPenaltyPerDay decimal(12,2),
		@rReserveDays smallint,
		@rCreatedUserId bigint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	BEGIN TRANSACTION	
	IF NOT EXISTS(Select SourceId from sLibrary.tIssueSetting WHERE SourceTypeId=@rSourceTypeId AND SourceId=@rSourceId)
	BEGIN
	INSERT INTO sLibrary.tIssueSetting
		(
			SourceTypeId,
			SourceId,
			NoOfBookIssuable,
			IssueDays,
			PenaltyPerDay,
			ReserveDays,
			CreatedUserId,
			CreatedDateTime
		)
	VALUES
		(
			@rSourceTypeId,
			@rSourceId,
			@rNoOfBookIssuable,
			@rIssueDays,
			@rPenaltyPerDay,
			@rReserveDays,
			@rCreatedUserId,
			sCommon.fGetDate()
		)
		    SELECT @rSourceId AS Result
	      
	END	
	ELSE
	 BEGIN
	    UPDATE  sLibrary.tIssueSetting
	    SET
			NoOfBookIssuable=@rNoOfBookIssuable,
			IssueDays=@rIssueDays,
			PenaltyPerDay=@rPenaltyPerDay,
			ReserveDays=@rReserveDays,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate()
	      
	      WHERE SourceTypeId = @rSourceTypeId
			AND SourceId=@rSourceId
	      SELECT @rSourceId AS Result
	
	 END  	

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


GO

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

	UNION ALL

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

	UNION ALL

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


GO
ALTER PROCEDURE [sMis].[pRptAverageAttendanceGet]
	
		@rBuilder1 nvarchar(max)='',
		@rBuilder2 nvarchar(max)='', 
		--@rBatchId int,
		@rClassId int,
		@rDepartmentId int,
		@rOrgMainGroupId int,
		@rOrgSubGroupId int,
		@rOrgId smallint,
		@rOrgGroupBatchId int,
		@rFromDate Date,
		@rToDate Date,
		@rStrOrgMainGroupId nvarchar(max),
		@rStrOrgSubGroupId nvarchar(max),
		@rStrOrgId nvarchar(max),
		@rStrDepartmentId nvarchar(max),
		@rStrClassId nvarchar(max),
		@rOrgGroupId int,
		@rIsTestMainGroup bit =0,
		@rIsTestSubGroup bit =0,
		@rIsTestOrg bit=0,
		@rIsTestClass bit=0,
		@rIsTestDepartment bit=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			@rIsTestMainGroup AS IsTestMainGroup,
			@rIsTestSubGroup AS IsTestSubGroup,
			@rIsTestOrg AS IsTestOrg,
			@rIsTestClass AS IsTestClass,
			@rIsTestDepartment AS IsTestDepartment,
			CM.Id AS ClassId,
			CM.DisplayTitle AS ClassName,
			CM.OrderIndex,
			CM.DepartmentId,
			DM.DisplayTitle AS DepartmentName,
			OMGM.Id AS OrgMainGroupId,
			OMGM.Title AS OrgMainGroupTitle,
			OSGM.Id AS OrgSubGroupId,
			OSGM.Title AS OrgSubGroupTitle,
			OM.Id AS OrgId,
			OM.DisplayTitle AS OrgDisplayTitle,
			(select ISNULL(count(1),0) from sAttendance.tStudentRegister SR
			INNER JOIN sStudent.tAcademic A ON SR.AcademicId = A.Id
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId AND BM.IsActive = 1			
			WHERE CM.Id = A.ClassId
			AND AttendanceTypeId = 1
			AND BM.OrgGroupBatchId = @rOrgGroupBatchId
			AND SR.IsPresent=1
			 ) PresentCount,
			(select ISNULL(count(1),0) from sAttendance.tStudentRegister SR
			INNER JOIN sStudent.tAcademic A ON SR.AcademicId = A.Id
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId AND BM.IsActive = 1			
			WHERE CM.Id = A.ClassId
			AND AttendanceTypeId = 1
			AND BM.OrgGroupBatchId = @rOrgGroupBatchId 
			AND SR.IsPresent=0
			) AbsentCount
			 
		   
	FROM 
			sSetup.tClassMaster CM			
			--INNER JOIN sSetup.tBatchClass BC ON BC.ClassId= CM.Id
			INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=CM.DepartmentId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = DM.OrgId
			INNER JOIN sSetup.tOrgSubGroupMaster OSGM ON OSGM.Id = OM.OrgSubGroupId
			INNER JOIN sSetup.tOrgMainGroupMaster OMGM ON OMGM.Id = OSGM.OrgMainGroupId
	WHERE 
			--BC.BatchId = @rBatchId
		   ((CM.Id=@rClassId) OR (@rClassId=0))
			AND	((CM.DepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))
			AND ((OMGM.Id=@rOrgMainGroupId) OR (@rOrgMainGroupId=0))
			AND ((OSGM.Id=@rOrgSubGroupId) OR (@rOrgSubGroupId=0))
			AND ((OM.Id=@rOrgId) OR (@rOrgId=0))
			AND ((OM.OrgGroupId = @rOrgGroupId))
			
			AND (OMGM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit(	@rStrOrgMainGroupId,','))OR @rStrOrgMainGroupId='')
			AND (OSGM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit(	@rStrOrgSubGroupId,','))OR @rStrOrgSubGroupId='')
			AND (OM.Id IN (SELECT cast (item as int) FROM  sCommon.fnsplit ( @rStrOrgId,','))OR @rStrOrgId='')
			AND (DM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit  (@rStrDepartmentId,','))OR @rStrDepartmentId='')
			AND (CM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit  (@rStrClassId,','))OR @rStrClassId='')
			 
			ORDER BY CM.OrderIndex ASC
END
GO
PRINT N'Altering [sMis].[pRptClassCapacityGet]...';


GO
ALTER PROCEDURE [sMis].[pRptClassCapacityGet]
	
		@rBuilder1 nvarchar(max)='',
		@rBuilder2 nvarchar(max)='', 
		--@rBatchId int,
		@rClassId int,
		@rDepartmentId int,
		@rOrgMainGroupId int,
		@rOrgSubGroupId int,
		@rOrgId smallint,
		@rStrOrgMainGroupId nvarchar(max),
		@rStrOrgSubGroupId nvarchar(max),
		@rStrOrgId nvarchar(max),
		@rStrDepartmentId nvarchar(max),
		@rStrClassId nvarchar(max),
		@rOrgGroupId int,
		@rOrgGroupBatchId int,
		@rIsTestMainGroup bit =0,
		@rIsTestSubGroup bit =0,
		@rIsTestOrg bit=0,
		@rIsTestClass bit=0,
		@rIsTestDepartment bit=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			@rIsTestMainGroup AS IsTestMainGroup,
			@rIsTestSubGroup AS IsTestSubGroup,
			@rIsTestOrg AS IsTestOrg,
			@rIsTestClass AS IsTestClass,
			@rIsTestDepartment AS IsTestDepartment,
			CM.Id AS ClassId,
			CM.DisplayTitle AS ClassName,
			CM.OrderIndex,
			ISNULL(CM.Capacity,0) AS Capacity,
			(SELECT ISNULL(count(1),0) FROM sStudent.tAcademic A INNER JOIN sStudent.tStudentMaster SM 
			ON A.StudentId = SM.Id INNER JOIN sSetup.tBatchMaster BM ON A.BatchId = BM.Id
			WHERE A.ClassId = CM.Id AND SM.StatusId = 1 						
			AND BM.IsActive = 1 AND BM.OrgGroupBatchId = @rOrgGroupBatchId
			) AS CurrentStrength,
			CM.DepartmentId,
			DM.DisplayTitle AS DepartmentName,
			OMGM.Id AS OrgMainGroupId,
			OMGM.Title AS OrgMainGroupTitle,
			OSGM.Id AS OrgSubGroupId,
			OSGM.Title AS OrgSubGroupTitle,
			OM.Id AS OrgId,
			OM.DisplayTitle AS OrgDisplayTitle
			
	FROM 
			sSetup.tClassMaster CM			
			--INNER JOIN sSetup.tBatchClass BC ON BC.ClassId= CM.Id
			INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=CM.DepartmentId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = DM.OrgId
			INNER JOIN sSetup.tOrgSubGroupMaster OSGM ON OSGM.Id = OM.OrgSubGroupId
			INNER JOIN sSetup.tOrgMainGroupMaster OMGM ON OMGM.Id = OSGM.OrgMainGroupId
			
	WHERE 
			--((BC.BatchId = @rBatchId)
			  ((CM.Id=@rClassId) OR (@rClassId=0))
			AND	((CM.DepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))
			AND ((OMGM.Id=@rOrgMainGroupId) OR (@rOrgMainGroupId=0))
			AND ((OSGM.Id=@rOrgSubGroupId) OR (@rOrgSubGroupId=0))
			AND ((OM.Id=@rOrgId) OR (@rOrgId=0))
			AND ((OM.OrgGroupId = @rOrgGroupId))
			
			AND (OMGM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit(	@rStrOrgMainGroupId,','))OR @rStrOrgMainGroupId='')
			AND (OSGM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit(	@rStrOrgSubGroupId,','))OR @rStrOrgSubGroupId='')
			AND (OM.Id IN (SELECT cast (item as int) FROM  sCommon.fnsplit ( @rStrOrgId,','))OR @rStrOrgId='')
			AND (DM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit  (@rStrDepartmentId,','))OR @rStrDepartmentId='')
			AND (CM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit  (@rStrClassId,','))OR @rStrClassId='')
			 
			ORDER BY CM.OrderIndex ASC
END
GO
PRINT N'Altering [sMis].[pRptDivisionCapacityGet]...';


GO
ALTER PROCEDURE [sMis].[pRptDivisionCapacityGet]
	 
		@rBuilder1 nvarchar(max)='',
		@rBuilder2 nvarchar(max)='', 
		--@rBatchId int,
		@rDepartmentId int,
		@rClassId int,
		@rDivisionId int,
		@rOrgMainGroupId int,
		@rOrgSubGroupId int,
		@rOrgId smallint,
		@rStrOrgMainGroupId nvarchar(max),
		@rStrOrgSubGroupId nvarchar(max),
		@rStrOrgId nvarchar(max),
		@rStrDepartmentId nvarchar(max),
		@rStrClassId nvarchar(max),
		@rOrgGroupId int,
		@rOrgGroupBatchId int,
		@rIsTestMainGroup bit =0,
		@rIsTestSubGroup bit =0,
		@rIsTestOrg bit=0,
		@rIsTestDepartment bit=0,
		@rIsTestClass bit=0
		
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 

  SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			@rIsTestMainGroup AS IsTestMainGroup,
			@rIsTestSubGroup AS IsTestSubGroup,
			@rIsTestOrg AS IsTestOrg,
			@rIsTestDepartment AS IsTestDepartment,
			@rIsTestClass AS IsTestClass,
			DM.Id AS DivisionId,
			CM.Id AS ClassId,
			CM.DisplayTitle AS ClassName,
			DM.DisplayTitle AS DivisionName,
			CM.DisplayTitle+'-'+DM.DisplayTitle AS ClassDivisionName,
			DM.OrderIndex,
			ISNULL(DM.Capacity,0) AS Capacity,
			(SELECT ISNULL(count(1),0) FROM sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON A.StudentId = SM.Id 
			INNER JOIN sSetup.tBatchMaster BM ON A.BatchId = BM.Id
			WHERE A.DivisionId = DM.Id AND SM.StatusId = 1 			
			AND BM.IsActive = 1 AND BM.OrgGroupBatchId = @rOrgGroupBatchId
			) AS CurrentStrength,
			CM.DepartmentId,
			DeptM.DisplayTitle AS DepartmentName,
			OMGM.Id AS OrgMainGroupId,
			OMGM.Title AS OrgMainGroupTitle,
			OSGM.Id AS OrgSubGroupId,
			OSGM.Title AS OrgSubGroupTitle,
			OM.Id AS OrgId,
			OM.DisplayTitle AS OrgDisplayTitle
  FROM 
			sSetup.tDivisionMaster DM
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=DM.ClassId
			--INNER JOIN sSetup.tBatchClass BC ON CM.Id=BC.ClassId
			INNER JOIN sSetup.tDepartmentMaster DeptM ON DeptM.Id=CM.DepartmentId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = DM.OrgId
			INNER JOIN sSetup.tOrgSubGroupMaster OSGM ON OSGM.Id = OM.OrgSubGroupId
			INNER JOIN sSetup.tOrgMainGroupMaster OMGM ON OMGM.Id = OSGM.OrgMainGroupId
  WHERE 
			--BC.BatchId = @rBatchId
			((CM.DepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))
			AND ((DM.Id=@rDivisionId) OR (@rDivisionId=0)) 
			AND ((CM.Id=@rClassId) OR (@rClassId=0))
			AND ((OMGM.Id=@rOrgMainGroupId) OR (@rOrgMainGroupId=0))
			AND ((OSGM.Id=@rOrgSubGroupId) OR (@rOrgSubGroupId=0))
			AND ((OM.Id=@rOrgId) OR (@rOrgId=0))
			AND ((OM.OrgGroupId = @rOrgGroupId))
			
			AND (OMGM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit(	@rStrOrgMainGroupId,','))OR @rStrOrgMainGroupId='')
			AND (OSGM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit(	@rStrOrgSubGroupId,','))OR @rStrOrgSubGroupId='')
			AND (OM.Id IN (SELECT cast (item as int) FROM  sCommon.fnsplit ( @rStrOrgId,','))OR @rStrOrgId='')
			AND (DM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit  (@rStrDepartmentId,','))OR @rStrDepartmentId='')
			AND (CM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit  (@rStrClassId,','))OR @rStrClassId='')
			
			ORDER BY CM.OrderIndex ASC
END
GO
PRINT N'Altering [sMis].[pRptInquiryAdmissionGet]...';


GO
ALTER PROCEDURE [sMis].[pRptInquiryAdmissionGet]
	
		@rBuilder1 nvarchar(max)='',
		@rBuilder2 nvarchar(max)='', 
		--@rBatchId int,
		@rClassId int,
		@rDepartmentId int,
		@rOrgMainGroupId int,
		@rOrgSubGroupId int,
		@rOrgId smallint,
		@rOrgGroupBatchId int,
		@rFromDate Date,
		@rToDate Date,
		@rStrOrgMainGroupId nvarchar(max),
		@rStrOrgSubGroupId nvarchar(max),
		@rStrOrgId nvarchar(max),
		@rStrDepartmentId nvarchar(max),
		@rStrClassId nvarchar(max),
		@rOrgGroupId int,
		--@rStrOrgMainGroupDisId nvarchar(max),
		@rIsTestMainGroup bit =0,
		@rIsTestSubGroup bit =0,
		@rIsTestOrg bit=0,
		@rIsTestClass bit=0,
		@rIsTestDepartment bit=0
		
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
--SET @rBatchId = ISNULL(@rBatchId,0)
	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			@rIsTestMainGroup AS IsTestMainGroup,
			@rIsTestSubGroup AS IsTestSubGroup,
			@rIsTestOrg AS IsTestOrg,
			@rIsTestClass AS IsTestClass,
			@rIsTestDepartment AS IsTestDepartment,
			CM.Id AS ClassId,
			CM.DisplayTitle AS ClassName,
			CM.OrderIndex,
			--ISNULL(CM.Capacity,0) AS Capacity,
			--(SELECT ISNULL(count(1),0) FROM sStudent.tAcademic A INNER JOIN sStudent.tStudentMaster SM ON A.StudentId = SM.Id WHERE A.ClassId = CM.Id AND SM.StatusId = 1 AND A.BatchId = @rBatchId) AS CurrentStrength,
			CM.DepartmentId,
			DM.DisplayTitle AS DepartmentName,
			OMGM.Id AS OrgMainGroupId,
			OMGM.Title AS OrgMainGroupTitle,
			OSGM.Id AS OrgSubGroupId,
			OSGM.Title AS OrgSubGroupTitle,
			OM.Id AS OrgId,
			OM.DisplayTitle AS OrgDisplayTitle,
			(select COUNT(AI.Id) FROM sAdmission.tAdmissionInquiry AI INNER JOIN sSetup.tBatchMaster BM
			 ON AI.ForBatchId = BM.Id
			 WHERE BM.OrgGroupBatchId = @rOrgGroupBatchId AND   AI.InquiryDate >= @rFromDate AND AI.InquiryDate <= @rToDate 
			 AND AI.ForClassId = CM.Id )  NoOfInquiry,
		    (select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
			WHERE BM.OrgGroupBatchId = @rOrgGroupBatchId AND SA.AdmissionDate >= @rFromDate AND   SA.AdmissionDate <= @rToDate
			AND A.ClassId =CM.Id ) AS NoOfAdmission
 
	FROM 
			sSetup.tClassMaster CM						
			INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=CM.DepartmentId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = DM.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OG ON OG.Id = OM.OrgGroupId
			INNER JOIN sSetup.tOrgSubGroupMaster OSGM ON OSGM.Id = OM.OrgSubGroupId
			INNER JOIN sSetup.tOrgMainGroupMaster OMGM ON OMGM.Id = OSGM.OrgMainGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OBM ON OBM.OrgGroupId = OG.Id
			--INNER JOIN sSetup.tBatchMaster BM ON BM.OrgId = OM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId 
	WHERE 
			--BC.BatchId = @rBatchId
		   ((CM.Id=@rClassId) OR (@rClassId=0))
			AND	((CM.DepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))
			AND ((OMGM.Id=@rOrgMainGroupId) OR (@rOrgMainGroupId=0))
			AND ((OSGM.Id=@rOrgSubGroupId) OR (@rOrgSubGroupId=0))
			AND ((OM.Id=@rOrgId) OR (@rOrgId=0))
			--AND ((BM.Id=@rBatchId) OR (@rBatchId=0))			 
			AND  (OBM.Id = @rOrgGroupBatchId)
			AND ((OM.OrgGroupId = @rOrgGroupId))
			AND (OMGM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit(	@rStrOrgMainGroupId,','))OR @rStrOrgMainGroupId='')
			AND (OSGM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit(	@rStrOrgSubGroupId,','))OR @rStrOrgSubGroupId='')
			AND (OM.Id IN (SELECT cast (item as int) FROM  sCommon.fnsplit ( @rStrOrgId,','))OR @rStrOrgId='')
			AND (DM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit  (@rStrDepartmentId,','))OR @rStrDepartmentId='')
			AND (CM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit  (@rStrClassId,','))OR @rStrClassId='')
			 
			--AND (OMGM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit(@rStrOrgMainGroupDisId,','))OR @rStrOrgMainGroupDisId='')
			 
			ORDER BY CM.OrderIndex ASC
END
GO
PRINT N'Altering [sMis].[pRptStudentStrengthGet]...';


GO
ALTER PROCEDURE [sMis].[pRptStudentStrengthGet]
	
		@rBuilder1 nvarchar(max)='',
		@rBuilder2 nvarchar(max)='', 
		--@rBatchId int,
		@rClassId int,
		@rDepartmentId int,
		@rOrgMainGroupId int,
		@rOrgSubGroupId int,
		@rOrgId smallint,
		@rOrgGroupBatchId int,
		@rFromDate Date,
		@rToDate Date,
		@rStrOrgMainGroupId nvarchar(max),
		@rStrOrgSubGroupId nvarchar(max),
		@rStrOrgId nvarchar(max),
		@rStrDepartmentId nvarchar(max),
		@rStrClassId nvarchar(max),
		@rIsTestMainGroup bit =0,
		@rIsTestSubGroup bit =0,
		@rIsTestOrg bit=0,
		@rIsTestClass bit=0,
		@rIsTestDepartment bit=0,
		@rOrgGroupId int
		
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			@rIsTestMainGroup AS IsTestMainGroup,
			@rIsTestSubGroup AS IsTestSubGroup,
			@rIsTestOrg AS IsTestOrg,
			@rIsTestClass AS IsTestClass,
			@rIsTestDepartment AS IsTestDepartment,
			CM.Id AS ClassId,
			CM.DisplayTitle AS ClassName,
			CM.OrderIndex,
			--ISNULL(CM.Capacity,0) AS Capacity,
			--(SELECT ISNULL(count(1),0) FROM sStudent.tAcademic A INNER JOIN sStudent.tStudentMaster SM ON A.StudentId = SM.Id WHERE A.ClassId = CM.Id AND SM.StatusId = 1 AND A.BatchId = @rBatchId) AS CurrentStrength,
			CM.DepartmentId,
			DM.DisplayTitle AS DepartmentName,
			OMGM.Id AS OrgMainGroupId,
			OMGM.Title AS OrgMainGroupTitle,
			OSGM.Id AS OrgSubGroupId,
			OSGM.Title AS OrgSubGroupTitle,
			OM.Id AS OrgId,
			OM.DisplayTitle AS OrgDisplayTitle,
						
		    (select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
			WHERE BM.IsActive = 1 AND SA.AdmissionDate < @rFromDate
			AND A.ClassId =CM.Id  ) AS OpeningStrength,
		   (select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
			WHERE BM.IsActive = 1 AND SA.AdmissionDate >= @rFromDate AND SA.AdmissionDate <= @rToDate
			AND A.ClassId =CM.Id  ) AS NewJoinedStudent,
		   (select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
			WHERE BM.IsActive = 1 AND SA.LeftDate >= @rFromDate AND SA.LeftDate <= @rToDate
			AND A.ClassId =CM.Id  ) AS LeftStudent,
		   (select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId 
			INNER JOIN sStudent.tStudentMaster SM ON SA.StudentId = SM.Id
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
			WHERE BM.IsActive = 1 AND SM.StatusId = 1
			AND A.ClassId =CM.Id  ) AS ClosingStrength
 
 
	FROM 
			sSetup.tClassMaster CM			
			--INNER JOIN sSetup.tBatchClass BC ON BC.ClassId= CM.Id
			INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=CM.DepartmentId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = DM.OrgId
			INNER JOIN sSetup.tOrgSubGroupMaster OSGM ON OSGM.Id = OM.OrgSubGroupId
			INNER JOIN sSetup.tOrgMainGroupMaster OMGM ON OMGM.Id = OSGM.OrgMainGroupId
	WHERE 
			--BC.BatchId = @rBatchId
		   ((CM.Id=@rClassId) OR (@rClassId=0))
			AND	((CM.DepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))
			AND ((OMGM.Id=@rOrgMainGroupId) OR (@rOrgMainGroupId=0))
			AND ((OSGM.Id=@rOrgSubGroupId) OR (@rOrgSubGroupId=0))
			AND ((OM.Id=@rOrgId) OR (@rOrgId=0))
			AND ((OM.OrgGroupId = @rOrgGroupId))
			
			AND (OMGM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit(	@rStrOrgMainGroupId,','))OR @rStrOrgMainGroupId='')
			AND (OSGM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit(	@rStrOrgSubGroupId,','))OR @rStrOrgSubGroupId='')
			AND (OM.Id IN (SELECT cast (item as int) FROM  sCommon.fnsplit ( @rStrOrgId,','))OR @rStrOrgId='')
			AND (DM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit  (@rStrDepartmentId,','))OR @rStrDepartmentId='')
			AND (CM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit  (@rStrClassId,','))OR @rStrClassId='')
			 
			ORDER BY CM.OrderIndex ASC
END
GO
PRINT N'Altering [sPayroll].[pCalculatePayrollAmount]...';


GO
ALTER PROCEDURE [sPayroll].[pCalculatePayrollAmount] 
	      	        
            @1PaypSetupId int,
            @1PayElementId 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
      
      DECLARE @1DependentTotal decimal(22,2)
          
      BEGIN  
      
   
    DECLARE @lBasicPayElementId int
	SELECT @lBasicPayElementId = Id FROM sPayroll.tPayElement WHERE PayrollId = @rPayrollId AND PayElementDefaultId = 1
 
      
		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 @lTotalAmount,'Basic'
        --    --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 PS ON  
        DependentPayElementId = PayElementId WHERE PaySetupId = @1PaypSetupId AND PS.PayrollYearId = @rPayrollYearId
        AND SourceId = @1SourceId --AND SourceTypeId = 2020
        ORDER BY ProcessOrder DESC  
       
 
        
        SELECT @1COUNT = COUNT(*) FROM #tmpDependPayElementDetail
	    SET @1DependentTotal = 0
	      WHILE @1COUNT > 0
	        BEGIN	   
	          SET @1DependPayElementId = 0
	          SET @1Amount = 0.0
	          SET @1DependPercentage = 0
	          SET @1DependPaySetupId = 0 
	          SET @1PayElementTypeId = 0
	          
	           
	          
	           SELECT @1DependPayElementId = DependPayElementId FROM #tmpDependPayElementDetail WHERE Id = @1COUNT
	           SELECT @1DependPaySetupId = Id,@1DependPercentage = Percentage FROM sPayroll.tPaySetup PS WHERE PayElementId = @1DependPayElementId AND PS.PayrollYearId = @rPayrollYearId
	            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 EXISTS (SELECT 1 FROM sPayroll.tPaySetupDependent WHERE PaySetupId = @1DependPaySetupId)
	                BEGIN 	                   
	                   EXECUTE [sPayroll].[pCalculatePayrollAmount] @1DependPaySetupId,@1PayElementId,@1DependPercentage,@1SourceId,@1OrgGroupId,@1EmployeeId,@lNextNumber,@rPayrollId,@rPayrollYearId,@1Result OUTPUT
	                  
	                  SET @1DependentTotal = @1DependentTotal + ISNULL(@1Result,0)
	                   
	                END
	               ELSE
	               BEGIN     
	                        
	                    SET @1DependentTotal = ISNULL(@1DependentTotal,0) + ISNULL(@1Amount,0)	                  
	               END  
	          
	            SET  @1COUNT = @1COUNT - 1               
	        END	       
	        
	        SET @lTotalAmount = ROUND((@1DependentTotal * @1Percentage)/100,0)
	        
	       
	          
		    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)
    
    DECLARE @1EmployeePfAmount DECIMAL(22,2)
    DECLARE @1EmployerPfAmount 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
    DECLARE  @1EmployeePfPercentEmpSetup DECIMAL(12,2)
	
	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 AND PayrollYearId = @rPayrollYearId 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 @1Basic = ISNULL(SUM(amount),0) FROM sPayroll.tPayProcessElement PPE INNER JOIN sPayroll.tPayElement PE 
		  ON PPE.PayElementId = PE.ID  WHERE  PayProcessEmployeeId = @rPayProcessEmployeeId AND PayElementId IN 
		  (SELECT DependentPayElementId FROM sPayroll.tPaySetupDependent PD INNER JOIN sPayroll.tPaySetup PS 
		  ON  PD.PaySetupId = PS.ID
		  INNER JOIN sPayroll.tPayElement PE 
		  ON PS.PayElementId = PE.ID WHERE PS.PayrollId = @rPayrollId AND PS.PayrollYearId = @rPayrollYearId
		  AND PE.PayElementDefaultId = 56)	     
		  
	      SELECT @1PfSalaryLimit = PfSalaryLimit,@1EmployeePfPercent=EmployeePfPercent,@1EmployerPfPercent=EmployerPfPercent FROM  sPayroll.tPfSetup Where PayrollYearId = @rPayrollYearId 
	      
	      
	      SELECT @1EmployeePfPercentEmpSetup = Percentage  FROM sPayroll.tPaySetup WHERE SourceTypeId = 95 AND SourceId = (SELECT EmployeeId FROM sPayroll.tPayProcessEmployee WHERE ID = @rPayProcessEmployeeId)
				AND PayElementId = @lPFPayElementId AND PayrollYearId = @rPayrollYearId
	   
	   IF @1EmployeePfPercentEmpSetup IS NOT NULL
	   SET @1EmployeePfPercent = @1EmployeePfPercentEmpSetup
	  
	      
	      SELECT @1PayProcesdsElementId = Id  FROM  sPayroll.tPayProcessElement Where PayProcessEmployeeId = @rPayProcessEmployeeId AND PayElementId = @lPFPayElementId
	        
	    
	     SET @1EmployeePfAmount = 0.0
		 SET @1EmployerPfAmount = 0.0
	       
	       --SELECT @1Basic ,'Basic',@1PfSalaryLimit,'PF Salary'
	       
	       IF(@1Basic < @1PfSalaryLimit)
	       BEGIN
	      SET @1EmployeePfAmount =  ROUND( @1Basic*ISNULL(@1EmployeePfPercent,0)/100,0)
	      SET @1EmployerPfAmount =  ROUND(@1Basic*ISNULL(@1EmployerPfPercent,0)/100,0) --OR @1Basic*3.67/100
	       END
	       ELSE
	       BEGIN
	      SET @1EmployeePfAmount =  ROUND(@1PfSalaryLimit*ISNULL(@1EmployeePfPercent,0)/100,0)
	      SET @1EmployerPfAmount =  ROUND(@1PfSalaryLimit*ISNULL(@1EmployerPfPercent,0)/100,0) --OR @1Basic*3.67/100
	       END
	       
	       --IF(@1Basic > @1PfSalaryLimit)
	       --   BEGIN
	           --SET @1EmployeePfAmount = @1Basic*@1EmployeePfPercent/100 
	             INSERT INTO  [sPayroll].[tPfProcess]
							   (
							    [PayProcessElementId]
							   ,[EmployeePfAmount]
							   ,[EmployerPfAmount]
							   ,[EmployerFpsAmount]
							   ,[EligibleFpsAmount]
							   )
							   Values
							   (
							     @1PayProcesdsElementId,
							     @1EmployeePfAmount,
							     @1EmployerPfAmount, --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,
     @rPayrollYearId int=0
	 
	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  AND PayrollYearId = @rPayrollYearId
		
	   DELETE FROM sPayroll.tPaySetup WHERE SourceId = @rCopyGradeId AND SourceTypeId = @rSourceTypeId AND PayrollId = @rPayrollId AND PayrollYearId = @rPayrollYearId
		
		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 PayrollYearId = @rPayrollYearId  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
	               ,@rPayrollYearId
	                
	        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].[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].[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 EXISTS(Select 1 FROM sPayroll.tPayProcess Where SalaryMonth = @rSalaryMonth AND SalaryYear = @rSalaryYear AND PayrollYearId = @rPayrollYearId)
	BEGIN
			SELECT -101 as Result
			RETURN
	END			
	
  --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,@rSalaryMonth,@rSalaryYear
       
	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
		   ,@rSalaryMonth tinyint
           ,@rSalaryYear smallint
           
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

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


GO
ALTER PROCEDURE [sPayroll].[pPaySetupElementWiseEmployeeGet]
	  
	 @rSourceTypeId smallint,
	 @rSourceId bigint,
	 @rPayrollId int,
	 @rPayElementId int,
	 @rPayrollYearId int=0
 
	 
	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(PE.SortOrder,0) AS ProcessOrder,
      ISNULL(PS.PayElementId,0) AS PayElementId 

	 FROM sHrm.vEmployeeCommonDetail EM
	INNER JOIN sHrm.tEmployeeStatutoryAndOther ESO
		ON EM.EmployeeId = ESO.EmployeeId	 
	LEFT JOIN sPayroll.tPaySetup PS 
		ON PS.SourceId = EM.EmployeeId  
			AND SourceTypeId = @rSourceTypeId 
			AND PS.PayElementId = @rPayElementId
			AND PS.PayRollId = ESO.PayrollId
			AND PS.PayRollYearId = @rPayrollYearId
	LEFT JOIN sPayroll.tPayElement PE ON  PE.ID=@rPayElementId			
	WHERE  ESO.PayrollId = @rPayrollId 
	ORDER BY EM.OrgId,EM.Code
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,
	 @rPayrollYearId int=0
	 
 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.PayRollYearId = @rPayrollYearId
         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)
         Order By EM.OrgId,EM.Code
		 
END
GO
PRINT N'Altering [sPayroll].[pPaySetupGet]...';


GO
ALTER PROCEDURE [sPayroll].[pPaySetupGet]
	  
	 @rSourceTypeId smallint,
	 @rSourceId bigint,
	 @rPayrollId int,
	 @rPayrollYearId int=0
 
	 
	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
			  ,ISNULL(PE.SortOrder,0) AS DisplayOrder
			  ,ISNULL(PS.[PayrollYearId],0) AS PayrollYearId
			  
		      
		FROM  sPayroll.tPayElement PE LEFT JOIN  [sPayroll].[tPaySetup] PS ON PE.ID = PS.PayElementId AND
			  PS.SourceTypeId = @rSourceTypeId AND PS.SourceId = @rSourceId AND PS.PayrollYearId = @rPayrollYearId 
			  
	   WHERE PE.IsObsolete = 0  AND PE.PayrollId = @rPayrollId 
	    
	   Order by ProcessOrder
       
END
GO
PRINT N'Altering [sPayroll].[pRptEmployeePaybillDetail]...';


GO


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

BEGIN  

	DECLARE @lBasicPayElementId int
	SELECT @lBasicPayElementId = Id FROM sPayroll.tPayElement WHERE PayrollId = @rPayrollId AND PayElementDefaultId = 1

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

	SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		EM.EmployeeId, 
		PP.ID As PayProcessId,
		PPE.ID AS PayProcessEmployeeId,
		PP.SalaryMonth,
		PP.SalaryYear,
		EM.EmployeeName,
		EM.Code AS EmployeeCode,
		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,
		ISNULL(ESO.BankName,'') AS BankName,
		ISNULL(ESO.AccountNumber,'') AS AccountNumber,
		MM.Title AS MonthName,
		ISNULL(PPE.WorkingDays,0) AS WorkingDays,
		(ISNULL(PPE.WorkingDays,0) - ISNULL(PPE.Lwp,0)) AS PresentDays,
		--ISNULL(PPE.Lwp,0) AS AbsentDays,
		ISNULL(PPE.GrossBasic,0) AS GrossBasic,
		PY.Title AS PayrollYearName
		
	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 sCommon.tMonthMaster MM ON MM.Id=PP.SalaryMonth	
	INNER JOIN sPayroll.tPayrollYearMaster PY ON PP.PayrollYearId = PY.Id 

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 ((PY.PayrollId=@rPayrollId) OR (@rPayrollId=0))
	  AND (PPE.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)='', 
	 @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
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2, 
		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,
		P.Code AS PayElementCode,
		(CASE WHEN PayElementId = @lBasicPayElementId then PPE.WorkingDays else 0 END) AS WorkingDays,
		(CASE WHEN PayElementId = @lBasicPayElementId then PPE.Lwp else 0 END) AS Lwp,
		P.SortOrder,
		PY.Title AS PayrollYearName
	 
	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 sCommon.tMonthMaster MM ON MM.Id=PP.SalaryMonth
	INNER JOIN sPayroll.tPayrollYearMaster PY ON PP.PayrollYearId = PY.Id 

where 
      (EM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
      AND (P.IsObsolete=0)
      AND ((EM.Code Like '%' +  @rEmployeeCode + '%' ) OR (@rEmployeeCode = ''))
	  AND ((EM.EmployeeName Like '%' + @rEmployeeName  + '%') OR (@rEmployeeName = ''))
	  AND (EM.DepartmentId = @rDepartmentId OR @rDepartmentId = 0)
	  AND (PP.SalaryMonth = @rForMonth OR @rForMonth = 0)
	  AND (PP.SalaryYear = @rForYear OR @rForYear = 0)
	  AND ((PY.PayrollId=@rPayrollId) OR (@rPayrollId=0))
	  AND (PPE.PayrollGroupId = @rPayrollGroupId OR @rPayrollGroupId = 0) 
	  AND (PP.PayrollYearId = @rPayrollYearId OR @rPayrollYearId = 0) 
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,	
	 @rPayElementTypeId int=0
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

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

	SELECT 
	
	@rBuilder1 AS Builder1,
	@rBuilder2 AS Builder2,	
	PE.Amount,
	P.Id AS PayElementId, 
	P.Title AS PayElementName,
	P.Code AS PayElementCode,
	EM.EmployeeId,
	EM.EmployeeName,
	EM.Code,
	EM.EmployeeDesignation,
	PP.SalaryMonth,
	PP.SalaryYear,
	MM.Title AS MonthName,
	PY.Title AS PayrollYearName,
	P.SortOrder,
	P.PayElementTypeId,
	@rPayElementTypeId AS IsPayElementTypeIdZero,
	@rPayElementId AS IsPayElementIdZero, 
	PPE.TotalEarning,		
	PPE.TotalDeduction,
	PPE.NetAmount,
	(CASE WHEN PayElementId = @lBasicPayElementId then PPE.TotalEarning else 0 END) AS TotalEarningTotal,
	(CASE WHEN (PayElementId = @lBasicPayElementId And @rPayElementTypeId <> 2) 
	 THEN PPE.TotalDeduction WHEN PayElementId = @lProfessionalTaxPayElementId And @rPayElementTypeId = 2 
	 THEN PPE.TotalDeduction ELSE 0 END) AS TotalDeductionTotal,	 
	(CASE WHEN PayElementId = @lBasicPayElementId then PPE.NetAmount else 0 END) AS NetAmountTotal

	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
		INNER JOIN sPayroll.tPayrollYearMaster PY ON PP.PayrollYearId = PY.Id 
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 ((PY.PayrollId=@rPayrollId) OR (@rPayrollId=0))
	  AND (PPE.PayrollGroupId = @rPayrollGroupId OR @rPayrollGroupId = 0) 
	  AND (PP.PayrollYearId = @rPayrollYearId OR @rPayrollYearId = 0) 
	  AND (P.PayElementTypeId = @rPayElementTypeId OR @rPayElementTypeId = 0) 
END
GO
PRINT N'Altering [sPayroll].[pSelectPayElementAdd]...';


GO
ALTER 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)
	IF NOT EXISTS(SELECT 1 FROM [sPayroll].[tPayElement] WHERE PayElementDefaultId = @rPayElementDefaultId AND
	PayrollId = @rPayrollId)
    
    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 PayrollId = @rPayrollId AND PayElementDefaultId = @rPayElementDefaultId    		     		    
			END        
	SELECT @lNextNumber AS Result	
	COMMIT TRANSACTION
	END TRY
	BEGIN CATCH
	ROLLBACK TRANSACTION
		SELECT -1 AS RESULT
	END CATCH	
END
GO
PRINT N'Altering [sPayroll].[pSelectPayElementGet]...';


GO
ALTER 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(PED.IsLwp,0) AS IsLwp,
			ISNULL(PED.IsEmployeeSpecific,0) AS IsEmployeeSpecific,
			ISNULL(PED.IsDepend,0) AS IsDepend,
			ISNULL(PED.IsAvailDuringProbation,0) AS IsAvailDuringProbation,
			ISNULL(PED.IsIncludeInPaySlip,0) AS IsIncludeInPaySlip,
			PED.SortOrder,
			--CASE ISNULL(PED.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 AND PE.IsObsolete = 0
			WHERE PED.IsObsolete = 0
			
			ORDER BY PED.SortOrder
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 [sScholarship].[pRptScholarshipEligibleStudentGet]...';


GO

ALTER PROCEDURE [sScholarship].[pRptScholarshipEligibleStudentGet]
          
           @rScholarshipId int,
           @rAcademicId bigint
AS
SET NOCOUNT ON
BEGIN
SELECT 
		STM.Title AS ScholarshipTypeName,
        SM.Title AS ScholarshipName,
        vSA.Code,
        vSA.Name AS StudentName,
        vSA.ClassName+' - '+vSA.DivisionName AS ClassDivisionName,
        ISNULL(SES.AcademicId,0) AS AcademicId,
        ISNULL(SES.ScholarshipId,0) AS ScholarshipId,
        ISNULL(SES.EligibleAmount,0) AS EligibleAmount
		
  FROM  sScholarship.tScholarshipEligibleStudent SES
	INNER JOIN  sScholarship.tScholarshipMaster SM ON SM.Id=SES.ScholarshipId
	INNER JOIN  sScholarship.tScholarshipTypeMaster STM ON STM.Id=SM.ScholarshipTypeId
    LEFT JOIN sStudent.vStudentAcademic vSA ON SES.AcademicId=vSA.AcademicId
  WHERE 
		(SES.ScholarshipId=@rScholarshipId OR @rScholarshipId=0)
		AND (SES.AcademicId=@rAcademicId OR @rAcademicId=0)
		order by ClassDivisionName
END
GO
PRINT N'Altering [sScholarship].[pScholarshipAdd]...';


GO


ALTER PROCEDURE [sScholarship].[pScholarshipAdd]
	
	@rOrgId int,
	@rBatchId int,
	@rScholarshipTypeId int,
	@rId int,
	@rTitle nvarchar(100),
	@rCreatedUserId bigint,
	@rIsObsolete bit,
	@rRemark nvarchar(200)=''
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	-- For New Entry
	IF(@rId = 0)	
		BEGIN
			If Exists(select Id from sScholarship.tScholarshipMaster where Title=@rTitle AND  BatchId=@rBatchId AND ScholarshipTypeId=@rScholarshipTypeId)
				BEGIN
				select -103 as Result
				RETURN
			END 
	 
		END
	-- For Update Entry
	ELSE	
		BEGIN
			If  Exists(select Id from sScholarship.tScholarshipMaster where Id<>@rId AND Title =@rTitle AND BatchId=@rBatchId AND ScholarshipTypeId=@rScholarshipTypeId)
			Begin
				select -103 as Result
				RETURN
			End
		END
BEGIN TRY
BEGIN TRANSACTION	
 IF(@rId = 0)	
 BEGIN
	DECLARE @lNextNumber INT     
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sScholarship.tScholarshipMaster', 0, 1, 1,@outNextNumber = @lNextNumber output

	INSERT INTO  sScholarship.tScholarshipMaster
		(
			BatchId,
			ScholarshipTypeId,
			Id,
			Title,
			CreatedUserId,
			CreatedDateTime,
			IsObsolete,
			Remark
		)
	VALUES
		(
			@rBatchId,
			@rScholarshipTypeId,
			@lNextNumber,
			@rTitle,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rIsObsolete,
			@rRemark
		)
		             
	END	 
ELSE
    BEGIN
	 SET @lNextNumber = @rId
	    UPDATE sScholarship.tScholarshipMaster
	    SET
			 ScholarshipTypeId=@rScholarshipTypeId,
			 Title=@rTitle,
			 IsObsolete=@rIsObsolete,
			 UpdatedUserId=@rCreatedUserId,
			 UpdatedDateTime=sCommon.fGetDate(),
			 Remark=@rRemark
			 
	      WHERE Id = @rId 	   
	 END  
		SELECT @lNextNumber AS Result
	
	COMMIT TRANSACTION
		
END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sScholarship].[pScholarshipEligibleStudentAdd]...';


GO
ALTER PROCEDURE [sScholarship].[pScholarshipEligibleStudentAdd]
	 
	@rScholarshipId int,
	@rAcademicId bigint,
	@rEligibleAmount decimal(10,2),
	@rIsDeleted bit
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	 BEGIN TRANSACTION	
-- For Delete sScholarship.tScholarshipStudentPaid
 If(@rIsDeleted=1) 
		BEGIN
			If Exists(select 1 from sScholarship.tScholarshipStudentPaid SSP INNER JOIN sScholarship.tScholarshipReceive SR ON SR.Id = SSP.ScholarshipReceiveId 
					AND SR.ScholarshipId=@rScholarshipId AND SSP.AcademicId=@rAcademicId AND SSP.PaidAmount > 0)
					BEGIN
						select -101 as Result
						RETURN
					END 
			 ELSE
					BEGIN
						Delete from sScholarship.tScholarshipEligibleStudent where ScholarshipId=@rScholarshipId AND AcademicId=@rAcademicId
						Select @rAcademicId as Result
					END
		END	
ELSE
BEGIN
	If Exists(select AcademicId from sScholarship.tScholarshipEligibleStudent where AcademicId=@rAcademicId AND ScholarshipId=@rScholarshipId)
		BEGIN
			select -103 as Result
			RETURN
		END 
	   
	INSERT INTO sScholarship.tScholarshipEligibleStudent
		(
			ScholarshipId,
			AcademicId,
			EligibleAmount
		)
	VALUES
		(
			@rScholarshipId,
			@rAcademicId,
			@rEligibleAmount
		)
		             
END	 
		SELECT @rAcademicId AS Result
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sScholarship].[pScholarshipEligibleStudentGet]...';


GO

ALTER PROCEDURE [sScholarship].[pScholarshipEligibleStudentGet]
          
           @rScholarshipId int,
           @rAcademicId bigint
AS
SET NOCOUNT ON
BEGIN
SELECT  
        SM.Title AS Scholarship,
        vSA.Code,
        vSA.Name AS StudentName,
        vSA.ClassName+' - '+vSA.DivisionName AS ClassDivisionName,
        ISNULL(SES.AcademicId,0) AS AcademicId,
        ISNULL(SES.ScholarshipId,0) AS ScholarshipId,
        ISNULL(SES.EligibleAmount,0.00) AS EligibleAmount
		
  FROM  sScholarship.tScholarshipEligibleStudent SES
	INNER JOIN  sScholarship.tScholarshipMaster SM ON SM.Id=SES.ScholarshipId
    LEFT JOIN sStudent.vStudentAcademic vSA ON SES.AcademicId=vSA.AcademicId
  WHERE 
		(SES.ScholarshipId=@rScholarshipId OR @rScholarshipId=0)
		order by ClassDivisionName
END
GO
PRINT N'Altering [sScholarship].[pScholarshipGet]...';


GO



ALTER PROCEDURE [sScholarship].[pScholarshipGet]
	 @rBatchId int,
	 @rScholarshipTypeId int,
	 @rId int = 0,
	 @rTitle nvarchar(100)
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	SET @rTitle = sCommon.fSearchStringGet(@rTitle)
END	 
BEGIN 

	SELECT 
	SM.BatchId,
	SM.ScholarshipTypeId,
	SM.Id,
	SM.Title,
	SM.IsObsolete,
	ISNULL(SM.Remark,'') AS Remark,
	STM.Title AS ScholarshipType
		
  FROM sScholarship.tScholarshipMaster SM  
  INNER JOIN  sScholarship.tScholarshipTypeMaster STM ON STM.Id=SM.ScholarshipTypeId
             
  WHERE 		
      ((SM.Id = @rId) OR (@rId = 0))
      AND  ((SM.ScholarshipTypeId = @rScholarshipTypeId) OR (ISNULL(@rScholarshipTypeId,0) = 0))    
      AND  ((SM.Title like @rTitle) OR (ISNULL(@rTitle,'') = '')) 
      AND SM.BatchId = @rBatchId
     
END
GO
PRINT N'Altering [sSecurity].[pLoggedInUserGet]...';


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

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

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


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

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

   --SELECT DISTINCT Menu.Id AS MenuID, 
	--		ISNULL(Menu.ParentMenuID, 0) AS ParentMenuID, 
	--		Menu.Title AS MenuTitle, 
	--		Menu.TitleResourceKeyId AS MenuResourceKey, 
	--		Screen.Title AS ScreenTitle,
	--		Screen.TitleResourceKeyId AS ScreenResourceKey,
	--		Screen.Page AS PageURL
	--FROM sSecurity.tMenu Menu
	--LEFT OUTER JOIN sSecurity.tScreen Screen
	--	ON Menu.ScreenId = Screen.Id
	--LEFT OUTER JOIN sSecurity.tPermission Permission
	--	ON Screen.TaskId = Permission.TaskId
	--WHERE	Menu.IsObsolete = 0 AND
	--		Screen.IsObsolete = 0 AND
	--		Permission.RoleId IN (SELECT RoleId FROM sSecurity.tUserRole WHERE UserId = @rUserId) AND
	--		(Permission.Permission & 2) = 2
	--ORDER BY ParentMenuID
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

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

BEGIN TRANSACTION	

	IF @rUserType = 'AdminPortal'
	BEGIN
		DELETE FROM sSecurity.tPermission WHERE OrgGroupId=@rOrgGroupId AND RoleId=sCommon.fGetIntIdForOrg(2,@rOrgGroupId)
	END
	--ELSE IF @rUserType = 'ParentPortal'
	--BEGIN
		
	--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
 
 
 
 DELETE FROM sSecurity.tRoleDashlet WHERE RoleId = sCommon.fGetIntIdForOrg(10,@rOrgGroupId)
INSERT INTO sSecurity.tRoleDashlet (DashletId,RoleId)
SELECT  
			Id,
			sCommon.fGetIntIdForOrg(10,@rOrgGroupId)
			 
	FROM 
		sSecurity.tDashletMaster
		WHERE IsObsolete = 0
	 
 
		----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(
142     ,--Login
245     , -- Change Password
9128	, -- Video Viewer
9137	, -- Link Viewer
20054	, -- Calendar
20085	, -- Circular List
20088	, -- Query List
20089	, -- New Query
20091	, -- Circular View
20093	, -- Assignment List
20095	, -- Assignment View
20097	, -- View Query
20099	, -- Blog List
20101	, -- Blog View
20104	, -- News List
20106	, -- News View
20109	, -- Discussion List
20110	, -- Discussion
20111	, -- Discussion View
20112	, -- Discussion Group
20114	, -- Group Members
20117	, -- Poll View
20118	, -- Poll Vote
20172	, -- View Task
20181	,-- Result
20246	,-- My Profile
20577   ,-- Birthday
20222   -- My Staff
				)


DELETE FROM sSecurity.tRoleDashlet WHERE RoleId = sCommon.fGetIntIdForOrg(10,@rOrgGroupId)
INSERT INTO sSecurity.tRoleDashlet (DashletId,RoleId)
SELECT  
			Id,
			sCommon.fGetIntIdForOrg(10,@rOrgGroupId)
			 
	FROM 
		sSecurity.tDashletMaster
	WHERE ID IN( 
	1,
	2,
	3,
	4,
	5,
	6,
	7,
	8,
	10,
	11,
	12,
	13,
	14,
	15,	 
	17,
	18
	
	)	
	AND IsObsolete = 0
	
		-- 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
	
	DELETE FROM sSecurity.tPermission WHERE OrgGroupId=@rOrgGroupId AND RoleId=sCommon.fGetIntIdForOrg(22,@rOrgGroupId)
	
    --	SELECT TaskId FROM sSecurity.tScreen WHERE ScreenGroupId = 114 
	--	SELECT TaskId FROM sSecurity.tScreen WHERE ScreenGroupId = 172 
		INSERT INTO sSecurity.tPermission
		(
			TaskId, 
			RoleId, 
			Permission, 
			IsObsolete, 
			CreatedUserId, 
			CreatedDateTime, 
			UpdatedUserId, 
			UpdatedDateTime,
			OrgGroupId
		)
	SELECT  
			Id,
			sCommon.fGetIntIdForOrg(22,@rOrgGroupId),
			AvailablePermission,
			0,
			1,
			sCommon.fGetDate(),
			1,
			sCommon.fGetDate(),
			@rOrgGroupId
	FROM 
		sSecurity.tTask
	WHERE ID IN(
142     ,--Login
245     , -- Change Password
9128	, -- Video Viewer
9137	, -- Link Viewer
10187	, -- My Profile
20054	, -- Calendar
20085	, -- Circular List
20088	, -- Query List
20089	, -- New Query
20091	, -- Circular View
20093	, -- Assignment List
20095	, -- Assignment View
20097	, -- View Query
20099	, -- Blog List
20101	, -- Blog View
20104	, -- News List
20106	, -- News View
20109	, -- Discussion List
20110	, -- Discussion
20111	, -- Discussion View
20112	, -- Discussion Group
20114	, -- Group Members
20117	, -- Poll View
20118	, -- Poll Vote
20130	, -- Behaviour List
--20172	, -- View Task
20180	, -- Student View Result
20182	, -- View Book List
20183	, -- View Category
--20190	, -- View Placement
20191	, -- My eTest
20198	, -- My Event List
20204	, -- My Poll
20209	, -- My Activity List
20241	, -- My Attendance
20563	, -- My Classwork
20564	, -- My Result
20565	, -- My Fee
20566	, -- My Book List
20577   ,-- Birthday
20222   ,-- My Staff
20191   ,-- My eTest
20617   --My Class

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

INSERT  INTO sSecurity.tRoleDashlet (DashletId,RoleId)
SELECT  
			Id,
			sCommon.fGetIntIdForOrg(22,@rOrgGroupId)
			 
	FROM 
		sSecurity.tDashletMaster
	WHERE ID IN( 
	1,
	2,
	3,
	7,
	12,
	13,
	14,
	15,	 
	17,
	18
	
	)
	AND IsObsolete = 0
	
		-- 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].[pUserByLoginUserNameGet]...';


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

SET @rDisplayTitle = sCommon.fSearchStringGet(@rDisplayTitle)
SET @rLoginTitle = sCommon.fSearchStringGet(@rLoginTitle) 
SET @rSourceCode= sCommon.fSearchStringGet(@rSourceCode)
SET @rSourceName= sCommon.fSearchStringGet(@rSourcename)

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


GO
ALTER PROCEDURE [sSetup].[pBatchMasterAdd]
	 
	@rId int,
	@rCode nvarchar(20),
	@rTitle nvarchar(100),
	@rOrgId int,
	@rIsHistory bit,
	@rIsObsolete bit,
	@rOrderIndex smallint,
	@rFromDate date,
	@rToDate date,
	@rCreatedUserId bigint,
	@rUpdatedUserId bigint,
	@rOrgGroupBatchId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	IF(@rId = 0)	
	BEGIN
	DECLARE @lBatchCount int,@lBatchCountActive int
	DECLARE @lTermPattern int
	DECLARE @lIsInContext bit,@lIsActive bit
	
	SELECT @lBatchCountActive = ISNULL(COUNT(ID),0) FROM sSetup.tBatchMaster WHERE OrgId = @rOrgId
	SELECT @lBatchCount = ISNULL(COUNT(ID),0) FROM sSetup.tBatchMaster WHERE OrgGroupBatchId = @rOrgGroupBatchId AND OrgId = @rOrgId
	SELECT @lTermPattern = TermPatternId FROM sSetup.tOrganizationMaster WHERE  Id = @rOrgId
	
	IF (@lBatchCount >= @lTermPattern)
	BEGIN
	SELECT -101 AS Result
	RETURN
	END

	IF (@lBatchCountActive = 0)
	SET @lIsActive = 1
	ELSE
	SET @lIsActive = 0
	
	IF (@lTermPattern = 1)
		SET @lIsInContext = 1
	ELSE IF (@lTermPattern = 2 AND  @lBatchCount = 0)
		SET @lIsInContext = 1
	END
	

	
	--BEGIN
	--		IF EXISTS(SELECT 1 FROM sSetup.tBatchMaster WHERE OrgId=@rOrgId AND OrgGroupBatchId=@rOrgGroupBatchId)
	--		BEGIN
	--			SELECT -100 AS Result
	--			RETURN
	--		END
	--END
	
	 BEGIN TRANSACTION	
 IF(@rId = 0)	
BEGIN

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

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


GO
ALTER PROCEDURE [sSetup].[pBatchMasterGet]
	 @rId int = 0,
	 @rCode nvarchar(20),
	 @rTitle nvarchar(100),
	 @rOrgId int,
	 @rIsSearch bit=0,
	 @rOrgGroupBatchId int=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 IF(@rIsSearch=1)
		BEGIN
			SET @rCode = sCommon.fSearchStringGet(@rCode)
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		END
	
	SELECT 
	
			BM.Id,
			BM.Code,
			BM.Title,
			BM.OrgId,
			BM.IsHistory,
			BM.IsObsolete,
			ISNULL(BM.IsActive,0) AS IsActive,
			BM.OrderIndex,
			BM.FromDate,
			BM.ToDate,
			BM.CreatedUserId,
			BM.CreatedDateTime,
			BM.UpdatedUserId,
			BM.UpdatedDateTime,
			ISNULL(BM.OrgGroupBatchId,0) AS OrgGroupBatchId,
			ISNULL(BM.IsInContext,0) AS IsInContext,
			OGBM.Title AS OrgGroupBatchTitle,
			OM.DisplayTitle AS OrganizationName,
			OGBM.Id AS OrgGroupBatchId,
			OGBM.OrgGroupId
			
			
  FROM 
            sSetup.tBatchMaster BM
            INNER JOIN sSetup.tOrgGroupBatchMaster OGBM
				ON OGBM.Id = BM.OrgGroupBatchId
			INNER JOIN sSetup.tOrganizationMaster OM
				ON OM.Id = BM.OrgId
  WHERE 
  
    ((BM.Id = @rId) OR (@rId = 0))
    AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  
	AND ((BM.Code like @rCode) OR (ISNULL(@rCode,'') = '')) 
	AND ((BM.Title like @rTitle) OR (ISNULL(@rTitle,'') = '')) 
	AND ((BM.OrgId = @rOrgId) OR (@rOrgId = 0))  
	--AND(BM.OrgId=@rOrgId)

ORDER BY OM.Id, BM.OrderIndex ASC
END
GO
PRINT N'Altering [sSetup].[pOrganizationMasterAdd]...';


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


GO
ALTER PROCEDURE [sSetup].[pOrganizationMasterGet]
	 
	 @rId int = 0,
	 @rCode nvarchar(20),
	 @rTitle nvarchar(100),
	 @rOrgGroupId smallint,
	 @rIsSearch bit
	 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 IF(@rIsSearch=1)
		BEGIN
			SET @rCode = sCommon.fSearchStringGet(@rCode)
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		END
	
	SELECT 
	
			OM.Id,
			OM.Code,
			OM.Title,
			OM.DisplayTitle,
			OM.AffiliationId,
			AM.Title AS AffiliationTitle,
			OM.LanguageId,
			LM.Title AS LanguageTitle,
			--OM.InstituteTypeId,
			--ITM.Title AS InstituteTypeTitle,
			--OM.InstituteSubTypeId,
			--ISTM.Title AS InstituteSubTypeTitle,
			OM.StreetOne,
			OM.StreetTwo,			 
			OM.StreetThree,
			OM.CityName,
			OM.StateName,
			OM.CountryName,
			OM.ZipCode,
			OM.HomePage,
			OM.PhoneNo,
			OM.FaxNo,
			OM.ReportOrgTitle,
			OM.SmallAddress1,
			OM.SmallAddress2,
			OM.RegistrationDetail,			 
			OM.CreatedUserId,
			OM.CreatedDateTime,
			OM.UpdatedUserId,
			OM.UpdatedDateTime,
			OM.IsObsolete,
			OM.OrgGroupId,
			OM.OrgLogo,
			OM.WeekOffs,
			--OM.IcardOrgTitle,
			--OM.IcardAddress1,
			--OM.ICardAddress2,
			--OM.ICardAddress3,
			--OM.LabelColor,
			--OM.DetailColor,
			--OM.HeaderColor,
			ISNULL(OM.OrgSubGroupId,0) AS OrgSubGroupId, 
			--OB.Code AS BatchName,
			--OB.FromDate,
			--OB.ToDate,
			ISNULL(OM.EmployeeId,0) AS EmployeeId,
		    ISNULL(EM.Code,'') AS EmployeeCode,
		    ISNULL(EM.FirstName,'')+ ' ' + ISNULL(EM.MiddleName,'')+ ' ' + ISNULL(EM.LastName,'') AS EmployeeName,
			ISNULL(OM.OrderIndex,0) AS OrderIndex,
			ISNULL(OM.TermPatternId,0) AS TermPatternId
			
      
  FROM 
            sSetup.tOrganizationMaster OM
           INNER JOIN sSetup.tAffiliationMaster AM
				ON AM.Id=OM.AffiliationId
		  -- INNER JOIN sSetup.tInstituteTypeMaster ITM
				--ON ITM.Id=OM.InstituteTypeId
		  -- INNER JOIN sSetup.tInstituteSubTypeMaster ISTM
				--ON ISTM.Id=OM.InstituteSubTypeId
		   INNER JOIN sSetup.tLanguageMaster LM
				ON LM.Id=OM.LanguageId
		  -- INNER JOIN sSetup.tOrgGroupBatchMaster OB 
				--ON OB.OrgGroupId=OM.OrgGroupId 
		   LEFT JOIN sHrm.tEmployeeMaster EM 
				ON EM.Id = OM.EmployeeId AND EM.IsObsolete = 0
  WHERE 
  
        ((OM.Id = @rId) OR (@rId = 0))
	AND ((OM.Code like @rCode) OR (ISNULL(@rCode,'') = '')) 
	AND ((OM.Title like @rTitle) OR (ISNULL(@rTitle,'') = '')) 
	AND ((OM.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId = 0))
	AND (OM.Id != 1)
 ORDER BY OM.OrderIndex
END
GO
PRINT N'Altering [sSetup].[pOrgLogoAdd]...';


GO
ALTER PROCEDURE [sSetup].[pOrgLogoAdd]
	 
	@rId bigint,
	@rOrgLogo varbinary(max),
	@rLoginBG varbinary(max),
	@rPrincipalSignature varbinary(max),
	@rIcardBg varbinary(max),
	@rIcardBackBg varbinary(max),
	@rDeleteOption nvarchar(20) = ''
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	SET @rDeleteOption = ISNULL(@rDeleteOption,'')
	BEGIN TRANSACTION
	
	IF (@rDeleteOption = '')
	BEGIN
	UPDATE  sSetup.tOrganizationMaster
	SET
		OrgLogo=@rOrgLogo,
		PrincipalSignature = @rPrincipalSignature
		--,
		--ICardBackground = @rIcardBg,
		--ICardBackBackground = @rIcardBackBg
		
	WHERE Id = @rId 
	END
	ELSE IF (@rDeleteOption = 'OrgLogo') 
	BEGIN
		UPDATE  sSetup.tOrganizationMaster
	SET
		OrgLogo=NULL 
	WHERE Id = @rId 
	END
	
	ELSE IF (@rDeleteOption = 'LoginBG') 
	BEGIN
		UPDATE  sSetup.tOrganizationMaster
	SET
		LoginBG=NULL 
	WHERE Id = @rId 
	END
	
	
	
    ELSE IF (@rDeleteOption = 'PrincipalSignature') 
    BEGIN
		UPDATE  sSetup.tOrganizationMaster
	SET
		PrincipalSignature = NULL
	WHERE Id = @rId 
	END
	--ELSE IF (@rDeleteOption = 'IcardBg') 
 --   BEGIN
	--	UPDATE  sSetup.tOrganizationMaster
	--SET
	--	ICardBackground = NULL
	--WHERE Id = @rId 
	--END
	--ELSE IF (@rDeleteOption = 'IcardBackBg') 
 --   BEGIN
	--	UPDATE  sSetup.tOrganizationMaster
	--SET
	--	ICardBackBackground = NULL
	--WHERE Id = @rId 
	--END
	
		SELECT 1 AS Result
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		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),
			@lBirthDateInWord 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),
		BirthDateInWord 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,
		BirthDateInWord,
		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,
		BirthDateInWord,
		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',		
		BirthDateInWord nvarchar(150) '@BirthDateInWord',
		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 @lBirthDateInWord = ''
		--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,
		@lBirthDateInWord = BirthDateInWord
											 	 
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,502,@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,@lBirthDateInWord,
			@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].[pRollNoGenerationAdd]...';


GO
ALTER PROCEDURE [sStudent].[pRollNoGenerationAdd]
	 
	@rId bigint,
	--@rStudentId bigint,
	--@rClassId int,
	--@rDivisionId int,
	@rRollNo int,
	--@rOrgId int,
	--@rBatchId int,
	@rCreatedUserId bigint
	--@rUpdatedUserId bigint
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
-- IF(@rId = 0)	
--BEGIN

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


--	INSERT INTO sStudent.tAcademic
--		(
--			Id,
--			StudentId,
--			ClassId,
--			DivisionId,
--			RollNo,
--			OrgId,
--			BatchId,
--			CreatedUserId,
--			CreatedDateTime
--		)
--	VALUES
--		(
--			@lNextNumber,
--			@rStudentId,
--			@rClassID,
--			@rDivisionId,
--			@rRollNo,
--			@rOrgId,
--			@rBatchId,
--			@rCreatedUserId,
--			sCommon.fGetDate()
--		)
		             
--	END	 
--	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	 SET @rRollNo = ISNULL(@rRollNo,0)
	    UPDATE  sStudent.tAcademic
	    SET
			--StudentId=@rStudentId,
			--ClassId=@rClassId,
			--DivisionId=@rDivisionId,
			RollNo=@rRollNo,
			--BatchId=@rBatchId,
			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 [sStudent].[pRptStudentIcardGet]...';


GO



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

BEGIN 

DECLARE @lIcardBorder nvarchar(10)

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


GO


ALTER PROCEDURE [sStudent].[pRptStudentStrengthDaywiseGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rOrgId smallint,
	 @rBatchId int,
	 @rClassId int,
	 @rDivisionId int,
	 @rReportId int=0,
	 @rDepartmentId int,
	
	-- @rStatus bit,
	 --@rOrgGroupBatchId int,
	-- @rStatusClass bit,
	 @rMonth nvarchar(10)='',
	 @rYear nvarchar(10)=''
  
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 


DECLARE @lMonthDays int

SELECT @lMonthDays = sCommon.fGetDaysInMonth(@rMonth,@rYear)
	SELECT 
			@lMonthDays AS MonthDays,
			Dept.Id AS DepartmentId,
			@rBuilder1 AS Builder1,
			
			
			(
			select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '01' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1 AND SR.AttendanceTypeId =1
			)
			 AS PB1,
			
			(
			select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '01' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1	AND SR.AttendanceTypeId=1
			)
			 AS PG1,
			(
			select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate= (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '01' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			)AS ABB1,
			(
			select count(A.Id) FROM  sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '01' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABG1,
			(
			select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '01' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS LB1,
			(
			select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '01' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id
			) AS LG1,
			(
			select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '01' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS NAB1,
			(
			select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '01' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id 
			) AS NAG1,
			
			(
			select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '02' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1 AND SR.AttendanceTypeId=1
			) AS PB2,
			(
			select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '02' )) AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1 AND SR.AttendanceTypeId=1
			) AS PG2,
			(
			select count(A.Id) FROM  sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '02' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0 AND SR.AttendanceTypeId=1
			) AS ABB2,
			(
			select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '02' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0 AND SR.AttendanceTypeId=1
			) AS ABG2,
			(
			select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '02' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS LB2,
			(
			select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '02' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id
			) AS LG2,
			(
			select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '02' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS NAB2,
			(
			select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '02' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id
			) AS NAG2,
			
			(
			select count(A.Id) FROM  sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '03' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND  SR.IsPresent=1 AND  SR.AttendanceTypeId=1
			) AS PB3,
			(
			select count(A.Id) FROM  sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '03' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1 AND SR.AttendanceTypeId=1
			) AS PG3,
			(
			select count(A.Id) FROM  sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '03' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0 AND SR.AttendanceTypeId=1
			) AS ABB3,
			(
			select count(A.Id) FROM  sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '03' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0 AND SR.AttendanceTypeId=1
			) AS ABG3,
			(
			select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '03' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS LB3,
			(
			select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '03' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id
			) AS LG3,
			(
			select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '03' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS NAB3,
			(
			select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate =(convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '03' )) AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id
			) AS NAG3,
			
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '04' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1 AND SR.AttendanceTypeId =1
			) AS PB4,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '04' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1	AND SR.AttendanceTypeId=1
			) AS PG4,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate= (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '04' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABB4,
			(select count(A.Id) FROM  sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '04' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABG4,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '04' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS LB4,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '04' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id
			) AS LG4,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '04' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS NAB4,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '04' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id
			) AS NAG4,
			
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '05' )) AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1 AND SR.AttendanceTypeId =1
			) AS PB5,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '05' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1	AND SR.AttendanceTypeId=1
			) AS PG5,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate= (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '05' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABB5,
			(select count(A.Id) FROM  sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '05' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABG5,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '05' )) AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS LB5,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '05' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id
			) AS LG5,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '05' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS NAB5,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '05' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id 
			) AS NAG5,
			
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '06' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1 AND SR.AttendanceTypeId =1
			) AS PB6,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '06' )) AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1	AND SR.AttendanceTypeId=1
			) AS PG6,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate= (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '06' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABB6,
			(select count(A.Id) FROM  sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '06' )) AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABG6,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '06' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS LB6,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '06' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id
			) AS LG6,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '06' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS NAB6,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '06' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id 
			) AS NAG6,
			
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '07' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1 AND SR.AttendanceTypeId =1
			) AS PB7,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '07' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1	AND SR.AttendanceTypeId=1
			) AS PG7,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate= (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '07' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABB7,
			(select count(A.Id) FROM  sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '07' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABG7,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '07' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS LB7,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '07' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id
			) AS LG7,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '07' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS NAB7,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '07' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id 
			) AS NAG7,
			
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '08' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1 AND SR.AttendanceTypeId =1
			) AS PB8,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '08' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1	AND SR.AttendanceTypeId=1
			) AS PG8,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate= (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '08' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABB8,
			(select count(A.Id) FROM  sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '08' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABG8,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '08' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS LB8,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '08' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id
			) AS LG8,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '08' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS NAB8,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '08' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id 
			) AS NAG8,
			
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '09' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1 AND SR.AttendanceTypeId =1
			) AS PB9,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '09' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1	AND SR.AttendanceTypeId=1
			) AS PG9,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate= (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '09' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1) AS ABB9,
			(select count(A.Id) FROM  sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '09' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABG9,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '09' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS LB9,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '09' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id) AS LG9,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '09' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS NAB9,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '09' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id 
			) AS NAG9,
			
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '10' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1 AND SR.AttendanceTypeId =1
			) AS PB10,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '10' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1	AND SR.AttendanceTypeId=1
			) AS PG10,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate= (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '10' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABB10,
			(select count(A.Id) FROM  sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '10' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABG10,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '10' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS LB10,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '10' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id
			) AS LG10,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '10' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS NAB10,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '10' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id 
			) AS NAG10,
			
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '11' )) AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1 AND SR.AttendanceTypeId =1
			) AS PB11,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '11' )) AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1	AND SR.AttendanceTypeId=1
			) AS PG11,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate= (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '11' )) AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABB11,
			(select count(A.Id) FROM  sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '11' )) AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABG11,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '11' )) AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS LB11,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '11' )) AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id
			) AS LG11,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '11' )) AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS NAB11,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '11' )) AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id 
			) AS NAG11,
			
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '12' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1 AND SR.AttendanceTypeId =1
			) AS PB12,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '12' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1	AND SR.AttendanceTypeId=1
			) AS PG12,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate= (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '12' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABB12,
			(select count(A.Id) FROM  sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '12' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABG12,
			(	select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '12' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS LB12,
			(	select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '12' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id
			) AS LG12,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '12' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS NAB12,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '12' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id 
			) AS NAG12,
			
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '13' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1 AND SR.AttendanceTypeId =1
			) AS PB13,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '13' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1	AND SR.AttendanceTypeId=1
			) AS PG13,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate= (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '13' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABB13,
			(select count(A.Id) FROM  sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '13' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABG13,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '13' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS LB13,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '13' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id
			) AS LG13,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '13' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS NAB13,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '13' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id 
			) AS NAG13,
			
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '14' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1 AND SR.AttendanceTypeId =1
			) AS PB14,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '14' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1	AND SR.AttendanceTypeId=1
			) AS PG14,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate= (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '14' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABB14,
			(select count(A.Id) FROM  sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '14' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABG14,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '14' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS LB14,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '14' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id
			) AS LG14,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '14' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS NAB14,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '14' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id 
			) AS NAG14,
			
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '15' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1 AND SR.AttendanceTypeId =1
			) AS PB15,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '15' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1	AND SR.AttendanceTypeId=1
			) AS PG15,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate= (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '15' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABB15,
			(select count(A.Id) FROM  sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '15' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABG15,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '15' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS LB15,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '15' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id) AS LG15,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '15' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS NAB15,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '15' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id
			) AS NAG15,
			
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '16' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1 AND SR.AttendanceTypeId =1
			) AS PB16,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '16' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1	AND SR.AttendanceTypeId=1
			) AS PG16,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate= (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '16' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABB16,
			(select count(A.Id) FROM  sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '16' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABG16,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '16' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS LB16,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '16' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id
			) AS LG16,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '16' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS NAB16,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '16' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id 
			) AS NAG16,
			
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '17' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1 AND SR.AttendanceTypeId =1
			) AS PB17,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '17' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1	AND SR.AttendanceTypeId=1
			) AS PG17,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate= (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '17' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABB17,
			(select count(A.Id) FROM  sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '17' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABG17,
			(	select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '17' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS LB17,
			(	select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '17' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id) AS LG17,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '17' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS NAB17,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '17' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id 
			) AS NAG17,
			
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '18' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1 AND SR.AttendanceTypeId =1
			) AS PB18,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '18' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1	AND SR.AttendanceTypeId=1
			) AS PG18,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate= (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '18' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABB18,
			(select count(A.Id) FROM  sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '18' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABG18,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '18' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS LB18,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '18' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id
			) AS LG18,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '18' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS NAB18,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '18' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id 
			) AS NAG18,
			
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '19' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1 AND SR.AttendanceTypeId =1
			) AS PB19,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '19' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1	AND SR.AttendanceTypeId=1
			) AS PG19,
			(	select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate= (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '19' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABB19,
			(select count(A.Id) FROM  sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '19' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABG19,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '19' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS LB19,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '19' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id) AS LG19,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '19' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS NAB19,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '19' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id 
			) AS NAG19,
			
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '20' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1 AND SR.AttendanceTypeId =1
			) AS PB20,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '20' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1	AND SR.AttendanceTypeId=1
			) AS PG20,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate= (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '20' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABB20,
			(select count(A.Id) FROM  sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '20' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABG20,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '20' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS LB20,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '20' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id
			) AS LG20,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '20' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS NAB20,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '20' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id 
			) AS NAG20,
			
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '21' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1 AND SR.AttendanceTypeId =1
			) AS PB21,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '21' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1	AND SR.AttendanceTypeId=1
			) AS PG21,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate= (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '21' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABB21,
			(select count(A.Id) FROM  sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '21' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABG21,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '21' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS LB21,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '21' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id
			) AS LG21,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '21' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS NAB21,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '21' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id 
			) AS NAG21,
			
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '22' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1 AND SR.AttendanceTypeId =1
			) AS PB22,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '22' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1	AND SR.AttendanceTypeId=1
			) AS PG22,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate= (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '22' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABB22,
			(select count(A.Id) FROM  sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '22' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABG22,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '22' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS LB22,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '22' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id
			) AS LG22,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '22' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS NAB22,
			(	select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '22' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id 
			) AS NAG22,
			
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '23' )) AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1 AND SR.AttendanceTypeId =1
			) AS PB23,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '23' )) AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1	AND SR.AttendanceTypeId=1
			) AS PG23,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate= (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '23' )) AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABB23,
			(select count(A.Id) FROM  sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '23' )) AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABG23,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '23' )) AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS LB23,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '23' )) AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id
			) AS LG23,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '23' )) AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS NAB23,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '23' )) AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id 
			) AS NAG23,
			
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '24' )) AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1 AND SR.AttendanceTypeId =1
			) AS PB24,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '24' )) AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1	AND SR.AttendanceTypeId=1
			) AS PG24,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate= (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '24' )) AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABB24,
			(select count(A.Id) FROM  sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '24' )) AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABG24,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '24' )) AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS LB24,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '24' )) AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id
			) AS LG24,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '24' )) AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS NAB24,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '24' )) AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id 
			) AS NAG24,
			
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '25' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1 AND SR.AttendanceTypeId =1
			) AS PB25,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '25' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1	AND SR.AttendanceTypeId=1
			) AS PG25,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate= (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '25' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABB25,
			(select count(A.Id) FROM  sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '25' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABG25,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '25' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS LB25,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '25' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id
			) AS LG25,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '25' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS NAB25,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '25' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id 
			) AS NAG25,
			
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '26' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1 AND SR.AttendanceTypeId =1
			) AS PB26,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '26' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1	AND SR.AttendanceTypeId=1
			) AS PG26,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate= (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '26' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABB26,
			(select count(A.Id) FROM  sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '26' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABG26,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '26' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS LB26,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '26' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id
			) AS LG26,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '26' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS NAB26,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '26' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id 
			) AS NAG26,
			
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '27' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1 AND SR.AttendanceTypeId =1
			) AS PB27,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '27' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1	AND SR.AttendanceTypeId=1
			) AS PG27,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate= (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '27' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABB27,
			(select count(A.Id) FROM  sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '27' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABG27,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '27' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS LB27,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '27' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id
			) AS LG27,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '27' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS NAB27,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '27' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id 
			) AS NAG27,
			
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '28' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1 AND SR.AttendanceTypeId =1
			) AS PB28,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '28' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1	AND SR.AttendanceTypeId=1
			) AS PG28,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate= (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '28' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABB28,
			(select count(A.Id) FROM  sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '28' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABG28,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '28' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS LB28,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '28' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id
			) AS LG28,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '28' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS NAB28,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '28' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id 
			) AS NAG28,
			
			CASE 
			WHEN @lMonthDays >= 29 THEN
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '29' )) AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1 AND SR.AttendanceTypeId =1
			)
			ELSE
			0
			END
			 AS PB29,
			 
			CASE 
			WHEN @lMonthDays >= 29 THEN
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '29' )) AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1	AND SR.AttendanceTypeId=1
			)
			ELSE
			0
			END AS PG29,
			CASE 
			WHEN @lMonthDays >= 29 THEN
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate= (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '29' )) AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			)ELSE
			0
			END AS ABB29,
			CASE 
			WHEN @lMonthDays >= 29 THEN
			(select count(A.Id) FROM  sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '29' )) AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			)ELSE
			0
			END AS ABG29,
			CASE 
			WHEN @lMonthDays >= 29 THEN
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '29' )) AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			)ELSE
			0
			END  AS LB29,
			CASE 
			WHEN @lMonthDays >= 29 THEN
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '29' )) AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id
			)ELSE
			0
			END   AS LG29,
			CASE 
			WHEN @lMonthDays >= 29 THEN
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '29' )) AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			)ELSE
			0
			END  AS NAB29,
			CASE 
			WHEN @lMonthDays >= 29 THEN
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '29' )) AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id 
			)ELSE
			0
			END  AS NAG29,
			CASE 
			WHEN @lMonthDays >= 30 THEN
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '30' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1 AND SR.AttendanceTypeId =1
			)ELSE
			0
			END  AS PB30,
			CASE 
			WHEN @lMonthDays >= 30 THEN
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '30' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1	AND SR.AttendanceTypeId=1
			)ELSE
			0
			END AS PG30,
			CASE 
			WHEN @lMonthDays >= 30 THEN
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate= (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '30' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			)ELSE
			0
			END  AS ABB30,
			CASE 
			WHEN @lMonthDays >= 30 THEN
			(select count(A.Id) FROM  sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '30' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			)ELSE
			0
			END  AS ABG30,
			CASE 
			WHEN @lMonthDays >= 30 THEN
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '30' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			)ELSE
			0
			END  AS LB30,
			CASE 
			WHEN @lMonthDays >= 30 THEN
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '30' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id
			)ELSE
			0
			END  AS LG30,
			CASE 
			WHEN @lMonthDays >= 30 THEN
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '30' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			)ELSE
			0
			END  AS NAB30,
			CASE 
			WHEN @lMonthDays >= 30 THEN
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '30' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id 
			)ELSE
			0
			END  AS NAG30,
			
			CASE 
			WHEN @lMonthDays >= 31 THEN
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
			WHERE A.BatchId = @rBatchId  
			AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '31' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1 AND SR.AttendanceTypeId =1
			)ELSE
			0
			END  AS PB31,
			CASE 
			WHEN @lMonthDays >= 31 THEN
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
			WHERE A.BatchId = @rBatchId  
			AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '31' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1	AND SR.AttendanceTypeId=1
			)ELSE
			0
			END   AS PG31,
			CASE 
			WHEN @lMonthDays >= 31 THEN
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
			WHERE A.BatchId = @rBatchId  
			AND SR.AttendanceDate= (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '31' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			)ELSE
			0
			END  AS ABB31,
			CASE 
			WHEN @lMonthDays >= 31 THEN
			(select count(A.Id) FROM  sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
			WHERE A.BatchId = @rBatchId  
			AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '31' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			)ELSE
			0
			END AS ABG31,
			CASE 
			WHEN @lMonthDays >= 31 THEN
			(	select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
			WHERE A.BatchId = @rBatchId  
			AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '31' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			)ELSE
			0
			END  AS LB31,
			CASE 
			WHEN @lMonthDays >= 31 THEN
			(	select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
			WHERE A.BatchId = @rBatchId  
			AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '31' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id
			)ELSE
			0
			END AS LG31,
			CASE 
			WHEN @lMonthDays >= 31 THEN
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
			WHERE A.BatchId = @rBatchId  
			AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '31' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			)ELSE
			0
			END AS NAB31,
			CASE 
			WHEN @lMonthDays >= 31 THEN
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
			WHERE A.BatchId = @rBatchId  
			AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '31' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id 
			)ELSE
			0
			END AS NAG31,
			
			MS.WorkingDays AS WorkingDays,
			Dept.Title AS DepartmentName,
			CM.Id AS ClassId,
			CM.Title AS ClassName,
			DM.Id AS DivId,
			DM.Title AS DivisionName,
			--@rStatus AS StatusCheck,
			--@rStatusClass AS StatusClass
			@rMonth AS StudentMonth,
			@rYear AS StudentYear
			
			FROM 
			
			
			sSetup.tDivisionMaster DM  
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=DM.ClassId
			INNER JOIN sAttendance.tMonthlySetup MS ON CM.Id=MS.ClassId		
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id=MS.BatchId	
			INNER JOIN sSetup.tDepartmentMaster Dept ON Dept.Id=CM.DepartmentId  
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = DM.OrgId
		
			
	WHERE 
		DM.OrgId=@rOrgId
		AND	MS.BatchId = @rBatchId 
		AND ((DM.ClassId=@rClassId) OR (@rClassId=0))
		AND ((DM.Id=@rDivisionId) OR (@rDivisionId=0))
		AND ((Dept.Id=@rDepartmentId) OR (@rDepartmentId=0))
		
		AND ((MS.ForMonth=@rMonth) OR(@rMonth =0)) 
		AND ((MS.ForYear=@rYear) OR (@rYear=0))
		--AND	BM.OrgGroupBatchId = @rOrgGroupBatchId 
	
	
END
GO
PRINT N'Altering [sStudent].[pRptStudentStrengthGet]...';


GO


ALTER PROCEDURE [sStudent].[pRptStudentStrengthGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rOrgId smallint,
	 @rBatchId int,
	 @rClassId int,
	 @rDivisionId int,
	 @rFromDate date='',
	 @rToDate date='',
	 @rReportId int=0,
	 @rDepartmentId int,
	 @rStatus bit,
	 @rOrgGroupBatchId int,
	 @rStatusClass bit
	 --@rAttendanceTypeId smallint=0
	
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	SELECT 
			Distinct Dept.Id AS DepartmentId,
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			
			
			(
			select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			 INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
			 INNER JOIN sCommon.tGenderMaster GM 
			ON GM.Id=SO.GenderId
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId 
	        WHERE  BM.OrgGroupBatchId = @rOrgGroupBatchId  AND SA.AdmissionDate >= @rFromDate 
			AND SA.AdmissionDate <= @rToDate AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND GM.Id=2 AND CM.DepartmentId = Dept.Id 
			)AS NewGirls,
		
			(
			select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId  INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId INNER JOIN sCommon.tGenderMaster GM 
			ON GM.Id=SO.GenderId INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId 
	        WHERE BM.OrgGroupBatchId = @rOrgGroupBatchId  AND SA.AdmissionDate >= @rFromDate 
			AND SA.AdmissionDate <= @rToDate
			AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id 
			AND GM.Id=1 AND  CM.DepartmentId=Dept.Id 
			) AS NewBoys,
			
			(
			select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId  INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId INNER JOIN sCommon.tGenderMaster GM 
			ON GM.Id=SO.GenderId INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId 
	        WHERE BM.OrgGroupBatchId = @rOrgGroupBatchId  AND SA.LeftDate >= @rFromDate 
			AND SA.LeftDate <= @rToDate
			AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id 
			AND GM.Id=2 AND  CM.DepartmentId=Dept.Id 
			) AS LeftGirls,
			
			(
			select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId  INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId INNER JOIN sCommon.tGenderMaster GM 
			ON GM.Id=SO.GenderId INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId 
	        WHERE BM.OrgGroupBatchId = @rOrgGroupBatchId  AND SA.LeftDate >= @rFromDate 
			AND SA.LeftDate <= @rToDate
			AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id 
			AND GM.Id=1 AND  CM.DepartmentId=Dept.Id 
			) AS LeftBoys,
			
			
			(
				select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
				ON SA.StudentId = A.StudentId
				 INNER JOIN sStudent.tStudentOther SO
				ON SO.StudentId=SA.StudentId
				 INNER JOIN sCommon.tGenderMaster GM 
				ON GM.Id=SO.GenderId INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId 
				WHERE BM.OrgGroupBatchId = @rOrgGroupBatchId  
				AND	SA.AdmissionDate < @rFromDate
				AND ( SA.LeftDate < @rFromDate OR ISNULL(SA.LeftDate,'')= '')
				AND A.ClassId =CM.Id 
				AND A.DivisionId=DM.Id AND GM.Id=2 AND CM.DepartmentId = Dept.Id
				
			) AS TotalGirls,
			(
				select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
				ON SA.StudentId = A.StudentId
				 INNER JOIN sStudent.tStudentOther SO
				ON SO.StudentId=SA.StudentId
				 INNER JOIN sCommon.tGenderMaster GM 
				ON GM.Id=SO.GenderId
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId 
				WHERE BM.OrgGroupBatchId = @rOrgGroupBatchId  
				AND	SA.AdmissionDate < @rFromDate
				AND ( SA.LeftDate < @rFromDate OR ISNULL(SA.LeftDate,'')= '')
				AND A.ClassId =CM.Id 
				AND A.DivisionId=DM.Id AND GM.Id=1 AND CM.DepartmentId = Dept.Id
			) AS TotalBoys,	
			
			
			Dept.Title AS DepartmentName,
			CM.Id AS ClassId,
			CM.Title AS ClassName,
			DM.Id AS DivId,
			DM.Title AS DivisionName,
			@rStatus AS StatusCheck,
			@rStatusClass AS StatusClass
			FROM 
			
			sStudent.tAcademic A		
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id=A.BatchId
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDepartmentMaster Dept ON Dept.Id=CM.DepartmentId AND DM.Id=A.DivisionId AND CM.Id=A.ClassId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = DM.OrgId
			
			
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			
	WHERE 
		 A.OrgId=@rOrgId
		--AND	A.BatchId = @rBatchId 
		
		AND ((A.ClassId=@rClassId) OR (@rClassId=0))
		AND ((DM.Id=@rDivisionId) OR (@rDivisionId=0))
		AND ((Dept.Id=@rDepartmentId) OR (@rDepartmentId=0))
		AND	BM.OrgGroupBatchId = @rOrgGroupBatchId 
		
	
END
GO
PRINT N'Altering [sStudent].[pStudentCustomSearchGet]...';


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

BEGIN
		DECLARE @Sql nvarchar(MAX)
		
		IF(@rDOBFromDate IS NULL)
			SET @rDOBFromDate='0001-01-01'
		IF(@rDOBToDate IS NULL)
			SET @rDOBToDate='9990-12-31'
		IF(@rDOAFromDate IS NULL)
			SET @rDOAFromDate='0001-01-01'
		IF(@rDOAToDate IS NULL)
			SET @rDOAToDate='9990-12-31'
		IF(@rDOLFromDate IS NULL)
			SET @rDOLFromDate='0001-01-01'
		IF(@rDOLToDate IS NULL)
			SET @rDOLToDate='9990-12-31'
		
		 
		SET @rDOBToDate = DATEADD(d,1,@rDOBToDate)		 
		SET @rDOAToDate = DATEADD(d,1,@rDOAToDate)		 
		SET @rDOLToDate = DATEADD(d,1,@rDOLToDate)	
		
		
	
		SET @rCode = sCommon.fSearchStringGet(@rCode)
		SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
		SET @rLastName = sCommon.fSearchStringGet(@rLastName)
		SET @rCountry = sCommon.fSearchStringGet(@rCountry)
		SET @rState = sCommon.fSearchStringGet(@rState)
		 
		  
		--select @rDOLFromDate,@rDOLToDate
		SELECT 
				*,
				SCS.ClassName+'-'+SCS.DivisionName AS ClassName1
		into sStudent.tTempStudent1
		FROM sStudent.vStudentCustomSearch SCS
		WHERE 
			SCS.OrgId = @rOrgId AND SCS.BatchId = @BatchId 
			AND ((SCS.Code Like @rCode + '%') OR (@rCode = ''))
			AND ((SCS.FirstName Like @rFirstName  + '%') OR (@rFirstName = ''))	 			 
			AND ((SCS.LastName Like @rLastName + '%')OR(@rLastName = ''))
			AND ((ISNULL(SCS.PermanentCountry,'') Like @rCountry + '%')OR(@rCountry = ''))
			AND ((ISNULL(SCS.PermanentState,'') Like @rState + '%')OR(@rState = ''))		 
			AND (( SCS.DateOfBirth  >= @rDOBFromDate) OR (ISNULL(SCS.DateOfBirth,'') = ''))
			AND (( SCS.DateOfBirth  < @rDOBToDate) OR (ISNULL(SCS.DateOfBirth,'') = ''))
			AND (( SCS.AdmissionDate >= @rDOAFromDate) OR (ISNULL(SCS.AdmissionDate,'') = ''))
			AND (( SCS.AdmissionDate < @rDOAToDate) OR (ISNULL(SCS.AdmissionDate,'') = ''))		 
			AND (( SCS.LeftDate  >= @rDOLFromDate) OR (ISNULL(SCS.LeftDate,'') = ''))
			AND (( SCS.LeftDate   < @rDOLToDate) OR (ISNULL(SCS.LeftDate,'') = ''))
			AND ((SCS.Hobby Like '%' + @rHobby + '%') OR (@rHobby = ''))		    
		    AND (ISNULL(SCS.PermanentCity,0) IN( SELECT item FROM  sCommon.fnsplit(@rCity,','))OR @rCity='')
		    
		    AND (ISNULL(SCS.PermanentStreetThree,0) IN( SELECT item FROM  sCommon.fnsplit(@rArea,','))OR @rArea='')
		    
		    AND (SCS.DivisionId In( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionId,','))OR @rDivisionId='')
		         	          
			AND (SCS.StatusId In( SELECT cast(item as int) FROM  sCommon.fnsplit(@rStatusId,','))OR @rStatusId='')	
	        
	        AND (SCS.TransportModeId In( SELECT cast(item as int) FROM  sCommon.fnsplit(@rTransportModeId,','))OR @rTransportModeId='')
	        
	        AND (ISNULL(SCS.BloodGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rBloodGroupId,','))OR @rBloodGroupId='') 
		    
		    AND (ISNULL(SCS.GenderId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rGenderId,','))OR @rGenderId='')
		            
		    AND (ISNULL(SCS.ReligionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rReligionId,','))OR @rReligionId='')
		           
		    AND (ISNULL(SCS.CastCategoryId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rCastCategoryId,','))OR @rCastCategoryId='')
		           
		    AND (ISNULL(SCS.HouseId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rHouseId,','))OR @rHouseId='')
		                   
		    AND (ISNULL(SCS.MotherTongueId,0) IN ( SELECT cast(item as int) FROM  sCommon.fnsplit(@rMotherTongueId,','))OR @rMotherTongueId='')
		           
		    AND (ISNULL(SCS.NationalityId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rNationalityId,','))OR @rNationalityId='')
		     
		    AND (ISNULL(SCS.BusRouteDestinationId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rBusRouteDestinationId,','))OR @rBusRouteDestinationId='')		
		    
		    AND (ISNULL(SCS.FatherQualification,'') IN( SELECT item FROM  sCommon.fnsplit(@rFatherQualification,','))OR @rFatherQualification='')
		    
		    AND (ISNULL(SCS.FatherOccupation,'') IN( SELECT item FROM  sCommon.fnsplit(@rFatherOccupation,','))OR @rFatherOccupation='')
		    
		    AND (ISNULL(SCS.MotherQualification,'') IN( SELECT item FROM  sCommon.fnsplit(@rMotherQualification,','))OR @rMotherQualification='')
		    
		    AND (ISNULL(SCS.MotherOccupation,'') IN( SELECT item FROM  sCommon.fnsplit(@rMotherOccupation,','))OR @rMotherOccupation='')
		    
		    AND (ISNULL(SCS.AdmissionCategoryId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rAdmissionCategoryId,','))OR @rAdmissionCategoryId='')
		    
		    AND (ISNULL(SCS.PreviousSchool,'') IN( SELECT item FROM  sCommon.fnsplit(@rPreviousSchool,','))OR @rPreviousSchool='')
		    
		    AND ((SCS.IsPysicalDeformity=@rIsPysicalDeformity) OR (@rIsPysicalDeformity=0))
		    AND ((SCS.IsMajorIllness=@rIsMajorIllness) OR (@rIsMajorIllness=0)) 
		    AND ((SCS.IsBlackList=@rIsBlackList) OR (@rIsBlackList=0))
		    AND ((SCS.Code >= @rFromCode) OR (@rFromCode=''))
			AND ((SCS.Code <= @rToCode) OR (@rToCode=''))
			AND ((SCS.StatusId = @rDropDownStatusId) OR (@rDropDownStatusId=0))
			AND ((SCS.ClassId = @rDropDownClassId) OR (@rDropDownClassId=0))
			AND ((SCS.DivisionId = @rDropDownDivisionId) OR (@rDropDownDivisionId=0))
		    
	SET @rOrderBy=Replace(@rOrderBy,'ID No','Code')
		SET @sql=
		'SELECT 
				StudentId,
				Code AS Code,
				Name,
				ClassName1 AS ClassName,
				StatusName 
		FROM sStudent.tTempStudent1 ORDER BY '+@rOrderBy
		exec(@Sql)
		--print @Sql
		DROP Table sStudent.tTempStudent1
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].[pStudentGenerateReport]...';


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

	INSERT INTO sStudent.tStudentCustomSearch
		(
			Id,
			Title,
			ColumnName,
			OrderBy,
			OrgId,
			Code,
			FirstName,	
			LastName,
			Country,
			State,
			City,
			Area,
			DivisionId,
			StatusId,
			TransportModeId,
			BusRouteDestinationId,
			BloodGroupId,
			GenderId,
			ReligionId,
			CastCategoryId,
			HouseId,
			MotherTongueId,
			NationalityId,
			Hobby,
			FatherQualification,
			MotherQualification,
			FatherOccupation,
			MotherOccupation,
			PreviousSchool,
			AdmissionCategoryId,
			DOBFromDate,
			DOBToDate,
			DOAFromDate,
			DOAToDate,
			DOLFromDate,
			DOLToDate,
			IsPysicalDeformity,
			IsMajorIllness,
			IsCommon,
			CreatedUserId,
			CreatedDateTime,
			IsBlackList,
			FromCode,
			ToCode
		)
	VALUES
		(
			@lNextNumber,
			@rTitle,
			@rColumnName,
			@rOrderBy,
			@rOrgId,
			@rCode,
			@rFirstName,	
			@rLastName,
			@rCountry,
			@rState,
			@rCity,
			@rArea,
			@rDivisionId,
			@rStatusId,
			@rTransportModeId,
			@rBusRouteDestinationId,
			@rBloodGroupId,
			@rGenderId,
			@rReligionId,
			@rCastCategoryId,
			@rHouseId,
			@rMotherTongueId,
			@rNationalityId,
			@rHobby,
			@rFatherQualification,
			@rMotherQualification,
			@rFatherOccupation,
			@rMotherOccupation,
			@rPreviousSchool,
			@rAdmissionCategoryId,
			@rDOBFromDate,
			@rDOBToDate,
			@rDOAFromDate,
			@rDOAToDate,
			@rDOLFromDate,
			@rDOLToDate,
			@rIsPysicalDeformity,
			@rIsMajorIllness,
			@rIsCommon,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rIsBlackList,
			@rFromCode,
			@rToCode
			
		)
		--SELECT @lNextNumber AS Result
	END
	IF(@rId > 0)
	BEGIN
		Select
				@rColumnName=ColumnName,
				@rOrderBy=OrderBy,
				@rOrgId=OrgId,
				@rCode=Code,
				@rFirstName=FirstName,	
				@rLastName=LastName,
				@rCountry=Country,
				@rState=State,
				@rCity=City,
				@rArea=Area,
				@rDivisionId=DivisionId,
				@rStatusId=StatusId,
				@rTransportModeId=TransportModeId,
				@rBusRouteDestinationId=BusRouteDestinationId,
				@rBloodGroupId=BloodGroupId,
				@rGenderId=GenderId,
				@rReligionId=ReligionId,
				@rCastCategoryId=CastCategoryId,
				@rHouseId=HouseId,
				@rMotherTongueId=MotherTongueId,
				@rNationalityId=NationalityId,
				@rHobby=Hobby,
				@rFatherQualification=FatherQualification,
				@rMotherQualification=MotherQualification,
				@rFatherOccupation=FatherOccupation,
				@rMotherOccupation=MotherOccupation,
				@rPreviousSchool=PreviousSchool,
				@rAdmissionCategoryId=AdmissionCategoryId,
				@rDOBFromDate=DOBFromDate,
				@rDOBToDate=DOBToDate,
				@rDOAFromDate=DOAFromDate,
				@rDOAToDate=DOAToDate,
				@rDOLFromDate=DOLFromDate,
				@rDOLToDate=DOLToDate,
				@rIsPysicalDeformity=IsPysicalDeformity,
				@rIsMajorIllness=IsMajorIllness,
				@rIsBlackList=IsBlackList,
				@rFromCode=FromCode,
				@rToCode=ToCode
		FROM
			sStudent.tStudentCustomSearch
		WHERE
			Id=@rId
	END
	
	SET @rColumnName=Replace(@rColumnName,'ID No','Code')
	SET @rOrderBy=Replace(@rOrderBy,'ID No','Code')
	DECLARE @Sql nvarchar(MAX)
	
	SET @rCode = sCommon.fSearchStringGet(@rCode)
	SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
	SET @rLastName = sCommon.fSearchStringGet(@rLastName)
	SET @rCountry = sCommon.fSearchStringGet(@rCountry)
	SET @rState = sCommon.fSearchStringGet(@rState)
	--SET @rCity = sCommon.fSearchStringGet(@rCity)
	
		SELECT 
			* into sStudent.tTempStudent
		FROM sStudent.vStudentCustomSearch SCS
		WHERE 
			SCS.OrgId = @rOrgId 
			AND ((SCS.Code Like @rCode + '%') OR (@rCode = ''))
			AND ((SCS.FirstName Like @rFirstName  + '%') OR (@rFirstName = ''))	 			 
			AND ((SCS.LastName Like @rLastName + '%')OR(@rLastName = ''))
			AND ((SCS.Hobby Like '%' + @rHobby + '%') OR (@rHobby = ''))
			AND ((ISNULL(SCS.PermanentCountry,'') Like @rCountry + '%')OR(@rCountry = ''))
			AND ((ISNULL(SCS.PermanentState,'') Like @rState + '%')OR(@rState = ''))
			--AND ((ISNULL(SCS.PermanentCity,'') Like @rCity + '%')OR(@rCity = ''))
			AND ((ISNULL(SCS.DateOfBirth,'0001-01-01') >= @rDOBFromDate) OR (ISNULL(@rDOBFromDate,'') = ''))
			AND ((ISNULL(SCS.DateOfBirth,'9999-12-31') <= @rDOBToDate) OR (ISNULL(@rDOBToDate,'') = ''))
			AND ((ISNULL(SCS.AdmissionDate,'0001-01-01') >= @rDOAFromDate) OR (ISNULL(@rDOAFromDate,'') = ''))
			AND ((ISNULL(SCS.AdmissionDate,'9999-12-31') <= @rDOAToDate) OR (ISNULL(@rDOAToDate,'') = ''))
			AND ((ISNULL(SCS.LeftDate,'0001-01-01') >= @rDOLFromDate) OR (ISNULL(@rDOLFromDate,'') = ''))
			AND ((ISNULL(SCS.LeftDate,'9999-12-31') <= @rDOLToDate) OR (ISNULL(@rDOLToDate,'') = ''))
				
			--AND (SCS.ClassId In( SELECT item FROM  sCommon.fnsplit(@rClassId,','))OR @rClassId=''))
		    
		    AND (ISNULL(SCS.PermanentCity,0) IN( SELECT item FROM  sCommon.fnsplit(@rCity,','))OR @rCity='')
		    
		    AND (ISNULL(SCS.PermanentStreetThree,0) IN( SELECT item FROM  sCommon.fnsplit(@rArea,','))OR @rArea='')
		    
		    AND (SCS.DivisionId In( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionId,','))OR @rDivisionId='')
		         	          
			AND (SCS.StatusId In( SELECT cast(item as int) FROM  sCommon.fnsplit(@rStatusId,','))OR @rStatusId='')	
	        
	        AND (SCS.TransportModeId In( SELECT cast(item as int) FROM  sCommon.fnsplit(@rTransportModeId,','))OR @rTransportModeId='')
	        
	        AND (ISNULL(SCS.BloodGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rBloodGroupId,','))OR @rBloodGroupId='') 
		    
		    AND (ISNULL(SCS.GenderId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rGenderId,','))OR @rGenderId='')
		            
		    AND (ISNULL(SCS.ReligionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rReligionId,','))OR @rReligionId='')
		           
		    AND (ISNULL(SCS.CastCategoryId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rCastCategoryId,','))OR @rCastCategoryId='')
		           
		    AND (ISNULL(SCS.HouseId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rHouseId,','))OR @rHouseId='')
		                   
		    AND (ISNULL(SCS.MotherTongueId,0) IN ( SELECT cast(item as int) FROM  sCommon.fnsplit(@rMotherTongueId,','))OR @rMotherTongueId='')
		           
		    AND (ISNULL(SCS.NationalityId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rNationalityId,','))OR @rNationalityId='')
		     
		    AND (ISNULL(SCS.BusRouteDestinationId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rBusRouteDestinationId,','))OR @rBusRouteDestinationId='')		
		    
		    AND (ISNULL(SCS.FatherQualification,'') IN( SELECT item FROM  sCommon.fnsplit(@rFatherQualification,','))OR @rFatherQualification='')
		    
		    AND (ISNULL(SCS.FatherOccupation,'') IN( SELECT item FROM  sCommon.fnsplit(@rFatherOccupation,','))OR @rFatherOccupation='')
		    
		    AND (ISNULL(SCS.MotherQualification,'') IN( SELECT item FROM  sCommon.fnsplit(@rMotherQualification,','))OR @rMotherQualification='')
		    
		    AND (ISNULL(SCS.MotherOccupation,'') IN( SELECT item FROM  sCommon.fnsplit(@rMotherOccupation,','))OR @rMotherOccupation='')
			
		    AND (ISNULL(SCS.AdmissionCategoryId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rAdmissionCategoryId,','))OR @rAdmissionCategoryId='')
		    
			AND (ISNULL(SCS.PreviousSchool,'') IN( SELECT item FROM  sCommon.fnsplit(@rPreviousSchool,','))OR @rPreviousSchool='')
		
			AND ((SCS.IsPysicalDeformity=@rIsPysicalDeformity) OR (@rIsPysicalDeformity=0))
		    AND ((SCS.IsMajorIllness=@rIsMajorIllness) OR (@rIsMajorIllness=0)) 
		    AND ((SCS.IsBlackList=@rIsBlackList) OR (@rIsBlackList=0))
		    AND ((SCS.Code >= @rFromCode) OR (@rFromCode=''))
			AND ((SCS.Code <= @rToCode) OR (@rToCode=''))
			AND ((SCS.StatusId = @rDropDownStatusId) OR (@rDropDownStatusId=0))
			AND ((SCS.ClassId = @rDropDownClassId) OR (@rDropDownClassId=0))
			AND ((SCS.DivisionId = @rDropDownDivisionId) OR (@rDropDownDivisionId=0))
			
		SET @rColumnName=Replace(@rColumnName,',Code',',Code AS [ID No]')
		--SET @rOrderBy=Replace(@rOrderBy,',Code',',Code AS [ID No]')
		SET @sql=
		'SELECT '+
		@rColumnName+' 
		FROM sStudent.tTempStudent ORDER BY '+@rOrderBy
		SET @sql=Replace(@sql,'SELECT Code','SELECT Code AS [ID No]')
		exec(@Sql)
		
		DROP Table sStudent.tTempStudent
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		--SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sStudent].[pStudentMasterGet]...';


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

BEGIN 

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


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


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


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

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

DELETE FROM sAdmission.tInquiryModeMaster

DELETE FROM sFee.tFeeMainGroupMaster

DELETE FROM sPayroll.tPayElementDefault

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


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


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


GO

ALTER PROCEDURE [sTransport].[pBusRouteDestinationMasterAdd]
	 
	        @rId int
	       ,@rBusRouteId int
	       ,@rTitle nvarchar(100)
           ,@rAmount decimal(12,2)
           ,@rOrderIndex smallint
           ,@rIsObsolete bit
           --,@rIsDeleted bit
           ,@rCreatedUserId bigint           
           ,@rOrgGroupId int
           ,@rPickupTime nvarchar(50)
           ,@rDropTime nvarchar(50)
           	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	--BEGIN TRY
	
	-- BEGIN TRANSACTION	
	 DECLARE @lNextNumber INT 
--If(@rIsDeleted=1)
--BEGIN
--	Delete from sFee.tChargeMaster where Id=@rId
--	Select @rId as Result
--END	
--ELSE
--BEGIN     
	
--If Exists(select top(1)* from sFee.tChargeMaster where Title=@rTitle AND OrgId=@rOrgId)
--BEGIN
--	If NOT Exists(select top(1)* from sFee.tChargeMaster where Title=@rTitle AND OrgId=@rOrgId AND Id=@rId)
--	BEGIN
--		select -101 as Result
--	END
--	ELSE
--	BEGIN
--	 SET @lNextNumber = @rId
--	    UPDATE  [sFee].[tChargeMaster]
--	    SET
--			  --Number=@rNumber
--	         --,Code=@rCode
--	         Title=@rTitle
--	         ,ChargeCategoryId=@rChargeCategoryId
--	         ,ChargeAmount=@rChargeAmount
--	         ,OrderIndex=@rOrderIndex
--             ,[IsObsolete] = @rIsObsolete                          
--             ,[UpdatedUserId] = @rCreatedUserId
--             ,[UpdatedDateTime] = sCommon.fGetDate()          
             
--	      WHERE Id = @rId 	 
--	      SELECT @lNextNumber AS Result
	
--		--COMMIT TRANSACTION  
--	 END  
--END
--ELSE
--BEGIN
IF(@rId = 0)	
BEGIN
	--EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sTransport.tBusRouteDestinationMaster',@lNextNumber = @lNextNumber output
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sTransport.tBusRouteDestinationMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	
	INSERT INTO [sTransport].[tBusRouteDestinationMaster] 
			   (
			    [Id]
			   ,[BusRouteId] 
			   ,[Title]
			   ,[Amount] 
			   ,[OrderIndex]
			   ,[IsObsolete]
			   ,[CreatedUserId]
			   ,[CreatedDateTime]
			   ,[UpdatedUserId]
			   ,[UpdatedDateTime]
			   ,[OrgGroupId]
			   ,[PickupTime]
			   ,[DropTime]
			   --,[OrgId]
			   )
		 VALUES
			   (
				@lNextNumber
			   ,@rBusRouteId
			   ,@rTitle
			   ,@rAmount
			   ,@rOrderIndex
			   ,@rIsObsolete
			   ,@rCreatedUserId
			   ,sCommon.fGetDate()
			   ,0
			   ,sCommon.fGetDate()
			   ,@rOrgGroupId
			   ,@rPickupTime
			   ,@rDropTime
			   --,@rOrgId
			   )
		    SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION         
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  [sTransport].[tBusRouteDestinationMaster] 
	    SET
			  BusRouteId=@rBusRouteId
			 ,Title=@rTitle
	         ,Amount=@rAmount
	         ,OrderIndex=@rOrderIndex
             ,[IsObsolete] = @rIsObsolete                          
             ,[UpdatedUserId] = @rCreatedUserId
             ,[UpdatedDateTime] = sCommon.fGetDate()
             ,PickupTime=@rPickupTime
			 ,DropTime=@rDropTime
             
	      WHERE Id = @rId 	   
	      SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION
	 END  
		
	--END
--END	
--COMMIT TRANSACTION		
--	END TRY
	
--	BEGIN CATCH 
--		ROLLBACK TRANSACTION
--		SELECT -1 AS Result
--	END CATCH	
		
END
GO
PRINT N'Altering [sTransport].[pBusRouteDestinationMasterGet]...';


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

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


GO

ALTER PROCEDURE [sTransport].[pBusRouteMasterGet]
          
           @rTitle nvarchar(100),
           @rOrgGroupBatchId int
          
AS
SET NOCOUNT ON
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
BEGIN
SELECT 
	   BRM.Id as BusRouteId
	  ,BRM.Title as BusRoute
	  ,BRM.Remark
	  ,BRM.DriverName
	  ,BRM.DriverMobileNo
	  ,BRM.ConductorName
	  ,BRM.ConductorMobileNo
	  ,BRM.VehicleId
	  ,BRM.OrderIndex as BusRouteOrderIndex
      ,BRM.IsObsolete as BusRouteIsObsolete
     
  FROM [sTransport].[tBusRouteMaster] BRM 
        
  WHERE 
	((BRM.Title Like @rTitle) OR (ISNULL(@rTitle,'') = ''))
	AND BRM.OrgGroupBatchId=@rOrgGroupBatchId
    order by BRM.OrderIndex
END
GO
PRINT N'Altering [sTransport].[pRptRoutewiseStudentListGet]...';


GO


ALTER PROCEDURE [sTransport].[pRptRoutewiseStudentListGet]

	 @rOrgGroupBatchId int,
	 @rOrgId int,
	 @rDepartmentId int,
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rClassId int,
	 @rDivisionId int,
	 @rRouteId int,
	 @rDestinationId int
	 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

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



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


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

	INSERT INTO sTransport.tVehicleMaster
		(
			Id,
			Title,
			RegistrationNumber,
			TypeOfVehicle,
			NoOfSeats,
			CreatedUserId,
			CreatedDateTime,
			IsObsolete,
			OrgGroupId 
		)
	VALUES
		(
			@lNextNumber,
			@rTitle,
			@rRegistrationNumber,
			@rTypeOfVehicle,
			@rNoOfSeats,
			@rCreatedUserId,
			sCommon.fGetDate(), 
			@rIsObsolete,
			@rOrgGroupId
		)
		    select 1 as Result         
	END	 
	 ELSE
		If  Exists(select Id from sTransport.tVehicleMaster where Title=@rTitle  AND Id<>@rId)
		Begin
			select -103 as Result
			RETURN
		
	END	
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sTransport.tVehicleMaster
	    SET
			Title=@rTitle,
			RegistrationNumber=@rRegistrationNumber,
			TypeOfVehicle=@rTypeOfVehicle,
			NoOfSeats=@rNoOfSeats,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate(), 
			IsObsolete=@rIsObsolete
	      
	      
	      WHERE Id = @rId and OrgGroupId=@rOrgGroupId
	       SELECT 105 AS Result
	
	 END  
		
		--COMMIT TRANSACTION
		
	--END TRY
	
	--BEGIN CATCH 
	--	ROLLBACK TRANSACTION
	--	SELECT -1 AS Result
	--END CATCH	
		
END
GO
PRINT N'Creating [sAcademic].[pTeacherSubjectAdd]...';


GO

CREATE PROCEDURE [sAcademic].[pTeacherSubjectAdd]
	
	@rTeacherSubjectImpXml [nvarchar](max),
	@rEmployeeId bigint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rTeacherSubjectImpXml
BEGIN
	
	BEGIN TRY
	BEGIN TRANSACTION
	
	 DELETE FROM sAcademic.tTeacherSubject WHERE EmployeeId=@rEmployeeId
	
	 INSERT INTO sAcademic.tTeacherSubject
		(
			EmployeeId,
			SubjectId
			)
		SELECT
			EmployeeId,
			SubjectId
		FROM OPENXML (@loDoc, '/Table/TeacherSubject', 1)
		WITH ( 
				EmployeeId bigint,
				SubjectId int
			  ) 
		
	   SELECT 1 AS Result
		
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Creating [sAcademic].[pTeacherSubjectDivisionAdd]...';


GO

CREATE PROCEDURE [sAcademic].[pTeacherSubjectDivisionAdd]
	
	@rTeacherSubjectDivisionImpXml [nvarchar](max),
	@rEmployeeId bigint,
	@rSubjectId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rTeacherSubjectDivisionImpXml
BEGIN
	
	BEGIN TRY
	BEGIN TRANSACTION
	
	 DELETE FROM sAcademic.tTeacherSubjectDivision WHERE EmployeeId=@rEmployeeId AND SubjectId=@rSubjectId
	
	 INSERT INTO sAcademic.tTeacherSubjectDivision
		(
			EmployeeId,
			SubjectId,
			DivisionId
			)
		SELECT
			EmployeeId,
			SubjectId,
			DivisionId
		FROM OPENXML (@loDoc, '/Table/TeacherSubjectDivision', 1)
		WITH ( 
				EmployeeId bigint,
				SubjectId int,
				DivisionId int
			  ) 
		
	   SELECT 1 AS Result
		
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Creating [sAcademic].[pTeacherSubjectDivisionGet]...';


GO
CREATE PROCEDURE [sAcademic].[pTeacherSubjectDivisionGet]

	 @rOrgId int,
	 @rSubject int,
	 @rEmployeeId bigint
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	SELECT 
		    vCD.DivisionId,
		    vCD.ClassDivisionName,
		    ISNULL(TSD.EmployeeId,0) AS EmployeeId,
		    ISNULL(TSD.SubjectId,0) AS SubjectId
	FROM 
			sAcademic.tTeacherSubjectDivision TSD
			RIGHT JOIN sSetup.vClassDivision vCD ON vCD.DivisionId = TSD.DivisionId AND TSD.SubjectId = @rSubject AND TSD.EmployeeId = @rEmployeeId
	WHERE 
		(vCD.OrgId=@rOrgId)
		
	Order by vCD.OrderIndex	
END
GO
PRINT N'Creating [sAcademic].[pTeacherSubjectGet]...';


GO
CREATE PROCEDURE [sAcademic].[pTeacherSubjectGet]

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

BEGIN 
	SELECT 
		    SM.Id AS SubjectId,
		    SM.Title AS SubjectName,
		    ISNULL(TS.EmployeeId,0) AS EmployeeId
	FROM 
			sAcademic.tTeacherSubject TS
			RIGHT JOIN sSetup.tSubjectMaster SM ON SM.Id = TS.SubjectId AND TS.EmployeeId = @rEmployeeId
	WHERE 
		(SM.OrgId=@rOrgId)
END
GO
PRINT N'Creating [sActivity].[pEventTypeMasterAdd]...';


GO

CREATE PROCEDURE [sActivity].[pEventTypeMasterAdd]
	 
		@rOrgGroupId int,
		@rId  int,
		@rCode nvarchar(20),
		@rTitle nvarchar(100),
		@rCreatedUserId bigint,
		@rCreatedDateTime date,
		@rIsObsolete bit,
		@rUpdateduserId bigint=0,
		@rUpdatedDateTime date='',
		@rHighlightColor nvarchar(100),
		@rOrderIndex int=0
		
      
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	--BEGIN TRY
	IF(@rId = 0)	
	BEGIN
		--If Exists(select Id from sActivity.tEventSchedule where Code=@rCode AND BatchId=@rBatchId)
		--	BEGIN
		--	select -102 as Result
		--	RETURN
		--END 
	
		If Exists(select Id from sActivity.tEventTypeMaster where Title=@rTitle AND Code=@rCode AND OrgGroupId=@rOrgGroupId)
			BEGIN
			select -103 as Result
			RETURN
		END 
	END
	ELSE
	BEGIN
		--If Exists(select Id from sActivity.tEventSchedule where Code=@rCode AND BatchId=@rBatchId AND Id<>@rId)
		--Begin
		--	select -102 as Result
		--	RETURN
		--End
		If  Exists(select Id from sActivity.tEventTypeMaster where Title=@rTitle AND Code=@rCode AND Id<>@rId)
		Begin
			select -103 as Result
			RETURN
		End

	END
	
	
	
	 --BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sActivity.tEventTypeMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sActivity.tEventTypeMaster
		(
		OrgGroupId,
		Id,
		Code,
		Title,
		CreatedUserId,
		CreatedDateTime,
		IsObsolete,
		HighlightColor,
		UpdatedUserId,
		UpdatedDateTime,
		OrderIndex
			
		)
	VALUES
		(
		@rOrgGroupId,
		@lNextNumber,
		@rCode,
		@rTitle,
		@rCreatedUserId,
		@rCreatedDateTime,
		@rIsObsolete,
		@rHighlightColor,
		@rCreatedUserId,
		@rCreatedDateTime,
		@rOrderIndex
		)
		    SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION         
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sActivity.tEventTypeMaster
	    SET
			Code=@rCode,
			Title=@rTitle,
			IsObsolete=@rIsObsolete,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate(),
			HighlightColor=@rHighlightColor,
			OrderIndex=@rOrderIndex
			
	      
	      
	      WHERE Id = @rId AND OrgGroupId = @rOrgGroupId
	      SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION
	 END  	

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


GO
CREATE PROCEDURE [sActivity].[pEventTypeMasterDelete]
	 @rId int,
	 @rOrgGroupId int
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	BEGIN TRY
		BEGIN TRANSACTION	
			Delete from sActivity.tEventTypeMaster where Id=@rId AND OrgGroupId=@rOrgGroupId
			
		COMMIT TRANSACTION	
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
	END CATCH	
END
GO
PRINT N'Creating [sActivity].[pEventTypeMasterGet]...';


GO
CREATE PROCEDURE [sActivity].[pEventTypeMasterGet]

	 @rOrgGroupId int,
	 @rId int = 0,
	 @rCode nvarchar(20),
	 @rTitle nvarchar(100)
	 
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
SET @rTitle = sCommon.fSearchStringGet(@rTitle)
BEGIN 
	
	
	SELECT 
	
	EM.OrgGroupId,
	EM.Id AS EventTypeId,
	EM.Code AS Code,
	EM.Title AS Title,
	EM.IsObsolete,
	EM.HighlightColor,
	EM.OrderIndex

  FROM 
            sActivity.tEventTypeMaster EM
  WHERE 
   (EM.Id = @rId) OR (@rId=0)
   AND (EM.OrgGroupId = @rOrgGroupId) 
   AND ((EM.Title Like @rTitle )OR( ISNULL(@rTitle,'') = ''))
   
   ORDER BY
	EM.OrderIndex
END
GO
PRINT N'Creating [sAssessment].[pCSStudentDetailGet]...';


GO

CREATE PROCEDURE [sAssessment].[pCSStudentDetailGet]
	  
	  @rBuilder1 nvarchar(max)='',
	  @rBuilder2 nvarchar(max)='', 
	  @rClassId int,
	  @rDivisionId int,
	  @rExamId int,
	  @rCCECSGroupId int,
	  @rCCECSIndicatorId int,
	  @rOrgId int,
	  @rBatchId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 		
		
	SELECT		
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,	
			SA.FirstName + ' ' + LastName AS Name,
			SA.RollNo,
			SA.Number,
			CGM.Title AS IndicatorGroup,
			CM.Title AS Indicator,
			AIS.Grade,
			SA.ClassName + '-' + SA.DivisionName AS Class,
			SA.ClassId,
			SA.DivisionId
  FROM 
  
			sStudent.vStudentAcademic SA
			INNER JOIN sAssessment.tCCECSExamScore AIS ON AIS.AcademicId =SA.AcademicId
			INNER JOIN sAssessment.tCCECSMaster CM ON AIS.CCECSId=CM.Id			
			INNER JOIN sAssessment.tCCECSGroupMaster CGM ON CGM.ID= CM.CCECAGroupId			
			--INNER JOIN sAssessment.tCCECSClass CC ON CC.ClassId=SA.ClassId
			
WHERE 
			SA.OrgId = @rOrgId
			AND (SA.BatchId = @rBatchId) 
			AND ((SA.ClassId = @rClassId) OR (@rClassId=0))
			AND ((SA.DivisionId = @rDivisionId) OR(@rDivisionId=0))
			AND ((AIS.ExamId= @rExamId) OR (@rExamId=0))
			AND ((CGM.Id=@rCCECSGroupId) OR (@rCCECSGroupId=0))
			AND ((CM.Id =@rCCECSIndicatorId) OR (@rCCECSIndicatorId=0)) 
			
			ORDER BY SA.RollNo
			
			
END
GO
PRINT N'Creating [sAssessment].[pMonthlyRegisterGet]...';


GO


CREATE PROCEDURE [sAssessment].[pMonthlyRegisterGet]

	 
	 @rAcedamicId bigint,
	 @rExamId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

SELECT  
	
	 Convert(nvarchar(20),A.Id) AS   AcademicIdText,	
	CONVERT (nvarchar(20),@rExamId) AS ExamIdText,
	 
	A.Id AS AcademicId,
	YR.AvergeAttendance,
	YR.TotalDays,
	YR.PresentDays,
	
	YR.Month1,
	YR.PresentDays1,
	YR.TotalDays1,
	
	YR.Month2,
	YR.PresentDays2,
	YR.TotalDays2,
	
	YR.Month3,
	YR.PresentDays3,
	YR.TotalDays3,
	
	YR.Month4,
	YR.PresentDays4,
	YR.TotalDays4,
	
	YR.Month5,
	YR.PresentDays5,
	YR.TotalDays5,
	
	YR.Month6,
	YR.PresentDays6,
	YR.TotalDays6,
	
	YR.Month7,
	YR.PresentDays7,
	YR.TotalDays7,
	
	YR.Month8,
	YR.PresentDays8,
	YR.TotalDays8,
	
	YR.Month9,
	YR.PresentDays9,
	YR.TotalDays9,
	
	YR.Month10,
	YR.PresentDays10,
	YR.TotalDays10,
	
	YR.Month11,
	YR.PresentDays11,
	YR.TotalDays11,
	
	YR.Month12,
	YR.PresentDays12,
	YR.TotalDays12
	
from
	sAttendance.tYearlyRegister YR
	INNER JOIN sStudent.tAcademic A ON A.Id=YR.AcademicId

where 

	((YR.AcademicId=@rAcedamicId) OR (@rAcedamicId=0))
	
END
GO
PRINT N'Creating [sAssessment].[pMyResultDetailGet]...';


GO


CREATE PROCEDURE [sAssessment].[pMyResultDetailGet]
	 
	@rExamSubGroupId int = 0,
	@rStudentId bigint =0,
	@rAcademicId bigint = 0,
	@rBatchId int = 0,
	@rResultId bigint=0,
	@rExamId 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,
		R.ResultStatus,
		R.ResultGrade,
		R.RankNumber,
		R.Percentage,
		R.Percentile,	
		ESGM.Id AS ExamSubGroupId,
		BM.Id AS BatchId,
		BM.Title AS BatchName,
		ED.Maximum,
		RD.Obtain,
		SM.Code AS SubjectCode, 
		ISNULL(RD.SubjectGrade,'') AS SubjectGrade
		
FROM 
			sAssessment.tResult R 
			INNER JOIN sAssessment.tResultDetail RD ON RD.ResultId=R.Id
			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.tExamDetail ED ON ED.ExamId=E.Id AND RD.ExamDetailId=ED.Id 
			INNER JOIN sSetup.tClassSubject CS ON ED.ClassSubjectId=CS.Id
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId
			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) or(@rStudentId=0))
		AND ((A.Id = @rAcademicId) OR (@rAcademicId =0))
		AND ((BM.Id = @rBatchId) OR (@rBatchId =0))
		AND (E.IsPublished = 1)  AND ISNULL(E.ReportId,0)  > 0
		AND ((R.Id=@rResultId)OR(@rResultId=0))
		AND ((R.ExamId=@rExamId)OR(@rExamId=0))
	
		 order by ESGM.OrderIndex desc
		
		
		 
		 
		
	
	
		
END
GO
PRINT N'Creating [sAssessment].[pRptCCEResultGet]...';


GO



CREATE PROCEDURE [sAssessment].[pRptCCEResultGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	-- @rOrgId int,
	 @rBatchId int=0,
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rClassSubjectId int=0,
	 @rCCEExamId int=0,
	 @rAcademicId bigint=0,
	 @rStatus int =0 ,
	@rCode nvarchar(20)=''
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	SELECT 
			--@rBuilder1 AS Builder1,
			--@rBuilder2 AS Builder2,
			
			SM.Code,
			ISNULL(SM.FirstName,'')+' '+ISNULL(SM.LastName,'') AS Name,
			ISNULL(SF.FatherName,'') AS FatherName,
			ISNULL(SF.MotherName,'')AS MotherName,
			A.RollNo,
			CCER.AcademicId,
			CONVERT(NVARCHAR,CCER.AcademicId) AS AcademicIdText,
			CONVERT(NVARCHAR,EM.Id)AS ExamIdText,
			CONVERT(NVARCHAR,@rCCEExamId) AS CCEExamIdText,
			 
			 
			ISNULL(SC.ParentContactNo,'') AS ContactNo,
			ISNULL(SC.PresentStreetThree,'')+' '+ISNULL(SC.PresentStreetTwo,'')+' '+ISNULL(SC.PresentStreetThree,'')+' '+ISNULL(SC.PresentCity,'')+' '+ISNULL(SC.PresentState,'') AS PresentAddress,
			--SO.DateOfBirth,
			CONVERT(VARCHAR(10),SO.DateOfBirth,103) AS DateOfBirth,
			CM.DisplayTitle AS Class,
			DM.DisplayTitle AS Division,
			ISNULL(HM.Title,'') AS House,
			ISNULL(CCER.AttendanceTerm1,0) AS AttendanceTerm1,
			ISNULL(CCER.AttendanceTerm2,0) AS AttendanceTerm2,
			ISNULL(CCER.WorkingDaysTerm1,0) AS WorkingDaysTerm1,
			ISNULL(CCER.WorkingDaysTerm2,0) AS WorkingDaysTerm2,
			ISNULL(CCER.Height,0) AS Height,
			ISNULL(CCER.Weight,0) AS Weight,
			ISNULL(CCER.VisionLeft,'') AS VisionLeft,
			ISNULL(CCER.VisionRight,'') AS VisionRight,
			ISNULL(CCER.DentalHygiene,'') AS DentalHygiene,
			ISNULL(BGM.Title,'') AS BloodGroup,
			EM.IsOnPrePrinted,
			EM.IsDisplayBirthDate,
			EM.IsDisplayPhoto,
			EM.IsDisplaySchoolName,			
			EM.IsLockForEdit,
			EM.IsIncludeCoScholastic,
			EM.IsDisplayAttendance,
			EM.IsDisplayHeightWeight,
			EM.IsResultStatus,
			EM.Remark1,
			EM.Remark2,
			EM.Remark3,
			EM.ExamSubGroupId,
			ESM.Code AS ExamSubGroupTitle,	
			EM.DisplayTitle,
			SI.StudentPhoto,
			ISNULL(EM.ExamMaximum,0) AS ExamMaximum,
			ISNULL(EM.FooterAdjustment,0) AS FooterAdjustment,
			ISNULL(EM.DetailAdjustment,0) AS DetailAdjustment,
			ISNULL(EM.TermScopeId,0) AS TermScopeId,	
			TSM.Title AS TermScopeTitle,
		ISNULL(EM.ReportId,0) as ReportId,
			'' AS GradeString,
			A.BatchId,
			BM.Title
			
			
			--CASE WHEN ED.ClassSubjectId=CS.Id THEN 'Yes' ELSE 'false' END AS Selected
      
	FROM 
	
			
            sAssessment.tCCEResult CCER  
            
			INNER JOIN sStudent.tAcademic A ON CCER.AcademicId=A.Id
		
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId
			left Join sStudent.tStudentFamily SF ON SF.StudentId =SM.Id
			LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=A.StudentId
			
			LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
			LEFT JOIN sActivity.tHouseMaster HM ON HM.Id=SO.HouseId
			LEFT JOIN sCommon.tBloodGroupMaster BGM ON BGM.Id=SO.BloodGroupId
			LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=SM.Id
			INNER JOIN sAssessment.tCCEExamSetting CE ON CE.ClassId = CM.Id AND CE.CCEExamId = @rCCEExamId AND CE.BatchId = @rBatchId 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ExamSubGroupId = CE.ExamSubGroupId AND EM.ClassId = CE.ClassId AND EM.BatchId = @rBatchId 
			Inner Join sAssessment.tExamSubGroupMaster ESM ON ESM.Id=EM.ExamSubGroupId
			--INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id
			LEFT JOIN sSetup.tTermScopeMaster TSM ON TSM.Id = EM.TermScopeId

			Inner Join sSetup.tBatchMaster BM ON BM.Id=A.BatchId
			--CROSS JOIN  sAssessment.tcceRptGroup RG ON CCER.AcademicId = RG.Id
			
	WHERE 
			
    A.BatchId = @rBatchId 
		
	AND (A.DivisionId=@rDivisionId OR @rDivisionId=0)
	AND (A.ClassId=@rClassId OR @rClassId=0) 
	 
	AND(CE.CCEExamId = @rCCEExamId OR @rCCEExamId=0)
	AND ( CCER.AcademicId=@rAcademicId OR @rAcademicId=0)
	AND (SM.StatusId=@rStatus OR @rStatus=0) 
	AND ((SM.Code=@rCode) OR (@rCode=''))
	ORDER BY A.RollNo 
END
GO
PRINT N'Creating [sAssessment].[pRptStudentProfileGet]...';


GO




CREATE PROCEDURE [sAssessment].[pRptStudentProfileGet]
	 
	
	
	 @rAcademicId bigint=0,
	 @rExamId int=0
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	SELECT 
			 
			  Convert(nvarchar(20),A.Id) AS   AcademicIdText,	
			CONVERT (nvarchar(20),@rExamId) AS ExamIdText,
			A.Id AS AcademicId,
			SM.Code,
			ISNULL(SM.FirstName,'')+' '+ISNULL(SM.LastName,'')+ ' ' +ISNULL(SM.MiddleName,'') AS Name,
			ISNULL(SF.FatherName,'') AS FatherName,
			ISNULL(SF.MotherName,'')AS MotherName,
			CONVERT(VARCHAR(10),SO.DateOfBirth,103) AS DateOfBirth,
			A.RollNo,
			CM.DisplayTitle + '-' + DM.DisplayTitle AS Class,
			ISNULL(SC.ParentContactNo,'') AS ContactNo,
			HM.Title AS House,
			SI.StudentPhoto,
			EM.FirstName + ' ' + EM.LastName AS ClassTeacherName
			
			--CASE WHEN ED.ClassSubjectId=CS.Id THEN 'Yes' ELSE 'false' END AS Selected
      
	FROM 
 
			sStudent.tAcademic A 
            
			 	
                                             
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId
			left Join sStudent.tStudentFamily SF ON SF.StudentId =SM.Id
			LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=A.StudentId
			LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=SM.Id
			LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
			--Inner Join sSetup.tBatchMaster BM ON BM.Id=A.BatchId
			LEFT JOIN sActivity.tHouseMaster HM ON HM.Id=SO.HouseId
			LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id =DM.InchargeEmployeeId
	
	WHERE 
		((A.Id=@rAcademicId) OR (@rAcademicId=0))
		
END
GO
PRINT N'Creating [sAssessment].[pStudentResultGet]...';


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

BEGIN 		


SELECT

	AD.Id AS AcademicId,
	AD.StudentId,
	AD.BatchId,
	EM.Id AS ExamId,
	ESGM.Title AS ExamName,
	SBM.Code AS Code,
	SBM.Title AS SubjectName,
	RD.Obtain,
	SM.FirstName,
	
	R.TotalMarks,
	
	R.TotalObtain,
	R.ResultStatus,
	R.ResultGrade,
	R.RankNumber,
	R.Percentage,
	R.Percentile,
	
	[sAssessment].[fGetHighestDivisionMark](AD.DivisionId ,RD.ExamDetailId)
			 AS HighestDivisionMark,
	[sAssessment].[fGetAverageDivisionMark](AD.DivisionId ,RD.ExamDetailId)
		 AS DivisionAverage	
	
	from
	sStudent.tStudentMaster SM
	INNER JOIN sStudent.tAcademic AD ON SM.Id = AD.StudentId
	INNER JOIN sAssessment.tExamMaster EM ON EM.BatchId = AD.BatchId AND EM.ClassId = AD.ClassId
	INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId = EM.Id
	INNER JOIN sAssessment.tResult R ON AD.Id = R.AcademicId AND R.ExamId = EM.Id
	INNER JOIN sAssessment.tResultDetail RD ON RD.ExamDetailId = ED.Id AND R.Id = RD.ResultId
	INNER JOIN sSetup.tClassSubject CS ON CS.Id = ED.ClassSubjectId
	INNER JOIN sSetup.tSubjectMaster SBM ON SBM.Id = CS.SubjectId
	INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId
	
	Where
	((AD.Id=@rAcademicId) OR (@rAcademicId=0))
	AND((AD.StudentId = @rStudentId) OR (@rStudentId=0))
	AND ((AD.BatchId =  @rBatchId) OR (@rBatchId=0))
	AND ((EM.Id=@rExamId) OR (@rExamId=0))


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


GO
CREATE PROCEDURE [sAttendance].[pAttendanceListGet]
	 	 
	 	 @rClassId int,
	 	 @rDivisionId int,
	 	 @rStudentCode nvarchar(20),
	 	 @rAttendanceTypeId tinyint,
	 	 @rSubjectId int,
	 	 @rRepeatCount tinyint,
	 	 @rPresent tinyint,
		 @rFromAttendanceDate date,
		 @rToAttendanceDate date,
	 	 @rBatchId int,
	 	 @rOrgId int
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	SELECT 
			SA.AcademicId,
			SA.Code AS StudentCode,
			ISNULL(SA.RollNo,0) as StudentRollNo,
			SA.Name,
			SA.ClassName + '-' + SA.DivisionName AS ClassName,
			SR.AttendanceTypeId,
			ATM.Title AS AttendanceTypeName,
			SR.AttendanceDate,
			SR.SubjectId,
			SR.RepeatCount,
			ISNULL(SR.IsPresent,'true') as IsPresent,
			ISNULL(SR.AbsentReasonId,0) as AbsentReasonId,
			ARM.Title AS AbsentReasonName,
			SM.Title As SubjectName,
			EM.EmployeeId,
			EM.Code AS EmployeeCode,
			EM.EmployeeName
  FROM 
            sStudent.vStudentAcademic SA 
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.AcademicId 
			LEFT JOIN sAttendance.tAttendanceTypeMaster ATM ON ATM.Id=SR.AttendanceTypeId
			LEFT JOIN sAttendance.tAbsentReasonMaster ARM ON ARM.Id=SR.AbsentReasonId
			LEFT JOIN sSetup.tSubjectMaster SM ON SM.Id=SR.SubjectId
			LEFT JOIN sHrm.vExtEmployeeMaster EM ON EM.EmployeeId=SA.InchargeEmployeeId
			
  WHERE 
	 ((SA.ClassId=@rClassId) OR (@rClassId=0))
	  AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
	  AND ((SA.Code=@rStudentCode) OR (@rStudentCode=''))
	  AND ((SR.AttendanceTypeId=@rAttendanceTypeId) OR (@rAttendanceTypeId=0))
	  AND ((SR.SubjectId=@rSubjectId) OR (@rSubjectId=0))
	  AND ((SR.RepeatCount=@rRepeatCount) OR (@rRepeatCount=0))
	  AND ((SR.IsPresent=@rPresent) OR (@rPresent=2))
	  AND ((SR.AttendanceDate >= @rFromAttendanceDate) OR (ISNULL(@rFromAttendanceDate,'') = ''))
	  AND ((SR.AttendanceDate <= @rToAttendanceDate) OR (ISNULL(@rToAttendanceDate,'') = ''))
      AND (SA.OrgId = @rOrgId)
      AND (SA.BatchId = @rBatchID)
      AND (SA.StatusId != 3)
      ORDER BY SA.DivisionOrder, SA.RollNo, SR.AttendanceDate DESC
END
GO
PRINT N'Creating [sAttendance].[pFilterCriteriaAdd]...';


GO


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

	END
	
	
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

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

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sAttendance.tFilterCriteria
	    SET
			  Code=@rCode
	         ,Title=@rTitle
	         ,[IsObsolete] = @rIsObsolete                          
             ,[UpdatedUserId] = @rCreatedUserId
             ,[UpdatedDateTime] = sCommon.fGetDate()          
             
	      WHERE Id = @rId 	   
	      SELECT @lNextNumber AS Result
	
		COMMIT TRANSACTION
	 END  	

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


GO

CREATE PROCEDURE sAttendance.pFilterCriteriaDelete
@rId bigint
AS
BEGIN
BEGIN TRY
	--IF EXISTS (SELECT 1 FROM sAssessment.tExamMaster WHERE GradeSetId= @rId)	
	--	BEGIN
	--		SELECT -101 AS RESULT
	--		RETURN
	--	END
	--IF Exists (Select 1 From sAssessment.tCCECSGroupMaster Where GradeSetId = @rId) 
	--	BEGIN
	--		SELECT -101 AS RESULT
	--		RETURN
	--	END
	--IF EXISTS (SELECT 1 FROM sAssessment.tExamDetail WHERE GradeSetId= @rId)	
	--	BEGIN
	--		SELECT -101 AS RESULT
	--		RETURN
	--	END

	  BEGIN
		DELETE FROM sAttendance.tFilterCriteriaDetail WHERE FilterCriteriaId IN (SELECT ID FROM sAttendance.tFilterCriteria WHERE ID=@rId)
		DELETE	FROM sAttendance.tFilterCriteria WHERE Id=@rId		
		SELECT 1 AS RESULT
	   END
END TRY
BEGIN CATCH
		SELECT -1 AS RESULT
END CATCH
END
GO
PRINT N'Creating [sAttendance].[pFilterCriteriaDetailAdd]...';


GO


CREATE PROCEDURE [sAttendance].[pFilterCriteriaDetailAdd]
	 
	        @rId int
           ,@rFilterCriteriaId int
           ,@rMinimumScore decimal(12,2)
		   ,@rGradeCode nvarchar(20)
		   ,@rGradeTitle nvarchar(50)
		   ,@rGradePoint decimal(6,2)
		   ,@rOrgId int
		   ,@rHighlightColor nvarchar(50)
		  	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

IF(@rId = 0)	
BEGIN
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAttendance.tFilterCriteriaDetail', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sAttendance.tFilterCriteriaDetail
			   (
			    [Id]
			   ,[FilterCriteriaId] 
			   ,[MinimumScore] 
			   ,[GradeCode]
			   ,[GradeTitle]
			   ,[GradePoint]
			  
			  ,[HighlightColor]
			   )
		 VALUES
			   (
				@lNextNumber
			   ,@rFilterCriteriaId
			   ,@rMinimumScore
			   ,@rGradeCode
			   ,@rGradeTitle
			   ,@rGradePoint
			   ,@rHighlightColor
			   )
		    SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION         
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sAttendance.tFilterCriteriaDetail
	    SET
			  --Number=@rNumber
	         --,Code=@rCode
	          FilterCriteriaId=@rFilterCriteriaId
	         ,MinimumScore=@rMinimumScore
	         ,GradeCode=@rGradeCode
			 ,GradeTitle=@rGradeTitle
			 ,GradePoint =@rGradePoint		
			 ,HighlightColor=@rHighlightColor             
	      WHERE Id = @rId 	   
	      SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION
	 END  
		
	--END
--END	
COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Creating [sAttendance].[pFilterCriteriaDetailGet]...';


GO

CREATE PROCEDURE [sAttendance].[pFilterCriteriaDetailGet]
	 @rFilterCriteriaId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 		
		
	SELECT 
			FC.TITLE,
			FC.Code,
			FCD.FilterCriteriaId,
			FCD.Id,
			FCD.GradeCode,
			FCD.GradeTitle,
			FCD.MinimumScore,
			FCD.GradePoint,
			FC.IsObsolete,
			FCD.HighlightColor
			
  FROM 
			sAttendance.tFilterCriteria FC
			INNER JOIN sAttendance.tFilterCriteriaDetail FCD ON FCD.FilterCriteriaId=FC.id
WHERE 
			(FCD.FilterCriteriaId=@rFilterCriteriaId OR @rFilterCriteriaId=0)  order by FCD.MinimumScore Desc
	
		
END
GO
PRINT N'Creating [sAttendance].[pFilterCriteriaGet]...';


GO


CREATE PROCEDURE sAttendance.pFilterCriteriaGet
          
           --@rId bigint,
           @rCode nvarchar(20),
           @rTitle nvarchar(100),
           @rOrgId int           
           --@rIsWildCardSearch bit
          
AS
SET NOCOUNT ON

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

BEGIN
SELECT FC.Id as FilterCriteriaId
	  ,FC.Title as Title
	  ,FC.Code as Code
      ,FC.IsObsolete as IsObsolete
     
  FROM sAttendance.tFilterCriteria FC 
        
  WHERE 
	--	 CCM.Id = @rId OR @rId = 0
	--AND 
	((FC.Title Like @rTitle)OR(ISNULL(@rTitle,'') = ''))
		AND OrgId = @rOrgId

	--AND  CCM.IsObsolete = 0
         
END
GO
PRINT N'Creating [sAttendance].[pFilterStudentGet]...';


GO

CREATE PROCEDURE [sAttendance].[pFilterStudentGet]
	 	 
		 @rClassId int=0,
		 @rDivisionId int=0,
		 @rStudentCode nvarchar(20)='',	
	 	 @rAttendanceTypeId tinyint=0,
	     @rSubjectId int=0,
	 	 @rPresent tinyint=0,
		 @rFromAttendanceDate date='',
		 @rToAttendanceDate date='',
	 	 @rBatchId int,
	 	 @rOrgId int,
	 	-- @rIndicator nvarchar(20)='',
	 	 @rFilterxml nvarchar(max)

	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rFilterxml

BEGIN 
	SELECT 
			--AcademicId,
			ClassId,
			DivisionId,
			Code AS StudentCode,
			ISNULL(RollNo,0) as StudentRollNo,
			Name,
			ClassName + '-' + DivisionName AS ClassName,
			0 AS AverageAttendance,
			'' AS AttendanceStatus
			--,
			--MonthNumber,
			--YearNumber
			
			
  FROM 
		 sStudent.vStudentAcademic SA 
		

WHERE 
		((ClassId=@rClassId) OR (@rClassId=0))
	 AND ((DivisionId=@rDivisionId) OR (@rDivisionId=0))
	 --AND ((Code=@rStudentCode) OR (@rStudentCode=''))
	 -- AND ((AttendanceDate >= @rFromAttendanceDate) OR (ISNULL(@rFromAttendanceDate,'') = ''))
	 -- AND ((AttendanceDate <= @rToAttendanceDate) OR (ISNULL(@rToAttendanceDate,'') = ''))
     AND  (OrgId = @rOrgId)
      AND (BatchId = @rBatchId)
    
END
GO
PRINT N'Creating [sAttendance].[pMonthlyRegisterDelete]...';


GO
CREATE PROCEDURE [sAttendance].[pMonthlyRegisterDelete]
	 
	@rClassId int, 
	@rDivisionId int,
	@rBatchId int,
	@rAttendanceTypeId tinyint,
	@rSubjectId int,
	@rForYear int,
	@rForMonth int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
BEGIN TRY
	 BEGIN TRANSACTION	

			DELETE MR
			FROM sAttendance.tMonthlyRegister MR
				INNER JOIN sStudent.tAcademic A
				ON MR.AcademicId= A.Id
				
			WHERE
			
			A.DivisionId = @rDivisionId
			AND A.ClassId = @rClassId
			AND A.BatchId = @rBatchId
			AND MR.AttendanceTypeId = @rAttendanceTypeId
			AND ((MR.SubjectId=@rSubjectId) OR (@rSubjectId=0))
			AND MR.ForYear = @rForYear
			AND MR.ForMonth = @rForMonth
		
			SELECT 1 AS Result
		
	COMMIT TRANSACTION
END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
			SELECT -1 AS Result
	END CATCH			
END
GO
PRINT N'Creating [sAttendance].[pStudetntAttendanceGet]...';


GO

CREATE PROCEDURE [sAttendance].[pStudetntAttendanceGet]
	 	 
	 	  @rForMonth smallint,
	      @rForYear smallint,
	      @rAcademicId bigint,
	      @rAttendanceTypeId smallint,
	      @rBatchId int = 0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	Select 
			DAY(SR.AttendanceDate) AS DayNo,
			(CASE SR.IsPresent WHEN 1 THEN 'P' 
				WHEN 0 THEN 'A'
				END )AS  Presence,
			OM.WeekOffs
			
		
	From  
			sStudent.vStudentAcademic SA
            INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.AcademicId
            INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
	
	WHERE
			SR.AttendanceTypeId=@rAttendanceTypeId
		AND SR.AcademicId=@rAcademicId
		AND YEAR(SR.AttendanceDate)=@rForYear
		AND MONTH(SR.AttendanceDate)=@rForMonth
		AND SA.BatchId=@rBatchId
		
		ORDER BY DayNo ASC
	
END
GO
PRINT N'Creating [sCommunication].[pMyUpdateGet]...';


GO
CREATE PROCEDURE [sCommunication].[pMyUpdateGet]
	 
@rOrgId int,	 
@rBatchId int,
@rOrgGroupBatchId int,
@rUserId bigint,
@rUserSourceId bigint,
@rUserSourceTypeId int,
@rSyncedAssignmentId bigint,
@rSyncedCircularId bigint,
@rSyncedPollId bigint,
@rSyncedQueryCommentId bigint,
@rSyncedNewsId bigint,
@rSyncedBlogId bigint,
@rSyncedBehaviourId bigint,
@rSyncedActivityId bigint,
@rSyncedResultId bigint,
@rSyncedAssignTaskId bigint,
@rSyncedPhotoCategoryId int


	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	DECLARE @lAcademicId bigint
	DECLARE @lScopeSourceId int
	DECLARE @lScopeSourceTypeId int
	
	DECLARE @lAssignmentStatus bit=0
	DECLARE @lCircularStatus bit=0
	DECLARE @lPollStatus bit=0
	DECLARE @lQueryStatus bit=0
	DECLARE @lBlogStatus bit=0
	DECLARE @lNewsStatus bit=0
	DECLARE @lBehaviourStatus bit=0
	DECLARE @lActivityStatus bit=0
	DECLARE @lResultStatus bit=0
	DECLARE @lAssignTaskStatus bit=0
	DECLARE @lPhotoCategoryStatus bit=0
	

IF(	@rUserSourceTypeId = 2003)	
BEGIN
SELECT @lAcademicId = Id, @lScopeSourceId = DivisionId FROM sStudent.tAcademic WHERE StudentId = @rUserSourceId AND BatchId = @rBatchId
SET @lScopeSourceTypeId = 2005
END
ELSE
BEGIN
SELECT @lScopeSourceId = OrganizationDepartmentId FROM sHrm.tEmployeeJobDetail WHERE EmployeeId = @rUserSourceId
SET @lScopeSourceTypeId = 2004
END

 
IF EXISTS(SELECT 1 FROM sCommunication.tAssignmentScope WHERE AssignmentId > @rSyncedAssignmentId AND SourceTypeId = @lScopeSourceTypeId AND SourceId = @lScopeSourceId)
SET @lAssignmentStatus = 1

IF EXISTS(SELECT 1 FROM sCommunication.tCircularScope WHERE  CircularId > @rSyncedCircularId AND SourceTypeId = @lScopeSourceTypeId AND SourceId = @lScopeSourceId)
SET @lCircularStatus = 1

IF EXISTS(SELECT 1 FROM sCommunication.tPollMember WHERE PollId > @rSyncedPollId AND SourceTypeId = @lScopeSourceTypeId AND SourceId = @lScopeSourceId)
SET @lPollStatus = 1

IF EXISTS(SELECT 1 FROM sCommunication.tBlogScope BS INNER JOIN sCommunication.tBlog B
ON B.Id = BS.BlogId
WHERE B.IsPublish = 1 AND BS.BlogId > @rSyncedBlogId AND BS.SourceTypeId = 1016 AND BS.SourceId = @rOrgId )
SET @lBlogStatus = 1

IF EXISTS(SELECT 1 FROM sCommunication.tNewsScope WHERE NewsId > @rSyncedNewsId AND SourceTypeId = 1016 AND SourceId = @rOrgId )
SET @lNewsStatus = 1

--IF EXISTS(SELECT 1 FROM sCommunication.tNewsScope WHERE NewsId > @rSyncedNewsId AND SourceTypeId = @rOrgId AND SourceId = 1016)
--SET @lNewsStatus = 1

IF EXISTS(SELECT 1 FROM sCommunication.tUploadResult WHERE Id > @rSyncedResultId AND DivisionId = @lScopeSourceId AND BatchId=@rBatchId AND IsObsolete=0 )
SET @lResultStatus = 1

IF EXISTS(SELECT 1 FROM  
sCommunication.tPhotoCategoryMaster PCM
INNER JOIN sCommunication.tPhotoCategoryOrg PCO 
ON PCM.Id=PCO.PhotoCategoryId WHERE PCM.Id > @rSyncedPhotoCategoryId AND PCO.OrgId = @rOrgId  AND PCM.IsObsolete=0 )
SET @lPhotoCategoryStatus = 1


IF EXISTS(SELECT 1 FROM sCommunication.tAssignTask WHERE  Id > @rSyncedAssignTaskId AND AssignedToSourceTypeId = @rUserSourceTypeId 
AND AssignedToSourceId = @rUserSourceId AND IsCompleted=0 AND IsClosed=0 AND OrgId=@rOrgId)
SET @lAssignTaskStatus = 1


IF EXISTS(SELECT 1 FROM sActivity.tActivityParticipant WHERE ActivityId > @rSyncedActivityId AND SourceTypeId = @rUserSourceTypeId AND SourceId = @rUserSourceId)
SET @lActivityStatus = 1



IF EXISTS(SELECT 1 FROM sCommunication.tBehaviour WHERE Id > @rSyncedBehaviourId AND AcademicId = @lAcademicId )
SET @lBehaviourStatus = 1

IF EXISTS(SELECT 1 FROM sCommunication.tQuery Q INNER JOIN sCommunication.tQueryComment QC ON Q.Id=QC.QueryId
WHERE Q.CreatedUserId=@rUserId AND Q.IsUserView=0 AND QC.Id>@rSyncedQueryCommentId AND QC.CreatedUserId <> @rUserSourceId)
SET @lQueryStatus = 1
 
 
 
CREATE TABLE #Module (
Id int,
Title nvarchar(20),
IsNew bit )
INSERT INTO #Module VALUES (20085,'Circular',@lCircularStatus)
INSERT INTO #Module VALUES (20088,'Query',@lQueryStatus)
INSERT INTO #Module VALUES (20099,'Blog',@lBlogStatus)
INSERT INTO #Module VALUES (20104,'News',@lNewsStatus)
INSERT INTO #Module VALUES (20172,'AssignTask',@lAssignTaskStatus)
INSERT INTO #Module VALUES (20183,'Gallery',@lPhotoCategoryStatus)
INSERT INTO #Module VALUES (20204,'Poll',@lPollStatus)
INSERT INTO #Module VALUES (20093,'Assignment',@lAssignmentStatus)
INSERT INTO #Module VALUES (20209,'Activity',@lActivityStatus)
INSERT INTO #Module VALUES (20130,'Behaviour',@lBehaviourStatus)
INSERT INTO #Module VALUES (20180,'Result',@lResultStatus)
 
 SELECT * FROM #Module
 
--SELECT @lAssignmentStatus AS Assignment,@lCircularStatus AS Circular,@lPollStatus AS Poll,@lQueryStatus AS Query,
--@lBlogStatus AS Blog,@lNewsStatus AS News,@lBehaviourStatus AS Behaviour,
--@lActivityStatus AS Activity,@lResultStatus AS Result,@lAssignTaskStatus AS AssignTask,@lPhotoCategoryStatus AS Gallery


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


GO
/****** Object:  StoredProcedure [sSupport].[pClaimAdd]    Script Date: 08/27/2013 10:32:12 ******/

CREATE PROCEDURE [sFee].[pAssignOptionalFeeHeadAdd]
		  
           @rSourceTypeId int,
           @rSourceId bigint,
           @rBatchId int,
           @rClassId int,
           @rAdmissionCategoryId int,
           @rFeeHeadId int

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
BEGIN TRY
	 BEGIN TRANSACTION	
	 
	DELETE FO FROM 
	
	SFee.tFeeOptional FO
	INNER JOIN sFee.tFeeSetup FS ON FO.FeeSetupId = FS.Id AND FO.BatchId = FS.BatchId
	INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS.FeeId
	INNER JOIN sFee.tFeeHeadMaster FHM ON FM.FeeHeadId = FHM.Id	 	 
		WHERE
	FHM.Id = @rFeeHeadId
	AND FS.BatchId = @rBatchId
	AND FS.ClassId = @rClassId
	AND FS.AdmissionCategoryId =@rAdmissionCategoryId 
	AND FS.IsOptional=1
	AND FO.SourceId = @rSourceId
	AND FO.SourceTypeId = @rSourceTypeId
	AND FO.BatchId  = @rBatchId
	 
	INSERT INTO sFee.tFeeOptional
		(
		   FeeSetupId,
		   SourceTypeId,
		   SourceId,
		   BatchId
		)
	 
			SELECT
				FS.Id,  
				@rSourceTypeId,
				@rSourceId,			 
				@rBatchId
			FROM 
				sFee.tFeeSetup FS
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS.FeeId
				INNER JOIN sFee.tFeeHeadMaster FHM ON FM.FeeHeadId = FHM.Id	 
				
	WHERE
		FHM.Id = @rFeeHeadId
		AND FS.BatchId = @rBatchId
		AND FS.ClassId = @rClassId
		AND FS.AdmissionCategoryId =@rAdmissionCategoryId 
		AND FS.IsOptional=1
		
		SELECT 1 AS Result
		
	COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Creating [sFee].[pRptFeePendingAllBatchGet]...';


GO

CREATE PROCEDURE [sFee].[pRptFeePendingAllBatchGet]
		@rReportId int=0,
		@rReceiptBookId int=0,
		@rAdmissionCategoryId int=0,
		@rClassId int=0,
		@rDivisionId int=0,
		@rUptoDate date='',
		@rBatchId int='',
		@rUserId bigint=0,
		@rBuilder1 nvarchar(max)='',	
		@rBuilder2 nvarchar(max)='',
		@rIsDetail bit=0,
		@rOrgId int=0,
		@rOrgGroupBatchId int=0,
		@rStatusId int=0,
		@rCommonBatch nvarchar(100)='',
		@rDepartmentId int=0,
		@rFromRollNo int=0,
	    @rToRollNo int=0,
	    @rCode nvarchar(20)='',
	    @rIsFilter bit=0,
		@rIsHeader bit=0,		
		@rCreatedUserName nvarchar(20) = ''
	    
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 	
	
	DECLARE @p as TempPendingFee
	
	INSERT INTO  @p 
	 
	SELECT 
		--@rBuilder1 AS Builder1,
		--@rBuilder2 AS Builder2,
		--@rIsDetail AS IsDetail,
		--@rIsFilter As IsFilter,
		--@rIsHeader As IsHeader,
		SA.AcademicId,
		SA.RollNo,
		SA.Name,
		SA.Code,
		SA.ClassId,
		SA.DivisionId,
		SA.ClassName,
		SA.DivisionName,
		SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
		FS.Id AS FeeSetupId,		
		ISNULL(FS.IsVariable,0)AS IsVariable,
		ISNULL(FS.Amount,0)AS Amount,
		ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
		ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
		ISNULL(FA.VariableAmount,0.00)AS FAAmount,
		ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
		ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
		ISNULL(R.PaidAmount,0) AS PaidAmount,
		ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)AS PendingAmount,
		ISNULL(FA.Remark,'') AS Remark,
		FS.ReceiptBookId,
		FS.FeeName,
		FS.FeeCode,
		SA.OrgId,
		O.Title AS OrgName,
		O.OrderIndex AS OrgOrderIndex,
		ISNULL(RBM.Title,'') AS ReceiptBookTitle,
		ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
		SA.BatchId,
		BM.Title AS BatchName
			
  FROM 
  
			 sStudent.vStudentAcademic SA
		INNER JOIN 
		(
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName,
				FM.Code AS FeeCode
			FROM sFee.tFeeSetup FS1
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
				AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0))
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			WHERE 
			    ((SA1.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				AND	((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=0)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				
				UNION ALL
				
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName,
				FM.Code AS FeeCode
			FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO
			ON FO.FeeSetupId=FS1.Id
	    INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
			AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) 
			AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
		WHERE
		        ((SA1.OrgGroupBatchId = @rOrgGroupBatchId)  OR (@rOrgGroupBatchId=0))
				AND ((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=1)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				
		) FS ON FS.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
		LEFT JOIN
		(
		    SELECT 
					ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
		    FROM
				sFee.tReceipt R 
				INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId				
				AND (SA1.ClassId=@rClassId OR @rClassId=0) 
				AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
				
			WHERE		
				(R.SourceTypeId = 2001)
				AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND (R.IsObsolete = 0) 
				AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				GROUP BY FeeSetupId,R.SourceId
				
				
		
		) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
		 INNER JOIN sSetup.tOrganizationMaster O ON
		 SA.OrgId = O.Id
		 INNER JOIN sFee.tReceiptBookMaster RBM 
			ON FS.ReceiptBookId=RBM.Id
		 INNER JOIN sSetup.tBatchMaster BM 
			ON BM.Id=SA.BatchId	
		 
		
	WHERE	
			((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
			AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0)) 
			AND (SA.StatusId = @rStatusId OR @rStatusId=0)
			AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
			AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
			AND ((SA.Code=@rCode) OR (@rCode=''))
			AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
			AND (ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00) -ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00) != 0)			
			Order by SA.RollNo

			SELECT
			OrgId,			 
			ReceiptBookId,
			AcademicId,
			DivisionId,
			ClassDivision,
			RollNo, 
			Name,
			Code,
			ReceiptBookTitle,
			OrgName,
			SUM(PendingAmount) AS PendingAmount, 
			[sFee].[fPendingFeeNamesGet](AcademicId,ReceiptBookId,	@p) AS PendingFeeName,
			ReceiptOrderIndex,
			BatchId,
			BatchName
			
			FROM @p 
			
			GROUP By ReceiptBookId,OrgId,AcademicId,DivisionId,BatchId,
			ClassDivision,RollNo, Name,Code,ReceiptBookTitle,OrgName,ReceiptOrderIndex,BatchName
			ORDER BY AcademicId
 
END
GO
PRINT N'Creating [sFee].[pRptFeePendingWithFeeNameGet]...';


GO

CREATE PROCEDURE [sFee].[pRptFeePendingWithFeeNameGet]
		@rReportId int=0,
		@rReceiptBookId int,
		@rAdmissionCategoryId int,
		@rClassId int,
		@rDivisionId int,
		@rUptoDate date,
		@rBatchId int,
		@rUserId bigint,
		@rBuilder1 nvarchar(max),
		@rBuilder2 nvarchar(max),
		@rIsDetail bit,
		@rOrgId int,
		@rOrgGroupBatchId int,
		@rStatusId int,
		@rCommonBatch nvarchar(100),
		@rDepartmentId int=0,
		@rFromRollNo int=0,
	    @rToRollNo int=0,
	    @rCode nvarchar(20)='',
	    @rIsFilter bit=0,
		@rIsHeader bit=0,		
		@rCreatedUserName nvarchar(20) = ''
	    
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 	


--CREATE TABLE #TempStudent
--	(
--	AcademicId bigint,
--	ClassId int,
--	BatchId int,
--	a
--	)
--	SELECT AcademicId

 
	--CREATE TYPE  TempPendingFee AS TABLE
	--(
	--AcademicId bigint
	--,
	--RollNo int,
	--Name nvarchar(200),
	--Code nvarchar(20),
	--ClassId int,
	--DivisionId int,
	--ClassName nvarchar(100),
	--DivisionName nvarchar(100),
	--ClassDivision nvarchar(100),
	--FeeSetupId int,
	--IsVariable int,
	--Amount Decimal(12,2),
	--StartDate date,
	--EndDate date,
	--FAAmount Decimal(12,2),
	--DiscountAmount Decimal(12,2),
	--AdditionalAmount Decimal(12,2),
	--PaidAmount Decimal(12,2),
	--PendingAmount Decimal(12,2),
	--Remark nvarchar(200),
	--ReceiptBookId int,
	--FeeName nvarchar(100),
	--FeeCode nvarchar(100),
	--OrgId int,
	--OrgName nvarchar(200),
	--OrgOrderIndex int,
	--ReceiptBookTitle nvarchar(200),
	--ReceiptOrderIndex int	
	--)
	
	DECLARE @p as TempPendingFee
	
	INSERT INTO  @p 
	 
	SELECT 
		--@rBuilder1 AS Builder1,
		--@rBuilder2 AS Builder2,
		--@rIsDetail AS IsDetail,
		--@rIsFilter As IsFilter,
		--@rIsHeader As IsHeader,
		SA.AcademicId
		,
		SA.RollNo,
		SA.Name,
		SA.Code,
		SA.ClassId,
		SA.DivisionId,
		SA.ClassName,
		SA.DivisionName,
		SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
		FS.Id AS FeeSetupId,		
		ISNULL(FS.IsVariable,0)AS IsVariable,
		ISNULL(FS.Amount,0)AS Amount,
		ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
		ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
		ISNULL(FA.VariableAmount,0.00)AS FAAmount,
		ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
		ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
		ISNULL(R.PaidAmount,0) AS PaidAmount,
		ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)AS PendingAmount,
		ISNULL(FA.Remark,'') AS Remark,
		FS.ReceiptBookId,
		FS.FeeName,
		FS.FeeCode,
		SA.OrgId,
		O.Title AS OrgName,
		O.OrderIndex AS OrgOrderIndex,
		ISNULL(RBM.Title,'') AS ReceiptBookTitle,
		ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
		0 AS BatchId,
		'' AS BatchName
			
  FROM 
  
			 sStudent.vStudentAcademic SA
		INNER JOIN 
		(
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName,
				FM.Code AS FeeCode
			FROM sFee.tFeeSetup FS1
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
				AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0))
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			WHERE 
			     (SA1.OrgGroupBatchId = @rOrgGroupBatchId)
				AND	((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=0)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				
				UNION ALL
				
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName,
				FM.Code AS FeeCode
			FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO
			ON FO.FeeSetupId=FS1.Id
	    INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
			AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) 
			AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
		WHERE
		       (SA1.OrgGroupBatchId = @rOrgGroupBatchId)
				AND ((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=1)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				
		) FS ON FS.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
		LEFT JOIN
		(
		    SELECT 
					ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
		    FROM
				sFee.tReceipt R 
				INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId				
				AND (SA1.ClassId=@rClassId OR @rClassId=0) 
				AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
				
			WHERE		
				(R.SourceTypeId = 2001)
				AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND (R.IsObsolete = 0) 
				AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId)  )
				AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				GROUP BY FeeSetupId,R.SourceId
				
				
		
		) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
		 INNER JOIN sSetup.tOrganizationMaster O ON
		 SA.OrgId = O.Id
		 INNER JOIN sFee.tReceiptBookMaster RBM 
			ON FS.ReceiptBookId=RBM.Id
		 
		
	WHERE	
			(SA.OrgGroupBatchId = @rOrgGroupBatchId)
			AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0)) 
			AND (SA.StatusId = @rStatusId OR @rStatusId=0)
			AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
			AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
			AND ((SA.Code=@rCode) OR (@rCode=''))
			AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
			AND (ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00) -ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00) != 0)			
			Order by SA.RollNo

			SELECT
			OrgId,			 
			ReceiptBookId,
			AcademicId,
			DivisionId,
			ClassDivision,RollNo, Name,Code,ReceiptBookTitle,OrgName,
			SUM(PendingAmount) AS PendingAmount, 
			[sFee].[fPendingFeeNamesGet](AcademicId,ReceiptBookId,	@p) AS PendingFeeName,
			ReceiptOrderIndex
			FROM @p 
			GROUP By ReceiptBookId,OrgId,AcademicId,DivisionId,
			ClassDivision,RollNo, Name,Code,
			ReceiptBookTitle,OrgName,ReceiptOrderIndex	
			ORDER BY AcademicId
 
END
GO
PRINT N'Creating [sFee].[pRptFeeReceiptTotalGet]...';


GO

CREATE PROCEDURE [sFee].[pRptFeeReceiptTotalGet]
		
		 
		
		@rFromDate date,
		@rToDate date,		
		@rOrgGroupBatchId int
		 
	    
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 	
	SELECT 
	 
		 
		 
		 
		ISNULL(RBM.Title,'') AS ReceiptBookTitle,
		ISNULL(RBM.Id,'0') As ReceiptBookId,		 
		SUM(ReceiptAmount) AS TotalAmount,
		RBM.OrderIndex
		 
			
  FROM 
			sFee.tReceipt R 
		INNER JOIN sFee.tReceiptBookMaster RBM 
			ON RBM.Id=R.ReceiptBookId
			
WHERE 
	R.SourceTypeId = 2001	 
	AND ((R.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
	AND ((R.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
	AND R.OrgGroupBatchId = @rOrgGroupBatchId	
	GROUP BY RBM.ID,RBM.Title,RBM.OrderIndex
	 
END
GO
PRINT N'Creating [sFee].[pXMLWinFeeDetailAdd]...';


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

SET NOCOUNT ON

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

	
	UPDATE sFee.tWinfeeDetail 
	SET	AcademicId=A1.AcademicId,
		feeName=A1.feeName,
		choice=A1.choice,
		Amount=A1.Amount,
		exemption=A1.exemption,
		paid=A1.paid,
		scheduleDate=A1.scheduleDate,
		ReceiptBookName=A1.ReceiptBookName,
		UpdatedDateTime=A1.UpdatedDateTime,
		BatchId=A1.BatchId	
	FROM
	(
		SELECT	
		feeChoiceId,	
		AcademicId,
		feeName,
		choice,
		Amount,
		exemption,
		paid,
		scheduleDate,
		ReceiptBookName,
		UpdatedDateTime,
		BatchId	
		FROM OPENXML (@intDoc, '/Table/UploadFee', 1)
		WITH
		(
			feeChoiceId int '@feeChoiceId',
			AcademicId bigint '@AcademicId',
			feeName nvarchar(100) '@feeName',
			choice int '@choice',
			Amount decimal(12,2) '@Amount',
			exemption decimal(12,2) '@exemption',
			paid decimal(12,2) '@paid',
			scheduleDate bigint '@scheduleDate',
			ReceiptBookName nvarchar(100) '@ReceiptBookName',
			UpdatedDateTime Datetime '@UpdatedDateTime',
			BatchId int '@BatchId'
		))A1 WHERE sFee.tWinfeeDetail.feeChoiceId = sCommon.fGetBigIntIdForOrg(convert(bigint,RIGHT(A1.feeChoiceId,5)),@rOrgId)


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

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


GO
CREATE PROCEDURE [sHrm].[pEmployeeIcardOrgAdd]
	 
	@rIcardTemplateId int,
	@rOrgId int,
	@rICardBackground varbinary(max)=null,
	@rICardBackBackGround varbinary(max)=null,
	@rICardOrgTitle nvarchar(200)='',
	@rICardAddress1 nvarchar(200)='',
	@rICardAddress2 nvarchar(200)='',
	@rICardAddress3 nvarchar(200)='',
	@rLabelColor nvarchar(20)='',
	@rDetailColor nvarchar(20)='',
	@rHeaderColor nvarchar(20)=''
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

			IF (@rIcardTemplateId=0)
			BEGIN
					DELETE FROM sHrm.tEmployeeICardOrg WHERE OrgId=@rOrgId
					SELECT -103 AS Result
					RETURN
			END 
			
	BEGIN TRY
		BEGIN TRANSACTION
		
		
	IF NOT EXISTS (SELECT 1 FROM sHrm.tEmployeeICardOrg WHERE OrgId=@rOrgId)	
	
	
	   BEGIN
			INSERT INTO sHrm.tEmployeeICardOrg
			(
				EmployeeIcardTemplateId,
				OrgId,
				ICardBackground,
				ICardBackBackGround
			)
			VALUES
			(
				@rIcardTemplateId,
				@rOrgId,
				@rICardBackground,
				NULL
			)
			SELECT 1 AS Result	 
		END	 
	ELSE
		BEGIN
			UPDATE sHrm.tEmployeeICardOrg
			SET
				EmployeeIcardTemplateId=@rIcardTemplateId,
				ICardBackground=@rICardBackground,
				ICardBackBackGround=@rICardBackBackGround,
				IcardOrgTitle=@rICardOrgTitle,
				IcardAddress1=@rICardAddress1,
				IcardAddress2=@rICardAddress2,
				IcardAddress3=@rICardAddress3,
				LabelColor=@rLabelColor,
				DetailColor=@rDetailColor,
				HeaderColor=@rHeaderColor
				
			WHERE OrgId=@rOrgId
			SELECT 11 AS Result
		END  
		COMMIT TRANSACTION
			END TRY
		BEGIN CATCH 
			ROLLBACK TRANSACTION
			SELECT -1 AS Result
		END CATCH	
END
GO
PRINT N'Creating [sHrm].[pRptEmployeeProfileGet]...';


GO

CREATE PROCEDURE [sHrm].[pRptEmployeeProfileGet]
(

		@rBuilder1 nvarchar(max)='',
		@rBuilder2 nvarchar(max)='',
		@rPayrollId int,
		@rPayrollGroupId int,
		@rPayrollYearId int,
    	@rEmployeeId bigint,
		@rEmployeeCode nvarchar(200),
		@rEmployeeName nvarchar(200)
)
AS
SET NOCOUNT ON

BEGIN
		SELECT 
				@rBuilder1 AS Builder1,
				@rBuilder2 AS Builder2,
				EM.EmployeeId AS EmployeeId,
				ISNULL(EM.FirstName, '') + ' '+ ISNULL(EM.LastName, '') AS Name,
				DM.Id AS DepartmentId,
				DM.Title AS DepartmentName,
				CONVERT(date,EJD.DateOfJoining) AS DateOfJoining,
				EM.Code AS Code,
				CONVERT(date,EJD.DateOfleaving) AS DateOfleaving,
				EDM.Title AS Designation,
				EPD.Qualification,
				EM.GenderTitle,
				CONVERT(date,EPD.DateOfBirth) AS DateOfBirth,
				EPD.UIDNumber,
				EC.PersonalEmail AS Email,
				ESO.BankName,
				ESO.AccountNumber,
				ESO.EPFNumber,
				ESO.PanNumber,
				EC.MobileNumber,
				ISNULL(DATEDIFF(YY,EJD.DateOfJoining,EJD.DateOfleaving),'')AS EXPYEAR,
				ISNULL(DATEDIFF(MM,EJD.DateOfJoining,EJD.DateOfleaving),'') AS EXPMONTH
		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.tPayrollYearMaster PY ON PP.PayrollYearId = PY.Id
			INNER JOIN  sHrm.tEmployeeCommunications EC ON EC.EmployeeId=EM.EmployeeId
			INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId=EM.EmployeeId
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.EmployeeId
			INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EJD.OrganizationDepartmentId
			INNER JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id=EJD.EmployeeDesignationId
			INNER JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.EmployeeId=PPE.EmployeeId	
		WHERE 
				(EM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
			AND((PY.PayrollId=@rPayrollId) OR (@rPayrollId=0))
			 AND (PPE.PayrollGroupId = @rPayrollGroupId OR @rPayrollGroupId = 0) 
			 AND ((EM.Code Like '%' +  @rEmployeeCode + '%' ) OR (@rEmployeeCode = ''))
			 AND ((EM.EmployeeName Like '%' + @rEmployeeName  + '%') OR (@rEmployeeName = ''))
			 AND (PP.PayrollYearId = @rPayrollYearId OR @rPayrollYearId = 0) 
			  
		END
GO
PRINT N'Creating [sMis].[pRptCastCategorywiseStudentGet]...';


GO


 
CREATE PROCEDURE [sMis].[pRptCastCategorywiseStudentGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
   	 @rClassId int,
   	 @rDivisionId int,
	@rDepartmentId int,
	@rOrgMainGroupId int,
	@rOrgSubGroupId int,
	@rOrgId smallint,
	@rOrgGroupBatchId int,
	
	@rStrOrgMainGroupId nvarchar(max),
	@rStrOrgSubGroupId nvarchar(max),
	@rStrOrgId nvarchar(max),
	@rStrDepartmentId nvarchar(max),
	@rStrClassId nvarchar(max),
	@rOrgGroupId int,
	@rIsTestMainGroup bit =0,
	@rIsTestSubGroup bit =0,	
	@rIsTestOrg bit=0,
	@rIsTestDepartment bit=0,
	@rIsTestClass bit=0,
	@rIsTestDivision bit=0,
	
	@rReportId int =0
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			@rIsTestMainGroup AS IsTestMainGroup,
			@rIsTestSubGroup AS IsTestSubGroup,
			@rIsTestOrg AS IsTestOrg,
			@rIsTestDepartment AS IsTestDepartment,
			@rIsTestClass AS IsTestClass,
			@rIsTestDivision AS IsTestDivision ,
			DV.Id AS DivisionId,
			CM.Id AS ClassId,
			CM.DisplayTitle AS Class,
			DM.DisplayTitle AS Department,
			CM.DisplayTitle+' '+DV.DisplayTitle AS ClassDivision,
			
			ISNULL(GM.Title,'') As Gender,
			A.Id AS AcademicId,
			--OBM.Title,
			
			DV.DisplayTitle AS Division,
		
			OMGM.Id AS OrgMainGroupId,
			OMGM.Title AS OrgMainGroupTitle,
			OSGM.Id AS OrgSubGroupId,
			OSGM.Title AS OrgSubGroupTitle,
			OM.Id AS OrgId,
			OM.DisplayTitle AS OrgDisplayTitle,
			CASE WHEN  @rReportId=20621	 -- Caste Category wise Summary
			THEN ISNULL(CCM.Title,'') 
		    WHEN  @rReportId=20623 -- Religionwise Summary
			THEN ISNULL(RM.Title,'')
			END AS Head,
			DV.OrderIndex AS DivisionOrder
			FROM 
			
			
			sStudent.tAcademic A	
			INNER JOIN	sSetup.tClassMaster CM	ON CM.Id=A.ClassId	
			INNER JOIN sSetup.tDivisionMaster DV ON DV.Id=A.DivisionId
			LEFT JOIN sStudent.tStudentOther SO ON A.StudentId=SO.StudentId
			INNER JOIN sCommon.tGenderMaster GM ON GM.Id=SO.GenderId	
				
			LEFT JOIN sCommon.tCastCategoryMaster CCM ON CCM.Id=SO.CastCategoryId
			LEFT JOIN sCommon.tReligionMaster RM ON RM.Id=SO.ReligionId		
			INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=CM.DepartmentId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = DM.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OG ON OG.Id = OM.OrgGroupId
			INNER JOIN sSetup.tOrgSubGroupMaster OSGM ON OSGM.Id = OM.OrgSubGroupId
			INNER JOIN sSetup.tOrgMainGroupMaster OMGM ON OMGM.Id = OSGM.OrgMainGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OBM ON OBM.OrgGroupId = OG.Id
			INNER JOIN sSetup.tBatchMaster BM ON  BM.Id=A.BatchId AND BM.IsActive = 1 AND BM.OrgGroupBatchId=OBM.Id
			
	WHERE 
		
		((A.ClassId=@rClassId) OR (@rClassId=0))
		AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		
			AND	((CM.DepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))
			AND ((OMGM.Id=@rOrgMainGroupId) OR (@rOrgMainGroupId=0))
			AND ((OSGM.Id=@rOrgSubGroupId) OR (@rOrgSubGroupId=0))
			AND ((OM.Id=@rOrgId) OR (@rOrgId=0))
			--AND ((BM.Id=@rBatchId) OR (@rBatchId=0))			 
			AND  (BM.OrgGroupBatchId = @rOrgGroupBatchId)
			AND ((OM.OrgGroupId = @rOrgGroupId))
			AND (OMGM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit(	@rStrOrgMainGroupId,','))OR @rStrOrgMainGroupId='')
			AND (OSGM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit(	@rStrOrgSubGroupId,','))OR @rStrOrgSubGroupId='')
			AND (OM.Id IN (SELECT cast (item as int) FROM  sCommon.fnsplit ( @rStrOrgId,','))OR @rStrOrgId='')
			AND (DM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit  (@rStrDepartmentId,','))OR @rStrDepartmentId='')
			AND (CM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit  (@rStrClassId,','))OR @rStrClassId='')
			 	
END
GO
PRINT N'Creating [sPayroll].[pPayElementListGet]...';


GO
CREATE PROCEDURE [sPayroll].[pPayElementListGet]

           @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
				INNER JOIN sPayroll.tPayElement PE 
			ON PED.ID = PE.PayElementDefaultId AND PE.PayrollId=@rPayrollId AND PE.IsObsolete = 0
			WHERE PED.IsObsolete = 0
			
			ORDER BY PE.SortOrder
END
GO
PRINT N'Creating [sSecurity].[pRoleDashletGet]...';


GO

CREATE PROCEDURE [sSecurity].[pRoleDashletGet]
	 
	@rRoleId bigint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

	SELECT		 
		DM.Title AS DashletName,
		DM.Id AS DashletId,
		CASE 
			WHEN RD.DashletId IS NULL THEN Convert(Bit,0)
			ELSE Convert(Bit,1)
		END AS IsCheck
	FROM
	sSecurity.tDashletMaster DM
	INNER JOIN sSecurity.tPermission P ON P.TaskId=DM.TaskId AND RoleId = @rRoleId	 
	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
	
	LEFT JOIN  
   sSecurity.tRoleDashlet RD 		 	
		ON RD.DashletId=DM.Id AND RD.RoleId =@rRoleId 
		WHERE 
		(P.Permission & 2) =2
		--AND ScreenGroupId=@rScreenGroupId AND U.IsObsolete=0
		 
		AND T.IsObsolete = 0	
		AND DM.IsObsolete = 0
	
	
END
GO
PRINT N'Creating [sSecurity].[pRoleDashletUpdate]...';


GO

CREATE PROCEDURE [sSecurity].[pRoleDashletUpdate]
	
	@rRoleDashletImpXml [nvarchar](max),
	@rRoleId bigint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rRoleDashletImpXml
BEGIN
	
	BEGIN TRY
	BEGIN TRANSACTION
	
	 DELETE FROM sSecurity.tRoleDashlet Where RoleId = @rRoleId
	
	 INSERT INTO sSecurity.tRoleDashlet
		(
			RoleId,
			DashletId
			)
		SELECT
			RoleId,
			DashletId
		FROM OPENXML (@loDoc, '/Table/RoleDashlet', 1)
		WITH ( 
				RoleId int,
				DashletId int
			  ) 
		
	   SELECT 1 AS Result
		
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Creating [sSecurity].[pUserDashletGet]...';


GO

CREATE PROCEDURE [sSecurity].[pUserDashletGet]
	 
	@rUserId bigint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

	SELECT
		RD.DashletId AS  RoleDashletId,
		ISNULL(UD.DashletId,0) AS  UserDashletId,
		DM.Title AS DashletName,
		CASE 
			WHEN UD.DashletId = RD.DashletId THEN CONVERT(Bit, 1)
			ELSE CONVERT(Bit, 0)
		END AS IsCheck
	FROM
	
	
	  sSecurity.tRoleDashlet RD
	  INNER JOIN sSecurity.tUserRole UR ON RD.RoleId = UR.RoleId AND UR.UserId = @rUserId
	  INNER JOIN sSecurity.tDashletMaster DM 
		ON RD.DashletId=DM.Id
		INNER JOIN sSecurity.tPermission P ON P.TaskId=DM.TaskId AND P.RoleId = RD.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	
	  LEFT JOIN sSecurity.tUserDashlet UD 
		ON UD.UserId = UR.UserId AND RD.DashletId = UD.DashletId		 
	

	
	WHERE 
	(P.Permission & 2) =2
		--AND ScreenGroupId=@rScreenGroupId AND U.IsObsolete=0
		AND UR.UserId=@rUserId 
		AND T.IsObsolete = 0		 
	AND UR.UserId =@rUserId
	AND UR.IsPrimary = 1
	AND UR.IsObsolete = 0
	AND DM.IsObsolete = 0
END
GO
PRINT N'Creating [sSecurity].[pUserDashletUpdate]...';


GO

CREATE PROCEDURE [sSecurity].[pUserDashletUpdate]
	
	@rRoleDashletImpXml [nvarchar](max),
	@rUserId bigint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rRoleDashletImpXml
BEGIN
	
	BEGIN TRY
	BEGIN TRANSACTION
	
	 DELETE FROM sSecurity.tUserDashlet Where UserId = @rUserId
	
	 INSERT INTO sSecurity.tUserDashlet
		(
			UserId,
			DashletId
			)
		SELECT
			UserId,
			DashletId
		FROM OPENXML (@loDoc, '/Table/RoleDashlet', 1)
		WITH ( 
				UserId bigint,
				DashletId int
			  ) 
		
	   SELECT 1 AS Result
		
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Creating [sSetup].[pBatchAdminUpdate]...';


GO
CREATE PROCEDURE [sSetup].[pBatchAdminUpdate]
	
	@rOrgGroupId int, 
	@rOrgId int,
	@rBatchGroupId int,
	@rBatchId int,
	@rIsHistory bit=0,
	@rFromActionId int, 
	@rUpdatedUserId bigint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	 BEGIN TRANSACTION	
BEGIN
	
	 IF (@rFromActionId = 1) -- For Active
		BEGIN
			UPDATE sSetup.tBatchMaster SET IsActive = 0 WHERE OrgId = @rOrgId
			UPDATE sSetup.tBatchMaster SET IsActive = 1,IsHistory = 0,UpdatedUserId=@rUpdatedUserId,UpdatedDateTime=sCommon.fGetDate() WHERE OrgId = @rOrgId AND Id = @rBatchId
		END
	 ELSE IF (@rFromActionId = 2) -- For In Context
		BEGIN
			UPDATE sSetup.tBatchMaster SET IsInContext = 0 WHERE OrgId = @rOrgId AND OrgGroupBatchId = @rBatchGroupId
			UPDATE sSetup.tBatchMaster SET IsInContext = 1,UpdatedUserId=@rUpdatedUserId,UpdatedDateTime=sCommon.fGetDate() WHERE OrgId = @rOrgId AND Id = @rBatchId
		END
	 ELSE IF (@rFromActionId = 3) -- For In History
		BEGIN
			UPDATE sSetup.tBatchMaster SET IsHistory = @rIsHistory,UpdatedUserId=@rUpdatedUserId,UpdatedDateTime=sCommon.fGetDate() WHERE OrgId = @rOrgId AND Id = @rBatchId
		END

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


GO
CREATE PROCEDURE [sStudent].[pIcardOrgAdd]
	 
	@rIcardTemplateId int,
	@rOrgId int,
	@rICardBackground varbinary(max)=null,
	@rICardBackBackGround varbinary(max)=null,
	@rICardOrgTitle nvarchar(200)='',
	@rICardAddress1 nvarchar(200)='',
	@rICardAddress2 nvarchar(200)='',
	@rICardAddress3 nvarchar(200)='',
	@rLabelColor nvarchar(20)='',
	@rDetailColor nvarchar(20)='',
	@rHeaderColor nvarchar(20)=''
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

			IF (@rIcardTemplateId=0)
			BEGIN
					DELETE FROM sStudent.tICardOrg WHERE OrgId=@rOrgId
					SELECT -103 AS Result
					RETURN
			END 
			
	BEGIN TRY
		BEGIN TRANSACTION
		
		
	IF NOT EXISTS (SELECT 1 FROM sStudent.tICardOrg WHERE OrgId=@rOrgId)	
	
	
	   BEGIN
			INSERT INTO sStudent.tICardOrg
			(
				IcardTemplateId,
				OrgId,
				ICardBackground,
				ICardBackBackGround
			)
			VALUES
			(
				@rIcardTemplateId,
				@rOrgId,
				@rICardBackground,
				NULL
			)
			SELECT 1 AS Result	 
		END	 
	ELSE
		BEGIN
			UPDATE sStudent.tICardOrg
			SET
				IcardTemplateId=@rIcardTemplateId,
				ICardBackground=@rICardBackground,
				ICardBackBackGround=@rICardBackBackGround,
				IcardOrgTitle=@rICardOrgTitle,
				IcardAddress1=@rICardAddress1,
				IcardAddress2=@rICardAddress2,
				IcardAddress3=@rICardAddress3,
				LabelColor=@rLabelColor,
				DetailColor=@rDetailColor,
				HeaderColor=@rHeaderColor
				
				
			WHERE OrgId=@rOrgId
			SELECT 11 AS Result
		END  
		COMMIT TRANSACTION
			END TRY
		BEGIN CATCH 
			ROLLBACK TRANSACTION
			SELECT -1 AS Result
		END CATCH	
END
GO
PRINT N'Creating [sStudent].[pMyClassGet]...';


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

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


GO

CREATE PROCEDURE [sSystem].[pIsAppUpgradeRequired]
	@rVersionCode nvarchar(20) = NULL
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

 SELECT 0 AS Result
GO


GO

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

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

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

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

GO
ALTER PROCEDURE [sLibrary].[pValidateImportBook]
    @rOrgId int,
	@rXmldoc [nvarchar](max)
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
DECLARE @lCount INT
DECLARE @lInterrorCode INT,
		@intDoc INT,
        @lCode nvarchar(50),             
        @1ReturnCode int = 1,
        @1ExistBookCode nvarchar(max) = '' 
       
EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc
 
CREATE TABLE #tTable1 
 (
		Id bigint identity,
        Code nvarchar(25),
        Title nvarchar(100)
  )
  INSERT INTO #tTable1
	(
	    Code,
	    Title	   
    ) 
   SELECT
        Code,
        Title	    
   
   FROM OPENXML (@intDoc, '/Table/ImportBook', 1)
   With
   (
   
        Code nvarchar(25) '@Code',   
        Title nvarchar(100) '@Title'     
   )     
   
EXEC sp_xml_removedocument @intDoc
			
IF EXISTS(SELECT 1 fROM #tTable1 WHERE Code IS NULL OR Code='')
BEGIN
	SELECT 'Code Should not be empty' AS BookCode
END
ELSE
IF EXISTS(SELECT 1 fROM #tTable1 WHERE Title IS NULL OR Title='')
BEGIN
	SELECT 'Title Should not be empty' AS BookCode
END
ELSE
BEGIN
			
SELECT @lCount =  COUNT(Id) FROM #tTable1

WHILE @lCount > 0 
BEGIN

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

	IF Exists ((select 1 from sLibrary.tBookMaster where LibraryId = @rOrgId AND Code = @lCode))         
    BEGIN
		SET @1ExistBookCode = @1ExistBookCode + @lCode + ','
    END	       
   
	SET @lCount = @lCount - 1	
	END		
	Select @1ExistBookCode AS BookCode
END
			 
END

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]
           ,IsInContext)
     
      SELECT sCommon.fGetIntIdForOrg(1,@rOrgId)
           ,Code
           ,Title
           ,@rOrgId
           ,0
           ,1
           ,0
           ,1
           ,FromDate
           ,ToDate
           ,@lOrgGroupBatchId
		  ,@lCreatedUserId
		  ,@lCreatedDateTime
		  ,@lCreatedUserId
		  ,@lCreatedDateTime
		  ,1
           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



---------------------------- Refresh ---------------------------


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


GO
EXECUTE sp_refreshview N'sLibrary.vOrganizationLibrary';


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


GO
EXECUTE sp_refreshview N'sFee.vFeeColumnName';


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


GO
EXECUTE sp_refreshview N'sFee.vFeeCustomSearch';


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


GO
EXECUTE sp_refreshview N'sSetup.vUserOrganization';


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


GO
EXECUTE sp_refreshview N'sAssessment.vGeneralExamCustomSearch';


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


GO
EXECUTE sp_refreshview N'sAssessment.vGeneralExamColumnName';


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


GO
EXECUTE sp_refreshview N'sStudent.vStudentCustomSearch';


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


GO
EXECUTE sp_refreshview N'sStudent.vStudentColumnName';


GO
