GO 
INSERT INTO [sSystem].[tVersionUpdate] ([VersionNumber],[VersionId],[Status],[UpdateScript],[StartDateTime],[EndDateTime],[OrgGroupId])
VALUES('20.10.01',201001,'BEGIN','Script',sCommon.fGetDate(),sCommon.fGetDate(),0)
GO 
 
 
GO
PRINT N'Altering [sCanteen].[tCanteenMaster]...';


GO
ALTER TABLE [sCanteen].[tCanteenMaster]
    ADD [DepositHeadId]        INT NULL,
        [DepositExpenseTypeId] INT NULL;


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


GO
ALTER TABLE [sCommunication].[teContent]
    ADD [CreatedUserId]   BIGINT NULL,
        [CreatedDateTime] DATE   NULL;


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


GO
ALTER TABLE [sFee].[tDepositAdjustment]
    ADD [ReferenceSourceTypeId] SMALLINT NULL,
        [ReferenceSourceId]     BIGINT   NULL;


GO
PRINT N'Altering [sOp].[tPaymentTransaction]...';


GO
ALTER TABLE [sOp].[tPaymentTransaction]
    ADD [PaymentGatewayId]    SMALLINT NULL,
        [IsUpdateQueryStatus] BIT      NULL;


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


GO
CREATE TABLE [sFee].[tFeeAllocationStudent] (
    [AutoId]              BIGINT          IDENTITY (1, 1) NOT NULL,
    [AcademicId]          BIGINT          NOT NULL,
    [FeeSetupId]          INT             NOT NULL,
    [FeeAmount]           DECIMAL (12, 2) NOT NULL,
    [VariableAmount]      DECIMAL (12, 2) NOT NULL,
    [DiscountAmount]      DECIMAL (12, 2) NOT NULL,
    [AdditionalAmount]    DECIMAL (12, 2) NOT NULL,
    [NotApplicableAmount] DECIMAL (12, 2) NOT NULL,
    [ToPayAmount]         DECIMAL (12, 2) NULL,
    [PaidAmount]          DECIMAL (12, 2) NOT NULL,
    [CreatedUserId]       BIGINT          NOT NULL,
    [CreatedDateTime]     DATETIME        NOT NULL,
    [UpdatedUserId]       BIGINT          NULL,
    [UpdatedDateTime]     DATETIME        NULL
);


GO
PRINT N'Creating PK_tFeeAllocationStudent...';


GO
ALTER TABLE [sFee].[tFeeAllocationStudent]
    ADD CONSTRAINT [PK_tFeeAllocationStudent] PRIMARY KEY CLUSTERED ([AutoId] ASC) WITH (ALLOW_PAGE_LOCKS = ON, ALLOW_ROW_LOCKS = ON, PAD_INDEX = OFF, IGNORE_DUP_KEY = OFF, STATISTICS_NORECOMPUTE = OFF);


GO
PRINT N'Creating UK_tFeeAllocationStudent...';


GO
ALTER TABLE [sFee].[tFeeAllocationStudent]
    ADD CONSTRAINT [UK_tFeeAllocationStudent] UNIQUE NONCLUSTERED ([AcademicId] ASC, [FeeSetupId] ASC) WITH (ALLOW_PAGE_LOCKS = ON, ALLOW_ROW_LOCKS = ON, PAD_INDEX = OFF, IGNORE_DUP_KEY = OFF, STATISTICS_NORECOMPUTE = OFF) ON [PRIMARY];


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


GO
CREATE TABLE [sFee].[tFeeClassBatchStatus] (
    [Id]              BIGINT   IDENTITY (1, 1) NOT NULL,
    [ClassId]         INT      NOT NULL,
    [BatchId]         INT      NOT NULL,
    [StatusId]        INT      NOT NULL,
    [UpdatedDateTime] DATETIME NULL
);


GO
PRINT N'Creating PK_tFeeClassBatchStatus...';


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


 


GO


 
GO
PRINT N'Altering [sCertificate].[vPrintTemplateStudentBasicDetails]...';


GO
 
 
ALTER VIEW [sCertificate].[vPrintTemplateStudentBasicDetails]
AS
	SELECT 
	  [sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS StudentName,
	  SM.Code,	
	  DM.Code AS ClassDivision,
	  A.RollNo,
	  BM.Title AS BatchName,
	  SO.DateOfBirth AS DateOfBirth,  	 
	  '[BatchName],[ClassDivision],[Code],[DateOfBirth],[RollNo],[FirstName],[MiddleName],
	  [LastName],[PreviousSchool],[Gender],[Caste],[SubCaste],[BirthPlace],[DOBInWords],[PreviousSchoolYear],
	  [OldGRNo],[PreviousLCDate],[PreviousLCResult],[PreviousLCNumber],[PreviousStandard],
	  [BirthTaluka],[BirthState],[BirthCountry],[BirthDistrict],[Address],[ContactNo],[Email],[Religion],[FamilyCaste],[CasteCategory],[Nationality],[MotherTongue],[BloodGroup],[AadhaarNumber],[PhysicalCategory],
	  [FatherName],[FatherQualification],[FatherOccupation],[FatherContactNo],[FatherOfficeAddress],[FatherEmail],[FatherExStudent],[FatherPassingYear],[FatherIncome],
	  [MotherName],[MotherQualification],[MotherOccupation],[MotherContactNo],[MotherOfficeAddress],[MotherEmail],[MotherExStudent],[MotherPassingYear],[MotherIncome]' As ColumnList
  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.tClassMaster CM
		ON CM.Id=A.ClassId
	INNER JOIN sSetup.tDivisionMaster DM
		ON DM.Id=A.DivisionId
	INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId 
	INNER JOIN sStudent.tStatusMaster STM
		ON STM.Id=SM.StatusId
	INNER JOIN sSetup.tDepartmentMaster DeptM
		ON DeptM.Id=CM.DepartmentId
	INNER JOIN sSetup.tOrganizationMaster OM 
	    ON A.OrgId = OM.Id
	INNER JOIN [sStudent].[tStudentOther] SO
	    ON SO.StudentId=SM.Id
GO
PRINT N'Altering [sCertificate].[vPrintTemplateStudentDetail]...';


GO
 
 

ALTER VIEW [sCertificate].[vPrintTemplateStudentDetail]
 
AS  
  
SELECT 
			A.Id AS AcademicId,
		    DivM.Id AS DivisionId,
		    DivM.DisplayTitle AS DivisionName,
		    CM.Id AS ClassId,
		    CM.DisplayTitle AS ClassName,
		    CM.DisplayTitle+'-'+DivM.DisplayTitle AS ClassDivision,
		    DM.Id AS DepartmentId,
		    DM.DisplayTitle AS DepartmentName,
		    SM.FirstName AS FirstName,
		    SM.MiddleName AS MiddleName,
		    SM.LastName AS LastName,
		    SM.Code,
		    A.RollNo,
		    A.BatchId,
		    BM.Title AS BatchName,
		    CONVERT(VARCHAR(10),SO.DateOfBirth,103) AS DateOfBirth,
		    SA.PreviousSchool,
			ISNULL(GM.Title,'') AS Gender,
			SO.FamilyCast AS Caste,  
			SO.FamilySubCast AS SubCaste,
			SO.BirthPlace,
			SO.BirthDateInWord AS DOBInWords,
			SA.PreviousLCDate AS PreviousLCDate,
			SA.PreviousLCResult AS PreviousLCResult,
			SA.PreviousLCNumber AS PreviousLCNumber,
			SA.AdmissionNumber AS OldGRNo,
			SA.PassingYear AS PreviousSchoolYear,			
			SA.PreviousStandard AS PreviousStandard,
			SO.BirthTaluka AS BirthTaluka,
			SO.BirthState AS BirthState,
			SO.BirthCountry AS BirthCountry,
			SO.BirthDistrict AS BirthDistrict,
			ISNULL(SC.PermanentStreetOne,'')+' '+ISNULL(SC.PresentStreetTwo,'')+' '+ISNULL(SC.PresentStreetThree,'')+' '+ISNULL(SC.PresentCity,'')+' '+ISNULL(SC.PresentState,'')+' '+ISNULL(SC.PresentZipCode,'') AS Address,
			SC.ParentContactNo AS ContactNo,		
			SC.ParentEmail AS Email,
			ISNULL(RM.Title,'') AS Religion,
			SO.FamilyCast AS FamilyCaste,
			ISNULL(CCM.Title,'') AS CasteCategory,
			ISNULL(NM.Title,'') AS Nationality,
			ISNULL(SO.MotherTongue,'') AS MotherTongue,
			ISNULL(BGM.Title,'') As BloodGroup,
			ISNULL(SO.AdhaarNumber,'') AS AadhaarNumber,
			ISNULL(PDCM.Title,'') AS PhysicalCategory,
			SF.FatherName AS FatherName,
			SF.FatherQualification AS FatherQualification,
			SF.FatherOccupation AS FatherOccupation,
			SF.FatherContactNo AS FatherContactNo,
			SF.FatherOfficeAddress AS FatherOfficeAddress,
			SF.FatherMail AS FatherEmail,
			SF.IsFatherExStudent AS FatherExStudent,
			SF.FatherPassOutYear AS FatherPassingYear,
			SF.FatherIncome AS FatherIncome,
			SF.MotherName AS MotherName,
			SF.MotherQualification AS MotherQualification,
			SF.MotherOccupation AS MotherOccupation,
			SF.MotherContactNo AS MotherContactNo,
			SF.MotherOfficeAddress AS MotherOfficeAddress,
			SF.MotherMail AS MotherEmail,
			SF.IsMotherExStudent AS MotherExStudent,
			SF.MotherPassOutYear AS MotherPassingYear,
			SF.MotherIncome AS MotherIncome
	FROM 
			sStudent.tAcademic A
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId
			INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=SM.Id
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDivisionMaster DivM ON DivM.Id=A.DivisionId
			INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id = CM.DepartmentId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
			LEFT JOIN sStudent.tStudentAdmission SA ON SA.StudentId=A.StudentId
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = A.StudentId
			LEFT JOIN sCommon.tBloodGroupMaster BGM ON BGM.Id=SO.BloodGroupId
			LEFT JOIN sCommon.tCastCategoryMaster CCM  ON CCM.Id=SO.CastCategoryId
			LEFT JoIN sCommon.tReligionMaster RM ON RM.Id=SO.ReligionId
			LEFT JOIN sCommon.tMotherTongueMaster MT ON MT.Id = SO.MotherTongueId
			LEFT JOIN sCommon.tCountryMaster NM ON NM.Id = SO.NationalityId
			LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = A.StudentId
			LEFT JOIN sStudent.tStudentHealth SH ON SH.StudentId = A.StudentId
			LEFT JOIN sCommon.tPhysicalDisabilityCategoryMaster PDCM ON PDCM.Id = SH.PhysicalDisabilityCategoryId
			LEFT JOIN sCommon.tGenderMaster GM ON GM.Id = SO.GenderId
GO


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


GO
 

 
ALTER PROCEDURE [sAcademic].[pOnlineLearningAdminListGet]
	 
	 @rEmployeeId bigint,
	 @rSourceTypeId int,
	 @rLearningTypeId int = 0,
	 @rClassId int = 0,
	 @rSubjectId int = 0,
	 @rTopicId int = 0,
	 @rStartDate date = '',
	 @rEndDate date = '',
	 @rIsCompleted int=-1,
	 @rTitle nvarchar(100) ='',
	 @rOrgGroupBatchId int,
	 @rBatchId int,
	 @lUserId bigint,
	 @rOrgId bigint

	 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 

	
	SELECT 
			OL.Id,
			DM.Title AS LearningType,
			ISNULL(EM.FirstName,'') +' ' + ISNULL(EM.MiddleName,'') +' ' + ISNULL(EM.LastName ,'') AS EmployeeName,
			EM.Code AS Code,
			EM.Id AS EmployeeId,
			SM.Title AS SubjectName,
			TM.Title AS Topic,
			CONVERT(NVARCHAR,OL.StartDate,103)+' '+CONVERT(NVARCHAR(5),OL.StartTime,108) as StartDate,
			CONVERT(NVARCHAR,OL.EndDate,103)+' '+CONVERT(NVARCHAR(5),OL.EndTime,108) as EndDate,
			(CASE WHEN OL.IsCompleted=0 THEN 'Pending' ELSE 'Completed' END) AS Status,
			ISNULL(CM.Title,'') AS Class,
			CM.Id AS ClassId,
			(CASE WHEN OL.IsAssignment = 0 THEN 'N' WHEN OL.IsAssignment = NULL THEN '' ELSE 'Y' END) AS IsAssignment,
			(CASE WHEN OL.IsSubmitAssignment = 0 THEN 'N' WHEN OL.IsSubmitAssignment = NULL THEN '' ELSE 'Y' END) AS IsSubmitAssignment
			
			FROM 
				sAcademic.tOnlineLearning OL
				INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=OL.SubjectId
				LEFT JOIN sSetup.tClassMaster CM ON CM.Id = OL.ClassId AND CM.OrgId = @rOrgId
				LEFT JOIN sAcademic.tTopicMaster TM ON TM.Id = OL.TopicId
				INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = OL.TeacherEmployeeId
				INNER JOIN sCommon.tDataMaster DM ON DM.Id = OL.LearningTypeId AND DM.DataTypeId = 3
			

			WHERE
				((OL.LearningTypeId = @rLearningTypeId) OR (@rLearningTypeId = 0))
				AND ((OL.ClassId = @rClassId ) OR (@rClassId=0))
				AND ((OL.SubjectId = @rSubjectId) OR (@rSubjectId = 0))
				AND ((OL.TopicId = @rTopicId) OR (@rTopicId = 0))
				AND ((OL.StartDate >= @rStartDate) OR (ISNULL(@rStartDate,'')=''))
				AND ((OL.StartDate <= @rEndDate) OR (ISNULL(@rEndDate,'')=''))
				AND ((OL.TeacherEmployeeId = @rEmployeeId) OR @rEmployeeId=0)
				--AND ((EM.Id = @rEmployeeId ) OR (@rEmployeeId=0))
				AND ((Convert(int,OL.IsCompleted)=@rIsCompleted) OR (@rIsCompleted = -1))
				AND ((OL.Title like '%' +@rTitle+ '%') OR (ISNULL(@rTitle,'')=''))
				AND (OL.BatchId = @rBatchId)
				--AND CM.OrgId = @rOrgId
				ORDER BY OL.IsCompleted,OL.StartDate,OL.StartTime,OL.EndDate
	
END
GO
PRINT N'Altering [sAlert].[pNotificationLogGet]...';


GO
 
ALTER PROCEDURE [sAlert].[pNotificationLogGet]

		@rOSTypeId tinyint,
		@rUserId bigint,
		@rUserSourceTypeId smallint,
		@rUserSourceId bigint,
		@rSyncedNotificationId bigint,
		@rFromDate Date='',
		@rToDate Date='',
		@rEventId int=0
			 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	
	DECLARE @lAcademicId bigint
	DECLARE @lEmployeeId bigint
	DECLARE @lStudentId bigint
	DECLARE @lDivisionId int
	DECLARE @lClassId int
	DECLARE @lDepartmentId int
	DECLARE @lOrgId int
	
	IF(@rUserSourceTypeId=2003)
	BEGIN
		SELECT 
		@lAcademicId=AcademicId,
		@lStudentId=StudentId,
		@lDivisionId=DivisionId,
		@lClassId=ClassId,
		@lDepartmentId=DepartmentId,
		@lOrgId=OrgId
		FROM sStudent.vStudentAcademic WHERE StudentId = @rUserSourceId AND IsActiveBatch=1
	 
		SELECT 
				NL.Id AS NotificationId,
				NL.EventId,
				NL.DocumentId,
				NL.MessageTitle,
				NL.NotificationMessage AS 'Message',
				CONVERT(VARCHAR,NL.CreatedDateTime,103)+' '+ left(right('0'+LTRIM(RIGHT(CONVERT(varchar,NL.CreatedDateTime,100),8)),7),5)+ ' ' + right(RIGHT('0'+LTRIM(RIGHT(CONVERT(varchar,NL.CreatedDateTime,100),8)),7),2) AS CreatedDateTime,
				--CONVERT(VARCHAR(25), NL.CreatedDateTime, 100) AS CreatedDateTime
				EM.Title as EventName
		FROM 
			sAlert.tNotificationLog NL
			LEFT JOIN sAlert.tEventMaster EM ON EM.Id = NL.EventId
		WHERE 
		(
		(NL.SourceId=@lAcademicId) AND (NL.SourceTypeId=2001)
		OR (NL.SourceId=@lStudentId) AND (NL.SourceTypeId=2003)
		OR (NL.SourceId=@lDivisionId) AND (NL.SourceTypeId=2005)
		OR (NL.SourceId=@lClassId) AND (NL.SourceTypeId=2016)
		OR (NL.SourceId=@lDepartmentId) AND (NL.SourceTypeId=2017)
		OR (NL.SourceId=@lOrgId) AND (NL.SourceTypeId=2021)	
		) AND NL.Id > @rSyncedNotificationId AND OSTypeId=@rOSTypeId
		AND ((NL.EventId = @rEventId) OR (@rEventId = 0))
		AND NL.EventId NOT IN (14,15)
		AND (convert(date,NL.CreatedDateTime)>=@rFromDate OR ISNULL(@rFromDate,'')='')
		AND (convert(date,NL.CreatedDateTime)<=@rToDate OR ISNULL(@rToDate,'')='' )
		
		UNION ALL
		
		SELECT 
				NL.Id AS NotificationId,
				NL.EventId,
				NL.DocumentId,
				NL.MessageTitle,
				NL.NotificationMessage AS 'Message',
				CONVERT(VARCHAR,NL.CreatedDateTime,103)+' '+ left(right('0'+LTRIM(RIGHT(CONVERT(varchar,NL.CreatedDateTime,100),8)),7),5)+ ' ' + right(RIGHT('0'+LTRIM(RIGHT(CONVERT(varchar,NL.CreatedDateTime,100),8)),7),2) AS CreatedDateTime,
				--CONVERT(VARCHAR(25), NL.CreatedDateTime, 100) AS CreatedDateTime
				EM.Title as EventName
		FROM 
			sAlert.tNotificationLog NL
			LEFT JOIN sAlert.tEventMaster EM ON EM.Id = NL.EventId
		WHERE 
		(
		(NL.SourceId=@lAcademicId) AND (NL.SourceTypeId=2001)
		OR (NL.SourceId=@lStudentId) AND (NL.SourceTypeId=2003)
		OR (NL.SourceId=@lDivisionId) AND (NL.SourceTypeId=2005)
		OR (NL.SourceId=@lClassId) AND (NL.SourceTypeId=2016)
		OR (NL.SourceId=@lDepartmentId) AND (NL.SourceTypeId=2017)
		OR (NL.SourceId=@lOrgId) AND (NL.SourceTypeId=2021)	
		) AND NL.Id > @rSyncedNotificationId AND OSTypeId=@rOSTypeId
		AND ((NL.EventId = @rEventId) OR (@rEventId = 0))
		AND (NL.EventId = 14) AND (SourceTypeId=2001 OR NL.SourceTypeId=2003 OR  NL.SourceTypeId=2005 OR NL.SourceTypeId=2016)
		AND (convert(date,NL.CreatedDateTime)>=@rFromDate OR ISNULL(@rFromDate,'')='')
		AND (convert(date,NL.CreatedDateTime)<=@rToDate OR ISNULL(@rToDate,'')='' )
		
		
		UNION ALL
		
		SELECT 
				NL.Id AS NotificationId,
				NL.EventId,
				NL.DocumentId,
				NL.MessageTitle,
				NL.NotificationMessage AS 'Message',
				CONVERT(VARCHAR,NL.CreatedDateTime,103)+' '+ left(right('0'+LTRIM(RIGHT(CONVERT(varchar,NL.CreatedDateTime,100),8)),7),5)+ ' ' + right(RIGHT('0'+LTRIM(RIGHT(CONVERT(varchar,NL.CreatedDateTime,100),8)),7),2) AS CreatedDateTime,
				--CONVERT(VARCHAR(25), NL.CreatedDateTime, 100) AS CreatedDateTime
				EM.Title as EventName
		FROM 
			sAlert.tNotificationLog NL
			INNER JOIN sCommunication.tCircularScope CS ON CS.SourceTypeId = NL.SourceTypeId AND CS.SourceId = NL.SourceId AND CS.CircularId=NL.DocumentId AND CS.AssigneeToId = 2
			INNER JOIN sCommunication.tCircular C ON C.Id = CS.CircularId AND CS.CircularId=NL.DocumentId  AND (C.AssigneeId=2 OR C.AssigneeId=1) 
			LEFT JOIN sAlert.tEventMaster EM ON EM.Id = NL.EventId
		WHERE 
		(
		(NL.SourceId=@lAcademicId) AND (NL.SourceTypeId=2001)
		OR (NL.SourceId=@lStudentId) AND (NL.SourceTypeId=2003)
		OR (NL.SourceId=@lDivisionId) AND (NL.SourceTypeId=2005)
		OR (NL.SourceId=@lClassId) AND (NL.SourceTypeId=2016)
		OR (NL.SourceId=@lDepartmentId) AND (NL.SourceTypeId=2017)
		OR (NL.SourceId=@lOrgId) AND (NL.SourceTypeId=2021)	
		) AND NL.Id > @rSyncedNotificationId AND OSTypeId=@rOSTypeId
		AND ((NL.EventId = @rEventId) OR (@rEventId = 0))
		AND NL.EventId = 14 AND NL.SourceTypeId=2021
		AND (convert(date,NL.CreatedDateTime)>=@rFromDate OR ISNULL(@rFromDate,'')='')
		AND (convert(date,NL.CreatedDateTime)<=@rToDate OR ISNULL(@rToDate,'')='' )
		 
		UNION ALL
		
		SELECT 
				NL.Id AS NotificationId,
				NL.EventId,
				NL.DocumentId,
				NL.MessageTitle,
				NL.NotificationMessage AS 'Message',
				CONVERT(VARCHAR,NL.CreatedDateTime,103)+' '+ left(right('0'+LTRIM(RIGHT(CONVERT(varchar,NL.CreatedDateTime,100),8)),7),5)+ ' ' + right(RIGHT('0'+LTRIM(RIGHT(CONVERT(varchar,NL.CreatedDateTime,100),8)),7),2) AS CreatedDateTime,
				--CONVERT(VARCHAR(25), NL.CreatedDateTime, 100) AS CreatedDateTime
				EM.Title as EventName
		FROM 
			sAlert.tNotificationLog NL
			INNER JOIN sCommunication.tCircularScope CS ON CS.SourceTypeId = NL.SourceTypeId AND CS.SourceId = NL.SourceId AND CS.CircularId=NL.DocumentId AND CS.AssigneeToId = 2
			INNER JOIN sCommunication.tCircular C ON C.Id = CS.CircularId AND CS.CircularId=NL.DocumentId AND (C.AssigneeId=2 OR C.AssigneeId=1)
			LEFT JOIN sAlert.tEventMaster EM ON EM.Id = NL.EventId
		WHERE 
		(
		(NL.SourceId=@lAcademicId) AND (NL.SourceTypeId=2001)
		OR (NL.SourceId=@lStudentId) AND (NL.SourceTypeId=2003)
		OR (NL.SourceId=@lDivisionId) AND (NL.SourceTypeId=2005)
		OR (NL.SourceId=@lClassId) AND (NL.SourceTypeId=2016)
		OR (NL.SourceId=@lDepartmentId) AND (NL.SourceTypeId=2017)
		OR (NL.SourceId=@lOrgId) AND (NL.SourceTypeId=2021)	
		) AND NL.Id > @rSyncedNotificationId AND OSTypeId=@rOSTypeId
		AND ((NL.EventId = @rEventId) OR (@rEventId = 0))
		AND NL.EventId = 14 AND NL.SourceTypeId=2017
		AND (convert(date,NL.CreatedDateTime)>=@rFromDate OR ISNULL(@rFromDate,'')='')
		AND (convert(date,NL.CreatedDateTime)<=@rToDate OR ISNULL(@rToDate,'')='' )

		UNION ALL
		
		SELECT 
				NL.Id AS NotificationId,
				NL.EventId,
				NL.DocumentId,
				NL.MessageTitle,
				NL.NotificationMessage AS 'Message',
				CONVERT(VARCHAR,NL.CreatedDateTime,103)+' '+ left(right('0'+LTRIM(RIGHT(CONVERT(varchar,NL.CreatedDateTime,100),8)),7),5)+ ' ' + right(RIGHT('0'+LTRIM(RIGHT(CONVERT(varchar,NL.CreatedDateTime,100),8)),7),2) AS CreatedDateTime,
				--CONVERT(VARCHAR(25), NL.CreatedDateTime, 100) AS CreatedDateTime
				EM.Title as EventName
		FROM 
			sAlert.tNotificationLog NL
			INNER JOIN sCommunication.tAssignmentScope AC ON AC.SourceTypeId = NL.SourceTypeId AND AC.SourceId = NL.SourceId AND AC.AssignmentId=NL.DocumentId
			INNER JOIN sCommunication.tAssignment A ON A.Id = AC.AssignmentId AND AC.AssignmentId=NL.DocumentId 
			LEFT JOIN sAlert.tEventMaster EM ON EM.Id = NL.EventId
		WHERE 
		(
		(NL.SourceId=@lDivisionId) AND (NL.SourceTypeId=2005)
		) AND NL.Id > @rSyncedNotificationId AND OSTypeId=@rOSTypeId
		AND ((NL.EventId = @rEventId) OR (@rEventId = 0))
		AND NL.EventId = 15 AND NL.SourceTypeId=2005
		AND (convert(date,NL.CreatedDateTime)>=@rFromDate OR ISNULL(@rFromDate,'')='')
		AND (convert(date,NL.CreatedDateTime)<=@rToDate OR ISNULL(@rToDate,'')='' )
		
	END
		
	IF(@rUserSourceTypeId=95)
	BEGIN
	
		SELECT 
		@lEmployeeId=EmployeeId,
		@lDepartmentId=OrganizationDepartmentId,
		@lOrgId=OrgId
		FROM sHrm.tEmployeeJobDetail WHERE EmployeeId = @rUserSourceId
		SELECT 
				NL.Id AS NotificationId,
				NL.EventId,
				NL.DocumentId,
				NL.MessageTitle,
				NL.NotificationMessage AS 'Message',
				CONVERT(VARCHAR,NL.CreatedDateTime,103)+' '+ left(right('0'+LTRIM(RIGHT(CONVERT(varchar,NL.CreatedDateTime,100),8)),7),5)+ ' ' + right(RIGHT('0'+LTRIM(RIGHT(CONVERT(varchar,NL.CreatedDateTime,100),8)),7),2) AS CreatedDateTime,
				--CONVERT(VARCHAR(25), NL.CreatedDateTime, 100) AS CreatedDateTime
				EM.Title as EventName
		FROM 
			sAlert.tNotificationLog NL
			LEFT JOIN sAlert.tEventMaster EM ON EM.Id = NL.EventId
		WHERE 
		(
		(NL.SourceId=@lEmployeeId) AND (NL.SourceTypeId=95)
		OR (NL.SourceId=@lDepartmentId) AND (NL.SourceTypeId=2017)
		OR (NL.SourceId=@lOrgId) AND (NL.SourceTypeId=2021)	
		) AND NL.Id > @rSyncedNotificationId AND OSTypeId=@rOSTypeId
		AND ((NL.EventId = @rEventId) OR (@rEventId = 0))
		AND NL.EventId != 14
		AND (convert(date,NL.CreatedDateTime)>=@rFromDate OR ISNULL(@rFromDate,'')='')
		AND (convert(date,NL.CreatedDateTime)<=@rToDate OR ISNULL(@rToDate,'')='' )
		
		
		
		UNION ALL
		
		SELECT 
				NL.Id AS NotificationId,
				NL.EventId,
				NL.DocumentId,
				NL.MessageTitle,
				NL.NotificationMessage AS 'Message',
				CONVERT(VARCHAR,NL.CreatedDateTime,103)+' '+ left(right('0'+LTRIM(RIGHT(CONVERT(varchar,NL.CreatedDateTime,100),8)),7),5)+ ' ' + right(RIGHT('0'+LTRIM(RIGHT(CONVERT(varchar,NL.CreatedDateTime,100),8)),7),2) AS CreatedDateTime,
				--CONVERT(VARCHAR(25), NL.CreatedDateTime, 100) AS CreatedDateTime
				EM.Title as EventName
		FROM 
			sAlert.tNotificationLog NL
			LEFT JOIN sAlert.tEventMaster EM ON EM.Id = NL.EventId
		WHERE 
		(
		(NL.SourceId=@lEmployeeId) AND (NL.SourceTypeId=95)
		OR (NL.SourceId=@lDepartmentId) AND (NL.SourceTypeId=2017)
		OR (NL.SourceId=@lOrgId) AND (NL.SourceTypeId=2021)	
		) AND NL.Id > @rSyncedNotificationId AND OSTypeId=@rOSTypeId
		AND ((NL.EventId = @rEventId) OR (@rEventId = 0))
		AND (NL.EventId = 14 AND NL.SourceTypeId=95)
		AND (convert(date,NL.CreatedDateTime)>=@rFromDate OR ISNULL(@rFromDate,'')='')
		AND (convert(date,NL.CreatedDateTime)<=@rToDate OR ISNULL(@rToDate,'')='' )
		
		UNION ALL
		
		SELECT 
				NL.Id AS NotificationId,
				NL.EventId,
				NL.DocumentId,
				NL.MessageTitle,
				NL.NotificationMessage AS 'Message',
				CONVERT(VARCHAR,NL.CreatedDateTime,103)+' '+ left(right('0'+LTRIM(RIGHT(CONVERT(varchar,NL.CreatedDateTime,100),8)),7),5)+ ' ' + right(RIGHT('0'+LTRIM(RIGHT(CONVERT(varchar,NL.CreatedDateTime,100),8)),7),2) AS CreatedDateTime,
				--CONVERT(VARCHAR(25), NL.CreatedDateTime, 100) AS CreatedDateTime
				EM.Title as EventName
		FROM 
			sAlert.tNotificationLog NL
			INNER JOIN sCommunication.tCircularScope CS ON CS.SourceTypeId = NL.SourceTypeId AND CS.SourceId = NL.SourceId AND CS.CircularId=NL.DocumentId AND CS.AssigneeToId = 3
			INNER JOIN sCommunication.tCircular C ON C.Id = CS.CircularId AND CS.CircularId=NL.DocumentId  AND (C.AssigneeId=3 OR C.AssigneeId=1)
			LEFT JOIN sAlert.tEventMaster EM ON EM.Id = NL.EventId
		WHERE 
		(
		(NL.SourceId=@lEmployeeId) AND (NL.SourceTypeId=95)
		OR (NL.SourceId=@lDepartmentId) AND (NL.SourceTypeId=2017)
		OR (NL.SourceId=@lOrgId) AND (NL.SourceTypeId=2021)	
		) AND NL.Id > @rSyncedNotificationId AND OSTypeId=@rOSTypeId
		AND ((NL.EventId = @rEventId) OR (@rEventId = 0))
		AND NL.EventId = 14 AND NL.SourceTypeId=2021
		AND (convert(date,NL.CreatedDateTime)>=@rFromDate OR ISNULL(@rFromDate,'')='')
		AND (convert(date,NL.CreatedDateTime)<=@rToDate OR ISNULL(@rToDate,'')='' )

		UNION ALL
		
		SELECT 
				NL.Id AS NotificationId,
				NL.EventId,
				NL.DocumentId,
				NL.MessageTitle,
				NL.NotificationMessage AS 'Message',
				CONVERT(VARCHAR,NL.CreatedDateTime,103)+' '+ left(right('0'+LTRIM(RIGHT(CONVERT(varchar,NL.CreatedDateTime,100),8)),7),5)+ ' ' + right(RIGHT('0'+LTRIM(RIGHT(CONVERT(varchar,NL.CreatedDateTime,100),8)),7),2) AS CreatedDateTime,
				--CONVERT(VARCHAR(25), NL.CreatedDateTime, 100) AS CreatedDateTime
				EM.Title as EventName
		FROM 
			sAlert.tNotificationLog NL
			INNER JOIN sCommunication.tCircularScope CS ON CS.SourceTypeId = NL.SourceTypeId AND CS.SourceId = NL.SourceId AND CS.CircularId=NL.DocumentId AND CS.AssigneeToId = 3
			INNER JOIN sCommunication.tCircular C ON C.Id = CS.CircularId AND CS.CircularId=NL.DocumentId AND (C.AssigneeId=3 OR C.AssigneeId=1)
			LEFT JOIN sAlert.tEventMaster EM ON EM.Id = NL.EventId
		WHERE 
		(
		(NL.SourceId=@lEmployeeId) AND (NL.SourceTypeId=95)
		OR (NL.SourceId=@lDepartmentId) AND (NL.SourceTypeId=2017)
		OR (NL.SourceId=@lOrgId) AND (NL.SourceTypeId=2021)	
		) AND NL.Id > @rSyncedNotificationId AND OSTypeId=@rOSTypeId
		AND ((NL.EventId = @rEventId) OR (@rEventId = 0))
		AND NL.EventId = 14 AND NL.SourceTypeId=2017
		AND (convert(date,NL.CreatedDateTime)>=@rFromDate OR ISNULL(@rFromDate,'')='')
		AND (convert(date,NL.CreatedDateTime)<=@rToDate OR ISNULL(@rToDate,'')='' )
		
	END
END
GO
PRINT N'Altering [sAlert].[pSMSViewGet]...';


GO

ALTER PROCEDURE [sAlert].[pSMSViewGet]
	@rMobileNumber nvarchar(50),
	@rEmail nvarchar(50),
	@rOrgId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
declare  @lAlertgrid NVARCHAR(max)=''
BEGIN

select AL.SourceEvent,EM.Title,AL.AlertSubject,[sCommon].[fXMLTagsReplace](AL.AlertMessage) as AlertMessage,AL.CreatedDateTime
Into #temp
FROM
		sAlert.tAlertLog AL
		INNER JOIN sAlert.tEventMaster EM ON EM.Id=AL.EventId
WHERE  ((AL.ContactId = @rMobileNumber) OR (AL.ContactId = @rEmail))
	And AL.OrgId=@rOrgId
ORDER BY AL.CreatedDateTime DESC
	
--select * from #temp return

    SELECT  @lAlertgrid = @lAlertgrid + '<tr>
	<td align="left" scope="col">' + isnull(SourceEvent,'') + '</td>
	<td align="left" scope="col">' + isnull(Title,'') + '</td>
	<td align="left" scope="col">' +  isnull(AlertSubject,'') + '</td>
	<td align="left" scope="col">' +  isnull(AlertMessage,'') + '</td>
	<td align="left" scope="col">' + Convert(varchar,isnull(CreatedDateTime,''),120) + '</td>
	</tr>'	
	FROM #temp
	--	sAlert.tAlertLog AL
	--	INNER JOIN sAlert.tEventMaster EM ON EM.Id=AL.EventId
	--WHERE  ((AL.ContactId = @rMobileNumber) OR (AL.ContactId = @rEmail))
	--And AL.OrgId=@rOrgId
END
 SELECT ISNULL(@lAlertgrid,'') AS Alertgrid
 
 DROP TABLE #temp
GO
PRINT N'Altering [sAssessment].[pExamListGet]...';


GO

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

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


GO
 
ALTER PROCEDURE [sAssessment].[pGeneralExamCustomSearchGet]
(
	@rOrgId smallint,
	@rBatchId int,
	@rOrderBy nvarchar(max) = 'RollNo',
	@rCode [nvarchar](20) = '',
	@rFirstName [nvarchar](50) = '',	
	@rLastName [nvarchar](50) = '',
	@rPageIndex int = null,
	@rDivisionId nvarchar(max) = '',
	@rExamId nvarchar(max) = '',
	@rFromMarks decimal(5,2),
	@rToMarks decimal(5,2),
	@rFromGradePoint decimal(6,2),
	@rToGradePoint decimal(6,2),
	@rFromRankNumber int,
	@rToRankNumber int,
	@rFromPercentage decimal(5,2),
	@rToPercentage decimal(5,2),
	@rFromPercentile decimal(5,2),
	@rToPercentile decimal(5,2),
	@rResultGrade nvarchar(10),
	@rCreatedUserId bigint,
	@rDropDownStatusId int,
	@rDropDownClassId int,
	@rDropDownDivisionId int,
	@rDropDownExamSubGroupId int,
	@rDepartmentId int=0,
	@rCastCategoryId nvarchar(max) = ''
 )
AS
SET NOCOUNT ON
BEGIN
	SET @rOrderBy=Replace(@rOrderBy,'GR No','Code')
	SET @rOrderBy=Replace(@rOrderBy,'ID No','Code')
	DECLARE @Sql nvarchar(MAX)
	
	SET @rCode = sCommon.fSearchStringGet(@rCode)
	SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
	SET @rLastName = sCommon.fSearchStringGet(@rLastName)
	SET @rResultGrade = sCommon.fSearchStringGet(@rResultGrade)
	
	
	SELECT * into #TempExam11
	FROM sAssessment.vGeneralExamCustomSearch ECS
	WHERE (ECS.OrgId = @rOrgId) AND (ECS.BatchId = @rBatchId)
	AND ((ECS.Code Like @rCode + '%') OR (@rCode = ''))
	AND ((ECS.FirstName Like @rFirstName  + '%') OR (@rFirstName = ''))
	AND ((ECS.LastName Like @rLastName + '%')OR(@rLastName = ''))
	AND ((ECS.TotalObtain >= @rFromMarks) OR (@rFromMarks=0))
	AND ((ECS.TotalObtain <= @rToMarks) OR (@rToMarks=0))
	AND ((ECS.ResultGradePoint >= @rFromGradePoint) OR (@rFromGradePoint=0))
	AND ((ECS.ResultGradePoint <= @rToGradePoint) OR (@rToGradePoint=0))
	AND ((ECS.RankNumber >= @rFromRankNumber) OR (@rFromRankNumber=0))
	AND ((ECS.RankNumber <= @rToRankNumber) OR (@rToRankNumber=0))
	AND ((ECS.Percentage >= @rFromPercentage) OR (@rFromPercentage=0))
	AND ((ECS.Percentage <= @rToPercentage) OR (@rToPercentage=0))
	AND ((ECS.Percentile >= @rFromPercentile) OR (@rFromPercentile=0))
	AND ((ECS.Percentile <= @rToPercentile) OR (@rToPercentile=0))
	AND ((ECS.ResultGrade Like @rResultGrade + '%')OR(@rResultGrade = ''))
	AND (ECS.DivisionId In( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionId,','))OR @rDivisionId='')
	AND (ECS.ExamId In( SELECT cast(item as int) FROM  sCommon.fnsplit(@rExamId,','))OR @rExamId='')
	AND ((ECS.StatusId = @rDropDownStatusId) OR (@rDropDownStatusId=0))
	AND ((ECS.ClassId = @rDropDownClassId) OR (@rDropDownClassId=0))
	AND ((ECS.DivisionId = @rDropDownDivisionId) OR (@rDropDownDivisionId=0))
	AND ((ECS.ExamSubGroupId = @rDropDownExamSubGroupId) OR (@rDropDownExamSubGroupId=0))
	AND ((ECS.DepartmentId =@rDepartmentId) OR (@rDepartmentId =0))
	AND (ISNULL(ECS.CastCategoryId,'') IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rCastCategoryId,','))OR @rCastCategoryId='')
	SET @sql='SELECT Code AS Code,Name,ClassName,RollNo,TotalMarks,TotalObtain,
	ResultStatus,ResultGrade,ResultGradePoint,RankNumber,Percentage,Percentile,
	ResultReMark,OtherRemark1,ExamName FROM #TempExam11 ORDER BY ' + @rOrderBy
	
	exec(@Sql)
	
	create table #TEMPExam
	(
		tid int identity(1,1),t_AcedemicId bigint,t_ResultId bigint
	)
	SET @sql='insert into #TEMPExam SELECT AcademicId,ResultId FROM #TempExam11 ORDER BY ' + @rOrderBy

	exec (@sql)

	declare @lTotalRecords int,@lPageSize int = 10,@lPaging varchar(max)='',@lResult varchar(max)=''
	
	select @lTotalRecords = count(*) from #TEMPExam
	select @lPaging = @lPaging + dbo.fnc_searchpagingformat(@rPageIndex,@lTotalRecords,@lPageSize)
	 
	select @lResult = @lResult + '<tr><td>' + isnull(Code,'') + '</td><td>' + isnull(Name,'') + '</td>
	<td>' + isnull(convert(varchar,RollNo),'') + '</td><td>' + isnull(ExamName,'') + '</td>
	<td>' + isnull(convert(varchar,TotalMarks),'') + '</td><td>' + isnull(convert(varchar,TotalObtain),'') + '</td>
	<td>' + isnull(ResultStatus,'') + '</td><td>' + isnull(ResultGrade,'') + '</td>

	<td>' + isnull(convert(varchar,RankNumber),'') + '</td>
	<td>' + isnull(convert(varchar,Percentage),'') + '</td><td>' + isnull(convert(varchar,Percentile),'') + '</td>
	<td>' + isnull(ResultReMark,'') + '</td><td>' + isnull(OtherRemark1,'') + '</td></tr>' 
	from #TempExam11,#TEMPExam
	where AcademicId = t_AcedemicId and  ResultId = t_ResultId and tid between ((@lPageSize * (@rPageIndex - 1)) + 1) AND (@lPageSize * @rPageIndex)
	Order By tid
	
	select @lResult as StudentList,@lPaging as Paging,@lTotalRecords as TotalRecords
	
	DROP table #TEMPExam
	DROP Table #TempExam11
	
		--<td>' + isnull(convert(varchar,ResultGradePoint),'') + '</td>
END
GO
PRINT N'Altering [sAssessment].[pStudentResultViewGet]...';


GO

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


GO
ALTER PROCEDURE [sAudit].[pActivityLogGet]
	@rOrgGroupId int,
	@rOrgId int,
	@rUserName nvarchar(100),
	@rScreenName nvarchar(100),
	@rActivity nvarchar(500),
	@rFromDate date,
	@rToDate date,
	@rOSTypeId tinyint=0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
SET @rScreenName = sCommon.fSearchStringGet(@rScreenName)
SET @rActivity = sCommon.fSearchStringGet(@rActivity)
SET @rToDate = DATEADD(day,1,@rToDate)
       SELECT 
            AL.OrgGroupId,
            AL.OrgId,
            OM.Title AS OrganizationName,
            AL.UserId,
			U.DisplayTitle AS UserName,
			U.LoginTitle,
			U.SessionId,
			S.Title AS ScreenName,
			AL.AuditDate,
			(CASE WHEN AL.ScreenId=126
				  THEN AL.Activity		
			      WHEN AL.ScreenId=20878
				  THEN AL.Activity		
				  WHEN AL.ScreenId=30179
				  THEN AL.Activity
			 ELSE SUBSTRING(AL.Activity, CHARINDEX(' ', AL.Activity)+1, LEN(AL.Activity)-(CHARINDEX(' ', AL.Activity)-1))  END)AS  Activity,			
			ISNULL(AL.RecordSourceId,0) AS RecordSourceId,
			ISNULL(AL.RecordDetail,'') AS RecordDetail,
			ISNULL(OS.Title,'') AS OSType
			
       FROM 
		   sAudit.tActivityLog AL
		   INNER JOIN sSecurity.tUser U ON U.Id = AL.UserId
		   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = AL.OrgId
		   INNER JOIN sSecurity.tScreen S ON S.Id = AL.ScreenId
		   LEFT JOIN sAlert.tOSType OS ON OS.Id = AL.OSTypeId
       WHERE
		   AL.OrgGroupId = @rOrgGroupId
		   AND ((AL.OrgId = @rOrgId) OR (@rOrgId=0))
		   AND ((U.DisplayTitle = @rUserName) OR (@rUserName = ''))
		   AND ((S.Title LIKE @rScreenName) OR (@rScreenName = ''))
		   AND ((AL.Activity LIKE @rActivity) OR (@rActivity = ''))
		   AND (AL.AuditDate >= @rFromDate)
		   AND (AL.AuditDate <= @rToDate)
		   AND ((AL.OSTypeId = @rOSTypeId) OR (@rOSTypeId=0))
       ORDER BY 
			AL.AuditDate DESC
END
GO
PRINT N'Altering [sCanteen].[pCanteenMasterAdd]...';


GO

ALTER PROCEDURE [sCanteen].[pCanteenMasterAdd]
	 
        @rId int,
		@rNumber  int,
		@rCode nvarchar(20),
		@rTitle nvarchar(100),
		@rIsObsolete bit,
		@rOrgGroupId smallint,
		@rCreatedUserId bigint,
		@rUpdatedUserId bigint,
		@rOrderIndex int,
		@rDepositHeadId bigint,
		@rDepositExpenseTypeId bigint
		
		
		
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	IF(@rId = 0)	
	BEGIN  
		
		If Exists(select 1 from sCanteen.tCanteenMaster  where Code=@rCode AND OrgGroupId=@rOrgGroupId )
		Begin
			select -102 as Result
			RETURN
		End
		If Exists(select 1 from sCanteen.tCanteenMaster where Title=@rTitle AND OrgGroupId=@rOrgGroupId)
			BEGIN
			select -103 as Result
			RETURN
		END 
	END
	ELSE
	BEGIN
		--
		If  Exists(select Id from sCanteen.tCanteenMaster where Title=@rTitle AND OrgGroupId=@rOrgGroupId AND Id<>@rId)
		Begin
			select -103 as Result
			RETURN
		End

	END
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber int

	IF(@rId = 0)	
	BEGIN
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sCanteen.tCanteenMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sCanteen.tCanteenMaster
		(
			Id,
			Title,
			Number,
			Code,
			IsObsolete,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime,
			OrgGroupId ,
			OrderIndex,
			DepositHeadId,
			DepositExpenseTypeId
		)
	VALUES
		(
			@lNextNumber,
			@rTitle,
			@rNumber,
			@rCode,
			@rIsObsolete,
			@rCreatedUserId,
			sCommon.fGetDate(), 
			@rUpdatedUserId,
			sCommon.fGetDate(),
			@rOrgGroupId,
			@rOrderIndex,
			@rDepositHeadId,
			@rDepositExpenseTypeId
		)
		
		  INSERT INTO sSecurity.tUserAccess
           (
           SourceTypeId
           ,SourceId
           ,[UserId]
           
           )
		   SELECT 
		   2026
		   ,@lNextNumber
		   ,@rCreatedUserId
		   
		    SELECT @lNextNumber AS Result
		   
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sCanteen.tCanteenMaster
	    SET
			Title=@rTitle,
			Number=@rNumber,
			Code=@rCode,
			IsObsolete=@rIsObsolete,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate(),
			OrderIndex=@rOrderIndex,
			DepositHeadId=@rDepositHeadId,
			DepositExpenseTypeId=@rDepositExpenseTypeId
			
	      
	      WHERE Id = @rId
	      SELECT @lNextNumber AS Result
	 END  	

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


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

BEGIN 
	 IF @rIsSearch = 1
		BEGIN
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		END
	
	SELECT 
	
			CM.Id,
			CM.Title,
		    CM.Code,
		    CM.Number,
			CM.IsObsolete,
			CM.OrderIndex,
			ISNULL(CM.DepositHeadId,0)AS DepositHeadId,
			ISNULL(CM.DepositExpenseTypeId,0)AS DepositExpenseTypeId
      
  FROM 
            sCanteen.tCanteenMaster CM
            
  WHERE   
           ((CM.Id = @rId) OR (@rId = 0))
	       AND ((CM.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
	       AND ((CM.Code like @rCode) OR (ISNULL(@rCode,'') = ''))
	       AND CM.OrgGroupId=@rOrgGroupId
	      order by OrderIndex desc
END
GO
PRINT N'Altering [sCanteen].[pDailyMenuListADD]...';


GO

ALTER PROCEDURE [sCanteen].[pDailyMenuListADD]
	(
		@rOrgGroupId int,
		@rXml  nvarchar(MAX),
		@rCanteenId int,
		@rBreakTypeId int,		
		@rCreatedUserId bigint ,
		@rMenuMonth tinyint,
		@rMenuYear smallint,
		@rClassId int=0
		
	)
AS

SET NOCOUNT ON

BEGIN

 

DECLARE @lInterrorCode INT,
			@intDoc INT
DECLARE @lNextNumber BIGINT			
 
	EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXml
	--IF(@rClassId <> 0)
	--BEGIN
	--DELETE FROM sCanteen.tDailyMenu WHERE BreakTypeId=@rBreakTypeId AND MenuMonth=@rMenuMonth AND MenuYear=@rMenuYear AND ClassId=@rClassId
	--END
	--ELSE
	--BEGIN
	DELETE FROM sCanteen.tDailyMenu WHERE BreakTypeId=@rBreakTypeId AND MenuMonth=@rMenuMonth AND MenuYear=@rMenuYear AND ClassId=@rClassId
	--END
	 
	
	 EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sCanteen.tDailyMenu', 0, 1, 1,@outNextNumber = @lNextNumber output
	INSERT INTO sCanteen.tDailyMenu
	(		
	CanteenId,
	Id,
	MenuDate,
	BreakTypeId,
	Title,
	MenuItems,
	CreatedUserId,
	CreatedDateTime,
	UpdatedUserId,
	UpdatedDateTime,
	MenuMonth,
	MenuYear,
	ClassId
		
			
	)
	SELECT	
			@rCanteenId,	
			@lNextNumber + ROW_NUMBER() OVER(ORDER BY Title ) ,
			A.MenuDate,
			@rBreakTypeId,
			A.Title,
			A.MenuItems,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rCreatedUserId,
			sCommon.fGetDate() ,
			@rMenuMonth ,
			@rMenuYear ,
			@rClassId

	FROM OPENXML (@intDoc, '/Table/DailyMenu', 1)
	WITH
	(
			 MenuDate date,
		   	Title nvarchar(100),
			MenuItems nvarchar(300)						 
	)A  
	

	EXEC sp_xml_removedocument @intDoc
	
	SELECT @lNextNumber = MAX(DM.ID) FROM sCanteen.tDailyMenu DM
	INNER JOIN sCanteen.tCanteenMaster CM ON DM.CanteenId=CM.Id Where CM.OrgGroupId=@rOrgGroupId
    EXECUTE sCommon.pTableRowIdModify @rOrgGroupId, @rTableTitle = 'sCanteen.tDailyMenu', @rCurrentNumber = @lNextNumber 

	SELECT 1 as Result
	 
END
GO
PRINT N'Altering [sCertificate].[pPrintTemplateStudentGet]...';


GO
 
ALTER PROCEDURE [sCertificate].[pPrintTemplateStudentGet]
	
	 @rClassId int,
	 @rDivisionId int,
	 @rPrintTemplateId int,
	 @rCode nvarchar(20),
	 @rBatchId int,
	 @rPrintGroupNumber int,
	 @rFromDate date='',
	 @rToDate date=''
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	
	SELECT 
			PTS.Id,
			PTS.PrintTemplateId,
			PT.Title AS PrintTemplate,
			PTS.Template,
			PTS.AcademicId,
		    PTS.PrintGroupNumber,
		    DivM.Id AS DivisionId,
		    DivM.DisplayTitle AS DivisionName,
		    CM.Id AS ClassId,
		    CM.DisplayTitle AS ClassName,
		    CM.DisplayTitle+'-'+DivM.DisplayTitle AS ClassDivisionName,
		    DM.Id AS DepartmentId,
		    DM.DisplayTitle AS DepartmentName,
		    SM.FirstName+' '+SM.LastName AS StudentName,
		    SM.Code,
		    A.RollNo
	FROM 
			sCertificate.tPrintTemplateStudent PTS
			INNER JOIN sCertificate.tPrintTemplate PT ON PT.Id=PTS.PrintTemplateId
			INNER JOIN sStudent.tAcademic A ON A.Id=PTS.AcademicId
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDivisionMaster DivM ON DivM.Id=A.DivisionId
			INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id = CM.DepartmentId
	WHERE 
		(PTS.BatchId=@rBatchId)
		AND ((CM.Id = @rClassId) OR (@rClassId = 0))
		AND ((DivM.Id= @rDivisionId) OR (@rDivisionId = 0))
		AND ((PTS.PrintTemplateId = @rPrintTemplateId) OR (@rPrintTemplateId = 0))
		AND ((SM.Code = @rCode) OR (@rCode = ''))
		AND ((PTS.PrintGroupNumber = @rPrintGroupNumber) OR (@rPrintGroupNumber = 0))
		AND ((CONVERT(date, PTS.CreatedDateTime)>= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
        AND ((CONVERT(date, PTS.CreatedDateTime)<= @rToDate) OR (ISNULL(@rToDate,'')=''))
		
		
		Order by PTS.PrintGroupNumber DESC, DivM.OrderIndex,SM.Number
END
GO
PRINT N'Altering [sCommon].[pOrganizationSetupRemove]...';


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

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


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

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

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

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

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

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

DELETE FROM sTimetable.tAssignOrg WHERE OrgId = @rOrgId

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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


DELETE FROM sFee.tFeeMainGroupOptionalFee WHERE OrgId = @rOrgId
DELETE FROM sFee.tFeeStructureDetail WHERE CAST(LEFT(FeeStructureId, 4) AS int) = @rOrgId
DELETE FROM sFee.tFeeStructureMaster WHERE OrgId = @rOrgId
DELETE FROM sFrontOffice.tEmployeeGatePass WHERE OrgId = @rOrgId
DELETE FROM sHostel.tHostelStudentGatePass WHERE CAST(LEFT(StudentId, 4) AS bigint) = @rOrgId
DELETE FROM sHrm.tLeaveBalanceLog WHERE CAST(LEFT(EmployeeId, 4) AS bigint) = @rOrgId
DELETE FROM sTransport.tAttendanceRegister WHERE CAST(LEFT(SourceId, 4) AS bigint) = @rOrgId

DELETE FROM sAssessment.tCCESubjectActivityExamScore WHERE CAST(LEFT(AcademicId, 4) AS bigint) = @rOrgId
DELETE FROM sAssessment.tTempAll_Exam WHERE CAST(LEFT(AcademicId, 4) AS bigint) = @rOrgId
DELETE FROM sCanteen.tAttendanceForBreak WHERE CAST(LEFT(SourceId, 4) AS bigint) = @rOrgId
DELETE FROM sCanteen.tRegisterForBreak WHERE CAST(LEFT(SourceId, 4) AS bigint) = @rOrgId
DELETE FROM sCertificate.tTransfer WHERE OrgId = @rOrgId
DELETE FROM sCanteen.tRegisterForBreak WHERE CAST(LEFT(SourceId, 4) AS bigint) = @rOrgId

DELETE FROM sErp.tLeadFollowup WHERE CAST(LEFT(LeadId, 4) AS int) = @rOrgId
DELETE FROM sErp.tLeadMaster WHERE OrgId = @rOrgId


DELETE FROM sAdmission.tAdmissionHSCDetail WHERE CAST(LEFT(AdmissionFormId, 4) AS bigint) = @rOrgId
DELETE FROM sBiometric.tEmployeeCheckIn WHERE CAST(LEFT(EmployeeId, 4) AS bigint) = @rOrgId

DELETE FROM sBiometric.tEmployeeLateStatus WHERE CAST(LEFT(EmployeeId, 4) AS bigint) = @rOrgId

DELETE FROM sCommon.tSubmitDocumentMaster WHERE OrgId = @rOrgId
DELETE FROM sStudent.tStudentDocument WHERE CAST(LEFT(SubmitDocumentMasterId, 4) AS int) = @rOrgId
DELETE FROM sTimetable.tAnnualSubjectWorkLoad WHERE CAST(LEFT(BatchId, 4) AS int) = @rOrgId

DELETE FROM sFee.tReceiptDeleted WHERE CAST(LEFT(BatchId, 4) AS int) = @rOrgId
DELETE FROM sFee.tReceiptDetailDeleted WHERE CAST(LEFT(ReceiptId, 4) AS bigint) = @rOrgId

DELETE FROM sAttendance.tStudentLeaveRequest WHERE CAST(LEFT(AcademicId, 4) AS bigint) = @rOrgId
DELETE FROM sInfrastructure.tResourceMaster WHERE CAST(LEFT(Id, 4) AS int) = @rOrgId
DELETE FROM sInfrastructure.tResourceRequest WHERE CAST(LEFT(Id, 4) AS bigint) = @rOrgId

DELETE FROM sAlumni.tRegistration WHERE OrgId = @rOrgId
DELETE FROM sBiometric.tMonthlyStatusUpdate WHERE CAST(LEFT(EmployeeId, 4) AS bigint) = @rOrgId
DELETE FROM sErp.tDSR WHERE OrgId = @rOrgId
DELETE FROM sErp.tDSRWorkTypeMaster WHERE OrgId = @rOrgId
DELETE FROM sErp.tProjectMaster WHERE OrgId = @rOrgId
DELETE FROM sFee.tFeeFollowup WHERE CAST(LEFT(AcademicId, 4) AS bigint) = @rOrgId
 
DELETE FROM sActivity.tWeekOffSetting WHERE CAST(LEFT(SourceId, 4) AS bigint) = @rOrgId
DELETE FROM sAssessment.tAllBatchResultCoScholestic WHERE CAST(LEFT(StudentId, 4) AS bigint) = @rOrgId
DELETE FROM sHrm.tEmployeeDocument WHERE CAST(LEFT(EmployeeId, 4) AS bigint) = @rOrgId
DELETE FROM sStudent.tChangeIdLog WHERE CAST(LEFT(StudentId, 4) AS bigint) = @rOrgId
DELETE FROM sAlert.tAssociateRecipient WHERE CAST(LEFT(ForUserId, 4) AS bigint) = @rOrgId

DELETE FROM sAcademic.tPreLessonPlan WHERE CAST(LEFT(BatchId, 4) AS int) = @rOrgId
DELETE FROM sAssessment.tAllBatchResultGrade WHERE CAST(LEFT(StudentId, 4) AS bigint) = @rOrgId

DELETE FROM sVts.tvtsClassMaster WHERE CAST(LEFT(ClassId, 4) AS int) = @rOrgId
DELETE FROM sVts.tvtsOrganizationMaster WHERE OrgId = @rOrgId
DELETE FROM sVts.tvtsStudent WHERE CAST(LEFT(StudentId, 4) AS bigint) = @rOrgId
DELETE FROM sErp.tLeadChannelPartnerMaster WHERE  OrgId = @rOrgId


DELETE FROM sAlumni.tStudentMapping WHERE CAST(LEFT(StudentId, 4) AS bigint) = @rOrgId
DELETE FROM sErp.tUserFeedback WHERE CAST(LEFT(UserId, 4) AS bigint) = @rOrgId
DELETE FROM sFee.tFeeExpense WHERE CAST(LEFT(AcademicId, 4) AS bigint) = @rOrgId


DELETE FROM sAdmission.tAdmissionCriteriaForm WHERE CAST(LEFT(BatchId, 4) AS int) = @rOrgId
DELETE FROM sAdmission.tAdmissionFormField WHERE CAST(LEFT(AdmissionFormId, 4) AS bigint) = @rOrgId
DELETE FROM sAssessment.tGradeSetClassSubjectDetail WHERE CAST(LEFT(Id, 4) AS int) = @rOrgId
DELETE FROM sAssessment.tGradeSetClassSubjectMaster WHERE OrgId = @rOrgId
DELETE FROM sBiometric.BioDetailMapping WHERE OrgId = @rOrgId
DELETE FROM sBiometric.tLog WHERE OrgId = @rOrgId

DELETE FROM sCertificate.tOtherCertificate WHERE OrgId = @rOrgId
DELETE FROM sWorkflow.tApprovalAction WHERE CAST(LEFT(ActionUserId, 4) AS bigint) = @rOrgId
DELETE FROM sWorkflow.tApprovalRequest WHERE CAST(LEFT(BatchId, 4) AS int) = @rOrgId
DELETE FROM sWorkflow.tFunctionalityApprovingAuthority WHERE OrgId = @rOrgId
DELETE FROM sWorkflow.tFunctionalityApprovingDepartment WHERE OrgId = @rOrgId

DELETE FROM sBiometric.tProcess WHERE CAST(LEFT(SourceId, 4) AS bigint) = @rOrgId
DELETE FROM sAssessment.tConfiguration WHERE OrgId = @rOrgId

DELETE FROM sAcademic.tHomeworkCheck WHERE CAST(LEFT(AcademicId, 4) AS bigint) = @rOrgId

DELETE FROM sAdmission.tAdmissionCriteriaFee WHERE CAST(LEFT(BatchId, 4) AS int) = @rOrgId
DELETE FROM sAdmission.tAdmissionFormFee WHERE CAST(LEFT(AdmissionFormId, 4) AS bigint) = @rOrgId


DELETE FROM sFee.tFeeOpening WHERE CAST(LEFT(AcademicId, 4) AS bigint) = @rOrgId
DELETE FROM sTransport.tChangeRouteLog WHERE CAST(LEFT(SourceId, 4) AS bigint) = @rOrgId

DELETE FROM sAcademic.tClassworkConfig WHERE OrgId = @rOrgId
DELETE FROM sBiometric.tPunchData WHERE CAST(LEFT(StudentID, 4) AS bigint) = @rOrgId
DELETE FROM sErp.tCallLog WHERE CAST(LEFT(EmployeeId, 4) AS bigint) = @rOrgId
DELETE FROM sErp.tMarketingActivityPlan WHERE CAST(LEFT(EmployeeId, 4) AS bigint) = @rOrgId
--DELETE FROM tMarketingActivityStatus WHERE CAST(LEFT(EmployeeId, 4) AS bigint) = @rOrgId
DELETE FROM sErp.tTripLog WHERE CAST(LEFT(EmployeeId, 4) AS bigint) = @rOrgId


DELETE FROM sAudit.HistoryLog WHERE CAST(LEFT(SourceId, 4) AS bigint) = @rOrgId
DELETE FROM sAudit.tOperationLog WHERE CAST(LEFT(SourceId, 4) AS int) = @rOrgId

--DELETE FROM sErp.tCustomerTicket WHERE OrgId= @rOrgId
DELETE FROM sPayroll.tPayProcessEmployeeRemark WHERE CAST(LEFT(EmployeeId, 4) AS int) = @rOrgId


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

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


DELETE FROM sAlert.tAlertLogHistory WHERE OrgId= @rOrgId
DELETE FROM sAlert.tNotificationLogHistory WHERE CAST(LEFT(CreatedUserId, 4) AS bigint) = @rOrgId
DELETE FROM sHrm.tBatchEmployeeCommunications WHERE CAST(LEFT(EmployeeId, 4) AS bigint) = @rOrgId
DELETE FROM sHrm.tBatchEmployeeFamilyDetails WHERE CAST(LEFT(EmployeeId, 4) AS bigint) = @rOrgId
DELETE FROM sHrm.tBatchEmployeeJobDetail WHERE OrgId= @rOrgId
DELETE FROM sHrm.tBatchEmployeeMaster WHERE OrgId= @rOrgId
DELETE FROM sHrm.tBatchEmployeePersonalDetail WHERE OrgId= @rOrgId
DELETE FROM sHrm.tBatchEmployeeStatutoryAndOther WHERE CAST(LEFT(EmployeeId, 4) AS bigint) = @rOrgId
DELETE FROM sSecurity.tUserLogHistory WHERE OrgId= @rOrgId
DELETE FROM sStudent.tAcademicStudent WHERE CAST(LEFT(AcademicId, 4) AS bigint) = @rOrgId
DELETE FROM sStudent.tAcademicStudentAdditional WHERE CAST(LEFT(AcademicId, 4) AS bigint) = @rOrgId
DELETE FROM sStudent.tAcademicStudentCommunication WHERE CAST(LEFT(AcademicId, 4) AS bigint) = @rOrgId
DELETE FROM sStudent.tAcademicStudentFamily WHERE CAST(LEFT(AcademicId, 4) AS bigint) = @rOrgId
DELETE FROM sStudent.tAcademicStudentHealth WHERE CAST(LEFT(AcademicId, 4) AS bigint) = @rOrgId
DELETE FROM sStudent.tAcademicStudentOther WHERE CAST(LEFT(AcademicId, 4) AS bigint) = @rOrgId
DELETE FROM sStudent.tStudentCustomFieldData WHERE CAST(LEFT(StudentId, 4) AS bigint) = @rOrgId
DELETE FROM sStudent.tStudentMasterDelete WHERE OrgId= @rOrgId

DELETE FROM sAudit.ChangeLog WHERE CAST(LEFT(SourceId, 4) AS bigint) = @rOrgId
DELETE FROM sHrm.tCertificateIncrement WHERE OrgId= @rOrgId
DELETE FROM sAudit.ChangeLog WHERE CAST(LEFT(ScreenId, 4) AS bigint) = @rOrgId

DELETE FROM sAcademic.tClassworkView WHERE CAST(LEFT(AcademicId, 4) AS bigint) = @rOrgId
DELETE FROM sBiometric.tPunchCount WHERE CAST(LEFT(SourceId, 4) AS bigint) = @rOrgId

DELETE FROM sFrontOffice.tOTPLog WHERE CAST(LEFT(CreatedUserId, 4) AS bigint) = @rOrgId
DELETE FROM sHrm.tLeaveDeduction WHERE CAST(LEFT(EmployeeId, 4) AS bigint) = @rOrgId


DELETE FROM sAdmission.tAdmissionCriteriaDocument WHERE CAST(LEFT(BatchId, 4) AS int) = @rOrgId
DELETE FROM sAdmission.tAdmissionStudentDocument WHERE CAST(LEFT(AdmissionFormId, 4) AS bigint) = @rOrgId
DELETE FROM sTimetable.tTimeTableTime WHERE CAST(LEFT(DivisionId, 4) AS int) = @rOrgId
DELETE FROM sHrm.tEmployeeWorkingDays WHERE CAST(LEFT(BatchId, 4) AS int) = @rOrgId

DELETE FROM sErp.tContactBookMaster WHERE OrgId= @rOrgId
DELETE FROM sErp.tEmployeeERPDetail WHERE CAST(LEFT(EmployeeId, 4) AS bigint) = @rOrgId
DELETE FROM sFrontOffice.tLostFoundRegisterScope WHERE CAST(LEFT(SourceId, 4) AS int) = @rOrgId
DELETE FROM sHrm.tEmployeeChangeHistory WHERE CAST(LEFT(EmployeeId, 4) AS bigint) = @rOrgId
DELETE FROM sCommon.tReportTemplate WHERE OrgId= @rOrgId
DELETE FROM sTransport.tBusRouteAssignedTo WHERE CAST(LEFT(SourceId, 4) AS bigint) = @rOrgId
DELETE FROM sWorkflow.tStudentDataChange WHERE CAST(LEFT(SourceId, 4) AS bigint) = @rOrgId

DELETE FROM sAcademic.tOnlineLearning WHERE CAST(LEFT(BatchId, 4) AS int) = @rOrgId
DELETE FROM sAcademic.tOnlineLearningAssignment WHERE CAST(LEFT(OnlineLearningId, 4) AS bigint) = @rOrgId
DELETE FROM sAcademic.tOnlineLearningAssignmentSubmit WHERE CAST(LEFT(OnlineLearningId, 4) AS bigint) = @rOrgId
DELETE FROM sAcademic.tOnlineLearningAttendance WHERE CAST(LEFT(OnlineLearningId, 4) AS bigint) = @rOrgId
DELETE FROM sAcademic.tOnlineLearningAttendanceLog WHERE CAST(LEFT(OnlineLearningId, 4) AS bigint) = @rOrgId
DELETE FROM sAcademic.tOnlineLearningReference WHERE CAST(LEFT(OnlineLearningId, 4) AS bigint) = @rOrgId
DELETE FROM sAcademic.tOnlineLearningResource WHERE CAST(LEFT(OnlineLearningId, 4) AS bigint) = @rOrgId
DELETE FROM sAcademic.tOnlineLearningScope WHERE CAST(LEFT(OnlineLearningId, 4) AS bigint) = @rOrgId
DELETE FROM sAcademic.tTempOnlineLearningScope WHERE CAST(LEFT(SourceId, 4) AS bigint) = @rOrgId
DELETE FROM sCommunication.tChat WHERE CAST(LEFT(FromSourceId, 4) AS bigint) = @rOrgId
DELETE FROM sCommunication.tTempChatGroupScope WHERE CAST(LEFT(MemberSourceId, 4) AS bigint) = @rOrgId


DELETE FROM sAcademic.tOnlineMeetingSettings WHERE CAST(LEFT(OnlineLearningId, 4) AS bigint) = @rOrgId
DELETE FROM sStudent.tDigitalForm WHERE OrgId= @rOrgId
DELETE FROM sStudent.tDigitalFormScope WHERE CAST(LEFT(DigitalFormId, 4) AS int) = @rOrgId
DELETE FROM sStudent.tDigitalFormField WHERE CAST(LEFT(DigitalFormId, 4) AS int) = @rOrgId
DELETE FROM sStudent.tDigitalFormStudent WHERE CAST(LEFT(DigitalFormId, 4) AS int) = @rOrgId

DELETE FROM sAcademic.tOnlineLearningView WHERE CAST(LEFT(AcademicId, 4) AS bigint) = @rOrgId

DELETE FROM sOp.tPaymentTransactionHistory WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROMsFee.tOnlineFeeHistory WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sFee.tOnlineFeeDetailHistory WHERE CAST(LEFT(OnlineFeeId, 4) AS INT) = @rOrgId
DELETE FROM sCommunication.tStudentDocumentUpload WHERE CAST(LEFT(BatchId, 4) AS INT) = @rOrgId

DELETE FROM sFee.tFeeAllocationHistory WHERE CAST(LEFT(SourceId, 4) AS bigint) = @rOrgId

DELETE FROM sCommon.tUploadDocument WHERE CAST(LEFT(CreatedUserId, 4) AS bigint) = @rOrgId

DELETE FROM sFee.tFeeAllocationStudent WHERE CAST(LEFT(AcademicId, 4) AS bigint) = @rOrgId
DELETE FROM sFee.tFeeClassBatchStatus WHERE CAST(LEFT(BatchId, 4) AS int) = @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 [sCommunication].[pAssignedQueryListGet]...';


GO
 
 
ALTER PROCEDURE [sCommunication].[pAssignedQueryListGet]
	 
	 @rOrgGroupId smallint,
	 @rOrgGroupBatchId int,
	 @rSourceId bigint,
	 @rSourceTypeId smallint,
	 @rStatusId tinyint,
	 @rFromDate datetime = NULL,
	 @rToDate datetime = NULL
	
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
		
BEGIN 
	SELECT 
			 Q.Id AS QueryId,
			 Q.Title AS QueryTitle,
			 Q.Remark AS QueryRemark,
			 SM.Id AS QueryStatusId,
			 SM.Title AS QueryStatus,
			 QCM.Title AS QueryCategoryTitle,
			 QCA.QueryCategoryId,
			 (CONVERT(VARCHAR(25),Q.CreatedDateTime, 100)) AS QueryCreatedDateTime,
			 (CASE WHEN U.SourceTypeId = 95 THEN 	'Employee'
			 WHEN U.SourceTypeId = 2003 THEN	'Student' END ) AS SourceType,
			 (CASE WHEN U.SourceTypeId = 95 THEN (SELECT EmployeeName FROM sHrm.vEmployeeCommonDetail WHERE EmployeeId= U.SourceId )	 
			 WHEN U.SourceTypeId = 2003 THEN (SELECT Name FROM sStudent.vStudentAcademic WHERE StudentId= U.SourceId AND OrgGroupBatchId = @rOrgGroupBatchId)  END ) AS SourceName,
			  (CASE WHEN U.SourceTypeId = 95 THEN (SELECT DepartmentName FROM sHrm.vEmployeeCommonDetail WHERE EmployeeId= U.SourceId )	 
			 WHEN U.SourceTypeId = 2003 THEN (SELECT ClassName +' - ' + DivisionName FROM sStudent.vStudentAcademic WHERE StudentId= U.SourceId AND OrgGroupBatchId = @rOrgGroupBatchId)  END ) AS ClasDivOrDept,
			 (CASE WHEN U.SourceTypeId = 95 THEN (SELECT OM.Title FROM sHrm.vEmployeeCommonDetail vECD INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = vECD.OrgID WHERE vECD.EmployeeId= U.SourceId )	 
			 WHEN U.SourceTypeId = 2003 THEN (SELECT OrganizationName FROM sStudent.vStudentAcademic WHERE StudentId= U.SourceId AND OrgGroupBatchId = @rOrgGroupBatchId)  END ) AS OrgTitle
	FROM 
				sCommunication.tQueryCategoryAssignedTo QCA
			INNER JOIN sCommunication.tQuery Q 
				ON Q.QueryCategoryId = QCA.QueryCategoryId AND (Q.StatusId=@rStatusId)
			INNER JOIN sSecurity.tUser U ON U.Id = Q.CreatedUserId
			INNER JOIN sCommunication.tQueryCategoryMaster QCM 
				ON QCM.Id=QCA.QueryCategoryId AND (QCM.OrgGroupId = @rOrgGroupId)	
			INNER JOIN sCommon.tStatusMaster SM 
				ON SM.Id = Q.StatusId
		WHERE 
			(QCA.SourceTypeId = @rSourceTypeId) 
			AND (QCA.SourceId = @rSourceId) 
			AND ((Q.CreatedDateTime >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((Q.CreatedDateTime <= @rToDate) OR (ISNULL(@rToDate,'')=''))
END
GO
PRINT N'Altering [sCommunication].[pChatGroupMasterAdd]...';


GO
 
 
ALTER PROCEDURE [sCommunication].[pChatGroupMasterAdd]
	 
        @rId bigint = 0,
		@rChatTypeId int,
		@rTitle nvarchar(100) = '',
		@rIsDisplayOnApproval bit = 0,
		@rChatAdminEmployeeId bigint,
		@rCreatedUserId bigint,
		@rBatchId int,
		@rOrgGroupId int,
		@rOrgId int,
		@rTempChatGroupMasterId nvarchar(100)

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	 
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sCommunication.tChatGroupMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	Print @lNextNumber
	INSERT INTO sCommunication.tChatGroupMaster
		(
			Id
           ,OrgGroupId
           ,ChatTypeId
           ,Title
           ,IsDisplayOnApproval
           ,ChatAdminEmployeeId
           ,CreatedUserId
           ,CreatedDateTime
            
		)
	VALUES
		(
			@lNextNumber,
			@rOrgGroupId,
			@rChatTypeId,
			@rTitle,
			@rIsDisplayOnApproval, 
			@rChatAdminEmployeeId,
			@rCreatedUserId,
			sCommon.fGetDate()
		)
		    SELECT @lNextNumber AS Result

		IF EXISTS (SELECT 1 FROM sCommunication.tTempChatGroupScope WHERE TempChatGroupId = @rTempChatGroupMasterId)
	   BEGIN
			INSERT INTO sCommunication.tChatGroupScope
			SELECT @lNextNumber,MemberSourceTypeId,MemberSourceId,AssigneeToId
			FROM sCommunication.tTempChatGroupScope 
			WHERE TempChatGroupId = @rTempChatGroupMasterId
		
			DELETE FROM sCommunication.tTempChatGroupScope WHERE TempChatGroupId = @rTempChatGroupMasterId
		--COMMIT TRANSACTION 
		END 
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE sCommunication.tChatGroupMaster
	    SET
			 
        	Id = @rId
           ,OrgGroupId = @rOrgGroupId
           ,ChatTypeId = @rChatTypeId
           ,Title = @rTitle
           ,IsDisplayOnApproval = @rIsDisplayOnApproval
           ,ChatAdminEmployeeId = @rChatAdminEmployeeId
           ,CreatedUserId = @rCreatedUserId
           ,CreatedDateTime = sCommon.fGetDate()
        
	      WHERE Id = @rId
	      
	      SELECT 1 AS Result
	
		--COMMIT TRANSACTION
	 END  	

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


GO
 
 
ALTER PROCEDURE [sCommunication].[peContentAdd] 
			
           @rSourceTypeId smallint
           ,@rSourceId bigint           
           ,@rAssignId int,
		   @rPathName nvarchar(500),
		   @reContentTypeId int,
		   @rTitle nvarchar(200) = '',
		   @rRemark nvarchar(500) = '',
		   @rOrgGroupBatchId int = 0,
		   @rIsBatchIndependent bit = 0,
		   @rContentSourceId int = 0,
		   @rCreatedUserId bigint = 0
           	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
DECLARE @lCount int
BEGIN 

set @lCount =  ( select ISNULL(COUNT(1),0) from sCommunication.teContent where  SourceTypeId=@rSourceTypeId AND SourceId=@rSourceId AND AssignedToId=@rAssignId AND PathName = @rPathName)
   
	If (@lCount <> 0)
		BEGIN
			UPDATE sCommunication.teContent SET SourceTypeId=@rSourceTypeId , SourceId=@rSourceId , PathName=@rPathName,AssignedToId=@rAssignId,eContentTypeId = @reContentTypeId			   
			,ContentTypeSourcetId=  @rContentSourceId,Title=@rTitle,Remark=@rRemark,IsBatchIndependent=@rIsBatchIndependent
			where  SourceTypeId=@rSourceTypeId AND SourceId=@rSourceId AND AssignedToId=@rAssignId
			SELECT 1 AS Result
	  END 
	ELSE
			
			INSERT INTO sCommunication.teContent
			(
				SourceTypeId
			   ,SourceId
			   ,AssignedToId
			   ,eContentTypeId
			   ,ContentTypeSourcetId
			   ,PathName
			   ,Title
			   ,Remark
			   ,IsBatchIndependent
			   ,OrgGroupBatchId
			   ,CreatedUserId
			   ,CreatedDateTime
			)
			VALUES
			(	@rSourceTypeId
			   ,@rSourceId
			   ,@rAssignId
			   ,@reContentTypeId
			   ,@rContentSourceId
			   ,@rPathName
			   ,@rTitle
			   ,@rRemark
			   ,@rIsBatchIndependent
			   ,@rOrgGroupBatchId
			   ,@rCreatedUserId
			   ,sCommon.fGetDate()
			)		
			SELECT 1 AS Result
	END
	
	 
END
GO
PRINT N'Altering [sCommunication].[peContentGet]...';


GO
 
 
ALTER PROCEDURE [sCommunication].[peContentGet] 
	@rAssignId int = 0,
	@rOrgGroupId int = 0,
	@reContentType int = 0,
	@rTitle nvarchar(200) = ''
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 		
		
		SELECT * FROM (SELECT VP.SourceTypeId, VP.SourceId, VP.AssignedToId,VP.eContentTypeId,VP.Title AS Title,VP.Remark AS Remark,VP.IsBatchIndependent AS BatchIndependent,CM.Title AS eContentType,OM.DisplayTitle AS OrgName,'' AS ClassDepartment, 'Organization' AS SourceType,OM.DisplayTitle AS Source,
CASE WHEN VP.AssignedToId=2 THEN 'Student' WHEN VP.AssignedToId=3 THEN 'Employee' ELSE 'Both' END AS Assignee,VP.PathName,OGM.Id AS OrgGroupId,VP.CreatedDateTime
FROM sCommunication.teContent VP
INNER JOIN sSetup.tOrganizationMaster OM ON VP.SourceId=OM.Id INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OM.OrgGroupId INNER JOIN sCommunication.teContentTypeMaster CM ON VP.eContentTypeId = CM.Id WHERE VP.SourceTypeId=2021 

UNION ALL

SELECT VP.SourceTypeId, VP.SourceId, VP.AssignedToId,VP.eContentTypeId,VP.Title AS Title,VP.Remark AS Remark,VP.IsBatchIndependent AS BatchIndependent,CM.Title AS eContentType,OM.DisplayTitle AS OrgName,DM.Title AS ClassDepartment, 'Department' AS SourceType,DM.DisplayTitle AS Source,
CASE WHEN VP.AssignedToId=2 THEN 'Student' WHEN VP.AssignedToId=3 THEN 'Employee' ELSE 'Both' END AS Assignee,VP.PathName,OGM.Id AS OrgGroupId,VP.CreatedDateTime
FROM sCommunication.teContent VP
INNER JOIN sSetup.tDepartmentMaster DM ON VP.SourceId=DM.Id
INNER JOIN sSetup.tOrganizationMaster OM ON DM.OrgId=OM.Id 
INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OM.OrgGroupId
INNER JOIN sCommunication.teContentTypeMaster CM ON VP.eContentTypeId = CM.Id
WHERE VP.SourceTypeId=2017

UNION ALL

SELECT VP.SourceTypeId, VP.SourceId, VP.AssignedToId,VP.eContentTypeId,VP.Title AS Title,VP.Remark AS Remark,VP.IsBatchIndependent AS BatchIndependent,CTM.Title AS eContentType,OM.DisplayTitle AS OrgName,DM.Title AS ClassDepartment, 'Class' AS SourceType,CM.DisplayTitle AS Source,
CASE WHEN VP.AssignedToId=2 THEN 'Student' WHEN VP.AssignedToId=3 THEN 'Employee' ELSE 'Both' END AS Assignee,VP.PathName,OGM.Id AS OrgGroupId,VP.CreatedDateTime
FROM sCommunication.teContent VP
INNER JOIN sSetup.tClassMaster CM ON VP.SourceId=CM.Id
INNER JOIN sSetup.tDepartmentMaster DM ON CM.DepartmentId =DM.Id		
INNER JOIN sSetup.tOrganizationMaster OM ON DM.OrgId=OM.Id
INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OM.OrgGroupId
INNER JOIN sCommunication.teContentTypeMaster CTM ON VP.eContentTypeId = CTM.Id
WHERE VP.SourceTypeId=2016

UNION ALL

SELECT VP.SourceTypeId, VP.SourceId, VP.AssignedToId,VP.eContentTypeId,VP.Title AS Title,VP.Remark AS Remark,VP.IsBatchIndependent AS BatchIndependent,CTM.Title AS eContentType,OM.DisplayTitle AS OrgName,DMast.Title AS ClassDepartment, 'Division' AS SourceType,CM.DisplayTitle+'-'+DM.DisplayTitle AS Source,
CASE WHEN VP.AssignedToId=2 THEN 'Student' WHEN VP.AssignedToId=3 THEN 'Employee' ELSE 'Both' END AS Assignee,VP.PathName,OGM.Id AS OrgGroupId,VP.CreatedDateTime
FROM sCommunication.teContent VP
INNER JOIN sSetup.tDivisionMaster DM ON VP.SourceId=DM.Id
INNER JOIN sSetup.tClassMaster CM ON DM.ClassId=CM.Id	
INNER JOIN sSetup.tDepartmentMaster DMast ON CM.DepartmentId =DMast.Id
INNER JOIN sSetup.tOrganizationMaster OM ON DMast.OrgId=OM.Id
INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OM.OrgGroupId
INNER JOIN sCommunication.teContentTypeMaster CTM ON VP.eContentTypeId = CTM.Id	
WHERE VP.SourceTypeId=2005

UNION ALL

SELECT VP.SourceTypeId, VP.SourceId, VP.AssignedToId,VP.eContentTypeId,VP.Title AS Title,VP.Remark AS Remark,VP.IsBatchIndependent AS BatchIndependent,CM.Title AS eContentType,OM.DisplayTitle AS OrgName,SA.ClassName+' - '+SA.DivisionName AS ClassDepartment, 'Student' AS SourceType,
[sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Source,
CASE WHEN VP.AssignedToId=2 THEN 'Student' WHEN VP.AssignedToId=3 THEN 'Employee' ELSE 'Both' END AS Assignee,VP.PathName,OGM.Id AS OrgGroupId,VP.CreatedDateTime
FROM sCommunication.teContent VP
INNER JOIN sStudent.tStudentMaster SM ON VP.SourceId=SM.Id
INNER JOIN  sStudent.vStudentAcademic SA ON VP.SourceId=SA.StudentId AND SA.IsActiveBatch=1 AND SA.StatusId=1		
INNER JOIN sSetup.tOrganizationMaster OM ON SM.OrgId = OM.Id
INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OM.OrgGroupId
INNER JOIN sCommunication.teContentTypeMaster CM ON VP.eContentTypeId = CM.Id		
WHERE VP.SourceTypeId=2003

UNION ALL

SELECT VP.SourceTypeId, VP.SourceId, VP.AssignedToId,VP.eContentTypeId,VP.Title AS Title,VP.Remark AS Remark,VP.IsBatchIndependent AS BatchIndependent,CM.Title AS eContentType,OM.DisplayTitle AS OrgName,SA.ClassName+' - '+SA.DivisionName AS ClassDepartment,'Student' AS SourceType,SA.Name AS Source,
CASE WHEN VP.AssignedToId=2 THEN 'Student' WHEN VP.AssignedToId=3 THEN 'Employee' ELSE 'Both' END AS Assignee,VP.PathName,OGM.Id AS OrgGroupId,VP.CreatedDateTime
FROM sCommunication.teContent VP
INNER JOIN sStudent.vStudentAcademic SA	ON VP.SourceId=SA.AcademicId AND SA.IsActiveBatch=1 AND SA.StatusId=1
INNER JOIN sSetup.tOrganizationMaster OM ON SA.OrgId = OM.Id
INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OM.OrgGroupId
INNER JOIN sCommunication.teContentTypeMaster CM ON VP.eContentTypeId = CM.Id			
WHERE VP.SourceTypeId=2001 

UNION ALL

SELECT VP.SourceTypeId, VP.SourceId, VP.AssignedToId,VP.eContentTypeId,VP.Title AS Title,VP.Remark AS Remark,VP.IsBatchIndependent AS BatchIndependent,CM.Title AS eContentType,OM.DisplayTitle AS OrgName,vEC.DepartmentName AS ClassDepartment,'Employee' AS SourceType,vEC.FirstName +' '+ vEC.LastName AS Source,
CASE WHEN VP.AssignedToId=2 THEN 'Student' WHEN VP.AssignedToId=3 THEN 'Employee' ELSE 'Both' END AS Assignee,VP.PathName,OGM.Id AS OrgGroupId,VP.CreatedDateTime
FROM sCommunication.teContent VP
INNER JOIN sHrm.vEmployeeCommunication vEC ON VP.SourceId=vEC.EmployeeId AND vEC.StatusId=7
INNER JOIN sSetup.tOrganizationMaster OM ON vEC.OrgId = OM.Id
INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OM.OrgGroupId
INNER JOIN sCommunication.teContentTypeMaster CM ON VP.eContentTypeId = CM.Id					
WHERE VP.SourceTypeId=95
) tmp
where (tmp.AssignedToId=@rAssignId OR (@rAssignId=0))
AND tmp.OrgGroupId = @rOrgGroupId
AND (tmp.eContentTypeId = @reContentType OR (@reContentType=0))
AND (tmp.Title = @rTitle OR (@rTitle=''))
ORDER BY tmp.CreatedDateTime DESC
END
GO
PRINT N'Altering [sCommunication].[peContentMobileAppGet]...';


GO
 
 
 
 
--exec [sCommunication].[peContentMobileAppGet] 1101,0,2003,1101000000003
ALTER PROCEDURE [sCommunication].[peContentMobileAppGet]
	@rOrgId int=0,
	@rUserId bigint=0,
	@rSourceTypeId int=0,
	@rSourceId bigint =0,
	@reContentTypeId int = 0,
	@rTitle nvarchar(200) = '',
	 @rOrgGroupBatchId int = 0
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
DECLARE @lAcademicId bigint,@lStudentId bigint,@lClassId int,@lDivisionId int,@lOrgId int,@lDepartmentId int,@lEmployeeId bigint
BEGIN

	if (@rSourceTypeId = 95)
		BEGIN
		SELECT @lDepartmentId=EJD.OrganizationDepartmentId,@lOrgId = EM.OrgId,@lEmployeeId = EM.Id 
		FROM sHrm.tEmployeeMaster EM INNER JOIN sHrm.tEmployeeJobDetail EJD	 ON EJD.EmployeeId = EM.Id WHERE EM.Id=@rSourceId


		BEGIN

			SELECT * FROM (SELECT CEC.SourceTypeId, CEC.SourceId, 'Organization' AS SourceType,OM.DisplayTitle AS Source,CEC.PathName ,CEC.AssignedToId,
				CASE WHEN CEC.AssignedToId=2 THEN 'Student' WHEN CEC.AssignedToId=3 THEN 'Employee' ELSE 'Both' END AS Assignee,
				CCTM.Title AS eContentType, CCTM.Id AS eContentTypeId,CEC.Title as eContentTitle, CEC.Remark AS eContentRemark,tSM.Id AS SubjectId,tSM.Title As SubjectName,CEC.OrgGroupBatchId,CEC.CreatedDateTime
				FROM [sCommunication].[teContent] CEC
				INNER JOIN [sCommunication].[teContentTypeMaster] CCTM on CEC.eContentTypeId = CCTM.Id
				INNER JOIN sSetup.tOrganizationMaster OM ON CEC.SourceId=OM.Id 
				LEFT JOIN [sSetup].[tSubjectMaster] tSM ON tSM.Id = CEC.ContentTypeSourcetId
				WHERE CEC.SourceTypeId=2021 AND ((OM.Id=@rOrgId) OR @rOrgId=0) AND CEC.AssignedToId IN (1,3) AND ((CEC.eContentTypeId=@reContentTypeId) OR @reContentTypeId=0) AND ((CEC.Title LIKE @rTitle) OR @rTitle='') 
				UNION 
				SELECT CEC.SourceTypeId, CEC.SourceId, 'Department' AS SourceType,DM.DisplayTitle AS Source,CEC.PathName  ,CEC.AssignedToId,
				CASE WHEN CEC.AssignedToId=2 THEN 'Student' WHEN CEC.AssignedToId=3 THEN 'Employee' ELSE 'Both' END AS Assignee,
				CCTM.Title AS eContentType, CCTM.Id AS eContentTypeId,CEC.Title as eContentTitle, CEC.Remark AS eContentRemark,tSM.Id AS SubjectId,tSM.Title As SubjectName,CEC.OrgGroupBatchId,CEC.CreatedDateTime
				FROM [sCommunication].[teContent] CEC
				INNER JOIN [sCommunication].[teContentTypeMaster] CCTM on CEC.eContentTypeId = CCTM.Id
				INNER JOIN sSetup.tDepartmentMaster DM ON CEC.SourceId=DM.Id
				INNER JOIN sSetup.tOrganizationMaster OM ON DM.OrgId=OM.Id 
				LEFT JOIN [sSetup].[tSubjectMaster] tSM ON tSM.Id = CEC.ContentTypeSourcetId
				WHERE CEC.SourceTypeId=2017 AND ((OM.Id=@rOrgId) OR @rOrgId=0) AND CEC.AssignedToId IN (1,3) AND ((CEC.eContentTypeId=@reContentTypeId) OR @reContentTypeId=0) AND ((CEC.Title LIKE @rTitle) OR @rTitle='') 
				UNION 
				SELECT CEC.SourceTypeId, CEC.SourceId, 'Employee' AS SourceType,EM.FirstName +' '+ EM.LastName AS Source,CEC.PathName,CEC.AssignedToId,
				CASE WHEN CEC.AssignedToId=2 THEN 'Student' WHEN CEC.AssignedToId=3 THEN 'Employee' ELSE 'Both' END AS Assignee,
				CCTM.Title AS eContentType, CCTM.Id AS eContentTypeId,CEC.Title as eContentTitle, CEC.Remark AS eContentRemark,tSM.Id AS SubjectId,tSM.Title As SubjectName,CEC.OrgGroupBatchId,CEC.CreatedDateTime
				FROM [sCommunication].[teContent] CEC
				INNER JOIN [sCommunication].[teContentTypeMaster] CCTM on CEC.eContentTypeId = CCTM.Id
				INNER JOIN [sHrm].[tEmployeeMaster] EM ON CEC.SourceId=EM.Id AND EM.StatusId=7
				INNER JOIN sSetup.tOrganizationMaster OM ON EM.OrgId = OM.Id					
				LEFT JOIN [sSetup].[tSubjectMaster] tSM ON tSM.Id = CEC.ContentTypeSourcetId
				WHERE CEC.SourceTypeId=95 AND ((OM.Id=@rOrgId) OR @rOrgId=0) AND ((CEC.eContentTypeId=@reContentTypeId) OR @reContentTypeId=0) AND ((CEC.Title LIKE @rTitle) OR @rTitle='')  ) econtentList				

				WHERE ((econtentList.SourceTypeId = 2021 AND econtentList.SourceId =@lOrgId) OR
					   (econtentList.SourceTypeId = 2017 AND econtentList.SourceId =@lDepartmentId) OR
					   (econtentList.SourceTypeId = 95 AND econtentList.SourceId =@lEmployeeId))  
					   AND (econtentList.OrgGroupBatchId = @rOrgGroupBatchId OR  @rOrgGroupBatchId = 0)

		UNION

				SELECT * FROM (SELECT CEC.SourceTypeId, CEC.SourceId, 'Organization' AS SourceType,OM.DisplayTitle AS Source,CEC.PathName ,CEC.AssignedToId,
				CASE WHEN CEC.AssignedToId=2 THEN 'Student' WHEN CEC.AssignedToId=3 THEN 'Employee' ELSE 'Both' END AS Assignee,
				CCTM.Title AS eContentType, CCTM.Id AS eContentTypeId,CEC.Title as eContentTitle, CEC.Remark AS eContentRemark,tSM.Id AS SubjectId,tSM.Title As SubjectName,CEC.OrgGroupBatchId,CEC.CreatedDateTime
				FROM [sCommunication].[teContent] CEC
				INNER JOIN [sCommunication].[teContentTypeMaster] CCTM on CEC.eContentTypeId = CCTM.Id
				INNER JOIN sSetup.tOrganizationMaster OM ON CEC.SourceId=OM.Id 
				LEFT JOIN [sSetup].[tSubjectMaster] tSM ON tSM.Id = CEC.ContentTypeSourcetId
				WHERE CEC.SourceTypeId=2021 AND ((OM.Id=@rOrgId) OR @rOrgId=0) AND CEC.AssignedToId IN (1,3) AND ((CEC.eContentTypeId=@reContentTypeId) OR @reContentTypeId=0) AND ((CEC.Title LIKE @rTitle) OR @rTitle='') AND CEC.IsBatchIndependent = 0
				UNION 
				SELECT CEC.SourceTypeId, CEC.SourceId, 'Department' AS SourceType,DM.DisplayTitle AS Source,CEC.PathName  ,CEC.AssignedToId,
				CASE WHEN CEC.AssignedToId=2 THEN 'Student' WHEN CEC.AssignedToId=3 THEN 'Employee' ELSE 'Both' END AS Assignee,
				CCTM.Title AS eContentType, CCTM.Id AS eContentTypeId,CEC.Title as eContentTitle, CEC.Remark AS eContentRemark,tSM.Id AS SubjectId,tSM.Title As SubjectName,CEC.OrgGroupBatchId,CEC.CreatedDateTime
				FROM [sCommunication].[teContent] CEC
				INNER JOIN [sCommunication].[teContentTypeMaster] CCTM on CEC.eContentTypeId = CCTM.Id
				INNER JOIN sSetup.tDepartmentMaster DM ON CEC.SourceId=DM.Id
				INNER JOIN sSetup.tOrganizationMaster OM ON DM.OrgId=OM.Id 
				LEFT JOIN [sSetup].[tSubjectMaster] tSM ON tSM.Id = CEC.ContentTypeSourcetId
				WHERE CEC.SourceTypeId=2017 AND ((OM.Id=@rOrgId) OR @rOrgId=0) AND CEC.AssignedToId IN (1,3) AND ((CEC.eContentTypeId=@reContentTypeId) OR @reContentTypeId=0) AND ((CEC.Title LIKE @rTitle) OR @rTitle='') AND CEC.IsBatchIndependent = 0
				UNION 
				SELECT CEC.SourceTypeId, CEC.SourceId, 'Employee' AS SourceType,EM.FirstName +' '+ EM.LastName AS Source,CEC.PathName,CEC.AssignedToId,
				CASE WHEN CEC.AssignedToId=2 THEN 'Student' WHEN CEC.AssignedToId=3 THEN 'Employee' ELSE 'Both' END AS Assignee,
				CCTM.Title AS eContentType, CCTM.Id AS eContentTypeId,CEC.Title as eContentTitle, CEC.Remark AS eContentRemark,tSM.Id AS SubjectId,tSM.Title As SubjectName,CEC.OrgGroupBatchId,CEC.CreatedDateTime
				FROM [sCommunication].[teContent] CEC
				INNER JOIN [sCommunication].[teContentTypeMaster] CCTM on CEC.eContentTypeId = CCTM.Id
				INNER JOIN [sHrm].[tEmployeeMaster] EM ON CEC.SourceId=EM.Id AND EM.StatusId=7
				INNER JOIN sSetup.tOrganizationMaster OM ON EM.OrgId = OM.Id					
				LEFT JOIN [sSetup].[tSubjectMaster] tSM ON tSM.Id = CEC.ContentTypeSourcetId
				WHERE CEC.SourceTypeId=95 AND ((OM.Id=@rOrgId) OR @rOrgId=0) AND ((CEC.eContentTypeId=@reContentTypeId) OR @reContentTypeId=0) AND ((CEC.Title LIKE @rTitle) OR @rTitle='')  AND (CEC.IsBatchIndependent = 0)  ) econtentList				
				WHERE ((econtentList.SourceTypeId = 2021 AND econtentList.SourceId =@lOrgId) OR
					   (econtentList.SourceTypeId = 2017 AND econtentList.SourceId =@lDepartmentId) OR
					   (econtentList.SourceTypeId = 95 AND econtentList.SourceId =@lEmployeeId))
					  
			END

		END
	ELSE IF (@rSourceTypeId = 2003)
		BEGIN
			SELECT @lAcademicId = A.Id,@lStudentId = A.StudentId,@lClassId = A.ClassId, @lDivisionId = A.DivisionId, @lOrgId= A.OrgId, @lDepartmentId=CM.DepartmentId
				FROM sStudent.tAcademic A 
				INNER JOIN sSetup.tBatchMaster BM	ON A.BatchId = BM.Id AND BM.IsActive = 1 
				INNER JOIN sSetup.tClassMaster CM ON CM.Id = A.ClassId
				WHERE StudentId = @rSourceId AND A.OrgId=@rOrgId
				--AND BM.OrgGroupBatchId = @rOrgGroupBatchId
        -- Select @lClassId
			BEGIN 		
		
				SELECT * FROM (SELECT CEC.SourceTypeId, CEC.SourceId, 'Organization' AS SourceType,OM.DisplayTitle AS Source,CEC.PathName,CEC.AssignedToId,
				CASE WHEN CEC.AssignedToId=2 THEN 'Student' WHEN CEC.AssignedToId=3 THEN 'Employee' ELSE 'Both' END AS Assignee,
				CCTM.Title AS eContentType, CCTM.Id AS eContentTypeId,CEC.Title as eContentTitle, CEC.Remark AS eContentRemark,tSM.Id AS SubjectId,tSM.Title As SubjectName, CEC.OrgGroupBatchId,CEC.CreatedDateTime
				FROM [sCommunication].[teContent] CEC
				INNER JOIN [sCommunication].[teContentTypeMaster] CCTM on CEC.eContentTypeId = CCTM.Id
				INNER JOIN sSetup.tOrganizationMaster OM ON CEC.SourceId=OM.Id 
				LEFT JOIN [sSetup].[tSubjectMaster] tSM ON tSM.Id = CEC.ContentTypeSourcetId
				WHERE CEC.SourceTypeId=2021 AND ((OM.Id=@rOrgId) OR @rOrgId=0) AND CEC.AssignedToId IN (1,2) AND ((CEC.eContentTypeId=@reContentTypeId) OR @reContentTypeId=0) AND ((CEC.Title LIKE @rTitle) OR @rTitle='') 
				UNION 
				SELECT CEC.SourceTypeId, CEC.SourceId, 'Department' AS SourceType,DM.DisplayTitle AS Source,CEC.PathName ,CEC.AssignedToId,
				CASE WHEN CEC.AssignedToId=2 THEN 'Student' WHEN CEC.AssignedToId=3 THEN 'Employee' ELSE 'Both' END AS Assignee,
				CCTM.Title AS eContentType, CCTM.Id AS eContentTypeId,CEC.Title as eContentTitle, CEC.Remark AS eContentRemark,tSM.Id AS SubjectId,tSM.Title As SubjectName, CEC.OrgGroupBatchId,CEC.CreatedDateTime
				FROM [sCommunication].[teContent] CEC
				INNER JOIN [sCommunication].[teContentTypeMaster] CCTM on CEC.eContentTypeId = CCTM.Id
				INNER JOIN sSetup.tDepartmentMaster DM ON CEC.SourceId=DM.Id
				INNER JOIN sSetup.tOrganizationMaster OM ON DM.OrgId=OM.Id 
				LEFT JOIN [sSetup].[tSubjectMaster] tSM ON tSM.Id = CEC.ContentTypeSourcetId
				WHERE CEC.SourceTypeId=2017 AND ((OM.Id=@rOrgId) OR @rOrgId=0) AND CEC.AssignedToId IN (1,2) AND ((CEC.eContentTypeId=@reContentTypeId) OR @reContentTypeId=0) AND ((CEC.Title LIKE @rTitle) OR @rTitle='') 
				UNION
				SELECT CEC.SourceTypeId, CEC.SourceId, 'Class' AS SourceType,CM.DisplayTitle AS Source,CEC.PathName,CEC.AssignedToId, 
				CASE WHEN CEC.AssignedToId=2 THEN 'Student' WHEN CEC.AssignedToId=3 THEN 'Employee' ELSE 'Both' END AS Assignee,
				CCTM.Title AS eContentType, CCTM.Id AS eContentTypeId,CEC.Title as eContentTitle, CEC.Remark AS eContentRemark,tSM.Id AS SubjectId,tSM.Title As SubjectName, CEC.OrgGroupBatchId,CEC.CreatedDateTime
				FROM [sCommunication].[teContent] CEC
				INNER JOIN [sCommunication].[teContentTypeMaster] CCTM on CEC.eContentTypeId = CCTM.Id
				INNER JOIN sSetup.tClassMaster CM ON CEC.SourceId=CM.Id
				INNER JOIN sSetup.tDepartmentMaster DM ON CM.DepartmentId =DM.Id		
				INNER JOIN sSetup.tOrganizationMaster OM ON DM.OrgId=OM.Id
				LEFT JOIN [sSetup].[tSubjectMaster] tSM ON tSM.Id = CEC.ContentTypeSourcetId
				WHERE CEC.SourceTypeId=2016 AND ((OM.Id=@rOrgId) OR @rOrgId=0) AND ((CEC.eContentTypeId=@reContentTypeId) OR @reContentTypeId=0) AND ((CEC.Title LIKE @rTitle) OR @rTitle='') 
				UNION
				SELECT CEC.SourceTypeId, CEC.SourceId, 'Division' AS SourceType,CM.DisplayTitle+'-'+DM.DisplayTitle AS Source,CEC.PathName,CEC.AssignedToId,
				CASE WHEN CEC.AssignedToId=2 THEN 'Student' WHEN CEC.AssignedToId=3 THEN 'Employee' ELSE 'Both' END AS Assignee,
				CCTM.Title AS eContentType, CCTM.Id AS eContentTypeId,CEC.Title as eContentTitle, CEC.Remark AS eContentRemark,tSM.Id AS SubjectId,tSM.Title As SubjectName, CEC.OrgGroupBatchId,CEC.CreatedDateTime
				FROM [sCommunication].[teContent] CEC
				INNER JOIN [sCommunication].[teContentTypeMaster] CCTM on CEC.eContentTypeId = CCTM.Id
				INNER JOIN sSetup.tDivisionMaster DM ON CEC.SourceId=DM.Id
				INNER JOIN sSetup.tClassMaster CM ON DM.ClassId=CM.Id	
				INNER JOIN sSetup.tDepartmentMaster DMast ON CM.DepartmentId =DMast.Id
				INNER JOIN sSetup.tOrganizationMaster OM ON DMast.OrgId=OM.Id		
				LEFT JOIN [sSetup].[tSubjectMaster] tSM ON tSM.Id = CEC.ContentTypeSourcetId
				WHERE CEC.SourceTypeId=2005 AND ((OM.Id=@rOrgId) OR @rOrgId=0) AND ((CEC.eContentTypeId=@reContentTypeId) OR @reContentTypeId=0) AND ((CEC.Title LIKE @rTitle) OR @rTitle='') 
				UNION 
				SELECT CEC.SourceTypeId, CEC.SourceId, 'Student' AS SourceType,[sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Source,CEC.PathName,
				CEC.AssignedToId,CASE WHEN CEC.AssignedToId=2 THEN 'Student' WHEN CEC.AssignedToId=3 THEN 'Employee' ELSE 'Both' END AS Assignee,
				CCTM.Title AS eContentType, CCTM.Id AS eContentTypeId,CEC.Title as eContentTitle, CEC.Remark AS eContentRemark,tSM.Id AS SubjectId,tSM.Title As SubjectName, CEC.OrgGroupBatchId,CEC.CreatedDateTime
				FROM [sCommunication].[teContent] CEC
				INNER JOIN [sCommunication].[teContentTypeMaster] CCTM on CEC.eContentTypeId = CCTM.Id
				INNER JOIN sStudent.tStudentMaster SM ON CEC.SourceId=SM.Id
				INNER JOIN  sStudent.vStudentAcademic SA ON CEC.SourceId=SA.StudentId AND SA.IsActiveBatch=1 AND SA.StatusId=1		
				INNER JOIN sSetup.tOrganizationMaster OM ON SM.OrgId = OM.Id		
				LEFT JOIN [sSetup].[tSubjectMaster] tSM ON tSM.Id = CEC.ContentTypeSourcetId
				WHERE CEC.SourceTypeId=2003 AND ((OM.Id=@rOrgId) OR @rOrgId=0) AND ((CEC.eContentTypeId=@reContentTypeId) OR @reContentTypeId=0) AND ((CEC.Title LIKE @rTitle) OR @rTitle='') 
				UNION
				SELECT CEC.SourceTypeId, CEC.SourceId, 'Student' AS SourceType,SA.Name AS Source,CEC.PathName,CEC.AssignedToId,
				CASE WHEN CEC.AssignedToId=2 THEN 'Student' WHEN CEC.AssignedToId=3 THEN 'Employee' ELSE 'Both' END AS Assignee,
				CCTM.Title AS eContentType, CCTM.Id AS eContentTypeId,CEC.Title as eContentTitle, CEC.Remark AS eContentRemark,tSM.Id AS SubjectId,tSM.Title As SubjectName, CEC.OrgGroupBatchId,CEC.CreatedDateTime
				FROM [sCommunication].[teContent] CEC
				INNER JOIN [sCommunication].[teContentTypeMaster] CCTM on CEC.eContentTypeId = CCTM.Id
				INNER JOIN sStudent.vStudentAcademic SA	ON CEC.SourceId=SA.StudentId  AND SA.IsActiveBatch=1 AND SA.StatusId=1
				INNER JOIN sSetup.tOrganizationMaster OM ON SA.OrgId = OM.Id			
				LEFT JOIN [sSetup].[tSubjectMaster] tSM ON tSM.Id = CEC.ContentTypeSourcetId
				WHERE CEC.SourceTypeId=2001 AND ((OM.Id=@rOrgId) OR @rOrgId=0) AND ((CEC.eContentTypeId=@reContentTypeId) OR @reContentTypeId=0) AND ((CEC.Title LIKE @rTitle) OR @rTitle='') 
				 ) econtentList

				

				WHERE ((econtentList.SourceTypeId = 2021 AND econtentList.SourceId =@lOrgId) OR
					   (econtentList.SourceTypeId = 2017 AND econtentList.SourceId =@lDepartmentId) OR
                       (econtentList.SourceTypeId = 2016 AND econtentList.SourceId =@lClassId) OR
                       (econtentList.SourceTypeId = 2005 AND econtentList.SourceId =@lDivisionId) OR
                       (econtentList.SourceTypeId = 2003 AND econtentList.SourceId =@lStudentId) OR
                       (econtentList.SourceTypeId = 2001 AND econtentList.SourceId =@lAcademicId) AND (econtentList.OrgGroupBatchId = @rOrgGroupBatchId OR  @rOrgGroupBatchId = 0))
					   


		UNION


			SELECT * FROM (SELECT CEC.SourceTypeId, CEC.SourceId, 'Organization' AS SourceType,OM.DisplayTitle AS Source,CEC.PathName,CEC.AssignedToId,
				CASE WHEN CEC.AssignedToId=2 THEN 'Student' WHEN CEC.AssignedToId=3 THEN 'Employee' ELSE 'Both' END AS Assignee,
				CCTM.Title AS eContentType, CCTM.Id AS eContentTypeId,CEC.Title as eContentTitle, CEC.Remark AS eContentRemark,tSM.Id AS SubjectId,tSM.Title As SubjectName, CEC.OrgGroupBatchId,CEC.CreatedDateTime
				FROM [sCommunication].[teContent] CEC
				INNER JOIN [sCommunication].[teContentTypeMaster] CCTM on CEC.eContentTypeId = CCTM.Id
				INNER JOIN sSetup.tOrganizationMaster OM ON CEC.SourceId=OM.Id 
				LEFT JOIN [sSetup].[tSubjectMaster] tSM ON tSM.Id = CEC.ContentTypeSourcetId
				WHERE CEC.SourceTypeId=2021 AND ((OM.Id=@rOrgId) OR @rOrgId=0) AND CEC.AssignedToId IN (1,2) AND ((CEC.eContentTypeId=@reContentTypeId) OR @reContentTypeId=0) AND ((CEC.Title LIKE @rTitle) OR @rTitle='')  AND CEC.IsBatchIndependent = 0
				UNION 
				SELECT CEC.SourceTypeId, CEC.SourceId, 'Department' AS SourceType,DM.DisplayTitle AS Source,CEC.PathName ,CEC.AssignedToId,
				CASE WHEN CEC.AssignedToId=2 THEN 'Student' WHEN CEC.AssignedToId=3 THEN 'Employee' ELSE 'Both' END AS Assignee,
				CCTM.Title AS eContentType, CCTM.Id AS eContentTypeId,CEC.Title as eContentTitle, CEC.Remark AS eContentRemark,tSM.Id AS SubjectId,tSM.Title As SubjectName, CEC.OrgGroupBatchId,CEC.CreatedDateTime
				FROM [sCommunication].[teContent] CEC
				INNER JOIN [sCommunication].[teContentTypeMaster] CCTM on CEC.eContentTypeId = CCTM.Id
				INNER JOIN sSetup.tDepartmentMaster DM ON CEC.SourceId=DM.Id
				INNER JOIN sSetup.tOrganizationMaster OM ON DM.OrgId=OM.Id 
				LEFT JOIN [sSetup].[tSubjectMaster] tSM ON tSM.Id = CEC.ContentTypeSourcetId
				WHERE CEC.SourceTypeId=2017 AND ((OM.Id=@rOrgId) OR @rOrgId=0) AND CEC.AssignedToId IN (1,2) AND ((CEC.eContentTypeId=@reContentTypeId) OR @reContentTypeId=0) AND ((CEC.Title LIKE @rTitle) OR @rTitle='')  AND CEC.IsBatchIndependent = 0
				UNION
				SELECT CEC.SourceTypeId, CEC.SourceId, 'Class' AS SourceType,CM.DisplayTitle AS Source,CEC.PathName,CEC.AssignedToId, 
				CASE WHEN CEC.AssignedToId=2 THEN 'Student' WHEN CEC.AssignedToId=3 THEN 'Employee' ELSE 'Both' END AS Assignee,
				CCTM.Title AS eContentType, CCTM.Id AS eContentTypeId,CEC.Title as eContentTitle, CEC.Remark AS eContentRemark,tSM.Id AS SubjectId,tSM.Title As SubjectName, CEC.OrgGroupBatchId,CEC.CreatedDateTime
				FROM [sCommunication].[teContent] CEC
				INNER JOIN [sCommunication].[teContentTypeMaster] CCTM on CEC.eContentTypeId = CCTM.Id
				INNER JOIN sSetup.tClassMaster CM ON CEC.SourceId=CM.Id
				INNER JOIN sSetup.tDepartmentMaster DM ON CM.DepartmentId =DM.Id		
				INNER JOIN sSetup.tOrganizationMaster OM ON DM.OrgId=OM.Id
				LEFT JOIN [sSetup].[tSubjectMaster] tSM ON tSM.Id = CEC.ContentTypeSourcetId
				WHERE CEC.SourceTypeId=2016 AND ((OM.Id=@rOrgId) OR @rOrgId=0) AND ((CEC.eContentTypeId=@reContentTypeId) OR @reContentTypeId=0) AND ((CEC.Title LIKE @rTitle) OR @rTitle='')  AND CEC.IsBatchIndependent = 0
				UNION
				SELECT CEC.SourceTypeId, CEC.SourceId, 'Division' AS SourceType,CM.DisplayTitle+'-'+DM.DisplayTitle AS Source,CEC.PathName,CEC.AssignedToId,
				CASE WHEN CEC.AssignedToId=2 THEN 'Student' WHEN CEC.AssignedToId=3 THEN 'Employee' ELSE 'Both' END AS Assignee,
				CCTM.Title AS eContentType, CCTM.Id AS eContentTypeId,CEC.Title as eContentTitle, CEC.Remark AS eContentRemark,tSM.Id AS SubjectId,tSM.Title As SubjectName, CEC.OrgGroupBatchId,CEC.CreatedDateTime
				FROM [sCommunication].[teContent] CEC
				INNER JOIN [sCommunication].[teContentTypeMaster] CCTM on CEC.eContentTypeId = CCTM.Id
				INNER JOIN sSetup.tDivisionMaster DM ON CEC.SourceId=DM.Id
				INNER JOIN sSetup.tClassMaster CM ON DM.ClassId=CM.Id	
				INNER JOIN sSetup.tDepartmentMaster DMast ON CM.DepartmentId =DMast.Id
				INNER JOIN sSetup.tOrganizationMaster OM ON DMast.OrgId=OM.Id		
				LEFT JOIN [sSetup].[tSubjectMaster] tSM ON tSM.Id = CEC.ContentTypeSourcetId
				WHERE CEC.SourceTypeId=2005 AND ((OM.Id=@rOrgId) OR @rOrgId=0) AND ((CEC.eContentTypeId=@reContentTypeId) OR @reContentTypeId=0) AND ((CEC.Title LIKE @rTitle) OR @rTitle='')  AND CEC.IsBatchIndependent = 0
				UNION 
				SELECT CEC.SourceTypeId, CEC.SourceId, 'Student' AS SourceType,[sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Source,CEC.PathName,
				CEC.AssignedToId,CASE WHEN CEC.AssignedToId=2 THEN 'Student' WHEN CEC.AssignedToId=3 THEN 'Employee' ELSE 'Both' END AS Assignee,
				CCTM.Title AS eContentType, CCTM.Id AS eContentTypeId,CEC.Title as eContentTitle, CEC.Remark AS eContentRemark,tSM.Id AS SubjectId,tSM.Title As SubjectName, CEC.OrgGroupBatchId,CEC.CreatedDateTime
				FROM [sCommunication].[teContent] CEC
				INNER JOIN [sCommunication].[teContentTypeMaster] CCTM on CEC.eContentTypeId = CCTM.Id
				INNER JOIN sStudent.tStudentMaster SM ON CEC.SourceId=SM.Id
				INNER JOIN  sStudent.vStudentAcademic SA ON CEC.SourceId=SA.StudentId AND SA.IsActiveBatch=1 AND SA.StatusId=1		
				INNER JOIN sSetup.tOrganizationMaster OM ON SM.OrgId = OM.Id		
				LEFT JOIN [sSetup].[tSubjectMaster] tSM ON tSM.Id = CEC.ContentTypeSourcetId
				WHERE CEC.SourceTypeId=2003 AND ((OM.Id=@rOrgId) OR @rOrgId=0) AND ((CEC.eContentTypeId=@reContentTypeId) OR @reContentTypeId=0) AND ((CEC.Title LIKE @rTitle) OR @rTitle='')  AND CEC.IsBatchIndependent = 0
				UNION
				SELECT CEC.SourceTypeId, CEC.SourceId, 'Student' AS SourceType,SA.Name AS Source,CEC.PathName,CEC.AssignedToId,
				CASE WHEN CEC.AssignedToId=2 THEN 'Student' WHEN CEC.AssignedToId=3 THEN 'Employee' ELSE 'Both' END AS Assignee,
				CCTM.Title AS eContentType, CCTM.Id AS eContentTypeId,CEC.Title as eContentTitle, CEC.Remark AS eContentRemark,tSM.Id AS SubjectId,tSM.Title As SubjectName, CEC.OrgGroupBatchId,CEC.CreatedDateTime
				FROM [sCommunication].[teContent] CEC
				INNER JOIN [sCommunication].[teContentTypeMaster] CCTM on CEC.eContentTypeId = CCTM.Id
				INNER JOIN sStudent.vStudentAcademic SA	ON CEC.SourceId=SA.StudentId  AND SA.IsActiveBatch=1 AND SA.StatusId=1
				INNER JOIN sSetup.tOrganizationMaster OM ON SA.OrgId = OM.Id			
				LEFT JOIN [sSetup].[tSubjectMaster] tSM ON tSM.Id = CEC.ContentTypeSourcetId
				WHERE CEC.SourceTypeId=2001 AND ((OM.Id=@rOrgId) OR @rOrgId=0) AND ((CEC.eContentTypeId=@reContentTypeId) OR @reContentTypeId=0) AND ((CEC.Title LIKE @rTitle) OR @rTitle='')  AND CEC.IsBatchIndependent = 0
				 ) econtentList

				

				WHERE ((econtentList.SourceTypeId = 2021 AND econtentList.SourceId =@lOrgId) OR
					   (econtentList.SourceTypeId = 2017 AND econtentList.SourceId =@lDepartmentId) OR
                       (econtentList.SourceTypeId = 2016 AND econtentList.SourceId =@lClassId) OR
                       (econtentList.SourceTypeId = 2005 AND econtentList.SourceId =@lDivisionId) OR
                       (econtentList.SourceTypeId = 2003 AND econtentList.SourceId =@lStudentId) OR
                       (econtentList.SourceTypeId = 2001 AND econtentList.SourceId =@lAcademicId) )

			END

		END
		ELSE IF (@rSourceTypeId = 0)
		BEGIN
				SELECT * FROM  (SELECT CEC.SourceTypeId, CEC.SourceId, 'Organization' AS SourceType,OM.DisplayTitle AS Source,CEC.PathName,CEC.AssignedToId,
				CASE WHEN CEC.AssignedToId=2 THEN 'Student' WHEN CEC.AssignedToId=3 THEN 'Employee' ELSE 'Both' END AS Assignee,
				CCTM.Title AS eContentType, CCTM.Id AS eContentTypeId,CEC.Title as eContentTitle, CEC.Remark AS eContentRemark,tSM.Id AS SubjectId,tSM.Title As SubjectName,CEC.OrgGroupBatchId,CEC.CreatedDateTime
				FROM [sCommunication].[teContent] CEC
				INNER JOIN [sCommunication].[teContentTypeMaster] CCTM on CEC.eContentTypeId = CCTM.Id
				INNER JOIN sSetup.tOrganizationMaster OM ON CEC.SourceId=OM.Id 
				LEFT JOIN [sSetup].[tSubjectMaster] tSM ON tSM.Id = CEC.ContentTypeSourcetId
				WHERE CEC.SourceTypeId=2021 AND ((OM.Id=@rOrgId) OR @rOrgId=0) AND CEC.AssignedToId IN (1,2,3) AND ((CEC.eContentTypeId=@reContentTypeId) OR @reContentTypeId=0) AND ((CEC.Title LIKE @rTitle) OR @rTitle='') 

				UNION
				 
				SELECT CEC.SourceTypeId, CEC.SourceId, 'Department' AS SourceType,DM.DisplayTitle AS Source,CEC.PathName ,CEC.AssignedToId,
				CASE WHEN CEC.AssignedToId=2 THEN 'Student' WHEN CEC.AssignedToId=3 THEN 'Employee' ELSE 'Both' END AS Assignee,
				CCTM.Title AS eContentType, CCTM.Id AS eContentTypeId,CEC.Title as eContentTitle, CEC.Remark AS eContentRemark,tSM.Id AS SubjectId,tSM.Title As SubjectName,CEC.OrgGroupBatchId,CEC.CreatedDateTime
				FROM [sCommunication].[teContent] CEC
				INNER JOIN [sCommunication].[teContentTypeMaster] CCTM on CEC.eContentTypeId = CCTM.Id
				INNER JOIN sSetup.tDepartmentMaster DM ON CEC.SourceId=DM.Id
				INNER JOIN sSetup.tOrganizationMaster OM ON DM.OrgId=OM.Id 
				LEFT JOIN [sSetup].[tSubjectMaster] tSM ON tSM.Id = CEC.ContentTypeSourcetId
				WHERE CEC.SourceTypeId=2017 AND ((OM.Id=@rOrgId) OR @rOrgId=0) AND CEC.AssignedToId IN (1,2,3) AND ((CEC.eContentTypeId=@reContentTypeId) OR @reContentTypeId=0) AND ((CEC.Title LIKE @rTitle) OR @rTitle='') 

				UNION

				SELECT CEC.SourceTypeId, CEC.SourceId, 'Class' AS SourceType,CM.DisplayTitle AS Source,CEC.PathName,CEC.AssignedToId, 
				CASE WHEN CEC.AssignedToId=2 THEN 'Student' WHEN CEC.AssignedToId=3 THEN 'Employee' ELSE 'Both' END AS Assignee,
				CCTM.Title AS eContentType, CCTM.Id AS eContentTypeId,CEC.Title as eContentTitle, CEC.Remark AS eContentRemark,tSM.Id AS SubjectId,tSM.Title As SubjectName,CEC.OrgGroupBatchId,CEC.CreatedDateTime
				FROM [sCommunication].[teContent] CEC
				INNER JOIN [sCommunication].[teContentTypeMaster] CCTM on CEC.eContentTypeId = CCTM.Id
				INNER JOIN sSetup.tClassMaster CM ON CEC.SourceId=CM.Id
				INNER JOIN sSetup.tDepartmentMaster DM ON CM.DepartmentId =DM.Id		
				INNER JOIN sSetup.tOrganizationMaster OM ON DM.OrgId=OM.Id
				LEFT JOIN [sSetup].[tSubjectMaster] tSM ON tSM.Id = CEC.ContentTypeSourcetId
				WHERE CEC.SourceTypeId=2016 AND ((OM.Id=@rOrgId) OR @rOrgId=0) AND ((CEC.eContentTypeId=@reContentTypeId) OR @reContentTypeId=0) AND ((CEC.Title LIKE @rTitle) OR @rTitle='') 

				UNION

				SELECT CEC.SourceTypeId, CEC.SourceId, 'Division' AS SourceType,CM.DisplayTitle+'-'+DM.DisplayTitle AS Source,CEC.PathName,CEC.AssignedToId,
				CASE WHEN CEC.AssignedToId=2 THEN 'Student' WHEN CEC.AssignedToId=3 THEN 'Employee' ELSE 'Both' END AS Assignee,
				CCTM.Title AS eContentType, CCTM.Id AS eContentTypeId,CEC.Title as eContentTitle, CEC.Remark AS eContentRemark,tSM.Id AS SubjectId,tSM.Title As SubjectName,CEC.OrgGroupBatchId,CEC.CreatedDateTime
				FROM [sCommunication].[teContent] CEC
				INNER JOIN [sCommunication].[teContentTypeMaster] CCTM on CEC.eContentTypeId = CCTM.Id
				INNER JOIN sSetup.tDivisionMaster DM ON CEC.SourceId=DM.Id
				INNER JOIN sSetup.tClassMaster CM ON DM.ClassId=CM.Id	
				INNER JOIN sSetup.tDepartmentMaster DMast ON CM.DepartmentId =DMast.Id
				INNER JOIN sSetup.tOrganizationMaster OM ON DMast.OrgId=OM.Id		
				LEFT JOIN [sSetup].[tSubjectMaster] tSM ON tSM.Id = CEC.ContentTypeSourcetId
				WHERE CEC.SourceTypeId=2005 AND ((OM.Id=@rOrgId) OR @rOrgId=0) AND ((CEC.eContentTypeId=@reContentTypeId) OR @reContentTypeId=0) AND ((CEC.Title LIKE @rTitle) OR @rTitle='') 

				UNION
				 
				SELECT CEC.SourceTypeId, CEC.SourceId, 'Student' AS SourceType,[sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Source,CEC.PathName,
				CEC.AssignedToId,CASE WHEN CEC.AssignedToId=2 THEN 'Student' WHEN CEC.AssignedToId=3 THEN 'Employee' ELSE 'Both' END AS Assignee,
				CCTM.Title AS eContentType, CCTM.Id AS eContentTypeId,CEC.Title as eContentTitle, CEC.Remark AS eContentRemark,tSM.Id AS SubjectId,tSM.Title As SubjectName,CEC.OrgGroupBatchId,CEC.CreatedDateTime
				FROM [sCommunication].[teContent] CEC
				INNER JOIN [sCommunication].[teContentTypeMaster] CCTM on CEC.eContentTypeId = CCTM.Id
				INNER JOIN sStudent.tStudentMaster SM ON CEC.SourceId=SM.Id
				INNER JOIN  sStudent.vStudentAcademic SA ON CEC.SourceId=SA.StudentId AND SA.IsActiveBatch=1 AND SA.StatusId=1		
				INNER JOIN sSetup.tOrganizationMaster OM ON SM.OrgId = OM.Id		
				LEFT JOIN [sSetup].[tSubjectMaster] tSM ON tSM.Id = CEC.ContentTypeSourcetId
				WHERE CEC.SourceTypeId=2003 AND ((OM.Id=@rOrgId) OR @rOrgId=0) AND ((CEC.eContentTypeId=@reContentTypeId) OR @reContentTypeId=0) AND ((CEC.Title LIKE @rTitle) OR @rTitle='') 

				UNION

				SELECT CEC.SourceTypeId, CEC.SourceId, 'Student' AS SourceType,SA.Name AS Source,CEC.PathName,CEC.AssignedToId,
				CASE WHEN CEC.AssignedToId=2 THEN 'Student' WHEN CEC.AssignedToId=3 THEN 'Employee' ELSE 'Both' END AS Assignee,
				CCTM.Title AS eContentType, CCTM.Id AS eContentTypeId,CEC.Title as eContentTitle, CEC.Remark AS eContentRemark,tSM.Id AS SubjectId,tSM.Title As SubjectName,CEC.OrgGroupBatchId,CEC.CreatedDateTime
				FROM [sCommunication].[teContent] CEC
				INNER JOIN [sCommunication].[teContentTypeMaster] CCTM on CEC.eContentTypeId = CCTM.Id
				INNER JOIN sStudent.vStudentAcademic SA	ON CEC.SourceId=SA.StudentId  AND SA.IsActiveBatch=1 AND SA.StatusId=1
				INNER JOIN sSetup.tOrganizationMaster OM ON SA.OrgId = OM.Id			
				LEFT JOIN [sSetup].[tSubjectMaster] tSM ON tSM.Id = CEC.ContentTypeSourcetId
				WHERE CEC.SourceTypeId=2001 AND ((OM.Id=@rOrgId) OR @rOrgId=0) AND ((CEC.eContentTypeId=@reContentTypeId) OR @reContentTypeId=0) AND ((CEC.Title LIKE @rTitle) OR @rTitle='') 

				UNION

				SELECT CEC.SourceTypeId, CEC.SourceId, 'Employee' AS SourceType,EM.FirstName +' '+ EM.LastName AS Source,CEC.PathName,CEC.AssignedToId,
				CASE WHEN CEC.AssignedToId=2 THEN 'Student' WHEN CEC.AssignedToId=3 THEN 'Employee' ELSE 'Both' END AS Assignee,
				CCTM.Title AS eContentType, CCTM.Id AS eContentTypeId,CEC.Title as eContentTitle, CEC.Remark AS eContentRemark,tSM.Id AS SubjectId,tSM.Title As SubjectName,CEC.OrgGroupBatchId,CEC.CreatedDateTime
				FROM [sCommunication].[teContent] CEC
				INNER JOIN [sCommunication].[teContentTypeMaster] CCTM on CEC.eContentTypeId = CCTM.Id
				INNER JOIN [sHrm].[tEmployeeMaster] EM ON CEC.SourceId=EM.Id AND EM.StatusId=7
				INNER JOIN sSetup.tOrganizationMaster OM ON EM.OrgId = OM.Id					
				LEFT JOIN [sSetup].[tSubjectMaster] tSM ON tSM.Id = CEC.ContentTypeSourcetId
				WHERE CEC.SourceTypeId=95 AND ((OM.Id=@rOrgId) OR @rOrgId=0) AND ((CEC.eContentTypeId=@reContentTypeId) OR @reContentTypeId=0) AND ((CEC.Title LIKE @rTitle) OR @rTitle='') ) econtentList
				WHERE (econtentList.OrgGroupBatchId = @rOrgGroupBatchId OR  @rOrgGroupBatchId = 0)

		UNION


				SELECT * FROM  (SELECT CEC.SourceTypeId, CEC.SourceId, 'Organization' AS SourceType,OM.DisplayTitle AS Source,CEC.PathName,CEC.AssignedToId,
				CASE WHEN CEC.AssignedToId=2 THEN 'Student' WHEN CEC.AssignedToId=3 THEN 'Employee' ELSE 'Both' END AS Assignee,
				CCTM.Title AS eContentType, CCTM.Id AS eContentTypeId,CEC.Title as eContentTitle, CEC.Remark AS eContentRemark,tSM.Id AS SubjectId,tSM.Title As SubjectName,CEC.OrgGroupBatchId,CEC.CreatedDateTime
				FROM [sCommunication].[teContent] CEC
				INNER JOIN [sCommunication].[teContentTypeMaster] CCTM on CEC.eContentTypeId = CCTM.Id
				INNER JOIN sSetup.tOrganizationMaster OM ON CEC.SourceId=OM.Id 
				LEFT JOIN [sSetup].[tSubjectMaster] tSM ON tSM.Id = CEC.ContentTypeSourcetId
				WHERE CEC.SourceTypeId=2021 AND ((OM.Id=@rOrgId) OR @rOrgId=0) AND CEC.AssignedToId IN (1,2,3) AND ((CEC.eContentTypeId=@reContentTypeId) OR @reContentTypeId=0) AND ((CEC.Title LIKE @rTitle) OR @rTitle='') AND CEC.IsBatchIndependent = 0

				UNION
				 
				SELECT CEC.SourceTypeId, CEC.SourceId, 'Department' AS SourceType,DM.DisplayTitle AS Source,CEC.PathName ,CEC.AssignedToId,
				CASE WHEN CEC.AssignedToId=2 THEN 'Student' WHEN CEC.AssignedToId=3 THEN 'Employee' ELSE 'Both' END AS Assignee,
				CCTM.Title AS eContentType, CCTM.Id AS eContentTypeId,CEC.Title as eContentTitle, CEC.Remark AS eContentRemark,tSM.Id AS SubjectId,tSM.Title As SubjectName,CEC.OrgGroupBatchId,CEC.CreatedDateTime
				FROM [sCommunication].[teContent] CEC
				INNER JOIN [sCommunication].[teContentTypeMaster] CCTM on CEC.eContentTypeId = CCTM.Id
				INNER JOIN sSetup.tDepartmentMaster DM ON CEC.SourceId=DM.Id
				INNER JOIN sSetup.tOrganizationMaster OM ON DM.OrgId=OM.Id 
				LEFT JOIN [sSetup].[tSubjectMaster] tSM ON tSM.Id = CEC.ContentTypeSourcetId
				WHERE CEC.SourceTypeId=2017 AND ((OM.Id=@rOrgId) OR @rOrgId=0) AND CEC.AssignedToId IN (1,2,3) AND ((CEC.eContentTypeId=@reContentTypeId) OR @reContentTypeId=0) AND ((CEC.Title LIKE @rTitle) OR @rTitle='') AND CEC.IsBatchIndependent = 0

				UNION

				SELECT CEC.SourceTypeId, CEC.SourceId, 'Class' AS SourceType,CM.DisplayTitle AS Source,CEC.PathName,CEC.AssignedToId, 
				CASE WHEN CEC.AssignedToId=2 THEN 'Student' WHEN CEC.AssignedToId=3 THEN 'Employee' ELSE 'Both' END AS Assignee,
				CCTM.Title AS eContentType, CCTM.Id AS eContentTypeId,CEC.Title as eContentTitle, CEC.Remark AS eContentRemark,tSM.Id AS SubjectId,tSM.Title As SubjectName,CEC.OrgGroupBatchId,CEC.CreatedDateTime
				FROM [sCommunication].[teContent] CEC
				INNER JOIN [sCommunication].[teContentTypeMaster] CCTM on CEC.eContentTypeId = CCTM.Id
				INNER JOIN sSetup.tClassMaster CM ON CEC.SourceId=CM.Id
				INNER JOIN sSetup.tDepartmentMaster DM ON CM.DepartmentId =DM.Id		
				INNER JOIN sSetup.tOrganizationMaster OM ON DM.OrgId=OM.Id
				LEFT JOIN [sSetup].[tSubjectMaster] tSM ON tSM.Id = CEC.ContentTypeSourcetId
				WHERE CEC.SourceTypeId=2016 AND ((OM.Id=@rOrgId) OR @rOrgId=0) AND ((CEC.eContentTypeId=@reContentTypeId) OR @reContentTypeId=0) AND ((CEC.Title LIKE @rTitle) OR @rTitle='') AND CEC.IsBatchIndependent = 0

				UNION

				SELECT CEC.SourceTypeId, CEC.SourceId, 'Division' AS SourceType,CM.DisplayTitle+'-'+DM.DisplayTitle AS Source,CEC.PathName,CEC.AssignedToId,
				CASE WHEN CEC.AssignedToId=2 THEN 'Student' WHEN CEC.AssignedToId=3 THEN 'Employee' ELSE 'Both' END AS Assignee,
				CCTM.Title AS eContentType, CCTM.Id AS eContentTypeId,CEC.Title as eContentTitle, CEC.Remark AS eContentRemark,tSM.Id AS SubjectId,tSM.Title As SubjectName,CEC.OrgGroupBatchId,CEC.CreatedDateTime
				FROM [sCommunication].[teContent] CEC
				INNER JOIN [sCommunication].[teContentTypeMaster] CCTM on CEC.eContentTypeId = CCTM.Id
				INNER JOIN sSetup.tDivisionMaster DM ON CEC.SourceId=DM.Id
				INNER JOIN sSetup.tClassMaster CM ON DM.ClassId=CM.Id	
				INNER JOIN sSetup.tDepartmentMaster DMast ON CM.DepartmentId =DMast.Id
				INNER JOIN sSetup.tOrganizationMaster OM ON DMast.OrgId=OM.Id		
				LEFT JOIN [sSetup].[tSubjectMaster] tSM ON tSM.Id = CEC.ContentTypeSourcetId
				WHERE CEC.SourceTypeId=2005 AND ((OM.Id=@rOrgId) OR @rOrgId=0) AND ((CEC.eContentTypeId=@reContentTypeId) OR @reContentTypeId=0) AND ((CEC.Title LIKE @rTitle) OR @rTitle='') AND CEC.IsBatchIndependent = 0

				UNION
				 
				SELECT CEC.SourceTypeId, CEC.SourceId, 'Student' AS SourceType,[sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Source,CEC.PathName,
				CEC.AssignedToId,CASE WHEN CEC.AssignedToId=2 THEN 'Student' WHEN CEC.AssignedToId=3 THEN 'Employee' ELSE 'Both' END AS Assignee,
				CCTM.Title AS eContentType, CCTM.Id AS eContentTypeId,CEC.Title as eContentTitle, CEC.Remark AS eContentRemark,tSM.Id AS SubjectId,tSM.Title As SubjectName,CEC.OrgGroupBatchId,CEC.CreatedDateTime
				FROM [sCommunication].[teContent] CEC
				INNER JOIN [sCommunication].[teContentTypeMaster] CCTM on CEC.eContentTypeId = CCTM.Id
				INNER JOIN sStudent.tStudentMaster SM ON CEC.SourceId=SM.Id
				INNER JOIN  sStudent.vStudentAcademic SA ON CEC.SourceId=SA.StudentId AND SA.IsActiveBatch=1 AND SA.StatusId=1		
				INNER JOIN sSetup.tOrganizationMaster OM ON SM.OrgId = OM.Id		
				LEFT JOIN [sSetup].[tSubjectMaster] tSM ON tSM.Id = CEC.ContentTypeSourcetId
				WHERE CEC.SourceTypeId=2003 AND ((OM.Id=@rOrgId) OR @rOrgId=0) AND ((CEC.eContentTypeId=@reContentTypeId) OR @reContentTypeId=0) AND ((CEC.Title LIKE @rTitle) OR @rTitle='') AND CEC.IsBatchIndependent = 0

				UNION

				SELECT CEC.SourceTypeId, CEC.SourceId, 'Student' AS SourceType,SA.Name AS Source,CEC.PathName,CEC.AssignedToId,
				CASE WHEN CEC.AssignedToId=2 THEN 'Student' WHEN CEC.AssignedToId=3 THEN 'Employee' ELSE 'Both' END AS Assignee,
				CCTM.Title AS eContentType, CCTM.Id AS eContentTypeId,CEC.Title as eContentTitle, CEC.Remark AS eContentRemark,tSM.Id AS SubjectId,tSM.Title As SubjectName,CEC.OrgGroupBatchId,CEC.CreatedDateTime
				FROM [sCommunication].[teContent] CEC
				INNER JOIN [sCommunication].[teContentTypeMaster] CCTM on CEC.eContentTypeId = CCTM.Id
				INNER JOIN sStudent.vStudentAcademic SA	ON CEC.SourceId=SA.StudentId  AND SA.IsActiveBatch=1 AND SA.StatusId=1
				INNER JOIN sSetup.tOrganizationMaster OM ON SA.OrgId = OM.Id			
				LEFT JOIN [sSetup].[tSubjectMaster] tSM ON tSM.Id = CEC.ContentTypeSourcetId
				WHERE CEC.SourceTypeId=2001 AND ((OM.Id=@rOrgId) OR @rOrgId=0) AND ((CEC.eContentTypeId=@reContentTypeId) OR @reContentTypeId=0) AND ((CEC.Title LIKE @rTitle) OR @rTitle='') AND CEC.IsBatchIndependent = 0

				UNION

				SELECT CEC.SourceTypeId, CEC.SourceId, 'Employee' AS SourceType,EM.FirstName +' '+ EM.LastName AS Source,CEC.PathName,CEC.AssignedToId,
				CASE WHEN CEC.AssignedToId=2 THEN 'Student' WHEN CEC.AssignedToId=3 THEN 'Employee' ELSE 'Both' END AS Assignee,
				CCTM.Title AS eContentType, CCTM.Id AS eContentTypeId,CEC.Title as eContentTitle, CEC.Remark AS eContentRemark,tSM.Id AS SubjectId,tSM.Title As SubjectName,CEC.OrgGroupBatchId,CEC.CreatedDateTime
				FROM [sCommunication].[teContent] CEC
				INNER JOIN [sCommunication].[teContentTypeMaster] CCTM on CEC.eContentTypeId = CCTM.Id
				INNER JOIN [sHrm].[tEmployeeMaster] EM ON CEC.SourceId=EM.Id AND EM.StatusId=7
				INNER JOIN sSetup.tOrganizationMaster OM ON EM.OrgId = OM.Id					
				LEFT JOIN [sSetup].[tSubjectMaster] tSM ON tSM.Id = CEC.ContentTypeSourcetId
				WHERE CEC.SourceTypeId=95 AND ((OM.Id=@rOrgId) OR @rOrgId=0) AND ((CEC.eContentTypeId=@reContentTypeId) OR @reContentTypeId=0) AND ((CEC.Title LIKE @rTitle) OR @rTitle='') AND CEC.IsBatchIndependent = 0 ) econtentList
				ORDER BY econtentList.CreatedDateTime DESC
				
		END
END
GO
PRINT N'Altering [sCommunication].[pOnlineLearningAttendanceListGet]...';


GO
 
ALTER PROCEDURE [sCommunication].[pOnlineLearningAttendanceListGet]
	@rOnlineLearningId bigint 
	

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 


CREATE TABLE #SourceTypeId
	(
		Id int IDENTITY,
		SourceTypeId bigint
	)
	CREATE TABLE #StudentData
	(
	StudentName nvarchar(200),
	LoggedInStatus int,
	IsPresent nvarchar(100),
	InCount int,
	StudentId bigint,
	AcademicId bigint,
	RollNo int,
	ClassName nvarchar(200),
	Code nvarchar(20)
	)


DECLARE @rClassId bigint , @rBatchId bigint
--Select Distinct @lSourceTypeId= SourceTypeId from [sAcademic].[tOnlineLearningScope] Where OnlineLearningId=@rOnlineLearningId
SELECT @rClassId = ClassId, @rBatchId= BatchId FROM sAcademic.tOnlineLearning WHERE Id = @rOnlineLearningId

INSERT INTO #SourceTypeId
Select Distinct  SourceTypeId from [sAcademic].[tOnlineLearningScope] Where OnlineLearningId=@rOnlineLearningId

--Select @lSourceTypeId
DECLARE @lCountSourceTypeId int,@lSourceTypeId int,@lId int

SELECT @lCountSourceTypeId=COUNT(SourceTypeId) FROM #SourceTypeId
	SELECT Top 1 @lId=Id FROM #SourceTypeId

	
	WHILE @lId <= @lCountSourceTypeId
			BEGIN
			SELECT @lSourceTypeId=SourceTypeId FROM #SourceTypeId WHERE Id=@lId

--StudentId
	IF(@lSourceTypeId=2003)
	BEGIN
	INSERT INTO #StudentData
	SELECT 

			
			SA.FirstName +' '+SA.MiddleName +' '+SA.LastName As StudentName ,
			ISNULL((SELECT ISNULL(IsLoggedIn,0)  FROM sAcademic.tOnlineLearningAttendance OLA 
			WHERE OLA.AcademicId=SA.AcademicId AND OLA.OnlineLearningId=@rOnlineLearningId),0)AS LoggedInStatus,
			ISNULL((SELECT (CASE WHEN OLA.IsPresent=1 THEN 'true' ELSE 'false' END)  FROM sAcademic.tOnlineLearningAttendance OLA 
			WHERE OLA.AcademicId=SA.AcademicId AND OLA.OnlineLearningId=@rOnlineLearningId),'false')AS IsPresent,
			(SELECT COUNT(OLAL.Academicid ) FROM sAcademic.tOnlineLearningAttendanceLog OLAL WHERE OLAL.AcademicId=SA.AcademicId
			 AND OLAL.OnlineLearningId = @rOnlineLearningId  
			)As InCount ,
			SA.StudentId ,
			SA.Academicid ,
			SA.RollNo,
			(SA.ClassName+'-'+SA.DivisionName) as ClassName,
			SA.Code
			
  FROM		sStudent.vStudentAcademic SA
			INNER JOIN sAcademic.tOnlineLearningScope OLS ON SA.StudentId=OLS.SourceId
			INNER JOIN [sAcademic].[tOnlineLearning] OL ON OL.Id=OLS.OnlineLearningId
			AND SA.BatchId = OL.BatchId
			WHERE 
			OLS.OnlineLearningId=@rOnlineLearningId
			AND OL.BatchId=@rBatchId AND SA.StatusId = 1
			GROUP BY --OLAL.OnlineLearningId,
			SA.StudentId,SA.FirstName ,SA.MiddleName,SA.LastName,--OLA.IsPresent,
			SA.ClassName,SA.Code,SA.RollNo,SA.RollNo,--OLAL.Academicid,
			SA.DivisionName,SA.ClassID,
			SA.DivisionId,SA.AcademicId,OL.StartDate
			ORDER BY SA.ClassID,SA.DivisionId,SA.RollNo
	END
	--AcademicId
	ELSE IF(@lSourceTypeId=2001)
	BEGIN
	INSERT INTO #StudentData
	SELECT 

			
			SA.FirstName +' '+SA.MiddleName +' '+SA.LastName As StudentName ,
			ISNULL((SELECT ISNULL(IsLoggedIn,0)  FROM sAcademic.tOnlineLearningAttendance OLA 
			WHERE OLA.AcademicId=SA.AcademicId AND OLA.OnlineLearningId=@rOnlineLearningId),0)AS LoggedInStatus,
			ISNULL((SELECT (CASE WHEN OLA.IsPresent=1 THEN 'true' ELSE 'false' END)  FROM sAcademic.tOnlineLearningAttendance OLA 
			WHERE OLA.AcademicId=SA.AcademicId AND OLA.OnlineLearningId=@rOnlineLearningId),'false')AS IsPresent,
			(SELECT COUNT(OLAL.Academicid ) FROM sAcademic.tOnlineLearningAttendanceLog OLAL WHERE OLAL.AcademicId=SA.AcademicId
			 AND OLAL.OnlineLearningId = @rOnlineLearningId  
			)As InCount ,
			SA.StudentId ,
			SA.Academicid ,
			SA.RollNo,
			(SA.ClassName+' - '+SA.DivisionName) as ClassName,
			SA.Code
			
  FROM		sStudent.vStudentAcademic SA
			INNER JOIN sAcademic.tOnlineLearningScope OLS ON SA.AcademicId=OLS.SourceId
			INNER JOIN [sAcademic].[tOnlineLearning] OL ON OL.Id=OLS.OnlineLearningId
			AND SA.BatchId = OL.BatchId
			WHERE 
			OLS.OnlineLearningId=@rOnlineLearningId
			AND OL.BatchId=@rBatchId AND SA.StatusId = 1
			GROUP BY --OLAL.OnlineLearningId,
			SA.StudentId,SA.FirstName ,SA.MiddleName,SA.LastName,--OLA.IsPresent,
			SA.ClassName,SA.Code,SA.RollNo,SA.RollNo,--OLAL.Academicid,
			SA.DivisionName,SA.ClassID,
			SA.DivisionId,SA.AcademicId,OL.StartDate
			ORDER BY SA.ClassID,SA.DivisionId,SA.RollNo
	END
	--ClassId
	ELSE IF(@lSourceTypeId=2016)
	BEGIN
	INSERT INTO #StudentData
	SELECT 

			SA.FirstName +' '+SA.MiddleName +' '+SA.LastName As StudentName ,
			ISNULL((SELECT ISNULL(IsLoggedIn,0)  FROM sAcademic.tOnlineLearningAttendance OLA 
			WHERE OLA.AcademicId=SA.AcademicId AND OLA.OnlineLearningId=@rOnlineLearningId),0)AS LoggedInStatus,
			ISNULL((SELECT (CASE WHEN OLA.IsPresent=1 THEN 'true' ELSE 'false' END)  FROM sAcademic.tOnlineLearningAttendance OLA 
			WHERE OLA.AcademicId=SA.AcademicId AND OLA.OnlineLearningId=@rOnlineLearningId),'false')AS IsPresent,
			(SELECT COUNT(OLAL.Academicid ) FROM sAcademic.tOnlineLearningAttendanceLog OLAL WHERE OLAL.AcademicId=SA.AcademicId
			 AND OLAL.OnlineLearningId = @rOnlineLearningId  
			)As InCount ,
			SA.StudentId ,
			SA.Academicid ,
			SA.RollNo,
			(SA.ClassName+' - '+SA.DivisionName) as ClassName,
			SA.Code
			
  FROM		sStudent.vStudentAcademic SA
			INNER JOIN sAcademic.tOnlineLearningScope OLS ON SA.ClassId=OLS.SourceId
			INNER JOIN [sAcademic].[tOnlineLearning] OL ON OL.Id=OLS.OnlineLearningId
			AND SA.BatchId = OL.BatchId			
			WHERE 
			OLS.OnlineLearningId=@rOnlineLearningId
			AND OL.BatchId=@rBatchId AND SA.StatusId = 1
			GROUP BY --OLAL.OnlineLearningId,
			SA.StudentId,SA.FirstName ,SA.MiddleName,SA.LastName,--OLA.IsPresent,
			SA.ClassName,SA.Code,SA.RollNo,SA.RollNo,--OLAL.Academicid,
			SA.DivisionName,SA.ClassID,
			SA.DivisionId,SA.AcademicId,OL.StartDate
			ORDER BY SA.ClassID,SA.DivisionId,SA.RollNo
	END
	--DeparmentId
	ELSE IF(@lSourceTypeId=2017)
	BEGIN
	INSERT INTO #StudentData
	SELECT 

			SA.FirstName +' '+SA.MiddleName +' '+SA.LastName As StudentName ,
			ISNULL((SELECT ISNULL(IsLoggedIn,0)  FROM sAcademic.tOnlineLearningAttendance OLA 
			WHERE OLA.AcademicId=SA.AcademicId AND OLA.OnlineLearningId=@rOnlineLearningId),0)AS LoggedInStatus,
			ISNULL((SELECT (CASE WHEN OLA.IsPresent=1 THEN 'true' ELSE 'false' END)  FROM sAcademic.tOnlineLearningAttendance OLA 
			WHERE OLA.AcademicId=SA.AcademicId AND OLA.OnlineLearningId=@rOnlineLearningId),'false')AS IsPresent,
			(SELECT COUNT(OLAL.Academicid ) FROM sAcademic.tOnlineLearningAttendanceLog OLAL WHERE OLAL.AcademicId=SA.AcademicId
			 AND OLAL.OnlineLearningId = @rOnlineLearningId  
			)As InCount ,
			SA.StudentId ,
			SA.Academicid ,
			SA.RollNo,
			(SA.ClassName+' - '+SA.DivisionName) as ClassName,
			SA.Code
			
  FROM		sStudent.vStudentAcademic SA
			INNER JOIN sAcademic.tOnlineLearningScope OLS ON SA.DepartmentId=OLS.SourceId
			INNER JOIN [sAcademic].[tOnlineLearning] OL ON OL.Id=OLS.OnlineLearningId
			AND SA.BatchId = OL.BatchId			
			WHERE 
			OLS.OnlineLearningId=@rOnlineLearningId
			AND OL.BatchId=@rBatchId AND SA.StatusId = 1
			GROUP BY --OLAL.OnlineLearningId,
			SA.StudentId,SA.FirstName ,SA.MiddleName,SA.LastName,--OLA.IsPresent,
			SA.ClassName,SA.Code,SA.RollNo,SA.RollNo,--OLAL.Academicid,
			SA.DivisionName,SA.ClassID,
			SA.DivisionId,SA.AcademicId,OL.StartDate
			ORDER BY SA.ClassID,SA.DivisionId,SA.RollNo
	END
	--OrgId
	ELSE IF(@lSourceTypeId=2021)
	BEGIN
	INSERT INTO #StudentData
	SELECT 

			SA.FirstName +' '+SA.MiddleName +' '+SA.LastName As StudentName ,
			ISNULL((SELECT ISNULL(IsLoggedIn,0)  FROM sAcademic.tOnlineLearningAttendance OLA 
			WHERE OLA.AcademicId=SA.AcademicId AND OLA.OnlineLearningId=@rOnlineLearningId),0)AS LoggedInStatus,
			ISNULL((SELECT (CASE WHEN OLA.IsPresent=1 THEN 'true' ELSE 'false' END)  FROM sAcademic.tOnlineLearningAttendance OLA 
			WHERE OLA.AcademicId=SA.AcademicId AND OLA.OnlineLearningId=@rOnlineLearningId),'false')AS IsPresent,
			(SELECT COUNT(OLAL.Academicid ) FROM sAcademic.tOnlineLearningAttendanceLog OLAL WHERE OLAL.AcademicId=SA.AcademicId
			 AND OLAL.OnlineLearningId = @rOnlineLearningId  
			)As InCount ,
			SA.StudentId ,
			SA.Academicid ,
			SA.RollNo,
			(SA.ClassName+' - '+SA.DivisionName) as ClassName,
			SA.Code
			
  FROM		sStudent.vStudentAcademic SA
			INNER JOIN sAcademic.tOnlineLearningScope OLS ON SA.OrgId=OLS.SourceId
			INNER JOIN [sAcademic].[tOnlineLearning] OL ON OL.Id=OLS.OnlineLearningId
			AND SA.BatchId = OL.BatchId			
			WHERE 
			OLS.OnlineLearningId=@rOnlineLearningId
			AND OL.BatchId=@rBatchId AND SA.StatusId = 1
			GROUP BY --OLAL.OnlineLearningId,
			SA.StudentId,SA.FirstName ,SA.MiddleName,SA.LastName,--OLA.IsPresent,
			SA.ClassName,SA.Code,SA.RollNo,SA.RollNo,--OLAL.Academicid,
			SA.DivisionName,SA.ClassID,
			SA.DivisionId,SA.AcademicId,OL.StartDate
			ORDER BY SA.ClassID,SA.DivisionId,SA.RollNo
	END
	
	--Division
	ELSE IF(@lSourceTypeId=2005)
	BEGIN
	INSERT INTO #StudentData
	SELECT 

			SA.FirstName +' '+SA.MiddleName +' '+SA.LastName As StudentName ,
			ISNULL((SELECT ISNULL(IsLoggedIn,0)  FROM sAcademic.tOnlineLearningAttendance OLA 
			WHERE OLA.AcademicId=SA.AcademicId AND OLA.OnlineLearningId=@rOnlineLearningId),0)AS LoggedInStatus,
			ISNULL((SELECT (CASE WHEN OLA.IsPresent=1 THEN 'true' ELSE 'false' END)  FROM sAcademic.tOnlineLearningAttendance OLA 
			WHERE OLA.AcademicId=SA.AcademicId AND OLA.OnlineLearningId=@rOnlineLearningId),'false')AS IsPresent,
			(SELECT COUNT(OLAL.Academicid ) FROM sAcademic.tOnlineLearningAttendanceLog OLAL WHERE OLAL.AcademicId=SA.AcademicId
			 AND OLAL.OnlineLearningId = @rOnlineLearningId  
			)As InCount ,
			SA.StudentId ,
			SA.Academicid ,
			SA.RollNo,
			(SA.ClassName+' - '+SA.DivisionName) as ClassName,
			SA.Code
			
  FROM		sStudent.vStudentAcademic SA
			INNER JOIN sAcademic.tOnlineLearningScope OLS ON SA.DivisionId=OLS.SourceId
			INNER JOIN [sAcademic].[tOnlineLearning] OL ON OL.Id=OLS.OnlineLearningId
			AND SA.BatchId = OL.BatchId
			WHERE 
			OLS.OnlineLearningId=@rOnlineLearningId
			AND OL.BatchId=@rBatchId AND SA.StatusId = 1
			GROUP BY --OLAL.OnlineLearningId,
			SA.StudentId,SA.FirstName ,SA.MiddleName,SA.LastName,--OLA.IsPresent,
			SA.ClassName,SA.Code,SA.RollNo,SA.RollNo,--OLAL.Academicid,
			SA.DivisionName,SA.ClassID,
			SA.DivisionId,SA.AcademicId,OL.StartDate
			ORDER BY SA.ClassID,SA.DivisionId,SA.RollNo
	END

	SET @lId=@lId+1
	END
	Select * from #StudentData
	DROP TABLE #SourceTypeId
	DROP TABLE #StudentData

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


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


GO
 
ALTER PROCEDURE [sCommunication].[pStudentUploadedDocumentListGet]
	 
	 @rSourceId bigint,
	 @rDivisionId int = 0,
	 @rBatchId int,
	 @rSyncedUploadResultId int=0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	IF (@rSourceId!=0)
	BEGIN
		SELECT @rDivisionId=DivisionId FROM sStudent.tAcademic		
		 WHERE StudentId=@rSourceId AND BatchId = @rBatchId
	END
		SELECT 
			@rSourceId AS SourceId,
			SDU.Id,
			SDU.Title,
			SDTM.Title AS DocumentType,
			S.Code,
			SDU.DocumentUploadDate,
			 BM.OrgId
		FROM 
			sCommunication.tStudentDocumentUpload SDU  
			INNER JOIN sStudent.vStudentAcademic S ON S.DivisionId = SDU.DivisionId AND SDU.BatchId = S.BatchId 
			AND S.StudentId = @rSourceId AND S.BatchId = @rBatchId
			INNER JOIN sCommunication.tStudentDocumentTypeMaster SDTM ON SDTM.Id = SDU.StudentDocumentTypeId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = S.BatchId
		WHERE 
			SDU.DivisionId=@rDivisionId
			AND SDU.BatchId=@rBatchId
			AND SDU.IsObsolete=0
			AND ( SDU.Id > @rSyncedUploadResultId OR @rSyncedUploadResultId = 0)
			and SDU.DocumentUploadDate <= replace(convert(varchar, sCommon.fGetDate(), 111), '/','-') 
				order by SDU.DocumentUploadDate,S.RollNo,S.Code DESC
END
GO
PRINT N'Altering [sEExam].[pAvailableTestsGet]...';


GO
 
 
ALTER PROCEDURE [sEExam].[pAvailableTestsGet]

		@rUserSourceTypeId smallint,
		@rUserSourceId bigint,
		@rBatchId int,
		@rFromDate date=NULL,
		@rToDate date=NULL
			
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			
BEGIN  
	
  SELECT  
		TP.Id AS TestParticipantId,		
		TM.Title AS Test,
		VCS.SubjectName,
		TM.Id AS TestId,
		TM.TotalMarks,
		ISNULL(SM.Title,'')AS TestStatus,
		TP.TestStatusId,
		[sEExam].[fCheckIsHTMLGet](TM.Id) AS IsHtml,
		TM.IsDisplayResultOnComplete,
		TM.IsAllowReview,
		ISNULL(TM.TestStartupRemark,'') AS TestStartupRemark,
		ISNULL(TM.TestDuration,0) AS TestDuration,
		ISNULL(TM.AlertDuration,0) AS AlertDuration,
		TM.FromTime,
		TM.ToTime,
		ISNULL(TM.FromDate,'')AS FromDate,
		ISNULL(TM.ToDate,'')AS ToDate,
		ISNULL(((CAST(TM.FromDate as DATETIME) + CAST(TM.FromTime as TIME))),'')AS FromDateTime,
		ISNULL(((CAST(TM.ToDate as DATETIME) + CAST(TM.ToTime as TIME))),'')AS ToDateTime
		

  FROM 
	    sEExam.tTestParticipant TP 
		INNER JOIN sEExam.tTestMaster TM ON TM.Id=TP.TestId 
		INNER JOIN sSetup.vClassSubject VCS ON VCS.ClassSubjectId=TM.ClassSubjectId
		LEFT JOIN sCommon.tStatusMaster SM ON SM.Id=TP.TestStatusId
WHERE 
		TP.SourceId=@rUserSourceId 
		AND TP.SourceTypeId = @rUserSourceTypeId 
		AND TM.BatchId = @rBatchId
		AND IsTestLock = 1
		AND ((TM.TestDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((TM.TestDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		AND TP.TestStatusId !=0
	    ORDER BY TP.TestStatusId,TP.TestId DESC 
END
GO
PRINT N'Altering [sEExam].[pDsTestParticipantAnswerAdd]...';


GO
 
ALTER PROCEDURE [sEExam].[pDsTestParticipantAnswerAdd]
	 
	@rTestParticipantId bigint,
	@rTestId int,
	@rQuestionDetailXml [nvarchar](max),
	@rQuestionOptionDetailXml [nvarchar](max)
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

	DECLARE @loQuestionDoc INT
	EXEC sp_xml_preparedocument @loQuestionDoc OUTPUT, @rQuestionDetailXml
	
	DECLARE @loQuestionOptionDoc INT
	EXEC sp_xml_preparedocument @loQuestionOptionDoc OUTPUT, @rQuestionOptionDetailXml
	
BEGIN

	BEGIN TRY	
	--BEGIN TRANSACTION
	
	DELETE FROM sEExam.tTestParticipantAnswer WHERE TestParticipantId=@rTestParticipantId AND TestId=@rTestId
	
	UPDATE sEExam.tTestParticipant
	    SET
			TestDate = A.TestDate,
			StartTime = A.StartTime,
			EndTime = A.EndTime,
			TestStatusId = A.TestStatusId,
			TotalMarks = A.TotalMarks,
			ScoredMarks = A.ScoredMarks,
			TotalQuestions = A.TotalQuestions,
			RightQuestions = A.RightQuestions,
			WrongQuestions = A.WrongQuestions,
			SkippQuestions = A.SkippQuestions,
			NotAttemptedQuestions = A.NotAttemptedQuestions
			FROM
		 (
	  SELECT TOP 1
	        @rTestParticipantId AS TestParticipantId,
	        @rTestId AS TestId,
			TestDate,
			StartTime,
			EndTime,
			TestStatusId,
			TotalMarks,
			ScoredMarks,
			TotalQuestions,
			RightQuestions,
			WrongQuestions,
			SkippQuestions,
			NotAttemptedQuestions
		FROM OPENXML (@loQuestionDoc, '/Table/QuestionDetail', 1)
		WITH ( 
		        SourceTypeId smallint,
			    SourceId bigint,
			    TestDate date,
			    StartTime time,
			    EndTime time,
			    TestStatusId smallint,
				TotalMarks decimal(6,2),
				ScoredMarks decimal(6,2),
				TotalQuestions int,
				RightQuestions int,
				WrongQuestions int,
				SkippQuestions int,
				NotAttemptedQuestions int
			  ))A	
			    WHERE 
			    --A.TestParticipantId = @rTestParticipantId AND A.TestId = @rTestId
			    --AND 
			    sEExam.tTestParticipant.Id = A.TestParticipantId
			    
	INSERT INTO sEExam.tTestParticipantAnswer
		(
			TestId,
			QuestionId,
			QuestionOptionId,
			ScoredMark,
			AnswerStatusId,
			OrderIndex,
			TestParticipantId
		)
	  SELECT 
			@rTestId,
			QuestionId,
			QuestionOptionId,
			ScoredMark,
			AnswerStatusId,
			OrderIndex,
			@rTestParticipantId
			
		FROM OPENXML (@loQuestionOptionDoc, '/Table/QuestionOptionDetail', 1)
		WITH ( 
		        TestId Int,
				QuestionId bigint,
				QuestionOptionId bigint,
				ScoredMark decimal(6,2),
				AnswerStatusId smallint,
				OrderIndex smallint
			  ) 
		SELECT 1 AS Result   
		
		SELECT IsDisplayResultOnComplete FROM sEExam.tTestMaster WHERE Id =@rTestId
		
		EXEC sp_xml_removedocument @loQuestionDoc
		EXEC sp_xml_removedocument @loQuestionOptionDoc
		--COMMIT TRANSACTION
	END TRY
	BEGIN CATCH 
		--ROLLBACK TRANSACTION
		SELECT -1 AS Result
		EXEC sp_xml_removedocument @loQuestionDoc
		EXEC sp_xml_removedocument @loQuestionOptionDoc
	END CATCH	 
	 
	
   
END
GO
PRINT N'Altering [sEExam].[pTestMasterGet]...';


GO

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

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


GO
ALTER PROCEDURE [sEExam].[pTestParticipantResultGet]
 
			@rBuilder1 nvarchar(max)='',
			@rTestId int,		 
			@rSourceTypeID int = 0,
			@rSourceId bigint = 0,
			@rBatchId int=0
           
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON  
BEGIN   

DECLARE @1TestAssignStatusId int

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


GO

  
ALTER PROCEDURE [sFee].[pFeeExportDetailsGet]    
      
  @rOrgGroupBatchId int,    
  @rAdmissionCategoryId int,    
  @rClassId int,    
  @rDivisionId int,    
  @rIdNo nvarchar(20)='',    
  @rFirstName nvarchar(100)='',    
  @rFromReceiptNumber int=0,    
  @rToReceiptNumber int=0,    
  @rReceiptBookId int=0,    
  @rSourceTypeId int=0,    
  @rPayTypeId int,    
  @rChequeNo nvarchar(20)='',    
  @rFromDate date,    
  @rToDate date,    
  @rIsObsolete bit,    
  @rOrgId smallint,    
  @rBatchId int,    
  @rOrgGroupId smallint,    
  @rCreatedUserName nvarchar(100),    
  @rCreatedUserId bigint,    
  @rDepartmentId int=0,    
  @rFromChequeDate date='',    
  @rToChequeDate date='',    
  @rSUId nvarchar(20) = '',    
  @rLastName nvarchar(100) = '',  
  @rPayTypeIds nvarchar(max) = '',
  @rBankName nvarchar(100)='',
  @rCancelStatusId int = 0
      
 WITH EXECUTE AS CALLER    
AS    
SET NOCOUNT ON    
        
    BEGIN    
		SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)    
		SET @rLastName = sCommon.fSearchStringGet(@rLastName)    
		SET @rCreatedUserName = sCommon.fSearchStringGet(@rCreatedUserName)   
		SET @rBankName = sCommon.fSearchStringGet(@rBankName)    
    END 
	
BEGIN       

CREATE Table #FeeReceiptDetail
		(
		StatusId bigint,
		ReceiptId bigint,
		FeeCode nvarchar(100),
		FeeAmount decimal(12,2),
		Organization nvarchar(max),
		Batch nvarchar(100),
		BatchId bigint,
		Code nvarchar(20),
		ClassDiv nvarchar(200),
		Name nvarchar(300),
		ReceiptNumber nvarchar(200),
		ReceiptDate Date,
		ReceiptAmount decimal(12,2),
		PayType nvarchar(300),
		ChequeNo nvarchar(20),
		Remark nvarchar(max),
		ChequeDate nvarchar(50),
		InvoiceNumber int,
		ReceiptCreatedDateTime datetime,
		BankName nvarchar(200),
		ReceiptBookName nvarchar(100),
		TotalReceiptAmount decimal(12,2),
		DiscountAmount decimal(12,2),
		VariableAmount decimal(12,2),
		ExemptionAmount decimal(12,2),
		AdditionalAmount decimal(12,2),
		NotApplicableAmount decimal(12,2)
		
		)


INSERT INTO #FeeReceiptDetail
 SELECT 
    A.StatusId,    
	R.Id AS ReceiptId,
	FM.Code,
	RD.Amount,
	OM.DisplayTitle AS Organization,  
	BM.Title AS Batch,
	BM.Id AS BatchId,
	A.Code AS Code, 
	CM.Title +' - '+ DM.Title AS ClassDiv,
	A.Name,    
	R.ReceiptNumber,   
	R.ReceiptDate,     
	ISNULL(R.ReceiptAmount,0)AS ReceiptAmount,
	PTM.Title AS PayType,    
	CASE WHEN ISNULL(R.ChequeNo,'') != '' THEN R.ChequeNo ELSE CONVERT(nvarchar(20),R.PaymentTransactionId) END AS ChequeNo,    
	R.Remark,
	CONVERT(VARCHAR(10), R.ChequeDate, 103)AS ChequeDate, 
	--ISNULL(CAST(R.ChequeDate AS Date),'') AS ChequeDate, 
	ISNULL(FI.InvoiceNumber,0) AS InvoiceNumber,    
	R.CreatedDateTime AS ReceiptCreatedDateTime,
	R.BankName,    
	RBM.Title AS ReceiptBook,    
    ISNULL(R.TotalReceiptAmount,0)AS TotalReceiptAmount,    
    ISNULL(R.DiscountAmount,0)AS DiscountAmount,
	FA.VariableAmount,
	FA.DiscountAmount AS ExemptionAmount,
	FA.AdditionalAmount,
	FA.NotApplicableAmount
	
	
  
  FROM     
  
     sFee.tReceipt R    
  INNER JOIN sStudent.vStudentAcademic A    
   ON A.AcademicId=R.SourceId AND (A.AdmissionCategoryId=@rAdmissionCategoryId OR @rAdmissionCategoryId=0)   
   
  INNER JOIN  sSetup.tClassMaster CM ON CM.Id = A.ClassId     
  INNER JOIN  sSetup.tDivisionMaster DM ON DM.Id = A.DivisionId     
  INNER JOIN sCommon.tSourceTypeMaster STM    
   ON STM.Id=R.SourceTypeId    
  INNER JOIN sFinanceCommon.tPayTypeMaster PTM    
   ON PTM.Id=R.PayTypeId    
  INNER JOIN sFee.tReceiptBookMaster RBM    
   ON RBM.Id=R.ReceiptBookId    
  INNER JOIN sSetup.tOrganizationMaster OM    
   ON OM.Id=A.OrgId    
    AND OM.OrgGroupId=@rOrgGroupId    
  INNER JOIN sSetup.tBatchMaster BM    
   ON BM.Id=R.BatchId     
   AND BM.OrgGroupBatchId=@rOrgGroupBatchId    
  LEFT JOIN sSecurity.tUser U ON U.Id=R.CreatedUserId    
  INNER JOIN sFee.vUserReceiptBook URB ON URB.Id=RBM.Id AND URB.UserId=@rCreatedUserId    
  LEFT JOIN sFee.tFeeInvoice FI ON FI.Id = R.FeeInvoiceId    
  
  INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
  INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id 
  INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
  LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=A.AcademicId
  
WHERE     
 ((A.Code like @rIdNo) OR (ISNULL(@rIdNo,'')=''))    
 AND (R.SourceTypeId=2001)    
 AND ((A.FirstName like @rFirstName) OR(ISNULL(@rFirstName,'')=''))    
 AND ((R.ReceiptNumber>=@rFromReceiptNumber)OR(@rFromReceiptNumber=0))    
 AND ((R.ReceiptNumber<=@rToReceiptNumber)OR(@rToReceiptNumber=0))    
 AND ((R.ReceiptBookId=@rReceiptBookId)OR(@rReceiptBookId=0))    
 AND ((R.PayTypeId=@rPayTypeId)OR(@rPayTypeId=0))    
 AND ((ISNULL(R.PayTypeId,0) IN ( SELECT cast(item as int) FROM  sCommon.fnsplit(@rPayTypeIds,','))) OR (ISNULL(@rPayTypeIds,'')=''))
 AND ((R.ChequeNo like @rChequeNo) OR(ISNULL(@rChequeNo,'')=''))    
 AND ((STM.Id=@rSourceTypeId)OR(@rSourceTypeId=0))    
 AND ((R.ReceiptDate>=@rFromDate)OR(ISNULL(@rFromDate,'')=''))    
 AND ((R.ReceiptDate<=@rToDate)OR(ISNULL(@rToDate,'')=''))    
 AND (R.IsObsolete=@rIsObsolete)    
 AND ((A.OrgId=@rOrgId) OR (@rOrgId=0))    
 AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))    
 AND ((ISNULL(U.DisplayTitle,'') like @rCreatedUserName) OR (ISNULL(@rCreatedUserName,'')=''))    
 AND ((CM.DepartmentId = @rDepartmentId) OR (@rDepartmentId=0))    
 AND ((A.ClassId=@rClassId) OR (@rClassId=0))     
 AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))    
 AND ((R.ChequeDate>=@rFromChequeDate)OR(ISNULL(@rFromChequeDate,'')=''))    
 AND ((R.ChequeDate<=@rToChequeDate)OR(ISNULL(@rToChequeDate,'')=''))    
 AND ((A.SUId like @rSUId) OR (ISNULL(@rSUId,'')=''))    
 AND ((A.LastName like @rLastName) OR (ISNULL(@rLastName,'')=''))  
 AND ((R.BankName like @rBankName) OR(ISNULL(@rBankName,'')=''))    
 AND ((R.CancelStatusId = @rCancelStatusId) OR(@rCancelStatusId=0)) ----Added By Dhruv for Issue No.11130    
 ORDER BY R.ReceiptNumber DESC   
 
 --Select * from #FeeReceiptDetail
 DECLARE @cols AS NVARCHAR(MAX),@query  AS NVARCHAR(MAX)

    SELECT @cols = STUFF((SELECT  DISTINCT ',' + QUOTENAME(ID.FeeCode)
                       FROM #FeeReceiptDetail ID FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,'')   
 
    SELECT @query = 
    'SELECT  
			P.*,
            ID.VariableAmount,
            ID.ExemptionAmount,
            ID.AdditionalAmount,
            ID.NotApplicableAmount ,
			ID.DiscountAmount
     FROM
    (SELECT  
	
		ReceiptId ,
		Organization ,
		Batch ,
		Code ,
		ClassDiv ,
		Name ,
		ReceiptNumber ,
		ReceiptDate ,
		ReceiptAmount ,
		Remark,
		PayType ,
		ChequeNo ,
		ChequeDate, 
		BankName ,
		ReceiptBookName ,
		InvoiceNumber,    
		ReceiptCreatedDateTime,
		TotalReceiptAmount ,
		FeeCode, 
        FeeAmount
		    		
    FROM #FeeReceiptDetail)X
    PIVOT 
    (
         SUM(FeeAmount) 
         FOR [FeeCode] IN (' +  @cols + ')
    ) P
    LEFT JOIN
	(
		SELECT
		    ReceiptId,
			SUM(VariableAmount) AS VariableAmount,
			SUM(ExemptionAmount) AS ExemptionAmount,
			SUM(AdditionalAmount) AS AdditionalAmount,
			SUM(NotApplicableAmount) AS NotApplicableAmount,
			(DiscountAmount) AS DiscountAmount
		FROM  
			#FeeReceiptDetail
			GROUP BY ReceiptId,DiscountAmount
    ) ID ON ID.ReceiptId = P.ReceiptId
	Order By P.ReceiptNumber DESC
    '
	EXECUTE(@query) 
END
GO
PRINT N'Altering [sFee].[pFeeReceiptListViewGet]...';


GO

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

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


GO


ALTER PROCEDURE [sFee].[pOldFeeDetailsImportAdd]
	
	@rOldOrgGroupBatchId int,
	@rNewOrgGroupBatchId int,
	@rOldBatchId int,
	@rNewBatchId int,
	@rOrgId int,
	@rCreatedUserId bigint,
	@rOldClassId bigint,
	@rNewClassId bigint
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
BEGIN TRY 

	CREATE TABLE #TempOldFeeImport
	(
		[AutoId] int identity,
		[StudentId] bigint NULL ,
		[AcademicId] bigint NULL,
		[Amount] decimal(12,2) NULL,
		[DiscountAmount] decimal(12,2) NULL,
		[AdditionalAmount] decimal(12,2) NULL,
		[NotApplicableAmount] decimal(12,2) NULL,
		[AdmissionCategoryId] bigint,
		[FeeSetupId] bigint
	)

	INSERT INTO #TempOldFeeImport 
	SELECT 
		SA.StudentId,
		SA.AcademicId,
		--SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)) AS PendingAmount
		ISNULL(FA.VariableAmount,0.00)AS Amount,
		ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
		ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
		ISNULL(FA.NotApplicableAmount,0.00)AS NotApplicableAmount,
		SA.AdmissionCategoryId,
		FA.FeeSetupId

  FROM 
  
			 sStudent.vStudentAcademic SA
			 INNER JOIN sSetup.tBatchMaster BM ON SA.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOldOrgGroupBatchId
			 LEFT JOIN sFee.tFeeAllocation FA ON  FA.SourceId=SA.AcademicId
			 WHERE 
			 SA.OrgGroupBatchId = @rOldOrgGroupBatchId
			AND ((SA.BatchId=@rOldBatchId) OR (@rOldBatchId=0))
			AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
			AND	((SA.ClassId=@rOldClassId) OR (@rOldClassId=0))
			AND SA.StatusId=1

			--Select * from #TempOldFeeImport
BEGIN TRANSACTION

			DECLARE @lCount int
			SELECT @lCount = COUNT(AutoId) FROM #TempOldFeeImport

	WHILE (@lCount > 0)
	BEGIN
		DECLARE @lAcademicId bigint = NULL
		DECLARE @lOldAcademicId bigint = NULL
		DECLARE @lStudentId bigint = NULL
		DECLARE @lClassId int = NULL
		DECLARE @lFeeSetupId int = NULL
		--DECLARE @lPendingAmount decimal(12,2)
		
		DECLARE @lDiscountAmount decimal(12,2)
		DECLARE @lAdditionalAmount decimal(12,2)
		DECLARE @lNotApplicableAmount decimal(12,2)
		DECLARE @rNewAdmissionCategoryId  bigint
		DECLARE @rOldAdmissionCategoryId  bigint
		DECLARE @OldFeeName nvarchar(200)
		DECLARE @newFeeName nvarchar(200)
		DECLARE @lOldAmount decimal(12,2)
		DECLARE @lNewAmount decimal(12,2)
		Declare @FeeName nvarchar(500)
		DECLARE @lOldFeeSetupId bigint
	
		SELECT @lStudentId = StudentId,@lOldAcademicId=AcademicId,@lOldAmount=Amount,@lDiscountAmount=DiscountAmount,@lAdditionalAmount=AdditionalAmount,@lNotApplicableAmount=NotApplicableAmount,@rOldAdmissionCategoryId=AdmissionCategoryId,@lOldFeeSetupId=FeeSetupId FROM #TempOldFeeImport WHERE AutoId = @lCount
		SELECT @lAcademicId = AcademicId, @lClassId=ClassId ,@rNewAdmissionCategoryId = AdmissionCategoryId FROM  sStudent.vStudentAcademic SA WHERE StudentId = @lStudentId AND BatchId = @rNewBatchId
		SELECT @OldFeeName=FM.Code FROM sFee.tFeeSetup FS1 INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
		WHERE  FS1.ClassId = @rOldClassId  AND FS1.BatchId=@rOldBatchId AND FS1.AdmissionCategoryId = @rOldAdmissionCategoryId AND FS1.Id=@lOldFeeSetupId
		
		SELECT @lFeeSetupId = FS1.Id FROM sFee.tFeeSetup FS1 INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
		WHERE  FS1.ClassId = @lClassId  AND FS1.BatchId=@rNewBatchId AND FS1.AdmissionCategoryId = @rNewAdmissionCategoryId AND FM.Code=@OldFeeName

		SELECT @lNewAmount=FS1.Amount FROM sFee.tFeeSetup FS1 
		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
		WHERE  FS1.ClassId = @lClassId  AND FS1.BatchId=@rNewBatchId AND FS1.AdmissionCategoryId = @rNewAdmissionCategoryId AND FS1.Id=@lFeeSetupId

		--Select @OldFeeName=FM.Code FROM sFee.tFeeSetup FS1 INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		--WHERE  ClassId = @rOldClassId  AND BatchId=@rOldBatchId AND AdmissionCategoryId = @rOldAdmissionCategoryId AND FS1.Id=@lOldFeeSetupId
		Select @NewFeeName=FM.Code FROM sFee.tFeeSetup FS1 INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
		WHERE  FS1.ClassId = @lClassId  AND FS1.BatchId=@rNewBatchId AND FS1.AdmissionCategoryId = @rNewAdmissionCategoryId AND FS1.Id=@lFeeSetupId

				--Select @lOldAcademicId,@lAcademicId,@lFeeSetupId,@OldFeeName,@NewFeeName,@lNewAmount,@lDiscountAmount,@FeeName,@OldFeeName
				--Select @OldFeeName,@NewFeeName


		--SELECT @lFeeSetupId,@lAcademicId,@lStudentId
		IF NOT EXISTS(Select 1 FROM  sFee.tFeeAllocation Where SourceId=@lAcademicId AND FeeSetupId=@lFeeSetupId)
		BEGIN
			IF @lAcademicId IS NOT NULL AND @lFeeSetupId IS NOT NULL AND @lClassId IS NOT NULL AND @OldFeeName IS NOT NULL AND @NewFeeName IS NOT NULL AND (@OldFeeName=@NewFeeName) 
			AND (ISNULL(@lNewAmount,0) >= ISNULL(@lDiscountAmount,0))
				BEGIN
		
				INSERT INTO sFee.tFeeAllocation
			   (
			    SourceTypeId,
			    SourceId,
			    FeeSetupId,
			    VariableAmount,
			    DiscountAmount,
			    AdditionalAmount,
			    NotApplicableAmount,
			    Remark,
			    ReferenceTypeId,
			    ReferenceSourceId,
			    CreatedUserId,
			    CreatedDateTime,
			    UpdatedUserId,
			    UpdatedDateTime
			   )
				VALUES
			   (
				2001,
				@lAcademicId,
				@lFeeSetupId,
				0,
				@lDiscountAmount,
				@lAdditionalAmount,
				@lNotApplicableAmount,
				'Old Year Discount,Additional,NotApplicable Fee',
				NULL,
				NULL,
				@rCreatedUserId,
				sCommon.fGetDate(),
				NULL,
				NULL
			   )

				END
				ELSE
				BEGIN
				 Select -102 AS Result
				END

		END
		ELSE
		BEGIN
			IF @lAcademicId IS NOT NULL AND @lFeeSetupId IS NOT NULL AND @lClassId IS NOT NULL AND @OldFeeName IS NOT NULL AND @NewFeeName IS NOT NULL AND (@OldFeeName=@NewFeeName) 
			AND (ISNULL(@lNewAmount,0) >= ISNULL(@lDiscountAmount,0))
				BEGIN
		
				-- Update Fee Allocation
				UPDATE sFee.tFeeAllocation
				SET SourceTypeId = 2001, 
			    SourceId = @lAcademicId,
			    FeeSetupId = @lFeeSetupId,
			    --VariableAmount = 0,
			    DiscountAmount = @lDiscountAmount,
			    AdditionalAmount = @lAdditionalAmount,
			    NotApplicableAmount = @lNotApplicableAmount,
			    Remark ='Old Year Discount,Additional,NotApplicable Fee',
			    ReferenceTypeId = NULL,
			    ReferenceSourceId = NULL,
			    CreatedUserId = @rCreatedUserId,
			    CreatedDateTime = sCommon.fGetDate(),
			    UpdatedUserId = NULL,
			    UpdatedDateTime = NULL
				WHERE 
				SourceId = @lAcademicId
				AND SourceTypeId = 2001
				AND FeeSetupId = @lFeeSetupId
			  
				END

			ELSE
			BEGIN
				Select -102 AS Result
			END
		END
		SET @lCount = @lCount -1
	END

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

BEGIN CATCH 

		ROLLBACK TRANSACTION
		SELECT -1 AS Result
END CATCH	
END
GO
PRINT N'Altering [sFee].[pRptFeeReceiptDetailsGet]...';


GO
ALTER PROCEDURE [sFee].[pRptFeeReceiptDetailsGet]
			
			
			@rReportId int=0,
			@rReceiptId bigint = 0,
			@rOrgGroupId int = 0,
			@rReceiptBookId int = 0,
			@rFromReceiptNo int=0,
			@rToReceiptNo int=0,
			@rOrgId int = 0,
			@rBatchId int = 0,
			@rReceiptDate Date='',
			@rClassId int = 0,
			@rOrgIds nvarchar(max) = '',
			@rReceiptPrintGroupId nvarchar(100)=''
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 	
	
	DECLARE @lOrgGroupId int = 0
	DECLARE @lAmountInWord nvarchar(500) = ''
	DECLARE @lReceiptAmount Decimal(12,2) = 0.0
	DECLARE @lCurrencyCode nvarchar(20) = ''
	DECLARE @lCurrencyTitle nvarchar(100) = ''
	Declare @lIDConfigValue nvarchar(50)='',@lOrgGroup_Id int=0
	Select @lOrgGroup_Id = OrgGroupId From  sSetup.tOrganizationMaster Where Id = @rOrgId
	 
	SELECT @lIDConfigValue =ItemValue From sConfig.tConfigurationSetup
	WHERE ConfigurationId = 236 AND SourceId = @rOrgGroupId
	
	IF(@rOrgGroupId=0)
	BEGIN
		SELECT @lOrgGroupId = OrgGroupId ,@lReceiptAmount = R.ReceiptAmount  FROM sFee.tReceipt R 
		INNER JOIN sSetup.tOrgGroupBatchMaster OB ON R.OrgGroupBatchId = OB.Id 
		WHERE R.Id = @rReceiptId

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

	SELECT 
			FRD.ReceiptId,
			FR.ReceiptNumber,
			FR.ReceiptDate,
			SA.AcademicId,
			--SA.FirstName+' '+SA.MiddleName+' '+SA.LastName AS Name,
			SA.Name AS Name,
			SA.Code,
			SA.RollNo,
			SA.ClassId,
			SA.DivisionId,
			SA.ClassName,
			SA.DivisionName,
			SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
			FM.FeeHeadId,
			FHM.Title AS FeeHead,
			FM.Id AS FeeId,
			FM.Title AS FeeName,
			FRD.Amount AS PaidAmount,
			PTM.Id AS PayTypeId,
			PTM.Title AS PayType,
			CASE WHEN ISNULL(FR.ChequeNo,'') != '' THEN FR.ChequeNo ELSE CONVERT(nvarchar(20),FR.PaymentTransactionId) + CONVERT(nvarchar(20),PT.BankTransactionId) END AS ChequeNo,
			--ISNULL(FR.ChequeNo,'') AS ChequeNo,
			ISNULL(FR.BankName,'') AS BankName,
			ISNULL(RBM.Address1,'') AS Address1,
			ISNULL(RBM.Address2,'') AS Address2,
			ISNULL(RBM.FullTitle,'') AS FullTitle,
			ISNULL(FR.TotalReceiptAmount,0.00) AS TotalReceiptAmount,
			ISNULL(FR.ReceiptAmount,0.00) AS ReceiptAmount,			
			
			(CASE WHEN @rOrgGroupId = 0 -- For Single Receipt
					THEN @lAmountInWord 
				  WHEN @rOrgGroupId != 0 -- For Bulk Receipt
					THEN sFinanceCommon.fNumberToWordsWithDecimal(ISNULL(FR.ReceiptAmount,0.00),1,2,@rOrgGroupId)
			END) AS ReceiptAmountInWords,
			
			ISNULL(FR.DiscountAmount,0.00) AS DiscountAmount,
			FR.Remark,
			(CASE WHEN  U.SourceTypeId = 2003 
			  THEN -- Navrachana
				'Online Generated'
				ELSE ISNULL(U.DisplayTitle,'') END) AS UserName,
			--ISNULL(U.DisplayTitle,'') AS UserName,
			OM.OrgLogo,
			RBM.Remark1,
			RBM.Remark2,			 
			ISNULL(RBM.IsOnPrePrinted,0) AS IsOnPrePrinted,
			ISNULL(RBM.IsSupressLogo,0) AS IsSupressLogo,
			ISNULL(RBM.IsDisplaySchoolName,0) AS IsDisplaySchoolName,
			RBM.ReportId,
			OM.Title AS OrganizationName,
			--(CASE  WHEN (RBM.ReportId = 20775 OR RBM.ReportId = 20777 OR RBM.ReportId = 20874 OR RBM.ReportId =20427 OR RBM.ReportId =20890 OR RBM.ReportId =20901 OR RBM.ReportId =20902) AND ISNULL(RBM.IsMonthDetailOnly,0) = 0  THEN 
			--	[sFee].[fFeeHeadMonthDetailGet](FR.ID,FHM.Id) -- Fee name in detail	
				  
			  
			(CASE WHEN  RBM.ReportId = 20576
			      THEN -- HM patel report
				  [sFee].[fReceiptMonthDetailGet](FR.ID,0)
			      WHEN RBM.ReportId = 30457 
			      THEN
				  [sFee].[fReceiptMonthDetailGet](FR.ID,1)		
			      WHEN ISNULL(RBM.IsMonthDetailOnly,0) = 1  AND ISNULL(RBM.IsFeeInvoiceHeadwise,0) = 1
			      THEN				
				  [sFee].[fFeeHeadMonthNameGet](FR.ID,FHM.Id) -- Head wise Month name in detail
				  WHEN ISNULL(RBM.IsMonthDetailOnly,0) = 1  AND ISNULL(RBM.IsFeeInvoiceHeadwise,0) = 0
			      THEN				
				  [sFee].[fFeeMonthNameGet](FR.ID,FM.Id) -- Fee wise Month name in detail
			ELSE '' END) 
			AS MonthDetail,    

 
			--FS.FeeDuration AS FeeDuration,
			
			Stuff((SELECT  N', ' +  FS1.FeeDuration FROM 
			sFee.tReceipt FR1				
			INNER JOIN sFee.tReceiptDetail FRD1	ON FR1.Id=FRD1.ReceiptId AND FR1.SourceTypeId=2001				
			INNER JOIN sFee.tFeeSetup FS1 ON FRD1.FeeSetupId = FS1.Id
			INNER JOIN sFee.tFeeMaster FM1 ON FS1.FeeId=FM1.Id						
			INNER JOIN sFee.tFeeHeadMaster FHM1 ON FHM1.Id=FM1.FeeHeadId 
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId = FR1.SourceId
			--Where FM1.FeeHeadId = FM.FeeHeadId AND FS.ClassId = FS1.ClassId AND FR1.Id = @rReceiptId
			Where FM1.Id = FM.Id AND FS.ClassId = FS1.ClassId AND FR1.Id = @rReceiptId
			AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
			 Order By FS.StartDate
			FOR XML PATH(''),TYPE).value('text()[1]','nvarchar(max)'),1,2,N'' ) AS FeeDuration,
			
			
			DM.Title AS DepartmentName,
			FM.OrderIndex AS FeeOrderIndex,
			FHM.OrderIndex AS FeeHeadOrderIndex,
			FR.IsObsolete AS IsCancelReceipt,
			@lCurrencyCode AS CurrencyCode,
			@lCurrencyTitle AS CurrencyTitle,
			BM.Title AS Batch,
			FR.ChequeDate AS ChequeDate,
			ISNULL(RBM.IsMonthDetailOnly,0) AS IsMonthDetailOnly,
	        ISNULL(RBM.IsFeeInvoiceHeadwise,0) AS IsFeeInvoiceHeadwise,
	        ISNULL(RBM.GroupTitle,'') AS GroupTitle,
	        ISNULL(RBM.IsSuppressFeeDetail,0) AS IsSuppressFeeDetail,
	        ISNULL(CGM.Title,'') AS CollectionGroupName,
	        ISNULL(FI.InvoiceNumber,0) AS InvoiceNumber,
	        SA.SUID,
	        CASE
				 WHEN RBM.IsOnPrePrinted=1       
				 THEN 2
				 ELSE  ISNULL(RBM.HeaderDisplayId,1)
				END AS HeaderDisplayId,
	        RBM.ReceiptBookHeader,
	        RBM.ServiceTaxPercentage,
	        ISNULL(FR.AmountAfterDiscount,0) AS AmountAfterDiscount,
	        (CASE WHEN  FR.CGSTPercentage IS NULL THEN RBM.CGSTPercentage ELSE FR.CGSTPercentage END) AS CGSTPercentage,
	        (CASE WHEN  FR.SGSTPercentage IS NULL THEN RBM.SGSTPercentage ELSE FR.SGSTPercentage END) AS SGSTPercentage,
	        ISNULL(FR.CGSTAmount,0) AS CGSTAmount,
	        ISNULL(FR.SGSTAmount,0) AS SGSTAmount,
	        ISNULL(OOM.GSTINNo,'') AS GSTINNo,
	        ISNULL(OOM.HSNSACCode,'') AS HSNSACCode,
	        @lIDConfigValue AS ItemValue ,
	        SF.FatherName,
	        SF.MotherName,
	        ISNULL(FA.DiscountAmount,0) AS ExemptionAmount,
			ISNULL(FA.Remark,'') AS ExemptionRemark,
			EI.EmployeeSign,
			ISNULL(SC.PresentCity,'') AS PresentCity,

			(ISNULL((CASE WHEN SC.PresentStreetOne IS NOT NULL AND SC.PresentStreetOne!='' THEN ''+ SC.PresentStreetOne END),'')+
			ISNULL((CASE WHEN SC.PresentStreetTwo IS NOT NULL AND SC.PresentStreetTwo!=''  THEN ', '+ SC.PresentStreetTwo END),'')+
			ISNULL((CASE WHEN SC.PresentStreetThree IS NOT NULL AND SC.PresentStreetThree!=''  THEN ', '+ SC.PresentStreetThree END),'')+
			ISNULL((CASE WHEN SC.PresentCity IS NOT NULL AND SC.PresentCity!=''  THEN ', ' + SC.PresentCity  END),'')+
			ISNULL((CASE WHEN SC.PresentState IS NOT NULL AND SC.PresentState!=''  THEN  ', '+ SC.PresentState END),'')+
			ISNULL((CASE WHEN SC.PresentZipCode IS NOT NULL AND SC.PresentZipCode!=''  THEN  ', '+ SC.PresentZipCode  END),''))
			 AS PresentAdress,
			--ISNULL(SC.PresentStreetOne +','+ SC.PresentStreetTwo +','+ SC.PresentStreetThree +','+ SC.PresentCity +','+ SC.PresentState +'-'+ SC.PresentZipCode ,'') AS PresentAdress,
			SC.ParentContactNo,
			ISNULL(RBM.IsDisplayPendingFeeAmount,0) AS IsDisplayPendingFeeAmount,
			(CASE WHEN  ISNULL(RBM.IsDisplayPendingFeeAmount,0) = 0 THEN 0 ELSE ISNULL([sFee].[fPendingFeeAmountReceiptBookwiseGet](FR.SourceId,0),0) END) AS PendingFeeAmount,
			SA.FirstName,
			SA.LastName
	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 sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
			INNER JOIn sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=FR.PayTypeId
			LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
			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
			LEFT JOIN sSetup.tOrganizationOtherDetail OOM ON OM.Id=OOM.OrgId	
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = FR.BatchId 
			LEFT JOIN sFee.tCollectionGroupMaster CGM ON CGM.Id=FR.CollectionGroupId 
			LEFT JOIN sFee.tFeeInvoice FI ON FI.Id=FR.FeeInvoiceId
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SA.StudentId
			LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = U.SourceId AND U.SourceTypeId=95
			LEFT JOIN sOp.tPaymentTransaction PT ON PT.Id = FR.PaymentTransactionId
	WHERE 
			((FR.Id=@rReceiptId) OR (@rReceiptId = 0))
			AND ((RBM.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId = 0))
			AND ((FR.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId = 0))
			AND ((FR.ReceiptNumber >= @rFromReceiptNo) OR (@rFromReceiptNo = 0))
			AND ((FR.ReceiptNumber <= @rToReceiptNo) OR (@rToReceiptNo = 0))
			AND ((FR.BatchId = @rBatchId) OR (@rBatchId = 0))
			AND ((BM.OrgId = @rOrgId) OR (@rOrgId = 0))
			AND ((FR.ReceiptDate = @rReceiptDate) OR (ISNULL(@rReceiptDate,'') = ''))
			AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
			AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')			
			AND ((ISNULL(FR.ReceiptPrintGroupId,'')=@rReceiptPrintGroupId) OR (ISNULL(@rReceiptPrintGroupId,'') = ''))
    ORDER BY 
            FS.StartDate,FHM.OrderIndex,FM.OrderIndex ASC

--For Dataset




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


GO


ALTER PROCEDURE [sFee].[pRptFeeStatusStudentWisewithDiscountGet]
		
	@rReportId int,
	@rReceiptBookId int,
	@rAdmissionCategoryId int,
	@rClassId int,
	@rDivisionId int,
	@rUptoDate date,
	@rBatchId int,
	@rUserId bigint,
	@rBuilder1 nvarchar(max),
	@rBuilder2 nvarchar(max),
	@rIsDetail bit,
	@rOrgId int,
	@rOrgGroupBatchId int,
	@rIsExemption bit =0,
	@rStatusId int,
	@rCommonBatch nvarchar(100),
	@rDepartmentId int,
	@rFromRollNo int,
    @rToRollNo int,
    @rCode nvarchar(20),
    @rIsFilter bit,
	@rIsHeader bit,
	@rCreatedUserName nvarchar(100)='',
	@rFeeHeadId nvarchar(max) = '',
	@rIsDisplayOrgGroup bit=0,
	@rExemptionTypeId int=0,
	@rFeeId nvarchar(max) = '',
	@rFilterId int=0,
	@rFeeGroupId int=0,
	@rOrgGroupId int=0,
	@rOrgIds nvarchar(max) = '',
	@rIsReceiptBookGroup bit=0,
	@rClassStatusId int=0   
		
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN
	

		CREATE TABLE #tmp
		(
		AcademicId bigint,
		RollNo int,
		Name nvarchar(200),
		Code nvarchar(100),
		ClassId bigint,
		DivisionId bigint,
		ClassName nvarchar(100),
		DivisionName nvarchar(100),
		DivisionOrderIndex int,
		ClassOrderIndex int,
		ClassDivision  nvarchar(200),
		--IsVariable int ,
		Amount decimal(12,2),
		--StartDate date,
	 --   EndDate date,
		FAAmount decimal(12,2),
		DiscountAmount decimal(12,2),
	    AdditionalAmount decimal(12,2),
		NotApplicableAmount decimal(12,2),
		PaidAmount decimal(12,2),
		PendingAmount decimal(12,2),
		--Remark nvarchar(max),
		--ReceiptBookId bigint,
		--FeeName nvarchar(200),
		--FeeCode nvarchar(200),
		OrgId bigint,
		OrgName nvarchar(500),
		OrgOrderIndex int,
		--ReceiptBookTitle nvarchar(500),
		--ReceiptOrderIndex int,
		DepartmentId bigint,
		DepartmentName nvarchar(200),
		--ExemptionTypeId bigint, 
		--ExemptionType nvarchar(200),
		--FeeHeadId bigint,
		--FeeHeadName nvarchar(500),
	    --FeeHeadOrderIndex int,
		--FeeGroup int,
		BatchId bigint,
		BatchName nvarchar(200),
		CancelAmount decimal(12,2),
		Discount decimal(12,2)
		
		)
		INSERT INTO #tmp
		SELECT 
			SA.AcademicId,
			SA.RollNo,
			SA.Name,
			SA.Code,
			SA.ClassId,
			SA.DivisionId,
			SA.ClassName,
			SA.DivisionName,
			SA.DivisionOrder AS DivisionOrderIndex,
			SA.ClassOrderIndex AS ClassOrderIndex,
			SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
			--FS.Id AS FeeSetupId,
			--ISNULL(FS.IsVariable,0)AS IsVariable,
			ISNULL(FS.Amount,0)AS Amount,
			--ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
			--ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
			ISNULL(FA.VariableAmount,0.00)AS FAAmount,
			ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
			ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
			ISNULL(FA.NotApplicableAmount,0.00)AS NotApplicableAmount,
			ISNULL(R.PaidAmount,0) AS PaidAmount,
			ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)AS PendingAmount,
			--ISNULL(FA.Remark,'') AS Remark,
			--FS.ReceiptBookId,
			--FS.FeeName,
			--FS.FeeCode,
			SA.OrgId,
			O.DisplayTitle AS OrgName,
			O.OrderIndex AS OrgOrderIndex,
			--ISNULL(RBM.Title,'') AS ReceiptBookTitle,
			--ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
			SA.DepartmentId,
			SA.DepartmentName,
			--SA.ExemptionTypeId,
			--ISNULL(ETM.Title,'') AS ExemptionType,
			--FHM.Id AS FeeHeadId,
			--FHM.Title AS FeeHeadName,
			--FHM.OrderIndex AS FeeHeadOrderIndex,
			--@rFeeGroupId As FeeGroup,
			SA.OrgGroupBatchId AS BatchId,
			SA.BatchName AS BatchName,
			0.00 AS CancelAmount,
			(Select ISNULL(SUM(R.DiscountAmount),0) FROM  sFee.tReceipt R Where R.SourceId=SA.AcademicId AND ((R.ReceiptBookId=@rReceiptBookId)OR (@rReceiptBookId=0))) AS Discount
	  FROM 
			sStudent.vStudentAcademic SA
			INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA.StudentId
			INNER JOIN 
			(
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.IsOptional,0)AS IsOptional,
					--ISNULL(FS1.IsVariable,0)AS IsVariable,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
					ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
					FS1.BatchId,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					SA1.AcademicId,
					FM.Title AS FeeName,
					FM.Code AS FeeCode,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0))
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				WHERE 
					((FS1.ClassId=@rClassId) OR (@rClassId=0))
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
					AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
					AND (FS1.IsOptional=0)
					AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
					AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
					AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
					AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
					AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
					UNION ALL
					
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.IsOptional,0)AS IsOptional,
					--ISNULL(FS1.IsVariable,0)AS IsVariable,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
					ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
					FS1.BatchId,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					SA1.AcademicId,
					FM.Title AS FeeName,
					FM.Code As FeeCode,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1
			INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id 
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND FS1.BatchId = SA1.BatchId
			AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) 
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
			WHERE
				((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=1)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0)
			) FS ON FS.AcademicId=SA.AcademicId
			LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
			LEFT JOIN
			(
				SELECT 
						ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
				FROM
						sFee.tReceipt R 
					INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
					INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
					INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
					INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId 
					INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA1.StudentId
					AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (SA1.ClassId=@rClassId OR @rClassId=0) 
					AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
				WHERE		
					(R.SourceTypeId = 2001)
					AND (R.IsObsolete = 0) 
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (SA1.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId=0)
					AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
					AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
					AND (R.ReceiptDate <= @rUptoDate)
					AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
					AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
					AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0)
					AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
					--AND ((tSA.LeftDate > @rUptoDate) OR (tSA.LeftDate Is null))
					AND (tSA.AdmissionDate <= @rUptoDate)
						GROUP BY FeeSetupId,R.SourceId
			
			) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
			 INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
			 INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
			 INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FS.FeeHeadId	
			 LEFT JOIN sFee.tExemptionTypeMaster ETM ON ETM.Id = SA.ExemptionTypeId
			 LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
			 LEFT JOIN
			(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
			INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
			INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
			ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 

			WHERE	
			((@rIsExemption = 0 AND  1 = 1) OR (@rIsExemption = 1  AND  ISNULL(FA.DiscountAmount,0) > 0))
			AND	((SA.BatchId=@rBatchId) OR (@rBatchId=0))   
			AND	((SA.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))   
			AND (SA.StatusId=@rStatusId OR @rStatusId=0)
			--AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
			AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
			AND ((SA.Code=@rCode) OR (@rCode=''))
			AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))		
			AND ((SA.ExemptionTypeId=@rExemptionTypeId) OR (@rExemptionTypeId=0))		
			AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
			AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			 AND (
					 (@rFilterId = 0) -- All
					 OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel
					 OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport
					 OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))
					 )	
		AND (O.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=0)
		AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
		--AND ((tSA.LeftDate > @rUptoDate) OR (tSA.LeftDate Is null))
		AND (tSA.AdmissionDate <= @rUptoDate)
		 AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))  	
		 
		Order by SA.RollNo 
		--Select * from #tmp
		SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		@rIsDetail AS IsDetail,
		@rIsFilter AS IsFilter,
		@rIsHeader AS IsHeader,
		@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
		AcademicId ,
		RollNo ,
		Name ,
		Code ,
		ClassId ,
		DivisionId ,
		ClassName ,
		DivisionName ,
		DivisionOrderIndex ,
		ClassOrderIndex ,
		ClassDivision  ,
		--IsVariable  ,
		--((select (SUM(Amount)) from #tmp t Where AcademicId=t1.AcademicId AND Amount > 0 )- (select (SUM(Amount))*-1 from #tmp t Where AcademicId=t1.AcademicId AND Amount < 0 ))AS Amount,
		SUM(Amount)AS Amount ,
		--StartDate ,
	    --   EndDate ,
		--((select SUM(FAAmount) from #tmp t Where AcademicId=t1.AcademicId AND FAAmount < 0 )- (select( SUM(FAAmount))*-1 from #tmp t Where AcademicId=t1.AcademicId AND FAAmount > 0 ))AS FAAmount,
		SUM(FAAmount )AS FAAmount,
		--((select SUM(DiscountAmount) from #tmp t Where AcademicId=t1.AcademicId AND DiscountAmount < 0 )- (select( SUM(DiscountAmount))*-1 from #tmp t Where AcademicId=t1.AcademicId AND DiscountAmount > 0 ))AS DiscountAmount,
		SUM(DiscountAmount )AS DiscountAmount,
		--((select SUM(AdditionalAmount) from #tmp t Where AcademicId=t1.AcademicId AND AdditionalAmount < 0 )- (select( SUM(AdditionalAmount))*-1 from #tmp t Where AcademicId=t1.AcademicId AND AdditionalAmount > 0 ))AS AdditionalAmount,
	    SUM(AdditionalAmount)AS AdditionalAmount,
		--((select SUM(NotApplicableAmount) from #tmp t Where AcademicId=t1.AcademicId AND NotApplicableAmount < 0 )- (select( SUM(NotApplicableAmount))*-1 from #tmp t Where AcademicId=t1.AcademicId AND NotApplicableAmount > 0 ))AS NotApplicableAmount,
		SUM(NotApplicableAmount)AS NotApplicableAmount,
		--((select SUM(PaidAmount) from #tmp t Where AcademicId=t1.AcademicId AND PaidAmount < 0 )- (select( SUM(PaidAmount))*-1 from #tmp t Where AcademicId=t1.AcademicId AND PaidAmount > 0 ))AS PaidAmount,
		SUM(PaidAmount)AS PaidAmount,
		--((select SUM(PendingAmount) from #tmp t Where AcademicId=t1.AcademicId AND PendingAmount < 0 )- (select( SUM(PendingAmount))*-1 from #tmp t Where AcademicId=t1.AcademicId AND PendingAmount > 0 ))AS PendingAmount,
		SUM(PendingAmount)AS PendingAmount,
		OrgId ,
		OrgName ,
		OrgOrderIndex ,
		DepartmentId ,
		DepartmentName ,
		BatchId ,
		BatchName ,
		Discount 
		--ReceiptBookId ,
		--ReceiptBookTitle
		
	    FROM #tmp 
		--INNER JOIN #tmp t1 ON AcademicId=t1.AcademicId
		Group By AcademicId ,RollNo ,Name ,Code ,ClassId ,DivisionId ,ClassName ,DivisionName ,DivisionOrderIndex ,ClassOrderIndex ,ClassDivision  ,
		OrgId ,OrgName ,OrgOrderIndex ,DepartmentId ,DepartmentName ,BatchId ,BatchName ,Discount 
		--,ReceiptBookId ,ReceiptBookTitle
		
		
		DROP TABLE #tmp
	
	
	--SELECT 
	--	'' Builder1,
	--	'' AS Builder2,
	--	0 AS IsDetail,
	--	0 AS IsFilter,
	--	0 AS IsHeader,
	--	0 AS IsDisplayOrgGroup,
	--	0 AS AcademicId ,
	--	0 AS RollNo ,
	--	''AS Name ,
	--	'' AS Code ,
	--	0 AS ClassId ,
	--	0 AS DivisionId ,
	--	'' AS ClassName ,
	--	'' AS DivisionName ,
	--	0 AS DivisionOrderIndex ,
	--	0 AS ClassOrderIndex ,
	--	'' AS ClassDivision  ,
	--	0 AS IsVariable  ,
	--	0 AS  Amount ,
	--	'' AS StartDate ,
	--    '' AS EndDate ,
	--	0 AS FAAmount,
	--	0 AS DiscountAmount,
	--    0 AS AdditionalAmount,
	--	0 AS NotApplicableAmount,
	--	0 AS PaidAmount,
	--	0 AS PendingAmount,
	--	0 AS OrgId ,
	--    '' AS OrgName ,
	--	0 AS OrgOrderIndex ,
	--	0 AS DepartmentId ,
	--    '' AS DepartmentName ,
	--	0 AS BatchId ,
	--	'' AS BatchName ,
	--	0 AS Discount ,
	--	0 AS ReceiptBookId,
	--	'' AS ReceiptBookTitle
	  
	
END
GO
PRINT N'Altering [sFee].[pRptFeeStatusStudentwisewithPaidDateGet]...';


GO
 
ALTER PROCEDURE [sFee].[pRptFeeStatusStudentwisewithPaidDateGet]
	    
	    @rReportId int,
		@rReceiptBookId int,
		@rAdmissionCategoryId int,
		@rClassId int,
		@rDivisionId int,
		@rUptoDate date,
		@rBatchId int,
		@rUserId bigint,
		@rBuilder1 nvarchar(max),
		@rBuilder2 nvarchar(max),
		@rIsDetail bit,
		@rOrgId int,
		@rOrgGroupBatchId int,
		@rIsExemption bit =0,
		@rStatusId int,
		@rCommonBatch nvarchar(100),
		@rDepartmentId int,
		@rFromRollNo int,
	    @rToRollNo int,
	    @rCode nvarchar(20),
	    @rIsFilter bit,
		@rIsHeader bit,
		@rCreatedUserName nvarchar(100)='',
		@rFeeHeadId nvarchar(max) = '',
		@rIsDisplayOrgGroup bit=0,
		@rExemptionTypeId int=0,
		@rFeeId nvarchar(max) = '',
		@rFilterId int=0,
		@rClassStatusId int=0--,
		--@rOrgIds nvarchar(max) = ''
		
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 	
	SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		@rIsDetail AS IsDetail,
		@rIsFilter As IsFilter,
		@rIsHeader As IsHeader, 
		@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
		SA.AcademicId,
		SA.RollNo,
		SA.Name,
		SA.Code,
		SA.ClassId,
		SA.DivisionId,
		SA.ClassName,
		SA.DivisionName,
		SA.DivisionOrder AS DivisionOrderIndex,
		SA.ClassOrderIndex AS ClassOrderIndex,
		SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
		FS.Id AS FeeSetupId,
		ISNULL(FS.IsVariable,0)AS IsVariable,
		ISNULL(FS.Amount,0)AS Amount,
		ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
		ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
		ISNULL(FA.VariableAmount,0.00)AS FAAmount,
		ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
		ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
		ISNULL(FA.NotApplicableAmount,0.00)AS NotApplicableAmount,
		ISNULL(R.PaidAmount,0) AS PaidAmount,
		ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)AS PendingAmount,
		ISNULL(FA.Remark,'') AS Remark,
		FS.ReceiptBookId,
		FS.FeeId,
		FS.FeeName,
		FS.OrderIndex AS FeeOrderIndex,
		SA.OrgId,
		O.DisplayTitle AS OrgName,
		O.OrderIndex AS OrgOrderIndex,
		ISNULL(RBM.Title,'') AS ReceiptBookTitle,
		ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
		SA.DepartmentId,
		SA.DepartmentName,
		SA.ExemptionTypeId,
		ISNULL(ETM.Title,'') AS ExemptionType,
		FHM.Id AS FeeHeadId,
		FHM.Title AS FeeHeadName,
		FHM.OrderIndex AS FeeHeadOrderIndex,
		SA.BatchId,
		SA.BatchName,
		BM.OrderIndex AS BatchOrderIndex,
		R.InvoiceNumber,
		R.ReceiptDate,
		SO.GenderId 
  FROM 
			 sStudent.vStudentAcademic SA
		INNER JOIN 
		(
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName,
				FM.FeeHeadId,
				FM.OrderIndex
			FROM sFee.tFeeSetup FS1
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
			AND ((SA1.ClassId=@rClassId) OR (@rClassId=0))
			AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			WHERE 
				((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=0)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				UNION ALL
				
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName,
				FM.FeeHeadId,
				FM.OrderIndex
			FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO
			ON FO.FeeSetupId=FS1.Id 
	    INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId 
		AND FS1.BatchId = SA1.BatchId AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
			AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) 
			AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0)) 
			AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
		WHERE
					((FS1.ClassId=@rClassId) OR (@rClassId=0))
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=1)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
		) FS ON FS.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
		LEFT JOIN
		(
		    SELECT 
					ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId, ISNULL(MAX(FI.InvoiceNumber),0) AS InvoiceNumber,MAX(R.ReceiptDate) as ReceiptDate
		    FROM
					sFee.tReceipt R 
				INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
				INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
				INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId 
				AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND (SA1.ClassId=@rClassId OR @rClassId=0) 
				AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
				LEFT JOIN sFee.tFeeInvoice FI ON FI.Id = R.FeeInvoiceId
				
			WHERE		
				(R.SourceTypeId = 2001)
				AND (R.IsObsolete = 0) 
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND (SA1.OrgGroupBatchId = @rOrgGroupBatchId)
				AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND (R.ReceiptDate <= @rUptoDate)
				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
					GROUP BY FeeSetupId,R.SourceId
		
		) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
		 INNER JOIN sSetup.tOrganizationMaster O ON
		 SA.OrgId = O.Id
		 INNER JOIN sFee.tReceiptBookMaster RBM 
			ON FS.ReceiptBookId=RBM.Id
		 INNER JOIN sFee.tFeeHeadMaster FHM 
			ON FHM.Id=FS.FeeHeadId	
		 LEFT JOIN sFee.tExemptionTypeMaster ETM
			ON ETM.Id = SA.ExemptionTypeId
		 INNER JOIN sSetup.tBatchMaster BM
			ON BM.Id = SA.BatchId
	  LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
         LEFT JOIN
	(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
    INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
    INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
    ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
	LEFT JOIN sStudent.tStudentOther SO ON SA.StudentId=SO.StudentId		
	WHERE	
	((@rIsExemption = 0 AND  1 = 1) OR (@rIsExemption = 1  AND  ISNULL(FA.DiscountAmount,0) > 0))
    AND	((SA.BatchId=@rBatchId) OR (@rBatchId=0))   
    AND	((SA.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))   
    AND (SA.StatusId=@rStatusId OR @rStatusId=0)
	--AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
	AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
	AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
	AND ((SA.Code=@rCode) OR (@rCode=''))
	AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))		
	AND ((SA.ExemptionTypeId=@rExemptionTypeId) OR (@rExemptionTypeId=0))		
	AND (ISNULL(FA.VariableAmount,0.00) + ISNULL(FS.Amount,0)) != 0	
	AND (
	 (@rFilterId = 0) -- All
     OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel
     OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport
     OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))
    )
	AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))
			Order by SA.RollNo
END
GO
PRINT N'Altering [sFee].[pRptFeeSummaryGet]...';


GO
 
ALTER PROCEDURE [sFee].[pRptFeeSummaryGet]
		
	@rReportId int,
	@rReceiptBookId int,
	@rAdmissionCategoryId int,
	@rClassId int,
	@rDivisionId int,
	@rUptoDate date,
	@rBatchId int,
	@rUserId bigint,
	@rBuilder1 nvarchar(max),
	@rBuilder2 nvarchar(max),
	@rIsDetail bit,
	@rOrgId int,
	@rOrgGroupBatchId int,
	@rIsExemption bit =0,
	@rStatusId int = 0,
	@rCommonBatch nvarchar(100),
	@rDepartmentId int,
	@rFromRollNo int,
    @rToRollNo int,
    @rCode nvarchar(20),
    @rIsFilter bit,
	@rIsHeader bit,
	@rCreatedUserName nvarchar(100)='',
	@rFeeHeadId nvarchar(max) = '',
	@rIsDisplayOrgGroup bit=0,
	@rExemptionTypeId int=0,
	@rFeeId nvarchar(max) = '',
	@rFilterId int=0,
	@rFeeGroupId int=0,
	@rOrgGroupId int=0,
	@rOrgIds nvarchar(max) = '',
	@rIsReceiptBookGroup bit=0,
	@rClassStatusId int=0   
		
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN
	
	IF(@rReportId=20624 OR @rReportId=20842 OR @rReportId=10150 OR @rReportId=30714)
	BEGIN
		SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			@rIsDetail AS IsDetail,
			@rIsFilter As IsFilter,
			@rIsHeader As IsHeader, 
			@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
			SA.AcademicId,
			SA.RollNo,
			SA.Name,
			SA.Code,
			SA.ClassId,
			SA.DivisionId,
			SA.ClassName,
			SA.DivisionName,
			SA.DivisionOrder AS DivisionOrderIndex,
			SA.ClassOrderIndex AS ClassOrderIndex,
			SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
			FS.Id AS FeeSetupId,
			ISNULL(FS.IsVariable,0)AS IsVariable,
			ISNULL(FS.Amount,0)AS Amount,
			ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
			ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
			ISNULL(FA.VariableAmount,0.00)AS FAAmount,
			ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
			ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
			ISNULL(FA.NotApplicableAmount,0.00)AS NotApplicableAmount,
			ISNULL(R.PaidAmount,0) AS PaidAmount,
			ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)AS PendingAmount,
			ISNULL(FA.Remark,'') AS Remark,
			FS.ReceiptBookId,
			FS.FeeName,
			FS.FeeCode,
			SA.OrgId,
			O.DisplayTitle AS OrgName,
			O.OrderIndex AS OrgOrderIndex,
			ISNULL(RBM.Title,'') AS ReceiptBookTitle,
			ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
			SA.DepartmentId,
			SA.DepartmentName,
			SA.ExemptionTypeId,
			ISNULL(ETM.Title,'') AS ExemptionType,
			FHM.Id AS FeeHeadId,
			FHM.Title AS FeeHeadName,
			FHM.OrderIndex AS FeeHeadOrderIndex,
			@rFeeGroupId As FeeGroup,
			SA.OrgGroupBatchId AS BatchId,
			SA.BatchName AS BatchName,
			0.00 AS CancelAmount,
			0.00 AS Discount
	  FROM 
			sStudent.vStudentAcademic SA
			INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA.StudentId
			INNER JOIN 
			(
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.IsOptional,0)AS IsOptional,
					ISNULL(FS1.IsVariable,0)AS IsVariable,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
					ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
					FS1.BatchId,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					SA1.AcademicId,
					FM.Title AS FeeName,
					FM.Code AS FeeCode,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0))
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				WHERE 
					((FS1.ClassId=@rClassId) OR (@rClassId=0))
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
					AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
					AND (FS1.IsOptional=0)
					AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
					AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
					AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
					AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
					AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
					UNION ALL
					
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.IsOptional,0)AS IsOptional,
					ISNULL(FS1.IsVariable,0)AS IsVariable,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
					ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
					FS1.BatchId,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					SA1.AcademicId,
					FM.Title AS FeeName,
					FM.Code As FeeCode,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1
			INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id 
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND FS1.BatchId = SA1.BatchId
			AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) 
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
			WHERE
				((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=1)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0)
			) FS ON FS.AcademicId=SA.AcademicId
			LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
			LEFT JOIN
			(
				SELECT 
						ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
				FROM
						sFee.tReceipt R 
					INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
					INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
					INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
					INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId 
					INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA1.StudentId
					AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (SA1.ClassId=@rClassId OR @rClassId=0) 
					AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
				WHERE		
					(R.SourceTypeId = 2001)
					AND (R.IsObsolete = 0) 
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (SA1.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId=0)
					AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
					AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
					AND (R.ReceiptDate <= @rUptoDate)
					AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
					AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
					AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0)
					AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
					--AND ((tSA.LeftDate > @rUptoDate) OR (tSA.LeftDate Is null))
					AND (tSA.AdmissionDate <= @rUptoDate)
						GROUP BY FeeSetupId,R.SourceId
			
			) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
			 INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
			 INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
			 INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FS.FeeHeadId	
			 LEFT JOIN sFee.tExemptionTypeMaster ETM ON ETM.Id = SA.ExemptionTypeId
			 LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
			 LEFT JOIN
			(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
			INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
			INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
			ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
			WHERE	
			((@rIsExemption = 0 AND  1 = 1) OR (@rIsExemption = 1  AND  ISNULL(FA.DiscountAmount,0) > 0))
			AND	((SA.BatchId=@rBatchId) OR (@rBatchId=0))   
			AND	((SA.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))   
			AND (SA.StatusId=@rStatusId OR @rStatusId=0)
			--AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
			AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
			AND ((SA.Code=@rCode) OR (@rCode=''))
			AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))		
			AND ((SA.ExemptionTypeId=@rExemptionTypeId) OR (@rExemptionTypeId=0))		
			AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
			AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			 AND (
					 (@rFilterId = 0) -- All
					 OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel
					 OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport
					 OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))
					 )	
		AND (O.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=0)
		AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
		--AND ((tSA.LeftDate > @rUptoDate) OR (tSA.LeftDate Is null))
		AND (tSA.AdmissionDate <= @rUptoDate)
		 AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))  	
		Order by SA.RollNo 
	END
	ELSE IF(@rReportId=30655)
	BEGIN
		SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			@rIsDetail AS IsDetail,
			@rIsFilter As IsFilter,
			@rIsHeader As IsHeader, 
			@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
			SA.AcademicId,
			SA.RollNo,
			SA.Name,
			SA.Code,
			SA.ClassId,
			SA.DivisionId,
			SA.ClassName,
			SA.DivisionName,
			SA.DivisionOrder AS DivisionOrderIndex,
			SA.ClassOrderIndex AS ClassOrderIndex,
			SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
			FS.Id AS FeeSetupId,
			ISNULL(FS.IsVariable,0)AS IsVariable,
			ISNULL(FS.Amount,0)AS Amount,
			ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
			ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
			ISNULL(FA.VariableAmount,0.00)AS FAAmount,
			ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
			ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
			ISNULL(FA.NotApplicableAmount,0.00)AS NotApplicableAmount,
			ISNULL(R.PaidAmount,0) AS PaidAmount,
			ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)AS PendingAmount,
			ISNULL(FA.Remark,'') AS Remark,
			FS.ReceiptBookId,
			FS.FeeName,
			SA.OrgId,
			O.DisplayTitle AS OrgName,
			O.OrderIndex AS OrgOrderIndex,
			ISNULL(RBM.Title,'') AS ReceiptBookTitle,
			ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
			SA.DepartmentId,
			SA.DepartmentName,
			SA.ExemptionTypeId,
			ISNULL(ETM.Title,'') AS ExemptionType,
			FHM.Id AS FeeHeadId,
			FHM.Title AS FeeHeadName,
			FHM.OrderIndex AS FeeHeadOrderIndex,
			@rFeeGroupId As FeeGroup,
			SA.OrgGroupBatchId AS BatchId,
			SA.BatchName AS BatchName,
			0.00 AS CancelAmount
	  FROM 
			sStudent.vStudentAcademic SA
			INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA.StudentId
			INNER JOIN 
			(
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.IsOptional,0)AS IsOptional,
					ISNULL(FS1.IsVariable,0)AS IsVariable,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
					ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
					FS1.BatchId,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					SA1.AcademicId,
					FM.Title AS FeeName,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0))
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				WHERE 
					((FS1.ClassId=@rClassId) OR (@rClassId=0))
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
					AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
					AND (FS1.IsOptional=0)
					AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
					AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
					AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
					AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
					AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
					UNION ALL
					
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.IsOptional,0)AS IsOptional,
					ISNULL(FS1.IsVariable,0)AS IsVariable,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
					ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
					FS1.BatchId,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					SA1.AcademicId,
					FM.Title AS FeeName,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1
			INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id 
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND FS1.BatchId = SA1.BatchId
			AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) 
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
			WHERE
				((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=1)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0)
			) FS ON FS.AcademicId=SA.AcademicId
			LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
			LEFT JOIN
			(
				SELECT 
						ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
				FROM
						sFee.tReceipt R 
					INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
					INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
					INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
					INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId 
					AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (SA1.ClassId=@rClassId OR @rClassId=0) 
					AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
				WHERE		
					(R.SourceTypeId = 2001)
					AND (R.IsObsolete = 0) 
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (SA1.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId=0)
					AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
					AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
					AND (R.ReceiptDate <= @rUptoDate)
					AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
					AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
					AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0)
					AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
						GROUP BY FeeSetupId,R.SourceId
			
			) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
			 INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
			 INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
			 INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FS.FeeHeadId	
			 LEFT JOIN sFee.tExemptionTypeMaster ETM ON ETM.Id = SA.ExemptionTypeId
			 LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
			 LEFT JOIN
			(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
			INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
			INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
			ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
			WHERE	
			((@rIsExemption = 0 AND  ISNULL(FA.NotApplicableAmount,0) > 0) OR (@rIsExemption = 1  AND  ISNULL(FA.DiscountAmount,0) > 0))
			AND	((SA.BatchId=@rBatchId) OR (@rBatchId=0))   
			AND	((SA.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))   
			AND (SA.StatusId=@rStatusId OR @rStatusId=0)
			--AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
			AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
			AND ((SA.Code=@rCode) OR (@rCode=''))
			AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))		
			AND ((SA.ExemptionTypeId=@rExemptionTypeId) OR (@rExemptionTypeId=0))		
			AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
			AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			 AND (
					 (@rFilterId = 0) -- All
					 OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel
					 OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport
					 OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))
					 )	
		AND (O.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=0)
		AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
		AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))  	
		Order by SA.RollNo
	END
	ELSE IF(@rReportId=30799)
	BEGIN
		SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			@rIsDetail AS IsDetail,
			@rIsFilter As IsFilter,
			@rIsHeader As IsHeader, 
			@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
			SA.AcademicId,
			SA.RollNo,
			SA.Name,
			SA.Code,
			SA.ClassId,
			SA.DivisionId,
			SA.ClassName,
			SA.DivisionName,
			SA.DivisionOrder AS DivisionOrderIndex,
			SA.ClassOrderIndex AS ClassOrderIndex,
			SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
			FS.Id AS FeeSetupId,
			ISNULL(FS.IsVariable,0)AS IsVariable,
			ISNULL(FS.Amount,0)AS Amount,
			ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
			ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
			ISNULL(FA.VariableAmount,0.00)AS FAAmount,
			ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
			ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
			ISNULL(FA.NotApplicableAmount,0.00)AS NotApplicableAmount,
			ISNULL(R1.PaidAmount,0) AS PaidAmount,
			ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R1.PaidAmount,0.00)AS PendingAmount,
			ISNULL(FA.Remark,'') AS Remark,
			FS.ReceiptBookId,
			FS.FeeName,
			FS.FeeCode,
			SA.OrgId,
			O.DisplayTitle AS OrgName,
			O.OrderIndex AS OrgOrderIndex,
			ISNULL(RBM.Title,'') AS ReceiptBookTitle,
			ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
			SA.DepartmentId,
			SA.DepartmentName,
			SA.ExemptionTypeId,
			ISNULL(ETM.Title,'') AS ExemptionType,
			FHM.Id AS FeeHeadId,
			FHM.Title AS FeeHeadName,
			FHM.OrderIndex AS FeeHeadOrderIndex,
			@rFeeGroupId As FeeGroup,
			SA.OrgGroupBatchId AS BatchId,
			SA.BatchName AS BatchName,
			ISNULL(R2.TotalReceiptAmount,0.00) AS CancelAmount
	  FROM 
			sStudent.vStudentAcademic SA
			INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA.StudentId
			INNER JOIN 
			(
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.IsOptional,0)AS IsOptional,
					ISNULL(FS1.IsVariable,0)AS IsVariable,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
					ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
					FS1.BatchId,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					SA1.AcademicId,
					FM.Title AS FeeName,
					FM.Code AS FeeCode,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0))
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				WHERE 
					((FS1.ClassId=@rClassId) OR (@rClassId=0))
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
					AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
					AND (FS1.IsOptional=0)
					AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
					AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
					AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
					AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
					AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
					UNION ALL
					
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.IsOptional,0)AS IsOptional,
					ISNULL(FS1.IsVariable,0)AS IsVariable,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
					ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
					FS1.BatchId,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					SA1.AcademicId,
					FM.Title AS FeeName,
					FM.Code As FeeCode,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1
			INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id 
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND FS1.BatchId = SA1.BatchId
			AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) 
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
			WHERE
				((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=1)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0)
			) FS ON FS.AcademicId=SA.AcademicId
			LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
			LEFT JOIN
			(
				SELECT 
						ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId,ISNULL(R.TotalReceiptAmount,0)AS TotalReceiptAmount
				FROM
						sFee.tReceipt R 
					INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
					INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
					INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
					INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId 
					INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA1.StudentId
					AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (SA1.ClassId=@rClassId OR @rClassId=0) 
					AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
				WHERE		
					(R.SourceTypeId = 2001)
					AND (R.IsObsolete = 0) 
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (SA1.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId=0)
					AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
					AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
					AND (R.ReceiptDate <= @rUptoDate)
					AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
					AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
					AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0)
					AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
					--AND ((tSA.LeftDate > @rUptoDate) OR (tSA.LeftDate Is null))
					AND (tSA.AdmissionDate <= @rUptoDate)
						GROUP BY FeeSetupId,R.SourceId,R.TotalReceiptAmount
			
			) R1 ON R1.FeeSetupId = FS.Id AND SA.AcademicId = R1.SourceId
			LEFT JOIN
			(
				SELECT 
						ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId,ISNULL(R.TotalReceiptAmount,0)AS TotalReceiptAmount
				FROM
						sFee.tReceipt R 
					INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
					INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
					INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
					INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId 
					INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA1.StudentId
					AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (SA1.ClassId=@rClassId OR @rClassId=0) 
					AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
				WHERE		
					(R.SourceTypeId = 2001)
					AND (R.IsObsolete = 1) 
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (SA1.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId=0)
					AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
					AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
					AND (R.ReceiptDate <= @rUptoDate)
					AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
					AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
					AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0)
					AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
					--AND ((tSA.LeftDate > @rUptoDate) OR (tSA.LeftDate Is null))
					AND (tSA.AdmissionDate <= @rUptoDate)
						GROUP BY FeeSetupId,R.SourceId,R.TotalReceiptAmount
			
			) R2 ON R2.FeeSetupId = FS.Id AND SA.AcademicId = R2.SourceId
			 INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
			 INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
			 INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FS.FeeHeadId	
			 LEFT JOIN sFee.tExemptionTypeMaster ETM ON ETM.Id = SA.ExemptionTypeId
			 LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
			 LEFT JOIN
			(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
			INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
			INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
			ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
			WHERE	
			((@rIsExemption = 0 AND  1 = 1) OR (@rIsExemption = 1  AND  ISNULL(FA.DiscountAmount,0) > 0))
			AND	((SA.BatchId=@rBatchId) OR (@rBatchId=0))   
			AND	((SA.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))   
			AND (SA.StatusId=@rStatusId OR @rStatusId=0)
			--AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
			AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
			AND ((SA.Code=@rCode) OR (@rCode=''))
			AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))		
			AND ((SA.ExemptionTypeId=@rExemptionTypeId) OR (@rExemptionTypeId=0))		
			AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
			AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			 AND (
					 (@rFilterId = 0) -- All
					 OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel
					 OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport
					 OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))
					 )	
		AND (O.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=0)
		AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
		--AND ((tSA.LeftDate > @rUptoDate) OR (tSA.LeftDate Is null))
		AND (tSA.AdmissionDate <= @rUptoDate)
		 AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))  	
		Order by SA.RollNo 
	END
	ELSE IF(@rReportId=30825)
	BEGIN
		SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			@rIsDetail AS IsDetail,
			@rIsFilter As IsFilter,
			@rIsHeader As IsHeader, 
			@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
			SA.AcademicId,
			SA.RollNo,
			SA.Name,
			SA.Code,
			SA.ClassId,
			SA.DivisionId,
			SA.ClassName,
			SA.DivisionName,
			SA.DivisionOrder AS DivisionOrderIndex,
			SA.ClassOrderIndex AS ClassOrderIndex,
			SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
			FS.Id AS FeeSetupId,
			ISNULL(FS.IsVariable,0)AS IsVariable,
			ISNULL(FS.Amount,0)AS Amount,
			ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
			ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
			ISNULL(FA.VariableAmount,0.00)AS FAAmount,
			ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
			ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
			ISNULL(FA.NotApplicableAmount,0.00)AS NotApplicableAmount,
			ISNULL(R.PaidAmount,0) AS PaidAmount,
			ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)AS PendingAmount,
			ISNULL(FA.Remark,'') AS Remark,
			FS.ReceiptBookId,
			FS.FeeName,
			FS.FeeCode,
			SA.OrgId,
			O.DisplayTitle AS OrgName,
			O.OrderIndex AS OrgOrderIndex,
			ISNULL(RBM.Title,'') AS ReceiptBookTitle,
			ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
			SA.DepartmentId,
			SA.DepartmentName,
			SA.ExemptionTypeId,
			ISNULL(ETM.Title,'') AS ExemptionType,
			FHM.Id AS FeeHeadId,
			FHM.Title AS FeeHeadName,
			FHM.OrderIndex AS FeeHeadOrderIndex,
			@rFeeGroupId As FeeGroup,
			SA.OrgGroupBatchId AS BatchId,
			SA.BatchName AS BatchName,
			0.00 AS CancelAmount,
			0.00 AS Discount
	  FROM 
			sStudent.vStudentAcademic SA
			INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA.StudentId
			INNER JOIN 
			(
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.IsOptional,0)AS IsOptional,
					ISNULL(FS1.IsVariable,0)AS IsVariable,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
					ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
					FS1.BatchId,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					SA1.AcademicId,
					FM.Title AS FeeName,
					FM.Code AS FeeCode,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0))
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				WHERE 
					((FS1.ClassId=@rClassId) OR (@rClassId=0))
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
					AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
					AND (FS1.IsOptional=0)
					AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
					AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
					AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
					AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
					AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
					UNION ALL
					
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.IsOptional,0)AS IsOptional,
					ISNULL(FS1.IsVariable,0)AS IsVariable,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
					ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
					FS1.BatchId,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					SA1.AcademicId,
					FM.Title AS FeeName,
					FM.Code As FeeCode,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1
			INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id 
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND FS1.BatchId = SA1.BatchId
			AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) 
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
			WHERE
				((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=1)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0)
			) FS ON FS.AcademicId=SA.AcademicId
			LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
			LEFT JOIN
			(
				SELECT 
						ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
				FROM
						sFee.tReceipt R 
					INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
					INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
					INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
					INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId 
					INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA1.StudentId
					AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (SA1.ClassId=@rClassId OR @rClassId=0) 
					AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
				WHERE		
					(R.SourceTypeId = 2001)
					AND (R.IsObsolete = 0) 
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (SA1.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId=0)
					AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
					AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
					AND (R.ReceiptDate <= @rUptoDate)
					AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
					AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
					AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0)
					AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
					--AND ((tSA.LeftDate > @rUptoDate) OR (tSA.LeftDate Is null))
					--AND (tSA.AdmissionDate <= @rUptoDate)
					AND ((tSA.LeftDate > @rUptoDate) OR (tSA.LeftDate Is null AND SA1.StatusId = 1))
						GROUP BY FeeSetupId,R.SourceId
			
			) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
			 INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
			 INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
			 INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FS.FeeHeadId	
			 LEFT JOIN sFee.tExemptionTypeMaster ETM ON ETM.Id = SA.ExemptionTypeId
			 LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
			 LEFT JOIN
			(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
			INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
			INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
			ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
			WHERE	
			((@rIsExemption = 0 AND  1 = 1) OR (@rIsExemption = 1  AND  ISNULL(FA.DiscountAmount,0) > 0))
			AND	((SA.BatchId=@rBatchId) OR (@rBatchId=0))   
			AND	((SA.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))   
			--AND (SA.StatusId=@rStatusId OR @rStatusId=0)
			--AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
			AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
			AND ((SA.Code=@rCode) OR (@rCode=''))
			AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))		
			AND ((SA.ExemptionTypeId=@rExemptionTypeId) OR (@rExemptionTypeId=0))		
			AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
			AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			 AND (
					 (@rFilterId = 0) -- All
					 OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel
					 OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport
					 OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))
					 )	
		AND (O.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=0)
		AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
		--AND ((tSA.LeftDate > @rUptoDate) OR (tSA.LeftDate Is null))
		--AND (tSA.AdmissionDate <= @rUptoDate)
		AND ((tSA.LeftDate > @rUptoDate) OR (tSA.LeftDate Is null AND SA.StatusId = 1))
		 --AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))  	
		Order by SA.RollNo 
	END
	--ELSE IF(@rReportId=30821)
	--BEGIN
	--	SELECT 
	--		@rBuilder1 AS Builder1,
	--		@rBuilder2 AS Builder2,
	--		@rIsDetail AS IsDetail,
	--		@rIsFilter As IsFilter,
	--		@rIsHeader As IsHeader, 
	--		@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
	--		SA.AcademicId,
	--		SA.RollNo,
	--		SA.Name,
	--		SA.Code,
	--		SA.ClassId,
	--		SA.DivisionId,
	--		SA.ClassName,
	--		SA.DivisionName,
	--		SA.DivisionOrder AS DivisionOrderIndex,
	--		SA.ClassOrderIndex AS ClassOrderIndex,
	--		SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
	--		FS.Id AS FeeSetupId,
	--		ISNULL(FS.IsVariable,0)AS IsVariable,
	--		ISNULL(FS.Amount,0)AS Amount,
	--		ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
	--		ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
	--		ISNULL(FA.VariableAmount,0.00)AS FAAmount,
	--		ISNULL(R.DiscountAmount,0.00)AS DiscountAmount,
	--		ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
	--		ISNULL(FA.NotApplicableAmount,0.00)AS NotApplicableAmount,
	--		ISNULL(R.PaidAmount,0) AS PaidAmount,
	--		ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)AS PendingAmount,
	--		ISNULL(FA.Remark,'') AS Remark,
	--		FS.ReceiptBookId,
	--		FS.FeeName,
	--		FS.FeeCode,
	--		SA.OrgId,
	--		O.DisplayTitle AS OrgName,
	--		O.OrderIndex AS OrgOrderIndex,
	--		ISNULL(RBM.Title,'') AS ReceiptBookTitle,
	--		ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
	--		SA.DepartmentId,
	--		SA.DepartmentName,
	--		SA.ExemptionTypeId,
	--		ISNULL(ETM.Title,'') AS ExemptionType,
	--		FHM.Id AS FeeHeadId,
	--		FHM.Title AS FeeHeadName,
	--		FHM.OrderIndex AS FeeHeadOrderIndex,
	--		@rFeeGroupId As FeeGroup,
	--		SA.OrgGroupBatchId AS BatchId,
	--		SA.BatchName AS BatchName,
	--		0.00 AS CancelAmount,
	--		(Select ISNULL(SUM(R.DiscountAmount),0) FROM  sFee.tReceipt R Where R.SourceId=SA.AcademicId)AS Discount
	--  FROM 
	--		sStudent.vStudentAcademic SA
	--		INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA.StudentId
	--		INNER JOIN 
	--		(
	--			SELECT 
	--				FS1.FeeId,
	--				FS1.Id,
	--				ISNULL(FS1.IsOptional,0)AS IsOptional,
	--				ISNULL(FS1.IsVariable,0)AS IsVariable,
	--				ISNULL(FS1.Amount,0)AS Amount,
	--				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
	--				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
	--				FS1.BatchId,
	--				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
	--				SA1.AcademicId,
	--				FM.Title AS FeeName,
	--				FM.Code AS FeeCode,
	--				FM.FeeHeadId
	--			FROM sFee.tFeeSetup FS1
	--			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
	--			AND ((SA1.ClassId=@rClassId) OR (@rClassId=0))
	--			AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
	--			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
	--			WHERE 
	--				((FS1.ClassId=@rClassId) OR (@rClassId=0))
	--				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
	--				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
	--				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
	--				AND (FS1.IsOptional=0)
	--				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
	--				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
	--				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
	--				AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	--				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
	--				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
	--				AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
	--				UNION ALL
					
	--			SELECT 
	--				FS1.FeeId,
	--				FS1.Id,
	--				ISNULL(FS1.IsOptional,0)AS IsOptional,
	--				ISNULL(FS1.IsVariable,0)AS IsVariable,
	--				ISNULL(FS1.Amount,0)AS Amount,
	--				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
	--				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
	--				FS1.BatchId,
	--				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
	--				SA1.AcademicId,
	--				FM.Title AS FeeName,
	--				FM.Code As FeeCode,
	--				FM.FeeHeadId
	--			FROM sFee.tFeeSetup FS1
	--		INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id 
	--		INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
	--		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND FS1.BatchId = SA1.BatchId
	--		AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
	--			AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) 
	--			AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
	--			AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
	--		WHERE
	--			((FS1.ClassId=@rClassId) OR (@rClassId=0))
	--			AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
	--			AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
	--			AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
	--			AND (FS1.IsOptional=1)
	--			AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
	--			AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
	--			AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
	--			AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	--			AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
	--			AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
	--			AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0)
	--		) FS ON FS.AcademicId=SA.AcademicId
	--		LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
	--		LEFT JOIN
	--		(
	--			SELECT 
	--					ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId,R.DiscountAmount
	--			FROM
	--					sFee.tReceipt R 
	--				INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
	--				INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
	--				INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
	--				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId 
	--				INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA1.StudentId
	--				AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
	--				AND (SA1.ClassId=@rClassId OR @rClassId=0) 
	--				AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
	--			WHERE		
	--				(R.SourceTypeId = 2001)
	--				AND (R.IsObsolete = 0) 
	--				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
	--				AND (SA1.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId=0)
	--				AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
	--				AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
	--				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
	--				AND (R.ReceiptDate <= @rUptoDate)
	--				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
	--				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
	--				AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0)
	--				AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
	--				--AND ((tSA.LeftDate > @rUptoDate) OR (tSA.LeftDate Is null))
	--				AND (tSA.AdmissionDate <= @rUptoDate)
	--					GROUP BY FeeSetupId,R.SourceId,R.DiscountAmount
			
	--		) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
	--		 INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
	--		 INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
	--		 INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FS.FeeHeadId	
	--		 LEFT JOIN sFee.tExemptionTypeMaster ETM ON ETM.Id = SA.ExemptionTypeId
	--		 LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
	--		 LEFT JOIN
	--		(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
	--		INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
	--		INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
	--		ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
	--		WHERE	
	--		((@rIsExemption = 0 AND  1 = 1) OR (@rIsExemption = 1  AND  ISNULL(FA.DiscountAmount,0) > 0))
	--		AND	((SA.BatchId=@rBatchId) OR (@rBatchId=0))   
	--		AND	((SA.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))   
	--		AND (SA.StatusId=@rStatusId OR @rStatusId=0)
	--		--AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
	--		AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
	--		AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
	--		AND ((SA.Code=@rCode) OR (@rCode=''))
	--		AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))		
	--		AND ((SA.ExemptionTypeId=@rExemptionTypeId) OR (@rExemptionTypeId=0))		
	--		AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
	--		AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
	--		 AND (
	--				 (@rFilterId = 0) -- All
	--				 OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel
	--				 OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport
	--				 OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))
	--				 )	
	--	AND (O.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=0)
	--	AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
	--	--AND ((tSA.LeftDate > @rUptoDate) OR (tSA.LeftDate Is null))
	--	AND (tSA.AdmissionDate <= @rUptoDate)
	--	 AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))  	
	--	Order by SA.RollNo 
	--END
	ELSE
	BEGIN
		SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			@rIsDetail AS IsDetail,
			@rIsFilter As IsFilter,
			@rIsHeader As IsHeader, 
			@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
			SA.AcademicId,
			SA.RollNo,
			SA.Name,
			SA.Code,
			SA.ClassId,
			SA.DivisionId,
			SA.ClassName,
			SA.DivisionName,
			SA.StatusId,
			SA.DivisionOrder AS DivisionOrderIndex,
			SA.ClassOrderIndex AS ClassOrderIndex,
			SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
			FS.Id AS FeeSetupId,
			ISNULL(FS.IsVariable,0)AS IsVariable,
			ISNULL(FS.Amount,0)AS Amount,
			ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
			ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
			ISNULL(FA.VariableAmount,0.00)AS FAAmount,
			ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
			ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
			ISNULL(FA.NotApplicableAmount,0.00)AS NotApplicableAmount,
			ISNULL(R.PaidAmount,0) AS PaidAmount,
			ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)AS PendingAmount,
			ISNULL(FA.Remark,'') AS Remark,
			--CASE WHEN ISNULL(FA.Remark,'') ='' THEN ''	ELSE [sFee].[fFeeAllocationRemarkGet](FA.SourceId,2) END as RemarkWithComma,
			'' RemarkWithComma,
			--CASE WHEN ISNULL(FA.DiscountRemark,'') ='' THEN ''	ELSE [sFee].[fFeeAllocationRemarkGet](FA.SourceId,1) END as ExampltedRemark,

			CASE WHEN ISNULL(DiscountRemark,'') ='' THEN ''
			ELSE
			(STUFF((SELECT  ','+DiscountRemark	FROM sFee.tFeeAllocation WHERE SourceId = FA.SourceId	
			ORDER BY DiscountRemark	FOR XML PATH('')), 1, 1,NULL)) END as ExampltedRemark,

			--CASE WHEN ISNULL(FA.DiscountRemark,'') ='' THEN ''	ELSE [sFee].[fFeeAllocationRemarkGet](FA.SourceId) END  as ExampltedRemark,

			--CASE WHEN ISNULL(FA.AdditionalRemark,'') ='' THEN ''	ELSE [sFee].[fFeeAllocationRemarkGet](FA.SourceId,3) END as AdditionalRemark,
			''  AdditionalRemark,
			--CASE WHEN ISNULL(FA.NotApplicableRemark,'') ='' THEN ''	ELSE [sFee].[fFeeAllocationRemarkGet](FA.SourceId,4) END as NotApplicableRemark,
			'' NotApplicableRemark,
			FS.ReceiptBookId,
			FS.FeeName,
			--FS.FeeCode,
			SA.OrgId,
			O.DisplayTitle AS OrgName,
			O.OrderIndex AS OrgOrderIndex,
			ISNULL(RBM.Title,'') AS ReceiptBookTitle,
			ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
			SA.DepartmentId,
			SA.DepartmentName,
			SA.ExemptionTypeId,
			ISNULL(ETM.Title,'') AS ExemptionType,
			FHM.Id AS FeeHeadId,
			FHM.Title AS FeeHeadName,
			FHM.OrderIndex AS FeeHeadOrderIndex,
			@rFeeGroupId As FeeGroup,
			SA.OrgGroupBatchId AS BatchId,
			SA.BatchName AS BatchName,
			0.00 AS CancelAmount
	  FROM 
			sStudent.vStudentAcademic SA
			INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA.StudentId
			INNER JOIN 
			(
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.IsOptional,0)AS IsOptional,
					ISNULL(FS1.IsVariable,0)AS IsVariable,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
					ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
					FS1.BatchId,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					SA1.AcademicId,
					FM.Title AS FeeName,
					--FM.Code AS FeeCode,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0))
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				WHERE 
					((FS1.ClassId=@rClassId) OR (@rClassId=0))
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
					AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
					AND (FS1.IsOptional=0)
					AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
					AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
					AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
					AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
					AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
					UNION ALL
					
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.IsOptional,0)AS IsOptional,
					ISNULL(FS1.IsVariable,0)AS IsVariable,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
					ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
					FS1.BatchId,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					SA1.AcademicId,
					FM.Title AS FeeName,
					--FM.Code AS FeeCode,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1
			INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id 
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND FS1.BatchId = SA1.BatchId
			AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) 
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
			WHERE
				((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=1)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0)
			) FS ON FS.AcademicId=SA.AcademicId
			LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
			LEFT JOIN
			(
				SELECT 
						ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
				FROM
						sFee.tReceipt R 
					INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
					INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
					INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
					INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId 
					AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (SA1.ClassId=@rClassId OR @rClassId=0) 
					AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
				WHERE		
					(R.SourceTypeId = 2001)
					AND (R.IsObsolete = 0) 
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (SA1.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId=0)
					AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
					AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
					AND (R.ReceiptDate <= @rUptoDate)
					AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
					AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
					AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0)
					AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
						GROUP BY FeeSetupId,R.SourceId
			
			) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
			 INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
			 INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
			 INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FS.FeeHeadId	
			 LEFT JOIN sFee.tExemptionTypeMaster ETM ON ETM.Id = SA.ExemptionTypeId
			 LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
			 LEFT JOIN
			(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
			INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
			INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
			ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
			WHERE	
			((@rIsExemption = 0 AND  1=1) OR (@rIsExemption = 1  AND  ISNULL(FA.DiscountAmount,0) > 0))
			AND	((SA.BatchId=@rBatchId) OR (@rBatchId=0))   
			AND	((SA.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))   
			AND (SA.StatusId=@rStatusId OR @rStatusId=0)
			--AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
			AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
			AND ((SA.Code=@rCode) OR (@rCode=''))
			AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))		
			AND ((SA.ExemptionTypeId=@rExemptionTypeId) OR (@rExemptionTypeId=0))		
			AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
			AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			 AND (
					 (@rFilterId = 0) -- All
					 OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel
					 OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport
					 OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))
					 )	
		AND (O.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=0)
		AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
		 AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))  	
		Order by SA.RollNo
	END
	
	
	
END
GO
PRINT N'Altering [sFee].[pStudentLedgerGet]...';


GO
 
ALTER PROCEDURE [sFee].[pStudentLedgerGet]
	
	 @rCode  nvarchar(20)='',
	 @rSUId nvarchar(20)='',
	 @rDepositHeadId int,
	 @rOrgId int,
	 @rBatchId int=0,
	 @rAcademicId bigint=0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON 
BEGIN 
 SELECT A.DepositDate ,
        A.Credit,
        A.Debit,
		A.ExpenseType,
		A.TransactionType,
		(CASE WHEN A.Debit = 0 THEN 'Credited' ELSE 'Debited' END)AS PayType
         FROM(
			SELECT 
			DA.DepositDate AS DepositDate,
			ISnull (DA.Amount,0) AS Credit,
		    0 AS Debit,
			'' AS ExpenseType,
			'Deposit Add' AS TransactionType
			FROM sStudent.vStudentAcademic  VA
			INNER JOIN sFee.tDepositAdd DA  ON VA.AcademicId = DA.AcademicId 
			Where 
			((VA.Code = @rCode) OR (ISNULL(@rCode,'') = ''))
			AND ((VA.SUId like @rSUId) OR (ISNULL(@rSUId,'')=''))
			AND (DA.DepositHeadId = @rDepositHeadId) 
			AND ((VA.OrgId = @rOrgId) OR (ISNULL(@rOrgId,0) = 0)) 
			AND VA.StudentId= @rAcademicId
			---AND VA.BatchId = @rBatchId
			UNION ALL 
			SELECT 
			DAJ.AdjustmentDate As DepositDate,
			0  AS Credit,
			ISnull (DAJ.Amount,0)  AS Debit,
			ISNULL(ETM.Title,'')AS ExpenseType,
			('Expense'+' '+ISNULL(ETM.Title,'')) AS TransactionType
			FROM sStudent.vStudentAcademic  VA
			  INNER JOIN sFee.tDepositAdjustment DAJ ON DAJ.AcademicId = VA.AcademicId
			  INNER JOIN sFee.tFeeDepositExpenseTypeMaster ETM ON ETM.Id =DAJ.FeeDepositExpenseTypeId
			Where 
			((VA.Code = @rCode) OR (ISNULL(@rCode,'') = ''))
			AND ((VA.SUId like @rSUId) OR (ISNULL(@rSUId,'')=''))
			AND (DAJ.DepositHeadId = @rDepositHeadId) 
			AND ((VA.OrgId = @rOrgId) OR (ISNULL(@rOrgId,0) = 0)) 
			--AND VA.BatchId = @rBatchId
			AND VA.StudentId = @rAcademicId
			UNION ALL 
			SELECT 
			DR.RefundDate As DepositDate,
			0  AS Credit,
			ISnull (DR.RefundAmount,0)  AS Debit,
			'' AS ExpenseType,
			'Deposit Refund' AS TransactionType
			FROM sStudent.vStudentAcademic  VA
			  INNER JOIN sFee.tDepositRefund DR ON DR.AcademicId = VA.AcademicId
			Where 
			((VA.Code = @rCode) OR (ISNULL(@rCode,'') = ''))
			AND ((VA.SUId like @rSUId) OR (ISNULL(@rSUId,'')=''))
			AND (DR.DepositHeadId = @rDepositHeadId) 
			AND ((VA.OrgId = @rOrgId) OR (ISNULL(@rOrgId,0) = 0)) 
		   -- AND VA.BatchId = @rBatchId
		    AND VA.StudentId = @rAcademicId
			)A 
			Order BY A.DepositDate
			
END
GO
PRINT N'Altering [sHrm].[pEmployeeDataModify]...';


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

--BEGIN TRY
--BEGIN TRANSACTION

EXEC sp_xml_preparedocument @loDoc OUTPUT,@rXML
BEGIN
	
	IF(@rSubCategoryField = 'Gender' OR @rSubCategoryField = 'Religion' OR @rSubCategoryField = 'BloodGroup'
	OR @rSubCategoryField = 'MaritalStatus' OR @rSubCategoryField = 'OrganizationDepartment' OR @rSubCategoryField = 'EmployeeType' OR @rSubCategoryField = 'EmployeeBusinessHead'
			OR @rSubCategoryField = 'EmployeeGroup' OR @rSubCategoryField = 'EmployeeGrade' OR @rSubCategoryField = 'Relationship' OR  @rSubCategoryField = 'EmployeeDesignation'
			OR  @rSubCategoryField = 'Payroll' OR  @rSubCategoryField = 'PayrollGroup'  OR  @rSubCategoryField = 'OrgGroupDepartment' OR  @rSubCategoryField = 'EmployeeManager' 
			)
	BEGIN
		SET @rSubCategoryField = @rSubCategoryField + 'Id'
	END
	ELSE IF (@rSubCategoryField = 'CasteCategory' )
		BEGIN
			SET @rSubCategoryField = Replace(@rSubCategoryField,'Caste','Cast')+'Id'
		END
	ELSE IF(@rSubCategoryField = 'NotEmployee')
		 BEGIN
		 SET @rSubCategoryField = Replace(@rSubCategoryField,'NotEmployee','IsOtherUser')
		 END
		
	IF OBJECT_ID('ListofData') IS NOT NULL	
	BEGIN 
		DROP TABLE ListofData
	END	
	
	CREATE TABLE ListofData(Id bigint,EmployeeId bigint,SubCategory nvarchar(150),UpdatedUserId bigint,IsExist bit);
	
	IF(@rCategoryId= 1)
		BEGIN
		insert into ListofData
		select 0,E.EmployeeId,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),E.UpdatedUserId,0
		from
		(
				SELECT EmployeeId,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Employees/Employees', 2)
				WITH (
						EmployeeId BIGINT, 
						SubCategory nvarchar(150),
						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,sSetup.fPortalXMLTagsReplaceReverse(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,sSetup.fPortalXMLTagsReplaceReverse(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 	

		IF(@rSubCategoryField = 'EmployeeManagerId' )
			BEGIN

		set @sql='UPDATE sHrm.tEmployeeJobDetail set '+@rSubCategoryField+' = (SELECT EmployeeId FROM sHrm.vExtEmployeeMaster WHERE CODE=LD.SubCategory AND ISNULL(IsOtherUser,0) = 0 ),
				  UpdatedUserId=LD.UpdatedUserId,
				  UpdatedDateTime=sCommon.fGetDate()  
				  from sHrm.tEmployeeJobDetail EJ	
				  INNER JOIN ListofData LD ON LD.EmployeeId=EJ.EmployeeId'
				  Exec sp_executesql @sql
		END

		ELSE
		BEGIN
	
		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
		END
		IF(@rSubCategoryField = 'DateOfJoining' )
		BEGIN
		SET @sql='UPDATE sHrm.tEmployeeJobDetail SET '+@rSubCategoryField+' = null WHERE DateOfJoining=''1900-01-01'''
			Exec sp_executesql @sql
		END
		
		IF(@rSubCategoryField = 'DateOfleaving' )
		BEGIN
		SET @sql='UPDATE sHrm.tEmployeeJobDetail SET '+@rSubCategoryField+' = null WHERE DateOfleaving=''1900-01-01'''
			Exec sp_executesql @sql
		END		
		IF(@rSubCategoryField = 'PermanentDate' )
		BEGIN
		SET @sql='UPDATE sHrm.tEmployeeJobDetail SET '+@rSubCategoryField+' = null WHERE PermanentDate=''1900-01-01'''
			Exec sp_executesql @sql
		END	
		IF(@rSubCategoryField = 'ProbationUptoDate' )
		BEGIN

		SET @sql='UPDATE sHrm.tEmployeeJobDetail SET '+@rSubCategoryField+' = null WHERE ProbationUptoDate=''1900-01-01'''
			Exec sp_executesql @sql
		END	
		IF(@rSubCategoryField = 'AhdocUptoDate' )
		BEGIN
		SET @sql='UPDATE sHrm.tEmployeeJobDetail SET '+@rSubCategoryField+' = null WHERE AhdocUptoDate=''1900-01-01'''
			Exec sp_executesql @sql
		END
		IF(@rSubCategoryField = 'DateOfResignation' )
		BEGIN
		SET @sql='UPDATE sHrm.tEmployeeJobDetail SET '+@rSubCategoryField+' = null WHERE DateOfResignation=''1900-01-01'''
			Exec sp_executesql @sql
		END		
		Drop Table ListofData
			 SELECT 1 AS StatusId
	    END	
  Else IF(@rCategoryId= 4)
	BEGIN
		
		
		IF(@rSubCategoryField = 'CustomTag')
		BEGIN
		insert into ListofData
		select 0,E.EmployeeId,sSetup.fPortalXMLTagsReplaceReverse(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 WHERE  ISNULL(IsOtherUser,0) = 0 ) 

			 
			DELETE FROM sHrm.tEmployeeCustomTag WHERE EmployeeId In (SELECT EmployeeId FROM ListofData WHERE IsExist=0)
			set @sql = '
				        INSERT INTO sHrm.tEmployeeCustomTag (EmployeeId,CustomTagId)
						SELECT
							LD.EmployeeId,
							CTM.Id
						FROM sHrm.tCustomTagMaster CTM INNER JOIN ListofData LD ON CTM.Title = LD.SubCategory 
						INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = LD.EmployeeId 
						INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgID 
						INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OM.OrgGroupId  
						WHERE IsExist = 0 AND CTM.OrgGroupId = OGM.Id'
			 
		END
		ELSE
		BEGIN
		insert into ListofData
		select 0,E.EmployeeId,sSetup.fPortalXMLTagsReplaceReverse(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 WHERE  ISNULL(IsOtherUser,0) = 0 ) 
		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 AND ISNULL(HEM.IsOtherUser,0) = 0 ' 
		END
		Print @sql
		Exec sp_executesql @sql
		Drop Table ListofData
			SELECT 1 AS StatusId
	    END
	    
	    Else IF(@rCategoryId= 5)
		BEGIN
		insert into ListofData
		select 0,E.EmployeeId,sSetup.fPortalXMLTagsReplaceReverse(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.tEmployeeStatutoryAndOther) 
		
		set @sql='INSERT INTO sHrm.tEmployeeStatutoryAndOther 
					(EmployeeId,'+@rSubCategoryField+',IsVPFDeduction,UpdatedUserId,UpdatedDateTime)
					SELECT
						LD.EmployeeId,Ld.SubCategory,0,LD.UpdatedUserId,sCommon.fGetDate()
					FROM
						ListofData LD WHERE LD.IsExist=1'
		Exec sp_executesql @sql			
		
		
		IF(@rSubCategoryField = 'EPFJoinDate')
		BEGIN			
		    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
			set @sql='UPDATE sHrm.tEmployeeStatutoryAndOther SET '+@rSubCategoryField+' = NULL WHERE EPFJoinDate=''1900-01-01'''
			Exec sp_executesql @sql
		END
		ELSE IF(@rSubCategoryField = 'IncrementDate')
		BEGIN			
		    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
			set @sql='UPDATE sHrm.tEmployeeStatutoryAndOther SET '+@rSubCategoryField+' = NULL WHERE IncrementDate=''1900-01-01'''
			Exec sp_executesql @sql
		END
			ELSE IF(@rSubCategoryField = 'RetirementDate')
		BEGIN			
		    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
			set @sql='UPDATE sHrm.tEmployeeStatutoryAndOther SET '+@rSubCategoryField+' = NULL WHERE RetirementDate=''1900-01-01'''
			Exec sp_executesql @sql
		END
		ELSE
		BEGIN
			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
		END
		
		
		Drop Table ListofData
			 SELECT 1 AS StatusId
	    END	
	    
	    
END 
	--   COMMIT TRANSACTION
		
	--END TRY
	
	--BEGIN CATCH 
	--	ROLLBACK TRANSACTION
	--	Drop Table ListofData
	--	SELECT -1 AS Result
	--END CATCH

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


GO
 
ALTER PROCEDURE [sHrm].[pRptEmployeeProfileGet]
(

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

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


GO
 
ALTER PROCEDURE [sOp].[pPaymentTransactionAdd]
	
			@rId bigint=0,
			@rTransactionSourceTypeId smallint,
			@rTransactionSourceId bigint,
			@rPayerSourceTypeId smallint,
			@rPayerSourceId bigint,
			@rPayAmount decimal(12,2),
			@rTransactionStatusId int,
			@rFunctionalityId smallint,
			@rOrgId int,
			@rOSTypeId smallint=0,
			@rPaymentGatewayId smallint = 0
			

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
		BEGIN TRY
		BEGIN TRANSACTION	
	 
	DECLARE @lNextNumber BIGINT     
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sOp.tPaymentTransaction', 0, 1, 1,@outNextNumber = @lNextNumber output

		INSERT INTO sOp.tPaymentTransaction
			(
				Id,
				TransactionSourceTypeId,
				TransactionSourceId,
				PayerSourceTypeId,
				PayerSourceId,
				PayDateTime,
				PayAmount,
				TransactionStatusId,
				FunctionalityId,
				OSTypeId,
				PaymentGatewayId
			)
		VALUES
			(
				@lNextNumber,
				@rTransactionSourceTypeId,
				@rTransactionSourceId,
				@rPayerSourceTypeId,
				@rPayerSourceId,
				sCommon.fGetDate(),
				@rPayAmount,
				@rTransactionStatusId,
				@rFunctionalityId,
				@rOSTypeId,
				@rPaymentGatewayId
			)

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


GO
 
ALTER PROCEDURE [sOp].[pPaymentTransactionGet]
	@rId bigint = 0,
	@rFromDate date,
	@rToDate date,
	@rTransactionStatusId int,
	@rFunctionalityId smallint,
	@rFirstName nvarchar(50)='',
	@rOrgGroupId smallint=0,
	@rOrgId int=0,
	@rBatchId int=0,
	@rReceiptBookId int=0,
	@rOSTypeId int=0,
	@rFormNo int=0,
	@rReferenceNo bigint=0
AS
SET NOCOUNT ON

BEGIN
	IF(@rFunctionalityId=0)
	BEGIN
	
	SELECT * FROM 
	(
	SELECT  
		TSM.Title As TransactionStatus,
		FM.Title AS Functionality,
		PT.PayAmount,
		PT.PayDateTime,
		CONVERT(nvarchar(20),SM.Code) AS Code,
		SM.FirstName + ' ' + SM.LastName AS Name,
		CM.DisplayTitle +' - '+ DM.DisplayTitle AS ClassName,
		TSM.ColorCode,
		PT.TransactionSourceTypeId,
		PT.TransactionSourceId,
		PT.BankName,
		PT.Id AS PaymentTransactionId,
		PT.TransactionStatusId,
		ISNULL(PT.MerchantTransactionId,0) AS MerchantTransactionId,
		ISNULL(PT.FunctionalityId,0) AS FunctionalityId,
		O.Title AS ReceiptBook,
		ISNULL(OS.Title,'') AS OSType,
		ISNULL(PT.BankTransactionId,0) AS BankTransactionId,
		ISNULL(PT.PaymentGatewayId,0) AS PaymentGatewayId
		
	FROM 
		sOp.tPaymentTransaction PT     
		LEFT JOIN sAlert.tOSType OS ON OS.Id = PT.OSTypeId                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    
		INNER JOIN sOp.tTransactionStatusMaster TSM ON TSM.ID = PT.TransactionStatusId
		INNER JOIN sOp.tFunctionalityMaster FM ON FM.Id = PT.FunctionalityId
		INNER JOIN sStudent.tAcademic A ON A.Id = PT.PayerSourceId
		INNER JOIN sStudent.tStudentMaster SM ON SM.Id = A.StudentId
		INNER JOIN sSetup.tClassMaster CM ON CM.Id = A.ClassId
		INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = A.DivisionId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = CM.OrgId
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
		INNER JOIN 
		(
			SELECT OP.Id,RB.Title FROM sFee.tOnlineFee OP 
			INNER JOIN  sFee.tReceiptBookMaster RB ON RB.Id = OP.ReceiptBookId
			WHERE (RB.Id = @rReceiptBookId OR @rReceiptBookId=0)
		) O ON O.Id = PT.TransactionSourceId AND TransactionSourceTypeId = 2024
		
	WHERE 
		 ((PT.TransactionStatusId = @rTransactionStatusId) OR (@rTransactionStatusId=0))
		 AND (PT.FunctionalityId = 1)
		 AND ((PT.PayDateTime >=@rFromDate) OR (ISNULL(@rFromDate,'')=''))
		 AND ((PT.PayDateTime < DateAdd(Day,1,@rToDate)) OR (ISNULL(@rToDate,'')=''))
		 AND ((PT.PayerSourceId=@rId) OR (@rId=0))
		 --AND ((SM.FirstName like '%'+ @rFirstName + '%') OR (@rFirstName=''))
		 AND OM.OrgGroupId = @rOrgGroupId
		 AND OM.Id = @rOrgId
		 AND BM.Id = @rBatchId
		 AND (ISNULL(PT.OSTypeId,0) = @rOSTypeId OR @rOSTypeId=0)
		 AND (PT.Id= @rReferenceNo OR @rReferenceNo=0)
	UNION ALL
	
	SELECT  
		TSM.Title As TransactionStatus,
		FM.Title AS Functionality,
		PT.PayAmount,
		PT.PayDateTime,
		CONVERT(nvarchar(20),AF.FormNo) AS Code,
		AF.FirstName + ' ' + AF.LastName AS Name,
		CM.DisplayTitle AS ClassName,
		TSM.ColorCode,
		PT.TransactionSourceTypeId,
		PT.TransactionSourceId,
		PT.BankName,
		PT.Id AS PaymentTransactionId,
		PT.TransactionStatusId,
		ISNULL(PT.MerchantTransactionId,0) AS MerchantTransactionId,
		ISNULL(PT.FunctionalityId,0) AS FunctionalityId,
		RBM.Title AS ReceiptBook,
		ISNULL(OS.Title,'') AS OSType,
		ISNULL(PT.BankTransactionId,0) AS BankTransactionId,
		ISNULL(PT.PaymentGatewayId,0) AS PaymentGatewayId
	
	FROM 
		sOp.tPaymentTransaction PT                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             
		LEFT JOIN sAlert.tOSType OS ON OS.Id = PT.OSTypeId
		INNER JOIN sOp.tTransactionStatusMaster TSM ON TSM.ID = PT.TransactionStatusId
		INNER JOIN sOp.tFunctionalityMaster FM ON FM.Id = PT.FunctionalityId
		INNER JOIN sAdmission.tAdmissionForm AF ON AF.Id = PT.PayerSourceId
		INNER JOIN sAdmission.tAdmissionCriteria AC ON AC.BatchId=AF.BatchId AND AC.ClassId=AF.ForClassId 
		INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id = AC.ReceiptBookId AND (RBM.Id = @rReceiptBookId OR @rReceiptBookId=0)
		INNER JOIN sSetup.tClassMaster CM ON CM.Id = AF.ForClassId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = CM.OrgId
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AF.BatchId
		 
	WHERE 
		 ((PT.TransactionStatusId = @rTransactionStatusId) OR (@rTransactionStatusId=0))
		 AND (PT.FunctionalityId = 2)
		 AND ((PT.PayDateTime >=@rFromDate) OR (ISNULL(@rFromDate,'')=''))
		 AND ((PT.PayDateTime < DateAdd(Day,1,@rToDate)) OR (ISNULL(@rToDate,'')=''))
		 AND ((PT.PayerSourceId=@rId) OR (@rId=0))
		 AND ((AF.FormNo = @rFormNo) OR (ISNULL(@rFormNo,0)=0))
		 --AND ((AF.FirstName like '%'+ @rFirstName + '%') OR (@rFirstName=''))
		 AND OM.OrgGroupId = @rOrgGroupId
		 AND OM.Id = @rOrgId
		 AND BM.Id = @rBatchId
		 AND (ISNULL(PT.OSTypeId,0) = @rOSTypeId OR @rOSTypeId=0)
		 AND (PT.Id= @rReferenceNo OR @rReferenceNo=0)
	) A
	ORDER BY PayDateTime DESC
	END	
	
	IF(@rFunctionalityId=1)
	BEGIN
	SELECT  
		TSM.Title As TransactionStatus,
		FM.Title AS Functionality,
		PT.PayAmount,
		PT.PayDateTime,
		CONVERT(nvarchar(20),SM.Code) AS Code,
		SM.FirstName + ' ' + SM.LastName AS Name,
		CM.DisplayTitle +' - '+ DM.DisplayTitle AS ClassName,
		TSM.ColorCode,
		PT.TransactionSourceTypeId,
		PT.TransactionSourceId,
		PT.BankName,
		PT.Id AS PaymentTransactionId,
		PT.TransactionStatusId,
		ISNULL(PT.MerchantTransactionId,0) AS MerchantTransactionId,
		ISNULL(PT.FunctionalityId,0) AS FunctionalityId,
		O.Title AS ReceiptBook,
		ISNULL(OS.Title,'') AS OSType,
		ISNULL(PT.BankTransactionId,0) AS BankTransactionId,
		ISNULL(PT.PaymentGatewayId,0) AS PaymentGatewayId
	
	FROM 
		sOp.tPaymentTransaction PT 
		LEFT JOIN sAlert.tOSType OS ON OS.Id = PT.OSTypeId                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            
		INNER JOIN sOp.tTransactionStatusMaster TSM ON TSM.ID = PT.TransactionStatusId
		INNER JOIN sOp.tFunctionalityMaster FM ON FM.Id = PT.FunctionalityId
		INNER JOIN sStudent.tAcademic A ON A.Id = PT.PayerSourceId
		INNER JOIN sStudent.tStudentMaster SM ON SM.Id = A.StudentId
		INNER JOIN sSetup.tClassMaster CM ON CM.Id = A.ClassId
		INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = A.DivisionId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = CM.OrgId
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
		INNER JOIN 
		(
			SELECT OP.Id,RB.Title FROM sFee.tOnlineFee OP 
			INNER JOIN  sFee.tReceiptBookMaster RB ON RB.Id = OP.ReceiptBookId
			WHERE (RB.Id = @rReceiptBookId OR @rReceiptBookId=0)
		) O ON O.Id = PT.TransactionSourceId AND TransactionSourceTypeId = 2024
	WHERE 
		 ((PT.TransactionStatusId = @rTransactionStatusId) OR (@rTransactionStatusId=0))
		 AND (PT.FunctionalityId = 1)
		 AND ((PT.PayDateTime >=@rFromDate) OR (ISNULL(@rFromDate,'')=''))
		 AND ((PT.PayDateTime < DateAdd(Day,1,@rToDate)) OR (ISNULL(@rToDate,'')=''))
		 AND ((PT.PayerSourceId=@rId) OR (@rId=0))
		 --AND ((SM.FirstName like '%'+ @rFirstName + '%') OR (@rFirstName=''))
		 AND OM.OrgGroupId = @rOrgGroupId
		 AND OM.Id = @rOrgId
		 AND BM.Id = @rBatchId
		 AND (ISNULL(PT.OSTypeId,0) = @rOSTypeId OR @rOSTypeId=0)
		 AND (PT.Id= @rReferenceNo OR @rReferenceNo=0)
		 ORDER BY PT.PayDateTime DESC
	END
	
	IF(@rFunctionalityId=2)
	BEGIN
		SELECT  
		TSM.Title As TransactionStatus,
		FM.Title AS Functionality,
		PT.PayAmount,
		PT.PayDateTime,
		CONVERT(nvarchar(20),AF.FormNo) AS Code,
		AF.FirstName + ' ' + AF.LastName AS Name,
		CM.DisplayTitle AS ClassName,
		TSM.ColorCode,
		PT.TransactionSourceTypeId,
		PT.TransactionSourceId,
		PT.BankName,
		PT.Id AS PaymentTransactionId,
		PT.TransactionStatusId,
		ISNULL(PT.MerchantTransactionId,0) AS MerchantTransactionId,
		ISNULL(PT.FunctionalityId,0) AS FunctionalityId,
		RBM.Title AS ReceiptBook,
		ISNULL(OS.Title,'') AS OSType,
		ISNULL(PT.BankTransactionId,0) AS BankTransactionId,
		ISNULL(PT.PaymentGatewayId,0) AS PaymentGatewayId
	
	FROM 
		sOp.tPaymentTransaction PT           
		LEFT JOIN sAlert.tOSType OS ON OS.Id = PT.OSTypeId                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  
		INNER JOIN sOp.tTransactionStatusMaster TSM ON TSM.ID = PT.TransactionStatusId
		INNER JOIN sOp.tFunctionalityMaster FM ON FM.Id = PT.FunctionalityId
		INNER JOIN sAdmission.tAdmissionForm AF ON AF.Id = PT.PayerSourceId
		INNER JOIN sAdmission.tAdmissionCriteria AC ON AC.BatchId=AF.BatchId AND AC.ClassId=AF.ForClassId 
		INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id = AC.ReceiptBookId AND (RBM.Id = @rReceiptBookId OR @rReceiptBookId=0)
		INNER JOIN sSetup.tClassMaster CM ON CM.Id = AF.ForClassId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = CM.OrgId
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AF.BatchId
	WHERE 
		 ((PT.TransactionStatusId = @rTransactionStatusId) OR (@rTransactionStatusId=0))
		 AND (PT.FunctionalityId = 2)
		 AND ((PT.PayDateTime >=@rFromDate) OR (ISNULL(@rFromDate,'')=''))
		 AND ((PT.PayDateTime < DateAdd(Day,1,@rToDate)) OR (ISNULL(@rToDate,'')=''))
		 AND ((PT.PayerSourceId=@rId) OR (@rId=0))
		 AND ((AF.FormNo = @rFormNo) OR (ISNULL(@rFormNo,0)=0))
		 --AND ((AF.FirstName like '%'+ @rFirstName + '%') OR (@rFirstName=''))
		 AND OM.OrgGroupId = @rOrgGroupId
		 AND OM.Id = @rOrgId
		 AND BM.Id = @rBatchId
		 AND (ISNULL(PT.OSTypeId,0) = @rOSTypeId OR @rOSTypeId=0)
		 AND (PT.Id= @rReferenceNo OR @rReferenceNo=0)
		 ORDER BY PT.PayDateTime DESC
	END
END
GO
PRINT N'Altering [sPayroll].[pPayrollCustomSearchGet]...';


GO
-- exec [sPayroll].[pPayrollCustomSearchGet]
-- drop proc [sPayroll].[pPayrollCustomSearchGet]
ALTER PROCEDURE [sPayroll].[pPayrollCustomSearchGet] 
	@rOrgId smallint,
	@rOrderBy nvarchar(max) = 'Code',
	@rCode [nvarchar](20) = '',
	@rFirstName [nvarchar](50) = '',	
	@rLastName[nvarchar](50) = '',
	@rEmployeeTypeId[nvarchar](50) = '',
	@rStatusId[nvarchar](50) = '',
	@rOrganizationDepartmentId[nvarchar](50) = '',
	@rReligionId[nvarchar](50) = '',
	@rMaritalStatusId[nvarchar](50) = '',
	@rQualification[nvarchar](50) = '',
	@rGenderId[nvarchar](50) = '',
	@rEmployeeDesignationId[nvarchar](50) = '',
	@rBloodGroupId[nvarchar](50) = '',
	@rEmployeeGroupId[nvarchar](50)='',
	@rDOBFromDate Date = '0001-01-01',
	@rDOBToDate Date = '9999-12-31',
	@rDOJFromDate Date = '0001-01-01',
	@rDOJToDate Date = '9999-12-31',
	@rDropDownStatusId int,
	@rPayrollId int,
	@rPageIndex int = null
AS
SET NOCOUNT ON
BEGIN
	DECLARE @Sql nvarchar(MAX)
	SET @rCode = sCommon.fSearchStringGet(@rCode)
	SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
	SET @rLastName = sCommon.fSearchStringGet(@rLastName)
	SET @rQualification = sCommon.fSearchStringGet(@rQualification)
	
	SELECT PCS.*
	into sPayroll.tTempPayroll1
	FROM sPayroll.vPayrollCustomSearch PCS
	WHERE ((PCS.OrgId = @rOrgId) OR (@rOrgId = 0))
	AND PCS.PayrollId = @rPayrollId
	AND ((PCS.Code Like @rCode + '%') OR (@rCode = ''))
	AND ((PCS.FirstName Like @rFirstName  + '%') OR (@rFirstName = ''))
	AND ((PCS.LastName Like @rLastName + '%')OR(@rLastName = ''))
	AND ((ISNULL(PCS.Qualification,'') Like @rQualification + '%')OR(@rQualification = ''))
	AND ((PCS.DateOfBirth >= @rDOBFromDate) OR (ISNULL(@rDOBFromDate,'') = ''))
	AND ((PCS.DateOfBirth <= @rDOBToDate) OR (ISNULL(@rDOBToDate,'') = ''))
	AND ((PCS.DateOfJoining >= @rDOJFromDate) OR (ISNULL(@rDOJFromDate,'') = ''))
	AND ((PCS.DateOfJoining <= @rDOJToDate) OR (ISNULL(@rDOJToDate,'') = ''))
	AND (ISNULL(PCS.OrganizationDepartmentId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrganizationDepartmentId,','))OR @rOrganizationDepartmentId='')
	AND (ISNULL(PCS.StatusId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rStatusId,','))OR @rStatusId='')
	AND (ISNULL(PCS.EmployeeTypeId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rEmployeeTypeId,','))OR @rEmployeeTypeId='')
	AND (ISNULL(PCS.EmployeeDesignationId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rEmployeeDesignationId,','))OR @rEmployeeDesignationId='')
	AND (ISNULL(PCS.EmployeeGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rEmployeeGroupId,','))OR @rEmployeeGroupId='')
	AND (ISNULL(PCS.BloodGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rBloodGroupId,','))OR @rBloodGroupId='')
	AND (ISNULL(PCS.ReligionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rReligionId,','))OR @rReligionId='')
	AND (ISNULL(PCS.MaritalStatusId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rMaritalStatusId,','))OR @rMaritalStatusId='')
	AND (ISNULL(PCS.GenderId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rGenderId,','))OR @rGenderId='')
	AND ((PCS.StatusId = @rDropDownStatusId) OR (@rDropDownStatusId=0))
	AND ISNULL(PCS.IsOtherUser,0) = 0
	
	SET @rOrderBy=Replace(@rOrderBy,'Code','Code')
	SET @sql='SELECT EmployeeId,Code AS Code,Name,EmployeeType,
	OrganizationDepartment AS OrganizationDepartment,StatusName,
	OrgName,0 AS SalaryMonth
	FROM sPayroll.tTempPayroll1 ORDER BY '+@rOrderBy
	
	exec(@Sql)
	
	create table #TEMPPay
	(
		tid int identity(1,1),t_EmpId bigint
	)
	SET @sql='insert into #TEMPPay SELECT EmployeeId FROM sPayroll.tTempPayroll1 ORDER BY '+ @rOrderBy
	exec(@Sql)
	
	select @rPageIndex = case when isnull(@rPageIndex,0) = 0 then 1 else @rPageIndex end
	declare @lPageSize int = 10,@lTotalRecords int,@lPaging varchar(max)='',@lResult varchar(max)=''
	
	select @lTotalRecords = count(1) from #TEMPPay
	select @lPaging = @lPaging + dbo.fnc_SearchPagingFormat(@rPageIndex,@lTotalRecords,@lPageSize)
	
	select @lResult = @lResult + '<tr><td>' + isnull(OrgName,'') + '</td><td>' + isnull(OrganizationDepartment,'') + '</td>
	<td>' + isnull(Code,'') + '</td><td>' + isnull(Name,'') + '</td><td>' + isnull(EmployeeType,'') + '</td>
	<td>' + isnull(StatusName,'') + '</td></tr>'
	from sPayroll.tTempPayroll1,#TEMPPay where EmployeeId = t_EmpId
	and tid between ((@lPageSize * (@rPageIndex - 1)) + 1) AND (@lPageSize * @rPageIndex)
	
	select @lTotalRecords as TotalRecords,@lResult as EmpList,@lPaging as Paging
	
	DROP Table sPayroll.tTempPayroll1
END
GO
PRINT N'Altering [sPayroll].[pRptEmployeePaybillDetail]...';


GO
 

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

BEGIN  
	
	DECLARE @lFirstDate Date
	DECLARE @lLasteDate Date
	
	IF(@rForMonth!=0 and @rForYear!=0)
	BEGIN
		SET @lFirstDate = CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'/'+CONVERT(NVARCHAR(2),@rForMonth)+'/01'))
		SET @lLasteDate=DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,@lFirstDate)+1,0))
	END
	 
	DECLARE @lBasicPayElementId int
	SELECT @lBasicPayElementId = Id FROM sPayroll.tPayElement WHERE PayrollId = @rPayrollId AND PayElementDefaultId = 1

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

	SELECT 
		@rOrderByField AS OrderByField,
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		EM.EmployeeId, 
		PP.ID As PayProcessId,
		PPE.ID AS PayProcessEmployeeId,
		PP.SalaryMonth,
		PP.SalaryYear,
		tEM.FirstName +' '+tEM.MiddleName+' '+tEm.LastName AS EmployeeName,
		EM.Code AS EmployeeCode,
		PPE.TotalEarning,
		PPE.TotalDeduction,
		PPE.NetAmount,
		(CASE WHEN PayElementId = @lBasicPayElementId then PPE.TotalEarning else 0 END) AS TotalEarningTotal,
		(CASE WHEN PayElementId = @lBasicPayElementId then PPE.TotalDeduction else 0 END) AS TotalDeductionTotal,
		(CASE WHEN PayElementId = @lBasicPayElementId then PPE.NetAmount else 0 END) AS NetAmountTotal,
		ISNULL(ESO.BankName,'') AS BankName,
		ISNULL(ESO.AccountNumber,'') AS AccountNumber,
		MM.Title AS MonthName,
		ISNULL(PPE.WorkingDays,0) AS WorkingDays,
		(ISNULL(PPE.WorkingDays,0) - ISNULL(PPE.Lwp,0)) AS PresentDays,
		--ISNULL(PPE.Lwp,0) AS AbsentDays,
		ISNULL(PPE.GrossBasic,0) AS GrossBasic,
		PY.Title AS PayrollYearName,
		PGM.Id AS PayrollGroupId,
		PGM.Title AS PayrollGroupName,
		ISNULL(ESO.IFSCNumber,'') AS IFSCNumber,
		tEM.FirstName,
		tEm.LastName,
		ISNULL(ESO.AccountHolderName,'')AS AccountHolderName
		
	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.tEmployeeMaster tEM ON tEM.Id = PPE.EmployeeId 
	INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
	INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID 
	LEFT JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.EmployeeId=PPE.EmployeeId	
	INNER JOIN sCommon.tMonthMaster MM ON MM.Id=PP.SalaryMonth	
	INNER JOIN sPayroll.tPayrollYearMaster PY ON PP.PayrollYearId = PY.Id 
	INNER JOIN sPayroll.tPayrollGroupMaster PGM ON PGM.Id = PPE.PayrollGroupId
where 
      (PPE.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
      AND ((EM.Code Like '%' +  @rEmployeeCode + '%' ) OR (@rEmployeeCode = ''))
	  AND ((EM.EmployeeName Like '%' + @rEmployeeName  + '%') OR (@rEmployeeName = ''))
	  AND (EM.DepartmentId = @rDepartmentId OR @rDepartmentId = 0)
	  AND (PP.SalaryMonth = @rForMonth OR @rForMonth = 0)
	  AND (PP.SalaryYear = @rForYear OR @rForYear = 0) 
	  AND ((PY.PayrollId=@rPayrollId) OR (@rPayrollId=0))
	  AND (PPE.PayrollGroupId = @rPayrollGroupId OR @rPayrollGroupId = 0) 
	  AND (PP.PayrollYearId = @rPayrollYearId OR @rPayrollYearId = 0) 
	  --AND ((EM.DateOfleaving >= @lFirstDate) OR ISNULL(EM.DateOfleaving,'') = '')
   --   AND ((EM.DateOfJoining <= @lLasteDate) OR ISNULL(EM.DateOfJoining,'') = '')
	  AND ((tEM.OrgID = @rOrgId) OR (@rOrgId = 0))
END
GO
PRINT N'Altering [sPayroll].[pRptEmployeePFDetail]...';


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

BEGIN 


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

	SELECT 
		@rOrderByField AS OrderByField,
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,	
		ISNULL(ESO.EPFNumber,'') AS PFNumber,
		EM.EmployeeId,
		tEM.FirstName +' '+tEM.MiddleName+' '+ tEM.LastName AS EmployeeName,
		EM.Code AS EmployeeCode,
		ISNULL(PPE.GrossBasic,0) AS GrossBasic,
		PFS.PfSalaryLimit,
		PFS.FpsSalaryLimit,
		PFS.EmployeePfPercent,
		PFS.EmployerPfPercent,
		PFS.EmployerFpsPercent,
		PFS.AdminChargesPercent,
		PFS.EdliPercent,
		PFS.InspectionChargesPercent,
		PFPro.PayProcessElementId,
		PFPro.EmployeePfAmount,
		PFPro.EmployerPfAmount,
		PFPro.EmployerFpsAmount,
		PFPro.AdminChargesAmount,
		PFPro.EdliChargesAmount,
		PFPro.InspectionChargesAmount,
		PY.Title AS PayrollYearName,
		PP.SalaryMonth,
		
		PP.SalaryYear,
	    MM.Title AS MonthName,
	    (ISNULL(AT.TotalWorkingDays,0) - ISNULL(AT.LWP,0)) AS WorkingDays,
	   (SELECT ISNULL(SUM(PPE.Amount),0) FROM sPayroll.tPayProcessElement PPE INNER JOIN sPayroll.tPayElement P  
	    ON PPE.PayElementId =  P.ID  WHERE PPE.PayProcessEmployeeId = PE.PayProcessEmployeeId AND PayElementId IN 
		(SELECT DependentPayElementId FROM sPayroll.tPaySetupDependent PD INNER JOIN sPayroll.tPaySetup PS ON  PD.PaySetupId = PS.ID
		INNER JOIN sPayroll.tPayElement PE ON PS.PayElementId = PE.ID 
		--WHERE PS.PayrollId = @rPayrollId 
		--AND PS.PayrollYearId = @rPayrollYearId 
		AND PE.PayElementDefaultId = 56 AND ((PS.SourceTypeId=2020 AND ESO.PayrollGroupId=PS.SourceId) OR (PS.SourceTypeId=95 AND tEM.Id=PS.SourceId)))
		) 
		AS Salary,
	    ISNULL(ESO.UAN,'') AS UAN,
	    PPE.TotalEarning,
	    EM.FirstName,
		EM.LastName
	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.tEmployeeMaster tEM ON tEM.Id=PPE.EmployeeId
		LEFT JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.EmployeeId=EM.EmployeeId
		INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
		INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID 
		INNER JOIN sPayroll.tPfProcess PFPro ON PFPro.PayProcessElementId=PE.ID
		INNER JOIN sPayroll.tPayrollYearMaster PY ON PP.PayrollYearId = PY.Id
		INNER JOIN sPayroll.tPfSetup PFS ON PFS.PayrollYearId = PY.Id 
		INNER JOIN sCommon.tMonthMaster MM ON MM.Id=PP.SalaryMonth
		INNER JOIN sHrm.tEmployeeAttendance AT ON AT.EmployeeId=EM.EmployeeId 
		--AND AT.ForMonth =PP.SalaryMonth AND AT.ForYear =PP.SalaryYear
		AND AT.ForMonth=PP.SalaryMonth AND AT.ForYear =PP.SalaryYear
		LEFT JOIN 
		(
		SELECT PE.Amount,PPE.WorkingDays,PPE.PayProcessId,PPE.EmployeeId, PPE.PayrollGroupId
		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.tEmployeeMaster tEM ON tEM.Id=PPE.EmployeeId
		LEFT JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.EmployeeId=EM.EmployeeId
		INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
		INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID AND P.PayElementDefaultId = 1
		INNER JOIN sPayroll.tPayrollYearMaster PY ON PP.PayrollYearId = PY.Id
		WHERE 
		(PPE.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
		AND ((EM.Code Like @rEmployeeCode) OR (@rEmployeeCode = ''))
		AND ((EM.EmployeeName Like @rEmployeeName) OR (@rEmployeeName = ''))		
		--AND ((PY.PayrollId=@rPayrollId) OR (@rPayrollId=0))
		AND (PPE.PayrollGroupId = @rPayrollGroupId OR @rPayrollGroupId = 0) 
		AND ((tEM.OrgID = @rOrgId) OR (@rOrgId = 0))		
		) A ON A.PayProcessId = PPE.PayProcessId AND A.EmployeeId = PPE.EmployeeId  AND A.PayrollGroupId =  PPE.PayrollGroupId
		
WHERE 
		(PPE.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
		AND ((EM.Code Like @rEmployeeCode) OR (@rEmployeeCode = ''))
		AND ((EM.EmployeeName Like @rEmployeeName) OR (@rEmployeeName = ''))
		AND ((PY.PayrollId=@rPayrollId) OR (@rPayrollId=0))
		AND (PPE.PayrollGroupId = @rPayrollGroupId OR @rPayrollGroupId = 0) 
		AND ((tEM.OrgID = @rOrgId) OR (@rOrgId = 0))		
END
GO
PRINT N'Altering [sPayroll].[pRptEmployeeSalaryDetail]...';


GO
 
ALTER PROCEDURE [sPayroll].[pRptEmployeeSalaryDetail]
	
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rEmployeeId bigint,
	 @rEmployeeCode nvarchar(200),
	 @rEmployeeName nvarchar(200),
	 @rDepartmentId int,
	 @rForMonth int,
	 @rForYear int,
	 @rPayrollId int,
	 @rPayrollGroupId int,
	 @rPayrollYearId int,
	 @rReportId smallint=0,
	 @rOrderByField nvarchar(20)='',
	 @rMonths nvarchar(50)='',
	 @rOrgId int = 0
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN  
	
	DECLARE @lMonthDay int=0
	SELECT @lMonthDay=[sCommon].[fGetDaysInMonth] (@rForMonth,@rForYear)

	DECLARE @lFirstDate Date
	DECLARE @lLasteDate Date
	IF(@rForMonth!=0 and @rForYear!=0)
	BEGIN
		SET @lFirstDate = CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'/'+CONVERT(NVARCHAR(2),@rForMonth)+'/01'))
		SET @lLasteDate=DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,@lFirstDate)+1,0))
	END
	
	DECLARE @lBasicPayElementId int
	SELECT @lBasicPayElementId = Id FROM sPayroll.tPayElement WHERE PayrollId = @rPayrollId AND PayElementDefaultId = 1
	
	SET @rEmployeeCode = sCommon.fSearchStringGet(@rEmployeeCode)
    SET @rEmployeeName = sCommon.fSearchStringGet(@rEmployeeName)

	SELECT
		@rOrderByField AS OrderByField,
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2, 
		EM.EmployeeId, 
		PP.ID As PayProcessId,
		PPE.ID AS PayProcessEmployeeId,
		PP.SalaryMonth,
		PP.SalaryYear,
		tEM.FirstName +' '+tEM.MiddleName+' '+tEm.LastName AS EmployeeName,
		EM.Code AS EmployeeCode,
		EM.EmployeeDesignation,
		EM.EmployeeGrade,
		ESO.EPFNumber,
		ESO.PanNumber,
		PPE.TotalEarning,		
		PPE.TotalDeduction,
		PPE.NetAmount,
		(CASE WHEN PayElementId = @lBasicPayElementId then PPE.TotalEarning else 0 END) AS TotalEarningTotal,
		(CASE WHEN PayElementId = @lBasicPayElementId then PPE.TotalDeduction else 0 END) AS TotalDeductionTotal,
		(CASE WHEN PayElementId = @lBasicPayElementId then PPE.NetAmount else 0 END) AS NetAmountTotal,
		PE.Amount As PPEAmount,
		P.Title AS PayElementTitle,
		P.ID AS PayElementId,
		P.PayElementTypeId,
		ISNULL(ESO.BankName,'') AS BankName,
		ISNULL(ESO.AccountNumber,'') AS AccountNumber, 
		MM.Title AS MonthName,
		P.Title AS PayElementName,
		P.Code AS PayElementCode,
		(CASE WHEN PayElementId = @lBasicPayElementId then ISNULL(PPE.WorkingDays,@lMonthDay) else 0 END) AS WorkingDays,
		--ISNULL(EWD.WorkingDays,@lMonthDay) AS WorkingDays,
		(CASE WHEN PayElementId = @lBasicPayElementId then PPE.Lwp else 0 END) AS Lwp,
		(CASE WHEN PayElementId = @lBasicPayElementId then ISNULL(PPE.PaidLeave,0) else 0 END) AS PaidLeave,
		P.SortOrder,
		PY.Title AS PayrollYearName,
		PGM.Id AS PayrollGroupId,
		PGM.Title AS PayrollGroupName,
		PPE.GrossBasic,
		P.PayElementDefaultId,
		ISNULL(EPD.Qualification,'') AS Qualification,
		EJD.DateOfJoining AS DateOfAppointment,
		ISNULL(ESO.PayScale,'') AS PayScale,
		EPD.DateOfBirth,
		ISNULL(ROG.SelectableField,'') AS SelectableField,
		RGO.SchoolRequiredSignature ,
		RGO.SchoolRemark1,
		ISNULL(ESO.BasicPay,0) AS BasicPay,
		DAY(DATEADD(DD,-1,DATEADD(mm, DATEDIFF(mm, 0, CONVERT(DATE,CONVERT(nvarchar,PP.SalaryMonth) +'/01/'+CONVERT(nvarchar,PP.SalaryYear)) ) + 1, 0))) AS MonthDay,
		ESO.UAN,
		EPD.GenderId,
		ISNULL(PPR.Remark,'') AS PayProcessEmployeeRemark,
		tEM.FirstName,
		tEm.LastName,
		EM.DateOfJoining,
		OI.CertificateHeaderA4Portrait AS CertificateHeaderA4,
		ISNULL(REPLACE(REPLACE(
		(SELECT STUFF(
		(
		  SELECT  ' ' + Leave FROM -- create comma separated values
			(
					Select '<br>'+('<b>'+ LTM.Code +'</b>' +' - '+ CAST(SUM(CAST(L.NoOfLeave AS FLOAT)) AS varchar(50)) ) + '</br>'AS Leave 
					from 
					sHrm.tLeaveTypeMaster LTM  
					INNER JOIN sHrm.tLeave L ON  EM.EmployeeId = L.EmployeeId 
					INNER JOIN sCommon.tStatusMaster SM ON SM.Id=L.StatusId
					Where EM.EmployeeId=EM.EmployeeId AND LTM.OrgId=EM.OrgId AND LTM.IsObsolete = 0 
					AND LTM.Id = L.LeaveTypeId AND SM.Id=550
					AND (YEAR(L.FromDate) = @rForYear OR @rForYear=0) 
					AND (MONTH(L.FromDate) = @rForMonth OR @rForMonth=0) 
					GROUP BY LTM.Code
					)AS T FOR XML PATH('')
		)
		,1,1,'')),'&lt;','<'),'&gt;','>')
		,'') AS LeaveCount
		
	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.tEmployeeMaster tEM ON tEM.Id = PPE.EmployeeId 
	INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
	INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID AND P.IsIncludeInPaySlip = 1
	LEFT JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.EmployeeId=PPE.EmployeeId	
	LEFT JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId=PPE.EmployeeId	
	LEFT JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=PPE.EmployeeId	
	INNER JOIN sCommon.tMonthMaster MM ON MM.Id=PP.SalaryMonth
	INNER JOIN sPayroll.tPayrollYearMaster PY ON PP.PayrollYearId = PY.Id 
	INNER JOIN sPayroll.tPayrollGroupMaster PGM ON PGM.Id = PPE.PayrollGroupId
	LEFT JOIN sCommon.tReportOrgGroup ROG ON ROG.OrgGroupId=PY.OrgGroupId AND (ROG.ReportId = @rReportId OR @rReportId = 0) 
	LEFT JOIN sCommon.tReportRemarkGroupOrg RGO ON RGO.OrgId = tEM.OrgID AND RGO.ReportRemarkGroupId =  4
	LEFT JOIN sPayroll.tPayProcessEmployeeRemark PPR ON PPR.SalaryMonth = PP.SalaryMonth
	AND PPR.SalaryYear = PP.SalaryYear AND PPR.PayrollYearId = PP.PayrollYearId AND  PPR.EmployeeId = PPE.EmployeeId
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=tEM.OrgId
	left JOIN sSetup.tOrgImages OI ON OI.OrgId = OM.Id
	
	--LEFT JOIN sHrm.tEmployeeWorkingDays EWD ON tEM.Id = EWD.EmployeeId AND PP.SalaryMonth=EWD.ForMonth AND PP.SalaryYear=EWD.ForYear
where 
      (EM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
      AND (P.IsObsolete=0)
      AND ((EM.Code Like '%' +  @rEmployeeCode + '%' ) OR (@rEmployeeCode = ''))
	  AND ((EM.EmployeeName Like '%' + @rEmployeeName  + '%') OR (@rEmployeeName = ''))
	  AND (EM.DepartmentId = @rDepartmentId OR @rDepartmentId = 0)
	  AND (PP.SalaryMonth = @rForMonth OR @rForMonth = 0)
	  AND (PP.SalaryYear = @rForYear OR @rForYear = 0)
	  AND ((PY.PayrollId=@rPayrollId) OR (@rPayrollId=0))
	  AND (PPE.PayrollGroupId = @rPayrollGroupId OR @rPayrollGroupId = 0) 
	  AND (PP.PayrollYearId = @rPayrollYearId OR @rPayrollYearId = 0) 
	  AND (PP.SalaryMonth IN(SELECT cast(item as int) FROM  sCommon.fnsplit(@rMonths,',')) OR @rMonths='')
	  --AND ((EM.DateOfleaving >= @lFirstDate) OR ISNULL(EM.DateOfleaving,'') = '')
   --   AND ((EM.DateOfJoining <= @lLasteDate) OR ISNULL(EM.DateOfJoining,'') = '')
	  AND ((tEM.OrgID = @rOrgId) OR (@rOrgId = 0))
END
GO
PRINT N'Altering [sPayroll].[pRptMonthlyPFStatement]...';


GO
 
 

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

BEGIN
	
	DECLARE @lFirstDate Date
	DECLARE @lLasteDate Date
	
	
	SET @lFirstDate = CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'/'+CONVERT(NVARCHAR(2),@rForMonth)+'/01'))
	SET @lLasteDate=DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,@lFirstDate)+1,0))
	 

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

	SELECT
		@rOrderByField AS OrderByField, 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,	
		ISNULL(ESO.EPFNumber,'') AS PFNumber,
		EM.EmployeeId,
		tEM.FirstName +' '+tEM.MiddleName+' '+ tEM.LastName AS EmployeeName,
		EM.Code AS EmployeeCode,
		ISNULL(PPE.GrossBasic,0) AS GrossBasic,
		ISNULL(PPE.TotalEarning,0) AS TotalEarning,
		PFS.PfSalaryLimit,
		PFS.FpsSalaryLimit,
		PFS.EmployeePfPercent,
		PFS.EmployerPfPercent,
		PFS.EmployerFpsPercent,
		PFS.AdminChargesPercent,
		PFS.EdliPercent,
		PFS.InspectionChargesPercent,
		PFPro.PayProcessElementId,
		PFPro.EmployeePfAmount,
		PFPro.EmployerPfAmount,
		PFPro.EmployerFpsAmount,
		PFPro.AdminChargesAmount,
		PFPro.EdliChargesAmount,
		PFPro.InspectionChargesAmount,
		PY.Title AS PayrollYearName,
		PP.SalaryMonth,
		PP.SalaryYear,
	    MM.Title AS MonthName,
	    (ISNULL(AT.TotalWorkingDays,0) - ISNULL(AT.LWP,0)) AS WorkingDays,
	    (SELECT ISNULL(SUM(PPE.Amount),0) FROM sPayroll.tPayProcessElement PPE INNER JOIN sPayroll.tPayElement P  
	    ON PPE.PayElementId =  P.ID  WHERE PPE.PayProcessEmployeeId = PE.PayProcessEmployeeId AND PayElementId IN 
		(SELECT DependentPayElementId FROM sPayroll.tPaySetupDependent PD INNER JOIN sPayroll.tPaySetup PS ON  PD.PaySetupId = PS.ID
		INNER JOIN sPayroll.tPayElement PE ON PS.PayElementId = PE.ID WHERE PS.PayrollId = @rPayrollId AND PS.PayrollYearId = @rPayrollYearId 
		AND PE.PayElementDefaultId = 56 AND ((PS.SourceTypeId=2020 AND PGM.Id=PS.SourceId) OR (PS.SourceTypeId=95 AND tEM.Id=PS.SourceId)))
		) 
		AS Salary,
		PGM.Id AS PayrollGroupId,
		PGM.Title AS PayrollGroup,
		EM.FirstName,
		EM.LastName
	FROM 
		sPayroll.tPayProcess PP 
		INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId=PP.ID
		INNER JOIN sPayroll.tPayrollGroupMaster PGM ON PGM.Id = PPE.PayrollGroupId
		INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = PPE.EmployeeId
		INNER JOIN sHrm.tEmployeeMaster tEM ON tEM.Id=PPE.EmployeeId
		LEFT JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.EmployeeId=EM.EmployeeId
		INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
		INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID 
		INNER JOIN sPayroll.tPfProcess PFPro ON PFPro.PayProcessElementId=PE.ID
		INNER JOIN sPayroll.tPayrollYearMaster PY ON PP.PayrollYearId = PY.Id
		INNER JOIN sPayroll.tPfSetup PFS ON PFS.PayrollYearId = PY.Id 
		INNER JOIN sCommon.tMonthMaster MM ON MM.Id=PP.SalaryMonth
		INNER JOIN sHrm.tEmployeeAttendance AT ON AT.EmployeeId=EM.EmployeeId AND AT.ForMonth=@rForMonth AND AT.ForYear =@rForYear
		--LEFT JOIN 
		--(
		--SELECT PE.Amount,PPE.WorkingDays,PPE.PayProcessId,PPE.EmployeeId, PPE.PayrollGroupId
		--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.tEmployeeMaster tEM ON tEM.Id=PPE.EmployeeId
		--LEFT JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.EmployeeId=EM.EmployeeId
		--INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
		--INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID AND P.PayElementDefaultId = 1
		--INNER JOIN sPayroll.tPayrollYearMaster PY ON PP.PayrollYearId = PY.Id
		--WHERE 
		--(PPE.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
		--AND ((EM.Code Like @rEmployeeCode) OR (@rEmployeeCode = ''))
		--AND ((EM.EmployeeName Like @rEmployeeName) OR (@rEmployeeName = ''))
		--AND ((PP.SalaryMonth = @rForMonth) OR (@rForMonth = 0))
	 --   AND ((PP.SalaryYear = @rForYear) OR (@rForYear = 0))
		--AND ((PY.PayrollId=@rPayrollId) OR (@rPayrollId=0))
		--AND (PPE.PayrollGroupId = @rPayrollGroupId OR @rPayrollGroupId = 0) 
		--AND (PP.PayrollYearId = @rPayrollYearId OR @rPayrollYearId = 0) 
		--) A ON A.PayProcessId = PPE.PayProcessId AND A.EmployeeId = PPE.EmployeeId  AND A.PayrollGroupId =  PPE.PayrollGroupId
		
WHERE 
		(PPE.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
		AND ((EM.Code Like @rEmployeeCode) OR (@rEmployeeCode = ''))
		AND ((EM.EmployeeName Like @rEmployeeName) OR (@rEmployeeName = ''))
		AND ((PP.SalaryMonth = @rForMonth) OR (@rForMonth = 0))
	    AND ((PP.SalaryYear = @rForYear) OR (@rForYear = 0))
		AND ((PY.PayrollId=@rPayrollId) OR (@rPayrollId=0))
		AND (PPE.PayrollGroupId = @rPayrollGroupId OR @rPayrollGroupId = 0) 
		AND (PP.PayrollYearId = @rPayrollYearId OR @rPayrollYearId = 0) 
		AND PFPro.EmployeePfAmount!=0
		AND ((EM.DateOfleaving >= @lFirstDate) OR ISNULL(EM.DateOfleaving,'') = '')
		AND ((EM.DateOfJoining <= @lLasteDate) OR ISNULL(EM.DateOfJoining,'') = '')
		AND ((tEM.OrgID = @rOrgId) OR (@rOrgId = 0))
END
GO
PRINT N'Altering [sPayroll].[pRptMonthlyProfessoionTaxSummary]...';


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

BEGIN   
		
		DECLARE @lFirstDate Date
		DECLARE @lLasteDate Date
	
	
		SET @lFirstDate = CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'/'+CONVERT(NVARCHAR(2),@rForMonth)+'/01'))
		SET @lLasteDate=DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,@lFirstDate)+1,0))
		
 
		SET @rEmployeeCode = sCommon.fSearchStringGet(@rEmployeeCode)
		SET @rEmployeeName = sCommon.fSearchStringGet(@rEmployeeName)

		SELECT
			@rBuilder1 AS Builder1,
		    @rBuilder2 AS Builder2, 
			PTR.Id,
			PTR.Tax,
			ISNULL(A.NomberOfEmployee,0) AS NumberOfEmployee
		FROM 
			sPayroll.tProfessionalTaxRange PTR
		LEFT JOIN 
		(	
		SELECT 
			PTR.Id, COUNT(EM.EmployeeId) AS NomberOfEmployee ,PE.Amount
		FROM 
			sPayroll.tProfessionalTaxRange PTR
			INNER JOIN sPayroll.tPayProcess PP ON PP.PayrollYearId = PTR.PayrollYearId
			INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId = PP.ID 
			INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = PPE.EmployeeId 
			INNER JOIN sHrm.tEmployeeMaster tEM ON tEM.Id = PPE.EmployeeId 
			INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
			INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID  AND PayElementDefaultId = 57 
			LEFT JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.EmployeeId=PPE.EmployeeId	
			LEFT JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId=PPE.EmployeeId	
			LEFT JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=PPE.EmployeeId	
			INNER JOIN sCommon.tMonthMaster MM ON MM.Id=PP.SalaryMonth
			INNER JOIN sPayroll.tPayrollYearMaster PY ON PP.PayrollYearId = PY.Id 
			INNER JOIN sPayroll.tPayrollGroupMaster PGM ON PGM.Id = PPE.PayrollGroupId
		WHERE 
			(EM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
			AND (P.IsObsolete=0)
			AND ((EM.Code Like '%' +  @rEmployeeCode + '%' ) OR (@rEmployeeCode = ''))
			AND ((EM.EmployeeName Like '%' + @rEmployeeName  + '%') OR (@rEmployeeName = ''))
			AND (EM.DepartmentId = @rDepartmentId OR @rDepartmentId = 0)
			AND (PP.SalaryMonth = @rForMonth OR @rForMonth = 0)
			AND (PP.SalaryYear = @rForYear OR @rForYear = 0)
			AND ((PY.PayrollId=@rPayrollId) OR (@rPayrollId=0))
			AND (PPE.PayrollGroupId = @rPayrollGroupId OR @rPayrollGroupId = 0) 
			AND (PP.PayrollYearId = @rPayrollYearId OR @rPayrollYearId = 0) 
			AND ((EM.DateOfleaving >= @lFirstDate) OR ISNULL(EM.DateOfleaving,'') = '')
			AND ((EM.DateOfJoining <= @lLasteDate) OR ISNULL(EM.DateOfJoining,'') = '')
			AND ((tEM.OrgID = @rOrgId) OR (@rOrgId = 0))
		GROUP BY 
			PTR.Id,EM.EmployeeId,PE.Amount
		) A ON A.Id = PTR.Id AND PTR.Tax = A.Amount
		WHERE PTR.PayrollYearId = @rPayrollYearId
		GROUP BY PTR.Id,PTR.Tax,A.NomberOfEmployee
		ORDER BY PTR.Tax
END
GO
PRINT N'Altering [sPayroll].[pRptPayElementwiseSummaryDetail]...';


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

BEGIN  
	
	DECLARE @lFirstDate Date
	DECLARE @lLasteDate Date
	IF(@rForMonth!=0 and @rForYear!=0)
	BEGIN
		SET @lFirstDate = CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'/'+CONVERT(NVARCHAR(2),@rForMonth)+'/01'))
		SET @lLasteDate=DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,@lFirstDate)+1,0))
	END
	
	DECLARE @lBasicPayElementId int
	DECLARE @lProfessionalTaxPayElementId int
	
	SELECT @lBasicPayElementId = Id FROM sPayroll.tPayElement WHERE PayrollId = @rPayrollId AND PayElementDefaultId = 1
	SELECT @lProfessionalTaxPayElementId = Id FROM sPayroll.tPayElement WHERE PayrollId = @rPayrollId AND PayElementDefaultId = 57
	
	SET @rEmployeeCode = sCommon.fSearchStringGet(@rEmployeeCode)
    SET @rEmployeeName = sCommon.fSearchStringGet(@rEmployeeName)

	SELECT 
	@rOrderByField AS OrderByField,
	@rBuilder1 AS Builder1,
	@rBuilder2 AS Builder2,	
	PE.Amount,
	P.Id AS PayElementId, 
	P.Title AS PayElementName,
	P.Code AS PayElementCode,
	EM.EmployeeId,
	tEM.FirstName +' '+tEM.MiddleName+' '+ tEM.LastName AS EmployeeName,
	EM.Code,
	EM.EmployeeDesignation,
	PP.SalaryMonth,
	PP.SalaryYear,
	MM.Title AS MonthName,
	PY.Title AS PayrollYearName,
	P.SortOrder,
	P.PayElementTypeId,
	@rPayElementTypeId AS IsPayElementTypeIdZero,
	@rPayElementId AS IsPayElementIdZero, 
	PPE.TotalEarning,		
	PPE.TotalDeduction,
	PPE.NetAmount,
	(CASE WHEN PayElementId = @lBasicPayElementId then PPE.TotalEarning else 0 END) AS TotalEarningTotal,
	(CASE WHEN (PayElementId = @lBasicPayElementId And @rPayElementTypeId <> 2) 
	 THEN PPE.TotalDeduction WHEN PayElementId = @lProfessionalTaxPayElementId And @rPayElementTypeId = 2 
	 THEN PPE.TotalDeduction ELSE 0 END) AS TotalDeductionTotal,	 
	(CASE WHEN PayElementId = @lBasicPayElementId then PPE.NetAmount else 0 END) AS NetAmountTotal,
	PGM.Id AS PayrollGroupId,
	PGM.Title AS PayrollGroupName,
	PPE.GrossBasic ,
	P.PayElementDefaultId,
	ISNULL(PPE.WorkingDays,0) AS WorkingDays,
	ISNULL(PPE.Lwp,0) AS Lwp,
	EM.FirstName,
	EM.LastName

	FROM sPayroll.tPayProcessEmployee PPE
		INNER JOIN sPayroll.tPayProcess PP ON PPE.PayProcessId=PP.ID
		INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
		INNER JOIN sPayroll.tPayElement P ON P.ID=PE.PayElementId
		INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId=PPE.EmployeeId
		INNER JOIN sHrm.tEmployeeMaster tEM ON tEM.Id=PPE.EmployeeId
		LEFT JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.EmployeeId=PPE.EmployeeId	
		INNER JOIN sCommon.tMonthMaster MM ON MM.Id=PP.SalaryMonth
		INNER JOIN sPayroll.tPayrollYearMaster PY ON PP.PayrollYearId = PY.Id 
		INNER JOIN sPayroll.tPayrollGroupMaster PGM ON PGM.Id = PPE.PayrollGroupId
WHERE 
      (PPE.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
      AND ((P.ID=@rPayElementId) OR (@rPayElementId=0))
      AND ((EM.Code Like  @rEmployeeCode) OR (@rEmployeeCode = ''))
	  AND ((EM.EmployeeName Like @rEmployeeName ) OR (@rEmployeeName = ''))
	  AND (EM.DepartmentId = @rDepartmentId OR @rDepartmentId = 0)
	  AND (PP.SalaryMonth = @rForMonth OR @rForMonth = 0)
	  AND (PP.SalaryYear = @rForYear OR @rForYear = 0)
	  AND ((PY.PayrollId=@rPayrollId) OR (@rPayrollId=0))
	  AND (PPE.PayrollGroupId = @rPayrollGroupId OR @rPayrollGroupId = 0) 
	  AND (PP.PayrollYearId = @rPayrollYearId OR @rPayrollYearId = 0) 
	  AND (P.PayElementTypeId = @rPayElementTypeId OR @rPayElementTypeId = 0) 
	  AND (PP.SalaryMonth IN(SELECT cast(item as int) FROM  sCommon.fnsplit(@rMonths,',')) OR @rMonths='')
	  AND ((tEM.OrgID = @rOrgId) OR (@rOrgId = 0))
	  --AND ((EM.DateOfleaving >= @lFirstDate) OR ISNULL(EM.DateOfleaving,'') = '')
   --   AND ((EM.DateOfJoining <= @lLasteDate) OR ISNULL(EM.DateOfJoining,'') = '')
END
GO
PRINT N'Altering [sPayroll].[pRptPaysheetDetail]...';


GO
 
 
ALTER PROCEDURE [sPayroll].[pRptPaysheetDetail]
	
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rEmployeeId bigint,
	 @rEmployeeCode nvarchar(200),
	 @rEmployeeName nvarchar(200),
	 @rDepartmentId int,
	 @rForMonth int,
	 @rForYear int,
	 @rPayrollId int,
	 @rPayrollGroupId int,
	 @rPayrollYearId int,
	 @rReportId smallint=0,
	 @rOrgId int,
	 @rOrderByField nvarchar(20)=''
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN  
DECLARE @lOrgGroupId int = 0
DECLARE @lCurrencyCode nvarchar(20) = ''
    SELECT  @lCurrencyCode = [sFinanceCommon].[fDefaultCurrencyCodeGet](@lOrgGroupId) 
	SELECT
		@rOrderByField AS OrderByField,
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		@lCurrencyCode AS CurrencyCode,
		@rForYear AS Foryear,
		(Select DateName( month , DateAdd( month ,@rForMonth, 0 ) - 1 )) AS ForMonth,
		(SELECT Title FROM sSetup.tOrganizationMaster  WHERE Id= EM.OrgId ) AS OrgName,
		(SELECT OG.Title FROM sSetup.tOrgGroupMaster OG INNER JOIN sSetup.tOrganizationMaster OM  ON OG.Id=OM.OrgGroupId WHERE OM.Id=EM.OrgId) AS TrustName,
		(SELECT SmallAddress1 FROM sSetup.tOrganizationMaster WHERE Id= EM.OrgId ) AS ReportAddress1,
		(SELECT SmallAddress2 FROM sSetup.tOrganizationMaster WHERE Id= EM.OrgId ) AS ReportAddress2,
	    (SELECT EM.FirstName+' '+EM.MiddleName+' ' +EM.LastName From  sHrm.tEmployeeMaster EM1
			INNER JOIN sHrm.tEmployeeJobDetail EJ ON EM1.Id=EJ.EmployeeId
			INNER JOIN sHrm.tEmployeeDesignationMaster ED ON ED.Id=EJ.EmployeeDesignationId
			Where EJ.OrgId=EM.OrgID AND ED.Code='PRINCIPAL' AND  ISNULL(EM.IsOtherUser,0) = 0)AS HeadMasterName,
		
		10000 AS SalaryGrant,
		10000 AS RecoveryAdj,
		10000 AS GrossAmount,
		10000 AS TutionFees	,						
		(SELECT sum(PE.Amount) FROM sPayroll.tPayProcess PP 
			INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId = PP.ID 
			INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
			INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID 
			WHERE P.PayElementDefaultId=1 and PayrollId=100100001
			GROUP BY PE.PayElementId,P.code) AS BasicPay,
			
		(SELECT sum(PE.Amount) FROM sPayroll.tPayProcess PP 
			INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId = PP.ID 
			INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
			INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID 
			WHERE P.PayElementDefaultId=8 and PayrollId=100100001
			GROUP BY PE.PayElementId,P.code) AS GradePay,
			
		(SELECT sum(PE.Amount) FROM sPayroll.tPayProcess PP 
			INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId = PP.ID 
			INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
			INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID 
			WHERE P.PayElementDefaultId=2 and PayrollId=100100001
			GROUP BY PE.PayElementId,P.code) AS DA,
			
		(SELECT sum(PE.Amount) FROM sPayroll.tPayProcess PP 
			INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId = PP.ID 
			INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
			INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID 
			WHERE P.PayElementDefaultId=4 and PayrollId=100100001
			GROUP BY PE.PayElementId,P.code) AS HRA,
			
		(SELECT sum(PE.Amount) FROM sPayroll.tPayProcess PP 
			INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId = PP.ID 
			INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
			INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID 
			WHERE P.PayElementDefaultId=3 and PayrollId=100100001
			GROUP BY PE.PayElementId,P.code) AS CLA,
			
		(SELECT sum(PE.Amount) FROM sPayroll.tPayProcess PP 
			INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId = PP.ID 
			INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
			INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID 
			WHERE P.PayElementDefaultId=18 and PayrollId=100100001
			GROUP BY PE.PayElementId,P.code) AS TA,
			
		(SELECT sum(PE.Amount) FROM sPayroll.tPayProcess PP 
			INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId = PP.ID 
			INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
			INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID 
			WHERE P.PayElementDefaultId=17 and PayrollId=100100001
			GROUP BY PE.PayElementId,P.code) AS Differenc,
			
		(SELECT sum(PE.Amount) FROM sPayroll.tPayProcess PP 
			INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId = PP.ID 
			INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
			INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID 
			WHERE P.PayElementDefaultId=56 and PayrollId=100100001
			GROUP BY PE.PayElementId,P.code) AS PF,
			
		(SELECT sum(PE.Amount) FROM sPayroll.tPayProcess PP
			INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId = PP.ID 
			INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
			INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID 
			WHERE P.PayElementDefaultId=57 and PayrollId=100100001
			GROUP BY PE.PayElementId,P.code) AS PT,
			
		(SELECT sum(PE.Amount) FROM sPayroll.tPayProcess PP
			INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId = PP.ID 
			INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
			INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID 
			WHERE P.PayElementDefaultId=57 and PayrollId=100100001
			GROUP BY PE.PayElementId,P.code) AS TrSoc,
			
		(SELECT sum(PE.Amount) FROM sPayroll.tPayProcess PP
			INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId = PP.ID 
			INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
			INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID 
			WHERE P.PayElementDefaultId=57 and PayrollId=100100001
			GROUP BY PE.PayElementId,P.code) AS NtrSoc,
			
		(SELECT sum(PE.Amount) FROM sPayroll.tPayProcess PP
			INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId = PP.ID 
			INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
			INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID 
			WHERE P.PayElementDefaultId=54 and PayrollId=100100001
			GROUP BY PE.PayElementId,P.code) AS LIC,
			
		(SELECT sum(PE.Amount) FROM sPayroll.tPayProcess PP
			INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId = PP.ID 
			INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
			INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID 
			WHERE P.PayElementDefaultId=57 and PayrollId=100100001
			GROUP BY PE.PayElementId,P.code) AS RD,
			
		(SELECT sum(PE.Amount) FROM sPayroll.tPayProcess PP
			INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId = PP.ID 
			INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
			INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID 
			WHERE P.PayElementDefaultId=52 and PayrollId=100100001
			GROUP BY PE.PayElementId,P.code) AS IncomeTax,
			
		(SELECT sum(PE.Amount) FROM sPayroll.tPayProcess PP
			INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId = PP.ID 
			INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
			INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID 
			WHERE P.PayElementDefaultId=52 and PayrollId=100100001
			GROUP BY PE.PayElementId,P.code) AS Other,
			1 AS HM,
			1 AS AHM,
			1 AS Sup,
			1 AS TG,
			1 AS TUG,
			1 AS SplTr,
			1 AS OS,
			1 AS HC,
			1 AS SrCl,
			1 AS JrCl,
			1 AS Libr,
			1 AS LAs,
			1 AS LAt,
			1 AS Naik,
			1 AS Peon,
			1 AS SS,
			EM.FirstName,
		    EM.LastName,
			EM.OrgID
				
			
			
	FROM 
	sHrm.tEmployeeMaster EM
    INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.EmployeeId = EM.Id AND  ISNULL(EM.IsOtherUser,0) = 0
	WHERE ((EM.OrgID = @rOrgId) OR (@rOrgId = 0))
END
GO
PRINT N'Altering [sPayroll].[pRptPFChallanDetailGet]...';


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

BEGIN 
	
	DECLARE @lFirstDate Date
	DECLARE @lLasteDate Date
	IF(@rForMonth!=0 and @rForYear!=0)
	BEGIN
		SET @lFirstDate = CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'/'+CONVERT(NVARCHAR(2),@rForMonth)+'/01'))
		SET @lLasteDate=DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,@lFirstDate)+1,0))
	END

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

	SELECT 
		@rOrderByField AS OrderByField,
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,	
		--ISNULL(ESO.EPFNumber,'') AS PFNumber,
		EM.EmployeeId,
		--tEM.FirstName +' '+tEM.MiddleName+' '+ tEM.LastName AS EmployeeName,
		--EM.Code AS EmployeeCode,
		--ISNULL(PPE.GrossBasic,0) AS GrossBasic,
		PFS.PfSalaryLimit,
		PFS.FpsSalaryLimit,
		PFS.EmployeePfPercent,
		PFS.EmployerPfPercent,
		PFS.EmployerFpsPercent,
		PFS.AdminChargesPercent,
		PFS.EdliPercent,
		PFS.InspectionChargesPercent,
		PFPro.PayProcessElementId,
		PFPro.EmployeePfAmount,
		PFPro.EmployerPfAmount,
		PFPro.EmployerFpsAmount,
		PFPro.AdminChargesAmount,
		PFPro.EdliChargesAmount,
		PFPro.InspectionChargesAmount,
		PY.Title AS PayrollYearName,
		PP.SalaryMonth,
		PP.SalaryYear,
	    MM.Title AS MonthName,
		(ISNULL(AT.TotalWorkingDays,0) - ISNULL(AT.LWP,0)) AS WorkingDays,
		(SELECT ISNULL(SUM(PPE.Amount),0) FROM sPayroll.tPayProcessElement PPE INNER JOIN sPayroll.tPayElement P  
	    ON PPE.PayElementId =  P.ID  WHERE PPE.PayProcessEmployeeId = PE.PayProcessEmployeeId AND PayElementId IN 
		(SELECT DependentPayElementId FROM sPayroll.tPaySetupDependent PD INNER JOIN sPayroll.tPaySetup PS ON  PD.PaySetupId = PS.ID
		INNER JOIN sPayroll.tPayElement PE ON PS.PayElementId = PE.ID WHERE PS.PayrollId = @rPayrollId AND PS.PayrollYearId = @rPayrollYearId 
		AND PE.PayElementDefaultId = 56 AND ((PS.SourceTypeId=2020 AND ESO.PayrollGroupId=PS.SourceId) OR (PS.SourceTypeId=95 AND tEM.Id=PS.SourceId)))
		) 
		AS Salary,
	    --ISNULL(ESO.UAN,'') AS UAN,
	   -- PPE.TotalEarning,
	    OOD.PFEstablishmentCode,
	    OM.DisplayTitle AS OrganizationName,
	    OM.StreetOne + ' ' + OM.StreetTwo + ' ' + OM.StreetThree AS OrgAddress,
		OM.CityName AS OrgCity,
		OM.StateName AS OrgState,
		OM.CountryName AS OrgCountry,
		OM.ZipCode AS OrgZipCode,
		OM.HomePage AS OrgHomePage,
		OM.PhoneNo AS OrgPhoneNo,
		OM.RegistrationDetail AS OrgRegistrationDetail,
	    EM.FirstName,
		EM.LastName
		
	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.tEmployeeMaster tEM ON tEM.Id=PPE.EmployeeId
		LEFT JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.EmployeeId=EM.EmployeeId
		INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
		--INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID 
		INNER JOIN sPayroll.tPfProcess PFPro ON PFPro.PayProcessElementId=PE.ID
		INNER JOIN sPayroll.tPayrollYearMaster PY ON PP.PayrollYearId = PY.Id
		INNER JOIN sPayroll.tPfSetup PFS ON PFS.PayrollYearId = PY.Id 
		INNER JOIN sCommon.tMonthMaster MM ON MM.Id=PP.SalaryMonth
		INNER JOIN sHrm.tEmployeeAttendance AT ON AT.EmployeeId=EM.EmployeeId AND AT.ForMonth=@rForMonth AND AT.ForYear =@rForYear
		INNER JOIN sSetup.tOrganizationOtherDetail OOD ON OOD.OrgId = EM.OrgID 
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = OOD.OrgId
		--LEFT JOIN 
		--(
		--SELECT PE.Amount,PPE.WorkingDays,PPE.PayProcessId,PPE.EmployeeId, PPE.PayrollGroupId
		--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.tEmployeeMaster tEM ON tEM.Id=PPE.EmployeeId
		--LEFT JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.EmployeeId=EM.EmployeeId
		--INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
		--INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID AND P.PayElementDefaultId = 1
		--INNER JOIN sPayroll.tPayrollYearMaster PY ON PP.PayrollYearId = PY.Id
		--WHERE 
		--(PPE.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
		--AND ((EM.Code Like @rEmployeeCode) OR (@rEmployeeCode = ''))
		--AND ((EM.EmployeeName Like @rEmployeeName) OR (@rEmployeeName = ''))
		--AND ((PP.SalaryMonth = @rForMonth) OR (@rForMonth = 0))
	 --   AND ((PP.SalaryYear = @rForYear) OR (@rForYear = 0))
		--AND ((PY.PayrollId=@rPayrollId) OR (@rPayrollId=0))
		--AND (PPE.PayrollGroupId = @rPayrollGroupId OR @rPayrollGroupId = 0) 
		--AND (PP.PayrollYearId = @rPayrollYearId OR @rPayrollYearId = 0) 
		--AND ((EM.DateOfleaving >= @lFirstDate) OR ISNULL(EM.DateOfleaving,'') = '')
  --      AND ((EM.DateOfJoining <= @lLasteDate) OR ISNULL(EM.DateOfJoining,'') = '')
		--) A ON A.PayProcessId = PPE.PayProcessId AND A.EmployeeId = PPE.EmployeeId  AND A.PayrollGroupId =  PPE.PayrollGroupId
WHERE 
		(PPE.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
		AND ((EM.Code Like @rEmployeeCode) OR (@rEmployeeCode = ''))
		AND ((EM.EmployeeName Like @rEmployeeName) OR (@rEmployeeName = ''))
		AND ((PP.SalaryMonth = @rForMonth) OR (@rForMonth = 0))
	    AND ((PP.SalaryYear = @rForYear) OR (@rForYear = 0))
		AND ((PY.PayrollId=@rPayrollId) OR (@rPayrollId=0))
		AND (PPE.PayrollGroupId = @rPayrollGroupId OR @rPayrollGroupId = 0) 
		AND (PP.PayrollYearId = @rPayrollYearId OR @rPayrollYearId = 0) 
		AND ((EM.DateOfleaving >= @lFirstDate) OR ISNULL(EM.DateOfleaving,'') = '')
        AND ((EM.DateOfJoining <= @lLasteDate) OR ISNULL(EM.DateOfJoining,'') = '')
		AND ((tEM.OrgID = @rOrgId) OR (@rOrgId = 0))
END
GO
PRINT N'Altering [sPayroll].[pRptPFDetail]...';


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

BEGIN 
	
	DECLARE @lFirstDate Date
	DECLARE @lLasteDate Date
	IF(@rForMonth!=0 and @rForYear!=0)
	BEGIN
		SET @lFirstDate = CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'/'+CONVERT(NVARCHAR(2),@rForMonth)+'/01'))
		SET @lLasteDate=DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,@lFirstDate)+1,0))
	END

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

	SELECT 
		@rOrderByField AS OrderByField,
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,	
		ISNULL(ESO.EPFNumber,'') AS PFNumber,
		EM.EmployeeId,
		tEM.FirstName +' '+tEM.MiddleName+' '+ tEM.LastName AS EmployeeName,
		EM.Code AS EmployeeCode,
		ISNULL(PPE.GrossBasic,0) AS GrossBasic,
		PFS.PfSalaryLimit,
		PFS.FpsSalaryLimit,
		PFS.EmployeePfPercent,
		PFS.EmployerPfPercent,
		PFS.EmployerFpsPercent,
		PFS.AdminChargesPercent,
		PFS.EdliPercent,
		PFS.InspectionChargesPercent,
		PFPro.PayProcessElementId,
		PFPro.EmployeePfAmount,
		PFPro.EmployerPfAmount,
		PFPro.EmployerFpsAmount,
		PFPro.AdminChargesAmount,
		PFPro.EdliChargesAmount,
		PFPro.InspectionChargesAmount,
		PY.Title AS PayrollYearName,
		PP.SalaryMonth,
		PP.SalaryYear,
	    MM.Title AS MonthName,
	    (ISNULL(AT.TotalWorkingDays,0) - ISNULL(AT.LWP,0)) AS WorkingDays,
	   (SELECT ISNULL(SUM(PPE.Amount),0) FROM sPayroll.tPayProcessElement PPE INNER JOIN sPayroll.tPayElement P  
	    ON PPE.PayElementId =  P.ID  WHERE PPE.PayProcessEmployeeId = PE.PayProcessEmployeeId AND PayElementId IN 
		(SELECT DependentPayElementId FROM sPayroll.tPaySetupDependent PD INNER JOIN sPayroll.tPaySetup PS ON  PD.PaySetupId = PS.ID
		INNER JOIN sPayroll.tPayElement PE ON PS.PayElementId = PE.ID WHERE PS.PayrollId = @rPayrollId AND PS.PayrollYearId = @rPayrollYearId 
		AND PE.PayElementDefaultId = 56 AND ((PS.SourceTypeId=2020 AND ESO.PayrollGroupId=PS.SourceId) OR (PS.SourceTypeId=95 AND tEM.Id=PS.SourceId)))
		) 
		AS Salary,
	    ISNULL(ESO.UAN,'') AS UAN,
	    PPE.TotalEarning,
	    EM.FirstName,
		EM.LastName
	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.tEmployeeMaster tEM ON tEM.Id=PPE.EmployeeId
		LEFT JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.EmployeeId=EM.EmployeeId
		INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
		INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID 
		INNER JOIN sPayroll.tPfProcess PFPro ON PFPro.PayProcessElementId=PE.ID
		INNER JOIN sPayroll.tPayrollYearMaster PY ON PP.PayrollYearId = PY.Id
		INNER JOIN sPayroll.tPfSetup PFS ON PFS.PayrollYearId = PY.Id 
		INNER JOIN sCommon.tMonthMaster MM ON MM.Id=PP.SalaryMonth
		--INNER JOIN sHrm.tEmployeeAttendance AT ON AT.EmployeeId=EM.EmployeeId AND AT.ForMonth=@rForMonth AND AT.ForYear =@rForYear
		--INNER JOIN sHrm.tEmployeeAttendance AT ON AT.EmployeeId=EM.EmployeeId AND ((AT.ForMonth = 0) OR (0 = 0))  AND ((AT.ForYear = 0) OR (0 = 0)) 
		INNER JOIN sHrm.tEmployeeAttendance AT ON AT.EmployeeId=EM.EmployeeId AND ((AT.ForMonth = @rForMonth) OR (@rForMonth = 0))  AND ((AT.ForYear = @rForYear) OR (@rForYear = 0)) 
		LEFT JOIN 
		(
		SELECT PE.Amount,PPE.WorkingDays,PPE.PayProcessId,PPE.EmployeeId, PPE.PayrollGroupId
		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.tEmployeeMaster tEM ON tEM.Id=PPE.EmployeeId
		LEFT JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.EmployeeId=EM.EmployeeId
		INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
		INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID AND P.PayElementDefaultId = 1
		INNER JOIN sPayroll.tPayrollYearMaster PY ON PP.PayrollYearId = PY.Id
		WHERE 
		(PPE.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
		AND ((EM.Code Like @rEmployeeCode) OR (@rEmployeeCode = ''))
		AND ((EM.EmployeeName Like @rEmployeeName) OR (@rEmployeeName = ''))
		AND ((PP.SalaryMonth = @rForMonth) OR (@rForMonth = 0))
	    AND ((PP.SalaryYear = @rForYear) OR (@rForYear = 0))
		AND ((PY.PayrollId=@rPayrollId) OR (@rPayrollId=0))
		AND (PPE.PayrollGroupId = @rPayrollGroupId OR @rPayrollGroupId = 0) 
		AND (PP.PayrollYearId = @rPayrollYearId OR @rPayrollYearId = 0) 
		AND ((EM.DateOfleaving >= @lFirstDate) OR ISNULL(EM.DateOfleaving,'') = '')
        AND ((EM.DateOfJoining <= @lLasteDate) OR ISNULL(EM.DateOfJoining,'') = '')
		AND ((tEM.OrgID = @rOrgId) OR (@rOrgId = 0))
		) A ON A.PayProcessId = PPE.PayProcessId AND A.EmployeeId = PPE.EmployeeId  AND A.PayrollGroupId =  PPE.PayrollGroupId
		
WHERE 
		(PPE.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
		AND ((EM.Code Like @rEmployeeCode) OR (@rEmployeeCode = ''))
		AND ((EM.EmployeeName Like @rEmployeeName) OR (@rEmployeeName = ''))
		AND ((PP.SalaryMonth = @rForMonth) OR (@rForMonth = 0))
	    AND ((PP.SalaryYear = @rForYear) OR (@rForYear = 0))
		AND ((PY.PayrollId=@rPayrollId) OR (@rPayrollId=0))
		AND (PPE.PayrollGroupId = @rPayrollGroupId OR @rPayrollGroupId = 0) 
		AND (PP.PayrollYearId = @rPayrollYearId OR @rPayrollYearId = 0) 
		AND ((EM.DateOfleaving >= @lFirstDate) OR ISNULL(EM.DateOfleaving,'') = '')
        AND ((EM.DateOfJoining <= @lLasteDate) OR ISNULL(EM.DateOfJoining,'') = '')
		AND ((tEM.OrgID = @rOrgId) OR (@rOrgId = 0))
END
GO
PRINT N'Altering [sPayroll].[pRptPFECRFormat]...';


GO
 
 
ALTER PROCEDURE [sPayroll].[pRptPFECRFormat]
	
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rEmployeeId bigint,
	 @rEmployeeCode nvarchar(200),
	 @rEmployeeName nvarchar(200),
	 @rForMonth int,
	 @rForYear int,
	 @rPayrollId int,
	 @rPayrollGroupId int,
	 @rPayrollYearId int,
	 @rOrgGroupId int,
	 @rOrderByField nvarchar(20)='',
	 @rOrgId int = 0
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

DECLARE @lFirstDate Date
DECLARE @lLasteDate Date


SET @lFirstDate = CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'/'+CONVERT(NVARCHAR(2),@rForMonth)+'/01'))
SET @lLasteDate=DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,@lFirstDate)+1,0))	

DECLARE @lIsActivateUniqueId bit = 0
DECLARE @lIsECRIsLWP nvarchar(10)

SELECT @lIsECRIsLWP = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 259 AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId

IF (@lIsECRIsLWP = '') OR (@lIsECRIsLWP = 'False')
	SET @lIsActivateUniqueId = 0
ELSE
	SET @lIsActivateUniqueId = 1

BEGIN  

	SET @rEmployeeCode = sCommon.fSearchStringGet(@rEmployeeCode)
	SET @rEmployeeName = sCommon.fSearchStringGet(@rEmployeeName)
-- For report
	SELECT 
		@rOrderByField AS OrderByField,
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,	
		ISNULL(ESO.EPFNumber,'') AS PFNumber,
		EM.EmployeeId,
		tEM.FirstName +' '+tEM.MiddleName+' '+ tEM.LastName AS EmployeeName,
		EM.Code AS EmployeeCode,
		ISNULL(PPE.GrossBasic,0) AS GrossBasic,
		PFS.PfSalaryLimit,
		PFS.FpsSalaryLimit,
		PFS.EmployeePfPercent,
		PFS.EmployerPfPercent,
		PFS.EmployerFpsPercent,
		PFS.AdminChargesPercent,
		PFS.EdliPercent,
		PFS.InspectionChargesPercent,
		PFPro.PayProcessElementId,
		PFPro.EmployeePfAmount,
		PFPro.EmployerPfAmount,
		PFPro.EmployerFpsAmount,
		PFPro.AdminChargesAmount,
		PFPro.EdliChargesAmount,
		PFPro.InspectionChargesAmount,
		PY.Title AS PayrollYearName,
		PP.SalaryMonth,
		PP.SalaryYear,
	    MM.Title AS MonthName,
	    ISNULL(A.WorkingDays,0) AS WorkingDays,
	    (SELECT ISNULL(SUM(PPE.Amount),0) FROM sPayroll.tPayProcessElement PPE INNER JOIN sPayroll.tPayElement P  
	    ON PPE.PayElementId =  P.ID  WHERE PPE.PayProcessEmployeeId = PE.PayProcessEmployeeId AND PayElementId IN 
		(SELECT DependentPayElementId FROM sPayroll.tPaySetupDependent PD INNER JOIN sPayroll.tPaySetup PS ON  PD.PaySetupId = PS.ID
		INNER JOIN sPayroll.tPayElement PE ON PS.PayElementId = PE.ID WHERE PS.PayrollId = @rPayrollId AND PS.PayrollYearId = @rPayrollYearId 
		AND PE.PayElementDefaultId = 56 AND ((PS.SourceTypeId=2020 AND ESO.PayrollGroupId=PS.SourceId) OR (PS.SourceTypeId=95 AND tEM.Id=PS.SourceId)))
		) 
		AS Salary,
	    ISNULL(ESO.UAN,'') AS UAN,
	    CASE WHEN @lIsActivateUniqueId = 1 THEN ROUND(1+PPE.Lwp,0)-1 ELSE 0 END AS NCPDays,
	    ISNULL(A.TotalEarning,0) AS TotalEarning,
	    EM.FirstName,
		EM.LastName
	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.tEmployeeMaster tEM ON tEM.Id=PPE.EmployeeId
		LEFT JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.EmployeeId=EM.EmployeeId
		INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
		INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID 
		INNER JOIN sPayroll.tPfProcess PFPro ON PFPro.PayProcessElementId=PE.ID
		INNER JOIN sPayroll.tPayrollYearMaster PY ON PP.PayrollYearId = PY.Id
		INNER JOIN sPayroll.tPfSetup PFS ON PFS.PayrollYearId = PY.Id 
		INNER JOIN sCommon.tMonthMaster MM ON MM.Id=PP.SalaryMonth
		LEFT JOIN 
		(
		SELECT PE.Amount,PPE.WorkingDays,PPE.PayProcessId,PPE.EmployeeId, PPE.PayrollGroupId,PPE.TotalEarning
		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.tEmployeeMaster tEM ON tEM.Id=PPE.EmployeeId
		LEFT JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.EmployeeId=EM.EmployeeId
		INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
		INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID AND P.PayElementDefaultId = 1
		INNER JOIN sPayroll.tPayrollYearMaster PY ON PP.PayrollYearId = PY.Id
		WHERE 
		(PPE.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
		AND ((EM.Code Like @rEmployeeCode) OR (@rEmployeeCode = ''))
		AND ((EM.EmployeeName Like @rEmployeeName) OR (@rEmployeeName = ''))
		AND ((PP.SalaryMonth = @rForMonth) OR (@rForMonth = 0))
	    AND ((PP.SalaryYear = @rForYear) OR (@rForYear = 0))
		AND ((PY.PayrollId=@rPayrollId) OR (@rPayrollId=0))
		AND (PPE.PayrollGroupId = @rPayrollGroupId OR @rPayrollGroupId = 0) 
		AND (PP.PayrollYearId = @rPayrollYearId OR @rPayrollYearId = 0) 
		AND ((EM.DateOfleaving >= @lFirstDate) OR ISNULL(EM.DateOfleaving,'') = '')
        AND ((EM.DateOfJoining <= @lLasteDate) OR ISNULL(EM.DateOfJoining,'') = '')
		AND ((tEM.OrgID = @rOrgId) OR (@rOrgId = 0))
		) A ON A.PayProcessId = PPE.PayProcessId AND A.EmployeeId = PPE.EmployeeId  AND A.PayrollGroupId =  PPE.PayrollGroupId
		
WHERE 
		(PPE.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
		AND ((EM.Code Like @rEmployeeCode) OR (@rEmployeeCode = ''))
		AND ((EM.EmployeeName Like @rEmployeeName) OR (@rEmployeeName = ''))
		AND ((PP.SalaryMonth = @rForMonth) OR (@rForMonth = 0))
	    AND ((PP.SalaryYear = @rForYear) OR (@rForYear = 0))
		AND ((PY.PayrollId=@rPayrollId) OR (@rPayrollId=0))
		AND (PPE.PayrollGroupId = @rPayrollGroupId OR @rPayrollGroupId = 0) 
		AND (PP.PayrollYearId = @rPayrollYearId OR @rPayrollYearId = 0) 
		AND ((tEM.OrgID = @rOrgId) OR (@rOrgId = 0))
--	For Notepad report
	
	SELECT 
		ISNULL(ESO.UAN,'') AS UAN,
		tEM.FirstName +' '+tEM.MiddleName+' '+ tEM.LastName AS EmployeeName,
		--ISNULL(cast(replace(A.TotalEarning, '.','') as integer),0) AS TotalEarning,
		ISNULL(CONVERT(DECIMAL(12,0),A.TotalEarning),0) AS TotalEarning,
		CASE WHEN ISNULL(PFS.PfSalaryLimit,0) > (SELECT ISNULL(SUM(PPE.Amount),0) FROM sPayroll.tPayProcessElement PPE INNER JOIN sPayroll.tPayElement P  
	    ON PPE.PayElementId =  P.ID  WHERE PPE.PayProcessEmployeeId = PE.PayProcessEmployeeId AND PayElementId IN 
		(SELECT DependentPayElementId FROM sPayroll.tPaySetupDependent PD INNER JOIN sPayroll.tPaySetup PS ON  PD.PaySetupId = PS.ID
		INNER JOIN sPayroll.tPayElement PE ON PS.PayElementId = PE.ID WHERE PS.PayrollId = @rPayrollId AND PS.PayrollYearId = @rPayrollYearId 
		AND PE.PayElementDefaultId = 56 AND ((PS.SourceTypeId=2020 AND ESO.PayrollGroupId=PS.SourceId) OR (PS.SourceTypeId=95 AND tEM.Id=PS.SourceId)))
		)  
		THEN 
		--(SELECT ISNULL(SUM(cast(replace(PPE.Amount, '.','') as integer)),0) FROM sPayroll.tPayProcessElement PPE 
		(SELECT ISNULL(SUM(CONVERT(DECIMAL(12,0),PPE.Amount)),0) FROM sPayroll.tPayProcessElement PPE
		INNER JOIN sPayroll.tPayElement P ON PPE.PayElementId =  P.ID  WHERE PPE.PayProcessEmployeeId = PE.PayProcessEmployeeId AND PayElementId 
		IN 
		(SELECT DependentPayElementId FROM sPayroll.tPaySetupDependent PD INNER JOIN sPayroll.tPaySetup PS ON  PD.PaySetupId = PS.ID
		INNER JOIN sPayroll.tPayElement PE ON PS.PayElementId = PE.ID WHERE PS.PayrollId = @rPayrollId AND PS.PayrollYearId = @rPayrollYearId 
		AND PE.PayElementDefaultId = 56 AND ((PS.SourceTypeId=2020 AND ESO.PayrollGroupId=PS.SourceId) OR (PS.SourceTypeId=95 AND tEM.Id=PS.SourceId)))
		)  
		--ELSE ISNULL(cast(replace(PFS.PfSalaryLimit, '.','') as integer),0)  END AS PfSalaryLimit1,
		ELSE ISNULL(CONVERT(DECIMAL(12,0),PFS.PfSalaryLimit),0)  END AS PfSalaryLimit1,
		CASE WHEN ISNULL(PFS.PfSalaryLimit,0) > (SELECT ISNULL(SUM(PPE.Amount),0) FROM sPayroll.tPayProcessElement PPE INNER JOIN sPayroll.tPayElement P  
	    ON PPE.PayElementId =  P.ID  WHERE PPE.PayProcessEmployeeId = PE.PayProcessEmployeeId AND PayElementId IN 
		(SELECT DependentPayElementId FROM sPayroll.tPaySetupDependent PD INNER JOIN sPayroll.tPaySetup PS ON  PD.PaySetupId = PS.ID
		INNER JOIN sPayroll.tPayElement PE ON PS.PayElementId = PE.ID WHERE PS.PayrollId = @rPayrollId AND PS.PayrollYearId = @rPayrollYearId 
		AND PE.PayElementDefaultId = 56 AND ((PS.SourceTypeId=2020 AND ESO.PayrollGroupId=PS.SourceId) OR (PS.SourceTypeId=95 AND tEM.Id=PS.SourceId)))
		)  THEN 
		--(SELECT ISNULL(SUM(cast(replace(PPE.Amount, '.','') as integer)),0) FROM sPayroll.tPayProcessElement PPE INNER JOIN sPayroll.tPayElement P  
		(SELECT ISNULL(SUM(CONVERT(DECIMAL(12,0),PPE.Amount)),0) FROM sPayroll.tPayProcessElement PPE INNER JOIN sPayroll.tPayElement P
	    ON PPE.PayElementId =  P.ID  WHERE PPE.PayProcessEmployeeId = PE.PayProcessEmployeeId AND PayElementId IN 
		(SELECT DependentPayElementId FROM sPayroll.tPaySetupDependent PD INNER JOIN sPayroll.tPaySetup PS ON  PD.PaySetupId = PS.ID
		INNER JOIN sPayroll.tPayElement PE ON PS.PayElementId = PE.ID WHERE PS.PayrollId = @rPayrollId AND PS.PayrollYearId = @rPayrollYearId 
		AND PE.PayElementDefaultId = 56 AND ((PS.SourceTypeId=2020 AND ESO.PayrollGroupId=PS.SourceId) OR (PS.SourceTypeId=95 AND tEM.Id=PS.SourceId)))
		)  
		--ELSE ISNULL(cast(replace(PFS.PfSalaryLimit, '.','') as integer),0)  END AS PfSalaryLimit2,
		ELSE ISNULL(CONVERT(DECIMAL(12,0),PFS.PfSalaryLimit),0)  END AS PfSalaryLimit2,
		CASE WHEN ISNULL(PFS.PfSalaryLimit,0) > (SELECT ISNULL(SUM(PPE.Amount),0) FROM sPayroll.tPayProcessElement PPE INNER JOIN sPayroll.tPayElement P  
	    ON PPE.PayElementId =  P.ID  WHERE PPE.PayProcessEmployeeId = PE.PayProcessEmployeeId AND PayElementId IN 
		(SELECT DependentPayElementId FROM sPayroll.tPaySetupDependent PD INNER JOIN sPayroll.tPaySetup PS ON  PD.PaySetupId = PS.ID
		INNER JOIN sPayroll.tPayElement PE ON PS.PayElementId = PE.ID WHERE PS.PayrollId = @rPayrollId AND PS.PayrollYearId = @rPayrollYearId 
		AND PE.PayElementDefaultId = 56 AND ((PS.SourceTypeId=2020 AND ESO.PayrollGroupId=PS.SourceId) OR (PS.SourceTypeId=95 AND tEM.Id=PS.SourceId)))
		)  
		--THEN (SELECT ISNULL(SUM(cast(replace(PPE.Amount, '.','') as integer)),0) FROM sPayroll.tPayProcessElement PPE INNER JOIN sPayroll.tPayElement P
		THEN (SELECT ISNULL(SUM(CONVERT(DECIMAL(12,0),PPE.Amount)),0) FROM sPayroll.tPayProcessElement PPE INNER JOIN sPayroll.tPayElement P  
	    ON PPE.PayElementId =  P.ID  WHERE PPE.PayProcessEmployeeId = PE.PayProcessEmployeeId AND PayElementId IN 
		(SELECT DependentPayElementId FROM sPayroll.tPaySetupDependent PD INNER JOIN sPayroll.tPaySetup PS ON  PD.PaySetupId = PS.ID
		INNER JOIN sPayroll.tPayElement PE ON PS.PayElementId = PE.ID WHERE PS.PayrollId = @rPayrollId AND PS.PayrollYearId = @rPayrollYearId 
		AND PE.PayElementDefaultId = 56 AND ((PS.SourceTypeId=2020 AND ESO.PayrollGroupId=PS.SourceId) OR (PS.SourceTypeId=95 AND tEM.Id=PS.SourceId)))
		--)  ELSE ISNULL(cast(replace(PFS.PfSalaryLimit, '.','') as integer),0)  END AS PfSalaryLimit3,
		)  ELSE ISNULL(CONVERT(DECIMAL(12,0),PFS.PfSalaryLimit),0)  END AS PfSalaryLimit3,
		--ISNULL(PFS.PfSalaryLimit,0) AS PfSalaryLimit1,
		--ISNULL(PFS.PfSalaryLimit,0) AS PfSalaryLimit2,
		--ISNULL(PFS.PfSalaryLimit,0) AS PfSalaryLimit3,
		--ISNULL(cast(replace(PFPro.EmployeePfAmount, '.','') as integer),0) AS EmployeePfAmount,
		ISNULL(CONVERT(DECIMAL(12,0),PFPro.EmployeePfAmount),0) AS EmployeePfAmount,
		--ISNULL(cast(replace(PFPro.EmployerFpsAmount, '.','') as integer),0) AS EmployerFpsAmount,
		ISNULL(CONVERT(DECIMAL(12,0),PFPro.EmployerFpsAmount),0) AS EmployerFpsAmount,
		--ISNULL(cast(replace(PFPro.EmployeePfAmount, '.','') as integer),0) - ISNULL(cast(replace(PFPro.EmployerFpsAmount, '.','') as integer),0) AS EPFEPS,
		ISNULL(CONVERT(DECIMAL(12,0),PFPro.EmployeePfAmount),0) - ISNULL(CONVERT(DECIMAL(12,0),PFPro.EmployerFpsAmount),0) AS EPFEPS,
		--CASE WHEN @lIsActivateUniqueId = 1 THEN cast(replace(ROUND(1+PPE.Lwp,0)-1, '.','') as integer) ELSE 0 END AS NCPDays,
		CASE WHEN @lIsActivateUniqueId = 1 THEN Convert(DECIMAL(12,0),(1+PPE.Lwp)-1,0) ELSE 0 END AS NCPDays,
		0 AS RefundAdv
	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.tEmployeeMaster tEM ON tEM.Id=PPE.EmployeeId
		LEFT JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.EmployeeId=EM.EmployeeId
		INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
		INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID 
		INNER JOIN sPayroll.tPfProcess PFPro ON PFPro.PayProcessElementId=PE.ID
		INNER JOIN sPayroll.tPayrollYearMaster PY ON PP.PayrollYearId = PY.Id
		INNER JOIN sPayroll.tPfSetup PFS ON PFS.PayrollYearId = PY.Id 
		INNER JOIN sCommon.tMonthMaster MM ON MM.Id=PP.SalaryMonth
		LEFT JOIN 
		(
		SELECT PE.Amount,PPE.WorkingDays,PPE.PayProcessId,PPE.EmployeeId, PPE.PayrollGroupId,PPE.TotalEarning
		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.tEmployeeMaster tEM ON tEM.Id=PPE.EmployeeId
		LEFT JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.EmployeeId=EM.EmployeeId
		INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
		INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID AND P.PayElementDefaultId = 1
		INNER JOIN sPayroll.tPayrollYearMaster PY ON PP.PayrollYearId = PY.Id
		WHERE 
		(PPE.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
		AND ((EM.Code Like @rEmployeeCode) OR (@rEmployeeCode = ''))
		AND ((EM.EmployeeName Like @rEmployeeName) OR (@rEmployeeName = ''))
		AND ((PP.SalaryMonth = @rForMonth) OR (@rForMonth = 0))
	    AND ((PP.SalaryYear = @rForYear) OR (@rForYear = 0))
		AND ((PY.PayrollId=@rPayrollId) OR (@rPayrollId=0))
		AND (PPE.PayrollGroupId = @rPayrollGroupId OR @rPayrollGroupId = 0) 
		AND (PP.PayrollYearId = @rPayrollYearId OR @rPayrollYearId = 0) 
		AND ((EM.DateOfleaving >= @lFirstDate) OR ISNULL(EM.DateOfleaving,'') = '')
        AND ((EM.DateOfJoining <= @lLasteDate) OR ISNULL(EM.DateOfJoining,'') = '')
		AND ((tEM.OrgID = @rOrgId) OR (@rOrgId = 0))
		) A ON A.PayProcessId = PPE.PayProcessId AND A.EmployeeId = PPE.EmployeeId  AND A.PayrollGroupId =  PPE.PayrollGroupId
		
WHERE 
		(PPE.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
		AND ((EM.Code Like @rEmployeeCode) OR (@rEmployeeCode = ''))
		AND ((EM.EmployeeName Like @rEmployeeName) OR (@rEmployeeName = ''))
		AND ((PP.SalaryMonth = @rForMonth) OR (@rForMonth = 0))
	    AND ((PP.SalaryYear = @rForYear) OR (@rForYear = 0))
		AND ((PY.PayrollId=@rPayrollId) OR (@rPayrollId=0))
		AND (PPE.PayrollGroupId = @rPayrollGroupId OR @rPayrollGroupId = 0) 
		AND (PP.PayrollYearId = @rPayrollYearId OR @rPayrollYearId = 0) 		
		AND ((tEM.OrgID = @rOrgId) OR (@rOrgId = 0))
END
GO
PRINT N'Altering [sSetup].[pMastedDataModify]...';


GO


ALTER PROCEDURE [sSetup].[pMastedDataModify]	 
	@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

EXEC sp_xml_preparedocument @loDoc OUTPUT,@rXML
BEGIN
	
	IF(@rSubCategoryField = 'InchargeEmployee') 	
		SET @rSubCategoryField = @rSubCategoryField + 'Id'	
		
	IF(@rSubCategoryField = 'DisplayTitle' AND @rCategoryId = 9) 	
		SET @rSubCategoryField = 'ExamSubGroupDisplayTitle'
	
	
	IF OBJECT_ID('ListofData') IS NOT NULL	
			DROP TABLE ListofData
		
	CREATE TABLE ListofData(Id int,SubCategory nvarchar(150),UpdatedUserId bigint,IsExist bit);
	
	IF(@rCategoryId= 1)  
		BEGIN
		
		insert into ListofData
		select E.Id,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),E.UpdatedUserId,0
		from
		(
				SELECT Id,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Masters/Masters', 2)
				WITH (
						Id BIGINT, 
						SubCategory nvarchar(150),
						UpdatedUserId bigint)	
						)E 	
						
		select *from ListofData				
		UPDATE ListofData SET IsExist=1 WHERE Id NOT IN(SELECT Id FROM sSetup.tOrganizationMaster ) 
		
		set @sql='INSERT INTO sSetup.tOrganizationMaster 
					(Id,'+@rSubCategoryField+',CreatedUserId,CreatedDateTime)
					SELECT
						LD.Id,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
					FROM
						ListofData LD WHERE LD.IsExist=1'
					
		print @sql		
		Exec sp_executesql @sql
		set @sql='UPDATE sSetup.tOrganizationMaster  set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sSetup.tOrganizationMaster SC 
					INNER JOIN ListofData LD ON SC.Id=LD.Id AND IsExist=0'
		
		Exec sp_executesql @sql
	
		
		Drop Table ListofData
			 SELECT 1 AS StatusCode
	    END
	    
	else IF(@rCategoryId= 2)     
	 
	 BEGIN
	 
	  insert into ListofData
		select E.Id,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),E.UpdatedUserId,0
		from
		(
				SELECT Id,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Masters/Masters', 2)
				WITH (
						Id BIGINT, 
						SubCategory nvarchar(150),
						UpdatedUserId bigint)	
						)E 	
	    UPDATE ListofData SET IsExist=1 WHERE Id NOT IN(SELECT Id FROM sSetup.tClassMaster ) 
	    
	    set @sql='INSERT INTO sSetup.tClassMaster 
					(Id,'+@rSubCategoryField+',CreatedUserId,CreatedDateTime)
					SELECT
						LD.Id,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
					FROM
						ListofData LD WHERE LD.IsExist=1'
					
		print @sql		
		Exec sp_executesql @sql
		set @sql='UPDATE sSetup.tClassMaster  set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sSetup.tClassMaster SC 
					INNER JOIN ListofData LD ON SC.Id=LD.Id AND IsExist=0'
		
		Exec sp_executesql @sql
	
		
		Drop Table ListofData
			 SELECT 1 AS StatusCode
	  END
	  
	  
	  else IF(@rCategoryId= 3)
	  BEGIN
	     
	     insert into ListofData
		select E.Id,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),E.UpdatedUserId,0
		from
		(
				SELECT Id,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Masters/Masters', 2)
				WITH (
						Id BIGINT, 
						SubCategory nvarchar(150),
						UpdatedUserId bigint)	
						)E 	
	    UPDATE ListofData SET IsExist=1 WHERE Id NOT IN(SELECT Id FROM sSetup.tDivisionMaster ) 
	    
	    set @sql='INSERT INTO sSetup.tDivisionMaster 
					(Id,'+@rSubCategoryField+',CreatedUserId,CreatedDateTime)
					SELECT
						LD.Id,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
					FROM
						ListofData LD WHERE LD.IsExist=1'
					
		print @sql		
		Exec sp_executesql @sql
		set @sql='UPDATE sSetup.tDivisionMaster  set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sSetup.tDivisionMaster SC 
					INNER JOIN ListofData LD ON SC.Id=LD.Id AND IsExist=0'
		--print @sql
		--return
		Exec sp_executesql @sql
	
		
		Drop Table ListofData
			 SELECT 1 AS StatusCode
	    
	  
	  END    
	  
	  else IF(@rCategoryId= 4)
	  BEGIN
	  
	   insert into ListofData
		select E.Id,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),E.UpdatedUserId,0
		from
		(
				SELECT Id,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Masters/Masters', 2)
				WITH (
						Id BIGINT, 
						SubCategory nvarchar(150),
						UpdatedUserId bigint)	
						)E 	
	    UPDATE ListofData SET IsExist=1 WHERE Id NOT IN(SELECT Id FROM sSetup.tSubjectMaster ) 
	    
	    set @sql='INSERT INTO sSetup.tSubjectMaster 
					(Id,'+@rSubCategoryField+',CreatedUserId,CreatedDateTime)
					SELECT
						LD.Id,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
					FROM
						ListofData LD WHERE LD.IsExist=1'
					
		print @sql		
		Exec sp_executesql @sql
		set @sql='UPDATE sSetup.tSubjectMaster  set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sSetup.tSubjectMaster SC 
					INNER JOIN ListofData LD ON SC.Id=LD.Id AND IsExist=0'
		
		Exec sp_executesql @sql
	
		
		Drop Table ListofData
			 SELECT 1 AS StatusCode
	  
	  END 
	    
	 else IF(@rCategoryId= 5)
	 
	 BEGIN
	  
	   insert into ListofData
		select E.Id,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),E.UpdatedUserId,0
		from
		(
				SELECT Id,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Masters/Masters', 2)
				WITH (
						Id BIGINT, 
						SubCategory nvarchar(150),
						UpdatedUserId bigint)	
						)E 	
	    UPDATE ListofData SET IsExist=1 WHERE Id NOT IN(SELECT Id FROM sSetup.tOrgGroupBatchMaster ) 
	    
	    set @sql='INSERT INTO sSetup.tOrgGroupBatchMaster 
					(Id,'+@rSubCategoryField+',CreatedUserId,CreatedDateTime)
					SELECT
						LD.Id,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
					FROM
						ListofData LD WHERE LD.IsExist=1'
					
		print @sql		
		Exec sp_executesql @sql
		set @sql='UPDATE sSetup.tOrgGroupBatchMaster  set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sSetup.tOrgGroupBatchMaster SC 
					INNER JOIN ListofData LD ON SC.Id=LD.Id 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,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),E.UpdatedUserId,0
		from
		(
				SELECT Id,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Masters/Masters', 2)
				WITH (
						Id BIGINT, 
						SubCategory nvarchar(150),
						UpdatedUserId bigint)	
						)E 	
	    UPDATE ListofData SET IsExist=1 WHERE Id NOT IN(SELECT Id FROM sSetup.tBatchMaster ) 
	    
	    set @sql='INSERT INTO sSetup.tBatchMaster 
					(Id,'+@rSubCategoryField+',CreatedUserId,CreatedDateTime)
					SELECT
						LD.Id,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
					FROM
						ListofData LD WHERE LD.IsExist=1'
					
		print @sql		
		Exec sp_executesql @sql
		set @sql='UPDATE sSetup.tBatchMaster  set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sSetup.tBatchMaster SC 
					INNER JOIN ListofData LD ON SC.Id=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 E.Id,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),E.UpdatedUserId,0
		from
		(
				SELECT Id,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Masters/Masters', 2)
				WITH (
						Id BIGINT, 
						SubCategory nvarchar(150),
						UpdatedUserId bigint)	
						)E 	
	    UPDATE ListofData SET IsExist=1 WHERE Id NOT IN(SELECT Id FROM sSetup.tDepartmentMaster ) 
	    
	    set @sql='INSERT INTO sSetup.tDepartmentMaster
					(Id,'+@rSubCategoryField+',CreatedUserId,CreatedDateTime)
					SELECT
						LD.Id,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
					FROM
						ListofData LD WHERE LD.IsExist=1'
					
		print @sql		
		Exec sp_executesql @sql
		set @sql='UPDATE sSetup.tDepartmentMaster  set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sSetup.tDepartmentMaster SC 
					INNER JOIN ListofData LD ON SC.Id=LD.Id AND IsExist=0'
		
		Exec sp_executesql @sql
	
		
		Drop Table ListofData
			 SELECT 1 AS StatusCode
			
	  END 
	  
	  
 else IF(@rCategoryId= 8)
	 BEGIN
	  insert into ListofData
		select E.Id,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),E.UpdatedUserId,0
		from
		(
				SELECT Id,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Masters/Masters', 2)
				WITH (
						Id BIGINT, 
						SubCategory nvarchar(150),
						UpdatedUserId bigint)	
						)E 	
	    UPDATE ListofData SET IsExist=1 WHERE Id NOT IN(SELECT Id FROM sCommon.tOrgGroupDepartmentMaster ) 
	    
	    set @sql='INSERT INTO sCommon.tOrgGroupDepartmentMaster
					(Id,'+@rSubCategoryField+',CreatedUserId,CreatedDateTime)
					SELECT
						LD.Id,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
					FROM
						ListofData LD WHERE LD.IsExist=1'
					
		print @sql		
		Exec sp_executesql @sql
		set @sql='UPDATE sCommon.tOrgGroupDepartmentMaster  set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sCommon.tOrgGroupDepartmentMaster SC 
					INNER JOIN ListofData LD ON SC.Id=LD.Id AND IsExist=0'
		
		Exec sp_executesql @sql
		
		Drop Table ListofData
			 SELECT 1 AS StatusCode
			
	  END 
	    
	   else IF(@rCategoryId= 9)
	 BEGIN
	  insert into ListofData
		select E.Id,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),E.UpdatedUserId,0
		from
		(
				SELECT Id,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Masters/Masters', 2)
				WITH (
						Id BIGINT, 
						SubCategory nvarchar(150),
						UpdatedUserId bigint)	
						)E 	
	    UPDATE ListofData SET IsExist=1 WHERE Id NOT IN(SELECT Id FROM sAssessment.tExamSubGroupMaster ) 
	    
	    set @sql='INSERT INTO sAssessment.tExamSubGroupMaster
					(Id,'+@rSubCategoryField+',CreatedUserId,CreatedDateTime)
					SELECT
						LD.Id,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
					FROM
						ListofData LD WHERE LD.IsExist=1'
					
		print @sql		
		Exec sp_executesql @sql
		set @sql='UPDATE sAssessment.tExamSubGroupMaster  set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sAssessment.tExamSubGroupMaster SC 
					INNER JOIN ListofData LD ON SC.Id=LD.Id AND IsExist=0'
		
		Exec sp_executesql @sql
		
		Drop Table ListofData
			 SELECT 1 AS StatusCode
			
	  END 
	 	
END 
	--   COMMIT TRANSACTION
		
	--END TRY
	
	--BEGIN CATCH 
	--	ROLLBACK TRANSACTION
	--	SELECT -1 AS Result
	--END CATCH
GO
PRINT N'Altering [sStudent].[pDigitalFormChangeRequestAdd]...';


GO
 
ALTER  PROCEDURE [sStudent].[pDigitalFormChangeRequestAdd]
			@rAcademicId Bigint = 0,
			@rDigitalFormId int,
			@rUpdateFieldId int=0,
			@rFieldTypeId int,
			@rOldValue NVarchar(500)='',
			@rNewValue NVarchar(500)='',
			@rRemark nvarchar(500) = '',
			@rCreatedUserId BigInt,
			@rStatusId int,
			@rOldValueImage varbinary(Max) = 0x00000000,
			@rNewValueImage Varbinary(Max) = 0x00000000
			 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

	BEGIN
	BEGIN TRY
	
	BEGIN TRANSACTION

		BEGIN

		IF(@rUpdateFieldId IN (7055,7056,7057,7058))
		BEGIN
			IF NOT EXISTS (SELECT 1 FROM sStudent.tDigitalFormStudent WHERE DigitalFormId = @rDigitalFormId AND AcademicId = @rAcademicId AND FieldTypeId = @rFieldTypeId AND UpdateFieldId = @rUpdateFieldId)
			BEGIN
			INSERT INTO sStudent.tDigitalFormStudent
				(
				DigitalFormId,
				AcademicId,
				FieldTypeId,
				UpdateFieldId,
				NewValue,
				OldValueImage,
				NewValueImage,
				StatusId,
				Remark,
				CreatedUserId,
				CreatedDateTime
				)
			Values
				(
				@rDigitalFormId,
				@rAcademicId,
				@rFieldTypeId,
				@rUpdateFieldId,
				@rNewValue,
				@rOldValueImage,
				@rNewValueImage,
				@rStatusId,
				@rRemark,
				@rCreatedUserId,
				sCommon.fGetDate()
				)

			
			END
			ELSE
			BEGIN
			UPDATE 
				sStudent.tDigitalFormStudent
			SET
				NewValueImage = @rNewValueImage
				,Remark = @rRemark
				,CreatedUserId = @rCreatedUserId
				,CreatedDateTime = sCommon.fGetDate()
			WHERE
				DigitalFormId = @rDigitalFormId 
				AND AcademicId = @rAcademicId 
				AND FieldTypeId = @rFieldTypeId 
				AND UpdateFieldId = @rUpdateFieldId
			END
		END
		ELSE
		BEGIN
			IF NOT EXISTS (SELECT 1 FROM sStudent.tDigitalFormStudent WHERE DigitalFormId = @rDigitalFormId AND AcademicId = @rAcademicId AND FieldTypeId = @rFieldTypeId AND UpdateFieldId = @rUpdateFieldId)
			BEGIN
			INSERT INTO sStudent.tDigitalFormStudent
				(
				DigitalFormId,
				AcademicId,
				FieldTypeId,
				UpdateFieldId,
				OldValue,
				NewValue,
				StatusId,
				Remark,
				CreatedUserId,
				CreatedDateTime
				)
			Values
				(
				@rDigitalFormId,
				@rAcademicId,
				@rFieldTypeId,
				@rUpdateFieldId,
				@rOldValue,
				@rNewValue,
				@rStatusId,
				@rRemark,
				@rCreatedUserId,
				sCommon.fGetDate()
				)

			
			END
			ELSE
			BEGIN
			UPDATE 
				sStudent.tDigitalFormStudent
			SET
				NewValue = @rNewValue
				,Remark = @rRemark
				,CreatedUserId = @rCreatedUserId
				,CreatedDateTime = sCommon.fGetDate()
			WHERE
				DigitalFormId = @rDigitalFormId 
				AND AcademicId = @rAcademicId 
				AND FieldTypeId = @rFieldTypeId 
				AND UpdateFieldId = @rUpdateFieldId
			END
		END
		
		SELECT 1 AS Result
		END
		
		COMMIT TRANSACTION

		END TRY	
	BEGIN CATCH
		ROLLBACK TRANSACTION
		SELECT -1 AS RESULT
	END CATCH
		
END
GO
PRINT N'Altering [sStudent].[pDigitalFormCustomFieldApprove]...';


GO
 
ALTER PROCEDURE [sStudent].[pDigitalFormCustomFieldApprove]	 
	@rId Bigint = 0,
	@rOldValue NVarchar(500)='',
	@rNewValue NVarchar(500)='',
	@rActionRemark nvarchar(500) = '',
	@rActionUserId BigInt,
	@rActionDateTime DateTime,
	@rStatusId int,
	@rRequestId int =0,
	@rOrgId int = 0,
	@rCustomFieldId nvarchar(100)
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
 
BEGIN
	IF EXISTS(SELECT 1 FROM sStudent.vStudentAcademic WHERE AcademicId = @rId)
	BEGIN
		 DECLARE @lStudentId BigInt
		 SET @lStudentId = (SELECT StudentId FROM sStudent.vStudentAcademic WHERE AcademicId = @rId)

		 Declare @Sql nvarchar(max)
		 DECLARE @lResult int
		 IF OBJECT_ID('ListofData') IS NOT NULL	
				BEGIN 
					DROP TABLE ListofData
				END	

		IF(@rStatusId = 550)
			BEGIN
			CREATE TABLE ListofData(Id bigint,StudentId bigint,SubCategory nvarchar(150),CustomFieldId int,UpdatedUserId bigint,IsExist bit);
			insert into ListofData VALUES (@rId,@lStudentId,@rNewValue,@rCustomFieldId,@rActionUserId,0)
	 SELECT * FROM ListofData
		UPDATE LD SET IsExist=1 
		   FROM sStudent.tStudentCustomFieldData SC
		      LEFT JOIN ListofData LD ON SC.StudentId=LD.StudentId 
		      AND  EXISTS (SELECT StudentCustomFieldId FROM sStudent.tStudentCustomFieldData WHERE StudentId=LD.StudentId AND StudentCustomFieldId = LD.CustomFieldId) 
		
		
		set @sql='INSERT INTO sStudent.tStudentCustomFieldData
					(StudentId,StudentCustomFieldId,FieldData,CreatedUserId,CreatedDateTime)
					SELECT
						LD.StudentId,ISNULL('+@rCustomFieldId+',0),LD.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
					FROM
						ListofData LD WHERE LD.IsExist=0'
			
		Exec sp_executesql @sql
		set @sql='UPDATE sStudent.tStudentCustomFieldData set FieldData = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sStudent.tStudentCustomFieldData SC 
					INNER JOIN ListofData LD ON SC.StudentId=LD.StudentId AND SC.StudentCustomFieldId=LD.CustomFieldId AND IsExist=1'
		print @sql
		Exec sp_executesql @sql
	
		Drop Table ListofData
			 SET @lResult = 1;
	      IF(@lResult = 1)
			BEGIN
				UPDATE sStudent.tDigitalFormStudent
				SET
					StatusId = @rStatusId
					,ActionRemark = @rActionRemark
					,ActionUserId = @rActionUserId
					,ActionDateTime = @rActionDateTime
				WHERE 
					AutoId = @rRequestId
			END
			SELECT 1 AS Result
		END 
		ELSE IF(@rStatusId = 551)
		BEGIN
			CREATE TABLE ListofData(Id bigint,StudentId bigint,SubCategory nvarchar(150),CustomFieldId int,UpdatedUserId bigint,IsExist bit);
			insert into ListofData VALUES (@rId,@lStudentId,@rOldValue,@rCustomFieldId,@rActionUserId,0)
	 
		UPDATE LD SET IsExist=1 
		   FROM sStudent.tStudentCustomFieldData SC
		      LEFT JOIN ListofData LD ON SC.StudentId=LD.StudentId 
		      AND  EXISTS (SELECT StudentCustomFieldId FROM sStudent.tStudentCustomFieldData WHERE StudentId=LD.StudentId AND StudentCustomFieldId = LD.CustomFieldId) 
		
		
		set @sql='INSERT INTO sStudent.tStudentCustomFieldData
					(StudentId,StudentCustomFieldId,FieldData,CreatedUserId,CreatedDateTime)
					SELECT
						LD.StudentId,ISNULL('+@rCustomFieldId+',0),LD.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
					FROM
						ListofData LD WHERE LD.IsExist=0'
			
		Exec sp_executesql @sql
		set @sql='UPDATE sStudent.tStudentCustomFieldData set FieldData = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sStudent.tStudentCustomFieldData SC 
					INNER JOIN ListofData LD ON SC.StudentId=LD.StudentId AND SC.StudentCustomFieldId=LD.CustomFieldId AND IsExist=1'
		print @sql
		Exec sp_executesql @sql
	
		Drop Table ListofData
			 SET @lResult = 1;
	      IF(@lResult = 1)
			BEGIN
				UPDATE sStudent.tDigitalFormStudent
				SET
					StatusId = @rStatusId
					,ActionRemark = @rActionRemark
					,ActionUserId = @rActionUserId
					,ActionDateTime = @rActionDateTime
				WHERE 
					AutoId = @rRequestId
			END
			SELECT 2 AS Result
		END
	END
	END
GO
PRINT N'Altering [sStudent].[pDigitalFormFieldApprove]...';


GO
 

ALTER PROCEDURE [sStudent].[pDigitalFormFieldApprove]
			@rId Bigint = 0,
			@rUpdateFieldId int=0,
			@rOldValue NVarchar(500)='',
			@rNewValue NVarchar(500)='',
			@rActionRemark nvarchar(500) = '',
			@rActionUserId BigInt,
			@rActionDateTime DateTime,
			@rStatusId int,
			@rRequestId int =0,
			@rOldValueImage varbinary(MAX) = 0x00000000,
			@rNewValueImage varbinary(MAX) = 0x00000000
			 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

	BEGIN
	BEGIN TRY
	
	BEGIN TRANSACTION

		IF EXISTS(SELECT 1 FROM sStudent.vStudentAcademic WHERE AcademicId = @rId)
		BEGIN
		    
			DECLARE @lResult int
			DECLARE @lDataTypeId nvarchar(1)
			SELECT @lDataTypeId=DataTypeId FROM sCommon.tUpdateFieldMaster WHERE Id=@rUpdateFieldId

			IF(@lDataTypeId = 4)
			BEGIN
				SET @rNewValue = CONVERT(datetime,@rNewValue,104)
				SET @rOldValue = CONVERT(datetime,@rOldValue,104)
			END

			DECLARE @lUpdateField NVARCHAR(100)
			DECLARE @lUpdateFieldImage varbinary(MAX)
			DECLARE @lSubFunctionality NVARCHAR(100)
			DECLARE @lStudentId BigInt

			SET @lUpdateField = (SELECT Field FROM sCommon.tUpdateFieldMaster WHERE Id = @rUpdateFieldId)

			SET @lSubFunctionality = (SELECT SubFunctionalityName FROM sCommon.tUpdateFieldMaster WHERE Id = @rUpdateFieldId)
			SET @lStudentId = (SELECT StudentId FROM sStudent.vStudentAcademic WHERE AcademicId = @rId)

			IF(@lUpdateField = 'Gender' OR @lUpdateField = 'Religion' OR @lUpdateField = 'BloodGroup' 
			 OR @lUpdateField = 'TransportMode' OR @lUpdateField = 'House' OR @lUpdateField = 'Quota' 
			OR @lUpdateField = 'Nationality'  OR @lUpdateField = 'AdmissionStandard' OR  @lUpdateField = 'AdmissionCategory' OR @lUpdateField = 'AdmissionQuota')
			BEGIN
			SET @lUpdateField =@lUpdateField + 'Id'
			END

			IF(@lUpdateField = 'CasteCategory' )
			BEGIN
			SET @lUpdateField = Replace(@lUpdateField,'Caste','Cast') + 'Id'
			END
			
			IF(	@lUpdateField = 'FamilyCaste' )
			BEGIN
				SET @lUpdateField = Replace(@lUpdateField,'Caste','Cast')  
			END
	
			IF(	@lUpdateField = 'StudentGroup' )
			BEGIN
				SET @lUpdateField = Replace(@lUpdateField,'StudentGroup','StudentGroupId')  
			END
			IF(	@lUpdateField = 'StudentOtherGroup' )
			BEGIN
				SET @lUpdateField = Replace(@lUpdateField,'StudentOtherGroup','StudentOtherGroupId')  
			END
	
			IF(@lUpdateField = 'FeeCategory' )
			BEGIN
				SET @lUpdateField = Replace(@lUpdateField,'FeeCategory','AdmissionCategory') + 'Id'
			END
	
			Declare @Sql nvarchar(max)

			IF OBJECT_ID('ListofData') IS NOT NULL	
			BEGIN 
				DROP TABLE ListofData
			END	
			
			IF(@rStatusId = 550)
			BEGIN

			IF(@lSubFunctionality = 'StudentImages')
			BEGIN
			
			IF(@lUpdateField = 'StudentImage')
			BEGIN
				SET @lUpdateField = 'StudentPhoto'
			END
			 
			 IF(@lUpdateField = 'FatherImage')
			BEGIN
				SET @lUpdateField = 'FatherPhoto'
			END

			IF(@lUpdateField = 'MotherImage')
			BEGIN
				SET @lUpdateField = 'MotherPhoto'
			END

			IF(@lUpdateField = 'RelativeImage')
			BEGIN
				SET @lUpdateField = 'RelativePhoto'
			END
				CREATE TABLE ListofData(Id bigint,StudentId bigint,SubCategory varbinary(MAX),UpdatedUserId bigint,IsExist bit);
			insert into ListofData VALUES (@rId,@lStudentId,@rNewValueImage,@rActionUserId,0)

			
			UPDATE ListofData SET IsExist=1 WHERE StudentId NOT IN(SELECT StudentId FROM sStudent.tStudentImages)
			
			
			set @sql='INSERT INTO sStudent.tStudentImages 
							(StudentId,'+@lUpdateField+',Original'+@lUpdateField+',UpdatedDateTime)
							SELECT
								LD.StudentId,Ld.SubCategory,Ld.SubCategory,sCommon.fGetDate()
							FROM
								ListofData LD WHERE LD.IsExist=1'
					
				print @sql		
				Exec sp_executesql @sql
				set @sql='UPDATE sStudent.tStudentImages  set '+@lUpdateField+' = LD.SubCategory,
							Original'+@lUpdateField+' = LD.SubCategory,
							UpdatedDateTime=sCommon.fGetDate()  
							from sStudent.tStudentImages  SI 
							INNER JOIN ListofData LD ON SI.StudentId=LD.StudentId AND IsExist=0'
		
				Exec sp_executesql @sql

				DROP TABLE ListofData
				SET @lResult = 1;
				SELECT 1 AS StatusCode
			END
			ELSE
			BEGIN
			CREATE TABLE ListofData(Id bigint,StudentId bigint,SubCategory nvarchar(150),UpdatedUserId bigint,IsExist bit);
			insert into ListofData VALUES (@rId,@lStudentId,@rNewValue,@rActionUserId,0)

			

			
			IF(@lSubFunctionality = 'Communication')  ----Communication
				BEGIN
			UPDATE ListofData SET IsExist=1 WHERE StudentId NOT IN(SELECT StudentId FROM sStudent.tStudentCommunication)
				set @sql='INSERT INTO sStudent.tStudentCommunication 
							(StudentId,'+@lUpdateField+',CreatedUserId,CreatedDateTime)
							SELECT
								LD.StudentId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
							FROM
								ListofData LD WHERE LD.IsExist=1'
					
				print @sql		
				Exec sp_executesql @sql
				set @sql='UPDATE sStudent.tStudentCommunication set '+@lUpdateField+' = 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
					 SET @lResult = 1;
				END

			
			Else IF(@lSubFunctionality = 'Other')         -------Other
				BEGIN
				UPDATE ListofData SET IsExist=1 WHERE StudentId NOT IN(SELECT StudentId FROM sStudent.tStudentOther) 
					IF(@lUpdateField = 'DateOfBirth')
					BEGIN			
						set @sql='INSERT INTO sStudent.tStudentOther 
								(StudentId,'+@lUpdateField+',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 '+@lUpdateField+' = 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 '+@lUpdateField+' = null WHERE DateOfBirth=''1900-01-01'''
						Exec sp_executesql @sql
					END
					ELSE
					BEGIN
						set @sql='INSERT INTO sStudent.tStudentOther 
									(StudentId,'+@lUpdateField+',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 '+@lUpdateField+' = 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
						 SET @lResult = 1;
				 END	

				Else IF(@lSubFunctionality = 'Admission')		--------Admission
					BEGIN
					set @sql='UPDATE sStudent.tStudentAdmission set '+@lUpdateField+' = 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
					IF(@lUpdateField = 'AdmissionDate' )
					BEGIN
					SET @sql='UPDATE sStudent.tStudentAdmission SET '+@lUpdateField+' = null WHERE AdmissionDate=''1900-01-01'''
						Exec sp_executesql @sql
					END
		
					IF(@lUpdateField = 'PreviousLCDate' )
					BEGIN
					SET @sql='UPDATE sStudent.tStudentAdmission SET '+@lUpdateField+' = null WHERE PreviousLCDate=''1900-01-01'''
						Exec sp_executesql @sql
					END
					
					Drop Table ListofData
							SET @lResult = 1;
					END	

				Else IF(@lSubFunctionality = 'Family')			---------Family
					BEGIN
						
						UPDATE ListofData SET IsExist=1 WHERE StudentId NOT IN(SELECT StudentId FROM sStudent.tStudentFamily) 
		
						set @sql='INSERT INTO sStudent.tStudentFamily 
									(StudentId,'+@lUpdateField+',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 '+@lUpdateField+' = 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
						
						IF(@lUpdateField = 'FatherDateOfBirth' )
						BEGIN
						SET @sql='UPDATE sStudent.tStudentFamily SET '+@lUpdateField+' = null WHERE FatherDateOfBirth=''1900-01-01'''
							Exec sp_executesql @sql
						END
		
						IF(@lUpdateField = 'MotherDateOfBirth' )
						BEGIN
						SET @sql='UPDATE sStudent.tStudentFamily SET '+@lUpdateField+' = null WHERE MotherDateOfBirth=''1900-01-01'''
							Exec sp_executesql @sql
						END

						IF(@lUpdateField = 'RelativeDateOfBirth' )
						BEGIN
						SET @sql='UPDATE sStudent.tStudentFamily SET '+@lUpdateField+' = null WHERE RelativeDateOfBirth=''1900-01-01'''
							Exec sp_executesql @sql
						END		
						Drop Table ListofData
							 SET @lResult = 1;
						END
			 Else IF(@lSubFunctionality = 'Health')	   ----------General
					 BEGIN

					 UPDATE ListofData SET IsExist=1 WHERE StudentId NOT IN(SELECT StudentId FROM sStudent.tStudentHealth) 
					 set @sql='INSERT INTO sStudent.tStudentHealth 
								(StudentId,'+@lUpdateField+',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 '+@lUpdateField+' = 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
							 SET @lResult = 1;
					END
			   Else IF(@lSubFunctionality = 'AcademicDetail')	   ----------General
					 BEGIN
					 UPDATE ListofData SET IsExist=1 WHERE Id NOT IN(SELECT AcademicId FROM sStudent.tAcademicDetail) 
						set @sql='INSERT INTO sStudent.tAcademicDetail 
								(AcademicId,'+@lUpdateField+')
								SELECT
									LD.Id,Ld.SubCategory
								FROM
									ListofData LD WHERE LD.IsExist=1'				
					Exec sp_executesql @sql
		
					set @sql='UPDATE sStudent.tAcademicDetail set '+@lUpdateField+' = LD.SubCategory
								from sStudent.tAcademicDetail AD 
								INNER JOIN ListofData LD ON AD.AcademicId=LD.Id AND IsExist=0'
		
					Exec sp_executesql @sql
		
					IF(@lUpdateField = 'BatchAdmissionDate' )
					BEGIN
					SET @sql='UPDATE sStudent.tAcademicDetail SET '+@lUpdateField+' = NULL WHERE BatchAdmissionDate=''1900-01-01'''
						Exec sp_executesql @sql
					END
					Drop Table ListofData
						 SET @lResult = 1;
					END	
			  Else IF(@lSubFunctionality = 'General')	   ----------General
					 BEGIN
						IF(@lUpdateField != 'AdmissionCategoryId')
						BEGIN
							
							UPDATE ListofData SET IsExist=1 WHERE StudentId NOT IN(SELECT Id FROM sStudent.tStudentMaster) 
			
							set @sql='UPDATE sStudent.tStudentMaster set '+@lUpdateField+' = 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
						END
						IF(@lUpdateField = 'AdmissionCategoryId')
						BEGIN
							set @sql='UPDATE sStudent.tAcademic set '+@lUpdateField+' = LD.SubCategory,
										UpdatedUserId=LD.UpdatedUserId,
										UpdatedDateTime=sCommon.fGetDate()  
										from sStudent.tAcademic A 
										INNER JOIN ListofData LD ON A.Id=LD.Id AND IsExist=0'
			
							Exec sp_executesql @sql
							Drop Table ListofData
		
						END
						 SET @lResult = 1;
					END			 
			Else IF(@lSubFunctionality= 'AdditionalInformation')
				 BEGIN
	      
				UPDATE ListofData SET IsExist=1 WHERE StudentId NOT IN(SELECT StudentId FROM sStudent.tStudentadditional) 
		
				set @sql='INSERT INTO sStudent.tStudentAdditional
							(StudentId,'+@lUpdateField+')
							SELECT
								LD.StudentId,Ld.SubCategory
							FROM
								ListofData LD WHERE LD.IsExist=1'				
				Exec sp_executesql @sql
		
				set @sql='UPDATE sStudent.tStudentAdditional set '+@lUpdateField+' = LD.SubCategory 
					 
							from sStudent.tStudentAdditional SA 
							INNER JOIN ListofData LD ON SA.StudentId=LD.StudentId AND IsExist=0'
					
				Exec sp_executesql @sql
					
				IF(@lUpdateField = 'PassportIssueDate' )
				BEGIN
				SET @sql='UPDATE sStudent.tStudentAdditional SET '+@lUpdateField+' = null WHERE PassportIssueDate=''1900-01-01'''
					Exec sp_executesql @sql
				END
		
				IF(@lUpdateField = 'PassportExpiryDate' )
				BEGIN
				SET @sql='UPDATE sStudent.tStudentAdditional SET '+@lUpdateField+' = null WHERE PassportExpiryDate=''1900-01-01'''
					Exec sp_executesql @sql
				END						
		
				Drop Table ListofData
					 SELECT 1 AS StatusCode
				END	
			 Else IF(@lSubFunctionality= 'StudentSibling')
				BEGIN
				 
				UPDATE ListofData SET IsExist=1 WHERE StudentId NOT IN(SELECT StudentId FROM sStudent.tStudentadditional) 
		
				set @sql='INSERT INTO sStudent.tStudentSibling
							(StudentId,'+@lUpdateField+')
							SELECT
								LD.StudentId,Ld.SubCategory
							FROM
								ListofData LD WHERE LD.IsExist=1'				
				Exec sp_executesql @sql
		
				set @sql='UPDATE sStudent.tStudentSibling set '+@lUpdateField+' = LD.SubCategory 
					 
							from sStudent.tStudentSibling SS 
							INNER JOIN ListofData LD ON SS.StudentId=LD.StudentId AND IsExist=0'
					
				Exec sp_executesql @sql
		
		
			END
			
		
				Drop Table ListofData
					 SELECT 1 AS StatusCode
				END	
			IF(@lResult = 1)
			BEGIN
				UPDATE sStudent.tDigitalFormStudent
				SET
					StatusId = @rStatusId
					,ActionRemark = @rActionRemark
					,ActionUserId = @rActionUserId
					,ActionDateTime = @rActionDateTime
				WHERE 
					AutoId = @rRequestId
			END
			
			SELECT 1 AS Result
			END
ELSE IF(@rStatusId = 551)
			BEGIN

			IF(@lSubFunctionality = 'StudentImages')
			BEGIN
			
			IF(@lUpdateField = 'StudentImage')
			BEGIN
				SET @lUpdateField = 'StudentPhoto'
			END
			 IF(@lUpdateField = 'FatherImage')
			BEGIN
				SET @lUpdateField = 'FatherPhoto'
			END

			IF(@lUpdateField = 'MotherImage')
			BEGIN
				SET @lUpdateField = 'MotherPhoto'
			END

			IF(@lUpdateField = 'RelativeImage')
			BEGIN
				SET @lUpdateField = 'RelativePhoto'
			END

				CREATE TABLE ListofData(Id bigint,StudentId bigint,SubCategory varbinary(MAX),UpdatedUserId bigint,IsExist bit);
			insert into ListofData VALUES (@rId,@lStudentId,@rOldValueImage,@rActionUserId,0)

			
			UPDATE ListofData SET IsExist=1 WHERE StudentId NOT IN(SELECT StudentId FROM sStudent.tStudentImages)
			
			
			set @sql='INSERT INTO sStudent.tStudentImages 
							(StudentId,'+@lUpdateField+',Original'+@lUpdateField+',UpdatedDateTime)
							SELECT
								LD.StudentId,Ld.SubCategory,LD.SubCategory,sCommon.fGetDate()
							FROM
								ListofData LD WHERE LD.IsExist=1'
					
				print @sql		
				Exec sp_executesql @sql
				set @sql='UPDATE sStudent.tStudentImages  set '+@lUpdateField+' = LD.SubCategory,
							Original'+@lUpdateField+' = LD.SubCategory,
							UpdatedDateTime=sCommon.fGetDate()  
							from sStudent.tStudentImages  SI 
							INNER JOIN ListofData LD ON SI.StudentId=LD.StudentId AND IsExist=0'
		
				Exec sp_executesql @sql

				DROP TABLE ListofData
				SET @lResult = 1;
				
			END
			ELSE
			BEGIN
			CREATE TABLE ListofData(Id bigint,StudentId bigint,SubCategory nvarchar(150),UpdatedUserId bigint,IsExist bit);
			insert into ListofData VALUES (@rId,@lStudentId,@rOldValue,@rActionUserId,0)

			UPDATE ListofData SET IsExist=1 WHERE StudentId NOT IN(SELECT StudentId FROM sStudent.tStudentCommunication)

			
			IF(@lSubFunctionality = 'Communication')  ----Communication
				BEGIN
			UPDATE ListofData SET IsExist=1 WHERE StudentId NOT IN(SELECT StudentId FROM sStudent.tStudentCommunication)
				set @sql='INSERT INTO sStudent.tStudentCommunication 
							(StudentId,'+@lUpdateField+',CreatedUserId,CreatedDateTime)
							SELECT
								LD.StudentId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
							FROM
								ListofData LD WHERE LD.IsExist=1'
					
				print @sql		
				Exec sp_executesql @sql
				set @sql='UPDATE sStudent.tStudentCommunication set '+@lUpdateField+' = 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
					 SET @lResult = 1;
				END

			Else IF(@lSubFunctionality = 'Other')         -------Other
				BEGIN
				UPDATE ListofData SET IsExist=1 WHERE StudentId NOT IN(SELECT StudentId FROM sStudent.tStudentOther) 
					IF(@lUpdateField = 'DateOfBirth')
					BEGIN			
						set @sql='INSERT INTO sStudent.tStudentOther 
								(StudentId,'+@lUpdateField+',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 '+@lUpdateField+' = 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 '+@lUpdateField+' = null WHERE DateOfBirth=''1900-01-01'''
						Exec sp_executesql @sql
					END
					ELSE
					BEGIN
						set @sql='INSERT INTO sStudent.tStudentOther 
									(StudentId,'+@lUpdateField+',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 '+@lUpdateField+' = 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
						 SET @lResult = 1;
				 END	

				Else IF(@lSubFunctionality = 'Admission')		--------Admission
					BEGIN
					set @sql='UPDATE sStudent.tStudentAdmission set '+@lUpdateField+' = 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
					IF(@lUpdateField = 'AdmissionDate' )
					BEGIN
					SET @sql='UPDATE sStudent.tStudentAdmission SET '+@lUpdateField+' = null WHERE AdmissionDate=''1900-01-01'''
						Exec sp_executesql @sql
					END
		
					IF(@lUpdateField = 'PreviousLCDate' )
					BEGIN
					SET @sql='UPDATE sStudent.tStudentAdmission SET '+@lUpdateField+' = null WHERE PreviousLCDate=''1900-01-01'''
						Exec sp_executesql @sql
					END
					
					Drop Table ListofData
							SET @lResult = 1;
					END	

				Else IF(@lSubFunctionality = 'Family')			---------Family
					BEGIN
						
						UPDATE ListofData SET IsExist=1 WHERE StudentId NOT IN(SELECT StudentId FROM sStudent.tStudentFamily) 
		
						set @sql='INSERT INTO sStudent.tStudentFamily 
									(StudentId,'+@lUpdateField+',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 '+@lUpdateField+' = 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
						
						IF(@lUpdateField = 'FatherDateOfBirth' )
						BEGIN
						SET @sql='UPDATE sStudent.tStudentFamily SET '+@lUpdateField+' = null WHERE FatherDateOfBirth=''1900-01-01'''
							Exec sp_executesql @sql
						END
		
						IF(@lUpdateField = 'MotherDateOfBirth' )
						BEGIN
						SET @sql='UPDATE sStudent.tStudentFamily SET '+@lUpdateField+' = null WHERE MotherDateOfBirth=''1900-01-01'''
							Exec sp_executesql @sql
						END

						IF(@lUpdateField = 'RelativeDateOfBirth' )
						BEGIN
						SET @sql='UPDATE sStudent.tStudentFamily SET '+@lUpdateField+' = null WHERE RelativeDateOfBirth=''1900-01-01'''
							Exec sp_executesql @sql
						END		
						Drop Table ListofData
							 SET @lResult = 1;
						END
			 Else IF(@lSubFunctionality = 'Health')	   ----------General
					 BEGIN

					 UPDATE ListofData SET IsExist=1 WHERE StudentId NOT IN(SELECT StudentId FROM sStudent.tStudentHealth) 
					 set @sql='INSERT INTO sStudent.tStudentHealth 
								(StudentId,'+@lUpdateField+',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 '+@lUpdateField+' = 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
							 SET @lResult = 1;
					END
			   Else IF(@lSubFunctionality = 'AcademicDetail')	   ----------General
					 BEGIN
					 UPDATE ListofData SET IsExist=1 WHERE Id NOT IN(SELECT AcademicId FROM sStudent.tAcademicDetail) 
						set @sql='INSERT INTO sStudent.tAcademicDetail 
								(AcademicId,'+@lUpdateField+')
								SELECT
									LD.Id,Ld.SubCategory
								FROM
									ListofData LD WHERE LD.IsExist=1'				
					Exec sp_executesql @sql
		
					set @sql='UPDATE sStudent.tAcademicDetail set '+@lUpdateField+' = LD.SubCategory
								from sStudent.tAcademicDetail AD 
								INNER JOIN ListofData LD ON AD.AcademicId=LD.Id AND IsExist=0'
		
					Exec sp_executesql @sql
		
					IF(@lUpdateField = 'BatchAdmissionDate' )
					BEGIN
					SET @sql='UPDATE sStudent.tAcademicDetail SET '+@lUpdateField+' = NULL WHERE BatchAdmissionDate=''1900-01-01'''
						Exec sp_executesql @sql
					END
					Drop Table ListofData
						 SET @lResult = 1;
					END	
			  Else IF(@lSubFunctionality = 'General')	   ----------General
					 BEGIN
						IF(@lUpdateField != 'AdmissionCategoryId')
						BEGIN
							
							UPDATE ListofData SET IsExist=1 WHERE StudentId NOT IN(SELECT Id FROM sStudent.tStudentMaster) 
			
							set @sql='UPDATE sStudent.tStudentMaster set '+@lUpdateField+' = 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
						END
						IF(@lUpdateField = 'AdmissionCategoryId')
						BEGIN
							set @sql='UPDATE sStudent.tAcademic set '+@lUpdateField+' = LD.SubCategory,
										UpdatedUserId=LD.UpdatedUserId,
										UpdatedDateTime=sCommon.fGetDate()  
										from sStudent.tAcademic A 
										INNER JOIN ListofData LD ON A.Id=LD.Id AND IsExist=0'
			
							Exec sp_executesql @sql
							Drop Table ListofData
		
						END
						 SET @lResult = 1;
					END			 
			Else IF(@lSubFunctionality= 'AdditionalInformation')
				 BEGIN
	      
				UPDATE ListofData SET IsExist=1 WHERE StudentId NOT IN(SELECT StudentId FROM sStudent.tStudentadditional) 
		
				set @sql='INSERT INTO sStudent.tStudentAdditional
							(StudentId,'+@lUpdateField+')
							SELECT
								LD.StudentId,Ld.SubCategory
							FROM
								ListofData LD WHERE LD.IsExist=1'				
				Exec sp_executesql @sql
		
				set @sql='UPDATE sStudent.tStudentAdditional set '+@lUpdateField+' = LD.SubCategory 
					 
							from sStudent.tStudentAdditional SA 
							INNER JOIN ListofData LD ON SA.StudentId=LD.StudentId AND IsExist=0'
					
				Exec sp_executesql @sql
					
				IF(@lUpdateField = 'PassportIssueDate' )
				BEGIN
				SET @sql='UPDATE sStudent.tStudentAdditional SET '+@lUpdateField+' = null WHERE PassportIssueDate=''1900-01-01'''
					Exec sp_executesql @sql
				END
		
				IF(@lUpdateField = 'PassportExpiryDate' )
				BEGIN
				SET @sql='UPDATE sStudent.tStudentAdditional SET '+@lUpdateField+' = null WHERE PassportExpiryDate=''1900-01-01'''
					Exec sp_executesql @sql
				END						
		
				Drop Table ListofData
					 SET @lResult = 1;
				END	
			 Else IF(@lSubFunctionality= 'StudentSibling')
				BEGIN
				 
				UPDATE ListofData SET IsExist=1 WHERE StudentId NOT IN(SELECT StudentId FROM sStudent.tStudentadditional) 
		
				set @sql='INSERT INTO sStudent.tStudentSibling
							(StudentId,'+@lUpdateField+')
							SELECT
								LD.StudentId,Ld.SubCategory
							FROM
								ListofData LD WHERE LD.IsExist=1'				
				Exec sp_executesql @sql
		
				set @sql='UPDATE sStudent.tStudentSibling set '+@lUpdateField+' = LD.SubCategory 
					 
							from sStudent.tStudentSibling SS 
							INNER JOIN ListofData LD ON SS.StudentId=LD.StudentId AND IsExist=0'
					
				Exec sp_executesql @sql
		
		
		
				Drop Table ListofData
					 SET @lResult = 1;
				END			 
			END
			IF(@lResult = 1)
			BEGIN
				UPDATE sStudent.tDigitalFormStudent
				SET
					StatusId = @rStatusId
					,ActionRemark = @rActionRemark
					,ActionUserId = @rActionUserId
					,ActionDateTime = @rActionDateTime
				WHERE 
					AutoId = @rRequestId
			END
			SELECT 2 AS Result
			END
		END
		ELSE
		BEGIN
		   SELECT -101 As Result
		END
		
		COMMIT TRANSACTION

		END TRY	
	BEGIN CATCH
		ROLLBACK TRANSACTION
		SELECT -1 AS RESULT
	END CATCH
		
END
GO
PRINT N'Altering [sStudent].[pRptAddressLabelGet]...';


GO


ALTER PROCEDURE [sStudent].[pRptAddressLabelGet]
	 
	 @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,
	 @rClassStatusId int,
	 @rDateOfBirth int,
	 @rDepartmentId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

	SELECT 
			@rBuilder1 As Builder1,
			SD.AcademicId,
			SD.StudentId,			
			SD.Code,
			SD.Number AS StudentNumber,
			SD.RollNo,			
			SD.FirstName,
			SD.MiddleName,			
			SD.LastName,
			SD.Name,	
			SD.ClassName,
			SD.DivisionId,
			SD.DivisionName,
			SD.DivisionOrder,
			SD.StatusName,
			SD.StatusId,			
			SI.StudentPhoto,			 			
			OM.Title AS OrgName,		
			BM.Title AS Batch,				
			CD.PresentStreetOne AS Address1,
			CD.PresentStreetTwo AS Address2,
			CD.PresentStreetThree AS Address3,
			CD.PresentCountry AS AddressCountry,
			CD.PresentState AS AddressState,
			CD.PresentCity AS AddressCity,
			CD.PresentZipCode AS AddressZipCode,
			CD.PresentContactNo AS ContactNo,
			CD.ParentContactNo ,
			CD.StudentContactNo,
			CD.ParentEmail,
			CD.StudentEmail,
			SD.SUID,
			SD.ClassStatusId,
			SF.FatherContactNo,
			SF.MotherContactNo
			
	FROM 
			sStudent.vStudentAcademic SD
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=SD.OrgId
			INNER JOIN sStudent.tStudentCommunication CD ON SD.StudentId = CD.StudentId
			LEFT JOIN sStudent.tStudentImages SI ON SD.StudentId = SI.StudentId
			INNER JOIN sSetup.tBatchMaster BM ON SD.BatchId = BM.Id 
			INNER JOIN sSetup.tBatchClass BC ON BC.ClassID =  SD.ClassId and BC.BatchId= @rBatchId
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SD.StudentId
			--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 ((SD.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=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

        --CategoryId
        --Communication = 1,
        --Other = 2,
        --Admission = 3,
        --Family = 4,
        --Health = 5,
        --AcademicDetail = 6,
        --General = 7
        --CustomDetail = 8
        --Sibling = 9

EXEC sp_xml_preparedocument @loDoc OUTPUT,@rXML
BEGIN
	
	IF(@rSubCategoryField = 'Gender' OR @rSubCategoryField = 'Religion' OR @rSubCategoryField = 'BloodGroup' 
			 OR @rSubCategoryField = 'TransportMode' OR @rSubCategoryField = 'House'
			OR @rSubCategoryField = 'Quota' 
			OR @rSubCategoryField = 'Nationality' OR @rSubCategoryField = 'AdmissionStandard' OR  @rSubCategoryField = 'AdmissionCategory' OR @rSubCategoryField = 'AdmissionQuota')
	BEGIN
		SET @rSubCategoryField = @rSubCategoryField + 'Id'
	END
	
	IF(	@rSubCategoryField = 'CasteCategory' )
	BEGIN
		SET @rSubCategoryField = Replace(@rSubCategoryField,'Caste','Cast') + 'Id'
	END
	
	IF(	@rSubCategoryField = 'FamilyCaste' )
	BEGIN
		SET @rSubCategoryField = Replace(@rSubCategoryField,'Caste','Cast')  
	END
	
	IF(	@rSubCategoryField = 'StudentGroup' )
	BEGIN
		SET @rSubCategoryField = Replace(@rSubCategoryField,'StudentGroup','StudentGroupId')  
	END
	IF(	@rSubCategoryField = 'StudentOtherGroup' )
	BEGIN
		SET @rSubCategoryField = Replace(@rSubCategoryField,'StudentOtherGroup','StudentOtherGroupId')  
	END
	
	IF(@rSubCategoryField = 'FeeCategory' )
	BEGIN
		SET @rSubCategoryField = Replace(@rSubCategoryField,'FeeCategory','AdmissionCategory') + 'Id'
	END
	
	IF OBJECT_ID('ListofData') IS NOT NULL	
	BEGIN 
		DROP TABLE ListofData
	END	
	
	CREATE TABLE ListofData(Id bigint,StudentId bigint,SubCategory nvarchar(150),UpdatedUserId bigint,IsExist bit);
	
	IF(@rCategoryId= 1)  
		BEGIN
		insert into ListofData
		select 0,E.StudentId,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),E.UpdatedUserId,0
		from
		(
				SELECT StudentId,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Students/Students', 2)
				WITH (
						StudentId BIGINT, 
						SubCategory nvarchar(150),
						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'
					
		print @sql		
		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,sSetup.fPortalXMLTagsReplaceReverse(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,sSetup.fPortalXMLTagsReplaceReverse(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
		
		IF(@rSubCategoryField = 'AdmissionDate' )
		BEGIN
		SET @sql='UPDATE sStudent.tStudentAdmission SET '+@rSubCategoryField+' = null WHERE AdmissionDate=''1900-01-01'''
			Exec sp_executesql @sql
		END
		
		IF(@rSubCategoryField = 'PreviousLCDate' )
		BEGIN
		SET @sql='UPDATE sStudent.tStudentAdmission SET '+@rSubCategoryField+' = null WHERE PreviousLCDate=''1900-01-01'''
			Exec sp_executesql @sql
		END
 
		
		Drop Table ListofData
			 SELECT 1 AS StatusCode
	    END	
  Else IF(@rCategoryId= 4)
	BEGIN
		insert into ListofData
		select 0,E.StudentId,sSetup.fPortalXMLTagsReplaceReverse(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
		
		IF(@rSubCategoryField = 'FatherDateOfBirth' )
		BEGIN
		SET @sql='UPDATE sStudent.tStudentFamily SET '+@rSubCategoryField+' = null WHERE FatherDateOfBirth=''1900-01-01'''
			Exec sp_executesql @sql
		END
		
		IF(@rSubCategoryField = 'MotherDateOfBirth' )
		BEGIN
		SET @sql='UPDATE sStudent.tStudentFamily SET '+@rSubCategoryField+' = null WHERE MotherDateOfBirth=''1900-01-01'''
			Exec sp_executesql @sql
		END

		IF(@rSubCategoryField = 'RelativeDateOfBirth' )
		BEGIN
		SET @sql='UPDATE sStudent.tStudentFamily SET '+@rSubCategoryField+' = null WHERE RelativeDateOfBirth=''1900-01-01'''
			Exec sp_executesql @sql
		END		
				
		
		
		Drop Table ListofData
			 SELECT 1 AS StatusCode
	    END
	    
    Else IF(@rCategoryId= 5)
	     BEGIN
		insert into ListofData
		select 0,E.StudentId,sSetup.fPortalXMLTagsReplaceReverse(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,sSetup.fPortalXMLTagsReplaceReverse(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
		
		IF(@rSubCategoryField = 'BatchAdmissionDate' )
		BEGIN
		SET @sql='UPDATE sStudent.tAcademicDetail SET '+@rSubCategoryField+' = NULL WHERE BatchAdmissionDate=''1900-01-01'''
			Exec sp_executesql @sql
		END
		
		Drop Table ListofData
			 SELECT 1 AS StatusCode
	    END	
	    
	Else IF(@rCategoryId= 7)
	     BEGIN
	    IF(@rSubCategoryField != 'AdmissionCategoryId')
		BEGIN
			insert into ListofData
			select 0,E.StudentId,sSetup.fPortalXMLTagsReplaceReverse(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
		END
		IF(@rSubCategoryField = 'AdmissionCategoryId')
		BEGIN
			insert into ListofData
			select E.Id,0,sSetup.fPortalXMLTagsReplaceReverse(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 
							
			set @sql='UPDATE sStudent.tAcademic set '+@rSubCategoryField+' = LD.SubCategory,
						UpdatedUserId=LD.UpdatedUserId,
						UpdatedDateTime=sCommon.fGetDate()  
						from sStudent.tAcademic A 
						INNER JOIN ListofData LD ON A.Id=LD.Id AND IsExist=0'
			
			Exec sp_executesql @sql
			Drop Table ListofData
		
		END
		
			 SELECT 1 AS StatusCode
	    END			 
	 
	 
	 Else IF(@rCategoryId= 8)
	     BEGIN
	     
		insert into ListofData
		select 0,E.StudentId,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),0,0
		from
		(
				SELECT StudentId,SubCategory FROM
				OPENXML (@loDoc, '/Students/Students', 2)
				WITH (
						StudentId BIGINT, 
						SubCategory nvarchar(100)
						 )	
						)E 	
		UPDATE ListofData SET IsExist=1 WHERE StudentId NOT IN(SELECT StudentId FROM sStudent.tStudentadditional) 
		
		set @sql='INSERT INTO sStudent.tStudentAdditional
					(StudentId,'+@rSubCategoryField+')
					SELECT
						LD.StudentId,Ld.SubCategory
					FROM
						ListofData LD WHERE LD.IsExist=1'				
		Exec sp_executesql @sql
		
		set @sql='UPDATE sStudent.tStudentAdditional set '+@rSubCategoryField+' = LD.SubCategory 
					 
					from sStudent.tStudentAdditional SA 
					INNER JOIN ListofData LD ON SA.StudentId=LD.StudentId AND IsExist=0'
					
		Exec sp_executesql @sql
					
		IF(@rSubCategoryField = 'PassportIssueDate' )
		BEGIN
		SET @sql='UPDATE sStudent.tStudentAdditional SET '+@rSubCategoryField+' = null WHERE PassportIssueDate=''1900-01-01'''
			Exec sp_executesql @sql
		END
		
		IF(@rSubCategoryField = 'PassportExpiryDate' )
		BEGIN
		SET @sql='UPDATE sStudent.tStudentAdditional SET '+@rSubCategoryField+' = null WHERE PassportExpiryDate=''1900-01-01'''
			Exec sp_executesql @sql
		END						
		
		Drop Table ListofData
			 SELECT 1 AS StatusCode
	    END	
	    
	    
	     
	 Else IF(@rCategoryId= 9)
	    BEGIN
		insert into ListofData
		select 0,E.StudentId,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),0,0
		from
		(
				SELECT StudentId,SubCategory FROM
				OPENXML (@loDoc, '/Students/Students', 2)
				WITH (
						StudentId BIGINT, 
						SubCategory nvarchar(200)
						 )	
						)E 	
		UPDATE ListofData SET IsExist=1 WHERE StudentId NOT IN(SELECT StudentId FROM sStudent.tStudentadditional) 
		
		set @sql='INSERT INTO sStudent.tStudentSibling
					(StudentId,'+@rSubCategoryField+')
					SELECT
						LD.StudentId,Ld.SubCategory
					FROM
						ListofData LD WHERE LD.IsExist=1'				
		Exec sp_executesql @sql
		
		set @sql='UPDATE sStudent.tStudentSibling set '+@rSubCategoryField+' = LD.SubCategory 
					 
					from sStudent.tStudentSibling SS 
					INNER JOIN ListofData LD ON SS.StudentId=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].[pStudentGenerateReport]...';


GO
 
 
ALTER PROCEDURE [sStudent].[pStudentGenerateReport]
	@rId bigint,
	@rTitle nvarchar(50),
	@rColumnName nvarchar(max) = '',
	@rOrderBy nvarchar(max) = 'RollNo',
	@rOrgId smallint,
	@rCode [nvarchar](20) = '',
	@rFirstName [nvarchar](50) = '',	
	@rLastName [nvarchar](50) = '',
	@rCountry [nvarchar](50) = '',
	@rState [nvarchar](50) = '',
	@rCity nvarchar(max) = '',
	@rArea nvarchar(max) = '',
	@rDivisionId nvarchar(max) = '',
	@rStatusId nvarchar(max) = '',
	@rTransportModeId nvarchar(max) = '',
	@rBusRouteDestinationId nvarchar(max) = '',
	@rBloodGroupId nvarchar(max) = '',
	@rGenderId nvarchar(max) = '',
	@rReligionId nvarchar(max) = '',
	@rCastCategoryId nvarchar(max) = '',
	@rHouseId nvarchar(max) = '',
	@rMotherTongueId nvarchar(max) = '',
	@rNationalityId nvarchar(max) = '',
	@rHobby nvarchar(50) = '',
	@rFatherQualification nvarchar(max) = '',
	@rMotherQualification nvarchar(max) = '',
	@rFatherOccupation nvarchar(max) = '',
	@rMotherOccupation nvarchar(max) = '',
	@rPreviousSchool nvarchar(max) = '',
	@rAdmissionCategoryId nvarchar(max) = '',
	@rDOBFromDate Date = '0001-01-01',
	@rDOBToDate Date = '9999-12-31',
	@rDOAFromDate Date = '0001-01-01',
	@rDOAToDate Date = '9999-12-31',
	@rDOLFromDate Date = '0001-01-01',
	@rDOLToDate Date = '9999-12-31',
	@rIsPysicalDeformity bit,
	@rIsMajorIllness bit,
	@rIsCommon bit,
	@rIsCommonForOrg bit,
	@rCreatedUserId bigint,
	@BatchId int,
	@rIsBlackList bit,
	@rFromCode nvarchar(20), 
	@rToCode nvarchar(20),
	@rSpecificCode nvarchar(max),
	@rDropDownStatusId int,
	@rDropDownClassId int,
	@rDropDownDivisionId int,
	@rCustomTagId nvarchar(max) = '',
	@rCustomGroupId nvarchar(max) = '',
	@rClubId nvarchar(max) = '',
	@rRepeatCount smallint=0,
	@rStudentStatusId smallint=0,
	@rHostelId nvarchar(max) = '',
	@rStudentGroupId nvarchar(max) = '',
	@rStudentOtherGroupId nvarchar(max) = '',
	@rOrgGroupBatchId int,
	@rBusRouteId nvarchar(max) = '',
	@rFeeExemption nvarchar(max)='',
	@rRecordTagId nvarchar(max) = ''
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
  
		IF(@rHostelId IS NULL)
			SET @rHostelId = ''
		IF(@rStudentGroupId IS NULL)
			SET @rStudentGroupId = ''
		IF(@rStudentOtherGroupId IS NULL)
			SET @rStudentOtherGroupId = ''	
		IF(@rOrgGroupBatchId IS NULL)
			SET @rOrgGroupBatchId = 0
		IF(@rGenderId IS NULL)
			SET @rGenderId = ''
		IF(@rBusRouteId IS NULL)
			SET @rBusRouteId = ''	
		IF(@rDOBFromDate IS NULL)
			SET @rDOBFromDate='0001-01-01'
		IF(@rDOBToDate IS NULL)
			SET @rDOBToDate='9999-12-31'
		IF(@rDOAFromDate IS NULL)
			SET @rDOAFromDate='0001-01-01'
		IF(@rDOAToDate IS NULL)
			SET @rDOAToDate='9999-12-31'
		IF(@rDOLFromDate IS NULL)
			SET @rDOLFromDate='0001-01-01'
		IF(@rDOLToDate IS NULL)
			SET @rDOLToDate='9999-12-31'
		
		IF(@rTitle != '' AND @rId = 0)
		BEGIN
			DECLARE @lNextNumber BIGINT
			EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sStudent.tStudentCustomSearch', 0, 1, 1,@outNextNumber = @lNextNumber output
			INSERT INTO sStudent.tStudentCustomSearch
			(
				Id,Title,ColumnName,OrderBy,OrgId,Code,FirstName,LastName,Country,State,City,Area,DivisionId,
				StatusId,TransportModeId,BusRouteDestinationId,BloodGroupId,GenderId,ReligionId,CastCategoryId,
				HouseId,MotherTongueId,NationalityId,Hobby,FatherQualification,MotherQualification,FatherOccupation,
				MotherOccupation,PreviousSchool,AdmissionCategoryId,DOBFromDate,DOBToDate,DOAFromDate,DOAToDate,
				DOLFromDate,DOLToDate,IsPysicalDeformity,IsMajorIllness,IsCommon,IsCommonForOrg, CreatedUserId,CreatedDateTime,
				IsBlackList,FromCode,ToCode,CustomTag,CustomGroup,Club,RepeatCount,StudentStatusId,Hostel,StudentGroup,
				StudentOtherGroup,FeeExemption,RecordTag
			)
			VALUES
			(
				@lNextNumber,@rTitle,@rColumnName,@rOrderBy,@rOrgId,@rSpecificCode,@rFirstName,@rLastName,@rCountry,@rState,
				@rCity,@rArea,@rDivisionId,@rStatusId,@rTransportModeId,@rBusRouteDestinationId,@rBloodGroupId,@rGenderId,
				@rReligionId,@rCastCategoryId,@rHouseId,@rMotherTongueId,@rNationalityId,@rHobby,@rFatherQualification,
				@rMotherQualification,@rFatherOccupation,@rMotherOccupation,@rPreviousSchool,@rAdmissionCategoryId,
				@rDOBFromDate,@rDOBToDate,@rDOAFromDate,@rDOAToDate,@rDOLFromDate,@rDOLToDate,@rIsPysicalDeformity,
				@rIsMajorIllness,@rIsCommon,@rIsCommonForOrg,@rCreatedUserId,sCommon.fGetDate(),@rIsBlackList,@rFromCode,@rToCode,
				@rCustomTagId,@rCustomGroupId,@rClubId,@rRepeatCount,@rStudentStatusId,@rHostelId,@rStudentGroupId,
				@rStudentOtherGroupId,@rFeeExemption,@rRecordTagId
			)
		END
		
		
		IF(@rId > 0)
		BEGIN
			Select @rColumnName=ColumnName,@rOrderBy=OrderBy,@rOrgId=OrgId,@rSpecificCode=Code,@rFirstName=FirstName,
			@rLastName=LastName,@rCountry=Country,@rState=State,@rCity=City,@rArea=Area,@rDivisionId=DivisionId,
			@rStatusId=StatusId,@rTransportModeId=TransportModeId,@rBusRouteDestinationId=BusRouteDestinationId,
			@rBloodGroupId=BloodGroupId,@rGenderId=GenderId,@rReligionId=ReligionId,@rCastCategoryId=CastCategoryId,
			@rHouseId=HouseId,@rMotherTongueId=MotherTongueId,@rNationalityId=NationalityId,@rHobby=Hobby,
			@rFatherQualification=FatherQualification,@rMotherQualification=MotherQualification,
			@rFatherOccupation=FatherOccupation,@rMotherOccupation=MotherOccupation,
			@rPreviousSchool=PreviousSchool,@rAdmissionCategoryId=AdmissionCategoryId,
			@rDOBFromDate=DOBFromDate,@rDOBToDate=DOBToDate,@rDOAFromDate=DOAFromDate,
			@rDOAToDate=DOAToDate,@rDOLFromDate=DOLFromDate,@rDOLToDate=DOLToDate,
			@rIsPysicalDeformity=IsPysicalDeformity,@rIsMajorIllness=IsMajorIllness,
			@rIsBlackList=IsBlackList,@rFromCode=FromCode,@rToCode=ToCode,
			@rCustomTagId=CustomTag,@rCustomGroupId = CustomGroup,@rClubId = Club,
			@rRepeatCount = RepeatCount,@rStudentStatusId =StudentStatusId,
			@rHostelId = Hostel,@rStudentGroupId = StudentGroup,
			@rStudentOtherGroupId = StudentOtherGroup,@rFeeExemption =FeeExemption,
			@rRecordTagId=RecordTag
			FROM sStudent.tStudentCustomSearch WHERE Id=@rId
		END
		
		DECLARE @ListofCodes TABLE(Code nvarchar(25), ID INT IDENTITY(1,1));
			INSERT INTO @ListofCodes
	     
		SELECT q2.value from
			(SELECT cast('<x>'+replace(@rSpecificCode,',','</x><x>')+'</x>' as xml) as thexml)q1 CROSS APPLY
			(SELECT x.value('.','nvarchar(max)') as value FROM thexml.nodes('x') as f(x))q2
		
		SET @rOrderBy=Replace(@rOrderBy,'GR No','Code')
		SET @rOrderBy=Replace(@rOrderBy,'ID No','Code')
		SET @rColumnName=Replace(@rColumnName,'GR No','Code')
		SET @rColumnName=Replace(@rColumnName,'ID No','Code')
		SET @rColumnName=Replace(@rColumnName,'PhysicalDeformityRemark','PysicalDeformityRemark')
		SET @rColumnName=Replace(@rColumnName,'IsPhysicalDeformity','IsPysicalDeformity')
		SET @rOrderBy=Replace(@rOrderBy,'PhysicalDeformityRemark','PysicalDeformityRemark')
		SET @rOrderBy=Replace(@rOrderBy,'IsPhysicalDeformity','IsPysicalDeformity')
		
		DECLARE @Sql nvarchar(MAX)= ''
		
		SET @rSpecificCode = sCommon.fSearchStringGet(@rSpecificCode)
		SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
		SET @rLastName = sCommon.fSearchStringGet(@rLastName)
		SET @rCountry = sCommon.fSearchStringGet(@rCountry)
		SET @rState = sCommon.fSearchStringGet(@rState)
		
		 IF  EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='tTempStudent1')
		 BEGIN
			DROP Table sStudent.tTempStudent1
		 END
		 IF  EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='tTempStudent2')
		 BEGIN		
			DROP Table sStudent.tTempStudent2
		 END
		 IF  EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='tTempStudent3')
		 BEGIN
			DROP Table sStudent.tTempStudent3
		 END
		 IF  EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='tTempStudent4')
		 BEGIN
			DROP Table sStudent.tTempStudent4
		 END
		 IF  EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='tTempStudent5')
		 BEGIN
			DROP Table sStudent.tTempStudent5  
		 END
		 IF  EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='tTempStudent6')
		 BEGIN
			DROP Table sStudent.tTempStudent6
		 END
		 
		 IF  EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='tTempStudent7')
		 BEGIN
			DROP Table sStudent.tTempStudent7
		 END
		 
		 IF  EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='tTempStudent8')
		 BEGIN
			DROP Table sStudent.tTempStudent8
		 END
		 IF  EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='tTempStudent9')
		 BEGIN
			DROP Table sStudent.tTempStudent9
		 END
		 IF  EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='tTempStudent10')
		 BEGIN
			DROP Table sStudent.tTempStudent10
		 END
		 IF  EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='tTempStudent11')
		 BEGIN
			DROP Table sStudent.tTempStudent11
		 END
		 IF  EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='tTempStudent12')
		 BEGIN
			DROP Table sStudent.tTempStudent12
		 END
		 IF  EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='tTempStudent13')
		 BEGIN
			DROP Table sStudent.tTempStudent13
		 END
		  IF  EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='tTempStudent14')
		 BEGIN
			DROP Table sStudent.tTempStudent14
		 END
		
		SELECT  DISTINCT SM.Id AS StudentId6,
		CASE WHEN SF.IsFatherExStudent = 0 THEN 'No' WHEN SF.IsFatherExStudent = 1 THEN 'Yes' ELSE '' END AS IsFatherExStudent,
		CASE WHEN SF.IsMotherExStudent = 0 THEN 'No' WHEN SF.IsMotherExStudent = 1 THEN 'Yes' ELSE '' END AS IsMotherExStudent,
		SF.FatherOrganization, SF.FatherDesignation, SF.MotherOrganization, SF.MotherDesignation, SF.RelativeOrganization, SF.RelativeDesignation
		INTO sStudent.tTempStudent11
		FROM sStudent.tStudentMaster SM
			 INNER JOIN sStudent.tAcademic A ON A.StudentId = SM.Id AND SM.OrgId = @rOrgId AND A.BatchId=@BatchId
			 INNER JOIN sStudent.tStudentFamily SF ON SF.StudentId = SM.Id
	
		-- For Left Detail
		SELECT DISTINCT  SA.StudentId AS StudentId12,InactiveDate,InActiveReason,LCBook,--LeftStandardId,
		CM.Title AS LeftStandard,
		CONVERT(VARCHAR(10),LCDate,111) AS LCDate,LCCopy,LeftReason,LCProgress,
		LCConduct,LCRemark 
		INTO sStudent.tTempStudent12
		FROM sStudent.tStudentAdmission SA
		     INNER JOIN sStudent.tAcademic A ON A.StudentId = SA.StudentId AND A.OrgId = @rOrgId AND A.BatchId=@BatchId
		     LEFT JOIN sSetup.tClassMaster CM ON CM.Id = SA.LeftStandardId
		
		-- For Custom Tag
		IF (@rCustomTagId <> '')
		BEGIN
			SELECT DISTINCT SM.Id AS StudentId1
			INTO sStudent.tTempStudent5
			FROM sStudent.tStudentMaster SM
			INNER JOIN sStudent.tStudentCustomTag SCT ON SCT.StudentId=SM.Id
			INNER JOIN sStudent.tAcademic A ON A.StudentId = SM.Id
			WHERE SM.OrgId = @rOrgId  AND A.BatchId = @BatchId
			AND (ISNULL(SCT.CustomTagId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rCustomTagId,','))OR @rCustomTagId='')
		END
		ELSE
		BEGIN
			SELECT DISTINCT NULL AS StudentId1
			INTO sStudent.tTempStudent5
		END
		
		-- For Custom Group
		IF (@rCustomGroupId <> '')
		BEGIN
			SELECT DISTINCT SM.Id AS StudentId2
			INTO sStudent.tTempStudent6
			FROM sStudent.tStudentMaster SM
			INNER JOIN sStudent.tAcademic A ON A.StudentId = SM.Id
			INNER JOIN sCommunication.tCustomGroupMember CGM ON CGM.SourceId = A.Id AND CGM.SourceTypeId=2001
			WHERE SM.OrgId = @rOrgId  AND A.BatchId = @BatchId
			AND (ISNULL(CGM.CustomGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rCustomGroupId,','))OR @rCustomGroupId='')
		END
		ELSE
		BEGIN
			SELECT DISTINCT NULL AS StudentId2
			INTO sStudent.tTempStudent6
		END
		
		-- For Club Group
		IF (@rClubId <> '')
		BEGIN
			SELECT DISTINCT SM.Id AS StudentId3
			INTO sStudent.tTempStudent7
			FROM sStudent.tStudentMaster SM
			INNER JOIN sStudent.tAcademic A ON A.StudentId = SM.Id
			INNER JOIN sActivity.tAssignClub AC ON AC.AcademicId = A.Id
			WHERE SM.OrgId = @rOrgId  AND A.BatchId = @BatchId
			AND (ISNULL(AC.ClubId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClubId,','))OR @rClubId='')
		END
		ELSE
		BEGIN
			SELECT DISTINCT NULL AS StudentId3
			INTO sStudent.tTempStudent7
		END
		
		-- For Hostel
		IF (@rHostelId <> '')
		BEGIN
			SELECT DISTINCT SM.Id AS StudentId4
			INTO sStudent.tTempStudent9
			FROM sStudent.tStudentMaster SM
			INNER JOIN sStudent.tAcademic A ON A.StudentId = SM.Id
			INNER JOIN sHostel.tAssignRoom AR ON AR.SourceId = A.StudentId
			AND ((AR.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
			INNER JOIN sHostel.tRoomMaster RM ON RM.Id = AR.RoomId
			WHERE SM.OrgId = @rOrgId
			AND (ISNULL(RM.HostelId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rHostelId,','))OR @rHostelId='')
		END
		ELSE
		BEGIN
			SELECT DISTINCT NULL AS StudentId4
			INTO sStudent.tTempStudent9
		END
		
		--Transport
		IF (@rBusRouteId <> '')
		BEGIN
			SELECT DISTINCT SM.Id AS StudentId5
			INTO sStudent.tTempStudent10
			FROM sStudent.tStudentMaster SM
			INNER JOIN sStudent.tAcademic A ON A.StudentId = SM.Id
			INNER JOIN sTransport.tAssignRoute AT ON AT.SourceId = A.StudentId
			INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id = AT.PickupDestinationId
			INNER JOIN sTransport.tBusRouteMaster BRM ON BRM.Id = BM.BusRouteId
			AND ((BRM.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
			WHERE SM.OrgId = @rOrgId 
			AND (ISNULL(BRM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rBusRouteId,','))OR @rBusRouteId='')
		END
		ELSE
		BEGIN
			SELECT DISTINCT NULL AS StudentId5
			INTO sStudent.tTempStudent10
			
			
		END
		-- For Record Tag
		IF (@rRecordTagId <> '')
		BEGIN
			SELECT DISTINCT SM.Id AS StudentId14		
			INTO sStudent.tTempStudent14
			FROM sStudent.tStudentMaster SM
			INNER JOIN sStudent.tAcademic A ON A.StudentId = SM.Id
			WHERE SM.OrgId = @rOrgId  AND A.BatchId = @BatchId
			AND (ISNULL(SM.RecordStatusId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rRecordTagId,','))OR @rRecordTagId='')
		END
		ELSE
		BEGIN
		
			SELECT DISTINCT NULL AS StudentId14
			INTO sStudent.tTempStudent14
		END
		
		SET @rColumnName=Replace(@rColumnName,'GR No','Code')
		SET @rColumnName=Replace(@rColumnName,'ID No','Code')
		--if @rColumnName <> ''
		--begin
		--	select @rColumnName = left(@rColumnName,len(@rColumnName)-1)
		--end
		--print 'asdasda'
		    DECLARE @lAvailableStudentColumns nvarchar(max)=''
			DECLARE @lAvailableStudentCustomRes nvarchar(max)=''
			Declare @Title as nvarchar(max)
			DECLARE @cols AS NVARCHAR(MAX),@query  AS NVARCHAR(MAX)
		
          --BEGIN  
		   
		   --drop table sStudent.tTempStudent13

             
			--print @BatchId
			--print @rOrgId
            DECLARE @rOrgGroupId smallint
             SET @rOrgGroupId = (Select orggroupid from sSetup.tOrganizationMaster where Id=@rOrgId)           
             
			SET @lAvailableStudentColumns=   STUFF((SELECT ',' + QUOTENAME(PP.FieldTitle,'[]'), '' AS FieldTitle, '' AS SalaryMonth
								from sStudent.tStudentCustomFieldMaster PP  WHERE PP.OrgGroupId = @rOrgGroupId  
						FOR XML PATH(''), TYPE
						).value('.', 'NVARCHAR(MAX)') 
					,1,1,'')
					Print @lAvailableStudentColumns
	        IF(@lAvailableStudentColumns IS NOT NULL)
	        BEGIN
				set @query = 'SELECT  StudentId AS StudentId13 ,' + @lAvailableStudentColumns + ' into sStudent.tTempStudent13 from 
					 (
						select PPE.FieldTitle,PP.StudentId,FieldData 
						FROM
						sStudent.tStudentCustomFieldData PP 
							INNER JOIN sStudent.tStudentCustomFieldMaster PPE ON PPE.Id = PP.StudentCustomFieldId AND PPE.IsObsolete=0
							INNER JOIN sStudent.tStudentMaster SM ON SM.Id = PP.StudentId						
							INNER JOIN sStudent.tAcademic A ON A.StudentId = SM.Id AND A.BatchId='+convert(varchar(20),@BatchId)+' 
							WHERE SM.OrgId='''+convert(varchar(20),@rOrgId)+''' 
					) x 
					pivot 
					(
						Max(FieldData)
						for FieldTitle in (' +@lAvailableStudentColumns  + ')
					) p'

				 --print @query
                execute(@query)
		   
		   
		
		Select * into sStudent.tTempStudent
		FROM sStudent.vStudentCustomSearch SCS
		INNER JOIN sStudent.tTempStudent5 T5 ON SCS.StudentId = T5.StudentId1 OR @rCustomTagId = ''
		INNER JOIN sStudent.tTempStudent6 T6 ON SCS.StudentId = T6.StudentId2 OR @rCustomGroupId = ''
		INNER JOIN sStudent.tTempStudent7 T7 ON SCS.StudentId = T7.StudentId3 OR @rClubId = ''
		INNER JOIN sStudent.tTempStudent9 T9 ON SCS.StudentId = T9.StudentId4 OR @rHostelId = ''
		INNER JOIN sStudent.tTempStudent10 T10 ON SCS.StudentId = T10.StudentId5 OR @rBusRouteId = ''
		LEFT JOIN sStudent.tTempStudent11 T11 ON SCS.StudentId = T11.StudentId6
		LEFT JOIN  sStudent.tTempStudent12 T12 ON SCS.StudentId= T12.StudentId12 
		LEFT JOIN  sStudent.tTempStudent13 T13 ON SCS.StudentId= T13.StudentId13 
		INNER JOIN sStudent.tTempStudent14 T14 ON SCS.StudentId = T14.StudentId14 OR @rRecordTagId = ''
		WHERE SCS.OrgId = @rOrgId 
		AND ((SCS.BatchId = @BatchId) OR (@BatchId = 0)) 
		--AND ((SCS.Code Like @rCode + '%') OR (@rCode = ''))
		AND ((SCS.FirstName Like @rFirstName  + '%') OR (@rFirstName = ''))
		AND ((SCS.LastName Like @rLastName + '%')OR(@rLastName = ''))
		AND ((SCS.Hobby Like '%' + @rHobby + '%') OR (@rHobby = ''))
		AND ((ISNULL(SCS.PermanentCountry,'') Like @rCountry + '%') OR(@rCountry = ''))
		AND ((ISNULL(SCS.PermanentState,'') Like @rState + '%')OR(@rState = ''))
		AND ((ISNULL(SCS.DateOfBirth,'0001-01-01') >= @rDOBFromDate) OR (ISNULL(@rDOBFromDate,'') = ''))
		AND ((ISNULL(SCS.DateOfBirth,'9999-12-31') <= @rDOBToDate) OR (ISNULL(@rDOBToDate,'') = ''))
		AND ((ISNULL(SCS.AdmissionDate,'0001-01-01') >= @rDOAFromDate) OR (ISNULL(@rDOAFromDate,'') = ''))
		AND ((ISNULL(SCS.AdmissionDate,'9999-12-31') <= @rDOAToDate) OR (ISNULL(@rDOAToDate,'') = ''))
		AND ((ISNULL(SCS.LeftDate,'0001-01-01') >= @rDOLFromDate) OR (ISNULL(@rDOLFromDate,'') = ''))
		AND ((ISNULL(SCS.LeftDate,'9999-12-31') <= @rDOLToDate) OR (ISNULL(@rDOLToDate,'') = ''))
		AND (ISNULL(SCS.PermanentCity,0) IN( SELECT item FROM  sCommon.fnsplit(@rCity,','))OR @rCity='')
		AND (ISNULL(SCS.PermanentStreetThree,0) IN( SELECT item FROM  sCommon.fnsplit(@rArea,','))OR @rArea='')
		AND (SCS.DivisionId In( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionId,','))OR @rDivisionId='')
		AND (SCS.StatusId In( SELECT cast(item as int) FROM  sCommon.fnsplit(@rStatusId,','))OR @rStatusId='')
		AND (SCS.TransportModeId In( SELECT cast(item as int) FROM  sCommon.fnsplit(@rTransportModeId,','))OR @rTransportModeId='')
		AND (ISNULL(SCS.BloodGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rBloodGroupId,','))OR @rBloodGroupId='')
		AND (ISNULL(SCS.GenderId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rGenderId,','))OR (@rGenderId=''))
		AND (ISNULL(SCS.ReligionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rReligionId,','))OR @rReligionId='')
		AND (ISNULL(SCS.CastCategoryId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rCastCategoryId,','))OR @rCastCategoryId='')
		AND (ISNULL(SCS.HouseId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rHouseId,','))OR @rHouseId='')
		AND (ISNULL(SCS.MotherTongueId,0) IN ( SELECT cast(item as int) FROM  sCommon.fnsplit(@rMotherTongueId,','))OR @rMotherTongueId='')
		AND (ISNULL(SCS.NationalityId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rNationalityId,','))OR @rNationalityId='')
		AND (ISNULL(SCS.BusRouteDestinationId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rBusRouteDestinationId,','))OR @rBusRouteDestinationId='')
		AND (ISNULL(SCS.FatherQualification,'') IN( SELECT item FROM  sCommon.fnsplit(@rFatherQualification,','))OR @rFatherQualification='')
		AND (ISNULL(SCS.FatherOccupation,'') IN( SELECT item FROM  sCommon.fnsplit(@rFatherOccupation,','))OR @rFatherOccupation='')
		AND (ISNULL(SCS.MotherQualification,'') IN( SELECT item FROM  sCommon.fnsplit(@rMotherQualification,','))OR @rMotherQualification='')
		AND (ISNULL(SCS.MotherOccupation,'') IN( SELECT item FROM  sCommon.fnsplit(@rMotherOccupation,','))OR @rMotherOccupation='')
		AND (ISNULL(SCS.AdmissionCategoryId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rAdmissionCategoryId,','))OR @rAdmissionCategoryId='')
		AND (ISNULL(SCS.PreviousSchool,'') IN( SELECT item FROM  sCommon.fnsplit(@rPreviousSchool,','))OR @rPreviousSchool='')
		AND (ISNULL(SCS.RepeatCount,0) IN( SELECT item FROM  sCommon.fnsplit(@rRepeatCount,','))OR @rRepeatCount='')
		AND (ISNULL(SCS.StudentStatusId,0) IN( SELECT item FROM  sCommon.fnsplit(@rStudentStatusId,','))OR @rStudentStatusId='')
		AND (ISNULL(SCS.StudentGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rStudentGroupId,','))OR @rStudentGroupId='')
		AND (ISNULL(SCS.StudentOtherGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rStudentOtherGroupId,','))OR @rStudentOtherGroupId='')
		AND ((SCS.IsPysicalDeformity=@rIsPysicalDeformity) OR (@rIsPysicalDeformity=0))
		AND ((SCS.IsMajorIllness=@rIsMajorIllness) OR (@rIsMajorIllness=0))
		AND ((SCS.IsBlackList=@rIsBlackList) OR (@rIsBlackList=0))
		AND ((SCS.Code >= @rFromCode) OR (@rFromCode=0))
		AND ((SCS.Code <= @rToCode) OR (@rToCode=0))
		AND ((SCS.Code IN(SELECT Code FROM @ListofCodes)) OR (ISNULL(@rSpecificCode,'') = ''))
		AND ((SCS.StatusId = @rDropDownStatusId) OR (@rDropDownStatusId=0))
		AND ((SCS.ClassId = @rDropDownClassId) OR (@rDropDownClassId=0))
		AND ((SCS.DivisionId = @rDropDownDivisionId) OR (@rDropDownDivisionId=0))
		AND (ISNULL(SCS.BusRouteId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rBusRouteId,','))OR @rBusRouteId='')
		AND (ISNULL(SCS.ExemptionTypeId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeExemption,','))OR @rFeeExemption='')
		
		--AND (ISNULL(SCS.CustomTagId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rCustomTagId,','))OR @rCustomTagId='')
		--Select * from sStudent.tTempStudent return	
		
				
				
		set @sql = 'SELECT '+ @rColumnName+' FROM sStudent.tTempStudent ORDER BY '+@rOrderBy
		
		if(@rColumnName='ID No')
		BEGIN
			SET @sql=Replace(@sql,'SELECT Code','SELECT Code AS [ID No]')
		END
		if(@rColumnName='GR No')
		BEGIN
			SET @sql=Replace(@sql,'SELECT Code','SELECT Code AS [GR No]')
		END
		
		exec(@Sql)
			
		DROP Table sStudent.tTempStudent
		DROP Table sStudent.tTempStudent5
		DROP Table sStudent.tTempStudent6
		DROP Table sStudent.tTempStudent7
		DROP Table sStudent.tTempStudent9
		DROP Table sStudent.tTempStudent10
		DROP Table sStudent.tTempStudent12
		DROP Table sStudent.tTempStudent13
		DROP Table sStudent.tTempStudent14
 
	END 
	 
	ELSE
	BEGIN
	    Select * into sStudent.tTempStudent
		FROM sStudent.vStudentCustomSearch SCS
		INNER JOIN sStudent.tTempStudent5 T5 ON SCS.StudentId = T5.StudentId1 OR @rCustomTagId = ''
		INNER JOIN sStudent.tTempStudent6 T6 ON SCS.StudentId = T6.StudentId2 OR @rCustomGroupId = ''
		INNER JOIN sStudent.tTempStudent7 T7 ON SCS.StudentId = T7.StudentId3 OR @rClubId = ''
		INNER JOIN sStudent.tTempStudent9 T9 ON SCS.StudentId = T9.StudentId4 OR @rHostelId = ''
		INNER JOIN sStudent.tTempStudent10 T10 ON SCS.StudentId = T10.StudentId5 OR @rBusRouteId = ''
		LEFT JOIN sStudent.tTempStudent11 T11 ON SCS.StudentId = T11.StudentId6
		LEFT JOIN  sStudent.tTempStudent12 T12 ON SCS.StudentId= T12.StudentId12 
		INNER JOIN sStudent.tTempStudent14 T14 ON SCS.StudentId = T14.StudentId14 OR @rRecordTagId = ''
		
		WHERE SCS.OrgId = @rOrgId 
		AND ((SCS.BatchId = @BatchId) OR (@BatchId = 0)) 
		--AND ((SCS.Code Like @rCode + '%') OR (@rCode = ''))
		AND ((SCS.FirstName Like @rFirstName  + '%') OR (@rFirstName = ''))
		AND ((SCS.LastName Like @rLastName + '%')OR(@rLastName = ''))
		AND ((SCS.Hobby Like '%' + @rHobby + '%') OR (@rHobby = ''))
		AND ((ISNULL(SCS.PermanentCountry,'') Like @rCountry + '%') OR(@rCountry = ''))
		AND ((ISNULL(SCS.PermanentState,'') Like @rState + '%')OR(@rState = ''))
		AND ((ISNULL(SCS.DateOfBirth,'0001-01-01') >= @rDOBFromDate) OR (ISNULL(@rDOBFromDate,'') = ''))
		AND ((ISNULL(SCS.DateOfBirth,'9999-12-31') <= @rDOBToDate) OR (ISNULL(@rDOBToDate,'') = ''))
		AND ((ISNULL(SCS.AdmissionDate,'0001-01-01') >= @rDOAFromDate) OR (ISNULL(@rDOAFromDate,'') = ''))
		AND ((ISNULL(SCS.AdmissionDate,'9999-12-31') <= @rDOAToDate) OR (ISNULL(@rDOAToDate,'') = ''))
		AND ((ISNULL(SCS.LeftDate,'0001-01-01') >= @rDOLFromDate) OR (ISNULL(@rDOLFromDate,'') = ''))
		AND ((ISNULL(SCS.LeftDate,'9999-12-31') <= @rDOLToDate) OR (ISNULL(@rDOLToDate,'') = ''))
		AND (ISNULL(SCS.PermanentCity,0) IN( SELECT item FROM  sCommon.fnsplit(@rCity,','))OR @rCity='')
		AND (ISNULL(SCS.PermanentStreetThree,0) IN( SELECT item FROM  sCommon.fnsplit(@rArea,','))OR @rArea='')
		AND (SCS.DivisionId In( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionId,','))OR @rDivisionId='')
		AND (SCS.StatusId In( SELECT cast(item as int) FROM  sCommon.fnsplit(@rStatusId,','))OR @rStatusId='')
		AND (SCS.TransportModeId In( SELECT cast(item as int) FROM  sCommon.fnsplit(@rTransportModeId,','))OR @rTransportModeId='')
		AND (ISNULL(SCS.BloodGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rBloodGroupId,','))OR @rBloodGroupId='')
		AND (ISNULL(SCS.GenderId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rGenderId,','))OR (@rGenderId=''))
		AND (ISNULL(SCS.ReligionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rReligionId,','))OR @rReligionId='')
		AND (ISNULL(SCS.CastCategoryId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rCastCategoryId,','))OR @rCastCategoryId='')
		AND (ISNULL(SCS.HouseId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rHouseId,','))OR @rHouseId='')
		AND (ISNULL(SCS.MotherTongueId,0) IN ( SELECT cast(item as int) FROM  sCommon.fnsplit(@rMotherTongueId,','))OR @rMotherTongueId='')
		AND (ISNULL(SCS.NationalityId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rNationalityId,','))OR @rNationalityId='')
		AND (ISNULL(SCS.BusRouteDestinationId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rBusRouteDestinationId,','))OR @rBusRouteDestinationId='')
		AND (ISNULL(SCS.FatherQualification,'') IN( SELECT item FROM  sCommon.fnsplit(@rFatherQualification,','))OR @rFatherQualification='')
		AND (ISNULL(SCS.FatherOccupation,'') IN( SELECT item FROM  sCommon.fnsplit(@rFatherOccupation,','))OR @rFatherOccupation='')
		AND (ISNULL(SCS.MotherQualification,'') IN( SELECT item FROM  sCommon.fnsplit(@rMotherQualification,','))OR @rMotherQualification='')
		AND (ISNULL(SCS.MotherOccupation,'') IN( SELECT item FROM  sCommon.fnsplit(@rMotherOccupation,','))OR @rMotherOccupation='')
		AND (ISNULL(SCS.AdmissionCategoryId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rAdmissionCategoryId,','))OR @rAdmissionCategoryId='')
		AND (ISNULL(SCS.PreviousSchool,'') IN( SELECT item FROM  sCommon.fnsplit(@rPreviousSchool,','))OR @rPreviousSchool='')
		AND (ISNULL(SCS.RepeatCount,0) IN( SELECT item FROM  sCommon.fnsplit(@rRepeatCount,','))OR @rRepeatCount='')
		AND (ISNULL(SCS.StudentStatusId,0) IN( SELECT item FROM  sCommon.fnsplit(@rStudentStatusId,','))OR @rStudentStatusId='')
		AND (ISNULL(SCS.StudentGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rStudentGroupId,','))OR @rStudentGroupId='')
		AND (ISNULL(SCS.StudentOtherGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rStudentOtherGroupId,','))OR @rStudentOtherGroupId='')
		AND ((SCS.IsPysicalDeformity=@rIsPysicalDeformity) OR (@rIsPysicalDeformity=0))
		AND ((SCS.IsMajorIllness=@rIsMajorIllness) OR (@rIsMajorIllness=0))
		AND ((SCS.IsBlackList=@rIsBlackList) OR (@rIsBlackList=0))
		AND ((SCS.Code >= @rFromCode) OR (@rFromCode=0))
		AND ((SCS.Code <= @rToCode) OR (@rToCode=0))
		AND ((SCS.Code IN(SELECT Code FROM @ListofCodes)) OR (ISNULL(@rSpecificCode,'') = ''))
		AND ((SCS.StatusId = @rDropDownStatusId) OR (@rDropDownStatusId=0))
		AND ((SCS.ClassId = @rDropDownClassId) OR (@rDropDownClassId=0))
		AND ((SCS.DivisionId = @rDropDownDivisionId) OR (@rDropDownDivisionId=0))
		AND (ISNULL(SCS.BusRouteId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rBusRouteId,','))OR @rBusRouteId='')
		AND (ISNULL(SCS.ExemptionTypeId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeExemption,','))OR @rFeeExemption='')
		
		--AND (ISNULL(SCS.CustomTagId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rCustomTagId,','))OR @rCustomTagId='')
		--Select * from sStudent.tTempStudent return	
		
				
				--Select * From sStudent.tTempStudent
		set @sql = 'SELECT '+ @rColumnName+' FROM sStudent.tTempStudent ORDER BY '+@rOrderBy
		
		
		if(@rColumnName='ID No')
		BEGIN
			SET @sql=Replace(@sql,'SELECT Code','SELECT Code AS [ID No]')
		END
		if(@rColumnName='GR No')
		BEGIN
			SET @sql=Replace(@sql,'SELECT Code','SELECT Code AS [GR No]')
		END
		
		exec(@Sql)
			
		DROP Table sStudent.tTempStudent
		DROP Table sStudent.tTempStudent5
		DROP Table sStudent.tTempStudent6
		DROP Table sStudent.tTempStudent7
		DROP Table sStudent.tTempStudent9
		DROP Table sStudent.tTempStudent10
		DROP Table sStudent.tTempStudent12
		
	    
	    
	END 
	 
	 
END
GO
PRINT N'Altering [sStudent].[pStudentProfileGet]...';


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

BEGIN 
	
	SELECT 
			--SA.FirstName + ' ' + ISNULL(SA.MiddleName,'') + ' ' + 	SA.LastName AS StudentName,
			SA.Name  AS StudentName,
			SA.Batch AS AcademicYear,
			ISNULL(SA.Code,'') AS Code,
			SA.DateOfBirth,
			SA.RollNo,
			ISNULL(SA.BirthPlace,'-') AS BirthPlace,
			SA.ClassDivision AS ClassDiv,
			SA.StudentId AS Id,
			--SA.GenderId			
			ISNULL(SM.Title,'-') AS House,
			ISNULL(SA.BloodGroup,'-') AS BloodGroup,
	   	    ISNULL(SA.StudentPhoto, CONVERT(VARBINARY(MAX), 0)) AS StudentPhoto,
			ISNULL(SA.PresentStreetone,'') + ' ' + ISNULL(SA.PresentStreetTwo,'') + ' ' + ISNULL(SA.PresentStreetThree,'') AS PresentAddress,
			ISNULL(SA.PresentCity,'-') AS City,
			ISNULL(SA.PresentState,'-') As State,
			ISNULL(SA.PresentZipCode,'-') as PinCode,
			ISNULL(SA.PresentCountry,'-') AS Country,
			ISNULL(SA.PresentContactNo,'-') as ContactNo,
			ISNULL(SF.FatherName,'-') AS FatherName,
			ISNULL(SF.FatherOccupation,'-') AS Occupation,
			ISNULL(SF.FatherQualification,'-') AS Qualification,
			SA.Gender,
			ISNULL(SF.FatherContactNo,'-') AS FatherContactNo,
			ISNULL(SF.FatherMail,'-') AS FatherMail,
			ISNULL(SF.FatherOfficeAddress,'-') AS FatherOfficeAddress,
			ISNULL(SA.ParentEmail,'-') AS ParentEmail,
			ISNULL(SA.ParentContactNo,'-') AS ParentContactNo,
			ISNULL(SA.DepartmentId,0) AS DepartmentId,
			ISNULL(SA.ClassId,0) AS ClassId,
			ISNULL(SA.DivisionId,0) AS DivisionId,
			OM.DisplayTitle AS OrgTitle,
			ISNULL(SA.SUId,SA.Code) AS SUId
  FROM 
           sStudent.vStudentAllDetail SA
           --LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
           LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SA.StudentId 
           ----AND SF.RelationshipId = 1
           --LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId = SA.StudentId
           LEFT JOIN sActivity.tHouseMaster SM ON SM.ID = SA.HouseId
           --LEFT JOIN sCommon.tGenderMaster GM ON GM.ID = SO.GenderId
           INNER JOIN sSetup.tOrganizationMaster OM 
			ON OM.Id=SA.OrgId  
             
  WHERE 
			--((SA.StudentId=@rStudentId)OR(@rStudentId=0))
			SA.StudentId=@rStudentId
			AND(SA.BatchId=@rBatchId)
			
 
  
		
END
GO
PRINT N'Altering [sWorkflow].[pStudentDataChangeApprove]...';


GO


ALTER  PROCEDURE [sWorkflow].[pStudentDataChangeApprove]
			@rId Bigint = 0,
			@rUpdateFieldId int=0,
			@rSourceTypeId int,
			@rSourceId BigInt,
			@rOldValue NVarchar(500)='',
			@rNewValue NVarchar(500)='',
			@rActionRemark nvarchar(500) = '',
			@rActionUserId BigInt,
			@rActionDateTime DateTime,
			@rStatusId int,
			@rRequestId int =0
			 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

	BEGIN
	BEGIN TRY
	
	BEGIN TRANSACTION

		IF EXISTS(SELECT 1 FROM sStudent.vStudentAcademic WHERE AcademicId = @rId)
		BEGIN
		    
			DECLARE @lResult int
			DECLARE @lDataTypeId nvarchar(1)
			SELECT @lDataTypeId=DataTypeId FROM sCommon.tUpdateFieldMaster WHERE Id=@rUpdateFieldId

			DECLARE @lUpdateField NVARCHAR(100)
			DECLARE @lSubFunctionality NVARCHAR(100)
			DECLARE @lStudentId BigInt

			SET @lUpdateField = (SELECT Field FROM sCommon.tUpdateFieldMaster WHERE Id = @rUpdateFieldId)
			SET @lSubFunctionality = (SELECT SubFunctionalityName FROM sCommon.tUpdateFieldMaster WHERE Id = @rUpdateFieldId)
			SET @lStudentId = (SELECT StudentId FROM sStudent.vStudentAcademic WHERE AcademicId = @rId)

			IF(@lUpdateField = 'Gender' OR @lUpdateField = 'Religion'OR @lUpdateField = 'Nationality')
			BEGIN
			SET @lUpdateField =@lUpdateField + 'Id'
			END

			IF(@lUpdateField = 'CasteCategory' )
			BEGIN
			SET @lUpdateField = Replace(@lUpdateField,'Caste','Cast') + 'Id'
			END
			

			Declare @Sql nvarchar(max)

			IF OBJECT_ID('ListofData') IS NOT NULL	
			BEGIN 
				DROP TABLE ListofData
			END	
			
			IF(@rStatusId = 550)
			BEGIN
			CREATE TABLE ListofData(Id bigint,StudentId bigint,SubCategory nvarchar(150),UpdatedUserId bigint,IsExist bit);
			insert into ListofData VALUES (@rId,@lStudentId,@rNewValue,@rActionUserId,0)

			UPDATE ListofData SET IsExist=1 WHERE StudentId NOT IN(SELECT StudentId FROM sStudent.tStudentCommunication)

			
			IF(@lSubFunctionality = 'Communication')  ----Communication
				BEGIN
			
				set @sql='INSERT INTO sStudent.tStudentCommunication 
							(StudentId,'+@lUpdateField+',CreatedUserId,CreatedDateTime)
							SELECT
								LD.StudentId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
							FROM
								ListofData LD WHERE LD.IsExist=1'
					
				print @sql		
				Exec sp_executesql @sql
				set @sql='UPDATE sStudent.tStudentCommunication set '+@lUpdateField+' = 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
					 SET @lResult = 1;
				END

			Else IF(@lSubFunctionality = 'Other')         -------Other
				BEGIN
					IF(@lUpdateField = 'DateOfBirth')
					BEGIN			
						set @sql='INSERT INTO sStudent.tStudentOther 
								(StudentId,'+@lUpdateField+',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 '+@lUpdateField+' = 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 '+@lUpdateField+' = null WHERE DateOfBirth=''1900-01-01'''
						Exec sp_executesql @sql
					END
					ELSE
					BEGIN
						set @sql='INSERT INTO sStudent.tStudentOther 
									(StudentId,'+@lUpdateField+',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 '+@lUpdateField+' = 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
						 SET @lResult = 1;
				 END	

				Else IF(@lSubFunctionality = 'Admission')		--------Admission
					BEGIN
					
					set @sql='UPDATE sStudent.tStudentAdmission set '+@lUpdateField+' = 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
							SET @lResult = 1;
					END	

				Else IF(@lSubFunctionality = 'Family')			---------Family
					BEGIN
						
						UPDATE ListofData SET IsExist=1 WHERE StudentId NOT IN(SELECT StudentId FROM sStudent.tStudentFamily) 
		
						set @sql='INSERT INTO sStudent.tStudentFamily 
									(StudentId,'+@lUpdateField+',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 '+@lUpdateField+' = 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
							 SET @lResult = 1;
						END

			  Else IF(@lSubFunctionality = 'General')	   ----------General
					 BEGIN
						IF(@lUpdateField != 'AdmissionCategoryId')
						BEGIN
							
							UPDATE ListofData SET IsExist=1 WHERE StudentId NOT IN(SELECT Id FROM sStudent.tStudentMaster) 
			
							set @sql='UPDATE sStudent.tStudentMaster set '+@lUpdateField+' = 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
						END
						 SET @lResult = 1;
					END			 
	 
			IF(@lResult = 1)
			BEGIN
				UPDATE sWorkFlow.tStudentDataChange
				SET
					StatusId = @rStatusId
					,ActionRemark = @rActionRemark
					,ActionUserId = @rActionUserId
					,ActionDateTime = @rActionDateTime
				WHERE 
					AutoId = @rRequestId
			END
			SELECT 1 AS Result
			END
			ELSE IF(@rStatusId = 551)
			BEGIN
			CREATE TABLE ListofData(Id bigint,StudentId bigint,SubCategory nvarchar(150),UpdatedUserId bigint,IsExist bit);
			insert into ListofData VALUES (@rId,@lStudentId,@rOldValue,@rActionUserId,0)

			UPDATE ListofData SET IsExist=1 WHERE StudentId NOT IN(SELECT StudentId FROM sStudent.tStudentCommunication)

			
			IF(@lSubFunctionality = 'Communication')  ----Communication
				BEGIN
			
				set @sql='INSERT INTO sStudent.tStudentCommunication 
							(StudentId,'+@lUpdateField+',CreatedUserId,CreatedDateTime)
							SELECT
								LD.StudentId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
							FROM
								ListofData LD WHERE LD.IsExist=1'
					
				print @sql		
				Exec sp_executesql @sql
				set @sql='UPDATE sStudent.tStudentCommunication set '+@lUpdateField+' = 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
					 SET @lResult = 1;
				END

			Else IF(@lSubFunctionality = 'Other')         -------Other
				BEGIN
					IF(@lUpdateField = 'DateOfBirth')
					BEGIN			
						set @sql='INSERT INTO sStudent.tStudentOther 
								(StudentId,'+@lUpdateField+',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 '+@lUpdateField+' = 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 '+@lUpdateField+' = null WHERE DateOfBirth=''1900-01-01'''
						Exec sp_executesql @sql
					END
					ELSE
					BEGIN
						set @sql='INSERT INTO sStudent.tStudentOther 
									(StudentId,'+@lUpdateField+',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 '+@lUpdateField+' = 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
						 SET @lResult = 1;
				 END	

				Else IF(@lSubFunctionality = 'Admission')		--------Admission
					BEGIN
					
					set @sql='UPDATE sStudent.tStudentAdmission set '+@lUpdateField+' = 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
							SET @lResult = 1;
					END	

				Else IF(@lSubFunctionality = 'Family')			---------Family
					BEGIN
						
						UPDATE ListofData SET IsExist=1 WHERE StudentId NOT IN(SELECT StudentId FROM sStudent.tStudentFamily) 
		
						set @sql='INSERT INTO sStudent.tStudentFamily 
									(StudentId,'+@lUpdateField+',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 '+@lUpdateField+' = 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
							 SET @lResult = 1;
						END

			  Else IF(@lSubFunctionality = 'General')	   ----------General
					 BEGIN
						IF(@lUpdateField != 'AdmissionCategoryId')
						BEGIN
							
							UPDATE ListofData SET IsExist=1 WHERE StudentId NOT IN(SELECT Id FROM sStudent.tStudentMaster) 
			
							set @sql='UPDATE sStudent.tStudentMaster set '+@lUpdateField+' = 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
						END
						 SET @lResult = 1;
					END			 
	 
			IF(@lResult = 1)
			BEGIN
				UPDATE sWorkFlow.tStudentDataChange
				SET
					StatusId = @rStatusId
					,ActionRemark = @rActionRemark
					,ActionUserId = @rActionUserId
					,ActionDateTime = @rActionDateTime
				WHERE 
					AutoId = @rRequestId
			END
			SELECT 2 AS Result
			END
		END
		ELSE
		BEGIN
		   SELECT -101 As Result
		END
		
		COMMIT TRANSACTION

		END TRY	
	BEGIN CATCH
		ROLLBACK TRANSACTION
		SELECT -1 AS RESULT
	END CATCH
		
END
GO
PRINT N'Creating [sAssetManagement].[pRptAssetListCategoryWise]...';


GO
 
CREATE PROCEDURE [sAssetManagement].[pRptAssetListCategoryWise]
	@rOrgId int,
	@rLocationId int = 0,
	@rCategoryId int = 0,
	@rStoreLocationId int,
	@rDepartmentId int = 0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
 
       SELECT 
				  DM.Title AS Department,
				  DM.Id AS DepartmentId,
				  LOC.Title AS Location,
				  LOC.Id AS LocationId,
                  CM.TITLE AS Category,
				  CM.Id AS CategoryId,
				  AM.Title AS AssetTitle,
				  AM.Code As AssetCode,
                  COUNT(AM.code) AS Quantity
                  
                  
            
         FROM sAssetManagement.tAssetMaster AM
			 INNER JOIN  sFixedAsset.tCategoryMaster CM ON AM.CATEGORYID = CM.ID
			 INNER JOIN  sCommon.tStatusMaster SM ON SM.ID =  AM.UsageStatusId 
			 INNER JOIN  sFixedAsset.VextLocationMaster LOC ON LOC.ID = AM.LocationId
			 INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id = AM.DepartmentID
			 
        WHERE 
        AM.OrgId = @rOrgId 
        AND ((AM.CategoryId = @rCategoryId) OR (@rCategoryId = 0))  
        AND ((AM.LocationId = @rLocationId) OR (@rLocationId = 0))
        AND ((AM.DepartmentId = @rDepartmentId) OR (@rDepartmentId = 0)) 
        AND((AM.StoreLocationId=@rStoreLocationId) OR @rStoreLocationId=0)
        
		Group By DM.Title,DM.Id,LOC.Title,LOC.Id,CM.TITLE,CM.Id,AM.Title,AM.Code
        ORDER BY  AM.Code  
END
GO
PRINT N'Creating [sFee].[pCanteenDepositAdjustmentAdd]...';


GO

CREATE PROCEDURE [sFee].[pCanteenDepositAdjustmentAdd]
	
	@rId bigint, 
	@rAdjustmentId bigint,
	@rDepositHeadId int,
	--@rStudentId bigint,
	@rAmount decimal(12,2),
	@rAdjustmentDate date,
	@rRemark nvarchar(200),
	@rCreatedUserId bigint,
	--@rBatchId int,
	@rOrgGroupId smallint,
	@rAcademicId bigint,
	@rFeeDepositExpenseTypeId int,
	--@rAdjustmentNumber Int,
	@rOrgGroupBatchId int,
	@rReferenceSourceId bigint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

DECLARE @lStudentId bigint

BEGIN	
BEGIN TRY
BEGIN TRANSACTION	
 DECLARE @rAdjustmentNumber Int
 Select @rAdjustmentNumber=(MAX(AdjustmentNumber) +1) from sFee.tDepositAdjustment

 --IF(@rId = 0)	
	--BEGIN  
		
	--	If Exists(select 1 from sFee.tDepositAdjustment  where OrgGroupBatchId=@rOrgGroupBatchId AND  AdjustmentNumber=@rAdjustmentNumber)
	--	Begin
	--		select -102 as Result
	--		RETURN
	--	End
	--		END
	--ELSE
	--BEGIN
		
	--	If  Exists(select Id from sFee.tDepositAdjustment where  OrgGroupBatchId=@rOrgGroupBatchId AND  AdjustmentNumber=@rAdjustmentNumber AND Id<>@rId)
	--	Begin
	--		select -102 as Result
	--		RETURN
	--	End

	--END
DECLARE @lNextNumber bigint 
IF NOT EXISTS(Select Id From sFee.tDepositAdjustment Where ReferenceSourceId=@rReferenceSourceId)
BEGIN
EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sFee.tDepositAdjustment', 0, 1, 1,@outNextNumber = @lNextNumber output 
	INSERT INTO sFee.tDepositAdjustment
		(
		Id,
		DepositHeadId,
		--StudentId,
		Amount,
		AdjustmentDate,
		Remark,
		CreatedUserId,
		CreatedDateTime,
		AcademicId,
		FeeDepositExpenseTypeId,
		AdjustmentNumber,
		OrgGroupBatchId,
		ReferenceSourceTypeId,
		ReferenceSourceId
		)
	VALUES
		(
		@lNextNumber,
		@rDepositHeadId,
		--@lStudentId,
		@rAmount,
		@rAdjustmentDate,
		@rRemark,
		@rCreatedUserId,
		sCommon.fGetDate(),
		@rAcademicId,
		@rFeeDepositExpenseTypeId,
		@rAdjustmentNumber,
		@rOrgGroupBatchId,
		2037 ,
		@rReferenceSourceId 
		) 
		SELECT @lNextNumber  AS Result   
	END	
ELSE
    BEGIN
    --SET @lNextNumber = @rId
	    UPDATE sFee.tDepositAdjustment
	    SET
	    DepositHeadId=@rDepositHeadId,
		Amount=@rAmount,
		AdjustmentDate=@rAdjustmentDate,
		Remark=@rRemark,
		UpdatedUserId=@rCreatedUserId,
	    UpdatedDateTime=sCommon.fGetDate(),
	    AcademicId=@rAcademicId,
	    FeeDepositExpenseTypeId=@rFeeDepositExpenseTypeId,
		AdjustmentNumber=@rAdjustmentNumber,
		OrgGroupBatchId=@rOrgGroupBatchId,
		ReferenceSourceTypeId=2037,
		ReferenceSourceId=@rReferenceSourceId
	    WHERE ReferenceSourceId = @rAdjustmentId 
	    SELECT 11 AS Result
	 END  
	COMMIT TRANSACTION
		
END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
	
END
GO
PRINT N'Creating [sFee].[pFeeGeneration]...';


GO
---
--exec [sFee].[pFeeGeneration] @rOrgId=1101,@rBatchId=110100101,@rClassId=110100002,@rDivisionId=110100003,@rCreatedUserId=1101000000003
---
CREATE PROCEDURE [sFee].[pFeeGeneration]
	 
		   @rOrgId int,
		   @rBatchId int,
           @rClassId int,
           @rDivisionId int,
		   @rCreatedUserId bigint
						 

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

SELECT batchid,classid,id AS academicid,admissioncategoryid,rownumAcademic 
INTO #temptAcademic 
FROM 
(SELECT batchid,classid,id,admissioncategoryid,ROW_NUMBER() OVER (ORDER BY id) rownumAcademic FROM sStudent.tacademic WHERE orgid=@rOrgId AND batchid=@rBatchId AND classid=@rClassId AND divisionid=@rDivisionId) AS tStudentAcademic

DECLARE @rowcountAcademic BIGINT=0

SELECT @rowcountAcademic = COUNT(rownumAcademic) FROM #temptAcademic

	WHILE (@rowcountAcademic!=0)
	BEGIN

		DECLARE @academicid BIGINT=0
		DECLARE @admissioncategoryid BIGINT=0
		
		SELECT @academicid=academicid,@admissioncategoryid=admissioncategoryid FROM #temptAcademic WHERE rownumAcademic=@rowcountAcademic

		SELECT rownumFeesetup,id AS feesetupid,amount AS feeamount 
		INTO  #temptfeesetup 
		FROM
		(SELECT ROW_NUMBER() OVER (ORDER BY id) rownumFeesetup,id,amount FROM sFee.tfeesetup WHERE batchid=@rBatchId AND classid=@rClassId AND admissioncategoryid=@admissioncategoryid) AS tFeeSetup
		
		DECLARE @rowcountFeesetup BIGINT=0

		SELECT @rowcountFeesetup = COUNT(rownumFeesetup) FROM #temptfeesetup

		WHILE (@rowcountFeesetup!=0)
		BEGIN
		
		BEGIN TRY

			DECLARE @feesetupid BIGINT=0
			DECLARE @feeAmount DECIMAL(12,2)=0.00
			DECLARE @toPayamount NCHAR(10)=0
			DECLARE @paidAmount DECIMAL(12,2)=0.00
			DECLARE @VariableAmount DECIMAL(12,2)=0.00
			DECLARE @DiscountAmount DECIMAL(12,2)=0.00
			DECLARE @AdditionalAmount DECIMAL(12,2)=0.00
			DECLARE @NotApplicableAmount DECIMAL(12,2)=0.00
					
			SELECT @feesetupid=feesetupid,@feeAmount=feeamount FROM #temptfeesetup WHERE rownumFeesetup=@rowcountFeesetup
			
			BEGIN TRANSACTION
			
			SELECT @paidAmount=a.amount FROM sFee.treceiptdetail a 
			JOIN sFee.treceipt  b 
			ON b.id=a.receiptid 
			WHERE b.sourceid=@academicid AND a.feesetupid=@feesetupid
						
			SELECT @VariableAmount=FA.[VariableAmount],@DiscountAmount=FA.[DiscountAmount],@AdditionalAmount=FA.[AdditionalAmount],@NotApplicableAmount=FA.[NotApplicableAmount]

			--,@paidamount=FA.PaidAmount
			--,RD.Amount PaidAmount,@rCreatedUserId CreatedUserId,sCommon.fGetDate()CreatedDateTime,@rCreatedUserId UpdatedUserId,sCommon.fGetDate() UpdatedDateTime
			
			FROM [sFee].[tFeeAllocation] AS FA					  
			
			--					LEFT JOIN 					  
			--				  (select a.amount,b.sourceid,a.feesetupid from sFee.treceiptdetail a join sFee.treceipt b on b.id=a.receiptid) AS RD
			--				  on FA.SourceId=RD.sourceid and FA.[FeeSetupId]=RD.feesetupid					  
			
			WHERE FA.sourceid=@academicid AND FA.feesetupid=@feesetupid

			--PRINT @academicid
			--PRINT @feesetupid
			
			IF EXISTS (SELECT 1 FROM [sFee].[tFeeAllocationStudent] FAS WHERE FAS.academicid=@academicid AND FAS.feesetupid=@feesetupid)
			BEGIN

			PRINT 'update'
			--SELECT FA.[SourceId]
			--					  ,FA.[FeeSetupId]
			--					  ,@feeAmount Amount
			--					  ,FA.[VariableAmount]
			--					  ,FA.[DiscountAmount]
			--					  ,FA.[AdditionalAmount]
			--					  ,FA.[NotApplicableAmount]
			--					  ,@toPayamount ToPayment
			--					  ,@paidamount PaidAmount
			--					  --,RD.Amount PaidAmount
			--					  ,@rCreatedUserId CreatedUserId 
			--					  ,sCommon.fGetDate() CreatedDateTime
			--					  ,@rCreatedUserId UpdatedUserId
			--					  ,sCommon.fGetDate() UpdatedDateTime
			--				  FROM [sFee].[tFeeAllocation] as FA					  
			----					LEFT JOIN 					  
			----				  (select a.amount,b.sourceid,a.feesetupid from sFee.treceiptdetail a join sFee.treceipt b on b.id=a.receiptid) AS RD
			----				  on FA.SourceId=RD.sourceid and FA.[FeeSetupId]=RD.feesetupid					  
			--				  where FA.sourceid=@academicid and FA.feesetupid=@feesetupid

				UPDATE [sFee].[tFeeAllocationStudent] 
				SET
					[FeeAmount]=@feeAmount
					,[VariableAmount]=@VariableAmount
					,[DiscountAmount]=@DiscountAmount
					,[AdditionalAmount]=@AdditionalAmount
					,[NotApplicableAmount]=@NotApplicableAmount
					--,[ToPayAmount]=@toPayamount
					,[PaidAmount]=@paidamount
					,[UpdatedUserId]=@rCreatedUserId
					,[UpdatedDateTime]=sCommon.fGetDate()									  
				WHERE academicid=@academicid AND feesetupid=@feesetupid
						
			END
			ELSE
			BEGIN

			PRINT 'insert'

				INSERT INTO [sFee].[tFeeAllocationStudent]
					   ([AcademicId],[FeeSetupId],[FeeAmount],[VariableAmount],[DiscountAmount],[AdditionalAmount],[NotApplicableAmount],[ToPayAmount]
					   ,[PaidAmount],[CreatedUserId],[CreatedDateTime],[UpdatedUserId],[UpdatedDateTime])
				VALUES
					(@academicid,@feesetupid,@feeAmount,@VariableAmount,@DiscountAmount,@AdditionalAmount,@NotApplicableAmount,@toPayamount
					,@paidamount,@rCreatedUserId,sCommon.fGetDate(),@rCreatedUserId,sCommon.fGetDate())	
				
				--(
				--SELECT FA.[SourceId],FA.[FeeSetupId],@feeAmount,FA.[VariableAmount],FA.[DiscountAmount],FA.[AdditionalAmount],FA.[NotApplicableAmount],@toPayamount
				--		--,@paidamount
				--		,RD.amount,@rCreatedUserId,sCommon.fGetDate(),@rCreatedUserId,sCommon.fGetDate()
				--FROM [sFee].[tFeeAllocation] as FA					  
				--LEFT JOIN 					  
				--(select a.amount,b.sourceid,a.feesetupid from sFee.treceiptdetail a join sFee.treceipt b on b.id=a.receiptid) AS RD
				--on FA.SourceId=RD.sourceid and FA.[FeeSetupId]=RD.feesetupid					  
				--where FA.sourceid=@academicid and FA.feesetupid=@feesetupid
				--)

			END
			
				SET @rowcountFeesetup=@rowcountFeesetup-1

			COMMIT TRANSACTION			
			--Success
		END TRY
		BEGIN CATCH 		
				ROLLBACK TRANSACTION
				PRINT @rowcountFeesetup
				PRINT 'fail'
		END CATCH
			
		END
		--drop table #temptfeesetup
		IF OBJECT_ID(N'tempdb..#temptfeesetup') IS NOT NULL
		BEGIN
			DROP TABLE #temptfeesetup
		END

		PRINT @rowcountAcademic

		SET @rowcountAcademic=@rowcountAcademic-1
	END
	
	--drop table #temptAcademic
	PRINT 'success'
	IF OBJECT_ID(N'tempdb..#temptAcademic') IS NOT NULL
	BEGIN
		DROP TABLE #temptAcademic
	END
END
GO
PRINT N'Creating [sFee].[pFeeProcessGenerate]...';


GO
---
--exec [sFee].[pFeeProcessGenerate] @rOrgId=1101,@rBatchId=110100110,@rClassId=110100024,@rCreatedUserId=1101000000003
--,@rDivisionId=110100003,@rCreatedUserId=1101000000003

CREATE PROCEDURE [sFee].[pFeeProcessGenerate]
	 
		   @rOrgId int,
		   @rBatchId int,
           @rClassId int,
           @rDivisionId int=NULL,
		   @rAcademicId bigint=NULL,
		   @rCreatedUserId bigint
						 

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

SELECT batchid,classid,id AS academicid,admissioncategoryid,rownumAcademic 
INTO #temptAcademic 
FROM 
(SELECT batchid,classid,id,admissioncategoryid,ROW_NUMBER() OVER (ORDER BY id) rownumAcademic FROM sStudent.tAcademic WHERE id=ISNULL(@rAcademicId,id) AND orgid=@rOrgId AND batchid=@rBatchId AND classid=@rClassId AND divisionid=ISNULL(@rDivisionId,divisionid)) AS tStudentAcademic

DECLARE @rowcountAcademic BIGINT=0

SELECT @rowcountAcademic = COUNT(rownumAcademic) FROM #temptAcademic

	WHILE (@rowcountAcademic!=0)
	BEGIN

		DECLARE @academicid BIGINT=0
		DECLARE @admissioncategoryid BIGINT=0
		
		SELECT @academicid=academicid,@admissioncategoryid=admissioncategoryid FROM #temptAcademic WHERE rownumAcademic=@rowcountAcademic

		SELECT rownumFeesetup,id AS feesetupid,amount AS feeamount,IsOptional,IsVariable 
		INTO  #temptFeeSetup 
		FROM
		(SELECT ROW_NUMBER() OVER (ORDER BY id) rownumFeesetup,id,amount,isoptional,isvariable FROM sFee.tFeeSetup WHERE batchid=@rBatchId AND classid=@rClassId AND admissioncategoryid=@admissioncategoryid) AS tFeeSetup
		
		DECLARE @rowcountFeesetup BIGINT=0

		SELECT @rowcountFeesetup = COUNT(rownumFeesetup) FROM #temptFeeSetup

		WHILE (@rowcountFeesetup!=0)
		BEGIN
		
		BEGIN TRY

			DECLARE @feesetupid BIGINT=0
			DECLARE @feeAmount DECIMAL(12,2)=0.00
			DECLARE @toPayamount NCHAR(10)=0
			DECLARE @paidAmount DECIMAL(12,2)=0.00
			DECLARE @VariableAmount DECIMAL(12,2)=0.00
			DECLARE @DiscountAmount DECIMAL(12,2)=0.00
			DECLARE @AdditionalAmount DECIMAL(12,2)=0.00
			DECLARE @NotApplicableAmount DECIMAL(12,2)=0.00
			DECLARE @IsOptional Bit=0
			DECLARE @IsVariable Bit=0
					
			SELECT @IsOptional=isoptional,@IsVariable=isvariable,@feesetupid=feesetupid,@feeAmount=ISNULL(feeamount,0) FROM #temptFeeSetup WHERE rownumFeesetup=@rowcountFeesetup
			
			SELECT @paidAmount=ISNULL(SUM(RD.amount),0) FROM sFee.tReceiptDetail RD 
			JOIN sFee.treceipt  R 
			ON R.id=RD.receiptid 
			WHERE R.sourceid=@academicid AND RD.feesetupid=@feesetupid
			GROUP BY R.sourceid,RD.feesetupid
			
			PRINT 'RowCountAcademic=='+CAST(@rowcountAcademic AS VARCHAR)+'RowCountFeeSetup=='+CAST(@rowcountFeesetup AS VARCHAR)
			PRINT 'Is Optional=='+CAST(@IsOptional AS VARCHAR)
			PRINT 'Is Variable=='+CAST(@IsVariable AS VARCHAR)
			PRINT 'Fee Amount=='+CAST(@feeAmount AS VARCHAR)

			--DELETE FROM tfeeallocationstudent academicid and feesetupid
			IF EXISTS (SELECT 1 FROM [sFee].[tFeeAllocationStudent] FAS WHERE FAS.academicid=@academicid AND FAS.feesetupid=@feesetupid)
			BEGIN
				DELETE FROM [sFee].[tFeeAllocationStudent] WHERE AcademicId=@academicid AND FeeSetupId=@feesetupid
			END

			IF NOT EXISTS (SELECT 1 FROM [sFee].[tFeeClassBatchStatus] WHERE ClassId=@rClassId AND BatchId=@rBatchId)
			BEGIN
				DELETE FROM [sFee].[tFeeClassBatchStatus] WHERE ClassId=@rClassId AND BatchId=@rBatchId
			END


			IF(@IsOptional=1 AND @IsVariable=1)
			BEGIN
				
				--variable amt = fee amount from fee set up
				SET @VariableAmount = @feeAmount

				SELECT @DiscountAmount=ISNULL(FA.[DiscountAmount],0),@AdditionalAmount=ISNULL(FA.[AdditionalAmount],0),@NotApplicableAmount=ISNULL(FA.[NotApplicableAmount],0)						
				FROM [sFee].[tFeeAllocation] AS FA					  			
				WHERE FA.sourceid=@academicid AND FA.feesetupid=@feesetupid
						 
			END
			

			IF(@IsOptional=1 AND @IsVariable=0)
			BEGIN
				
				--fee amount and variable amt =0 from fee set up
				SET @VariableAmount = 0
				SET @feeAmount = 0

				SELECT @DiscountAmount=ISNULL(FA.[DiscountAmount],0),@AdditionalAmount=ISNULL(FA.[AdditionalAmount],0),@NotApplicableAmount=ISNULL(FA.[NotApplicableAmount],0)						
				FROM [sFee].[tFeeAllocation] AS FA					  			
				WHERE FA.sourceid=@academicid AND FA.feesetupid=@feesetupid

			END


			IF(@IsOptional=0)
			BEGIN

				--Normal
				SELECT @VariableAmount=ISNULL(FA.[VariableAmount],0),@DiscountAmount=ISNULL(FA.[DiscountAmount],0),@AdditionalAmount=ISNULL(FA.[AdditionalAmount],0),@NotApplicableAmount=ISNULL(FA.[NotApplicableAmount],0)						
				FROM [sFee].[tFeeAllocation] AS FA					  			
				WHERE FA.sourceid=@academicid AND FA.feesetupid=@feesetupid

			END


			PRINT 'Variable Amount=='+CAST(@VariableAmount AS VARCHAR)
									
			--SELECT @VariableAmount=ISNULL(FA.[VariableAmount],0),@DiscountAmount=ISNULL(FA.[DiscountAmount],0),@AdditionalAmount=ISNULL(FA.[AdditionalAmount],0),@NotApplicableAmount=ISNULL(FA.[NotApplicableAmount],0)						
			--FROM [sFee].[tFeeAllocation] AS FA					  			
			--WHERE FA.sourceid=@academicid AND FA.feesetupid=@feesetupid
						
			--PRINT @academicid
			--PRINT @feesetupid
			
			--if optional 
			--SELECT * FROM [sFee].[tFeeOptional]
			
			IF EXISTS (SELECT 1 FROM [sFee].[tFeeOptional] WHERE FeeSetupId=@feesetupid AND SourceId=@academicid AND BatchId=@rBatchId AND  @IsOptional=1)
			BEGIN
				IF EXISTS (SELECT 1 FROM [sFee].[tFeeAllocationStudent] FAS WHERE FAS.academicid=@academicid AND FAS.feesetupid=@feesetupid)
				BEGIN					

				--	UPDATE [sFee].[tFeeAllocationStudent] 
				--SET
				--	[FeeAmount]=@feeAmount
				--	,[VariableAmount]=@VariableAmount
				--	,[DiscountAmount]=@DiscountAmount
				--	,[AdditionalAmount]=@AdditionalAmount
				--	,[NotApplicableAmount]=@NotApplicableAmount
				--	,[ToPayAmount]=(@feeAmount+@VariableAmount+@AdditionalAmount-@DiscountAmount-@paidamount)
				--	,[PaidAmount]=@paidamount
				--	,[UpdatedUserId]=@rCreatedUserId
				--	,[UpdatedDateTime]=sCommon.fGetDate()									  
				--WHERE academicid=@academicid AND feesetupid=@feesetupid
			
					PRINT 'update'+CAST(@rowcountFeesetup AS VARCHAR)
						
				END
				ELSE
				BEGIN						
					IF NOT EXISTS (SELECT 1 FROM [sFee].[tFeeClassBatchStatus] WHERE ClassId=@rClassId AND BatchId=@rBatchId)
					BEGIN
					--	INSERT INTO [sFee].[tFeeClassBatchStatus]
					--   ([ClassId]
					--   ,[BatchId]
					--   ,[StatusId]
					--   ,[UpdatedDateTime])
					--VALUES
					--   (@rClassId
					--   ,@rBatchId 
					--   ,723
					--   ,sCommon.fGetDate())
						PRINT 'insert' + CAST(@rowcountFeesetup AS VARCHAR)

					END

					--INSERT INTO [sFee].[tFeeAllocationStudent]
					--		([AcademicId],[FeeSetupId],[FeeAmount],[VariableAmount],[DiscountAmount],[AdditionalAmount],[NotApplicableAmount],[ToPayAmount]
					--		,[PaidAmount],[CreatedUserId],[CreatedDateTime],[UpdatedUserId],[UpdatedDateTime])
					--VALUES
					--	(@academicid,@feesetupid,@feeAmount,@VariableAmount,@DiscountAmount,@AdditionalAmount,@NotApplicableAmount,(@feeAmount+@VariableAmount+@AdditionalAmount-@DiscountAmount-@paidamount)
					--	,@paidamount,@rCreatedUserId,sCommon.fGetDate(),@rCreatedUserId,sCommon.fGetDate())				
				
					PRINT 'insert' + CAST(@rowcountFeesetup AS VARCHAR)

				END
			END
			ELSE
			BEGIN
				IF EXISTS (SELECT 1 FROM [sFee].[tFeeAllocationStudent] FAS WHERE FAS.academicid=@academicid AND FAS.feesetupid=@feesetupid)
				BEGIN					

				--	UPDATE [sFee].[tFeeAllocationStudent] 
				--SET
				--	[FeeAmount]=@feeAmount
				--	,[VariableAmount]=@VariableAmount
				--	,[DiscountAmount]=@DiscountAmount
				--	,[AdditionalAmount]=@AdditionalAmount
				--	,[NotApplicableAmount]=@NotApplicableAmount
				--	,[ToPayAmount]=(@feeAmount+@VariableAmount+@AdditionalAmount-@DiscountAmount-@paidamount)
				--	,[PaidAmount]=@paidamount
				--	,[UpdatedUserId]=@rCreatedUserId
				--	,[UpdatedDateTime]=sCommon.fGetDate()									  
				--WHERE academicid=@academicid AND feesetupid=@feesetupid
			
					PRINT 'update'+CAST(@rowcountFeesetup AS VARCHAR)
						
				END
				ELSE
				BEGIN						
					IF NOT EXISTS (SELECT 1 FROM [sFee].[tFeeClassBatchStatus] WHERE ClassId=@rClassId AND BatchId=@rBatchId)
					BEGIN
					--	INSERT INTO [sFee].[tFeeClassBatchStatus]
					--   ([ClassId]
					--   ,[BatchId]
					--   ,[StatusId]
					--   ,[UpdatedDateTime])
					--VALUES
					--   (@rClassId
					--   ,@rBatchId 
					--   ,723
					--   ,sCommon.fGetDate())
						PRINT 'insert' + CAST(@rowcountFeesetup AS VARCHAR)

					END

					--INSERT INTO [sFee].[tFeeAllocationStudent]
					--		([AcademicId],[FeeSetupId],[FeeAmount],[VariableAmount],[DiscountAmount],[AdditionalAmount],[NotApplicableAmount],[ToPayAmount]
					--		,[PaidAmount],[CreatedUserId],[CreatedDateTime],[UpdatedUserId],[UpdatedDateTime])
					--VALUES
					--	(@academicid,@feesetupid,@feeAmount,@VariableAmount,@DiscountAmount,@AdditionalAmount,@NotApplicableAmount,(@feeAmount+@VariableAmount+@AdditionalAmount-@DiscountAmount-@paidamount)
					--	,@paidamount,@rCreatedUserId,sCommon.fGetDate(),@rCreatedUserId,sCommon.fGetDate())				
				
					PRINT 'insert' + CAST(@rowcountFeesetup AS VARCHAR)

				END
			END
						
						
			SET @rowcountFeesetup=@rowcountFeesetup-1

		END TRY
		BEGIN CATCH 		
				PRINT 'fail'+CAST(@rowcountFeesetup AS VARCHAR)
				PRINT ERROR_MESSAGE()
				BREAK
		END CATCH			
		END

		--drop table #temptfeesetup
		IF OBJECT_ID(N'tempdb..#temptfeesetup') IS NOT NULL
		BEGIN
			DROP TABLE #temptfeesetup
		END

		PRINT @rowcountAcademic

		SET @rowcountAcademic=@rowcountAcademic-1
	END
	
	--drop table #temptAcademic	
	IF OBJECT_ID(N'tempdb..#temptAcademic') IS NOT NULL
	BEGIN
		DROP TABLE #temptAcademic
	END

	PRINT 'success'

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


GO
--exec [sFee].[pFeeProcessGenerateGet] @rOrgId=1101,@rBatchId=110100001
--,@rClassId=110100010
--,@rDivisionId=110100003
--,@rAcademicId=1101000002336
--
CREATE PROCEDURE [sFee].[pFeeProcessGenerateGet]
	 
		   @rOrgId int,
		   @rBatchId int,
           @rClassId int=NULL,
           @rDivisionId int=NULL,
		   @rAcademicId bigint=NULL						 

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

SELECT CM.Id ClassId,CM.Title,CM.DisplayTitle,
ISNULL(SM.Title,'Pending') AS ClassFeeStatus,
ISNULL(FCBS.Id,0) AS FeeClassBactchStatusId

FROM sSetup.tClassMaster CM 
JOIN sStudent.tAcademic A ON CM.Id=A.ClassId
LEFT JOIN sFee.tFeeClassBatchStatus FCBS ON FCBS.ClassId=CM.Id AND FCBS.BatchId=A.BatchId
LEFT JOIN sCommon.tStatusMaster SM ON SM.Id=FCBS.StatusId AND SM.StatusTypeId=656			

WHERE CM.OrgId=@rOrgId AND A.BatchId=@rBatchId 

AND A.ClassId=ISNULL(@rClassId,A.ClassId) 
AND A.DivisionId=ISNULL(@rDivisionId,A.DivisionId)
AND A.Id=ISNULL(@rAcademicId,A.Id)

GROUP BY CM.Id,CM.Title,CM.Displaytitle,SM.Title,FCBS.Id

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