 
PRINT N'Altering [sAssessment].[tCCEExamSetting]...';


GO
ALTER TABLE [sAssessment].[tCCEExamSetting]
    ADD [GradeSetId] INT NULL;


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


GO
ALTER TABLE [sAssessment].[tCCEResultDetail]
    ADD [FA1]   DECIMAL (6, 2) NULL,
        [FA2]   DECIMAL (6, 2) NULL,
        [SA1]   DECIMAL (6, 2) NULL,
        [FA3]   DECIMAL (6, 2) NULL,
        [FA4]   DECIMAL (6, 2) NULL,
        [SA2]   DECIMAL (6, 2) NULL,
        [FA]    DECIMAL (6, 2) NULL,
        [SA]    DECIMAL (6, 2) NULL,
        [TERM1] DECIMAL (6, 2) NULL,
        [TERM2] DECIMAL (6, 2) NULL,
        [TOTAL] DECIMAL (6, 2) NULL;


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


GO
ALTER TABLE [sFee].[tChargeReceipt]
    ADD [ReceiptAmount] DECIMAL (12, 2) NULL;


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


GO
ALTER TABLE [sFee].[tChargeReceiptBookMaster]
    ADD [IsDisplaySchoolName] BIT NULL;


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


GO
ALTER TABLE [sSetup].[tOrganizationMaster]
    ADD [TermPatternId] TINYINT NULL;


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


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


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


GO
ALTER TABLE [sSetup].[tBatchMaster]
    ADD [IsInContext] BIT NULL;

GO


PRINT N'Creating [sCommon].[fGetYearMonthNumber]...';


GO

CREATE FUNCTION [sCommon].[fGetYearMonthNumber](@rYear [int],@rMonth [int] )
RETURNS [bigint] WITH EXECUTE AS CALLER
AS 
BEGIN


return cast(cast(@rYear as nvarchar) + '' + replicate('0', 2 - len(@rMonth)) + cast (@rMonth as nvarchar) as bigint)

    
  

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


GO

















/******************************************************************************  
 Purpose          : To get Batch Wise  Class
 Created date     : 21 Nov 2013
 Author           : Kundan Patel 
 Copyright©       : Copyright © Sapphire Software Solutions
 ******************************************************************************/  
ALTER VIEW [sAssessment].[vExamClassDivision]  
  
AS  
  
SELECT 	
		 EM.Id,
		 ESGM.Id AS ExamSubGroupId,
		 ESGM.Title AS Name,
		 EM.BatchId,
	  	 EM.ClassId,
	  	 DM.Id AS DivisionId
FROM 
		sAssessment.tExamMaster EM
	INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId=EM.ClassId
	INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId
GO




/*
Deployment script for NetVidyalayaVersionBlank
*/
 
PRINT N'Altering [sStudent].[vStudentAcademic]...';


GO


















/******************************************************************************  
 Purpose          : To get Doctor details  
 Created date     : 18 Jan 2012  
 Author           : Rajendra Patel 
 Copyright©       : Copyright © Sapphire Software Solutions
 Last Change Desc : Moved EmployeeMaster from sCommon to sHrm.
*******************************************************************************/  
ALTER VIEW [sStudent].[vStudentAcademic]  
  
AS  
 
SELECT 
	  A.Id AS AcademicId,	  
	  A.ClassId,
	  A.DivisionId,
	  A.RollNo,
	  A.OrgId,
	  A.BatchId,
	  SM.Id AS StudentId,
	  SM.Code,
	  ISNULL(SM.Number,0) AS Number,
	  SM.RegistrationNumber,
	  SM.FirstName,
	  SM.MiddleName,
	  SM.LastName,
	  SM.FirstName + ' ' + SM.MiddleName +' '+SM.LastName AS Name,
	  Convert(Nvarchar(20),A.RollNo) + '-' + SM.FirstName+' '+SM.LastName AS RollNoName,
	  --SM.DepartmentId,
	  SM.StatusId,
	  CM.DisplayTitle AS ClassName,
	  DM.DisplayTitle AS DivisionName,
	  STM.Title AS StatusName,
	  --ISNULL(SO.DateOfBirth,'') AS DateOfBirth,
	  SM.RecordStatusId,
	  --ISNULL(SO.GenderId,0) AS GenderId,
	  DM.InchargeEmployeeId,
	  --SI.StudentPhoto,
	  --DATEDIFF(yy,ISNULL(SO.DateOfBirth,GETDATE()),GETDATE()) AS Age,
	  BM.OrgGroupBatchId,	  
	  SM.AdmissionCategoryId,
	  DM.OrderIndex DivisionOrder,
	  BM.IsActive AS IsActiveBatch,
	  BM.Title AS BatchName,
	  ISNULL(DeptM.Id,0) AS DepartmentId,
	  ISNULL(DeptM.Title,'') AS DepartmentName,
	  SM.IsBlackList,
	  SM.BlackListReason,
	  CM.OrderIndex AS ClassOrderIndex
  FROM 
	sStudent.tAcademic A
	INNER JOIN sStudent.tStudentMaster SM
		ON A.StudentId=SM.Id	
	INNER JOIN sSetup.tClassMaster CM
		ON CM.Id=A.ClassId
	INNER JOIN sSetup.tDivisionMaster DM
		ON DM.Id=A.DivisionId
	INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId 
	INNER JOIN sStudent.tStatusMaster STM
		ON STM.Id=SM.StatusId
	LEFT JOIN sSetup.tDepartmentMaster DeptM
		ON DeptM.Id=CM.DepartmentId
		
	--INNER JOIN sStudent.tStudentOther SO
	--ON SO.StudentId=A.StudentId
	--LEFT JOIN sStudent.tStudentImages SI 
	--ON SI.StudentId=A.StudentId
GO
PRINT N'Refreshing [sStudent].[vStudentCustomSearch]...';


GO
EXECUTE sp_refreshview N'sStudent.vStudentCustomSearch';


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


GO
EXECUTE sp_refreshview N'sStudent.vStudentColumnName';


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


GO
EXECUTE sp_refreshview N'sFee.vFeeColumnName';


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


GO
EXECUTE sp_refreshview N'sFee.vFeeCustomSearch';


GO
PRINT N'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 [sFee].[vUserChrageReceiptBook]...';


GO
EXECUTE sp_refreshview N'sFee.vUserChrageReceiptBook';


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


GO
EXECUTE sp_refreshview N'sSetup.vBatchCommon';


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


GO
EXECUTE sp_refreshview N'sStudent.vStudentAcademic';


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


GO
EXECUTE sp_refreshview N'sAssessment.vGeneralExamCustomSearch';


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


GO
EXECUTE sp_refreshview N'sAssessment.vGeneralExamColumnName';


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


GO
EXECUTE sp_refreshview N'sCertificate.vPrintTemplateStudentDetail';


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


GO
EXECUTE sp_refreshview N'sStudent.vStudentAllDetail';


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


GO
EXECUTE sp_refreshview N'sLibrary.vOrganizationLibrary';


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


GO
EXECUTE sp_refreshview N'sSetup.vUserOrganization';


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


GO
EXECUTE sp_refreshview N'sStudent.vStudentCustomSearch';


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


GO
EXECUTE sp_refreshview N'sStudent.vStudentColumnName';


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


GO
EXECUTE sp_refreshview N'sFee.vFeeColumnName';


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


GO
EXECUTE sp_refreshview N'sFee.vFeeCustomSearch';


GO


/*
Deployment script for NetVidyalayaVersionBlank
*/

 
PRINT N'Altering [sAdmission].[pRptStudentNewAdmissionListGet]...';


GO



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

BEGIN 
	
	select 
	@rBuilder1 AS Builder1,
	@rBuilder2 AS Builder2,
	SM.FirstName+' '+SM.MiddleName+' '+SM.LastName AS Name,
	SA.AdmissionDate,
	SM.Code,
	A.RollNo,
	CM.Title+'-'+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))
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
	 	 
	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)
		
	 	
			
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 ))
		
		

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


GO
ALTER PROCEDURE [sAssessment].[pCCEExamCombineGet]
	 @rClassId int
	,@rCCEExamId SMALLINT
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 		
	SELECT 
	EC.SubExamId AS SubExamId,
	EM.ClassId AS ClassId,
	ISNULL(EC.Weightage,0) AS Weightage,
	ISNULL(ExamOrder,0) AS ExamOrder
  FROM 
			[sAssessment].[tExamMaster] EM
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=EM.ClassId
			INNER JOIN sAssessment.tExamCombine EC ON EC.ExamId=EM.Id
			INNER JOIN sAssessment.tCCEExamSetting CS ON CS.CLASSID = CM.ID 
			AND CS.ExamSubGroupId = EM.ExamSubGroupId
WHERE 
			(EM.ClassId=@rClassId OR @rClassId=0)  
			AND CS.CCEExamId = @rCCEExamId
			ORDER BY EM.ExamSubGroupId ASC
		
END
GO
PRINT N'Altering [sAssessment].[pCCEExamSettingAdd]...';


GO

ALTER PROCEDURE [sAssessment].[pCCEExamSettingAdd]
	 
            @rClassId int
           ,@rCCEExamId int
		   ,@rMaxMark Decimal
		   ,@rGradeSetId Int
		   ,@rExamSubGroupId Int
		   ,@rBatchId Int
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
BEGIN  
  BEGIN
	DELETE FROM [sAssessment].[tCCEExamSetting] WHERE CCEExamId = @rCCEExamId AND ClassId = @rClassId
 	INSERT INTO [sAssessment].[tCCEExamSetting]
			   (
			    [CCEExamId]
			   ,[ClassId]
			   ,[MaxMark]
			   ,[ExamSubGroupId]
			   ,[GradeSetId]
			   ,[BatchId]
			   )
		 VALUES
			   (
			    @rCCEExamId
			   ,@rClassId
			   ,@rMaxMark
			   ,@rExamSubGroupId
			   ,@rGradeSetId
			   ,@rBatchId
			   )
		    SELECT 1 AS Result
	END
		--COMMIT TRANSACTION         
END	 
COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sAssessment].[pCCEExamSettingGet]...';


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

BEGIN 	
SELECT
	ISNULL(EM.ID,0) AS CCEEXAMID,
	ISNULL(CE.CLASSId,0) AS CLASSID,
	ISNULL(CE.MAXMARK,0) AS MAXMARK,
	ISNULL(CE.ExamSubGroupId,0) AS ExamSubGroupId,
	ISNULL(CE.GradeSetId,0) AS GradeSetId,
	EM.Title AS ExamName
FROM
sAssessment.tCCEEXAMSETTING CE 
RIGHT JOIN sAssessment.tCCEEXAMMASTER EM ON EM.Id = CE.CCEExamId AND CE.CLASSId = @rClassId 
--WHERE EM.ID>=7

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


GO


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

IF ISNULL(@lCCEResultDetailId,0) = 0
	 BEGIN

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

--SELECT @lDataSetID=GradeSetId FROM sAssessment.tExamDetail WHERE ExamId = @rCCEExamId AND ClassSubjectId = @rClassSubjectId
  SELECT @lClassId = ClassId From sStudent.tAcademic Where Id =  @rAcademicId 	
  SELECT @lDataSetID=GradeSetId FROM sAssessment.tCCEExamSetting WHERE CCEExamId = @rCCEExamId AND ClassId = @lClassId

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

SELECT @lCount =  COUNT(Id) FROM #tempGradeSetDetail
DECLARE @lloopCount int
--set @lloopCount=1
while ( @lCount > 0 )
BEGIN
		SELECT @MinimumScore =MinimumScore,@GradeTitle=GradeTitle,@GradePoint=GradePoint
		FROM #tempGradeSetDetail WHERE Id = @lCount
		
		SELECT  @lMaxiMark = Maximum FROM sAssessment.tExamDetail Where ExamId = @rSubExamId AND ClassSubjectId = @rClassSubjectId
		
		IF @rExamOrder = 1 
		BEGIN				
			Update sAssessment.tCCEResultDetail  Set GradeFA1 = @GradeTitle WHERE (FA1 * 100)/@lMaxiMark  >= @MinimumScore 
		END
		IF @rExamOrder = 2 
		BEGIN							
			Update sAssessment.tCCEResultDetail  Set GradeFA2 = @GradeTitle WHERE (FA2 * 100)/@lMaxiMark >= @MinimumScore 
		END
		IF @rExamOrder = 3 
		BEGIN				
			Update sAssessment.tCCEResultDetail  Set GradeSA1 = @GradeTitle WHERE (SA1 * 100)/@lMaxiMark >= @MinimumScore 
		END
		IF @rExamOrder = 4 
		BEGIN				
			Update sAssessment.tCCEResultDetail  Set GradeFA3 = @GradeTitle WHERE (FA3 * 100)/@lMaxiMark >= @MinimumScore 
		END
		IF @rExamOrder = 5 
		BEGIN				
			Update sAssessment.tCCEResultDetail  Set GradeFA4 = @GradeTitle WHERE (FA4 * 100)/@lMaxiMark >= @MinimumScore 
		END
		IF @rExamOrder = 6 
		BEGIN		
			Update sAssessment.tCCEResultDetail  Set GradeSA2 = @GradeTitle WHERE (SA2 * 100)/@lMaxiMark >= @MinimumScore 
		END
		
		SET @lCount = @lCount - 1
 END
	--End Grade Evaluation	
--END	
COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sAssessment].[pCCEResultDetailSubjectGradeUpdate]...';


GO
ALTER PROCEDURE [sAssessment].[pCCEResultDetailSubjectGradeUpdate]
	  
	
	  @rExamOrder INT
	 ,@rCCEExamId INT
	 ,@rSubExamId INT
	
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 	
BEGIN TRY
 BEGIN TRANSACTION		
		DECLARE @MinimumScore decimal(5,2)
		DECLARE @GradeTitle nvarchar(10)
		DECLARE @GradePoint decimal(6,2)
		DECLARE @lCount int
		DECLARE @lDataSetID INT
		DECLARE @lClassId INT

		--SELECT @lDataSetID=GradeSetId FROM sAssessment.tExamMaster WHERE Id = @rCCEExamId 
		 SELECT @lClassId = ClassId From sAssessment.tExamMaster Where Id =  @rSubExamId
		 SELECT @lDataSetID=GradeSetId FROM sAssessment.tCCEExamSetting WHERE CCEExamId = @rCCEExamId AND ClassId = @lClassId
		
		CREATE TABLE #tempGradeSetDetail
			(
				Id INT IDENTITY (1, 1),
				MinimumScore decimal(5,2),
				GradeTitle nvarchar(10),
				GradePoint decimal(6,2) 					 
			) 
			INSERT INTO #tempGradeSetDetail
			SELECT MinimumScore,GradeCode,GradePoint		
			FROM sAssessment.tGradeSetDetail where GradesetId=@lDataSetID
			order by Id Asc

		SELECT @lCount =  COUNT(Id) FROM #tempGradeSetDetail
		DECLARE @lloopCount int
		set @lloopCount=1
		SELECT @lCount =  COUNT(Id) FROM #tempGradeSetDetail
 set @lloopCount=1
 while (@lloopCount <= @lCount )
 BEGIN
	SELECT
		@MinimumScore =MinimumScore,
		@GradeTitle=GradeTitle,
		@GradePoint=GradePoint
		FROM #tempGradeSetDetail WHERE Id = @lloopCount
		
		IF @rExamOrder = 1 
		BEGIN				
			Update sAssessment.tCCEResultDetail  Set GradePointFA1 = @GradePoint WHERE GradeFA1 = @GradeTitle 
		END
		IF @rExamOrder = 2 
		BEGIN				
			Update sAssessment.tCCEResultDetail  Set GradePointFA2 = @GradePoint WHERE GradeFA2 = @GradeTitle 
		END
		IF @rExamOrder = 3 
		BEGIN				
			Update sAssessment.tCCEResultDetail  Set GradePointSA1 = @GradePoint WHERE GradeSA1 = @GradeTitle 
		END
		IF @rExamOrder = 4 
		BEGIN				
			Update sAssessment.tCCEResultDetail  Set GradePointFA3 = @GradePoint WHERE GradeFA3 = @GradeTitle 
		END
		IF @rExamOrder = 5 
		BEGIN				
			Update sAssessment.tCCEResultDetail  Set GradePointFA4 = @GradePoint WHERE GradeFA4 = @GradeTitle 
		END
		IF @rExamOrder = 6 
		BEGIN				
			Update sAssessment.tCCEResultDetail  Set GradePointSA2 = @GradePoint WHERE GradeSA2 = @GradeTitle 
		END
	
		
		Update sAssessment.tCCEResultDetail  Set FAGrade = @GradeTitle WHERE FAGRADEPOINT = @GradePoint 
		Update sAssessment.tCCEResultDetail  Set SAGrade = @GradeTitle WHERE SAGRADEPOINT = @GradePoint 
		Update sAssessment.tCCEResultDetail  Set Term1Grade = @GradeTitle WHERE Term1GRADEPOINT = @GradePoint 
		Update sAssessment.tCCEResultDetail  Set Term2Grade = @GradeTitle WHERE Term2GRADEPOINT = @GradePoint 
		Update sAssessment.tCCEResultDetail  Set Grade = @GradeTitle WHERE GRADEPOINT = @GradePoint  
		
		SET @lloopCount = @lloopCount + 1
		
 END
 	    Update sAssessment.tCCEResultDetail  Set FA = ROUND((FA1+FA2+FA3 +FA4)/4,0)
		Update sAssessment.tCCEResultDetail  Set SA = ROUND((SA1+SA2)/2,0)
		Update sAssessment.tCCEResultDetail  Set Term1 = ROUND((FA1+FA2+SA1)/3,0) 
		Update sAssessment.tCCEResultDetail  Set Term2 = ROUND((FA3+FA4+SA2)/3,0) 
		Update sAssessment.tCCEResultDetail  Set TOTAL = ROUND((FA1+FA2+FA3 +FA4 + SA1 +SA2),0)
		
		Update sAssessment.tCCEResultDetail  Set FAGradePoint = ROUND((GradePointFA1+GradePointFA2+GradePointFA3 +GradePointFA4)/4,0)
		Update sAssessment.tCCEResultDetail  Set SAGradePoint = ROUND((GradePointSA1+GradePointSA2)/2,0)
		Update sAssessment.tCCEResultDetail  Set Term1GradePoint = ROUND((GradePointFA1+GradePointFA2+GradePointSA1)/3,0) 
		Update sAssessment.tCCEResultDetail  Set Term2GradePoint = ROUND((GradePointFA3+GradePointFA4+GradePointSA2)/3,0) 
		
		Update sAssessment.tCCEResultDetail  Set GRADEPOINT = ROUND((GradePointFA1+GradePointFA2+GradePointFA3)/3,0) WHERE Term2GradePoint = 0
		Update sAssessment.tCCEResultDetail  Set GRADEPOINT = ROUND((GradePointFA1+GradePointFA2+GradePointFA3 +GradePointFA4+GradePointSA1+GradePointSA2)/6,0)
		WHERE Term2GradePoint <> 0 AND Term1GradePoint <> 0
 
	update CR set cgpa =  (CRD.GradePoint) from  sAssessment.tCCEResult CR 
	Inner Join (select Avg(GradePoint) AS GradePoint,AcademicId From sAssessment.tCCEResultDetail Group By ACademicId ) CRD 
	ON CR.AcademicId = CRD.AcademicId
 
 
		SELECT 1 AS Result
	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END
GO
PRINT N'Altering [sAssessment].[pCCERptFirstTermResultGet]...';


GO


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

BEGIN 

	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			SM.Code,
			ISNULL(SM.FirstName,'')+' '+ISNULL(SM.LastName,'') AS Name,
			A.RollNo,
			CCER.AcademicId,
			CONVERT(NVARCHAR,CCER.AcademicId) AS AcademicIdText,
			ISNULL(SC.ParentContactNo,'') AS ContactNo,
			ISNULL(SC.PresentStreetThree,'')+' '+ISNULL(SC.PresentStreetTwo,'')+' '+ISNULL(SC.PresentStreetThree,'')+' '+ISNULL(SC.PresentCity,'')+' '+ISNULL(SC.PresentState,'') AS PresentAddress,
			SO.DateOfBirth,
			CM.DisplayTitle AS Class,
			DM.DisplayTitle AS Division,
			ISNULL(HM.Title,'') AS House,
			ISNULL(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,
			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.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
			--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.tStudentCommunication SC ON SC.StudentId=A.StudentId
			LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
			LEFT JOIN sActivity.tHouseMaster HM ON HM.Id=SO.HouseId
			LEFT JOIN sSetup.tClassSubject CS ON CS.Id=CCERD.ClassSubjectId
			INNER JOIN sSetup.tSubjectMaster SubM ON SubM.Id=CS.SubjectId
			LEFT JOIN sCommon.tBloodGroupMaster BGM ON BGM.Id=SO.BloodGroupId
			LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=A.StudentId
			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
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id
			LEFT JOIN sSetup.tTermScopeMaster TSM ON TSM.Id = EM.TermScopeId

			
			
	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)
	
	ORDER BY A.RollNo,CS.OrderIndex	
END
GO
PRINT N'Altering [sAssessment].[pExamCombineMarkEntryGet]...';


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

BEGIN 		

IF EXISTS (SELECT ID from sAssessment.tExamCombine where ExamId = @rExamId)
BEGIN
select  
(case WHEN A.Maxi = 0 then 0
else
ISNULL((A.Obtain*ED.Maximum)/A.Maxi,0) END) AS Obtain,


@rAcademicId AS AcademicId,
ED.Id AS ExamDetailID,
ED.ExamId,ISNULL((select IsPresent from sAssessment.tResultDetail rd1 
		   inner join sAssessment.tResult r1 on r1.Id=rd1.ResultId and r1.ExamId=@rExamId and r1.AcademicId=@rAcademicId
		   and rd1.ExamDetailId=ED.Id ),0)  AS IsPresent
from
(SELECT 
Sum(Obtain*weightage/100) AS Obtain,Sum(Maximum*weightage/100) AS Maxi,RM.AcademicId,ED.ClassSubjectId
FROM sAssessment.tResult RM 
	INNER JOIN sAssessment.tResultDetail RD ON RD.ResultId=RM.Id
	INNER JOIN sAssessment.tExamDetail ED ON RD.ExamDetailId=ED.Id
	INNER JOIN sAssessment.tExamCombine EC ON ED.ExamId=EC.SubExamId
	INNER JOIN sSetup.vClassSubject V ON V.ClassSubjectId = Ed.ClassSubjectId  	
	WHERE EC.ExamId=@rExamId 
	
GROUP BY RM.AcademicId,ED.ClassSubjectId having RM.AcademicId=@rAcademicId) AS A
INNER JOIN sAssessment.tExamDetail ED ON ED.ClassSubjectId=A.ClassSubjectId
Where ED.ExamId =@rExamId
END
		
END
GO
PRINT N'Altering [sAssessment].[pMarkEntryMasterUpdate]...';


GO

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


GO


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

BEGIN 

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


GO

 
 

ALTER PROCEDURE [sAttendance].[pAttenanceRegisterGet]

	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rAttendanceTypeId smallint,
	 @rOrgId int,
	 @rForMonth smallint,
	 @rForYear smallint,
	 @rClassId int,
	 @rDivisionId int,
	 @rBatchId int = 0,
	 @rStudentCode nvarchar(20)='',
	 @rDepartmentId int = 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)
            
             WHERE 
	        ((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.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 [sCertificate].[pBonafideGet]...';


GO
ALTER PROCEDURE [sCertificate].[pBonafideGet]
	 @rId bigint = 0,
	 @rCode nvarchar(20),
	 @rName nvarchar(200),
	 @rFromDate date,
	 @rToDate date,
	 @rOrgId smallint,
	 @rBatchId int,
	 @rIsSearch bit = 1,
	 @rClassId int,
	 @rDivisionId int
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 IF @rIsSearch = 1
		BEGIN
			SET @rCode = sCommon.fSearchStringGet(@rCode)
			SET @rName = sCommon.fSearchStringGet(@rName)
		END
	
	SELECT 
	
			BC.Id,
			BC.AcademicId,
			SA.Code,
			SA.Name,
			SA.ClassName+'-'+SA.DivisionName as ClassDivision,
			BC.Number,
			BC.BonafideDate,
			BC.Remark
			
  FROM 
            sCertificate.tBonafide BC
       INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=BC.AcademicId AND SA.OrgId=@rOrgId AND SA.BatchId=@rBatchId
  WHERE 
  
      ((BC.Id = @rId) OR (@rId = 0))
      AND ((SA.Code like @rCode) OR (ISNULL(@rCode,'') = ''))
	AND ((SA.Name like @rName) OR (ISNULL(@rName,'') = ''))
	AND ((BC.BonafideDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	AND ((BC.BonafideDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
	AND (SA.ClassId = @rClassId OR @rClassId = 0)
	AND (SA.DivisionId = @rDivisionId OR @rDivisionId = 0)
	order by BC.Number
END
GO
PRINT N'Altering [sCertificate].[pLeavingBulkGet]...';


GO

ALTER PROCEDURE [sCertificate].[pLeavingBulkGet]
	 
	 @rClassID int,
	 @rDivisionId int,
	 @rOrgId int,
	 @rBatchId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	
	SELECT 
			SA.AcademicId,
			ISNULL(SA.RollNo,0) AS RollNo,
			SA.Code,
			SA.Name,
			ISNULL(L.Id,0) AS Id,
			ISNULL(L.LCNumber,0) AS LCNumber,
			ISNULL(L.LCDate,'') AS LCDate
			
			
  FROM 
			[sStudent].[vStudentAcademic]  SA 
			LEFT JOIN sCertificate.tLeaving L ON L.AcademicId=SA.AcademicId
  WHERE 
			(SA.ClassId=@rClassId OR @rClassId=0)
			AND (SA.DivisionId=@rDivisionId OR @rDivisionId=0)
			AND SA.BatchId=@rBatchId
			--AND SA.StatusId IN(1,2)
			AND SA.OrgID=@rOrgId order by SA.RollNo
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 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





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

	-- special case will come orgwise and orggroupwise

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

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


GO
ALTER PROCEDURE [sFee].[pChargeReceiptAdd]
	 
	@rId bigint,
	@rSourceTypeId smallint,
	@rSourceId bigint,
	@rGuestName nvarchar(200),
	@rReceiptBookId int,
	@rRemark nvarchar(200),
	@rReceiptNumber int,
	@rReceiptDate date,
	@rPayTypeId tinyint,
	@rChequeNo nvarchar(20),
	@rBankName nvarchar(200),
	@rIsObsolete bit,
	@rOrgId int,
	@rBatchId int,
	@rOrgGroupBatchId int,
	@rCreatedUserId bigint,
	@rReceiptAmount Decimal(12,2)
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
 IF(@rId = 0)	
BEGIN
--  EXECUTE sCommon.pPrefixSetupNextNumberGet @rOrgId = @rOrgId, @rPrefixFunctionalityId = 2002,@rStoreLocationId = 0, @rNextNumber  = @rReceiptNumber OUTPUT

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

--		IF @rReceiptNumber = '-300'
--	  BEGIN
--		SELECT -300 AS Result, '' AS ReceiptNumber, 0 AS Id 
--		RETURN
--	  END

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



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

	INSERT INTO sFee.tChargeReceipt
		(
			Id,
			SourceTypeId,
			SourceId,
			GuestName,
			ChargeReceiptBookId,
			Remark,
			ReceiptNumber,
			ReceiptDate,
			PayTypeId,
			ChequeNo,
			BankName,
			IsObsolete,
			CreatedUserId,
			CreatedDateTime,
			OrgId,
			BatchId,
			OrgGroupBatchId,
			ReceiptAmount
		)
	VALUES
		(
			@lNextNumber,
			@rSourceTypeId,
			@rSourceId,
			@rGuestName,
			@rReceiptBookId,
			@rRemark,
			@rReceiptNumber,
			@rReceiptDate,
			@rPayTypeId,
			@rChequeNo,
			@rBankName,
			@rIsObsolete,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rOrgId,
			@rBatchId,
			@rOrgGroupBatchId,
			@rReceiptAmount
		)
		             
	END	 
	 ELSE
	 SET @lNextNumber = @rId
	    UPDATE  sFee.tChargeReceipt
	    SET
			SourceTypeId=@rSourceTypeId,
			SourceId=@rSourceId,
			GuestName=@rGuestName,
			ChargeReceiptBookId=@rReceiptBookId,
			Remark=@rRemark,
			ReceiptNumber=@rReceiptNumber,
			ReceiptDate=@rReceiptDate,
			PayTypeId=@rPayTypeId,
			ChequeNo=@rChequeNo,
			BankName=@rBankName,
			IsObsolete=@rIsObsolete,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate(),
			ReceiptAmount=@rReceiptAmount
	      
	      WHERE Id = @rId 	   
	 	 
		  SELECT @lNextNumber AS Result	   
		
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sFee].[pChargeReceiptBookMasterAdd]...';


GO

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

	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sFee.tChargeReceiptBookMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	
	INSERT INTO [sFee].[tChargeReceiptBookMaster]
			   (
			    [Id]
			   ,[Code]
			   ,[Title]
			   ,[FullTitle]
			   ,[Address1] 
			   ,[Address2] 
			   ,[BankAccountNumber] 
			   ,[IsObsolete]
			   ,[Remark1] 
			   ,[Remark2] 
			   ,[CreatedUserId]
			   ,[CreatedDateTime]
			   ,[OrgGroupId]
			   ,IsOnPrePrinted
			   ,ReportId
			   ,IsSupressLogo
			   ,OrderIndex
			   ,IsDisplaySchoolName
			   )
		 VALUES
			   (
				@lNextNumber
			   ,@rCode
			   ,@rTitle
			   ,@rFullTitle
			   ,@rAddress1
			   ,@rAddress2
			   ,@rBankAccountNumber
			   ,@rIsObsolete
			   ,@rRemark1
			   ,@rRemark2
			   ,@rCreatedUserId
			   ,sCommon.fGetDate()
			   ,@rOrgGroupId
			   ,@rIsOnPrePrinted
			   ,@rReportId
			   ,@rIsSupressLogo
			   ,@rOrderIndex
			   ,@rIsDisplaySchoolName
			   )
		    SELECT @lNextNumber AS Result
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  [sFee].[tChargeReceiptBookMaster]
	    SET
			  --Code=@rCode
	          Title=@rTitle
	          ,FullTitle=@rFullTitle
	         ,Address1=@rAddress1
	         ,Address2=@rAddress2
	         ,BankAccountNumber=@rBankAccountNumber
	         ,[IsObsolete] = @rIsObsolete          
	         ,[Remark1] = @rRemark1
	         ,[Remark2] = @rRemark2                     
             ,[UpdatedUserId] = @rCreatedUserId
             ,[UpdatedDateTime] = sCommon.fGetDate()   
             ,IsOnPrePrinted=@rIsOnPrePrinted
             ,ReportId=@rReportId
             ,IsSupressLogo=@rIsSupressLogo
             ,OrderIndex=@rOrderIndex              
             ,IsDisplaySchoolName=@rIsDisplaySchoolName
             
	      WHERE Id = @rId 	   
	      SELECT @lNextNumber AS Result
	 END  
		
	END
COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sFee].[pChargeReceiptBookMasterGet]...';


GO

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

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

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


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

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


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

ORDER BY CM.OrderIndex ASC

END
GO
PRINT N'Altering [sFee].[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)
		
		
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 	
	SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		@rIsCancel AS IsCancel,
		R.Id AS ReceiptId,
		R.ReceiptNumber,
		SA.ClassId,
		--SA.ClassName,
		SA.DivisionId,
		--SA.DivisionName,
		SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
		SA.RollNo,
		SA.AcademicId,
		SA.FirstName,
		SA.MiddleName,
		SA.LastName,
		SA.Code,
		SA.Name,
		PTM.Title AS PayType,
		R.ChequeNo,
		R.BankName,
		R.ReceiptAmount,
		R.ReceiptDate,
		FM.Title AS FeeDetail,
		FM.Code AS FeeCode,
		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
			
  FROM 
			sFee.tReceipt R
		--INNER JOIN sCommon.tSourceTypeMaster STM
		--	ON STM.Id=R.SourceTypeId AND R.SourceTypeId = 2001
		INNER JOIN sStudent.vStudentAcademic SA
			ON SA.AcademicId=R.SourceId AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))
		INNER JOIN sFinanceCommon.tPayTypeMaster PTM
			ON PTM.Id=R.PayTypeId
		INNER JOIN sFee.tReceiptDetail RD
			ON RD.ReceiptId=R.Id
		INNER JOIN sFee.tFeeSetup FS
			ON FS.Id=RD.FeeSetupId
		INNER JOIN sFee.tFeeMaster FM
			ON FM.Id=FS.FeeId
		INNER JOIN sFee.tFeeHeadMaster FHM
			ON FHM.Id=FM.FeeHeadId
		INNER JOIN sFee.tReceiptBookMaster RBM 
			ON RBM.Id=R.ReceiptBookId
		INNER JOIN sSetup.tOrganizationMaster O
			ON O.Id=sa.OrgId
			
			
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))
	ORDER BY R.ReceiptNumber
	
--	UNION ALL
	
--	SELECT 
--		R.Id AS ReceiptId,
--		0 AS ClassId,
--		--SA.ClassName,
--		0 AS DivisionId,
--		--SA.DivisionName,
--		EM.DepartmentId,
--		EM.DepartmentName AS ClassDept,
--		0 AS RollNo,
--		EM.Code,
--		EM.EmployeeName,
--		PTM.Title AS PayType,
--		R.ReceiptAmount
			
--  FROM 
--			sFee.tReceipt R
--		INNER JOIN sCommon.tSourceTypeMaster STM
--			ON STM.Id=R.SourceTypeId AND R.SourceTypeId = 95
--		INNER JOIN sHrm.vExtEmployeeMaster EM
--			ON EM.EmployeeId=R.SourceId
--		INNER JOIN sFinanceCommon.tPayTypeMaster PTM
--			ON PTM.Id=R.PayTypeId
			
--WHERE 
--		((EM.DepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))
--	AND ((R.ReceiptNumber >= @rFromReceiptNo) OR (@rFromReceiptNo = 0))
--	AND ((R.ReceiptNumber <= @rToReceiptNo) OR (@rToReceiptNo = 0))
--	AND ((R.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
--	AND ((R.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
--	AND (R.BatchId = @rBatchId)
END
GO
PRINT N'Altering [sFee].[pRptFeeReceiptDetailsGet]...';


GO
ALTER PROCEDURE [sFee].[pRptFeeReceiptDetailsGet]
			@rReportId int=0,
			@rReceiptId bigint = 0
			--,			
			--@rReceiptBookId int=0,
			--@rAdmissionCategoryId int=0,
			--@rClassId int=0,
			--@rDivisionId int=0,		 
			--@rFromDate date='1900-01-01',
			--@rToDate date='9990-12-31',
			--@rFromReceiptNo int=0,
			--@rToReceiptNo int=0,
			--@rBatchId int=0,
			--@rUserId bigint=0,
			--@rBuilder1 nvarchar(max)='',
			--@rBuilder2 nvarchar(max)='',
			--@rIsDetail bit=0,
			--@rIsCancel bit=0,
			--@rOrgId int=0,
			--@rOrgGroupBatchId int=0,
			--@rStatusId int=0,
			--@rPaytypeId int=0
			
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 	

--DECLARE @rOrgId smallint


--DECLARE @lIsOnPrePrinted bit = 0

--DECLARE @lConfigValue nvarchar(50)

--SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 125 AND SourceTypeId = 1016 AND SourceId = 1001
	
--	IF (@lConfigValue IS NULL) OR (@lConfigValue = 'False')
--	SET @lIsOnPrePrinted = 0
--	ELSE
--	SET @lIsOnPrePrinted = 1

 

	SELECT 
			FRD.ReceiptId,
			FR.ReceiptNumber,
			FR.ReceiptDate,
			SA.AcademicId,
			SA.FirstName+' '+SA.MiddleName+' '+SA.LastName AS Name,
			SA.Code,
			SA.RollNo,
			SA.ClassId,
			SA.DivisionId,
			SA.ClassName,
			SA.DivisionName,
			SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
			FM.FeeHeadId,
			FHM.Title AS FeeHead,
			FM.Id AS FeeId,
			FM.Title AS FeeName,
			FRD.Amount AS PaidAmount,
			PTM.Title AS PayType,
			ISNULL(FR.ChequeNo,'') AS ChequeNo,
			ISNULL(FR.BankName,'') AS BankName,
			ISNULL(RBM.Address1,'') AS Address1,
			ISNULL(RBM.Address2,'') AS Address2,
			ISNULL(RBM.FullTitle,'') AS FullTitle,
			ISNULL(FR.TotalReceiptAmount,0.00) AS TotalReceiptAmount,
			ISNULL(FR.ReceiptAmount,0.00) AS ReceiptAmount,
			sFinanceCommon.fNumberToWordsWithDecimal(ISNULL(FR.ReceiptAmount,0.00),0,2) AS ReceiptAmountInWords,
			ISNULL(FR.DiscountAmount,0.00) AS DiscountAmount,
			FR.Remark,
			ISNULL(U.DisplayTitle,'') AS UserName,
			OM.OrgLogo,
			RBM.Remark1,
			RBM.Remark2,			 
			ISNULL(RBM.IsOnPrePrinted,0) AS IsOnPrePrinted,
			ISNULL(RBM.IsSupressLogo,0) AS IsSupressLogo,
			ISNULL(RBM.IsDisplaySchoolName,0) AS IsDisplaySchoolName,
			RBM.ReportId,
			OM.Title AS OrganizationName,
			(CASE  WHEN ISNULL(RBM.IsMonthDetailOnly,0) = 1 THEN 
			[sFee].[fReceiptMonthDetailGet](FR.ID)						 
			ELSE
			''
			END) AS MonthDetail,
			DM.Title AS DepartmentName,
			FM.OrderIndex AS FeeOrderIndex,
			FHM.OrderIndex AS FeeHeadOrderIndex
	
	FROM 
	
			sFee.tReceipt FR				
			INNER JOIN sFee.tReceiptDetail FRD
				ON FR.Id=FRD.ReceiptId AND FR.SourceTypeId=2001				
			INNER JOIN sFee.tFeeSetup FS
				ON FRD.FeeSetupId = FS.Id				
			INNER JOIN sFee.tFeeMaster FM
				ON FS.FeeId=FM.Id						
			INNER JOIN sFee.tFeeHeadMaster FHM
				ON FHM.Id=FM.FeeHeadId
			INNER JOIN sStudent.vStudentAcademic SA
				ON SA.AcademicId = FR.SourceId
			INNER JOIn sFinanceCommon.tPayTypeMaster PTM
				ON PTM.Id=FR.PayTypeId
			--LEFT JOIN sFee.tFeeAllocation FA
			--	ON FA.FeeSetupId=FS.Id
			INNER JOIN sFee.tReceiptBookMaster RBM 
				ON RBM.Id=FR.ReceiptBookId
			LEFT JOIN sSecurity.tUser U
				ON U.Id=FR.CreatedUserId
			INNER JOIN sSetup.tDepartmentMaster DM
				ON SA.DepartmentId =DM.Id
			LEFT JOIN sSetup.tOrganizationMaster OM
				ON OM.Id=DM.OrgId
	WHERE 
	 FR.Id=@rReceiptId 
	--AND	((SA.AdmissionCategoryId = @rAdmissionCategoryId) OR (@rAdmissionCategoryId = 0))
	--AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
	--AND ((SA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))
	--AND ((FR.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId = 0))
	--AND ((FR.ReceiptNumber >= @rFromReceiptNo) OR (@rFromReceiptNo = 0))
	--AND ((FR.ReceiptNumber <= @rToReceiptNo) OR (@rToReceiptNo = 0))
	--AND ((FR.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
	--AND ((FR.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
	--AND (FR.OrgGroupBatchId = @rOrgGroupBatchId)
	--AND ((FR.BatchId=@rBatchId) OR (@rBatchId=0))
	--AND ((FR.CreatedUserId=@rUserId) OR (@rUserId=0))
	--AND (FR.IsObsolete = @rIsCancel) 
	--AND (SA.StatusId=@rStatusId OR @rStatusId=0)
	--AND (FR.PayTypeId = @rPaytypeId OR @rPaytypeId=0)

ORDER BY FS.StartDate,FM.OrderIndex ASC

END
GO
PRINT N'Altering [sHrm].[pAvailableLeaveEmployeeWise]...';


GO


ALTER PROCEDURE [sHrm].[pAvailableLeaveEmployeeWise]
(
	@rOrgId int,    
    @rEmployeeId  bigint,  
    @rLeaveTypeId int,     
    @rBatchId int 
 )
AS
SET NOCOUNT ON

BEGIN
    
	   SELECT    
			SUM(NoOfLeave) AS AvailableLeave
       FROM 
			[sHrm].[tLeave] L  
  --INNER JOIN sHrm.tLeaveTypeGradeSettings LTGS ON LTGS.EmployeeGradeId = EM.EmployeeGradeId AND LTGS.LeaveTypeId = L.LeaveTypeId 
	   WHERE 
			(L.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
		AND (L.LeaveTypeId = @rLeaveTypeId OR @rLeaveTypeId = 0)      
		AND BatchId = @rBatchId AND L.OrgId = @rOrgId 
		AND L.StatusId = 550 -- apporved
      GROUP BY EmployeeId,LeaveTypeId
END


--select * from scommon.tStatusTypeMaster
--select * from scommon.tStatusMaster
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].[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')
	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 = 'Gender' OR @rSubCategory = 'Religion' OR @rSubCategory = 'BloodGroup')
		BEGIN
			SET @rSubCategory = @rSubCategory + 'Id'
		END
		ELSE IF (@rSubCategory = 'MaritalStatusId' OR @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].[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 
		--INNER JOIN
		sHrm.tLeave L 
		--ON L.EmployeeId = EM.EmployeeId	 	
		--INNER JOIN sHrm.tWorkingDays WD ON  EM.EmployeeGradeId = WD.EmployeeGradeId
	   
		--LEFT JOIN sHrm.tLeave L ON L.EmployeeId = EM.EmployeeId  
    	WHERE L.EmployeeId = @rEmployeeId AND L.BatchId = @rBatchId  
    	AND L.StatusId = 550 -- apporved
    	--AND WD.ForMonth=@rForMonth AND WD.ForYear=@rForYear
    	--) t
    --GROUP BY EmployeeId,WorkingDays
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].[pBulkBookLogListGet]...';


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

	UNION

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

	UNION 

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

  SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			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 WHERE A.DivisionId = DM.Id AND SM.StatusId = 1 AND A.BatchId = @rBatchId) 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
			AND	((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 (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 [sProcurement].[pRptGoodsReturnNote]...';


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


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

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

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

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

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


GO
ALTER PROCEDURE [sSecurity].[pDashBoardMenuGet]
	
	@rUserSourceTypeId smallint,
	@rUserId bigint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	SELECT
		MenuID,
		ModuleId,
		ParentMenuID,
		MenuTitle,	 
		MenuTitle AS 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
						AND T.Id IN
						(
						--Assignment List
						20093,
						--Behaviour List
						20130,
						--Blog List
						20099,
						--Circular List
						20085,
						--Discussion List
						20109,
						--My Poll
						20204,
						--News List
						20104,
						--Query List
						20088,
						--View Task
						20172,
						--View Category
						20183,
						--View Photo
						20185,
						--Image Viewer
						9133,
						--Video Viewer
						9128,
						--Link Viewer
						9137,
						--Calender
						20054,
						--My Event List
						20198,
						--My Activity List
						20209,
						--View Placement
						20190,
						--Student View Result
						20180,
						--Employee View Result
						20181,
						--View Book List
						20182,
						-- Student Profile						
						10187,
						-- Employee Profile
						20246
						)
						
						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 
						 INNER JOIN sSecurity.tTask  T ON T.Id =  Screen.TaskId 	
						 AND T.Id IN
						(
						--Assignment List
						20093,
						--Behaviour List
						20130,
						--Blog List
						20099,
						--Circular List
						20085,
						--Discussion List
						20109,
						--My Poll
						20204,
						--News List
						20104,
						--Query List
						20088,
						--View Task
						20172,
						--View Category
						20183,
						--View Photo
						20185,
						--Image Viewer
						9133,
						--Video Viewer
						9128,
						--Link Viewer
						9137,
						--Calender
						20054,
						--My Event List
						20198,
						--My Activity List
						20209,
						--View Placement
						20190,
						--Student View Result
						20180,
						--Employee View Result
						20181,
						--View Book List
						20182,
						-- Student Profile						
						10187,
						-- Employee Profile
						20246
						)					
					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
	 		
	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 [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
	
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
			
			--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
			--@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
			--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.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 [sStudent].[pRptStudentRegisterGet]...';


GO


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

BEGIN 

	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			SD.AcademicId,
			SD.StudentId, 
			SD.ClassId,
			SD.DivisionId,
			SD.ClassDivision,
			SD.Code,
			SD.RollNo,			
			SD.FirstName,
			SD.MiddleName,			
			SD.LastName,
			SD.Name,		
			SD.ClassName,
			SD.DivisionName,
			SD.StatusName,
			SD.StatusId,
			SD.LCProgress,
			SD.Religion,
			SD.FamilyCast,
			SD.FamilySubCast,
			SD.LCConduct,
			SD.BirthPlace,
			SD.BirthTaluka,
			SD.BirthDistrict,
			SD.LeftDate,
			SD.PreviousSchool,
			SD.DateOfBirth,
			SD.BirthDateInWord,
			SD.LeftReason,
			SD.AdmissionDate,
			SD.AdmissionStandard,
			SD.LeftStandard,
			SD.LCNumber,
			SD.LCDate,
			SD.StudentPhoto,
			SD.BloodGroup,
			SD.PresentAddress,
			SD.ContactNo,
			SD.Batch,
			SD.InactiveDate,
			OM.Title AS OrgName,
			SF.MotherName,
			SD.DivisionOrder,
			SD.Number AS StudentNumber,
			SF.FatherName
      
	FROM 
			sStudent.vStudentAllDetail SD
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=SD.OrgId
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId=SD.StudentId
	WHERE 
			SD.OrgId=@rOrgId
		AND	SD.BatchId = @rBatchId 
		AND (ISNULL(SD.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rStrCode,',')) OR @rStrCode='') 
		AND ((SD.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SD.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((SD.StudentId=@rStudentId) OR (@rStudentId=0))
		AND ((SD.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((SD.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((SD.StatusId=@rStatusId)OR(@rStatusId=0))
		AND ((MONTH(SD.DateOfBirth)=@rDateOfBirth OR @rDateOfBirth=0))
	    AND ((SD.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
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].[pXMLStudentImportAdd]...';


GO

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

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

	BEGIN TRY
	BEGIN TRANSACTION
	DECLARE @lCount INT
	DECLARE @lNextNumber BIGINT 
	Declare @lExistCode nvarchar(max)
	DECLARE @MaxCode AS bigint
	
 
 
	IF EXISTS(SELECT SM.Code
	from
	(
			SELECT StudentId FROM
			OPENXML (@loDoc, '/Table/StudentImportDetail', 1)
			WITH (
					StudentId bigint)	
	)E
	INNER JOIN sStudent.tStudentMaster SM ON SM.ReferenceSourceId=E.StudentId AND SM.OrgId=@rToOrgId	
	)
	BEGIN
		SELECT @lExistCode  = COALESCE(@lExistCode ,'') + CONVERT(VARCHAR(15),E.Code) + ' , ' 
		from
		(
				SELECT StudentId,Code FROM
				OPENXML (@loDoc, '/Table/StudentImportDetail', 1)
				WITH (
						StudentId bigint,
						Code nvarchar(20)
						)
		)E
		INNER JOIN sStudent.tStudentMaster SM ON SM.ReferenceSourceId=E.StudentId AND SM.OrgId=@rToOrgId	
		SELECT @lExistCode
		RETURN
	END
	
	
	EXECUTE sCommon.pTableRowIdGet @rToOrgId, 'sStudent.tStudentMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	SELECT @MaxCode = MAX(Number) FROM sStudent.tStudentMaster WHERE OrgId = @rToOrgId
	SET @MaxCode = ISNULL(@MaxCode,0) + 1
	
	SELECT 
			@lNextNumber + ROW_NUMBER() OVER(ORDER BY E.StudentId)AS NewStudentId,
			E.StudentId,
			@MaxCode + ROW_NUMBER() OVER(ORDER BY E.StudentId)AS Code
	INTO 
			sStudent.tTempStudentId
	from
	(
			SELECT StudentId FROM
			OPENXML (@loDoc, '/Table/StudentImportDetail', 1)
			WITH (
					StudentId bigint)	
	)E

	SELECT @lCount = COUNT(1) FROM OPENXML (@loDoc, '/Table/StudentImportDetail', 1)
				 WITH ( Id int )
	SET @lNextNumber  = @lCount + @lNextNumber 
	
	EXECUTE sCommon.pTableRowIdModify @rToOrgId, @rTableTitle = 'sStudent.tStudentMaster', @rCurrentNumber = @lNextNumber 
		
	--Insert Into Student Master
	INSERT INTO sStudent.tStudentMaster
	(
			Id,
			Code,
			Number,
			FirstName,
			MiddleName,
			LastName,
			OrgId,
			StatusId,
			RecordStatusId,
			CreatedUserId,
			CreatedDateTime,
			ReferenceSourceId,
			AdmissionCategoryId
		
	)
	SELECT 
			TS.NewStudentId,
			TS.Code,
			TS.Code,
			SM.FirstName,
			SM.MiddleName,
			SM.LastName,
			@rToOrgId,
			1,
			502,
			@rCreatedUserId,
			sCommon.fGetDate(),
			TS.StudentId,
			SM.AdmissionCategoryId
	FROM
			sStudent.tTempStudentId TS	
		INNER JOIN sStudent.tStudentMaster SM ON SM.ID=TS.StudentId
		
	--Insert Into Academic
		
	EXECUTE sCommon.pTableRowIdGet @rToOrgId, 'sStudent.tAcademic', 0, 1, 1,@outNextNumber = @lNextNumber output
 
	INSERT INTO sStudent.tAcademic
	(
			Id,
			StudentId,
			ClassId,
			BatchId,
			DivisionId,
			RollNo,
			OrgId,
			CreatedUserId,
			CreatedDateTime
	)
	SELECT
			@lNextNumber+ ROW_NUMBER() OVER(ORDER BY StudentId),
			NewStudentId,
			@rToClassId,
			@rToBatchId,
			@rToDivisionId,
			0,
			@rToOrgId,
			@rCreatedUserId,
			sCommon.fGetDate()
	FROM 
			sStudent.tTempStudentId
		
	SELECT @lCount = COUNT(1) FROM OPENXML (@loDoc, '/Table/StudentImportDetail', 1)
			 WITH ( Id int )
	SET @lNextNumber  = @lCount + @lNextNumber 
	
	EXECUTE sCommon.pTableRowIdModify @rToOrgId, @rTableTitle = 'sStudent.tAcademic', @rCurrentNumber = @lNextNumber 
	
	--Insert Into Student Other
	INSERT INTO sStudent.tStudentOther
	(
		   [StudentId]
		  ,[UIDNumber]
		  ,[DateOfBirth]
		  ,[BirthDateInWord]
		  ,[TransportModeId]
		  ,[GenderId]
		  ,[BloodGroupId]
		  ,[BirthPlace]
		  ,[BirthTaluka]
		  ,[BirthDistrict]
		  ,[FamilyCast]
		  ,[FamilySubCast]
		  ,[CastCategoryId]
		  ,[ReligionId]
		  ,[HouseId]
		  ,[MotherTongueId]
		  ,[NationalityId]
		  ,[Hobby]		   
		  ,[CreatedUserId]
		  ,[CreatedDateTime]
		  ,ReferenceRemark
	)
	SELECT 
		   TS.NewStudentId
		  ,SO.[UIDNumber]
		  ,SO.[DateOfBirth]
		  ,SO.[BirthDateInWord]
		  ,SO.[TransportModeId]
		  ,SO.[GenderId]
		  ,SO.[BloodGroupId]
		  ,SO.[BirthPlace]
		  ,SO.[BirthTaluka]
		  ,SO.[BirthDistrict]
		  ,SO.[FamilyCast]
		  ,SO.[FamilySubCast]
		  ,SO.[CastCategoryId]
		  ,SO.ReligionId		   
		  ,NULL
		  ,so.MotherTongueId
		  ,So.NationalityId		 
		  ,SO.[Hobby] 
		  ,@rCreatedUserId
		  ,sCommon.fGetDate()
		  ,ReferenceRemark
	FROM
			sStudent.tTempStudentId TS	
		INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=TS.StudentId
	
	--Insert Into Student Admission
	INSERT INTO sStudent.tStudentAdmission
	(
		   [StudentId]
		  ,[PreviousStudentId]
		  ,[AdmissionStandardId]
		  ,[AdmissionDate]
		  ,[AdmissionYear]
		  ,[BatchId]
		  ,[CreatedUserId]
		  ,[CreatedDateTime]
		  ,PreviousSchool
	)
	SELECT 
		   TS.NewStudentId
		  ,TS.StudentId
		  ,@rToClassId
		  ,@rAdmissionDate
		  ,YEAR(GETDATE())
		  ,@rToBatchId
		  ,@rCreatedUserId
		  ,sCommon.fGetDate()
		  ,PreviousSchool
	FROM
			sStudent.tTempStudentId TS	
		INNER JOIN sStudent.tStudentAdmission SA ON SA.StudentId=TS.StudentId
	
	
INSERT INTO [sStudent].[tStudentCommunication]
           ([StudentId]
           ,[PresentStreetOne]
           ,[PresentStreetTwo]
           ,[PresentStreetThree]
           ,[PresentCountry]
           ,[PresentState]
           ,[PresentCity]
           ,[PresentZipCode]
           ,[PresentContactNo]
           ,[PermanentStreetOne]
           ,[PermanentStreetTwo]
           ,[PermanentStreetThree]
           ,[PermanentCountry]
           ,[PermanentState]
           ,[PermanentCity]
           ,[PermanentZipCode]
           ,[PermanentContactNo]
           ,[EmergencyStreetOne]
           ,[EmergencyStreetTwo]
           ,[EmergencyStreetThree]
           ,[EmergencyCountry]
           ,[EmergencyState]
           ,[EmergencyCity]
           ,[EmergencyZipCode]
           ,[EmergencyContactNo]
           ,[ParentContactNo]
           ,[ParentEmail]
           ,[StudentContactNo]
           ,[StudentEmail]
           ,[CreatedUserId]
           ,[CreatedDateTime])
 
 SELECT 
			TS.NewStudentId
           ,[PresentStreetOne]
           ,[PresentStreetTwo]
           ,[PresentStreetThree]
           ,[PresentCountry]
           ,[PresentState]
           ,[PresentCity]
           ,[PresentZipCode]
           ,[PresentContactNo]
           ,[PermanentStreetOne]
           ,[PermanentStreetTwo]
           ,[PermanentStreetThree]
           ,[PermanentCountry]
           ,[PermanentState]
           ,[PermanentCity]
           ,[PermanentZipCode]
           ,[PermanentContactNo]
           ,[EmergencyStreetOne]
           ,[EmergencyStreetTwo]
           ,[EmergencyStreetThree]
           ,[EmergencyCountry]
           ,[EmergencyState]
           ,[EmergencyCity]
           ,[EmergencyZipCode]
           ,[EmergencyContactNo]
           ,[ParentContactNo]
           ,[ParentEmail]
           ,[StudentContactNo]
           ,[StudentEmail]
           ,@rCreatedUserId
           ,sCommon.fGetDate()
        
	FROM
			sStudent.tTempStudentId TS	
		INNER JOIN [sStudent].[tStudentCommunication] SA ON SA.StudentId=TS.StudentId          
	
	
	
	INSERT INTO  [sStudent].[tStudentFamily]
           ([StudentId]
           ,[FatherName]
           ,[FatherDateOfBirth]
           ,[FatherOccupation]
           ,[FatherQualification]
           ,[FatherContactNo]
           ,[FatherMail]
           ,[FatherOfficeAddress]
           ,[FatherIncome]
           ,[MotherName]
           ,[MotherDateOfBirth]
           ,[MotherOccupation]
           ,[MotherQualification]
           ,[MotherContactNo]
           ,[MotherMail]
           ,[MotherOfficeAddress]
           ,[MotherIncome]
           ,[RelationshipName]
           ,[RelativeName]
           ,[RelativeDateOfBirth]
           ,[RelativeOccupation]
           ,[RelativeQualification]
           ,[RelativeContactNo]
           ,[RelativeMail]
           ,[RelativeOfficeAddress]
           ,[RelativeIncome]
           ,[CreatedUserId]
           ,[CreatedDateTime]
           ,[FatherPhoto]
           ,[MotherPhoto]
           ,[RelativePhoto]
           ,[MarriageAnniversaryDate])
     SELECT    
			TS.NewStudentId
           ,[FatherName]
           ,[FatherDateOfBirth]
           ,[FatherOccupation]
           ,[FatherQualification]
           ,[FatherContactNo]
           ,[FatherMail]
           ,[FatherOfficeAddress]
           ,[FatherIncome]
           ,[MotherName]
           ,[MotherDateOfBirth]
           ,[MotherOccupation]
           ,[MotherQualification]
           ,[MotherContactNo]
           ,[MotherMail]
           ,[MotherOfficeAddress]
           ,[MotherIncome]
           ,[RelationshipName]
           ,[RelativeName]
           ,[RelativeDateOfBirth]
           ,[RelativeOccupation]
           ,[RelativeQualification]
           ,[RelativeContactNo]
           ,[RelativeMail]
           ,[RelativeOfficeAddress]
           ,[RelativeIncome]
           ,@rCreatedUserId
           ,sCommon.fGetDate()
           ,[FatherPhoto]
           ,[MotherPhoto]
           ,[RelativePhoto]
           ,[MarriageAnniversaryDate]
   	FROM
			sStudent.tTempStudentId TS	
		INNER JOIN sStudent.tStudentFamily SA ON SA.StudentId=TS.StudentId    


INSERT INTO  [sStudent].[tStudentHealth]
           ([StudentId]
           ,[IdentificationMark1]
           ,[IdentificationMark2]
           ,[IsPysicalDeformity]
           ,[PysicalDeformityRemark]
           ,[IsMajorIllness]
           ,[MajorIllnessRemark]
           ,[IsAllergy]
           ,[AllergyRemark]
           ,[IsPastHistory]
           ,[PastHistoryRemark]
           ,[FamilyDoctorName]
           ,[FamilyDoctorContactNo]
           ,[UpdatedUserId]
           ,[UpdatedDateTime])
SELECT

			TS.NewStudentId
           ,[IdentificationMark1]
           ,[IdentificationMark2]
           ,[IsPysicalDeformity]
           ,[PysicalDeformityRemark]
           ,[IsMajorIllness]
           ,[MajorIllnessRemark]
           ,[IsAllergy]
           ,[AllergyRemark]
           ,[IsPastHistory]
           ,[PastHistoryRemark]
           ,[FamilyDoctorName]
           ,[FamilyDoctorContactNo]
           ,@rCreatedUserId
           ,sCommon.fGetDate()

   	FROM
			sStudent.tTempStudentId TS	
		INNER JOIN sStudent.tStudentHealth SA ON SA.StudentId=TS.StudentId 
		
		
		INSERT INTO  [sStudent].[tStudentImages]
           ([StudentId]
           ,[StudentPhoto]
           ,[FatherPhoto]
           ,[MotherPhoto]
           ,[RelativePhoto]
           ,[UpdatedDateTime])
           
           SELECT           
            TS.NewStudentId
           ,[StudentPhoto]
           ,[FatherPhoto]
           ,[MotherPhoto]
           ,[RelativePhoto]
           ,sCommon.fGetDate()
         	FROM
			sStudent.tTempStudentId TS	
		INNER JOIN sStudent.tStudentImages SA ON SA.StudentId=TS.StudentId      
	
	DROP TABLE sStudent.tTempStudentId
	
    SELECT 1 AS Result
	
	COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
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

END
GO
PRINT N'Creating [sCommunication].[pMyBookGet]...';


GO
CREATE PROCEDURE [sCommunication].[pMyBookGet]
	 
	 @rReaderSourceTypeId smallint,
	 @rReaderSourceId bigint,
	 @rBatchId int
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 



select BL.Id AS BookLogId,
	BM.Title AS BookTitle,
	BL.LogDate AS IssueDate,
	--BL.IsCurrentStatus AS IsReturnPending,
	CASE WHEN BL.IsCurrentStatus = 0 THEN 'Pending' ELSE 'Return' END AS IsReturnPending,
	BL.DueDate 
	--CASE WHEN BL.IsCurrentStatus = 0 THEN BL.DueDate ELSE '' END AS DueDate

  from sLibrary.tBookLog BL INNER JOIN sLibrary.tBookMaster BM
  ON BL.ResourceSourceId = BM.Id AND BL.ResourceSourceTypeId = 2009  
  WHERE BL.statusId = 523
  ORDER BY BL.LogDate DESC

END
GO
PRINT N'Creating [sEExam].[pXMLDataBankImport]...';


GO

CREATE PROCEDURE [sEExam].[pXMLDataBankImport] 
    @rXMLDoc nvarchar(Max),
	@rOrgGroupId int,
	@rDataBankId int,
	@rDBName nvarchar(100)
AS
SET NOCOUNT ON
BEGIN
--	  SET @rXMLDoc = REPLACE(@rXMLDoc,'&','AND')
	  DECLARE @lXMLDoc INT, @intDoc INT 	
	
	BEGIN TRY
		BEGIN TRANSACTION	
			  EXECUTE @lXMLDoc = sp_xml_preparedocument @intDoc OUTPUT, @rXMLDoc	

			-- DataSubject Master	
				IF @rDBName = 'DataSubject'
				BEGIN			
					INSERT INTO sEExam.tDataSubjectMaster
					(Id,DataBankId,Code,Number,Title,IsObsolete,OrderIndex,CreatedUserId,CreatedDateTime)
					SELECT
						[sCommon].[fGetIntIdForOrg] (Id %100000,@rOrgGroupId),@rDataBankId,Code,Number,Title,IsObsolete,OrderIndex,CreatedUserId,getdate()				
					FROM OPENXML (@intDoc, '/Table/DataSubjectMaster', 1)
					WITH
					(
							Id int '@Id',Code nvarchar(20) '@Code',Number smallint '@Number',
							Title nvarchar(100) '@Title',IsObsolete bit '@IsObsolete',OrderIndex smallint '@OrderIndex',
							CreatedUserId bigint '@CreatedUserId'
					) A
					WHERE [sCommon].[fGetIntIdForOrg] (Id %100000,@rOrgGroupId) NOT IN (SELECT Id FROM sEExam.tDataSubjectMaster)
				END
			-- Data Topic Master
				ELSE IF @rDBName = 'TopicMaster'
				BEGIN					
					INSERT INTO sEExam.tDataTopicMaster
					(Id,Code,Number,Title,DataSubjectId,ClassGroupId,DataTopicTypeId,IsObsolete,OrgGroupId,DataBankId,CreatedUserId,CreatedDateTime)	
					SELECT
						[sCommon].[fGetIntIdForOrg] (Id %100000,@rOrgGroupId),Code,Number,Title,[sCommon].[fGetIntIdForOrg] (DataSubjectId %100000,@rOrgGroupId),
						ClassGroupId,[sCommon].[fGetIntIdForOrg] (DataTopicTypeId %100000,@rOrgGroupId),IsObsolete,
						@rOrgGroupId,@rDataBankId,CreatedUserId,GETDATE()				
					FROM OPENXML (@intDoc, '/Table/DataTopicMaster', 1)
					WITH
					(
							Id int '@Id',Code nvarchar(20) '@Code',Number smallint '@Number',Title nvarchar(100) '@Title',
							DataSubjectId int '@DataSubjectId',ClassGroupId int '@ClassGroupId',IsObsolete bit '@IsObsolete',
							OrderIndex smallint '@OrderIndex',CreatedUserId bigint '@CreatedUserId',
							DataTopicTypeId int '@DataTopicTypeId'
					) A
					WHERE [sCommon].[fGetIntIdForOrg] (Id %100000,@rOrgGroupId) NOT IN (SELECT Id FROM sEExam.tDataTopicMaster)
				END
			-- Data Topic Type Master	
				ELSE IF @rDBName = 'TopicType'
					BEGIN
					INSERT INTO sEExam.tDataTopicTypeMaster
					(Id,Code,Number,Title,DataSubjectId,OrgGroupId,IsObsolete,OrderIndex,DataBankId,CreatedUserId,CreatedDateTime)	
					SELECT
						[sCommon].[fGetIntIdForOrg] (Id %100000,@rOrgGroupId),Code,Number,Title,[sCommon].[fGetIntIdForOrg] (DataSubjectId %100000,@rOrgGroupId),OrgGroupId,IsObsolete,OrderIndex,
						@rDataBankId,CreatedUserId,GETDATE()				
					FROM OPENXML (@intDoc, '/Table/DataTopicTypeMaster', 1)
					WITH
					(
							Id int '@Id',Code nvarchar(20) '@Code',Number smallint '@Number',Title nvarchar(100) '@Title',
							DataSubjectId int '@DataSubjectId',IsObsolete bit '@IsObsolete',OrgGroupId int '@OrgGroupId',
							OrderIndex smallint '@OrderIndex',CreatedUserId bigint '@CreatedUserId'
					) A
					WHERE [sCommon].[fGetIntIdForOrg] (Id %100000,@rOrgGroupId) NOT IN (SELECT Id FROM sEExam.tDataTopicTypeMaster)
				END
			-- Question Master	
				ELSE IF @rDBName = 'Question'
				BEGIN
					INSERT INTO sEExam.tQuestionMaster
					(Id,TopicId,DifficultyLevelId,QuestionParagraphId,QuestionDescription,QuestionDescription2,Marks,
					 IsObsolete,OrderIndex,CreatedUserId,CreatedDateTime,DataBankId,EntryModeId)	
					SELECT
						[sCommon].[fGetBigIntIdForOrg] (Id %1000000000,@rOrgGroupId),[sCommon].[fGetIntIdForOrg] (TopicId %100000,@rOrgGroupId),
						DifficultyLevelId,[sCommon].[fGetBigIntIdForOrg] (QuestionParagraphId %1000000000,@rOrgGroupId),QuestionDescription,QuestionDescription2,Marks,
						IsObsolete,OrderIndex,CreatedUserId,GETDATE(),@rDataBankId,EntryModeId				
					FROM OPENXML (@intDoc, '/Table/QuestionMaster', 1)
					WITH
					(
							Id bigint '@Id',TopicId int '@TopicId',DifficultyLevelId tinyint '@DifficultyLevelId',
							QuestionParagraphId bigint '@QuestionParagraphId',QuestionDescription nvarchar(max) '@QuestionDescription',
							QuestionDescription2 nvarchar(max) '@QuestionDescription2',Marks Decimal(6,2) '@Marks',IsObsolete bit '@IsObsolete',
							OrderIndex smallint '@OrderIndex',CreatedUserId bigint '@CreatedUserId',
							EntryModeId tinyint '@EntryModeId'
					) A
					WHERE [sCommon].[fGetBigIntIdForOrg] (Id %100000,@rOrgGroupId) NOT IN (SELECT Id FROM sEExam.tQuestionMaster)	
				END
			-- Question Option	
				ELSE IF @rDBName = 'QuestionOption'
				BEGIN
					INSERT INTO sEExam.tQuestionOption
					(Id,QuestionId,ChoiceDescription,ChoiceDescription2,IsKey,OrderIndex)
					SELECT
						[sCommon].[fGetBigIntIdForOrg] (Id %1000000000,@rOrgGroupId),[sCommon].[fGetBigIntIdForOrg] (QuestionId %1000000000,@rOrgGroupId),
						ChoiceDescription,ChoiceDescription2,IsKey,OrderIndex
					FROM OPENXML (@intDoc, '/Table/QuestionOption', 1)
					WITH
					(
							Id bigint '@Id',QuestionId bigint '@QuestionId',IsKey bit '@IsKey',OrderIndex smallint '@OrderIndex',
							ChoiceDescription nvarchar(max) '@ChoiceDescription',ChoiceDescription2 nvarchar(max) '@ChoiceDescription2'						
					) A
					WHERE [sCommon].[fGetBigIntIdForOrg] (Id %100000,@rOrgGroupId) NOT IN (SELECT Id FROM sEExam.tQuestionOption)	
				END
			-- Question Paragraph	
				ELSE IF @rDBName = 'QuestionPara'
				BEGIN
					INSERT INTO sEExam.tQuestionParagraph
					(Id,QuestionParagraphDescription,QuestionParagraphDescription2,UpdatedUserId,UpdatedDateTime,DataBankId)
					SELECT
						[sCommon].[fGetBigIntIdForOrg] (Id %1000000000,@rOrgGroupId),QuestionParagraphDescription,QuestionParagraphDescription2,
						UpdatedUserId,GETDATE(),@rDataBankId
					FROM OPENXML (@intDoc, '/Table/QuestionParagraph', 1)
					WITH
					(
							Id bigint '@Id',QuestionId bigint '@QuestionId',UpdatedUserId bigint '@UpdatedUserId',
							QuestionParagraphDescription nvarchar(max) '@QuestionParagraphDescription',QuestionParagraphDescription2 nvarchar(max) '@QuestionParagraphDescription2'
													
					) A
					WHERE [sCommon].[fGetBigIntIdForOrg] (Id %100000,@rOrgGroupId) NOT IN (SELECT Id FROM sEExam.tQuestionParagraph)	
				END
			
			  EXEC sp_xml_removedocument @intDoc	
			
		COMMIT TRANSACTION
		SELECT 1
	END TRY
	BEGIN CATCH
		SELECT -1
	END CATCH
END
GO
PRINT N'Creating [sMis].[pRptAverageAttendanceGet]...';


GO
CREATE 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)
		
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			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,
			
			Attendance=0
		   
	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 (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'Creating [sMis].[pRptInquiryAdmissionGet]...';


GO
CREATE 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)
		
		
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			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.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 (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'Creating [sMis].[pRptStudentStrengthGet]...';


GO
CREATE 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)
		
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			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.OrgGroupBatchId = @rOrgGroupBatchId AND SA.AdmissionDate < @rFromDate
			AND A.ClassId =CM.Id AND BM.IsInContext = 1 ) 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.OrgGroupBatchId = @rOrgGroupBatchId AND SA.AdmissionDate >= @rFromDate AND SA.AdmissionDate <= @rToDate
			AND A.ClassId =CM.Id AND BM.IsInContext = 1 ) 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.OrgGroupBatchId = @rOrgGroupBatchId AND SA.LeftDate >= @rFromDate AND SA.LeftDate <= @rToDate
			AND A.ClassId =CM.Id AND BM.IsInContext = 1 ) 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.OrgGroupBatchId = @rOrgGroupBatchId AND SM.StatusId = 1
			AND A.ClassId =CM.Id AND BM.IsInContext = 1 ) 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 (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

/*
Deployment script for NetVidyalayaVersionBlank
*/
 
PRINT N'Altering [sAssessment].[pCCERptFirstTermResultGet]...';


GO


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

BEGIN 

	SELECT 
			--@rBuilder1 AS Builder1,
			--@rBuilder2 AS Builder2,
			SM.Code,
			ISNULL(SM.FirstName,'')+' '+ISNULL(SM.LastName,'') AS Name,
			A.RollNo,
			CCER.AcademicId,
			CONVERT(NVARCHAR,CCER.AcademicId) AS AcademicIdText,
			ISNULL(SC.ParentContactNo,'') AS ContactNo,
			ISNULL(SC.PresentStreetThree,'')+' '+ISNULL(SC.PresentStreetTwo,'')+' '+ISNULL(SC.PresentStreetThree,'')+' '+ISNULL(SC.PresentCity,'')+' '+ISNULL(SC.PresentState,'') AS PresentAddress,
			--SO.DateOfBirth,
			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.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
			--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.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
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id
			LEFT JOIN sSetup.tTermScopeMaster TSM ON TSM.Id = EM.TermScopeId

			
			
	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)
	
	ORDER BY A.RollNo,CS.OrderIndex	
END
GO
PRINT N'Altering [sCommunication].[pDiscussionGet]...';


GO
ALTER PROCEDURE [sCommunication].[pDiscussionGet]
	 @rId bigint,
	 @rBatchId int,
	 @rDiscussionGroupId bigint,
	 @rTitle nvarchar(200),
	 @rIsSearch bit = 1,
	 @rSourceId bigint
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
 
	 IF @rIsSearch = 1
		BEGIN
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		END
	
	SELECT 
			D.Id,
			D.DiscussionGroupId,
			DG.Title AS DiscussionGroup,
			D.BatchId,
			BM.Title AS Batch,
			D.Title,
		    D.Remark,
		    U.DisplayTitle AS DiscussionCreatedUserName,
		    D.CreatedDateTime AS DiscussionCreatedDateTime,
		    (SELECT ISNULL( Count(1),0) FROM sCommunication.tDiscussionComment DC WHERE DC.DiscussionId = D.Id) AS TotalDiscussionComment
		    
  FROM 
            sCommunication.tDiscussion D
            INNER JOIN sSetup.tBatchMaster BM ON BM.Id=D.BatchId
            INNER JOIN sCommunication.tDiscussionGroup DG ON DG.Id=D.DiscussionGroupId
            INNER JOIN sCommunication.tDiscussionGroupMember DGM ON DGM.DiscussionGroupId=DG.Id AND DGM.SourceTypeId=95 
						AND (DGM.SourceId=@rSourceId)
            INNER JOIN sSecurity.tUser U ON U.Id=D.CreatedUserId
  WHERE 
  
      ((D.Id = @rId) OR (@rId = 0))
	AND ((D.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
	AND ((D.DiscussionGroupId=@rDiscussionGroupId) OR (@rDiscussionGroupId=0))
	AND ((D.BatchId=@rBatchId) OR (@rBatchId=0))
	
	UNION 
	
	SELECT 
			D.Id,
			D.DiscussionGroupId,
			DG.Title AS DiscussionGroup,
			D.BatchId,
			BM.Title AS Batch,
			D.Title,
		    D.Remark,
		    U.DisplayTitle AS DiscussionCreatedUserName,
		    D.CreatedDateTime AS DiscussionCreatedDateTime,
		    (SELECT ISNULL( Count(1),0) FROM sCommunication.tDiscussionComment DC WHERE DC.DiscussionId = D.Id) AS TotalDiscussionComment
		    
  FROM 
            sCommunication.tDiscussion D
            INNER JOIN sSetup.tBatchMaster BM ON BM.Id=D.BatchId
            INNER JOIN sCommunication.tDiscussionGroup DG ON DG.Id=D.DiscussionGroupId
            INNER JOIN sCommunication.tDiscussionGroupMember DGM ON DGM.DiscussionGroupId=DG.Id AND DGM.SourceTypeId=2001 
						AND (DGM.SourceId=(SELECT AcademicId FROM sStudent.vStudentName WHERE StudentId=@rSourceId AND BatchId = @rBatchId))
            INNER JOIN sSecurity.tUser U ON U.Id=D.CreatedUserId
  WHERE 
  
      ((D.Id = @rId) OR (@rId = 0))
	AND ((D.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
	AND ((D.DiscussionGroupId=@rDiscussionGroupId) OR (@rDiscussionGroupId=0))
	AND ((D.BatchId=@rBatchId) OR (@rBatchId=0))
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
		
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 	
	SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		@rIsCancel AS IsCancel,
		@rIsDetail AS IsDetail,
		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 sCommon.tSourceTypeMaster STM
		--	ON STM.Id=R.SourceTypeId AND R.SourceTypeId = 2001
		INNER JOIN sStudent.vStudentAcademic SA
			ON SA.AcademicId=R.SourceId AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))
		INNER JOIN sFinanceCommon.tPayTypeMaster PTM
			ON PTM.Id=R.PayTypeId
		INNER JOIN sFee.tReceiptDetail RD
			ON RD.ReceiptId=R.Id
		INNER JOIN sFee.tFeeSetup FS
			ON FS.Id=RD.FeeSetupId
		INNER JOIN sFee.tFeeMaster FM
			ON FM.Id=FS.FeeId
		INNER JOIN sFee.tFeeHeadMaster FHM
			ON FHM.Id=FM.FeeHeadId
		INNER JOIN sFee.tReceiptBookMaster RBM 
			ON RBM.Id=R.ReceiptBookId
		INNER JOIN sSetup.tDepartmentMaster DM
			ON SA.DepartmentId=DM.Id
		INNER JOIN sSetup.tOrganizationMaster O
			ON O.Id=sa.OrgId
			
			
			
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))
	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 [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].[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')
	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 = 'Gender' OR @rSubCategory = 'Religion' OR @rSubCategory = 'BloodGroup')
		BEGIN
			SET @rSubCategory = @rSubCategory + 'Id'
		END
		ELSE IF (@rSubCategory = 'MaritalStatusId' OR @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 [sIp].[pBinMaintenanceGet]...';


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

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

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


GO
ALTER PROCEDURE [sPayroll].[pEmployeePayrollListGet]

	@rPayrollId int,
	@rPayrollGroupId int,
	@rForYear int,
	@rForMonth int
 
AS
SET NOCOUNT ON

BEGIN
		SELECT 
			EM.Code AS Code,
			ISNULL(EM.FirstName, '') + ' ' + ISNULL(EM.MiddleName, '') + ' ' + ISNULL(EM.LastName, '') AS Name,
			ISNULL(ETM.Title,'') As EmployeeType,
			OM.Title AS OrganizationName,
			ODM.Title AS OrganizationDepartmentName,
			PGM.Title AS PayrollGroupName,
			ISNULL(AT.TotalWorkingDays,0) AS WorkingDays, 
			ISNULL(AT.LWP,0) AS LWP,
			(ISNULL(AT.TotalWorkingDays,0) - ISNULL(AT.LWP,0) ) AS PresentDays
		FROM 
			sHrm.tEmployeeMaster EM
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=EM.OrgId
			INNER JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.EmployeeId = EM.Id  
			INNER JOIN sPayroll.tPayrollGroupMaster PGM ON ESO.PayrollGroupId = PGM.ID
			INNER JOIN sSetup.tDepartmentMaster ODM ON ODM.Id = EJD.OrganizationDepartmentId
			LEFT JOIN sHrm.tEmployeeTypeMaster ETM ON ETM.Id = EJD.EmployeeTypeId			
			INNER JOIN sHrm.tEmployeeAttendance AT ON AT.EmployeeId=EM.Id	
		WHERE 
			ESO.PayrollId = @rPayrollId 
			AND ((ESO.PayrollGroupId=@rPayrollGroupId) OR (@rPayrollGroupId=0))
			AND AT.ForYear = @rForYear AND AT.ForMonth = @rForMonth
			ORDER BY EM.OrgId,EM.Code
END
GO
PRINT N'Altering [sPayroll].[pGetPayProcessEmployeeDetail]...';


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

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

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

	FROM sPayroll.tPayProcess PP INNER JOIN  
	sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId = PP.ID INNER JOIN
	sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = PPE.EmployeeId
	--INNER JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.EmployeeId=EM.EmployeeId 
	INNER JOIN sPayroll.tPayrollYearMaster PY ON PP.PayrollYearId = PY.Id

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


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

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

	 FROM sHrm.vEmployeeCommonDetail EM
	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
	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
	 
 WITH EXECUTE AS CALLER
AS
 SET NOCOUNT ON
 
BEGIN 		
	   SELECT 
		   ISNULL(PS.[ID],0) AS PaySetupId	  		  
		  ,PE.Id AS PayElementId
		  ,PS.SourceId
		  ,[Amount]
		  ,[Percentage]
		  ,ISNULL([ProcessOrder],0) AS ProcessOrder
		  ,ISNULL(PS.[PayrollId],0) AS PayrollId
	      ,PE.Title  AS PayElement
	      ,PE.IsDepend
	      ,EM.Code
	      ,EM.EmployeeName
	     
	      
	FROM  sPayroll.tPayElement PE INNER JOIN  [sPayroll].[tPaySetup] PS ON PE.ID = PS.PayElementId  
		   INNER JOIN sHrm.vEmployeeCommonDetail Em ON Em.EmployeeId = PS.SourceId
		  
   WHERE 
         (Ps.ID = @rId OR ISNULL(@rId,0) = 0)
         AND PE.IsObsolete = 0  AND PE.PayrollId = @rPayrollId
         AND  PS.SourceTypeId = @rSourceTypeId
         AND (PS.SourceId = @rSourceId OR @rSourceId = 0)
         AND (EM.Code LIKE @rEmployeeCode + '%' OR ISNULL(@rEmployeeCode,'') = '')
         AND (EmployeeName LIKE @rEmployeeName + '%' OR ISNULL(@rEmployeeName,'') = '')
         AND (SourceId = @rSourceId OR ISNULL(@rSourceId,0) = 0)
         AND (PE.Id = @rPayElementId OR ISNULL(@rPayElementId,0) = 0)
         Order By EM.OrgId,EM.Code
		 
END
GO
PRINT N'Altering [sPayroll].[pPaySetupGet]...';


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

BEGIN 
       		
		SELECT 
			   ISNULL(PS.[ID],0) AS PaySetupId	  		  
			  ,PE.Id AS PayElementId
			  ,[Amount]
			  ,[Percentage]
			  ,ISNULL([ProcessOrder],0) AS ProcessOrder
			  ,ISNULL(PS.[PayrollId],0) AS PayrollId
			  ,PE.Title  AS PayElement
			  ,[sPayroll].[fGetPaySetupDependentElement](ISNULL(PS.Id,0)) AS PaysetupDependentElement
			  ,ISNULL(PE.IsDepend,0) AS IsDepend
			  ,PE.PayElementDefaultId
		      
		FROM  sPayroll.tPayElement PE LEFT JOIN  [sPayroll].[tPaySetup] PS ON PE.ID = PS.PayElementId AND
			  PS.SourceTypeId = @rSourceTypeId AND PS.SourceId = @rSourceId
			  
	   WHERE PE.IsObsolete = 0  AND PE.PayrollId = @rPayrollId   
	   Order by ProcessOrder
       
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 [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'Creating [sPayroll].[pPayProcessDelete]...';


GO


CREATE PROCEDURE [sPayroll].[pPayProcessDelete]
	 
           @rSalaryMonth tinyint,
           @rSalaryYear smallint,
           @rPayrollYearId int,
           @rPayrollId int,
           @rOrgGroupId int
	    
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 	

	-- Delete For EsiProcess
	DELETE sPayroll.tEsiProcess
			FROM sPayroll.tEsiProcess EP
		INNER JOIN sPayroll.tPayProcessElement PPE  
			ON EP.PayProcessElementId=PPE.ID
		INNER JOIN sPayroll.tPayProcessEmployee PPEM 
			ON PPEM.ID=PPE.PayProcessEmployeeId
		INNER JOIN sPayroll.tPayProcess PP
			ON PP.ID=PPEM.PayProcessId
		INNER JOIN sPayroll.tPayrollYearMaster PYM
			ON PYM.Id=PP.PayrollYearId
	WHERE 
		PP.SalaryMonth=@rSalaryMonth
		AND ((PP.SalaryYear = @rSalaryYear))
		AND ((PP.PayrollYearId = @rPayrollYearId))
		AND ((PYM.PayrollId = @rPayrollId))
		AND ((PYM.OrgGroupId = @rOrgGroupId))


	-- Delete For PfProcess
	DELETE sPayroll.tPfProcess
			FROM sPayroll.tPfProcess PFP
		INNER JOIN sPayroll.tPayProcessElement PPE  
			ON PFP.PayProcessElementId=PPE.ID
		INNER JOIN sPayroll.tPayProcessEmployee PPEM 
			ON PPEM.ID=PPE.PayProcessEmployeeId
		INNER JOIN sPayroll.tPayProcess PP
			ON PP.ID=PPEM.PayProcessId
		INNER JOIN sPayroll.tPayrollYearMaster PYM
			ON PYM.Id=PP.PayrollYearId
	WHERE 
		PP.SalaryMonth=@rSalaryMonth
		AND ((PP.SalaryYear = @rSalaryYear))
		AND ((PP.PayrollYearId = @rPayrollYearId))
		AND ((PYM.PayrollId = @rPayrollId))
		AND ((PYM.OrgGroupId = @rOrgGroupId))
		
	
	-- Delete For PayProcessElement
	DELETE sPayroll.tPayProcessElement
			FROM sPayroll.tPayProcessElement PPE 
		INNER JOIN sPayroll.tPayProcessEmployee PPEM 
			ON PPEM.ID=PPE.PayProcessEmployeeId
		INNER JOIN sPayroll.tPayProcess PP
			ON PP.ID=PPEM.PayProcessId
		INNER JOIN sPayroll.tPayrollYearMaster PYM
			ON PYM.Id=PP.PayrollYearId
	WHERE 
		PP.SalaryMonth=@rSalaryMonth
		AND ((PP.SalaryYear = @rSalaryYear))
		AND ((PP.PayrollYearId = @rPayrollYearId))
		AND ((PYM.PayrollId = @rPayrollId))
		AND ((PYM.OrgGroupId = @rOrgGroupId))
	
	
	-- Delete For PayProcessEmployee
	DELETE sPayroll.tPayProcessEmployee
			FROM sPayroll.tPayProcessEmployee PPEM 
		INNER JOIN sPayroll.tPayProcess PP
			ON PP.ID=PPEM.PayProcessId
		INNER JOIN sPayroll.tPayrollYearMaster PYM
			ON PYM.Id=PP.PayrollYearId
	WHERE 
		PP.SalaryMonth=@rSalaryMonth
		AND ((PP.SalaryYear = @rSalaryYear))
		AND ((PP.PayrollYearId = @rPayrollYearId))
		AND ((PYM.PayrollId = @rPayrollId))
		AND ((PYM.OrgGroupId = @rOrgGroupId))
		
		
	-- Delete For PayProcess
	DELETE sPayroll.tPayProcess
			FROM sPayroll.tPayProcess PP
		INNER JOIN sPayroll.tPayrollYearMaster PYM
			ON PYM.Id=PP.PayrollYearId
	WHERE 
		PP.SalaryMonth=@rSalaryMonth
		AND ((PP.SalaryYear = @rSalaryYear))
		AND ((PP.PayrollYearId = @rPayrollYearId))
		AND ((PYM.PayrollId = @rPayrollId))
		AND ((PYM.OrgGroupId = @rOrgGroupId))				

	SELECT 1 AS Result

END
GO




GO

DELETE FROM sCommon.tTableRowId

WHERE TableTitle in (

'sEExam.tDataBankMaster',
'sEExam.tDataSubjectMaster',
'sEExam.tDataTopicMaster',
'sEExam.tDataTopicTypeMaster', 
'sEExam.tQuestionMaster',
'sEExam.tQuestionOption',
'sEExam.tQuestionParagraph',
'sEExam.tTestTemplateMaster',
'sEExam.tTestTemplateQuestion',
 'sEExam.tTestAssign',
 'sEExam.tTestMaster',
 'sEExam.tTestParticipant',
 'sEExam.tTestParticipantAnswer',
 'sEExam.tTestQuestion',
 'sEExam.tTestTemplateMaster',
 'sEExam.tTestTemplateQuestion'

)

GO
 
DELETE FROM sEExam.tDataBankMaster
DELETE FROM sEExam.tDataSubjectMaster
DELETE FROM sEExam.tDataTopicMaster
DELETE FROM sEExam.tDataTopicTypeMaster
 
DELETE FROM sEExam.tQuestionMaster
DELETE FROM sEExam.tQuestionOption
DELETE FROM sEExam.tQuestionParagraph

DELETE FROM sEExam.tTestAssign
DELETE FROM sEExam.tTestMaster
DELETE FROM sEExam.tTestParticipant
DELETE FROM sEExam.tTestParticipantAnswer
DELETE FROM sEExam.tTestQuestion
DELETE FROM sEExam.tTestTemplateMaster
DELETE FROM sEExam.tTestTemplateQuestion

GO



update   sSetup.tOrganizationMaster SET TermPatternId = 1
WHERE AffiliationId IN (1,2,3)

update   sSetup.tOrganizationMaster SET TermPatternId = 2
WHERE AffiliationId IN (4,5)

update   sSetup.tOrganizationMaster SET TermPatternId = 1
WHERE AffiliationId is null


update   sSetup.tOrganizationMaster SET TermPatternId = 1
WHERE AffiliationId = 0

GO
