GO 
INSERT INTO [sSystem].[tVersionUpdate] ([VersionNumber],[VersionId],[Status],[UpdateScript],[StartDateTime],[EndDateTime],[OrgGroupId])
VALUES('22.07.04',220704,'BEGIN','Script',sCommon.fGetDate(),sCommon.fGetDate(),0)
GO 
 
 
GO
PRINT N'Altering [sAdmission].[tAdmissionCriteria]...';


GO
ALTER TABLE [sAdmission].[tAdmissionCriteria]
    ADD [IsOptionalSubject] BIT NULL;


GO
PRINT N'Altering [sAlert].[tWhatsAppConfiguration]...';


GO
ALTER TABLE [sAlert].[tWhatsAppConfiguration] DROP COLUMN [WhatsAppAutoLoginURL];


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


GO
ALTER TABLE [sCommunication].[tPhotoCategoryMaster]
    ADD [OrgGroupBatchId] INT NULL;


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


GO
ALTER TABLE [sStudent].[tOnlineRegistrationStudentMaster]
    ADD [StudentId] BIGINT NULL;


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


GO
CREATE TABLE [sAdmission].[tAdmissionCriteriaOptionalSubject] (
    [BatchId]        INT NOT NULL,
    [ClassId]        INT NOT NULL,
    [ClassSubjectId] INT NOT NULL
);


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


GO
CREATE TABLE [sAdmission].[tAdmissionOptionalSubject] (
    [AdmissionFormId] BIGINT NOT NULL,
    [ClassSubjectId]  INT    NOT NULL
);


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


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


GO
PRINT N'Creating PK_tDigitalFrom...';


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


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


GO
CREATE TABLE [sHrm].[tDigitalFormEmployee] (
    [AutoId]          INT             IDENTITY (1, 1) NOT NULL,
    [DigitalFormId]   INT             NOT NULL,
    [EmployeeId]      BIGINT          NOT NULL,
    [FieldTypeId]     SMALLINT        NOT NULL,
    [UpdateFieldId]   INT             NOT NULL,
    [OldValue]        NVARCHAR (500)  NULL,
    [NewValue]        NVARCHAR (500)  NOT NULL,
    [StatusId]        SMALLINT        NOT NULL,
    [Remark]          NVARCHAR (500)  NULL,
    [CreatedUserId]   BIGINT          NOT NULL,
    [CreatedDateTime] DATETIME        NOT NULL,
    [ActionUserId]    BIGINT          NULL,
    [ActionDateTime]  DATETIME        NULL,
    [ActionRemark]    NVARCHAR (500)  NULL,
    [OldValueImage]   VARBINARY (MAX) NULL,
    [NewValueImage]   VARBINARY (MAX) NULL
);


GO
PRINT N'Creating PK_tDigitalFromStudent...';


GO
ALTER TABLE [sHrm].[tDigitalFormEmployee]
    ADD CONSTRAINT [PK_tDigitalFromStudent] 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 [sHrm].[tDigitalFormField]...';


GO
CREATE TABLE [sHrm].[tDigitalFormField] (
    [DigitalFormId] INT      NOT NULL,
    [FieldTypeId]   SMALLINT NOT NULL,
    [UpdateFieldId] INT      NOT NULL
);


GO
PRINT N'Creating UK_tDigitalFromField...';


GO
ALTER TABLE [sHrm].[tDigitalFormField]
    ADD CONSTRAINT [UK_tDigitalFromField] UNIQUE NONCLUSTERED ([DigitalFormId] ASC, [FieldTypeId] ASC, [UpdateFieldId] 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 [sHrm].[tDigitalFormScope]...';


GO
CREATE TABLE [sHrm].[tDigitalFormScope] (
    [DigitalFormId] INT      NOT NULL,
    [SourceTypeId]  SMALLINT NOT NULL,
    [SourceId]      BIGINT   NOT NULL
);


GO
PRINT N'Creating UK_tDigitalFromScope...';


GO
ALTER TABLE [sHrm].[tDigitalFormScope]
    ADD CONSTRAINT [UK_tDigitalFromScope] UNIQUE NONCLUSTERED ([DigitalFormId] ASC, [SourceTypeId] ASC, [SourceId] 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 [sStudent].[tOnlineRegistrationCriteria]...';


GO
CREATE TABLE [sStudent].[tOnlineRegistrationCriteria] (
    [ClassId]           INT NOT NULL,
    [BatchId]           INT NOT NULL,
    [IsOptionalSubject] BIT NOT NULL
);


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


GO
CREATE TABLE [sStudent].[tOnlineRegistrationCriteriaOptionalSubject] (
    [BatchId]        INT NOT NULL,
    [ClassId]        INT NOT NULL,
    [ClassSubjectId] INT NOT NULL
);


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


GO
CREATE TABLE [sStudent].[tOnlineRegistrationStudentOptionalSubject] (
    [OnlineRegistrationStudentId] BIGINT NOT NULL,
    [ClassSubjectId]              INT    NOT NULL
);


GO

 
GO
PRINT N'Altering [sActivity].[pHealthCheckupStudentGet]...';


GO
ALTER PROCEDURE [sActivity].[pHealthCheckupStudentGet]
	        
	       @rBuilder1 nvarchar(max)='',
		   @rBuilder2 nvarchar(max)='',     
           @rAcadamicId bigint,
           @rHealthCheckupId int,
           @rStatusId int,
           @rBatchId int,
           @rFromDate date = null,
           @rToDate date = null,
           @rDivisioId int,
           @rClassId int                 
	
WITH EXECUTE AS CALLER	
AS
SET NOCOUNT ON
BEGIN
	 BEGIN TRY 
	 BEGIN TRANSACTION	
	   
  SELECT      
			  @rBuilder1 AS Builder1,
			  @rBuilder2 AS Builder2,
			  [HealthCheckupId]     
	          ,HT.AcademicId 
			  ,ISNULL([HeightInCm],0) AS HeightInCm 
			  ,ISNULL([WeightInKg],0) AS WeightInKg
			  ,[Dental]
			  ,[Nails]
			  ,[Hair]
			  ,[Skin]
			  ,[Ear]
			  ,[Nose]
			  ,[Throat]
			  ,[Respiratory]
			  ,[Cardiovascular]
			  ,[Nervous]
			  ,[Eye]
			  ,[Other]
			  ,[ImportantFinding]
			  ,[Remarks]
			  ,[FollowupDetail]
			  ,HT.[StatusId]			 			   
			  ,(SM.ClassName +'-' + SM.DivisionName) AS ClassName
			  ,SM.Name AS StudentName
			  ,SM.Code AS StudentCode
			  ,SM.RollNo
			  ,SM.ClassId
			  ,SM.DivisionId
			  ,ISNULL(SM.GenderId,0) AS GenderId
			  --,SM.Age
			  ,SC.PresentStreetOne+' '+SC.PresentStreetTwo+' '+SC.PermanentStreetThree+' '+SC.PresentCity AS Address  
			  ,SC.PresentContactNo As ContactNo
			  ,BGM.Title AS BloodGroup
			  ,SMM.Title AS Status
			  ,HC.Title AS HealthCheckup
			  ,HC.DoctorName
			  ,HC.CheckupDate
			  
			  
  FROM		[sActivity].[tHealthCheckupStudent]       
    		HT INNER JOIN sStudent.vStudentAcademic SM ON SM.AcademicId = HT.AcademicId	
    		INNER JOIN sCommon.tStatusMaster SMM ON SMM.Id = HT.StatusId	
    		INNER JOIN sActivity.tHealthCheckup HC ON HC.Id = HT.HealthCheckupId  
    		LEFT JOIN sStudent.tStudentCommunication SC ON SM.StudentId=SC.StudentId
    		LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=SM.StudentId
    		LEFT JOIN sCommon.tBloodGroupMaster BGM ON SO.BloodGroupId=BGM.Id
    		    		
  
  WHERE  (HT.HealthCheckupId = @rHealthCheckupId OR @rHealthCheckupId = 0)	
	     AND (HT.AcademicId = @rAcadamicId OR @rAcadamicId =  0)
	     AND (HT.StatusId = @rStatusId OR @rStatusId = 0)
	     AND HC.BatchId = @rBatchId
         AND (HC.CheckupDate >= @rFromDate OR ISNULL(@rFromDate,'') = '')
		 AND (CheckupDate <= @rToDate OR ISNULL(@rToDate,'') = '')
		 AND (SM.ClassId = @rClassId OR @rClassId = 0)
		 ANd (SM.DivisionId = @rDivisioId OR @rDivisioId = 0)
			
		ORDER BY CheckupDate,ClassId,DivisionId,RollNo ASC
      
	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sAdmission].[pAdmissionCriteriaOnlineGet]...';


GO
 
ALTER PROCEDURE [sAdmission].[pAdmissionCriteriaOnlineGet]
	 @rClassId int = 0,
	 @rBatchId int
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
		
	SELECT 
	   [ClassId]
      ,[BatchId]
      ,[IsValidateBirthdate]
      ,[FromDateOfBirth]
      ,[ToDateOfBirth]
      ,[IsParentAcademicRequired]
      ,[IsStudentAcademicRequired]
      ,[IsFamilyDetailRequired]
      ,[IsSiblingDetailRequired]
      ,[IsReferenceDetailRequired]
      ,[IsFixStudentAcademic]
      ,[StudentAcademicFor]
      ,[StudentAcademicRemark]
      ,[FamilyDetailRemark]
      ,[IsFixParentAcademic]
      ,[ParentAcademicFor]
      ,[ParentAcademicRemark]
      ,[ConfirmationRemark]
      ,[AdmissionFormRemark]
      ,[Reference1]
      ,[Reference2]
      ,[IsOtherInformationRequired]
      ,[IsPayFormFeeOnline]
      ,[FormFeeName]
      ,[FormFeeAmount]
      ,Isnull(IsHostelDetailRequired,0) As IsHostelDetailRequired
      ,Isnull(IsTransportDetailRequired,0) AS IsTransportDetailRequired
      ,Isnull(IsHealthDetailRequired,0) AS IsHealthDetailRequired
      ,Isnull(IsBirthPlaceDetailRequired,0) aS IsBirthPlaceDetailRequired
      ,Isnull(IsAadhaarDetailRequired,0) As IsAadhaarDetailRequired
      ,Isnull(IsBloodGroupDetailRequired,0) As IsBloodGroupDetailRequired,
      Isnull(IsFatherDetail,0) As IsFatherDetail,
      Isnull(IsFatherFullDetail,0) As IsFatherFullDetail,
       Isnull(IsFatherAcademic,0) As IsFatherAcademic,
       Isnull(IsMotherDetail,0) As IsMotherDetail,
        Isnull(IsMotherFullDetail,0) As IsMotherFullDetail,
         Isnull(IsMotherAcademic,0) As IsMotherAcademic,
          Isnull(IsGuardianDetail,0) As IsGuardianDetail,
        Isnull(IsGuardianFullDetail,0) As IsGuardianFullDetail   ,
        Isnull(IsGuardianAcademic,0) As IsGuardianAcademic,
        ISNULL(IsAdmissionFeeBreakup,0) AS IsAdmissionFeeBreakup,
        ISNULL(AdmissionConfirmationRemark,'') As AdmissionConfirmationRemark,
		ISNULL(IsOptionalSubject,0) AS IsOptionalSubject
  FROM sAdmission.tAdmissionCriteria
  WHERE 
		 ((ClassId=@rClassId) OR (@rClassId=0))
		AND BatchId=@rBatchId
END
GO
PRINT N'Altering [sAdmission].[pAdmissionCriteriaSetupAdd]...';


GO
 
ALTER PROCEDURE [sAdmission].[pAdmissionCriteriaSetupAdd]
		@rClassId int
		,@rBatchId int
		,@rIsValidateBirthdate bit
		,@rFromDateOfBirth date
		,@rToDateOfBirth date
		,@rIsParentAcademicRequired bit
		,@rIsStudentAcademicRequired bit
		,@rIsFamilyDetailRequired bit
		,@rIsSiblingDetailRequired bit
		,@rIsReferenceDetailRequired bit
		
		,@rIsFixStudentAcademic bit
		,@rStudentAcademicFor nvarchar(300)
		,@rStudentAcademicRemark nvarchar(max)
		,@rFamilyDetailRemark nvarchar(max)
		,@rIsFixParentAcademic bit
		,@rParentAcademicFor nvarchar(300)
		,@rParentAcademicRemark nvarchar(max)
		,@rConfirmationRemark nvarchar(max)
		,@rAdmissionFormRemark nvarchar(max),
		@rReference1 nvarchar(150),
		@rReference2 nvarchar(150),
		@rIsOtherInformationRequired bit,
		@rIsPayFormFeeOnline bit = NULL,
		@rFormFeeName nvarchar(100)=NULL,
		@rFormFeeAmount decimal(12,2)=NULL,
		@rIsHostelDetailRequired	bit	,
		@rIsTransportDetailRequired	bit	,
		@rIsHealthDetailRequired	bit	,
		@rIsBirthPlaceDetailRequired	bit	,
		@rIsAadhaarDetailRequired	bit	,
		@rIsBloodGroupDetailRequired	bit,
		@rReceiptBookId int = NULL	,
		@rIsFatherDetail bit=0,
		@rIsFatherFullDetail bit=0,
		@rIsFatherAcademic bit=0,
		@rIsMotherDetail bit=0,
		@rIsMotherFullDetail bit=0,
		@rIsMotherAcademic bit=0,
		@rIsGuardianDetail bit=0,
		@rIsGuardianFullDetail bit=0,
		@rIsGuardianAcademic bit=0,
		@rIsPublish bit=0,
		
		@rIsCustomField1Required bit=0,
		@rCustomField1Remark nvarchar(500)=NULL,	
		@rCustomField1TypeId int=0,
		@rCustomField1List nvarchar(500)=NULL,
		@rIsCustomField1Mandatory bit=0,
		
		@rIsCustomField2Required bit=0,
		@rCustomField2Remark nvarchar(500)=NULL,
		@rCustomField2TypeId int=0,
		@rCustomField2List nvarchar(500)=NULL,
		@rIsCustomField2Mandatory bit=0,
		
		@rIsCustomField3Required bit=0,
		@rCustomField3Remark nvarchar(500)=NULL,
		@rCustomField3TypeId int=0,
		@rCustomField3List nvarchar(500)=NULL,
		@rIsCustomField3Mandatory bit=0,
		
		@rIsAdmissionFeeBreakup bit =0,
		@rAgeCutOffDate date,
		@rExtraRemark1 nvarchar(max)=null,
		@rExtraRemark2 nvarchar(max)=null,
		@rExtraRemark3 nvarchar(max)=null,
		@rAdmissionInquiryRemark nvarchar(max),
		@rAdmissionConfirmationRemark nvarchar(max),
		@rIsSendMailFormAttachment bit =0,
		@rIsOptionalSubject bit = 0
				
		
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	--BEGIN TRY
	if(@rIsPublish = 1)
	BEGIN
		UPDATE sAdmission.tAdmissionCriteria SET IsPublish=0 where ClassId=@rClassId
	END

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

	INSERT INTO sAdmission.tAdmissionCriteria
		(
			 ClassId
			 ,BatchId
			 ,IsValidateBirthdate
			 ,FromDateOfBirth
			,ToDateOfBirth
			,IsParentAcademicRequired
			,IsStudentAcademicRequired
			,IsFamilyDetailRequired
			,IsSiblingDetailRequired
			,IsReferenceDetailRequired
			
			,IsFixStudentAcademic
			,StudentAcademicFor
			,StudentAcademicRemark
			,FamilyDetailRemark
			,IsFixParentAcademic
			,ParentAcademicFor
			,ParentAcademicRemark
			,ConfirmationRemark
			,AdmissionFormRemark,
			Reference1,
			Reference2,
			IsOtherInformationRequired,
			IsPayFormFeeOnline,
			FormFeeName,
			FormFeeAmount,
			IsHostelDetailRequired,
			IsTransportDetailRequired,
			IsHealthDetailRequired,
			IsBirthPlaceDetailRequired,
			IsAadhaarDetailRequired,
			IsBloodGroupDetailRequired,
			ReceiptBookId	,
			IsFatherDetail,
			IsFatherFullDetail,
			IsFatherAcademic,
			IsMotherDetail,
			IsMotherFullDetail,
			IsMotherAcademic,
			IsGuardianDetail,
			IsGuardianFullDetail,
			IsGuardianAcademic,
			IsPublish,
			
			IsCustomField1Required,
			CustomField1Remark,
			CustomField1TypeId,
			CustomField1List,
			IsCustomField1Mandatory,
			
			IsCustomField2Required,
			CustomField2Remark,
			CustomField2TypeId,
			CustomField2List,
			IsCustomField2Mandatory,
			
			IsCustomField3Required,
			CustomField3Remark,
			CustomField3TypeId,
			CustomField3List,
			IsCustomField3Mandatory,
			
			IsAdmissionFeeBreakup,
			AgeCutOffDate,
			Remark1,
			Remark2,
			Remark3,
			AdmissionInquiryRemark,
			AdmissionConfirmationRemark,
			IsSendMailFormAttachment,
			IsOptionalSubject
			

		)
	VALUES
		(
			 @rClassId
			,@rBatchId
			,@rIsValidateBirthdate
			,@rFromDateOfBirth
			,@rToDateOfBirth
			,@rIsParentAcademicRequired
			,@rIsStudentAcademicRequired
			,@rIsFamilyDetailRequired
			,@rIsSiblingDetailRequired
			,@rIsReferenceDetailRequired
			
			,@rIsFixStudentAcademic
			,@rStudentAcademicFor
			,@rStudentAcademicRemark
			,@rFamilyDetailRemark
			,@rIsFixParentAcademic
			,@rParentAcademicFor
			,@rParentAcademicRemark
			,@rConfirmationRemark
			,@rAdmissionFormRemark,
			@rReference1,
			@rReference2,
			@rIsOtherInformationRequired,
			@rIsPayFormFeeOnline,
			@rFormFeeName,
			@rFormFeeAmount,
			@rIsHostelDetailRequired,
			@rIsTransportDetailRequired,
			@rIsHealthDetailRequired,
			@rIsBirthPlaceDetailRequired,
			@rIsAadhaarDetailRequired,
			@rIsBloodGroupDetailRequired,	
			@rReceiptBookId,
			@rIsFatherDetail,
			@rIsFatherFullDetail,
			@rIsFatherAcademic,
			@rIsMotherDetail,
			@rIsMotherFullDetail,
			@rIsMotherAcademic,
			@rIsGuardianDetail,
			@rIsGuardianFullDetail,
			@rIsGuardianAcademic,
			@rIsPublish,
			
			@rIsCustomField1Required,
			@rCustomField1Remark,	  
			@rCustomField1TypeId,	  
			@rCustomField1List,
			@rIsCustomField1Mandatory,
			
			@rIsCustomField2Required, 
			@rCustomField2Remark,
			@rCustomField2TypeId,	
			@rCustomField2List,
			@rIsCustomField2Mandatory,
			
			@rIsCustomField3Required,
			@rCustomField3Remark,
			@rCustomField3TypeId,	
			@rCustomField3List,
			@rIsCustomField3Mandatory,
			
			@rIsAdmissionFeeBreakup,
			@rAgeCutOffDate,
			@rExtraRemark1,
			@rExtraRemark2,
			@rExtraRemark3,
			@rAdmissionInquiryRemark,
			@rAdmissionConfirmationRemark,
			@rIsSendMailFormAttachment,
			@rIsOptionalSubject
		)
		     SELECT 103 AS Result
	
		--COMMIT TRANSACTION
	
			
END
GO
PRINT N'Altering [sAdmission].[pAdmissionCriteriaSetupGet]...';


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

	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
	 

BEGIN 
	 
	 
	
	SELECT 
		
		ClassId,
		BatchId,
		ISNULL(IsValidateBirthdate,'') AS IsValidateBirthdate,
		ISNULL(FromDateOfBirth,'') AS FromDateOfBirth,
		ISNULL(ToDateOfBirth,'')AS ToDateOfBirth,
		ISNULL(IsParentAcademicRequired,'') AS IsParentAcademicRequired,
		ISNULL(IsStudentAcademicRequired,'') AS IsStudentAcademicRequired,
		ISNULL(IsFamilyDetailRequired,'') AS IsFamilyDetailRequired,
		ISNULL(IsSiblingDetailRequired,'') AS IsSiblingDetailRequired,
		ISNULL(IsReferenceDetailRequired,'') AS IsReferenceDetailRequired,
		
		ISNULL(IsFixStudentAcademic,'') AS IsFixStudentAcademic,
		StudentAcademicFor,
		StudentAcademicRemark,
		FamilyDetailRemark,
		ISNULL(IsFixParentAcademic,'') AS IsFixParentAcademic,
		ParentAcademicFor,
		ParentAcademicRemark,
		ConfirmationRemark,
		AdmissionFormRemark,
		ISNULL(Reference1,'') AS Reference1,
		ISNULL(Reference2,'')AS Reference2,
		ISNULL(IsOtherInformationRequired,0) As IsOtherInformationRequired,
		ISNULL(IsPayFormFeeOnline,0) AS IsPayFormFeeOnline,
		ISNULL(FormFeeName,'') AS FormFeeName,
		ISNULL(FormFeeAmount,0) AS FormFeeAmount,
		ISNULL(IsHostelDetailRequired,0) AS IsHostelDetailRequired,
		ISNULL(IsTransportDetailRequired,0) AS IsTransportDetailRequired,
		ISNULL(IsHealthDetailRequired,0) AS IsHealthDetailRequired,
		ISNULL(IsBirthPlaceDetailRequired,0) AS IsBirthPlaceDetailRequired,
		ISNULL(IsAadhaarDetailRequired,0) AS IsAadhaarDetailRequired,
		ISNULL(IsBloodGroupDetailRequired,0) AS IsBloodGroupDetailRequired,
		ISNULL(ReceiptBookId,0) AS ReceiptBookId,
		ISNULL(IsFatherDetail,0) AS IsFatherDetail,
		ISNULL(IsFatherFullDetail,0) AS IsFatherFullDetail,
		ISNULL(IsFatherAcademic,0) AS IsFatherAcademic,
		ISNULL(IsMotherDetail,0) AS IsMotherDetail,
		ISNULL(IsMotherFullDetail,0) AS IsMotherFullDetail,
		ISNULL(IsMotherAcademic,0) AS IsMotherAcademic,
		ISNULL(IsGuardianDetail,0) AS IsGuardianDetail,
		ISNULL(IsGuardianFullDetail,0) AS IsGuardianFullDetail,
		ISNULL(IsGuardianAcademic,0) AS IsGuardianAcademic,
		ISNULL(IsPublish,0) As IsPublish,
		
		ISNULL(IsCustomField1Required,0) AS IsCustomField1Required,
		ISNULL(CustomField1Remark,'') AS CustomField1Remark,
		ISNULL(CustomField1TypeId,0) AS CustomField1TypeId,
		ISNULL(CustomField1List,'') AS CustomField1List,
		ISNULL(IsCustomField1Mandatory,0) AS IsCustomField1Mandatory,
		ISNULL(IsCustomField2Required,0) AS IsCustomField2Required,
		ISNULL(CustomField2Remark,'') AS CustomField2Remark,
		ISNULL(CustomField2TypeId,0) AS CustomField2TypeId,
		ISNULL(CustomField2List,'') AS CustomField2List,
		ISNULL(IsCustomField2Mandatory,0) AS IsCustomField2Mandatory,
		ISNULL(IsCustomField3Required,0) AS IsCustomField3Required,
		ISNULL(CustomField3Remark,'') AS CustomField3Remark,
		ISNULL(CustomField3TypeId,0) AS CustomField3TypeId,
		ISNULL(CustomField3List,'') AS CustomField3List,
		ISNULL(IsCustomField3Mandatory,0) AS IsCustomField3Mandatory,
		ISNULL(IsAdmissionFeeBreakup,0) AS IsAdmissionFeeBreakup,
		ISNULL(AgeCutOffDate,'') AS AgeCutOffDate,
		ISNULL(Remark1,'') AS ExtraRemark1,
		ISNULL(Remark2,'') AS ExtraRemark2,
		ISNULL(Remark3,'') AS ExtraRemark3,
		ISNULL(AdmissionInquiryRemark,'') As AdmissionInquiryRemark ,
		ISNULL(AdmissionConfirmationRemark,'') As AdmissionConfirmationRemark,
		ISNULL(IsSendMailFormAttachment,0) AS IsSendMailFormAttachment,
		ISNULL(IsOptionalSubject,0) AS IsOptionalSubject
  FROM 
            sAdmission.tAdmissionCriteria
			 
  WHERE 
   (ClassId=@rClassId)
   AND BatchId=@rBatchId
	
END
GO
PRINT N'Altering [sAdmission].[pAdmissionFormDelete]...';


GO
 
 
ALTER PROCEDURE [sAdmission].[pAdmissionFormDelete]
	 @rId bigint
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	BEGIN TRY
		BEGIN TRANSACTION SD			 
			--Delete from sSecurity.tUserAccess where SourceId=@rId AND SourceTypeId = 2019
			Delete from sAdmission.tAdmissionFormFamilyDetail where AdmissionFormId = @rId
			Delete from sAdmission.tAdmissionFormParentAcademic where AdmissionFormId = @rid
			Delete from sAdmission.tAdmissionFormReference where AdmissionFormId = @rId
			Delete from sAdmission.tAdmissionFormSelected where AdmissionFormId = @rId
			Delete from sAdmission.tAdmissionFormSibling where AdmissionFormId = @rId
			Delete from sAdmission.tAdmissionFormStudentAcademic where AdmissionFormId = @rId
			Delete from sAdmission.tAdmissionSetupStudent where AdmissionFormId = @rId
			Delete from sAdmission.tAdmissionForm where Id=@rId
			Delete from sAdmission.tAdmissionFormField where AdmissionFormId =  @rId 
			DELETE FROM sAdmission.tAdmissionOptionalSubject WHERE AdmissionFormId = @rId 
			
			
			
		 
		COMMIT TRANSACTION	SD
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION SD
	END CATCH	
END
GO
PRINT N'Altering [sAssessment].[pRptExamFullGet]...';


GO
ALTER PROCEDURE [sAssessment].[pRptExamFullGet]
	 @rId int=0,
	 @rExamIds nvarchar(200)='',
	 @rBuilder1 nvarchar(200)='' 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 	

					 
	SELECT 
	EM.Id,
	@rBuilder1 AS Builder1,
	Convert (nvarchar(20),EM.Id) AS ExamIdText,
	EM.BatchId,
	ESGM.Code,
	ESGM.Title AS Name,
	ESGM.Id AS ExamGRoupId,
	EM.ClassId,
	--EC.Id,
	--EM.IsRankNo,
	CASE WHEN ISNULL(IsRankNo,0) = 0 THEN 'No' ELSE 'Yes' END AS IsIsRankNo,
	--EM.IsGrade,
	CASE WHEN ISNULL(IsGrade,0) = 0 THEN 'No' ELSE 'Yes' END AS IsGrade,
	--EM.IsPercentile,
	CASE WHEN ISNULL(IsPercentile,0) = 0 THEN 'No' ELSE 'Yes' END AS IsPercentile,
	--EM.IsPercentage,
	CASE WHEN ISNULL(IsPercentage,0) = 0 THEN 'No' ELSE 'Yes' END AS IsPercentage,
	--EM.IsSubjectPercentile,
	CASE WHEN ISNULL(IsSubjectPercentile,0) = 0 THEN 'No' ELSE 'Yes' END AS IsSubjectPercentile,
	ISNULL(EM.GradeSetId,0) AS GradeSetId,
	ISNULL(EM.RankSetId,0) AS RankSetId,
	ISNULL(EM.LevelSetId,0) AS LevelSetId ,
	CASE WHEN ISNULL(IsProcessResult,0) = 0 THEN 'No' ELSE 'Yes' END AS IsProcessResult,
	CASE WHEN IsNull(IsMarksInDecimal,0) = 0 THEN 'No' ELSE 'Yes' END AS IsMarksInDecimal,
	CASE WHEN ISNULL(ISNegativeMarks,0)=0 THEN 'No' ELSE 'Yes' END AS ISNegativeMarks,
	Isnull(ED.Id,0) as ExamDetailId,
	ISNULL(ED.GradeSetId,0) as GradeSetDetailId,
	ISNULL(ED.ExamId,0) as ExamId,
	ISNULL(CS.Id,0) as ClassSubjectId,
	ISNULL(ED.Maximum,0) as Maximum,
	ISNULL(ED.Minimum,0) as Minimum,
	--ISNULL(ED.IsIncludeInTotal,0) as IsIncludeInTotal,
	CASE WHEN ISNULL(IsIncludeInTotal,0)=0 THEN 'No' ELSE 'Yes' END AS IsIncludeInTotal,
	--ISNULL(ED.IsDisplayInMarksheet,0) as IsDisplayInMarksheet,
	CASE WHEN ISNULL(IsDisplayInMarksheet,0)=0 THEN 'No' ELSE 'Yes' END AS IsDisplayInMarksheet,
	--ISNULL(ED.IsShowSubjectGrade,0) as IsShowSubjectGrade,
	CASE WHEN ISNULL(IsShowSubjectGrade,0)=0 THEN 'No' ELSE 'Yes' END AS IsShowSubjectGrade,
	ISNULL(ED.DisplayOrder,0) as DisplayOrder,
	ISNULL(ED.ExamDate,sCommon.fGetDate()) as ExamDate,
	ISNULL(ED.ExamTime,'') as ExamTime,
	ISNULL(ED.ExamTopic,'') as ExamTopic,
	GSM.Title as GradeSET,
	EGM.Title as ExamGroup,
	ESGM.Title as ExamName,
	SM.Title as SubjectName,
	CM.DisplayTitle as ClassName,
	
	CASE WHEN ISNULL(IsOnPrePrinted,0) = 0 THEN 'No' ELSE 'Yes' END AS IsOnPrePrinted,
	CASE WHEN ISNULL(IsDisplayBirthDate,0) = 0 THEN 'No' ELSE 'Yes' END AS IsDisplayBirthDate,
	CASE WHEN ISNULL(IsDisplayPhoto,0) = 0 THEN 'No' ELSE 'Yes' END AS IsDisplayPhoto,
	CASE WHEN ISNULL(IsDisplaySchoolName,0) = 0 THEN 'No' ELSE 'Yes' END AS IsDisplaySchoolName,
	CASE WHEN ISNULL(IsLockForEdit,0) = 0 THEN 'No' ELSE 'Yes' END AS IsLockForEdit,
	CASE WHEN ISNULL(IsIncludeCoScholastic,0) = 0 THEN 'No' ELSE 'Yes' END AS IsIncludeCoScholastic,
	
	CASE WHEN ISNULL(IsDisplayAttendance,0) = 0 THEN 'No' ELSE 'Yes' END AS IsDisplayAttendance,
	CASE WHEN ISNULL(IsDisplayHeightWeight,0) = 0 THEN 'No' ELSE 'Yes' END AS IsDisplayHeightWeight,
	CASE WHEN ISNULL(IsResultStatus,0) = 0 THEN 'No' ELSE 'Yes' END AS IsDisplayResultStatus,
	EM.Remark1,
	EM.Remark2,
	EM.Remark3,
	EM.DisplayTitle,
	ISNULL(EM.ExamMaximum,0) AS ExamMaximum,
	ISNULL(EM.FooterAdjustment,0) AS FooterAdjustment,
	ISNULL(EM.DetailAdjustment,0) AS DetailAdjustment,
	--ISNULL(EM.TermScopeId,0) AS TermScopeId,	
	TSM.Title AS TermScopeTitle,
	ISNULL(EM.ReportId,0) as ReportId,
	CASE WHEN ED.ClassSubjectId=CS.Id THEN 'Yes' ELSE 'false' END AS Selected,
	CASE WHEN ISNULL(IsShowSubjectMark,0)=0 THEN 'No' ELSE 'Yes' END AS IsShowSubjectMark,
	CASE WHEN ISNULL(EM.IsDisplayParentName,0)=0 THEN 'No' ELSE 'Yes' ENd AS IsDisplayParentName,
	ISNULL(EM.SubjectGroupPerPage,0)AS SubjectGroupPerPage,
	CASE WHEN ISNULL(EM.IsDisplayTeacherSign,0)=0 THEN 'No' ELSe 'Yes' END AS IsDisplayTeacherSign,
	CASE WHEN ISNULL(EM.IsDisplayPrincipalSign,0)=0 THEN 'No' ELSe 'Yes' ENd  AS IsDisplayPrincipalSign,
	CASE WHEN ISNULL(EM.PercentileScopeId,0)=0 THEN 'No' ELSE 'Yes' END AS PercentileScopeId ,
 	CASE WHEN 	ISNULL(EM.CoScholasticScopeId,0)=1 THEn 'Single' ELSE 'Combine' END AS CoScholasticScope,
 	CASE WHEN ISNULL(EM.IsExcludeAbsentTotal,0) = 0 THEN 'No' ELSE 'Yes' END AS IsExcludeAbsentTotal,
	ISNULL(EM.IsDisplayTotalMark,0) AS IsDisplayTotalMarks,
	CASE WHEN ISNULL(IsAllExamPassRequired,0)=0 THEN 'No' ELSE 'Yes' END AS IsAllExamPassRequired,
	CASE WHEN ISNULL(IsGenerateRankNo,0) = 0 THEN 'No' ELSE 'Yes' END AS IsGenerateRankNo,
	ISNULL(EM.ResultSheetAdditionalTitle,'')  AS ResultSheetAdditionalTitle,
	ISNULL(DM1.Title,'Default (No)') AS DisplayAttendence,
	ISNULL(DM2.Title,'Default (No)') AS ReportHeader
  FROM 
			--		sAssessment.tExamCombine EC
			--INNER JOIN 
			sAssessment.tExamMaster EM  
			INNER JOIN sAssessment.tExamSubGroupMaster	ESGM ON ESGM.Id = EM.ExamSubGroupId
			INNER JOIN sAssessment.tExamGroupMaster EGM ON EGM.Id=ESGM.ExamGroupId
			INNER JOIN sSetup.tClassMaster CM on CM.Id=EM.ClassId			
			INNER Join sSetup.tClassSubject CS ON EM.ClassId=CS.ClassId 
			INNER JOIN sSetup.tSubjectMaster SM on   CS.SubjectId=SM.Id
			LEFT JOIN sAssessment.tExamDetail ED ON ED.ClassSubjectId = CS.Id AND ED.ExamId=EM.Id
			Left Join sAssessment.tGradeSetMaster GSM ON GSM.Id = ED.GradeSetId
			LEFT JOIN sSetup.tTermScopeMaster TSM ON TSM.Id = EM.TermScopeId
			left Join sCommon.tDataMaster DM1 ON DM1.DataTypeId=14 And DM1.Id=EM.DisplayAttendanceId
			Left Join sCommon.tDataMaster DM2 ON DM2.DataTypeId=15 And DM1.Id=EM.ReportHeaderId
			
												
						
WHERE       
           
            (EM.Id=@rId OR @rId = 0)			 
            AND (ISNULL(EM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rExamIds,','))OR @rExamIds='')
			 
          	
			order by  DisplayOrder
		
END
GO
PRINT N'Altering [sAttendance].[pAttendanceFollowupDetailGet]...';


GO
 
 
ALTER PROCEDURE [sAttendance].[pAttendanceFollowupDetailGet]
	 	 
	 	 @rClassId int=0,
	 	 @rDivisionId int,
	 	 @rAttendanceTypeId tinyint,
		 @rFollowupDate date,
	 	 @rBatchId int,
	 	 @rOrgId int,
		 @rPresentStatus int,
		 @rCode nvarchar(20)=''
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	SELECT
	SA.AcademicId, 
	SA.ClassName +'-' + SA.DivisionName AS ClassDivision,
	SA.Code,
	SA.RollNo,
	SA.Name,
	SC.PresentContactNo,
	SC.PermanentContactNo,
	SC.EmergencyContactNo,
	SC.ParentContactNo,
	SC.StudentContactNo,
	--AF.Remark,
	CASE WHEN (ISNULL((SELECT 1 FROM [sAttendance].[tStudentLeaveRequest] WHERE AcademicId = SA.AcademicId AND @rFollowupDate BETWEEN LeaveFromDate AND LeaveToDate),0)
	= 1 AND (AF.Remark IS NULL OR AF.Remark = '')) THEN (SELECT LeaveReason FROM [sAttendance].[tStudentLeaveRequest] WHERE AcademicId = SA.AcademicId AND @rFollowupDate BETWEEN LeaveFromDate AND LeaveToDate)
	ELSE (
	replace (
	replace (
	replace (
	replace (
	replace (
	replace(AF.Remark,'\n','<br />'),
	'#amp;','&'),
	'#gt;','>'),
	'#quot;','\"'),
	'#lt;','<'),
	'#39;','''')) END AS Remark,
	ISNULL((SELECT 1 FROM [sAttendance].[tStudentLeaveRequest] WHERE AcademicId = SA.AcademicId AND @rFollowupDate BETWEEN LeaveFromDate AND LeaveToDate),0) AS IsOnLeave

	FROM
	sStudent.vStudentAcademic SA
	INNER JOIN sStudent.tStudentAdmission AD ON SA.StudentId = AD.StudentId 
	INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.AcademicId 
	--AND (SR.AttendanceTypeId = @rAttendanceTypeId)
	--AND (SR.AttendanceDate = @rFollowupDate)
	LEFT JOIN sAttendance.tAttendanceFollowup AF ON AF.AcademicId = SA.AcademicId AND SR.AttendanceTypeId = AF.AttendanceTypeId AND SR.AttendanceDate  = AF.FollowupDate
	LEFT JOIN sStudent.tStudentCommunication SC ON SA.StudentId = SC.StudentId
 
	WHERE 
		  ((SA.ClassId=@rClassId) OR (@rClassId=0))
		  AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		  AND (SA.OrgId = @rOrgId)
		  AND (SA.BatchId = @rBatchId)
		  AND (SA.StatusId NOT IN(2,3))
		  AND SR.IsPresent = @rPresentStatus
		  AND (AD.AdmissionDate <= @rFollowupDate)
		  AND ((SA.Code=@rCode)OR (ISNULL(@rCode,'')=''))
		  AND (SR.AttendanceTypeId = @rAttendanceTypeId)
		  AND (SR.AttendanceDate = @rFollowupDate)
END
GO
PRINT N'Altering [sAttendance].[pStudentRegisterGet]...';


GO
 
 
ALTER PROCEDURE [sAttendance].[pStudentRegisterGet]
	 	 
	 	 @rClassId int,
	 	 @rDivisionId int,
	 	 @rAttendanceTypeId tinyint,
		 @rAttendanceDate date,
		 @rSubjectId int,
		 @rSubjectBatchId int,
		 @rRepeatCount tinyint,
	 	 @rBatchId int,
	 	 @rOrgId int
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
IF @rSubjectBatchId=0
BEGIN
	IF @rRepeatCount=0
	BEGIN
	SELECT 
			SA.AcademicId,
			ISNULL(SA.RollNo,0) as RollNo,
			SA.Name,
			SA.Code,
			ISNULL(SR.IsPresent,'true') as IsPresent,
			ISNULL(SR.AbsentReasonId,0) as AbsentReasonId,
			case when SR.CreatedUserId IS NULL then 'false' else 'true' end as IsDeleted,
			SR.RepeatCount,
			EM.EmployeeId,
			EM.Code AS EmployeeCode,
			EM.EmployeeName,
			ISNULL(SR.AttendanceTagId,0) AS AttendanceTagId,
			ISNULL(SO.GenderId,0) AS GenderId,
			ISNULL(GM.Title,'') AS Gender,
			ISNULL(SR.AttendanceRemark,'') AS AttendanceRemark,
			(CASE WHEN SLR.AcademicId IS NOT NULL THEN 'On Leave' ELSE '' END) AS LeaveApply
			
  FROM 
            sStudent.vStudentAcademic SA 
            LEFT JOIN sStudent.tStudentOther SO ON SA.StudentId = SO.StudentId
            LEFT JOIN sCommon.tGenderMaster GM ON GM.Id = SO.GenderId
            INNER JOIN sStudent.tStudentAdmission AD ON SA.StudentId = AD.StudentId
			LEFT JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.AcademicId 
			AND (SR.AttendanceTypeId=@rAttendanceTypeId)
			AND (SR.AttendanceDate=@rAttendanceDate)
			AND (ISNULL(SR.SubjectId,0)=@rSubjectId)
			AND (ISNULL(SR.RepeatCount,0)=@rRepeatCount)
			LEFT JOIN sHrm.vExtEmployeeMaster EM ON EM.EmployeeId=SA.InchargeEmployeeId
			LEFT JOIN sAttendance.tStudentLeaveRequest SLR ON SLR.AcademicId=SA.AcademicId AND SLR.StatusId = 550 
			AND @rAttendanceDate >= SLR.LeaveFromDate AND @rAttendanceDate <=SLR.LeaveToDate
  WHERE 
		  ((SA.ClassId=@rClassId) OR (@rClassId=0))
	  AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
      AND (SA.OrgId = @rOrgId)
      AND (SA.BatchId = @rBatchID)
	  AND (SA.StatusId NOT IN (2,3))
      AND (AD.LeftDate > @rAttendanceDate OR ISNULL(AD.LeftDate,'')= '')
      AND (AD.AdmissionDate <= @rAttendanceDate)
      ORDER BY RollNo
  END
  ELSE
  BEGIN
	SELECT 
			SA.AcademicId,
			ISNULL(SA.RollNo,0) as RollNo,
			SA.Name,
			SA.Code,
			ISNULL(SR.IsPresent,'true') as IsPresent,
			ISNULL(SR.AbsentReasonId,0) as AbsentReasonId,
			case when SR.CreatedUserId IS NULL then 'false' else 'true' end as IsDeleted,
			SR.RepeatCount,
			EM.EmployeeId,
			EM.Code AS EmployeeCode,
			EM.EmployeeName,
			ISNULL(SR.AttendanceTagId,0) AS AttendanceTagId,
			ISNULL(SR.AttendanceRemark,'') AS AttendanceRemark,
			(CASE WHEN SLR.AcademicId IS NOT NULL THEN 'On Leave' ELSE '' END) AS LeaveApply
  FROM 
            sStudent.vStudentAcademic SA 
            INNER JOIN sStudent.tStudentAdmission AD ON SA.StudentId = AD.StudentId
        LEFT JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.AcademicId 
			AND (SR.AttendanceTypeId=@rAttendanceTypeId)
			AND (SR.AttendanceDate=@rAttendanceDate)
			AND ((ISNULL(SR.SubjectId,0)=@rSubjectId) OR (@rSubjectId=0))
			AND ((ISNULL(SR.RepeatCount,0)=@rRepeatCount) OR (@rRepeatCount=0))
		LEFT JOIN sHrm.vExtEmployeeMaster EM ON EM.EmployeeId=SA.InchargeEmployeeId
		LEFT JOIN sAttendance.tStudentLeaveRequest SLR ON SLR.AcademicId=SA.AcademicId 
			AND @rAttendanceDate >= SLR.LeaveFromDate AND @rAttendanceDate <=SLR.LeaveToDate
  WHERE 
		  ((SA.ClassId=@rClassId) OR (@rClassId=0))
	  AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
      AND (SA.OrgId = @rOrgId)
      AND (SA.BatchId = @rBatchID)
	  AND (SA.StatusId NOT IN(2,3))
      AND (AD.LeftDate > @rAttendanceDate OR ISNULL(AD.LeftDate,'')= '')
      AND (AD.AdmissionDate <= @rAttendanceDate)
      ORDER BY RollNo
  END
END
ELSE
BEGIN
	IF @rRepeatCount=0
	BEGIN
	SELECT 
			SA.AcademicId,
			ISNULL(SA.RollNo,0) as RollNo,
			SA.Name,
			SA.Code,
			ISNULL(SR.IsPresent,'true') as IsPresent,
			ISNULL(SR.AbsentReasonId,0) as AbsentReasonId,
			case when SR.CreatedUserId IS NULL then 'false' else 'true' end as IsDeleted,
			SR.RepeatCount,
			EM.EmployeeId,
			EM.Code AS EmployeeCode,
			EM.EmployeeName,
			ISNULL(SR.AttendanceTagId,0) AS AttendanceTagId,
			ISNULL(SR.AttendanceRemark,'') AS AttendanceRemark,
			(CASE WHEN SLR.AcademicId IS NOT NULL THEN 'On Leave' ELSE '' END) AS LeaveApply
  FROM 
            sStudent.vStudentAcademic SA
             INNER JOIN sStudent.tStudentAdmission AD ON SA.StudentId = AD.StudentId 
        LEFT JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.AcademicId 
			AND (SR.AttendanceTypeId=@rAttendanceTypeId)
			AND (SR.AttendanceDate=@rAttendanceDate)
			AND (ISNULL(SR.SubjectId,0)=@rSubjectId)
			AND (ISNULL(SR.RepeatCount,0)=@rRepeatCount)
		INNER JOIN sAttendance.tSubjectBatchStudent SBS ON SBS.AcademicId=SA.AcademicId 
			AND SBS.BatchId=@rBatchId AND SBS.SubjectBatchId=@rSubjectBatchId
		LEFT JOIN sHrm.vExtEmployeeMaster EM ON EM.EmployeeId=SA.InchargeEmployeeId
		LEFT JOIN sAttendance.tStudentLeaveRequest SLR ON SLR.AcademicId=SA.AcademicId 
			AND @rAttendanceDate >= SLR.LeaveFromDate AND @rAttendanceDate <=SLR.LeaveToDate
  WHERE 
		  ((SA.ClassId=@rClassId) OR (@rClassId=0))
	  AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
      AND (SA.OrgId = @rOrgId)
      AND (SA.BatchId = @rBatchID)
	  AND (SA.StatusId NOT IN(2,3))
      AND (AD.LeftDate > @rAttendanceDate OR ISNULL(AD.LeftDate,'')= '')
      AND (AD.AdmissionDate <= @rAttendanceDate)
      ORDER BY RollNo
  END
  ELSE
  BEGIN
	SELECT 
			SA.AcademicId,
			ISNULL(SA.RollNo,0) as RollNo,
			SA.Name,
			SA.Code,
			ISNULL(SR.IsPresent,'true') as IsPresent,
			ISNULL(SR.AbsentReasonId,0) as AbsentReasonId,
			case when SR.CreatedUserId IS NULL then 'false' else 'true' end as IsDeleted,
			SR.RepeatCount,
			EM.EmployeeId,
			EM.Code AS EmployeeCode,
			EM.EmployeeName,
			ISNULL(SR.AttendanceTagId,0) AS AttendanceTagId,
			ISNULL(SR.AttendanceRemark,'') AS AttendanceRemark,
			(CASE WHEN SLR.AcademicId IS NOT NULL THEN 'On Leave' ELSE '' END) AS LeaveApply
  FROM 
            sStudent.vStudentAcademic SA 
             INNER JOIN sStudent.tStudentAdmission AD ON SA.StudentId = AD.StudentId
        LEFT JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.AcademicId 
			AND (SR.AttendanceTypeId=@rAttendanceTypeId)
			AND (SR.AttendanceDate=@rAttendanceDate)
			AND ((ISNULL(SR.SubjectId,0)=@rSubjectId) OR (@rSubjectId=0))
			AND ((ISNULL(SR.RepeatCount,0)=@rRepeatCount) OR (@rRepeatCount=0))
		INNER JOIN sAttendance.tSubjectBatchStudent SBS ON SBS.AcademicId=SA.AcademicId 
			AND SBS.BatchId=@rBatchId AND SBS.SubjectBatchId=@rSubjectBatchId
		LEFT JOIN sHrm.vExtEmployeeMaster EM ON EM.EmployeeId=SA.InchargeEmployeeId
		LEFT JOIN sAttendance.tStudentLeaveRequest SLR ON SLR.AcademicId=SA.AcademicId 
			AND @rAttendanceDate >= SLR.LeaveFromDate AND @rAttendanceDate <=SLR.LeaveToDate
  WHERE 
		  ((SA.ClassId=@rClassId) OR (@rClassId=0))
	  AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
      AND (SA.OrgId = @rOrgId)
      AND (SA.BatchId = @rBatchID)
	  AND (SA.StatusId NOT IN(2,3))
       AND (AD.LeftDate > @rAttendanceDate OR ISNULL(AD.LeftDate,'')= '')
      AND (AD.AdmissionDate <= @rAttendanceDate)
      ORDER BY RollNo
  END
END
END
GO
PRINT N'Altering [sCertificate].[pRptBonafiedCertificateGet]...';


GO


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

DECLARE @lIsShowPhoto bit = 0
DECLARE @lIsOnPrePrinted bit = 0
DECLARE @lIsDisplayReligion bit=0
DECLARE @lIsDisplayImageHeader bit=0

DECLARE @lConfigValue nvarchar(50)
Declare @lIDConfigValue nvarchar(50)='',@lOrgGroupId int=0


	SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 124 AND SourceTypeId = 1016 AND SourceId = @rOrgId
	
	IF (@lConfigValue IS NULL) OR (@lConfigValue = 'False')
	SET @lIsShowPhoto = 0
	ELSE
	SET @lIsShowPhoto = 1
	
	SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 177 AND SourceTypeId = 1016 AND SourceId = @rOrgId
	
	IF (@lConfigValue IS NULL) OR (@lConfigValue = 'Default')
	BEGIN
	SET @lIsOnPrePrinted = 0
	SET @lIsDisplayImageHeader = 0
	END
	ELSE IF (@lConfigValue = 'Blank')
	BEGIN
	SET @lIsOnPrePrinted = 1
	SET @lIsDisplayImageHeader = 0
	END
	ELSE IF (@lConfigValue = 'Image')
	BEGIN
	SET @lIsOnPrePrinted = 0
	SET @lIsDisplayImageHeader = 1
	END
	
	
	SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 157 AND SourceTypeId = 1016 AND SourceId = @rOrgId
	
	IF (@lConfigValue IS NULL) OR (@lConfigValue = 'False')
	SET @lIsDisplayReligion = 0
	ELSE
	SET @lIsDisplayReligion = 1
	
	Select @lOrgGroupId = OrgGroupId From  sSetup.tOrganizationMaster Where Id = @rOrgId
	SELECT @lIDConfigValue =ItemValue From sConfig.tConfigurationSetup
	WHERE ConfigurationId = 236 AND SourceId = @lOrgGroupId
	--SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 158 AND SourceTypeId = 1016 AND SourceId = @rOrgId
	
	--IF (@lConfigValue IS NULL) OR (@lConfigValue = 'False')
	--SET @lIsDisplayImageHeader = 0
	--ELSE
	--SET @lIsDisplayImageHeader = 1	
	
	
	
	SELECT 	
			@rBuilder1 AS Builder1,
		    @rBuilder2 AS Builder2,
			B.Id,
			B.Number,
			B.AcademicId,
			SM.Code,
			--SM.FirstName+' '+SM.MiddleName+' '+SM.LastName AS Name,
			   [sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Name,
			CM.DisplayTitle+' - '+DM.DisplayTitle AS Class,
			BM.Title AS Batch,
			SM.FirstName,
			SM.MiddleName,
			SM.LastName,
			SO.DateOfBirth,
			ISNULL(SO.BirthDateInWord,'') AS DOBInWords,
			ISNULL(SO.BirthPlace,'') AS BirthPlace,
			ISNULL(SO.BirthTaluka,'') AS Taluka,
			ISNULL(SO.BirthDistrict,'')	AS District,		
			B.BonafideDate,
			ISNULL(SO.FamilyCast,'') AS Caste,
			ISNULL(SO.FamilySubCast,'') AS SubCaste,
			ISNULL(OM.CityName,'') AS City,
			ISNULL(OM.StateName,'') AS CityState,
			SO.GenderId,
			SI.StudentPhoto,
			OM.OrgLogo,
			OM.Title AS OrgTitle,
			--OM.StreetOne+' '+OM.StreetTwo+' '+OM.StreetThree AS OrgAddress,
			--OM.PhoneNo,
			SM.StatusId,
			A.RollNo,
			DM.OrderIndex AS DivisionOrder,
			ATM.Title AS AffiliationType,
			OM.ReportOrgTitle,
			OM.SmallAddress1,
			OM.SmallAddress2,
			OM.RegistrationDetail,
			ISNULL(RM.Title,'') AS ReligionName,
			@lIsShowPhoto AS IsShowPhoto,
			@lIsOnPrePrinted AS IsOnPrePrinted,
			@lIsDisplayReligion AS IsDisplayReligion,
			B.Remark AS ReceiptNo,
			SF.FatherName,
			SA.AdmissionDate,
			DP.Title AS DepartmentName,
			ISNULL(OM.DegreeAwarded,'') AS DegreeAwarded,
			@lIsDisplayImageHeader AS IsDisplayImageHeader,
			--OI.CertificateHeaderA4,
			REPLICATE(',',OM.LetterHeadMargin)    AS LetterHeadMargin,
			ISNULL(B.BonafiedReason,'') AS BonafiedReason,
			CT.Title AS Category,
			SF.MotherName,
			C.PermanentStreetOne,
			C.PermanentStreetTwo,
			C.PermanentStreetThree,
			C.PermanentCountry,
			C.PermanentState,
			C.PermanentCity,
			C.PermanentZipCode,
			C.PermanentContactNo,
			C.PresentStreetOne,
			C.PresentStreetTwo,
			C.PresentStreetThree,
			C.PresentCountry,
			C.PresentState,
			C.PresentCity,
			C.PresentContactNo,
			C.PresentZipCode,
			SM.SUId,
			SO.AdhaarNumber,
			CM.DisplayTitle AS ClassName,
			ISNULL(CTM.Nationality,'') AS Nationality,
			OM.PrincipalSignature,
			ISnull(AR.SourceId,0) AS StudentidForhostel,
			DM.DisplayTitle AS Divisionname,
			@lIDConfigValue AS ItemValue ,
			SM.RecordStatusId,
			SO.BirthState AS BirthState,
			CM1.Title AS AdmissionStandard,
			RRG.SchoolRemark1,
			RRG.SchoolRemark2,
			RRG.SchoolRemark3,
			SF.FatherAdhaarNumber AS FatherAadharNo,
			SF.MotherAdhaarNumber AS MotherAadharNo,
			ISNULL(OM.ReportOrgGroupTitle,'') AS ReportOrgGroupTitle,
			OM.ReportOrgTitle,
			--OI.CertificateHeaderA4,
			OI.CertificateHeaderA4Portrait AS CertificateHeaderA4,
			SM.Id AS StudentId,
			(CASE WHEN RRG.SchoolRequiredSignature IS NULL THEN NULL ELSE RRG.SchoolRequiredSignature END) AS SchoolRequiredSignature ,
			SO.UIDNumber,
			ISNULL(EI.EmployeeSign,0x) AS EmployeeSign,
			ISNULL(SA.AdmissionNumber,'') AS AdmissionNumber
		
	FROM 
			sCertificate.tBonafide B
			
			INNER JOIN sStudent.tAcademic A ON B.AcademicId=A.Id
			LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=A.StudentId
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId
			LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
			INNER JOIN sSetup.tDivisionMaster DM ON A.DivisionId = DM.Id  
			INNER JOIN sSetup.tClassMaster CM ON CM.Id= DM.ClassId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id=A.BatchId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId
			left JOIN sSetup.tOrgImages OI ON OI.OrgId = OM.Id
			INNER JOIN sSetup.tAffiliationMaster AM ON OM.AffiliationId = AM.Id
			INNER JOIN sSetup.tAffiliationTypeMaster ATM ON AM.AffiliationTypeId = ATM.Id
			LEFT JOIN sCommon.tReligionMaster RM ON SO.ReligionId=RM.Id
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SM.Id
			INNER JOIN sStudent.tStudentAdmission SA ON SA.StudentId = SM.Id
			LEFT JOIN sSetup.tClassMaster CM1 ON CM1.Id = SA.AdmissionStandardId
			INNER JOIN sSetup.tDepartmentMaster DP ON CM.DepartmentId = DP.Id
			LEFT JOIN sCommon.tCastCategoryMaster CT ON CT.Id = SO.CastCategoryId
			LEFT JOIN sStudent.tStudentCommunication C ON C.StudentId = A.StudentId
			LEFT JOIN sCommon.tCountryMaster CTM ON CTM.Id=SO.NationalityId
			LEFT JOIN SHostel.tAssignRoom Ar On Ar.SourceId=A.StudentId AND Ar.OrgGroupBatchId=@rOrgGroupBatchId 
			LEFT JOIN sCommon.tReportRemarkGroupOrg RRG ON RRG.OrgId = OM.Id AND ReportRemarkGroupId=6
			LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = DM.InchargeEmployeeId
			--INNER JOIN sSetup.tTermMaster TM ON  TM.ID=
	WHERE 
			A.OrgId=@rOrgId
			AND	A.BatchId = @rBatchId 
			AND ((A.ClassId=@rClassId) OR (@rClassId=0))
			AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			AND ((SM.Code = @rCode) OR (ISNULL(@rCode,'') = ''))
			AND ((SM.FirstName = @rName) OR (ISNULL(@rName,'') = ''))
			--AND ((B.BonafideDate=@rBonafiedDate) OR (ISNULL(@rBonafiedDate,'')=''))
			AND ((B.Number=@rNumber) OR (@rNumber=''))
			AND ((B.Number >= @rFromNo) OR (@rFromNo=''))
			AND ((B.Number <= @rToNo) OR (@rToNo=''))
			AND ((B.BonafideDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((B.BonafideDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			--Group By B.AcademicId,SM.Code,SM.FirstName,SM.LastName,SM.MiddleName,CM.DisplayTitle,BM.Title,SO.DateOfBirth,SO.BirthDateInWord,
			--SO.BirthPlace,SO.BirthTaluka,SO.BirthDistrict,B.BonafideDate,OM.CityName,OM.StateName,SO.FamilyCast,SO.FamilySubCast,SO.GenderId,SI.StudentPhoto,SM.StatusId,
			--OM.OrgLogo,OM.PhoneNo,OM.Title,OM.StreetOne,OM.StreetTwo,OM.StreetThree
	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 FROM sFee.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
DELETE FROM sHrm.tEmployeeBatch WHERE CAST(LEFT([EmployeeId], 4) AS bigint) = @rOrgId
DELETE FROM sCommunication.tEmployeeDocumentUpload WHERE OrgId = @rOrgId

DELETE FROM [sHrm].[tEmployeeCustomFieldData] WHERE CAST(LEFT([EmployeeId], 4) AS bigint) = @rOrgId

DELETE FROM [sCommunication].[tDailyThoughtAssign] WHERE OrgId= @rOrgId
DELETE FROM [sFee].[tEMandate] WHERE CAST(LEFT(Id, 4) AS bigint) = @rOrgId

DELETE FROM [sAdmission].[tAdmissionInquiryCriteria] WHERE CAST(LEFT([ClassId], 4) AS int) = @rOrgId
DELETE FROM [sCommon].[tSubmitDocumentScope] WHERE CAST(LEFT([SubmitDocumentId], 4) AS int) = @rOrgId

DELETE FROM sAcademic.tOnlineLearningRecording WHERE CAST(LEFT([OnlineLearningId], 4) AS bigint) = @rOrgId

DELETE FROM [sCommon].[tUserToken] WHERE CAST(LEFT([UserId], 4) AS bigint) = @rOrgId

DELETE FROM [sBiometric].[tEmployeeConfiguration] WHERE CAST(LEFT([EmployeeId], 4) AS bigint) = @rOrgId
DELETE FROM sAlert.tWhatsAppConfiguration WHERE OrgId= @rOrgId
DELETE FROM sFee.tDepositSetup WHERE CAST(LEFT([StudentId], 4) AS bigint) = @rOrgId
DELETE FROM [sAlert].[tWhatsAppLog] WHERE CAST(LEFT([SourceId], 4) AS bigint) = @rOrgId

DELETE FROM sAcademic.tOnlineLearningHistoryLog WHERE CAST(LEFT([BatchId], 4) AS int) = @rOrgId

DELETE FROM [sAlert].[tAlertTrack] WHERE OrgId = @rOrgId
DELETE FROM sTally.tJVPosting WHERE CAST(LEFT([StudentId], 4) AS bigint) = @rOrgId

DELETE FROM [sHrm].[tLeavePeriod] WHERE OrgId = @rOrgId
DELETE FROM [sRecruitment].[tAssignOrganization] WHERE OrgId = @rOrgId

DELETE FROM sAdmission.tAdmissionCustomSearch WHERE OrgId = @rOrgId

DELETE FROM[sCommunication].[tTempQueryCategoryScope] WHERE CAST(LEFT([SourceId], 4) AS bigint) = @rOrgId


DELETE FROM [sStudent].[tOnlineRegistrationStudentAdmission] WHERE CAST(LEFT([StudentId], 4) AS bigint) = @rOrgId
DELETE FROM [sStudent].[tOnlineRegistrationStudentCommunication] WHERE CAST(LEFT([StudentId], 4) AS bigint) = @rOrgId
DELETE FROM [sStudent].[tOnlineRegistrationStudentCustomFieldData] WHERE CAST(LEFT([StudentId], 4) AS bigint) = @rOrgId
DELETE FROM [sStudent].[tOnlineRegistrationStudentDocument] WHERE CAST(LEFT([StudentId], 4) AS bigint) = @rOrgId
DELETE FROM [sStudent].[tOnlineRegistrationStudentFamily] WHERE CAST(LEFT([StudentId], 4) AS bigint) = @rOrgId
DELETE FROM [sStudent].[tOnlineRegistrationStudentImages] WHERE CAST(LEFT([StudentId], 4) AS bigint) = @rOrgId
DELETE FROM [sStudent].[tOnlineRegistrationStudentOther] WHERE CAST(LEFT([StudentId], 4) AS bigint) = @rOrgId
DELETE FROM [sStudent].[tOnlineRegistrationCollegeDetail] WHERE CAST(LEFT([StudentId], 4) AS bigint) = @rOrgId
DELETE FROM [sStudent].[tOnlineRegistrationDisplayField]  WHERE CAST(LEFT([BatchId], 4) AS int) = @rOrgId
DELETE FROM [sStudent].[tOnlineRegistrationCriteriaDocument]  WHERE CAST(LEFT([BatchId], 4) AS int) = @rOrgId
DELETE FROM [sStudent].[tOnlineRegistrationCriteriaForm]  WHERE CAST(LEFT([BatchId], 4) AS int) = @rOrgId
DELETE FROM [sStudent].[tOnlineRegistrationStudentMaster] WHERE OrgId = @rOrgId

DELETE FROM [sBiometric].[tShiftAllocationCloud] WHERE CAST(LEFT([SourceId], 4) AS bigint) = @rOrgId
DELETE FROM [sBiometric].[tCloudTransactionData] WHERE CAST(LEFT([SourceId], 4) AS bigint) = @rOrgId

DELETE FROM [sTransport].[tAssignRouteLog] WHERE CAST(LEFT([SourceId], 4) AS bigint) = @rOrgId
DELETE FROM [sAttendance].[tAttendanceFollowup] WHERE CAST(LEFT([AcademicId], 4) AS bigint) = @rOrgId

DELETE FROM sAssessment.tAssessmentLabelSetup WHERE OrgId = @rOrgId
DELETE FROM [sAssessment].[tStudentExamRemark] WHERE CAST(LEFT([AcademicId], 4) AS bigint) = @rOrgId
DELETE FROM [sBiometric].[tDeviceMasterCloud] WHERE OrgId = @rOrgId

DELETE FROM [sHrm].[tDigitalForm] WHERE OrgId = @rOrgId
DELETE FROM [sHrm].[tDigitalFormField] WHERE CAST(LEFT([DigitalFormId], 4) AS int) = @rOrgId
DELETE FROM [sHrm].[tDigitalFormScope] WHERE CAST(LEFT([DigitalFormId], 4) AS int) = @rOrgId
DELETE FROM [sHrm].[tDigitalFormEmployee] WHERE CAST(LEFT([DigitalFormId], 4) AS int) = @rOrgId
DELETE FROM [sAdmission].[tAdmissionOptionalSubject] WHERE CAST(LEFT([AdmissionFormId], 4) AS bigint) = @rOrgId
DELETE FROM [sStudent].[tOnlineRegistrationStudentOptionalSubject] WHERE CAST(LEFT([OnlineRegistrationStudentId], 4) AS bigint) = @rOrgId
DELETE FROM [sStudent].[tOnlineRegistrationCriteria] WHERE CAST(LEFT([BatchId], 4) AS int) = @rOrgId
DELETE FROM [sStudent].[tOnlineRegistrationCriteriaOptionalSubject] WHERE CAST(LEFT([BatchId], 4) AS int) = @rOrgId
DELETE FROM [sAdmission].[tAdmissionCriteriaOptionalSubject] 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 [sCommon].[pPrefixSetupAdd]...';


GO
 
ALTER PROCEDURE [sCommon].[pPrefixSetupAdd]
	@rOrgId [smallint],
	@rPrefixFunctionalityId [int],
	@rPrefix [nvarchar](10),
	@rEffectiveDate [datetime],
	@rIsObsolete [bit],
	@rCreatedUserId [bigint],
	@rSpecifiedPrefixLength [int],
	@rStoreLocationId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

    DECLARE @rSeriesTypeId INT
		
   select  @rSeriesTypeId = SeriesTypeId From sCommon.tPrefixFunctionality Where Id =  @rPrefixFunctionalityId

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

	IF NOT EXISTS (SELECT 1 FROM sCommon.tPrefixSetup WHERE StoreLocationId = @rStoreLocationId AND Prefix = @rPrefix AND OrgId = @rOrgId AND PrefixFunctionalityId = @rPrefixFunctionalityId)
	BEGIN
	INSERT INTO sCommon.tPrefixSetup
		(
			OrgId,
			Id,		
			PrefixFunctionalityId,			
			Prefix,
			EffectiveDate,
			IsObsolete,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime, 
			NumberLength,
			StoreLocationId
		)
	VALUES
		(
			@rOrgId,
			@lNextNumber,
			@rPrefixFunctionalityId,
			@rPrefix,
			@rEffectiveDate,
			@rIsObsolete,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rCreatedUserId,
			sCommon.fGetDate(), 
			@rSpecifiedPrefixLength,
			CASE @rSeriesTypeId 
			   WHEN 3 THEN @rStoreLocationId
			   WHEN 2 THEN 0
			   WHEN 1 THEN 0
			  END
		)
		END
		SELECT 1 AS RESULT
END
GO
PRINT N'Altering [sCommunication].[pAllPhotoCategory_Get]...';


GO
ALTER PROCEDURE [sCommunication].[pAllPhotoCategory_Get]
	 @rId int = 0,
	 @rSyncedPhotoCategoryId int = 0,
	 @rBatchId int,
	 @rIsDivisionWise bit=true,
	 @rBatchYear int = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	
    DECLARE @lOrgGroupId smallint,@lOrgGroupBatchID int,@lOrgId smallint
    
	SELECT @lOrgGroupId=OM.OrgGRoupId FROM sSetup.tOrganizationMaster OM
	INNER JOIN sSetup.tBatchMaster BM ON BM.OrgId=OM.Id
	WHERE Bm.Id=@rBatchId
    IF(@rIsDivisionWise=0)
    BEGIN
		SELECT   
			PCM.[Id]
			,PCM.[Title]
			,PCM.[IsObsolete]
			,ISNULL(PCM.ScopeSourceTypeId,0) AS ScopeSourceTypeId
			,ISNULL(PCM.Remark,'') AS Remark,
			PCM.CreatedDateTime,
			CASE WHEN ISNULL(PCM.ScopeSourceTypeId,0) = 2021 THEN 'Organization'
			WHEN ISNULL(PCM.ScopeSourceTypeId,0) = 2017 THEN 'Department' 
			WHEN ISNULL(PCM.ScopeSourceTypeId,0) = 2016 THEN 'Class' 
			WHEN ISNULL(PCM.ScopeSourceTypeId,0) = 2005 THEN 'Division' 
			WHEN ISNULL(PCM.ScopeSourceTypeId,0) = 2014 THEN 'Hostel' 
			WHEN ISNULL(PCM.ScopeSourceTypeId,0) = 2029 THEN 'House' 
			END +' - '+ [sCommunication].[fPhotoCategoryScopeGet](PCM.Id,PCM.ScopeSourceTypeId) AS ScopeSourceType,
			U.DisplayTitle AS UserName,
			ISNULL(PCM.OrgGroupBatchId,0) AS OrgGroupBatchId
		FROM    
			[sCommunication].[tPhotoCategoryMaster]  PCM 
			INNER JOIN sSecurity.tUser U ON PCM.CreatedUserId = U.Id
		WHERE   
			((PCM.Id = @rId) OR (@rId = 0))
			AND ((PCM.Id > @rSyncedPhotoCategoryId) OR (@rSyncedPhotoCategoryId = 0))
			AND OrgGroupId=@lOrgGroupId
			AND PCM.IsObsolete =0
			AND ((YEAR(PCM.CreatedDateTime) = @rBatchYear) OR (@rBatchYear = 0))
		ORDER BY 
			PCM.CreatedDateTime DESC
	END		
	ELSE
	
	 BEGIN
		SELECT   
			PCM.[Id]
			,PCM.[Title]
			,PCM.[IsObsolete]
			,ISNULL(PCM.ScopeSourceTypeId,0) AS ScopeSourceTypeId
			,ISNULL(PCM.Remark,'') AS Remark,
			PCM.CreatedDateTime,
			CASE WHEN ISNULL(PCM.ScopeSourceTypeId,0) = 2021 THEN 'Organization'
			WHEN ISNULL(PCM.ScopeSourceTypeId,0) = 2017 THEN 'Department' 
			WHEN ISNULL(PCM.ScopeSourceTypeId,0) = 2016 THEN 'Class' 
			WHEN ISNULL(PCM.ScopeSourceTypeId,0) = 2005 THEN 'Division' 
			WHEN ISNULL(PCM.ScopeSourceTypeId,0) = 2014 THEN 'Hostel' 
			WHEN ISNULL(PCM.ScopeSourceTypeId,0) = 2029 THEN 'House' 
			END +' - '+ [sCommunication].[fPhotoCategoryScopeGet](PCM.Id,PCM.ScopeSourceTypeId) AS ScopeSourceType,
			U.DisplayTitle AS UserName,
			ISNULL(PCM.OrgGroupBatchId,0) AS OrgGroupBatchId
		FROM    
			[sCommunication].[tPhotoCategoryMaster]  PCM 
			INNER JOIN sSecurity.tUser U ON PCM.CreatedUserId = U.Id
		WHERE   
			((PCM.Id = @rId) OR (@rId = 0))
			AND ((PCM.Id > @rSyncedPhotoCategoryId) OR (@rSyncedPhotoCategoryId = 0))
			AND OrgGroupId=@lOrgGroupId
			AND ScopeSourceTypeId=2005
			AND PCM.IsObsolete =0
			AND ((YEAR(PCM.CreatedDateTime) = @rBatchYear) OR (@rBatchYear = 0))
		ORDER BY 
			PCM.CreatedDateTime DESC
	END		
END
GO
PRINT N'Altering [sCommunication].[pPhotoCategoryMaster_Get]...';


GO
ALTER PROCEDURE [sCommunication].[pPhotoCategoryMaster_Get]
	 
	 @rScopeSourceId bigint=0,
	 @rId int = 0,
	 @rSyncedPhotoCategoryId int = 0,
	 @rSourcetypeId smallint,
	 @rBatchId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 

	DECLARE @lOrgGroupId smallint,@lOrgGroupBatchID int,@lOrgId smallint
  
	IF @rSourcetypeId=2003
	BEGIN
		SELECT @lOrgGroupId=Om.OrgGroupId,@lOrgId=OM.Id ,@lOrgGroupBatchID=BM.OrgGroupBatchId  
		FROM sSetup.tOrganizationMaster OM INNER JOIN sStudent.tAcademic A ON A.OrgId=OM.Id
		INNER JOIN sSetup.tBatchMaster BM ON  BM.Id=A.BatchId 
		WHERE A.BatchId= @rBatchId AND A.Id=@rScopeSourceId 
	END
	ELSE IF @rSourcetypeId=95
	BEGIN
		SELECT @lOrgGroupId=Om.OrgGroupId, @lOrgId=OrgId 
		FROM sSetup.tOrganizationMaster OM INNER JOIN sHrm.tEmployeeMaster EM ON EM.OrgID=OM.Id 
		WHERE Em.Id=@rScopeSourceId AND ISNULL(EM.IsOtherUser,0) = 0
	END
	ELSE
	BEGIN
		SELECT @lOrgGroupId=OM.OrgGRoupId 
		FROM sSetup.tOrganizationMaster OM INNER JOIN sSetup.tBatchMaster BM ON BM.OrgId=OM.Id 
		WHERE Bm.Id=@rBatchId
	END
 
	IF @rSourcetypeId=2003
	BEGIN
	SELECT   
		PCM.[Id],
  		PCM.[Title],
		PCM.[IsObsolete],
		ISNULL(PCM.ScopeSourceTypeId,0) AS ScopeSourceTypeId,
		ISNULL(Remark,'') AS Remark,
		ISNULL(PCM.OrgGroupBatchId,0) AS OrgGroupBatchId
	FROM 
		[sCommunication].[tPhotoCategoryMaster] PCM 
		LEFT JOIN sCommunication.tPhotoCategoryScope PCS  ON PCM.Id = PCS.PhotoCateGoryId 
		AND (PCS.ScopeSourceId = CASE WHEN PCM.ScopeSourceTypeId = 2005 THEN
		(SELECT DivisionId FROM sStudent.tAcademic WHERE DivisionId = PCS.ScopeSourceId And Id = @rScopeSourceId)
		WHEN PCM.ScopeSourceTypeId = 2016 THEN
		(SELECT ClassId FROM sStudent.tAcademic WHERE DivisionId = PCS.ScopeSourceId And Id = @rScopeSourceId)
		WHEN PCM.ScopeSourceTypeId = 2017 THEN
		(SELECT D.Id FROM sSetup.tDepartmentMaster D INNER JOIN sSetup.tClassMaster CA ON CA.DepartmentId=D.Id 
		INNER JOIN sStudent.tAcademic A ON A.ClassID=CA.Id WHERE A.Id =@rScopeSourceId)
		WHEN PCM.ScopeSourceTypeId =2021 THEN
		(SELECT OM.Id FROM sSetup.tOrganizationMaster OM INNER JOIN sStudent.tAcademic A ON A.OrgId =OM.Id WHERE A.Id=@rScopeSourceId)
		WHEN PCM.ScopeSourceTypeId =2014 THEN
		(SELECT Hm.Id FROM sHostel.tHostelMaster Hm INNER JOIN  sHostel.tRoomMaster RA ON RA.HostelId=HM.Id 
		INNER JOIN sHostel.tAssignRoom AR ON AR.RoomId=RA.Id
		INNER JOIN sStudent.tAcademic A ON A.StudentId=AR.SourceId 
		WHERE AR.OrgGroupBatchId = @lOrgGroupBatchID AND HM.OrgGroupId=@lOrgGroupId AND A.Id=@rScopeSourceId)
		WHEN PCM.ScopeSourceTypeId =2029 THEN
		(SELECT HO.Id FROM sActivity.tHouseMaster HO
		INNER JOIN sStudent.tStudentOther SO ON SO.HouseId=HO.Id 
		INNER JOIN sStudent.tAcademic A ON A.StudentId=SO.StudentId
		WHERE HO.OrgId=@lOrgId AND A.Id=@rScopeSourceId)
		ENd)
	WHERE 
		PCM.IsObsolete=0	
		AND (PCM.Id=@rId OR @rId=0) 
		AND PCM.OrgGroupId = @lOrgGroupId
	ORDER BY PCM.CreatedDateTime DESC
	END
	ELSE IF @rSourcetypeId=95
	BEGIN 
	SELECT
		PCM.[Id],
		PCM.[Title],
		PCM.[IsObsolete],
		ISNULL(PCM.ScopeSourceTypeId,0) AS ScopeSourceTypeId,
		ISNULL(Remark,'') AS Remark,
		ISNULL(PCM.OrgGroupBatchId,0) AS OrgGroupBatchId
	FROM 
		[sCommunication].[tPhotoCategoryMaster] PCM 
		LEFT join sCommunication.tPhotoCategoryScope PCS  ON PCM.Id = PCS.PhotoCateGoryId AND
		(PCS.ScopeSourceId = Case WHEN PCM.ScopeSourceTypeId = 2017 THEN
		(SELECT D.Id FROM sSetup.tDepartmentMaster D 
		INNER JOIN sHrm.tEmployeeJobDetail EJ ON EJ.OrganizationDepartmentId=D.Id
		WHERE EJ.EmployeeId=@rScopeSourceId AND EJ.OrgId=@lOrgId)
		WHEN PCM.ScopeSourceTypeId=2021 THEN
		(SELECT OM.Id FROM sSetup.tOrganizationMaster OM 
		INNER JOIN sHrm.tEmployeeMaster EM ON EM.OrgId=OM.Id
		WHERE EM.OrgId=@lOrgId and Em.Id=@rScopeSourceId AND ISNULL(EM.IsOtherUser,0) = 0)
		END)
	WHERE 
		PCM.IsObsolete=0 
		AND ((PCM.Id = @rId) OR (@rId=0)) 
		AND PCM.OrgGroupId = @lOrgGroupId
		ORDER BY PCM.CreatedDateTime DESC
	END
	ELSE
	BEGIN
	SELECT   
		PCM.[Id],
  		PCM.[Title],
		PCM.[IsObsolete],
		ISNULL(PCM.ScopeSourceTypeId,0) AS ScopeSourceTypeId,
		ISNULL(Remark,'') AS Remark,
		ISNULL(PCM.OrgGroupBatchId,0) AS OrgGroupBatchId
	FROM    
		[sCommunication].[tPhotoCategoryMaster]  PCM 
	WHERE   
		PCM.IsObsolete = 0
		AND ((PCM.Id = @rId) OR (@rId = 0))
		AND ((PCM.Id > @rSyncedPhotoCategoryId) OR (@rSyncedPhotoCategoryId = 0))
		AND OrgGroupId=@lOrgGroupId
		ORDER BY PCM.CreatedDateTime DESC
	END   
      
END
GO
PRINT N'Altering [sCommunication].[pPhotoCategoryMasterAdd]...';


GO
ALTER PROCEDURE [sCommunication].[pPhotoCategoryMasterAdd]
	 
	 @rId int,
	 @rOrgGroupId int,
	 @rTitle nvarchar(100),
	 @rIsObsolete bit,
	 @rCreatedUserId bigint,
	 @rScopeSourceTypeId smallint=0,
	 @rRemark nvarchar(300)='',
	 @rOrgGroupBatchId int = 0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
IF(@rId = 0)	
BEGIN
	IF EXISTS(Select 1 FROM sCommunication.tPhotoCategoryMaster Where Title = @rTitle AND IsObsolete = 0 AND OrgGroupId=@rOrgGroupId)
	BEGIN 
		SELECT -101 AS Result
		RETURN
	END 
END
ELSE 
BEGIN 
	IF EXISTS(Select 1 FROM sCommunication.tPhotoCategoryMaster Where Title = @rTitle AND OrgGroupId=@rOrgGroupId AND IsObsolete = 0 AND Id!=@rId)
	BEGIN 
		SELECT -101 AS Result
		RETURN
	END 
END
	
BEGIN TRY

BEGIN TRANSACTION	
 IF(@rId = 0)	
BEGIN
  
	DECLARE @lNextNumber BIGINT     
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sCommunication.tPhotoCategoryMaster', 0, 1, 1,@outNextNumber = @lNextNumber output

	INSERT INTO [sCommunication].[tPhotoCategoryMaster]
           (
            [Id]
           ,[Title]
           ,[IsObsolete]
           ,[CreatedUserId]
           ,[CreatedDateTime]
           ,[UpdatedUserId]
           ,[UpdatedDateTime]
           ,[OrgGroupId]
           ,ScopeSourceTypeId
           ,Remark
		   ,OrgGroupBatchId)
     VALUES
		(
			@lNextNumber,
			@rTitle,
			@rIsObsolete,
			@rCreatedUserId,
		    sCommon.fGetDate(),
			@rCreatedUserId,	 
			sCommon.fGetDate(),
			@rOrgGroupId,
			@rScopeSourceTypeId,
			@rRemark,
			@rOrgGroupBatchId
		)
		             
	END	 
	 ELSE
	  BEGIN
	 SET @lNextNumber = @rId
	    UPDATE [sCommunication].[tPhotoCategoryMaster]
	    SET
			Title = @rTitle,
			IsObsolete = @rIsObsolete,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate(),
			ScopeSourceTypeId=@rScopeSourceTypeId,
			Remark=@rRemark
			--OrgGroupBatchId = @rOrgGroupBatchId
	      
	      WHERE Id = @rId 	 
		END
		SELECT @lNextNumber AS Result	   
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sCommunication].[pViewPhotoCategoryMaster_Get]...';


GO
 
ALTER PROCEDURE [sCommunication].[pViewPhotoCategoryMaster_Get]
	 
	 @rScopeSourceId bigint=0,
	 @rId int = 0,
	 @rSyncedPhotoCategoryId int = 0,
	 --@rOrgGroupId smallint,
	 @rSourcetypeId smallint,
	 --@rOrgGroupBatchID int,
	 @rBatchId int,
	 @rBatchYear int = 0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 

  declare @lOrgGroupId smallint,@lOrgGroupBatchID int,@lOrgId smallint
  
  if @rSourcetypeId=2003
  BEGIN
  
	  Select @lOrgGroupId=Om.OrgGroupId,@lOrgId=OM.Id ,@lOrgGroupBatchID=BM.OrgGroupBatchId  from 
	  sSetup.tOrganizationMaster OM
	  INNER JOIN sStudent.tAcademic A ON A.OrgId=OM.Id
	  INNER JOIN sSetup.tBatchMaster BM ON  BM.Id=A.BatchId
	  where A.BatchId= @rBatchId AND A.Id=@rScopeSourceId 
	  
  END
  
 else if @rSourcetypeId=95
  BEGIN
	 Select @lOrgId=OrgId From 
	 sSetup.tOrganizationMaster OM
	 INNER JOIN sHrm.tEmployeeMaster EM ON EM.OrgID=OM.Id AND  ISNULL(EM.IsOtherUser,0) = 0
	 Where Em.Id=@rScopeSourceId
  END
  else
  BEGIN
	Select @lOrgGroupId=OM.OrgGRoupId from sSetup.tOrganizationMaster OM
	INNER JOIN sSetup.tBatchMaster BM ON BM.OrgId=OM.Id
	Where Bm.Id=@rBatchId
  END
 
  if @rSourcetypeId=2003
  BEGIN
		
  SELECT   PCM.[Id]
  		  ,PCM.[Title]
          ,PCM.[IsObsolete],
          ISNULL(PCM.ScopeSourceTypeId,0) AS ScopeSourceTypeId,
          ISNULL(Remark,'') AS Remark,
		  PCM.CreatedDateTime,
		  ISNULL(PCM.OrgGroupBatchId,0)AS OrgGroupBatchId
          
  from [sCommunication].[tPhotoCategoryMaster] PCM 
	INNER join sCommunication.tPhotoCategoryScope PCS  ON PCM.Id = PCS.PhotoCateGoryId AND
	(PCS.ScopeSourceId = Case  When PCM.ScopeSourceTypeId = 2005 Then
	(Select DivisionId From sStudent.tAcademic Where DivisionId = PCS.ScopeSourceId And Id = @rScopeSourceId)
	When PCM.ScopeSourceTypeId = 2016 Then
    (Select ClassId From sStudent.tAcademic Where ClassId = PCS.ScopeSourceId And Id = @rScopeSourceId)
	when PCM.ScopeSourceTypeId = 2017 Then
	(select D.Id from sSetup.tDepartmentMaster D INNER JOIN sSetup.tClassMaster CA ON CA.DepartmentId=D.Id 
	INNER JOIN sStudent.tAcademic A ON A.ClassID=CA.Id Where A.Id =@rScopeSourceId)
	When PCM.ScopeSourceTypeId =2021 Then
	(Select OM.Id from sSetup.tOrganizationMaster OM INNER JOIN sStudent.tAcademic A ON A.OrgId =OM.Id Where A.Id=@rScopeSourceId)
	When PCM.ScopeSourceTypeId =2014 Then
	(Select Hm.Id from sHostel.tHostelMaster Hm INNER JOIN  sHostel.tRoomMaster RA ON RA.HostelId=HM.Id 
	INNER JOIN sHostel.tAssignRoom AR ON AR.RoomId=RA.Id
	INNER JOIN sStudent.tAcademic A ON A.StudentId=AR.SourceId 
	Where AR.OrgGroupBatchId = @lOrgGroupBatchID AND HM.OrgGroupId=@lOrgGroupId AND A.Id=@rScopeSourceId)
	When PCM.ScopeSourceTypeId =2029 Then
	(select HO.Id from sActivity.tHouseMaster HO
	INNER JOIN sStudent.tStudentOther SO ON SO.HouseId=HO.Id 
	INNER JOIN sStudent.tAcademic A ON A.StudentId=SO.StudentId
	Where HO.OrgId=@lOrgId AND A.Id=@rScopeSourceId)
	ENd)
	where ((PCM.Id=@rId) OR (@rId=0))  AND PCM.IsObsolete=0
	AND ((YEAR(PCM.CreatedDateTime) = @rBatchYear) OR (@rBatchYear = 0))
	 
      END
  else if @rSourcetypeId=95
  BEGIN 
		SELECT   PCM.[Id]
  		  ,PCM.[Title]
          ,PCM.[IsObsolete],
          ISNULL(PCM.ScopeSourceTypeId,0) AS ScopeSourceTypeId,
          ISNULL(Remark,'') AS Remark,
		  PCM.CreatedDateTime,
		  ISNULL(PCM.OrgGroupBatchId,0)AS OrgGroupBatchId
        From [sCommunication].[tPhotoCategoryMaster] PCM 
        INNER join sCommunication.tPhotoCategoryScope PCS  ON PCM.Id = PCS.PhotoCateGoryId AND
        (PCS.ScopeSourceId = Case when PCM.ScopeSourceTypeId = 2017 Then
        (Select D.Id from sSetup.tDepartmentMaster D 
        INNER JOIN sHrm.tEmployeeJobDetail EJ ON EJ.OrganizationDepartmentId=D.Id
        Where EJ.EmployeeId=@rScopeSourceId AND EJ.OrgId=@lOrgId)
        when PCM.ScopeSourceTypeId=2021 Then
        (Select OM.Id from sSetup.tOrganizationMaster OM 
        INNER JOIN sHrm.tEmployeeMaster EM ON EM.OrgId=OM.Id AND  ISNULL(EM.IsOtherUser,0) = 0
        Where EM.OrgId=@lOrgId and Em.Id=@rScopeSourceId)
        END)
        where ((PCM.Id = @rId) OR (@rId=0))  AND PCM.IsObsolete=0
		AND ((YEAR(PCM.CreatedDateTime) = @rBatchYear) OR (@rBatchYear = 0))
        
  END
  else
  BEGIN
  SELECT   PCM.[Id]
  		  ,PCM.[Title]
          ,PCM.[IsObsolete],
          ISNULL(PCM.ScopeSourceTypeId,0) AS ScopeSourceTypeId,
          ISNULL(Remark,'') AS Remark,
		  PCM.CreatedDateTime,
		  ISNULL(PCM.OrgGroupBatchId,0)AS OrgGroupBatchId
          
  FROM    [sCommunication].[tPhotoCategoryMaster]  PCM 
            
  WHERE   
      PCM.IsObsolete = 0
      AND  ((PCM.Id = @rId) OR (@rId = 0))
      AND ((PCM.Id > @rSyncedPhotoCategoryId) OR (@rSyncedPhotoCategoryId = 0))
      --AND PCM.ScopeSourceTypeId=@rScopeSourceId
      AND OrgGroupId=@lOrgGroupId
	  AND ((YEAR(PCM.CreatedDateTime) = @rBatchYear) OR (@rBatchYear = 0))
      ORDER BY PCM.CreatedDateTime DESC
   END   
      
END
GO
PRINT N'Altering [sFee].[pFeeCustomSearchGet]...';


GO
 
ALTER PROCEDURE [sFee].[pFeeCustomSearchGet]
(
	@rOrgGroupBatchId int,
	@rOrgId smallint,
	@rBatchId int,
	@rOrderBy nvarchar(max) = 'ReceiptNumber',
	@rCode [nvarchar](20) = '',
	@rFirstName [nvarchar](50) = '',	
	@rLastName [nvarchar](50) = '',	
	@rDivisionId nvarchar(max) = '',
	@rReceiptBookId nvarchar(max) = '',
	@rFromReceiptDate Date = '0001-01-01',
	@rToReceiptDate Date = '9999-12-31',
	@rFromReceiptNo int,
	@rToReceiptNo int,
	@rCreatedUserId bigint,
	@rIsObsolete bit,
	@rDropDownStatusId int,
	@rDropDownClassId int,
	@rDropDownDivisionId int,
	@rDropDownReceiptBookId int,
	@rDepartmentId int=0,
	@rPageIndex int = null,
	@rAdmissionCategoryId int = 0
 )
AS
SET NOCOUNT ON
BEGIN
	create table #TEMPFee
	(
		tid int identity(1,1),t_AcedemicId bigint,t_ReceiptId bigint
	)
	
	DECLARE @Sql nvarchar(MAX)
	IF(@rFromReceiptDate IS NULL)
		SET @rFromReceiptDate='0001-01-01'
	IF(@rToReceiptDate IS NULL)
		SET @rToReceiptDate='9999-12-31'

		
	SET @rCode = sCommon.fSearchStringGet(@rCode)
	SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
	SET @rLastName = sCommon.fSearchStringGet(@rLastName)
	select @rPageIndex = case when isnull(@rPageIndex,0) = 0 then 1 else @rPageIndex end
	
	SELECT FCS.AcademicId,FCS.ClassId,FCS.DivisionId,FCS.RollNo,FCS.OrgGroupBatchId,
	FCS.OrgId,FCS.BatchId,FCS.OrgGroupBatch,FCS.Organization,FCS.Batch,FCS.StudentId,
	FCS.Code,FCS.Number,FCS.FirstName,FCS.LastName,FCS.Name,FCS.StatusId,FCS.ClassName,
	FCS.DivisionName,FCS.StatusName,FCS.ReceiptId,FCS.ReceiptNumber,FCS.ReceiptDate,
	FCS.ReceiptAmount,FCS.ChequeNo,FCS.BankName,FCS.Remark,FCS.IsObsolete,FCS.FeeReceiptBookId,
	FCS.ReceiptBookCode,FCS.ReceiptBookName,FCS.Address1,FCS.Address2,FCS.BankAccountNumber,
	FCS.PayTypeId,FCS.PayType,FCS.CreatedUserId,FCS.CreatedUserName, FCS.ParentContactNo
	into sFee.tTempFee1
	FROM sFee.vFeeCustomSearch FCS
	INNER JOIN sSetup.tClassMaster CM ON CM.Id = FCS.ClassId
	WHERE (FCS.OrgGroupBatchId = @rOrgGroupBatchId)
	AND	((FCS.OrgId = @rOrgId) OR (@rOrgId=0))
	AND ((FCS.BatchId = @rBatchId) OR (@rBatchId=0))
	AND ((FCS.Code Like @rCode + '%') OR (@rCode = ''))
	AND ((FCS.FirstName Like @rFirstName  + '%') OR (@rFirstName = ''))
	AND ((FCS.LastName Like @rLastName + '%')OR(@rLastName = ''))
	AND ((FCS.ReceiptNumber >= @rFromReceiptNo) OR (@rFromReceiptNo =0))
	AND ((FCS.ReceiptNumber <= @rToReceiptNo) OR (@rToReceiptNo=0))
	AND ((ISNULL(FCS.ReceiptDate,'0001-01-01') >= @rFromReceiptDate) OR (ISNULL(@rFromReceiptDate,'') = ''))
	AND ((ISNULL(FCS.ReceiptDate,'9999-12-31') <= @rToReceiptDate) OR (ISNULL(@rToReceiptDate,'') = ''))
	AND (FCS.DivisionId In( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionId,','))OR @rDivisionId='')
	AND (FCS.FeeReceiptBookId In( SELECT cast(item as int) FROM  sCommon.fnsplit(@rReceiptBookId,','))OR @rReceiptBookId='')
	AND ((FCS.CreatedUserId=@rCreatedUserId) OR (@rCreatedUserId=0))
	AND (FCS.IsObsolete=@rIsObsolete)
	AND ((FCS.StatusId = @rDropDownStatusId) OR (@rDropDownStatusId=0))
	AND ((FCS.ClassId = @rDropDownClassId) OR (@rDropDownClassId=0))
	AND ((FCS.DivisionId = @rDropDownDivisionId) OR (@rDropDownDivisionId=0))
	AND ((FCS.FeeReceiptBookId = @rDropDownReceiptBookId) OR (@rDropDownReceiptBookId=0))
	AND ((Cm.DepartmentId =@rDepartmentId ) OR (@rDepartmentId=0))
	AND ((FCS.AdmissionCategoryId = @rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
	
	SET @rOrderBy=Replace(@rOrderBy,'ID No','Code')
	SET @rOrderBy=Replace(@rOrderBy,'GR No','Code')
	
	SET @sql='SELECT Code AS Code,Name,ReceiptNumber,ReceiptDate,ReceiptAmount,
	PayType,ChequeNo,BankName,ReceiptBookName,Remark,OrgId,BatchId
	FROM sFee.tTempFee1 ORDER BY '+@rOrderBy
	
	exec(@Sql)
	
	SET @sql='INSERT INTO #TEMPFee SELECT AcademicId, ReceiptId
	FROM sFee.tTempFee1 ORDER BY '+@rOrderBy
	
	exec(@Sql)
	
	declare @lTotalRecords int,@lPageSize int = 10,@lPaging varchar(max)='',@lResult varchar(max)=''
	select @lTotalRecords = count(*) from #TEMPFee
	
	select @lPaging = @lPaging + dbo.fnc_SearchPagingFormat(@rPageIndex,@lTotalRecords,@lPageSize)
	
	select @lResult = @lResult + '<tr attrId="' + convert(varchar,isnull(t_AcedemicId,0)) + '"
	attrCode="' + isnull(Code,'') + '"
	attrReceiptNo="' + isnull(convert(varchar,ReceiptNumber),'') + '"
	attrBatchId="' + convert(varchar,@rBatchId) + '"
	attrOrgId="' + convert(varchar,@rOrgId) + '"
	attrOrgGroupBatchId="' + convert(varchar,@rOrgGroupBatchId) + '">
	<td><a style="cursor:pointer;" onclick="SecectThisRecord(this);">Select</a></td><td>' + isnull(Code,'') + '</td>
	<td>' + isnull(Name,'') + '</td><td>' + isnull(convert(varchar,ReceiptNumber),'') + '</td>
	<td>' + isnull(convert(varchar,ReceiptDate,103),'') + '</td>
	<td>' + isnull(convert(varchar,ReceiptAmount),'') + '</td><td>' + isnull(PayType,'') + '</td>
	<td>' + isnull(ChequeNo,'') + '</td><td>' + isnull(BankName,'') + '</td>
	<td>' + isnull(ReceiptBookName,'') + '</td><td>' + isnull(Remark,'') + '</td></tr>'
	from sFee.tTempFee1,#TEMPFee where t_AcedemicId = AcademicId AND t_ReceiptId = ReceiptId
	and tid between ((@lPageSize * (@rPageIndex - 1)) + 1) AND (@lPageSize * @rPageIndex)
	
	select @lPaging as UserPaging,@lResult as UserResult,@lTotalRecords as UserTotal
			
	DROP Table sFee.tTempFee1
	drop Table #TEMPFee
END
GO
PRINT N'Altering [sHostel].[pRptRoomwiseStudentListGet]...';


GO


ALTER PROCEDURE [sHostel].[pRptRoomwiseStudentListGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rHostelId int,
	 @rOrgGroupBatchId int,
	 @rOrgId int,
	 @rRoomId int=0,
	 @rStudentName nvarchar(100)='',
	 @rStudentCode nvarchar(100)='',
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rIsBasedOnSUId bit = 0,
	 @rDepartmentId int=0,
	 @rSUId nvarchar(20)='',
	 @rFromAllocateDate date='',
	 @rToAllocateDate Date=''
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 


	SELECT
        @rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
       'Student' AS SourceType,
		2003 AS SourceTypeId,
		ISNULL(SA.StudentId,0) as SourceId,
		SA.SUId AS SUId,
		SA.Code as SourceCode,
		SA.Name as SourceName,
		SA.ClassName+'-'+SA.DivisionName as ClassDivisionName,
		SA.ClassId,
		SA.ClassName AS ClassName,
		SA.RollNo,
		RM.StudentsPerRoom,
		HTM.Title as HostelType,
		HM.Title AS HostelName,
		RM.Title AS Room,
		SC.ParentContactNo,
		SA.OrgId,
		OM.DisplayTitle AS OrganizatinName,
		SA.DivisionId,
		SA.DivisionOrder,
		@rIsBasedOnSUId AS IsBasedOnSUId,
		HM.ReportOrgTitle,
		HM.SmallAddress1,
		HM.SmallAddress2,
	   (SELECT sum(Total) FROM(SELECT Max(StudentsPerRoom) AS Total FROM sHostel.tRoomMaster RM 
		LEFT JOIN sHostel.tAssignRoom AR ON RM.Id=AR.RoomId AND AR.SourceTypeId=2003   AND  AR.OrgGroupBatchId = @rOrgGroupBatchId
		INNER JOIN sStudent.vStudentAcademic SA ON AR.SourceId=SA.StudentId 
		WHERE ((RM.HostelId=@rHostelId) OR (@rHostelId=0)) AND  SA.OrgGroupBatchId = @rOrgGroupBatchId AND ((RM.Id=@rRoomId) OR (@rRoomId=0))
		GRoup By RM.Id)A) AS TotalStudentPerRoom
		
	FROM sHostel.tRoomMaster RM 
		LEFT JOIN sHostel.tAssignRoom AR ON RM.Id=AR.RoomId AND AR.SourceTypeId=2003   AND  AR.OrgGroupBatchId = @rOrgGroupBatchId
		INNER JOIN sStudent.vStudentAcademic SA ON AR.SourceId=SA.StudentId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
		--LEFT JOIN sSetup.tBatchMaster BM ON BM.Id=SA.BatchId AND BM.IsActive = 1
		LEFT JOIN sStudent.tStudentCommunication SC ON SA.StudentId=SC.StudentId
		LEFT JOIN sHostel.tHostelMaster HM ON HM.Id=RM.HostelId
		LEFT JOIN sHostel.tHostelTypeMaster HTM ON HTM.Id=HM.HostelTypeId
	    LEFT JOIN sHostel.tHostelAdmission HAM ON HAM.SourceId=AR.SourceId AND HAM.SourceTypeId=2003 AND  HAM.OrgGroupBatchId = @rOrgGroupBatchId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.OrgGroupBatchId = AR.OrgGroupBatchId AND BM.Id = SA.BatchId
	    
	WHERE 
       (SA.OrgGroupBatchId = @rOrgGroupBatchId)
		 AND ((SA.OrgId = @rOrgId) OR (@rOrgId=0))
		AND ((RM.HostelId=@rHostelId) OR (@rHostelId=0))
		AND ((RM.Id=@rRoomId) OR (@rRoomId=0))
		--AND ((RM.Id=@rRoomId) OR (@rRoomId=0))
		AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
		AND ((SA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))
		AND ((SA.Code Like @rStudentCode) OR (ISNULL(@rStudentCode,'')=''))
		AND ((SA.FirstName like @rStudentName + '%') OR (ISNULL(@rStudentName,'') = ''))
		AND ((SA.DepartmentId = @rDepartmentId ) OR (@rDepartmentId = 0))
		AND (SA.SUId like @rSUId OR ISNULL(@rSUId,'')='')
		AND ((HAM.AllocateDate >= @rFromAllocateDate ) OR (ISNULL(@rFromAllocateDate,'') = ''))
	    AND ((HAM.AllocateDate <= @rToAllocateDate ) OR (Isnull(@rToAllocateDate,'') = ''))
	    AND BM.IsInContext = 1
	END
GO
PRINT N'Altering [sHrm].[pLeaveBulkGet]...';


GO

ALTER PROCEDURE [sHrm].[pLeaveBulkGet]  
(  
	@rOrgId int,  
    @rEmployeeId  bigint,     
    @rFromDate date,   
    @rTodate date,  
    @rOrgGroupBatchId int,   
    @rOrgGroupId int,  
    @rDepartmentId int
	 
 )  
AS  
SET NOCOUNT ON  

BEGIN
		SELECT 
		EM.EmployeeId,
		EMP.FirstName +' '+EMP.MiddleName+' '+EMP.LastName As EmployeeName,
		EMP.Code As EmployeeCode,
		EAR.AttendanceDate As LeaveDate,
		EAR.IsPresent
		
		FROM 
		sHrm.tEmployeeAttendanceRegister EAR
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = EAR.BatchId    
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId  
		LEFT JOIN sHrm.tEmployeeMaster EMP ON EMP.Id = EAR.EmployeeId 
		INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = EAR.EmployeeId   
		WHERE EAR.EmployeeId 
		NOT IN (SELECT EmployeeId FROM sHrm.tLeave WHERE Fromdate >=AttendanceDate AND TODATE <=AttendanceDate)
		--AND  AttendanceDate >=@rFromDate AND AttendanceDate <=@rToDate
		AND  ((AttendanceDate >=@rFromDate)  OR (ISNULL(@rFromDate,'')=''))
		AND ((AttendanceDate <=@rToDate)  OR (ISNULL(@rToDate,'')=''))
		and IsPresent=0
		AND ((EM.DepartmentId = @rDepartmentId ) OR (@rDepartmentId = 0))
		AND BM.OrgGroupBatchId = @rOrgGroupBatchId  
		AND ((EMP.OrgId = @rOrgId) OR (@rOrgId = 0)) 

END
GO
PRINT N'Altering [sLibrary].[pBookMasterGet]...';


GO


ALTER PROCEDURE [sLibrary].[pBookMasterGet]
	 
	 @rId bigint = 0,
	 @rCode nvarchar(200),
	 @rTitle nvarchar(100),
	 @rOrgId int,
	 @rPublisher nvarchar(200),
	 @rSupplier nvarchar(200),
	 @rAuthor nvarchar(200),
	 @rSubject nvarchar(200),
	 @rLanguage nvarchar(200),
	 @rLocation nvarchar(200),
	 @rEdition nvarchar(50),
	 @rPrice decimal=0,
	 @rCurrency nvarchar(100),
	 @rISBNNumber nvarchar(100),
	 @rBookTag nvarchar(200),
	 @rBookCustomTag nvarchar(200),
	 @rBookAgeGroupId int,
	 @rResourceTypeId int,
	 @rStatusId smallint,
	 @rCreatedUserId bigint,
	 @rLibraryId int,
	 @rBookDepartment nvarchar(150),
	 @rShowWithPhotoId int=0,
	 @rBookGroup1Id int=0,
	 @rBookGroup2Id int=0,
	 @rAccession nvarchar(50)
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
--DECLARE @lpaging
BEGIN 


	  --BEGIN
			--SET @rCode = sCommon.fSearchStringGet(@rCode)
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
			SET @rPublisher = sCommon.fSearchStringGet(@rPublisher)
			SET @rSupplier = sCommon.fSearchStringGet(@rSupplier)
			SET @rAuthor = sCommon.fSearchStringGet(@rAuthor)
			SET @rSubject = sCommon.fSearchStringGet(@rSubject)
			SET @rLanguage = sCommon.fSearchStringGet(@rLanguage)
			SET @rLocation = sCommon.fSearchStringGet(@rLocation)
			SET @rEdition = sCommon.fSearchStringGet(@rEdition)
			SET @rCurrency = sCommon.fSearchStringGet(@rCurrency)
			SET @rISBNNumber = sCommon.fSearchStringGet(@rISBNNumber)
			SET @rBookTag = sCommon.fSearchStringGet(@rBookTag)
			SET @rBookCustomTag = sCommon.fSearchStringGet(@rBookCustomTag)
			SET @rAccession = sCommon.fSearchStringGet(@rAccession)
		
	  --END
	 declare @quer nvarchar(max)=''
	declare @lId bigint = 0,@lCode nvarchar(200),@lTitle nvarchar(100),@lOrgId int,
	@lPublisher nvarchar(200),@lSupplier nvarchar(200),@lAuthor nvarchar(200),
	@lSubject nvarchar(200),@lLanguage nvarchar(200),@lLocation nvarchar(200),
	@lEdition nvarchar(50),@lPrice decimal=0,@lCurrency nvarchar(100),
	@lISBNNumber nvarchar(100),@lBookTag nvarchar(200),@lBookCustomTag nvarchar(200),
	@lBookAgeGroupId int,@lResourceTypeId int,@lStatusId smallint,@lCreatedUserId bigint,
	@lLibraryId int,@lBookDepartment nvarchar(150),@lBookGroup1Id int,@lBookGroup2Id int,@lAccession nvarchar(50)
	select @lId = isnull(@rId,0),@lCode = isnull(@rCode,''),@lTitle = isnull(@rTitle,''),
	@lOrgId = isnull(@rOrgId,0),@lPublisher = isnull(@rPublisher,''),@lSupplier = isnull(@rSupplier,''),
	@lAuthor = isnull(@rAuthor,''),@lSubject = isnull(@rSubject,''),
	@lLanguage = isnull(@rLanguage,''),@lLocation = isnull(@rLocation,''),
	@lEdition = isnull(@rEdition,''),@lPrice = isnull(@rPrice,0),@lCurrency = isnull(@rCurrency,''),
	@lISBNNumber = isnull(@rISBNNumber,''),@lBookTag = isnull(@rBookTag,''),
	@lBookCustomTag = isnull(@rBookCustomTag,''),@lBookAgeGroupId = isnull(@rBookAgeGroupId,0),
	@lResourceTypeId = isnull(@rResourceTypeId,0),@lStatusId = isnull(@rStatusId,0),@lCreatedUserId = isnull(@rCreatedUserId,0),
	@lLibraryId = isnull(@rLibraryId,0),@lBookDepartment = isnull(@rBookDepartment,''),
	@lBookGroup1Id = isnull(@rBookGroup1Id,0),@lBookGroup2Id = isnull(@rBookGroup2Id,0),@lAccession = ISNULL(@rAccession,'')

	 
	SELECT @quer='SELECT BM.Code,
	BM.Title,
	ISNULL(BM.Publisher,'''')AS Publisher,
	ISNULL(BM.Supplier,'''')AS Supplier,
	ISNULL(BM.Author,'''')AS Author,
	ISNULL(BM.BookSubject,'''') AS BookSubject,
	ISNULL(BM.BookLanguage,'''') AS BookLanguage,
	ISNULL(BM.Location,'''') AS Location,
	ISNULL(BM.Edition,'''')AS Edition,
	ISNULL(BM.ISBNNumber,'''') AS ISBNNumber,
	ISNULL(BM.Price,0) AS Price,
	ISNULL(BM.Currency,'''') AS Currency,
	ISNULL(BM.BookTag,'''')AS BookTag,
	ISNULL(BM.BookCustomTag,'''') AS BookCustomTag,
	ISNULL(BM.BookDepartment,'''') AS BookDepartment,
	ISNULL(BM.ClassNumber,'''') AS ClassNumber,
	ISNULL(BM.BookVolume,1) AS BookVolume,
	ISNULL(BM.NoOfCopies,1) AS NoOfCopies,
	SM.Title AS StatusName,
	BM.Id,
	ISNULL(AGM.Id,0)AS BookAgeGroupId,
	ISNULL(RTM.Id,0) AS ResourceTypeId,
	BM.CreatedUserId,
	BM.CreatedDateTime,
	ISNULL(BM.UpdatedUserId,0) AS UpdatedUserId,
	ISNULL(BM.UpdatedDateTime,'''') AS UpdatedDateTime,
	BM.LibraryId,
	SM.Id AS StatusId,
	BM.ClassificationNo,
	BM.AccessionNo,
	ISNUll(BM.NoOfPages,0) AS NoOfPages,
	 ISNULL(BM.PurchaseDate,''0001/01/01'') AS PurchaseDate,
    ISNUll(BM.BookRemark,'''') AS BookRemark,
    ISNULL(BM.BillNumber,'''') AS BillNumber,
    BM.YearOfPublication,
    ISNULL(BM.BookEntryDate,''0001/01/01'') AS BookEntryDate,
    CASE WHEN ' + convert(varchar,@rShowWithPhotoId) + '= 1 Then ISNULL(BM.BookImage, CONVERT(VARBINARY(MAX), 0)) ELSE BM.BookImage END AS BookPicture,
    ISNULL(BM.BookGroup1Id,0) AS BookGroup1Id,
    ISNULL(BM.BookGroup2Id,0) AS BookGroup2Id
 
	FROM 
         sLibrary.tBookMaster BM
         LEFT JOIN sLibrary.tBookAgeGroupMaster AGM ON BM.BookAgeGroupId=AGM.Id
         INNER JOIN sLibrary.tResourceTypeMaster RTM ON BM.ResourceTypeId=RTM.Id
         INNER JOIN sLibrary.tBookLog BL ON BL.ResourceSourceId = BM.Id AND IsCurrentStatus=1
         INNER JOIN sCommon.tStatusMaster SM ON SM.Id=BL.StatusId 
         
         WHERE ((BM.Id = ' + convert(varchar,@lId) + ') OR (' + convert(varchar,@lId) + ' = 0))
	AND ((BM.Code = ''' + @lCode + ''') OR (''' + @lCode + ''' = ''''))
	AND ((BM.Title like N''' + @lTitle + ''') OR (''' + @lTitle + ''' = '''')) 
	AND ((BM.AccessionNo like ''' + @lAccession + ''') OR (''' + @lAccession + ''' = '''')) 
	AND ((BM.Publisher like N''' + @lPublisher + ''') OR (''' + @lPublisher + ''' = '''')) 
	AND ((BM.Supplier like ''' + @lSupplier + ''') OR (''' + @lSupplier + ''' = '''')) 
	AND ((BM.Author like N''' + @lAuthor + ''') OR (''' + @lAuthor + ''' = '''')) 
	AND ((BM.BookSubject like N''' + @lSubject + ''') OR (''' + @lSubject + ''' = ''''))  
	AND ((BM.BookLanguage like N''' + @lLanguage + ''') OR (''' + @lLanguage + ''' = ''''))  
	AND ((BM.Location like ''' + @lLocation + ''') OR (''' + @lLocation + ''' = ''''))  
	AND ((BM.Edition like ''' + @lEdition + ''') OR (''' + @lEdition + ''' = ''''))  
	AND ((BM.ISBNNumber like ''' + @lISBNNumber + ''') OR (''' + @lISBNNumber + ''' = ''''))  
	AND ((BM.BookTag like ''' + @lBookTag + ''') OR ( ''' + @lBookTag + ''' = ''''))
	AND ((BM.BookCustomTag like ''' + @lBookCustomTag + ''') OR (''' + @lBookCustomTag + ''' = ''''))
	AND ((BM.BookAgeGroupId = ' + convert(varchar,@lBookAgeGroupId) + ') OR(' + convert(varchar,@lBookAgeGroupId) + ' = 0))
	AND ((BM.ResourceTypeId = ' + convert(varchar,@lResourceTypeId) + ') OR (' + convert(varchar,@lResourceTypeId) + ' = 0))
	AND ((BM.BookGroup1Id = ' + convert(varchar,@lBookGroup1Id) + ') OR (' + convert(varchar,@lBookGroup1Id) + ' = 0))
	AND ((BM.BookGroup2Id = ' + convert(varchar,@lBookGroup2Id) + ') OR (' + convert(varchar,@lBookGroup2Id) + ' = 0))
	AND ((BM.Price = ' + convert(varchar,@lPrice) + ') OR (' + convert(varchar,@lPrice) + ' = 0))
	AND ((BM.Currency like ''' + @lCurrency + ''') OR (''' + @lCurrency  + ''' = ''''))
	AND ((BL.StatusId = ' + convert(varchar,@lStatusId) + ') OR (' + convert(varchar,@lStatusId) + '=0))
	AND ((BM.BookDepartment like ''' + @lBookDepartment + ''') OR (''' + @lBookDepartment + ''' = ''''))
	AND BM.LibraryId = ' + convert(varchar,@lLibraryId)
	--print(@quer);
	exec (@quer)
	

  --FROM 
  --      sLibrary.tBookMaster BM
  --       LEFT JOIN sLibrary.tBookAgeGroupMaster AGM
  --       ON BM.BookAgeGroupId=AGM.Id
  --       INNER JOIN sLibrary.tResourceTypeMaster RTM
  --       ON BM.ResourceTypeId=RTM.Id
  --       INNER JOIN sLibrary.tBookLog BL
  --       ON BL.ResourceSourceId=BM.Id AND IsCurrentStatus=1
  --       INNER JOIN sCommon.tStatusMaster SM
  --       ON SM.Id=BL.StatusId 
        -- WHERE 
  
      --((BM.Id = @rId) OR (@rId = 0))
      --ANd ((BM.Code = @rCode) OR (ISNULL(@rCode,'') = ''))
      -- AND  ((BM.Title like @rTitle) OR (ISNULL(@rTitle,'') = '')) 
      --  AND  ((BM.Publisher like @rPublisher) OR (ISNULL(@rPublisher,'') = '')) 
      --   AND  ((BM.Supplier like @rSupplier) OR (ISNULL(@rSupplier,'') = '')) 
      --    AND  ((BM.Author like @rAuthor) OR (ISNULL(@rAuthor,'') = '')) 
      --     AND  ((BM.BookSubject like @rSubject) OR (ISNULL(@rSubject,'') = ''))  
      --      AND  ((BM.BookLanguage like @rLanguage) OR (ISNULL(@rLanguage,'') = ''))  
      --       AND  ((BM.Location like @rLocation) OR (ISNULL(@rLocation,'') = ''))  
      --        AND  ((BM.Edition like @rEdition) OR (ISNULL(@rEdition,'') = ''))  
      --         AND  ((BM.ISBNNumber like @rISBNNumber) OR (ISNULL(@rISBNNumber,'') = ''))  
      --          AND  ((BM.BookTag like @rBookTag) OR (ISNULL(@rBookTag,'') = ''))
      --           AND  ((BM.BookCustomTag like @rBookCustomTag) OR (ISNULL(@rBookCustomTag,'') = ''))
      --            AND  ((BM.BookAgeGroupId = @rBookAgeGroupId) OR(@rBookAgeGroupId=0))
      --             AND  ((BM.ResourceTypeId = @rResourceTypeId) OR (@rResourceTypeId=0))
      --              AND  ((BM.Price = @rPrice) OR (@rPrice=0))
      --               AND  ((BM.Currency like @rCurrency) OR (ISNULL(@rCurrency,'') = ''))
      --                AND  ((BL.StatusId = @rStatusId) OR (@rStatusId=0))
      --                ANd ((BM.BookDepartment like @rBookDepartment) OR (ISNULL(@rBookDepartment,'') = ''))
						--AND ((BL.OrgId=@rOrgId) OR (@rOrgId=0))
	  --AND BM.LibraryId = @rLibraryId
END
GO
PRINT N'Altering [sLibrary].[pRptBookListGet]...';


GO
 
ALTER PROCEDURE [sLibrary].[pRptBookListGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='',
	 @rBookSupplier nvarchar(200),
	 @rBookPublisher nvarchar(200),
	 @rBookSubjectText nvarchar(200),
	 @rBookLanguage nvarchar(200),
	 @rBookTag nvarchar(200),
	 @rBookCustomTag nvarchar(200),
	 @rLibraryId int,
	 @rBookDepartment nvarchar(150)='',
	 @rIsDetail bit=0,
	 @rFromPurchaseDate date='',
	 @rToPurchaseDate date='',
	 @rBookGroup1Id int,
	 @rBookGroup2Id int,
	 --@rOrgGroupId int,
	 @rFromCode nvarchar(25) ='',
	 @rToCode nvarchar(25) ='',
	 @rSpecificCode nvarchar(max) ='',
	 @rBookSubjectDrop nvarchar(500)='',
	 @rFromDate date ='',
	 @rToDate date =''
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
		
BEGIN 
	--DECLARE @rFromCodeInt INT, @rToCodeInt INT
	--DECLARE @BookConfig NVARCHAR, @rFromCodeString NVARCHAR, @rToCodeString NVARCHAR
	--SELECT @BookConfig = ItemValue From sConfig.tConfigurationSetup	WHERE ConfigurationId = 260 AND SourceId = @rOrgGroupId
	
	--SET @rFromCodeInt = Convert(Int,ISNULL(@rFromCode,0))
	--SET @rToCodeInt = Convert(Int,ISNULL(@rToCode,0))
	--SET @rFromCodeString = Convert(nvarchar,ISNULL(@rFromCode,''))
	--SET @rToCodeString = Convert(nvarchar,ISNULL(@rToCode,''))
	
	DECLARE @ListofBookCodes TABLE(Code nvarchar(25), ID INT IDENTITY(1,1));
		INSERT INTO @ListofBookCodes
	
	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
		

	BEGIN	  
		SET @rBookSupplier = sCommon.fSearchStringGet(@rBookSupplier)
		SET @rBookPublisher = sCommon.fSearchStringGet(@rBookPublisher)
		SET @rBookSubjectText = sCommon.fSearchStringGet(@rBookSubjectText)
		SET @rBookLanguage = sCommon.fSearchStringGet(@rBookLanguage)
		SET @rBookTag = sCommon.fSearchStringGet(@rBookTag)
		SET @rBookCustomTag = sCommon.fSearchStringGet(@rBookCustomTag)
		SET @rBookDepartment = sCommon.fSearchStringGet(@rBookDepartment)
    END

	SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		BM.Code,
		BM.Title As BookTitle,
		BM.Publisher,BM.Supplier,
		BM.BookSubject,
		BM.Code AS BookCode,
		BM.BookLanguage,
		BM.BookCustomTag,
		BM.BookCustomTag,
		BM.Location,
		BM.ISBNNumber,
		LM.ReportOrgTitle,
        LM.SmallAddress1,
        LM.SmallAddress2,
        CASE WHEN BM.BookDepartment is null THEN 'Blank'
            WHEN BM.BookDepartment='' THEN 'Blank'  ELSE BM.BookDepartment END AS  BookDepartment,
        BM.NoOfCopies,
        @rIsDetail AS IsDetail,
        LM.Code AS LibraryCode,	       
         LM.Title AS LibraryTitle,
        BM.AccessionNo AS AccessionNo
		
	FROM 
		sLibrary.tBookMaster BM
		LEFT JOIN sLibrary.tLibraryMaster LM ON LM.Id=BM.LibraryId
	WHERE 
		BM.LibraryId=@rLibraryId
		AND ((BM.Supplier like @rBookSupplier) OR (@rBookSupplier=''))
		AND ((BM.Publisher like @rBookPublisher) OR (@rBookPublisher=''))
		AND ((BM.BookSubject like @rBookSubjectText) OR (@rBookSubjectText=''))
		AND ((BM.BookSubject = @rBookSubjectDrop) OR (@rBookSubjectDrop=''))
		AND ((BM.BookLanguage like @rBookLanguage) OR (@rBookLanguage=''))
		AND ((BM.BookTag like @rBookTag) OR (@rBookTag=''))
		AND ((BM.BookCustomTag like @rBookCustomTag) OR (@rBookCustomTag=''))
		AND ((BM.BookDepartment like @rBookDepartment) OR (@rBookDepartment=''))
		AND ((BM.PurchaseDate >= @rFromPurchaseDate) OR (ISNULL(@rFromPurchaseDate,'') = ''))
		AND ((BM.PurchaseDate <= @rToPurchaseDate) OR (ISNULL(@rToPurchaseDate,'') ='') OR (BM.PurchaseDate is null))
		AND ((BM.BookGroup1Id = @rBookGroup1Id) OR (@rBookGroup1Id=0))
		AND ((BM.BookGroup2Id = @rBookGroup2Id) OR (@rBookGroup2Id=0))
		AND ((Convert(nvarchar(25),ISNULL(BM.Code,'')) >= @rFromCode) OR (ISNULL(@rFromCode,'') = ''))
		AND ((Convert(nvarchar(25),ISNULL(BM.Code,'')) <= @rToCode) OR (ISNULL(@rToCode,'') = ''))
		AND ((BM.Code IN(SELECT Code FROM @ListofBookCodes)) OR (ISNULL(@rSpecificCode,'') = ''))
		--AND CASE WHEN @BookConfig = 'True' THEN BM.Code >= @rFromCodeString ELSE BM.Code > @rFromCodeInt END AS BM.Code
		--AND CASE WHEN @BookConfig = 'True' THEN BM.Code <= @rToCodeString ELSE BM.Code > @rToCodeInt END AS BM.Code
		AND ((BM.BookEntryDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
		AND ((BM.BookEntryDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
		ORDER BY
		CASE WHEN BM.Code like '%[0-9]%' 
		 THEN Replicate('0', 100 - Len(BM.Code)) + BM.Code
		 ELSE BM.Code  END
		--ORDER BY CONVERT(INT, BM.Code)
		
	END
GO
PRINT N'Altering [sSecurity].[pAppPermissionGet]...';


GO
 
 
 
ALTER PROCEDURE [sSecurity].[pAppPermissionGet]
	@rOrgGroupId [int],
	@rUserId [bigint]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
IF EXISTS (SELECT 1 FROM sSecurity.tPermissionUser WHERE UserId=@rUserId AND OrgGroupId=@rOrgGroupId)

	BEGIN
	
		SELECT		
			TP.TaskId AS TaskID,
			CAST(MAX(TP.C) AS BIT) AS [Create],
			CAST(MAX(TP.R) AS BIT) AS [Read],
			CAST(MAX(TP.U) AS BIT) AS [Update],
			CAST(MAX(TP.D) AS BIT) AS [Delete],
			CAST(MAX(TP.S) AS BIT) AS [Search],
			CAST(MAX(TP.P) AS BIT) AS [Print],
			CAST(MAX(TP.X) AS BIT) AS [Execute]
		FROM
		(
			SELECT 	
				P.TaskId					AS	TaskID,
				(Permission & 1) 		AS	C, --[Create],
				(Permission & 2)/2		AS	R, --[Read],
				(Permission & 4)/4		AS	U, --[Update],
				(Permission & 8)/8		AS	D, --[Delete],
				(Permission & 16)/16 	AS	S, --[Search],
				(Permission & 32)/32 	AS	P, --[Print],
				(Permission & 64)/64 	AS	X --[Execute]
			FROM sSecurity.tPermissionUser P
			INNER JOIN sSecurity.tOrganizationTask T ON P.TaskId = T.TaskId And T.OrgGroupId = @rOrgGroupId
			INNER JOIN sSecurity.tTask T1 ON T1.Id=P.TaskId 
			INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId=T1.ModuleId AND MP.OrgGroupId=@rOrgGroupId
			WHERE
			P.OrgGroupId = @rOrgGroupId 
			AND T1.Id in(
			20075, -- Student Register
			20086, -- Circular
			20094, -- Assignment
			20107, -- Query Queue
			20126, -- Behaviour Entry
			20171, -- Assign Task
			20184, -- Add Photo
			20538, -- Leave Listing
			20561, -- Classwork
			20983, -- My Leave
			30032, -- Subjectwise Attendance
			30502, -- Consolidate - Receipt Details
			30501, -- Consolidate - Fee Status
			30505, -- Consolidate - Student Attendance
			30504, -- Consolidate - Assessment
			30508, -- Consolidate - Task - Attendance
			30507, -- Consolidate - Admission form
			30506, -- Consolidate - Staff
			30536, -- My Expense
			30546, -- Student Alert
			30547, -- Employee Alert
			30550, -- Student Birthdays
			30551, -- Employee Birthdays
			30560, -- Lead Master Admin Permission
			30572, -- Add Lead Permission
			30573, -- Consolidate - Admission Inquiry 
			20089, -- New Query
			30607, -- Consolidate - Task - CW/HW
			30621, -- Consolidate - Fee Collection
			30630, -- Payment Transaction Update
			30621, -- Consolidate - Fee Collection
			20555, -- Lesson Plan
			30635, -- Division Wise -  Photo
			30662, -- Data Search
			30663, -- ClassWork - Home Work Dash Board Search
			30664, -- ClassWork HomeWork Queue
			30678, -- Assignment Queue
			30585, -- Circular Queue
			30687, -- Is Allow SMS Alert
			30688, -- Is Allow Email Alert
			30689, -- Is Allow Notification Alert
			30222, -- Circular Admin
			30540, -- Summarise - Security Dashboard
			30541, -- Summarise - Library Dashboard
			30542, -- Summarise - Transport Dashboard
			30703, -- Summarise - Employee Summary
			30706, -- Summarise - Student Summary
			30766, -- Consolidate Pending Fee
			30768, -- Religionwise Strength Dashboard
			30769, -- Exam Schedule Dashboard 
			20097, -- View Query
			30249, -- Classwork/Homework
			30788, -- Online Learning - Teacher
			30792, -- Online Learning Admin View
			30786, --Online Learning 
			30787, --Online learning Student View
			30815, --Consolidate - Fee Status
			30813, --My Chat - OnlineLearning
			30862,  --Manage Mobile Account
			30900,  -- Close Query
			30927,  -- Classwork Homework Queue Search All
			30930,   -- Consolidate - Admission Inquiry Summary,
			30933,   -- Biometric Punch
			20284,   --Visitor Gate Pass
			30646,   -- Mark Entry From App 
			30944,   -- Circular - Data Search
			30945,   -- Assignment Data Search
			30946,   -- Lesson Data Search
			30947,   -- CW/HW Data Search
			30951,   -- Visitor Log Listing
			30861,   -- Consolidate - Student Subject Attendance
			30505,    -- Consolidate - Student Attendance
			30983,    -- Consolidate - Fee Details Status
			20080,   -- AdmissionInquiry
			30994,   -- AttendanceFollowup
			20556,   -- HostelStudentGatePass
			20934,   -- CS Exam Mark Entry Bulk
			20710,   -- CS Exam Grade Entry Bulk
			20478,   -- CS Exam Indicator Entry Bulk
			20749,   -- Activity Mark Entry Bulk
			20745,   -- Activity Grade Score Bulk
			20746,   -- Activity Indicator Score Bulk
			31007,   -- Is Mark Entry View
			31008 ,  -- Is CS Entry View
			31009   -- Is Activity Entry View

			)
		) TP 
		GROUP BY TP.TaskId
	END
ELSE
	BEGIN
	
		SELECT		
			TP.TaskId AS TaskID,
			CAST(MAX(TP.C) AS BIT) AS [Create],
			CAST(MAX(TP.R) AS BIT) AS [Read],
			CAST(MAX(TP.U) AS BIT) AS [Update],
			CAST(MAX(TP.D) AS BIT) AS [Delete],
			CAST(MAX(TP.S) AS BIT) AS [Search],
			CAST(MAX(TP.P) AS BIT) AS [Print],
			CAST(MAX(TP.X) AS BIT) AS [Execute]
		FROM
		(
			SELECT 	
				P.TaskId					AS	TaskID,
				(Permission & 1) 		AS	C, --[Create],
				(Permission & 2)/2		AS	R, --[Read],
				(Permission & 4)/4		AS	U, --[Update],
				(Permission & 8)/8		AS	D, --[Delete],
				(Permission & 16)/16 	AS	S, --[Search],
				(Permission & 32)/32 	AS	P, --[Print],
				(Permission & 64)/64 	AS	X --[Execute]
			FROM sSecurity.tPermission P
			INNER JOIN sSecurity.tOrganizationTask T ON P.TaskId = T.TaskId And T.OrgGroupId = @rOrgGroupId
			INNER JOIN sSecurity.tTask T1 ON T1.Id=P.TaskId 
			INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId=T1.ModuleId AND MP.OrgGroupId=@rOrgGroupId
			INNER JOIN (SELECT RoleId FROM sSecurity.tUserRole WHERE IsObsolete = 0 AND UserId = @rUserId) R
			ON R.RoleId = P.RoleId 
			WHERE
			P.OrgGroupId = @rOrgGroupId 
			AND T1.Id in(
			20075, -- Student Register
			20086, -- Circular
			20094, -- Assignment
			20107, -- Query Queue
			20126, -- Behaviour Entry
			20171, -- Assign Task
			20184, -- Add Photo
			20538, -- Leave Listing
			20561, -- Classwork
			20983, -- My Leave
			30032, -- Subjectwise Attendance
			30502, -- Consolidate - Receipt Details
			30501, -- Consolidate - Fee Status
			30505, -- Consolidate - Student Attendance
			30504, -- Consolidate - Assessment
			30508, -- Consolidate - Task - Attendance
			30507, -- Consolidate - Admission form
			30506, -- Consolidate - Staff
			30536, -- My Expense
			30546, -- Student Alert
			30547, -- Employee Alert
			30550, -- Student Birthdays
			30551, -- Employee Birthdays
			30560, -- Lead Master Admin Permission
			30572, -- Add Lead Permission
			30573, -- Consolidate - Admission Inquiry 
			20089, -- New Query
			30607, -- Consolidate - Task - CW/HW
			30621, -- Consolidate - Fee Collection
			30630, -- Payment Transaction Update
			30621, -- Consolidate - Fee Collection
			20555, -- Lesson Plan
			30635, -- Division Wise -  Photo
			30662, -- Data Search
			30663, -- ClassWork - Home Work Dash Board Search
			30664, -- ClassWork HomeWork Queue
			30678, -- Assignment Queue
			30585, -- Circular Queue
			30687, -- Is Allow SMS Alert
			30688, -- Is Allow Email Alert
			30689, -- Is Allow Notification Alert
			30222, -- Circular Admin
			30540, -- Summarise - Security Dashboard
			30541, -- Summarise - Library Dashboard
			30542, -- Summarise - Transport Dashboard
			30703, -- Summarise - Employee Summary
			30706, -- Summarise - Student Summary
			30766, -- Consolidate Pending Fee
			30768, -- Religionwise Strength Dashboard
			30769, -- Exam Schedule Dashboard
			20097, -- View Query
			30249,  -- Classwork/Homework
			30788, -- Online Learning - Teacher
			30792, -- Online Learning Admin View
			30786 , --Online Learning 
			30787,  --Online learning Student View
			30815,  --Consolidate - Fee Status
			30813,  --My Chat - OnlineLearning
			30862,  --Manage Mobile Account
			30900,  -- Close Query
			30927,  -- Classwork Homework Queue Search All
			30930,  -- Consolidate - Admission Inquiry Summary
			30933,   -- Biometric Punch
			20284,   --Visitor Gate Pass
			30646,   -- Mark Entry From App
			30944,   -- Circular - Data Search
			30945,   -- Assignment Data Search
			30946,   -- Lesson Data Search
			30947,   -- CW/HW Data Search
			30951,    -- Visitor Log Listing
			30861,   -- Consolidate - Student Subject Attendance
			30505,    -- Consolidate - Student Attendance			
			30983,    -- Consolidate - Fee Details Status
			20080,   -- AdmissionInquiry
			30994,   -- AttendanceFollowup
			20556,    -- HostelStudentGatePass
			20934,   -- CS Exam Mark Entry Bulk
			20710,   -- CS Exam Grade Entry Bulk
			20478,   -- CS Exam Indicator Entry Bulk
			20749,   -- Activity Mark Entry Bulk
			20745,   -- Activity Grade Score Bulk
			20746,   -- Activity Indicator Score Bulk
			31007,   -- Is Mark Entry View
			31008 ,  -- Is CS Entry View
			31009   -- Is Activity Entry View
			) 
		) TP 
		GROUP BY TP.TaskId
	END
END
GO
PRINT N'Altering [sSecurity].[pScreenGroupDataListGet]...';


GO
 
ALTER PROCEDURE [sSecurity].[pScreenGroupDataListGet]

	@rUserId [bigint]

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

DECLARE @lOrgGroupId bigint , @lConfigValue nvarchar(10) = ''

IF EXISTS (SELECT OM.OrgGroupId FROM sSecurity.tUser U INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = U.OrgId WHERE U.Id = @rUserId)
BEGIN
	SELECT @lOrgGroupId = OM.OrgGroupId FROM sSecurity.tUser U INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = U.OrgId WHERE U.Id = @rUserId
		
	SELECT @lConfigValue = ISNULL(CS.ItemValue,'False') FROM sConfig.tConfigurationMaster CM LEFT JOIN sConfig.tConfigurationSetup CS ON CM.Id=CS.Configurationid AND CS.SourceId= @lOrgGroupId AND CS.SourceTypeId=2010 WHERE CM.Id = 327

		IF(@lConfigValue = 'True')
		BEGIN
		     IF EXISTS (SELECT 1 FROM sSecurity.tPermissionUser WHERE UserId=@rUserId AND OrgGroupId=@lOrgGroupId)
				BEGIN
					SELECT S.Id AS Id,LEFT(S.Title,32) AS Title 
					From sSecurity.tScreen S 
					INNER JOIN sSecurity.tPermissionUser P ON P.TaskId=S.TaskId 
					INNER JOIN sSecurity.tTask T ON T.ID = p.TaskId 
					INNER JOIN sSecurity.tOrganizationTask OT ON T.Id = OT.TaskId AND OT.OrgGroupId = P.OrgGroupId 
					INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId=T.ModuleId AND MP.OrgGroupId=@lOrgGroupId
					WHERE (P.Permission & 2) =2 AND P.OrgGroupId = @lOrgGroupId AND T.IsObsolete = 0 AND P.UserId=@rUserId
					AND T.Id IN (20085,20086,30401,30222,20762,20091,20184,20183,20054,20621,20056,20199,
					30228,20693,20692,20241,20563,20561,30249,20622,143,9072,144,20249,20223,20270,20246,20001,20002,20003,20004,20007,20285,20323,20616,20055,
					139,20175,20176,141,142,20158, 30499,20309,20021,20312,20269,30299,10187,20716,20268,20968,20216,20215,20962,20080,31002)
				END
			ELSE
				BEGIN
					SELECT S.Id AS Id,LEFT(S.Title,32) AS Title 
					From sSecurity.tScreen S 
					INNER JOIN sSecurity.tPermission P ON P.TaskId=S.TaskId 
					INNER JOIN sSecurity.tUserRole U ON U.RoleId=P.RoleId 
					INNER JOIN sSecurity.tTask T ON T.ID = p.TaskId 
					INNER JOIN sSecurity.tOrganizationTask OT ON T.Id = OT.TaskId AND OT.OrgGroupId = P.OrgGroupId 
					WHERE (P.Permission & 2) =2 AND U.IsObsolete=0 AND T.IsObsolete = 0 AND U.UserId=@rUserId
					AND T.Id IN (20085,20086,30401,30222,20762,20091,20184,20183,20054,20621,20056,20199,
					30228,20693,20692,20241,20563,20561,30249,20622,143,9072,144,20249,20223,20270,20246,20001,20002,20003,20004,20007,20285,20323,20616,20055,
					139,20175,20176,141,142,20158, 30499,20309,20021,20312,20269,30299,10187,20716,20268,20968,20216,20215,20962,20080,31002)
				END
		END
		ELSE
		BEGIN
			  IF EXISTS (SELECT 1 FROM sSecurity.tPermissionUser WHERE UserId=@rUserId AND OrgGroupId=@lOrgGroupId)
				BEGIN
					SELECT S.Id AS Id,LEFT(S.Title,32) AS Title 
					From sSecurity.tScreen S 
					INNER JOIN sSecurity.tPermissionUser P ON P.TaskId=S.TaskId 
					INNER JOIN sSecurity.tTask T ON T.ID = p.TaskId 
					INNER JOIN sSecurity.tOrganizationTask OT ON T.Id = OT.TaskId AND OT.OrgGroupId = P.OrgGroupId 
					INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId=T.ModuleId AND MP.OrgGroupId=@lOrgGroupId
					WHERE (P.Permission & 2) =2 AND P.OrgGroupId = @lOrgGroupId AND T.IsObsolete = 0 AND P.UserId=@rUserId
				END
			  ELSE
				BEGIN
					SELECT S.Id AS Id,LEFT(S.Title,32) AS Title 
					From sSecurity.tScreen S 
					INNER JOIN sSecurity.tPermission P ON P.TaskId=S.TaskId 
					INNER JOIN sSecurity.tUserRole U ON U.RoleId=P.RoleId 
					INNER JOIN sSecurity.tTask T ON T.ID = p.TaskId 
					INNER JOIN sSecurity.tOrganizationTask OT ON T.Id = OT.TaskId AND OT.OrgGroupId = P.OrgGroupId 
					WHERE (P.Permission & 2) =2 AND U.IsObsolete=0 AND T.IsObsolete = 0 AND U.UserId=@rUserId
				END
		END
END

END
GO
PRINT N'Altering [sSetup].[pDivisionMasterGet]...';


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

BEGIN 
	 IF @rIsSearch = 1
		BEGIN
			SET @rCode = sCommon.fSearchStringGet(@rCode)
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		END
	
	SELECT 
	
			DM.Id,
			DM.Code,
			DM.Title,
			DM.DisplayTitle,
			DM.ClassId,
			CM.Title AS ClassTitle,
			InchargeEmployeeId AS InchargeEmployeeId,
		    ISNULL(EM.Code,'') AS InchargeEmployeeCode,
		    ISNULL(EM.FirstName,'')+ ' ' + ISNULL(EM.MiddleName,'')+ ' ' + ISNULL(EM.LastName,'') AS InchargeEmployeeName,
		    DM.Location,
			DM.OrderIndex,
			DM.CreatedUserId,
			DM.CreatedDateTime,
			DM.UpdatedUserId,
			DM.UpdatedDateTime,
			DM.IsObsolete,
			ISNULL(DM.Capacity,0) AS Capacity,
			ISNULL(DM.IsBlockAttendanceAlert,0) AS IsBlockAttendanceAlert
      
  FROM 
            sSetup.tDivisionMaster DM
           INNER JOIN sSetup.tClassMaster CM
				ON CM.Id=DM.ClassId
		   LEFT JOIN sHrm.tEmployeeMaster EM 
				ON EM.Id = DM.InchargeEmployeeId AND EM.IsObsolete = 0 AND ISNULL(EM.IsOtherUser,0) = 0 
					     
		    
  WHERE 
  
      ((DM.Id = @rId) OR (@rId = 0))
	AND  ((DM.Code like @rCode) OR (ISNULL(@rCode,'') = '')) 
	AND  ((DM.Title like @rTitle) OR (ISNULL(@rTitle,'') = '')) 
	AND ((DM.ClassId=@rClassId) OR (@rClassId = 0))
	AND DM.OrgId=@rOrgId	
	order by DM.OrderIndex asc	
END
GO
PRINT N'Altering [sTimetable].[pAssignTimeTableBreakTime]...';


GO

ALTER PROCEDURE [sTimetable].[pAssignTimeTableBreakTime]
		
		@rTimeTableSchemaId int,
        @rDivisionId int,
		@rDayId int,
		@rAfterLectureNumber int,
		@rFromTime nvarchar(MAX),
		@rToTime nvarchar(MAX),
		@rIsBreak bit = 1,
		@rOrgId int

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	IF EXISTS(SELECT 1 FROM sTimetable.tTimeTableTime WHERE TimeTableSchemaId = @rTimeTableSchemaId AND DivisionId = @rDivisionId AND DayId = @rDayId AND LectureNumber = @rAfterLectureNumber AND IsBreak = @rIsBreak)
	BEGIN
	 UPDATE  sTimetable.tTimeTableTime
	    SET
			 FromTime = @rFromTime,
			 ToTime = @rToTime
	      
	      WHERE TimeTableSchemaId = @rTimeTableSchemaId 
				AND DivisionId = @rDivisionId 
				AND DayId = @rDayId 
				AND LectureNumber = @rAfterLectureNumber
				AND IsBreak = @rIsBreak
		SELECT 1 As Result
	END
ELSE
	BEGIN
	Insert Into sTimetable.tTimeTableTime
		(
			TimeTableSchemaId,
			DivisionId,
			DayId,
			LectureNumber,
			FromTime,
			ToTime,
			IsBreak
		)
	VALUES
		(
		@rTimeTableSchemaId,
        @rDivisionId,
		@rDayId,
		@rAfterLectureNumber,
		@rFromTime,
		@rToTime,
		@rIsBreak
		)
		DECLARE @lNextNumber BIGINT
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sTimetable.tTimeTable', 0, 1, 1,@outNextNumber = @lNextNumber output

	IF NOT EXISTS (SELECT 1 FROM sTimetable.tTimeTable WHERE TimeTableSchemaId = @rTimeTableSchemaId AND DivisionId = @rDivisionId ANd DayId = @rDayId
	AND LectureNumber = @rAfterLectureNumber)
	BEGIN
	Insert Into sTimetable.tTimeTable
		(
			Id,
			TimeTableSchemaId,
			EmployeeId,
			DivisionId,
			SubjectId,
			DayId,
			LectureNumber,
			LockNo,
			LockColour,
			SchoolRoomId,
			IsBreak
			
		)
	VALUES
		(
		@lNextNumber,
		@rTimeTableSchemaId,
		0,
        @rDivisionId,
		0,
		@rDayId,
		@rAfterLectureNumber,
		0,
		0,
		0,
		@rIsBreak
		)
		SELECT @lNextNumber AS Result
		END
	END
END
GO
PRINT N'Altering [sTimetable].[pAssignTimeTableBreakTimeToOtherClass]...';


GO

 
ALTER PROCEDURE [sTimetable].[pAssignTimeTableBreakTimeToOtherClass]
		
		@rTimeTableSchemaId int,
        @rDivisionId int,
		@rDayId int,
		@rAfterLectureNumber int,
		@rIsBreak bit = 1,
		@rOrgId int,
		@rApplyForClassDivision nvarchar(MAX)

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	CREATE TABLE #TmpClassDivisionTable
	(
	 Id int IDENTITY(1,1),
	 DivisionId BIGINT
	)

	INSERT INTO #TmpClassDivisionTable SELECT * FROM sCommon.fnSplit(@rApplyForClassDivision,',')

	DECLARE @cnt INT = 0, @lDivisionCount INT = 0, @lClassDivisionId BIGINT;
	SELECT @lDivisionCount = COUNT(*) FROM #TmpClassDivisionTable

	WHILE @cnt < @lDivisionCount
	BEGIN
		
		SET @lClassDivisionId = (SELECT DivisionId FROM #TmpClassDivisionTable WHERE Id = @cnt + 1)

		IF EXISTS(SELECT 1 FROM sTimetable.tTimeTableTime WHERE TimeTableSchemaId = @rTimeTableSchemaId AND DivisionId = @lClassDivisionId AND DayId = @rDayId AND LectureNumber = @rAfterLectureNumber AND IsBreak = @rIsBreak)
		BEGIN
			UPDATE  sTimetable.tTimeTableTime
			SET
					FromTime = (SELECT FromTime FROM sTimetable.tTimeTableTime WHERE TimeTableSchemaId = @rTimeTableSchemaId AND DivisionId = @rDivisionId AND DayId = @rDayId AND LectureNumber = @rAfterLectureNumber AND IsBreak = @rIsBreak),
					ToTime = (SELECT ToTime FROM sTimetable.tTimeTableTime WHERE TimeTableSchemaId = @rTimeTableSchemaId AND DivisionId = @rDivisionId AND DayId = @rDayId AND LectureNumber = @rAfterLectureNumber AND IsBreak = @rIsBreak)
	      
				WHERE TimeTableSchemaId = @rTimeTableSchemaId 
					AND DivisionId = @lClassDivisionId 
					AND DayId = @rDayId 
					AND LectureNumber = @rAfterLectureNumber
					AND IsBreak = @rIsBreak
			SELECT 1 As Result
		END
		ELSE
			BEGIN
			Insert Into sTimetable.tTimeTableTime
				(
					TimeTableSchemaId,
					DivisionId,
					DayId,
					LectureNumber,
					FromTime,
					ToTime,
					IsBreak
				)
			SELECT TimeTableSchemaId,@lClassDivisionId,DayId,LectureNumber,FromTime,ToTime,@rIsBreak FROM sTimetable.tTimeTableTime 
			   WHERE TimeTableSchemaId = @rTimeTableSchemaId 
					AND DivisionId = @rDivisionId 
					AND DayId = @rDayId 
					AND LectureNumber = @rAfterLectureNumber
					AND IsBreak = @rIsBreak

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

			IF NOT EXISTS (SELECT 1 FROM sTimetable.tTimeTable WHERE TimeTableSchemaId = @rTimeTableSchemaId AND DivisionId = @lClassDivisionId ANd DayId = @rDayId
			AND LectureNumber = @rAfterLectureNumber)
			BEGIN
			Insert Into sTimetable.tTimeTable
				(
					Id,
					TimeTableSchemaId,
					EmployeeId,
					DivisionId,
					SubjectId,
					DayId,
					LectureNumber,
					LockNo,
					LockColour,
					SchoolRoomId,
					IsBreak
			
				)
			VALUES
				(
				@lNextNumber,
				@rTimeTableSchemaId,
				0,
				@lClassDivisionId,
				0,
				@rDayId,
				@rAfterLectureNumber,
				0,
				0,
				0,
				@rIsBreak
				)
				SELECT @lNextNumber AS Result

				END
			END

		SET @cnt = @cnt + 1;
	END
	DROP TABLE #TmpClassDivisionTable

	
END
GO
PRINT N'Altering [sTimetable].[pRptDivisionTimeTableGet]...';


GO


 
ALTER PROCEDURE [sTimetable].[pRptDivisionTimeTableGet]

	  --@rBuilder1 nvarchar(max)='',
	  --@rBuilder2 nvarchar(max)='', 
	  @rBatchId int,
	  @rClassId int,
	  @rDivisionId int,
	  @rEmployeeId bigint,
	  @rTimeTableSchemaId int,
	  @rReportId int=0,
	  @rDate Date='',
	  @rOrgId int=0
	  
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON 

BEGIN   
  IF(@rReportId=10166) -- Teacherwise
  BEGIN
  SELECT

	A.TimeTableID,
	A.DivisionName,
	
	A.EmployeeId,
	A.SubjectId,
	
	CASE WHEN A.EmployeeId=-1 THEN '###' WHEN A.EmployeeId=-2 THEN '***' ELSE A.EmployeeName END  AS EmployeeName,
	CASE WHEN A.SubjectId=-1 THEN '###' WHEN A.SubjectId=-2 THEN '***' ELSE A.Subject END  AS Subject,
	--A.Subject,
	A.DivisionId,
	ISNULL(L.Title,'') AS DayName,
	ISNULL(L.DayId,0) AS DayId,
	ISNULL(L.LectureNumber,'') AS LactureNumber,
	--ISNULL(A.DayName,'') AS DayName,
	--ISNULL(A.DayId,0) AS DayId,
	--ISNULL(A.LactureNumber,'') AS LactureNumber,
	A.DayLacture,
	A.ClassId,
	A.ClassDivisionName,
	A.DivisionOrderIndex,
	A.Code,
	A.TimeTableDetail,
	0 As IsPresent,
	'' As WeekOffs,
	CASE WHEN EXISTS (SELECT 1 FROM sTimetable.tTimeTableSchema TS INNER JOIN sTimetable.tTimeTable TT ON TT.TimeTableSchemaId = TS.Id WHERE TS.IsDisplayPeriodTime = 1 AND TS.Id = @rTimeTableSchemaId) THEN A.FromTime ELSE '' END As FromTime,
	CASE WHEN EXISTS (SELECT 1 FROM sTimetable.tTimeTableSchema TS INNER JOIN sTimetable.tTimeTable TT ON TT.TimeTableSchemaId = TS.Id WHERE TS.IsDisplayPeriodTime = 1 AND TS.Id = @rTimeTableSchemaId) THEN A.ToTime ELSE '' END As ToTime,
	ISNULL(IsDiplayPeriodTime,0) As IsDiplayPeriodTime,
	'' as DivisionIncharge,
	IsBreak

  FROM
(
	SELECT 
	--@rBuilder1 AS Builder1,
	--@rBuilder2 AS Builder2,	 
	TT.Id AS TimeTableID,
	ISNULL(DV.Title,'') AS DivisionName,
	ISNULL(EmployeeId,0) AS EmployeeId,
	ISNULL(SubjectId,0) AS SubjectId,

	ISNULL(Em.FirstName +'  '+Em.LastName,'')  AS EmployeeName,
	--ISNULL(Em.FirstName,'')  AS EmployeeName,  
	ISNULL(SM.Title,'') AS Subject,
	ISNULL(TT.DivisionId,0) AS DivisionId,
	ISNULL(DM.Title,'') AS DayName,
	ISNULL(TT.DayId,0) AS DayId,
	ISNULL(TT.LectureNumber,'') AS LactureNumber,
	ISNULL(DM.Title,'') +'-'+ISNULL(convert(nvarchar(4),TT.LectureNumber),'') AS DayLacture,
	ISNULL(DV.ClassId,0) AS ClassId,
	ISNULL(CM.DisplayTitle,'')+'-'+ISNULL(DV.Title,'') as ClassDivisionName,
	ISNULL(DV.OrderIndex,0) As DivisionOrderIndex,
	ISNULL(SM.Code,'') AS Code,
	--'' AS TimeTableDetail,
	--(ISNULL(CM.DisplayTitle,'')+'-'+ISNULL(DV.Title,'') + ISNULL(SM.Title,'')) AS TimeTableDetail
	ISNULL([sTimetable].[fTimeTableDivisionGet](TT.TimeTableSchemaId,TT.Id,TT.EmployeeId,TT.DayId,TT.LectureNumber,0),'') AS TimeTableDetail,
	ISNULL(TTM.FromTime,0) As FromTime,
	ISNULL(TTM.ToTime,0) As ToTime,
	ISNULL(TS.IsDisplayPeriodTime,0) As IsDiplayPeriodTime,

	--GetBreak
	CASE WHEN 
	(SELECT ISNULL(IsBreak,0) FROM sTimetable.tTimeTableTime WHERE TimeTableSchemaId = TT.TimeTableSchemaId 
	AND DayId = TT.DayId AND DivisionId = TT.DivisionId AND LectureNumber = TT.LectureNumber AND IsBreak = 1) = 1 
	THEN (SELECT ISNULL(IsBreak,0) FROM sTimetable.tTimeTableTime WHERE TimeTableSchemaId = TT.TimeTableSchemaId 
	AND DayId = TT.DayId AND DivisionId = TT.DivisionId AND LectureNumber = TT.LectureNumber AND IsBreak = 1)
	ELSE ISNULL(TT.IsBreak,0) END AS IsBreak

	FROM 
	sTimetable.tTimeTable TT	
	LEFT JOIN sSetup.tSubjectMaster SM ON SM.Id = TT.SubjectId 
	LEFT JOIN sHrm.tEmployeeMaster Em ON Em.Id = TT.EmployeeId
	LEFT JOIN sCommon.tDayMaster DM ON DM.Id = TT.DayId
	LEFT JOIN sSetup.tDivisionMaster DV ON DV.Id = TT.DivisionId
	LEFT JOIN sSetup.tClassMaster CM ON CM.Id = DV.ClassId
	LEFT JOIN sTimetable.tTimeTableTime TTM ON TTM.TimeTableSchemaId=TT.TimeTableSchemaId AND TTM.DayId = DM.Id AND TTM.DivisionId = TT.DivisionId AND TTM.LectureNumber = TT.LectureNumber
	INNER JOIN sTimetable.tTimeTableSchema TS ON TS.Id = TT.TimeTableSchemaId
	WHERE (ClassId = @rClassId OR @rClassId=0)
	  AND (TT.DivisionId = @rDivisionId OR @rDivisionId=0)	
	  AND (TT.EmployeeId=@rEmployeeId OR @rEmployeeId=0)
	  AND TT.TimeTableSchemaId=@rTimeTableSchemaId
	  
	  UNION ALL
	  
	  
	  
	  	SELECT 
	--@rBuilder1 AS Builder1,
	--@rBuilder2 AS Builder2,	 
	TT.Id AS TimeTableID,
	ISNULL(DV.Title,'') AS DivisionName,
	ISNULL(TTD.EmployeeId,0) AS EmployeeId,
	ISNULL(TTD.SubjectId,0) AS SubjectId,

	ISNULL(Em.FirstName +'  '+Em.LastName,'')  AS EmployeeName,
	--ISNULL(Em.FirstName,'')  AS EmployeeName,  
	ISNULL(SM.Title,'') AS Subject,
	ISNULL(TT.DivisionId,0) AS DivisionId,
	ISNULL(DM.Title,'') AS DayName,
	ISNULL(TT.DayId,0) AS DayId,
	ISNULL(TT.LectureNumber,'') AS LactureNumber,
	ISNULL(DM.Title,'') +'-'+ISNULL(convert(nvarchar(4),TT.LectureNumber),'') AS DayLacture,
	ISNULL(DV.ClassId,0) AS ClassId,
	ISNULL(CM.DisplayTitle,'')+'-'+ISNULL(DV.Title,'') as ClassDivisionName,
	ISNULL(DV.OrderIndex,0) As DivisionOrderIndex,
	ISNULL(SM.Code,'') AS Code,
	--(ISNULL(CM.DisplayTitle,'')+'-'+ISNULL(DV.Title,'') + ISNULL(SM.Title,'')) AS TimeTableDetail
	'' AS TimeTableDetail,
	ISNULL(TTM.FromTime,0) As FromTime,
	ISNULL(TTM.ToTime,0) As ToTime,
	ISNULL(TS.IsDisplayPeriodTime,0) As IsDiplayPeriodTime,
	0 AS IsBreak
	FROM 
	sTimetable.tTimeTable TT
	INNER JOIN 	sTimetable.tTimeTableDetail TTD ON TTD.TimetableId = TT.Id
	INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = TTD.SubjectId 
	INNER JOIN sHrm.tEmployeeMaster Em ON Em.Id = TTD.EmployeeId
	LEFT JOIN sCommon.tDayMaster DM ON DM.Id = TT.DayId
	LEFT JOIN sSetup.tDivisionMaster DV ON DV.Id = TT.DivisionId
	LEFT JOIN sSetup.tClassMaster CM ON CM.Id = DV.ClassId
	LEFT JOIN sTimetable.tTimeTableTime TTM ON TTM.TimeTableSchemaId=TT.TimeTableSchemaId AND TTM.DayId = DM.Id AND TTM.DivisionId = TT.DivisionId AND TTM.LectureNumber = TT.LectureNumber
	INNER JOIN sTimetable.tTimeTableSchema TS ON TS.Id = TT.TimeTableSchemaId 

	WHERE (ClassId = @rClassId OR @rClassId=0)
	  AND (TT.DivisionId = @rDivisionId OR @rDivisionId=0)	
	  AND (TTD.EmployeeId=@rEmployeeId OR @rEmployeeId=0)
	  AND TT.TimeTableSchemaId=@rTimeTableSchemaId
	 
	  
	  --ORDER BY DV.OrderIndex
	  )
	  A
			INNER JOIN (SELECT DISTINCT DayId,LectureNumber,DM.title  FROM sTimetable.tTimeTable
			INNER JOIN sCommon.tDayMaster DM ON DM.Id = DayId
			WHERE TimeTableSchemaId=@rTimeTableSchemaId  ) L
			ON A.LactureNumber = L.LectureNumber AND A.DayId = L.DayId

	END
ELSE IF(@rReportId = 30661) --- Absent Teacher Divisionwise
  BEGIN
	  SELECT

	A.TimeTableID,
	A.DivisionName,
	
	A.EmployeeId,
	A.SubjectId,
	
	CASE WHEN A.EmployeeId=-1 THEN '###' WHEN A.EmployeeId=-2 THEN '***' ELSE A.EmployeeName END  AS EmployeeName,
	CASE WHEN A.SubjectId=-1 THEN '###' WHEN A.SubjectId=-2 THEN '***' ELSE A.Subject END  AS Subject,
	--A.Subject,
	A.DivisionId,
	ISNULL(L.Title,'') AS DayName,
	ISNULL(L.DayId,0) AS DayId,
	ISNULL(L.LectureNumber,'') AS LactureNumber,
	--ISNULL(A.DayName,'') AS DayName,
	--ISNULL(A.DayId,0) AS DayId,
	--ISNULL(A.LactureNumber,'') AS LactureNumber,
	A.DayLacture,
	A.ClassId,
	ISNULL(A.ClassDivisionName,'')AS ClassDivisionName,
	A.DivisionOrderIndex,
	A.Code,
	A.TimeTableDetail,
	A.IsPresent,
	'' As WeekOffs,
	0 As FromTime,
	0 As ToTime,
	'' as DivisionIncharge
  FROM
(
	SELECT 
	--@rBuilder1 AS Builder1,
	--@rBuilder2 AS Builder2,	 
	TT.Id AS TimeTableID,
	ISNULL(DV.Title,'') AS DivisionName,
	ISNULL(EAR.EmployeeId,0) AS EmployeeId,
	ISNULL(SubjectId,0) AS SubjectId,

	ISNULL(Em.FirstName +'  '+Em.LastName,'')  AS EmployeeName,
	--ISNULL(Em.FirstName,'')  AS EmployeeName,  
	ISNULL(SM.Title,'') AS Subject,
	ISNULL(TT.DivisionId,0) AS DivisionId,
	ISNULL(DM.Title,'') AS DayName,
	ISNULL(TT.DayId,0) AS DayId,
	ISNULL(TT.LectureNumber,'') AS LactureNumber,
	ISNULL(DM.Title,'') +'-'+ISNULL(convert(nvarchar(4),TT.LectureNumber),'') AS DayLacture,
	ISNULL(DV.ClassId,0) AS ClassId,
	ISNULL(CM.DisplayTitle,'')+'-'+ISNULL(DV.Title,'') as ClassDivisionName,
	ISNULL(DV.OrderIndex,0) As DivisionOrderIndex,
	ISNULL(SM.Code,'') AS Code,
	'' AS TimeTableDetail,
	ISNULL(EAR.IsPresent,0) AS IsPresent
	--(ISNULL(CM.DisplayTitle,'')+'-'+ISNULL(DV.Title,'') + ISNULL(SM.Title,'')) AS TimeTableDetail
	--ISNULL([sTimetable].[fTimeTableDivisionGet](TT.TimeTableSchemaId,TT.Id,TT.EmployeeId,TT.DayId,TT.LectureNumber),'') AS TimeTableDetail
	FROM 
	sTimetable.tTimeTable TT	 
	LEFT JOIN sSetup.tSubjectMaster SM ON SM.Id = TT.SubjectId 
	LEFT JOIN sHrm.tEmployeeMaster Em ON Em.Id = TT.EmployeeId
	LEFT JOIN sCommon.tDayMaster DM ON DM.Id = TT.DayId
	LEFT JOIN sSetup.tDivisionMaster DV ON DV.Id = TT.DivisionId
	LEFT JOIN sSetup.tClassMaster CM ON CM.Id = DV.ClassId
	RIGHT JOIN sHrm.tEmployeeAttendanceRegister EAR ON EAR.EmployeeId = Em.Id

	WHERE (ClassId = @rClassId OR @rClassId=0)
	  AND (TT.DivisionId = @rDivisionId OR @rDivisionId=0)	
	  AND (TT.EmployeeId=@rEmployeeId OR @rEmployeeId=0)
	  AND TT.TimeTableSchemaId=@rTimeTableSchemaId
	  AND (EAR.AttendanceDate = @rDate OR @rDate = '')
	  AND (TT.DayId = (DATEPART(weekday,@rDate)) OR @rDate = '')

	  UNION ALL
	  
	  
	  
	  	SELECT 
	--@rBuilder1 AS Builder1,
	--@rBuilder2 AS Builder2,	 
	TT.Id AS TimeTableID,
	ISNULL(DV.Title,'') AS DivisionName,
	ISNULL(TTD.EmployeeId,0) AS EmployeeId,
	ISNULL(TTD.SubjectId,0) AS SubjectId,

	ISNULL(Em.FirstName +'  '+Em.LastName,'')  AS EmployeeName,
	--ISNULL(Em.FirstName,'')  AS EmployeeName,  
	ISNULL(SM.Title,'') AS Subject,
	ISNULL(TT.DivisionId,0) AS DivisionId,
	ISNULL(DM.Title,'') AS DayName,
	ISNULL(TT.DayId,0) AS DayId,
	ISNULL(TT.LectureNumber,'') AS LactureNumber,
	ISNULL(DM.Title,'') +'-'+ISNULL(convert(nvarchar(4),TT.LectureNumber),'') AS DayLacture,
	ISNULL(DV.ClassId,0) AS ClassId,
	ISNULL(CM.DisplayTitle,'')+'-'+ISNULL(DV.Title,'') as ClassDivisionName,
	ISNULL(DV.OrderIndex,0) As DivisionOrderIndex,
	ISNULL(SM.Code,'') AS Code,
	--(ISNULL(CM.DisplayTitle,'')+'-'+ISNULL(DV.Title,'') + ISNULL(SM.Title,'')) AS TimeTableDetail
	ISNULL([sTimetable].[fTimeTableDivisionGet](TT.TimeTableSchemaId,TT.Id,TTD.EmployeeId,TT.DayId,TT.LectureNumber,0),'') AS TimeTableDetail,
	ISNULL(EAR.IsPresent,'') As IsPresent
	FROM 
	sTimetable.tTimeTable TT
	INNER JOIN 	sTimetable.tTimeTableDetail TTD ON TTD.TimetableId = TT.Id
	INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = TTD.SubjectId 
	INNER JOIN sHrm.tEmployeeMaster Em ON Em.Id = TTD.EmployeeId
	LEFT JOIN sCommon.tDayMaster DM ON DM.Id = TT.DayId
	LEFT JOIN sSetup.tDivisionMaster DV ON DV.Id = TT.DivisionId
	LEFT JOIN sSetup.tClassMaster CM ON CM.Id = DV.ClassId
	LEFT JOIN sHrm.tEmployeeAttendanceRegister EAR ON EAR.EmployeeId = Em.Id

	WHERE (ClassId = @rClassId OR @rClassId=0)
	  AND (TT.DivisionId = @rDivisionId OR @rDivisionId=0)	
	  AND (TTD.EmployeeId=@rEmployeeId OR @rEmployeeId=0)
	  AND TT.TimeTableSchemaId=@rTimeTableSchemaId
	  AND (EAR.AttendanceDate = @rDate OR @rDate = '')
	  AND (TT.DayId = (DATEPART(weekday,@rDate)) OR @rDate = '') 
	  
	  --ORDER BY DV.OrderIndex
	  )
	  A
			INNER JOIN (SELECT DISTINCT DayId,LectureNumber,DM.title  FROM sTimetable.tTimeTable
			INNER JOIN sCommon.tDayMaster DM ON DM.Id = DayId
			
			WHERE TimeTableSchemaId=@rTimeTableSchemaId ) L
			ON A.LactureNumber = L.LectureNumber AND A.DayId = L.DayId

	END
ELSE IF(@rReportId = 30925) --TeacherTimeTable_2
   BEGIN
   SELECT

	A.TimeTableID,
	A.DivisionName,
	A.EmployeeId,
	A.SubjectId,
	CASE WHEN A.EmployeeId=-1 THEN '###' WHEN A.EmployeeId=-2 THEN '***' ELSE A.EmployeeName END As EmployeeName,
	CASE WHEN A.SubjectId=-1 THEN '###' WHEN A.SubjectId=-2 THEN '***' ELSE A.Subject END  AS Subject,
	--A.Subject,
	A.DivisionId,
	--ISNULL(L.Title,'') AS DayName,
	--ISNULL(L.DayId,0) AS DayId,
	--ISNULL(L.LectureNumber,'') AS LactureNumber,
	ISNULL(A.DayName,'') AS DayName,
	ISNULL(A.DayId,0) AS DayId,
	ISNULL(A.LactureNumber,'') AS LactureNumber,
	A.DayLacture,
	A.ClassId,
	A.ClassDivisionName,
	A.DivisionOrderIndex,
	A.Code,
	[sTimetable].[fTimeTableDetailGet](A.TimeTableID,1) AS TimeTableDetail,
	0 AS IsPresent,
	A.WeekOffs,
	CASE WHEN EXISTS (SELECT 1 FROM sTimetable.tTimeTableSchema TS INNER JOIN sTimetable.tTimeTable TT ON TT.TimeTableSchemaId = TS.Id WHERE TS.IsDisplayPeriodTime = 1 AND TS.Id = @rTimeTableSchemaId) THEN A.FromTime ELSE '' END As FromTime,
	CASE WHEN EXISTS (SELECT 1 FROM sTimetable.tTimeTableSchema TS INNER JOIN sTimetable.tTimeTable TT ON TT.TimeTableSchemaId = TS.Id WHERE TS.IsDisplayPeriodTime = 1 AND TS.Id = @rTimeTableSchemaId) THEN A.ToTime ELSE '' END As ToTime,
	ISNULL(IsDiplayPeriodTime,0) As IsDiplayPeriodTime,
	DivisionIncharge
FROM
(
	SELECT 
	--@rBuilder1 AS Builder1,
	--@rBuilder2 AS Builder2,	 
	TT.Id AS TimeTableID,
	ISNULL(DV.Title,'') AS DivisionName,
	ISNULL(TT.EmployeeId,0) AS EmployeeId,
	ISNULL(SubjectId,0) AS SubjectId,
	ISNULL(EM.LastName+' '+EM.FirstName,'')  AS EmployeeName,
	ISNULL(SM.Title,'') AS Subject,
	ISNULL(TT.DivisionId,0) AS DivisionId,
	ISNULL(DM.Title,'') AS DayName,
	ISNULL(TT.DayId,0) AS DayId,
	ISNULL(TT.LectureNumber,'') AS LactureNumber,
	ISNULL(DM.Title,'') +'-'+ISNULL(convert(nvarchar(4),TT.LectureNumber),'') AS DayLacture,
	ISNULL(DV.ClassId,0) AS ClassId,
	ISNULL(CM.DisplayTitle,'')+'-'+ISNULL(DV.Title,'') as ClassDivisionName,
	ISNULL(DV.OrderIndex,0) As DivisionOrderIndex,
	ISNULL(SM.Code,'') AS Code,
	ISNULL(TTS.WeekOffs,'') As WeekOffs,
	ISNULL(TTM.FromTime,'') As FromTime,
	ISNULL(TTM.ToTime,'') As ToTime,
	ISNULL(TS.IsDisplayPeriodTime,0) As IsDiplayPeriodTime,
	(SELECT ISNULL(EM.FirstName+' '+EM.LastName,'') FROM sHrm.tEmployeeMaster EM INNER JOIN sSetup.tDivisionMaster DIE ON DIE.InchargeEmployeeId = EM.Id  WHERE DIE.Id = DV.Id) as DivisionIncharge
	FROM 
	sTimetable.tTimeTable TT  
	LEFT JOIN sSetup.tSubjectMaster SM ON SM.Id = TT.SubjectId 
	INNER JOIN sHrm.tEmployeeMaster Em ON Em.Id = TT.EmployeeId
	LEFT JOIN sCommon.tDayMaster DM ON DM.Id = TT.DayId
	LEFT JOIN sSetup.tDivisionMaster DV ON DV.Id = TT.DivisionId
	LEFT JOIN sSetup.tClassMaster CM ON CM.Id = DV.ClassId
	LEFT JOIN sTimetable.tTimeTableSchema TTS ON TTS.Id = TT.TimeTableSchemaId
	LEFT JOIN sTimetable.tTimeTableTime TTM ON TTM.TimeTableSchemaId=TT.TimeTableSchemaId AND TTM.DayId = DM.Id AND TTM.DivisionId = TT.DivisionId AND TTM.LectureNumber = TT.LectureNumber AND TTM.IsBreak = 0
	INNER JOIN sTimetable.tTimeTableSchema TS ON TS.Id = TT.TimeTableSchemaId 
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = DV.OrgId
	WHERE (ClassId = @rClassId OR @rClassId=0)
	  AND (TT.DivisionId = @rDivisionId OR @rDivisionId=0)	
	  AND (TT.EmployeeId=@rEmployeeId OR @rEmployeeId=0)
	  AND TT.TimeTableSchemaId=@rTimeTableSchemaId
	  AND (TT.DayId = (DATEPART(weekday,@rDate)) OR @rDate = '')
	  AND (OM.Id = @rOrgId OR @rOrgId = 0)
	  --AND (Em.OrgId = @rOrgId OR @rOrgId = 0)
	  )
	  A  ORDER BY A.EmployeeName, A.DivisionOrderIndex,A.DayId, A.LactureNumber
   END
 ELSE
 BEGIN
	SELECT

	A.TimeTableID,
	A.DivisionName,
	A.EmployeeId,
	A.SubjectId,
	CASE WHEN A.EmployeeId=-1 THEN '###' WHEN A.EmployeeId=-2 THEN '***' ELSE A.EmployeeName END As EmployeeName,
	CASE WHEN A.SubjectId=-1 THEN '###' WHEN A.SubjectId=-2 THEN '***' ELSE A.Subject END  AS Subject,
	--A.Subject,
	A.DivisionId,
	--ISNULL(L.Title,'') AS DayName,
	--ISNULL(L.DayId,0) AS DayId,
	--ISNULL(L.LectureNumber,'') AS LactureNumber,
	ISNULL(A.DayName,'') AS DayName,
	ISNULL(A.DayId,0) AS DayId,
	ISNULL(A.LactureNumber,'') AS LactureNumber,
	A.DayLacture,
	A.ClassId,
	A.ClassDivisionName,
	A.DivisionOrderIndex,
	A.Code,
	[sTimetable].[fTimeTableDetailGet](A.TimeTableID,1) AS TimeTableDetail,
	0 AS IsPresent,
	A.WeekOffs,
	CASE WHEN EXISTS (SELECT 1 FROM sTimetable.tTimeTableSchema TS INNER JOIN sTimetable.tTimeTable TT ON TT.TimeTableSchemaId = TS.Id WHERE TS.IsDisplayPeriodTime = 1 AND TS.Id = @rTimeTableSchemaId) THEN A.FromTime ELSE '' END As FromTime,
	CASE WHEN EXISTS (SELECT 1 FROM sTimetable.tTimeTableSchema TS INNER JOIN sTimetable.tTimeTable TT ON TT.TimeTableSchemaId = TS.Id WHERE TS.IsDisplayPeriodTime = 1 AND TS.Id = @rTimeTableSchemaId) THEN A.ToTime ELSE '' END As ToTime,
	ISNULL(IsDiplayPeriodTime,0) As IsDiplayPeriodTime,
	DivisionIncharge,
	IsBreak
FROM
(
	SELECT 
	--@rBuilder1 AS Builder1,
	--@rBuilder2 AS Builder2,	 
	TT.Id AS TimeTableID,
	ISNULL(DV.Title,'') AS DivisionName,
	ISNULL(TT.EmployeeId,0) AS EmployeeId,
	ISNULL(SubjectId,0) AS SubjectId,
	ISNULL(EM.LastName+' '+EM.FirstName,'')  AS EmployeeName,
	ISNULL(SM.Title,'') AS Subject,
	ISNULL(TT.DivisionId,0) AS DivisionId,
	ISNULL(DM.Title,'') AS DayName,
	ISNULL(TT.DayId,0) AS DayId,
	ISNULL(TT.LectureNumber,'') AS LactureNumber,
	ISNULL(DM.Title,'') +'-'+ISNULL(convert(nvarchar(4),TT.LectureNumber),'') AS DayLacture,
	ISNULL(DV.ClassId,0) AS ClassId,
	ISNULL(CM.DisplayTitle,'')+'-'+ISNULL(DV.Title,'') as ClassDivisionName,
	ISNULL(DV.OrderIndex,0) As DivisionOrderIndex,
	ISNULL(SM.Code,'') AS Code,
	ISNULL(TTS.WeekOffs,'') As WeekOffs,
	ISNULL(TTM.FromTime,'') As FromTime,
	ISNULL(TTM.ToTime,'') As ToTime,
	ISNULL(TS.IsDisplayPeriodTime,0) As IsDiplayPeriodTime,
	(SELECT ISNULL(EM.FirstName+' '+EM.LastName,'') FROM sHrm.tEmployeeMaster EM INNER JOIN sSetup.tDivisionMaster DIE ON DIE.InchargeEmployeeId = EM.Id  WHERE DIE.Id = DV.Id) as DivisionIncharge,

	--GetBreak
	CASE WHEN 
	(SELECT ISNULL(IsBreak,0) FROM sTimetable.tTimeTableTime WHERE TimeTableSchemaId = TT.TimeTableSchemaId 
	AND DayId = TT.DayId AND DivisionId = TT.DivisionId AND LectureNumber = TT.LectureNumber AND IsBreak = 1) = 1 
	THEN (SELECT ISNULL(IsBreak,0) FROM sTimetable.tTimeTableTime WHERE TimeTableSchemaId = TT.TimeTableSchemaId 
	AND DayId = TT.DayId AND DivisionId = TT.DivisionId AND LectureNumber = TT.LectureNumber AND IsBreak = 1)
	ELSE ISNULL(TT.IsBreak,0) END AS IsBreak
	FROM 
	sTimetable.tTimeTable TT  
	LEFT JOIN sSetup.tSubjectMaster SM ON SM.Id = TT.SubjectId 
	LEFT JOIN sHrm.tEmployeeMaster Em ON Em.Id = TT.EmployeeId
	LEFT JOIN sCommon.tDayMaster DM ON DM.Id = TT.DayId
	LEFT JOIN sSetup.tDivisionMaster DV ON DV.Id = TT.DivisionId
	LEFT JOIN sSetup.tClassMaster CM ON CM.Id = DV.ClassId
	LEFT JOIN sTimetable.tTimeTableSchema TTS ON TTS.Id = TT.TimeTableSchemaId
	LEFT JOIN sTimetable.tTimeTableTime TTM ON TTM.TimeTableSchemaId=TT.TimeTableSchemaId AND TTM.DayId = DM.Id AND TTM.DivisionId = TT.DivisionId AND TTM.LectureNumber = TT.LectureNumber AND TTM.IsBreak = 0	
	INNER JOIN sTimetable.tTimeTableSchema TS ON TS.Id = TT.TimeTableSchemaId 
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = DV.OrgId
	WHERE (ClassId = @rClassId OR @rClassId=0)
	  AND (TT.DivisionId = @rDivisionId OR @rDivisionId=0)	
	  AND (TT.EmployeeId=@rEmployeeId OR @rEmployeeId=0)
	  AND TT.TimeTableSchemaId=@rTimeTableSchemaId
	  AND (TT.DayId = (DATEPART(weekday,@rDate)) OR @rDate = '')
	  AND (OM.Id = @rOrgId OR @rOrgId = 0)
	  )
	  A  ORDER BY A.EmployeeName, A.DivisionOrderIndex,A.DayId, A.LactureNumber
		END
END
GO
PRINT N'Altering [sTimetable].[pStudentTimeTableGet]...';


GO

 
ALTER PROCEDURE [sTimetable].[pStudentTimeTableGet]
	
	 @rStudentId bigint,
	 @rTimeTableSchemaId int,
	 @rDivisionId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 

	DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX),@query1  AS NVARCHAR(MAX),@query2  AS NVARCHAR(MAX),@query3 AS NVARCHAR(MAX)

select @cols = STUFF((SELECT ',' + QUOTENAME(Title) 
                    from sCommon.tDayMaster
                    group by Title,Id 
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')
        
     
 IF EXISTS(SELECT 1 FROM sTimetable.tTimeTableSchema TS INNER JOIN sTimetable.tTimeTable TT ON TT.TimeTableSchemaId = TS.Id WHERE TS.IsDisplayPeriodTime = 1 AND TS.Id = @rTimeTableSchemaId)
  BEGIN 
		set @query = 'SELECT LectureNumber , ' + @cols + ',WeekOffs from 
					 (
					Select T.LectureNumber, ISNULL(EM.ShortName + '+ ''' - ''' +' +SM.Code ,'''') + [sTimetable].[fTimeTableDetailGet](T.Id,1) + '' | ''+ ISNULL(TTM.FromTime,0) + ''-''+ ISNULL(TTM.ToTime,0) + '' | '' + CASE WHEN ISNULL(TTM.IsBreak,0) = 1 THEN ''Break'' ELSE '''' END AS EmployeeName ,DM.Title AS DayNames
					,TTS.WeekOffs
					from
					sTimetable.tTimeTable T 
					INNER JOIN sTimetable.tTimeTableSchema TTS ON TTS.Id = T.TimeTableSchemaId AND TTS.IsPublish = 1
					INNER JOIN sCommon.tDayMaster DM ON DM.Id = T.DayId
					INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id=T.EmployeeId
					INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=T.SubjectId
					INNER JOIN sStudent.tAcademic A ON A.DivisionId=T.DivisionId
					LEFT JOIN sTimetable.tTimeTableTime TTM ON TTM.TimeTableSchemaId=T.TimeTableSchemaId AND TTM.DayId = DM.Id AND TTM.DivisionId = T.DivisionId AND TTM.LectureNumber = T.LectureNumber  AND TTM.IsBreak = 0
					 WHERE    
					((A.StudentId=' + CAST(@rStudentId AS NVARCHAR(30))+') OR('+ CAST(@rStudentId AS NVARCHAR(30))+'=0))
					AND  ((T.DivisionId=' + CAST(@rDivisionId AS NVARCHAR(30))+') OR ('+CAST(@rDivisionId AS NVARCHAR(30))+'= 0) )
					 AND ((T.TimeTableSchemaId=' + CAST(@rTimeTableSchemaId AS NVARCHAR(30))+') OR ('+CAST(@rTimeTableSchemaId AS NVARCHAR(30))+'= 0))
					) x
					pivot 
					(
						max(EmployeeName)
						for DayNames in (' + @cols + ')
					) p '
    END
 ELSE
	BEGIN
		set @query = 'SELECT LectureNumber , ' + @cols + ',WeekOffs from 
					 (
					Select LectureNumber, ISNULL(EM.ShortName + '+ ''' - ''' +' +SM.Code ,'''') + [sTimetable].[fTimeTableDetailGet](T.Id,1) + '' | '' + CASE WHEN ISNULL(TTM.IsBreak,0) = 1 THEN ''Break'' ELSE '''' END AS EmployeeName ,DM.Title AS DayNames
					,TTS.WeekOffs
					from
					sTimetable.tTimeTable T 
					INNER JOIN sTimetable.tTimeTableSchema TTS ON TTS.Id = T.TimeTableSchemaId AND TTS.IsPublish = 1
					INNER JOIN sCommon.tDayMaster DM ON DM.Id = T.DayId
					INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id=T.EmployeeId
					INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=T.SubjectId
					INNER JOIN sStudent.tAcademic A ON A.DivisionId=T.DivisionId
					 WHERE    
					((A.StudentId=' + CAST(@rStudentId AS NVARCHAR(30))+') OR('+ CAST(@rStudentId AS NVARCHAR(30))+'=0))
					AND  ((T.DivisionId=' + CAST(@rDivisionId AS NVARCHAR(30))+') OR ('+CAST(@rDivisionId AS NVARCHAR(30))+'= 0) )
					 AND ((T.TimeTableSchemaId=' + CAST(@rTimeTableSchemaId AS NVARCHAR(30))+') OR ('+CAST(@rTimeTableSchemaId AS NVARCHAR(30))+'= 0))
	       
					) x
					pivot 
					(
						max(EmployeeName)
						for DayNames in (' + @cols + ')
					) p '
	END
		print @query
		execute(@query)
END
GO
PRINT N'Altering [sTimetable].[pTeacherTimeTableGet]...';


GO
 
 
 
ALTER PROCEDURE [sTimetable].[pTeacherTimeTableGet]
	
	 @rEmployeeId bigint,
	 @rBatchId int=0,
	 @rTimeTableSchemaId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

	DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX),@query1  AS NVARCHAR(MAX),@query2  AS NVARCHAR(MAX),@query3 AS NVARCHAR(MAX)

select @cols = STUFF((SELECT ',' + QUOTENAME(Title) 
                    from sCommon.tDayMaster
                    order by Id,Title 
                    
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')
        
IF EXISTS(SELECT 1 FROM sTimetable.tTimeTableSchema TS INNER JOIN sTimetable.tTimeTable TT ON TT.TimeTableSchemaId = TS.Id WHERE TS.IsDisplayPeriodTime = 1 AND TS.Id = @rTimeTableSchemaId)
 BEGIN 
set @query = 'SELECT  LectureNumber,' + @cols + ',WeekOffs from 
             (
                Select T.LectureNumber, ISNULL(VBCD.ClassDivisionName + '' - ''+  SM.Code  + ''|''+ ISNULL(TTM.FromTime,0) + ''-''+ ISNULL(TTM.ToTime,0) ,'''') + [sTimetable].[fTimeTableDivisionGet](T.TimeTableSchemaId, T.Id,T.EmployeeId,T.DayId,T.LectureNumber,1) + '' | '' + CASE WHEN ISNULL(TTM.IsBreak,0) = 1 THEN ''Break'' ELSE '''' END AS DivisionTitle,DM.Title AS DayNames
				,TTS.WeekOffs
            from
            sTimetable.tTimeTable T 
            LEFT JOIN sTimetable.tTimeTableDetail TD ON T.Id = TD.TimeTableId 
            INNER JOIN sTimetable.tTimeTableSchema TTS ON TTS.Id = T.TimeTableSchemaId
            INNER JOIN sCommon.tDayMaster DM ON DM.Id = T.DayId
            INNER JOIN sSetup.vClassDivision VBCD ON VBCD.DivisionId=T.DivisionId
	        INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=T.SubjectId
	        LEFT JOIN sSetup.tSubjectMaster TDSM ON TDSM.Id=TD.SubjectId
			LEFT JOIN sTimetable.tTimeTableTime TTM ON TTM.TimeTableSchemaId=T.TimeTableSchemaId AND TTM.DayId = DM.Id AND TTM.DivisionId = VBCD.DivisionId AND TTM.LectureNumber = T.LectureNumber
	         WHERE 
	        ((T.EmployeeId=' + CAST(@rEmployeeId AS NVARCHAR(30))+') OR (TD.EmployeeId=' + CAST(@rEmployeeId AS NVARCHAR(30))+') OR ('+CAST(@rEmployeeId AS NVARCHAR(30))+'= 0))
	         
	         AND ((T.TimeTableSchemaId=' + CAST(@rTimeTableSchemaId AS NVARCHAR(30))+') )
            ) x
            pivot 
            (
                max(DivisionTitle)
                for DayNames in (' + @cols + ')
            ) p order by LectureNumber'
	END 
	ELSE
	BEGIN
set @query = 'SELECT  LectureNumber,' + @cols + ',WeekOffs from 
             (
                Select T.LectureNumber, ISNULL(VBCD.ClassDivisionName + '' - ''+ SM.Code ,'''') + [sTimetable].[fTimeTableDivisionGet](T.TimeTableSchemaId, T.Id,T.EmployeeId,T.DayId,T.LectureNumber,1) + '' | '' + CASE WHEN ISNULL(TTM.IsBreak,0) = 1 THEN ''Break'' ELSE '''' END AS DivisionTitle,DM.Title AS DayNames
				,TTS.WeekOffs
			from
            sTimetable.tTimeTable T 
            LEFT JOIN sTimetable.tTimeTableDetail TD ON T.Id = TD.TimeTableId 
            INNER JOIN sTimetable.tTimeTableSchema TTS ON TTS.Id = T.TimeTableSchemaId AND TTS.IsPublish = 1
            INNER JOIN sCommon.tDayMaster DM ON DM.Id = T.DayId
            INNER JOIN sSetup.vClassDivision VBCD ON VBCD.DivisionId=T.DivisionId
	        INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=T.SubjectId
	        LEFT JOIN sSetup.tSubjectMaster TDSM ON TDSM.Id=TD.SubjectId
	         WHERE 
	        ((T.EmployeeId=' + CAST(@rEmployeeId AS NVARCHAR(30))+') OR (TD.EmployeeId=' + CAST(@rEmployeeId AS NVARCHAR(30))+') OR ('+CAST(@rEmployeeId AS NVARCHAR(30))+'= 0))
	         
	         AND ((T.TimeTableSchemaId=' + CAST(@rTimeTableSchemaId AS NVARCHAR(30))+') )
            ) x
            pivot 
            (
                max(DivisionTitle)
                for DayNames in (' + @cols + ')
            ) p order by LectureNumber'
	END
print @query
 execute(@query)
END
GO
PRINT N'Creating [sAdmission].[pAdmissionCriteriaOptionalSubjectAdd]...';


GO
 
 
CREATE PROCEDURE [sAdmission].[pAdmissionCriteriaOptionalSubjectAdd]
	  
	@rClassId int=0,
	@rBatchId int=0,
	@rStrXml nvarchar(max) = ''
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

SET @rStrXml=REPLACE(@rStrXml,'&','AND')
SET @rStrXml=REPLACE(@rStrXml,'ANDapos;','&apos;')
DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml

BEGIN
	BEGIN TRY
		
		DELETE FROM [sAdmission].[tAdmissionCriteriaOptionalSubject] WHERE ClassId = @rClassId AND BatchId = @rBatchId
	
		INSERT INTO [sAdmission].[tAdmissionCriteriaOptionalSubject]
		(
			ClassId,
			BatchId,
			ClassSubjectId
		)
		SELECT
			@rClassId,@rBatchId,ClassSubjectId
		FROM
			OPENXML (@loDoc, '/Table/OptionalSubject', 1) WITH 
			( 			
			ClassSubjectId int
			)
	SELECT 1 As Result
	END TRY
	BEGIN CATCH 
	SELECT -1 AS Result
	END CATCH	
END
GO
PRINT N'Creating [sAdmission].[pAdmissionOptionalSubjectAdd]...';


GO
 
CREATE PROCEDURE [sAdmission].[pAdmissionOptionalSubjectAdd]
	  
	@rAdmissionFormIdId bigint=0,
	@rStrXml nvarchar(max) 
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

SET @rStrXml=REPLACE(@rStrXml,'&','AND')
SET @rStrXml=REPLACE(@rStrXml,'ANDapos;','&apos;')
DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml

BEGIN
	BEGIN TRY
		
		DELETE FROM sAdmission.tAdmissionOptionalSubject WHERE AdmissionFormId=@rAdmissionFormIdId
	
		INSERT INTO sAdmission.tAdmissionOptionalSubject
		(
			AdmissionFormId,
			ClassSubjectId
		)
		SELECT
			@rAdmissionFormIdId,ClassSubjectId
		FROM
			OPENXML (@loDoc, '/Table/OptionalSubject', 1) WITH 
			( 			
			ClassSubjectId int
			)
	SELECT 1 As Result
	END TRY
	BEGIN CATCH 
	SELECT -1 AS Result
	END CATCH	
END
GO
PRINT N'Creating [sAlert].[pWeeklyAttendanceGet]...';


GO
 

CREATE PROCEDURE [sAlert].[pWeeklyAttendanceGet]
	 	 
	 	 @rBatchId int,
	 	 @rClassId int,
	 	 @rDivisionId int,
	 	 @rOrgId int,
	 	 @rTemplate nvarchar(max),
	 	 @rAttendanceTypeId tinyint,
	 	 @rSubjectId int,
	 	 @rFromDate datetime,
	 	 @rToDate datetime,
	 	 @rMailSubject nvarchar(500)=''
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	Select 
			SC.AcademicId,
			SC.Code,
			SC.Name,
			SC.ParentContactNo AS MobileNo,	
			SC.ParentEmail AS EmailId,
			ISNULL(SC.StudentContactNo,'') AS StudentContactNo,
			ISNULL(SC.StudentEmail,'') AS StudentEmail,
			ISNULL(SC.FatherContactNo,'') AS FatherContactNo,
			ISNULL(SC.FatherMail,'') AS FatherMail,
			ISNULL(SC.MotherContactNo,'') AS MotherContactNo,
			ISNULL(SC.MotherMail,'') AS MotherMail,
			replace (
			replace (
			replace (
			replace (						
			replace (
			replace(@rTemplate,'[Name]',SC.Name),
			'[Class]',SC.ClassName),
			'[Division]',SC.DivisionName),			
			'[TotalCount]',ISNULL(COUNT(MR.AcademicId),0)),
			'[PresentCount]',ISNULL(CASE WHEN MR.IsPresent = 1 THEN COUNT(MR.AcademicId) END,0)),
			'[AbsentCount]',ISNULL(CASE WHEN MR.IsPresent = 0 THEN COUNT(MR.AcademicId) END,0))			
			 AS Template,
			 @rMailSubject AS Subject,
			 2001 AS ReceiverSourceTypeId,
			 SC.AcademicId AS ReceiverSourceId,
			 SC.ClassName AS Class,
			 SC.DivisionName AS Division,			 
			 ISNULL(CASE WHEN MR.IsPresent = 1 THEN COUNT(MR.AcademicId) END,0) AS PresentCount,
			 ISNULL(CASE WHEN MR.IsPresent = 0 THEN COUNT(MR.AcademicId) END,0) AS AbsentCount,
			 ISNULL(COUNT(MR.AcademicId),0) AS TotalCount,			 
			 SC.WhatsAppContactNo
	From 
		sStudent.vStudentCommunication SC
	INNER JOIN sAttendance.tStudentRegister MR ON MR.AcademicId=SC.AcademicId	
			AND ((MR.AttendanceTypeId=@rAttendanceTypeId) OR (@rAttendanceTypeId=0))
			AND ((MR.SubjectId=@rSubjectId) OR (@rSubjectId=0))
			AND ((MR.AttendanceDate >= @rFromDate) OR (@rFromDate=''))
			AND ((MR.AttendanceDate <= @rToDate) OR (@rToDate=''))			
	WHERE
			((SC.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SC.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND (SC.OrgId=@rOrgId)
		AND (SC.BatchId=@rBatchId)
		AND (SC.StatusId=1) AND SC.IsBlockAllAlert=0
		--ORDER BY SC.DivisionOrderIndex,SC.Rollno
		GROUP BY SC.AcademicId,
			SC.Code,
			SC.Name,
			MR.IsPresent,
			SC.ParentContactNo,	
			SC.ParentEmail,
			SC.StudentContactNo,
			SC.StudentEmail,
			SC.FatherContactNo,
			SC.FatherMail,
			SC.MotherContactNo,
			SC.MotherMail,
			SC.ClassName,
			SC.DivisionName,
			SC.WhatsAppContactNo
END
GO
PRINT N'Creating [sAssessment].[pAPICCESubjectActivityExamScoreAdd]...';


GO
 
CREATE PROCEDURE [sAssessment].[pAPICCESubjectActivityExamScoreAdd]
	 	
	@rDetails [nvarchar](max),
	@rCCEExamId int,
	@rSubjectActivityId int,
	@rClassId int,
	@rBatchId int
	 	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

SET @rDetails=REPLACE(@rDetails,'&','AND')
DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rDetails

BEGIN 
	declare @lDataSetID int,@lCount int,@MinimumScore decimal(5,2),@GradeTitle nvarchar(10),@lCountTemp int,
			@lAcademicId Bigint,@lSubjectActivityId int,@lExamId int,@lMark decimal(10,2)
	 SELECT @lDataSetID=GradeSetId FROM sAssessment.tCCESubjectActivityMaster WHERE  Id=	@rSubjectActivityId	
	 
		if exists(select 1 from sAssessment.tCCESubjectActivityExamScore AI
			INNER JOIN OPENXML (@loDoc, '/Table/SubjectActivityScoreBulk', 1)
				WITH ( 				
							AcademicId Bigint,
							SubjectActivityId int, 
							ExamId int
					 )
					 A 	ON AI.AcademicId = A.AcademicId AND AI.ExamId=@rCCEExamId
			AND AI.SubjectActivityId =@rSubjectActivityId )
	 BEGIN	
		UPDATE AI SET AI.Marks = Mark FROM sAssessment.tCCESubjectActivityExamScore AI
			INNER JOIN OPENXML (@loDoc, '/Table/SubjectActivityScoreBulk', 1)
				WITH ( 				
							AcademicId Bigint,
							SubjectActivityId int,--CCECSId int,
							ExamId int,
							Mark decimal(10,2)			
					  ) A 	ON AI.AcademicId = A.AcademicId AND AI.ExamId=@rCCEExamId
			AND AI.SubjectActivityId = @rSubjectActivityId
			 --AND A.CCECSId = AI.CCECSId 
			
			
			
			 
		END
	else
	BEGIN	
		INSERT INTO sAssessment.tCCESubjectActivityExamScore
			(ExamId,AcademicId,SubjectActivityId,Marks)
			
			SELECT	@rCCEExamId,AcademicId,@rSubjectActivityId,Mark
         			
			FROM OPENXML (@loDoc, '/Table/SubjectActivityScoreBulk', 1)
			WITH ( 				
					AcademicId Bigint,					
					Mark decimal(10,2)--CCECSId int
				  ) A 	
			 --A.AcademicId NOT IN (Select AcademicId From sAssessment.tCCESubjectActivityExamScore Where AcademicId =A.AcademicId AND A.ExamId = ExamId AND SubjectActivityId=AM.Id)
	     SELECT 1 AS Result
	     
	END 
 
 CREATE TABLE #tempGradeSetDetail
	(
		Id INT IDENTITY (1, 1),
		MinimumScore decimal(5,2),
		GradeTitle nvarchar(20),
		GradePoint decimal(6,2) 					 
	) 
	INSERT INTO #tempGradeSetDetail
	SELECT MinimumScore,GradeCode,GradePoint		
	FROM sAssessment.tGradeSetDetail where GradesetId=@lDataSetID
	order by MinimumScore DESC
	
	Select @lCount= count(id) from #tempGradeSetDetail
	while (@lCount>0)
	BEGIN
	 Select @MinimumScore =MinimumScore,@GradeTitle=GradeTitle from #tempGradeSetDetail Where Id=@lCount
	 UPDATE AI SET AI.Grade = @GradeTitle FROM sAssessment.tCCESubjectActivityExamScore AI
			INNER JOIN OPENXML (@loDoc, '/Table/SubjectActivityScoreBulk', 1)
				WITH ( 				
							AcademicId Bigint,
							SubjectActivityId int,--CCECSId int,
							ExamId int,
							Mark decimal(10,2)			
					  ) A 	ON AI.AcademicId = A.AcademicId AND AI.ExamId=@rCCEExamId
			AND AI.SubjectActivityId = @rSubjectActivityId
			AND A.Mark >=@MinimumScore 
			
		 Set @lCount=@lCount-1	  			
		END
		
END
GO
PRINT N'Creating [sAssessment].[pAPICSExamGradeAdd]...';


GO


CREATE PROCEDURE [sAssessment].[pAPICSExamGradeAdd]
	 	
	@rStrXml [nvarchar](max)
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

SET @rStrXml=REPLACE(@rStrXml,'&','AND')
DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml

BEGIN
	BEGIN TRY
	 BEGIN	
		UPDATE AI 
		SET AI.Grade = Term1Grade,
		AI.GradeIndicator = GradeTitle   
		FROM sAssessment.tCCECSExamScore AI
		INNER JOIN OPENXML (@loDoc, '/Table/CSExamGrade', 1)
			WITH ( 				
						AcademicId bigint,
						CCECSId int,
						ExamId int,
						Term1Grade nvarchar(20),
						GradeTitle nvarchar(50)
									
				  ) A 	ON AI.AcademicId = A.AcademicId AND AI.ExamId=A.ExamId
		AND A.CCECSId = AI.CCECSId 
		
		INSERT INTO sAssessment.tCCECSExamScore
			(ExamId,AcademicId,CCECSId,Grade,GradeIndicator)
			
			SELECT	
			A.ExamId,A.AcademicId,A.CCECSId,Term1Grade,GradeTitle
         			
			FROM OPENXML (@loDoc, '/Table/CSExamGrade', 1)
			WITH ( 				
					ExamId int,
					AcademicId bigint,					
					Term1Grade nvarchar(20),
					GradeTitle nvarchar(50),
					CCECSId int
				  ) A  LEFT JOIN sAssessment.tCCECSExamScore AI ON AI.AcademicId = A.AcademicId AND AI.ExamId=A.ExamId  AND A.CCECSId = AI.CCECSId 
			       WHERE (AI.AcademicId IS NULL AND AI.ExamId IS NULL AND AI.CCECSId IS NULL)
	
 	 SELECT 1 AS Result
	END		
	END TRY
	
	BEGIN CATCH 
	
		
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Creating [sAssessment].[pAPICSExamGradeGet]...';


GO
CREATE PROCEDURE [sAssessment].[pAPICSExamGradeGet]
	  @rClassId bigint,
	  @rDivisionId Bigint,
	  @rExamId int,
	  @rOrgId int,
	  @rCCECSGroupId int,
	  @rBatchId int,
	  @rCCECSId int=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 	

SELECT 
	SA.AcademicId,
	SA.RollNo,
	SA.Code As Number,
	SA.Name,  
	AM.Title, 
	ISNULL(AIS.Grade,'') AS CoScholasticActivityGrade,
	GSD.Id AS GradeId
FROM sStudent.vStudentAcademic SA
	INNER JOIN sAssessment.tCCECSClass CA ON CA.ClassId = SA.ClassId AND SA.StatusId = 1 AND CA.CCECSGroupId = @rCCECSGroupId AND CA.BatchID = @rBatchID
	INNER JOIN sAssessment.tCCECSMaster AM ON CA.CCECSGroupId=AM.CCECAGroupId
	INNER JOIN sAssessment.tCCECSForClass CL ON CL.CCECSID= AM.Id AND CL.ClassID = @rClassId  AND CL.BatchId=@rBatchId
	LEFT JOIN sAssessment.tCCECSExamScore AIS ON AIS.AcademicId =SA.AcademicId AND AIS.CCECSId= AM.Id AND AIS.ExamId= @rExamId
	INNER JOIN sAssessment.vCCECSGROUPMASTER GM ON GM.Id = CA.CCECSGroupId AND GM.ClassId = CA.ClassId AND GM.BatchId = CA.BatchID
	LEFT JOIN sAssessment.tGradeSetDetail GSD ON GSD.GradeSetId = GM.GradeSetId AND GSD.GradeCode = AIS.Grade
WHERE 
	SA.ClassId= @rClassId
	And SA.DivisionId = @rDivisionId
	And SA.BatchId = @rBatchId 
	And AM.CCECAGroupId= @rCCECSGroupId
	AND ((AM.Id = @rCCECSId  OR @rCCECSId = 0))

END
GO
PRINT N'Creating [sAssessment].[pAPICSEXamIndicatorAdd]...';


GO


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

DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml
BEGIN
	BEGIN TRY
	 BEGIN	
	 DECLARE @lNextNumber BIGINT 
	 DECLARE @lCount INT

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


GO
CREATE PROCEDURE [sAssessment].[pAPICSExamIndicatorGet]
	  @rClassId bigint,
	  @rDivisionId Bigint,
	  @rExamId int,
	  @rOrgId int,
	  @rCCECSGroupId int,
	  @rBatchId int,
	  @rCCECSId int=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 	
SELECT 
	SA.AcademicId,
	SA.RollNo,
	SA.Code As Number,
	SA.Name,
	AM.Title,	 
	ISNULL(AIS.IndicatorIds,'') AS CoScholasticActivityIndicator
FROM sStudent.vStudentAcademic SA
INNER JOIN sAssessment.tCCECSClass CA ON CA.ClassId = SA.ClassId AND SA.StatusId = 1 AND CA.BatchID = @rBatchID
INNER JOIN sAssessment.tCCECSMaster AM ON CA.CCECSGroupId=AM.CCECAGroupId
INNER JOIN sAssessment.tCCECSForClass CL ON CL.CCECSID= AM.Id AND CL.ClassID = @rClassId ANd CL.BatchId = @rBatchID
LEFT JOIN sAssessment.tCCECSExamScore AIS ON AIS.AcademicId =SA.AcademicId AND AIS.CCECSId= AM.Id AND AIS.ExamId= @rExamId AND (AIS.CCECSId = @rCCECSId OR @rCCECSId = 0 ) 
WHERE SA.ClassId = @rClassId
And SA.DivisionId = @rDivisionId	
And SA.BatchId = @rBatchId	
And AM.CCECAGroupId= @rCCECSGroupId
AND ((AM.Id = @rCCECSId) OR(@rCCECSId = 0))

END
GO
PRINT N'Creating [sAssessment].[pAPICSExamMarkEntryGet]...';


GO
CREATE PROCEDURE [sAssessment].[pAPICSExamMarkEntryGet]
	  @rClassId bigint,
	  @rDivisionId Bigint,
	  @rExamId int,
	  @rOrgId int,
	  @rCCECSGroupId int,
	  @rBatchId int,
	  @rCCECSId int=0
	  --@rFilter int=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 

SELECT 
	SA.RollNo,
	SA.Code As Number,
	SA.Name,
	AM.Title, 
	ISNULL(AIS.ObtianMark,0) AS CoScholasticActivityMark,
	SA.AcademicId
	FROM sStudent.vStudentAcademic SA
	INNER JOIN sAssessment.tCCECSClass CA ON CA.ClassId = SA.ClassId AND SA.StatusId = 1 AND CA.BatchID=@rBatchId
	INNER JOIN sAssessment.tCCECSMaster AM ON CA.CCECSGroupId=AM.CCECAGroupId
	INNER JOIN sAssessment.tCCECSForClass CL ON CL.CCECSID= AM.Id AND CL.ClassID=@rClassId AND CL.BatchId=@rBatchId
	LEFT JOIN sAssessment.tCCECSExamScore AIS ON AIS.AcademicId =SA.AcademicId AND AIS.CCECSId= AM.Id AND AIS.ExamId= @rExamId  AND (AIS.CCECSId = @rCCECSId   OR @rCCECSId = 0 ) 
	WHERE SA.ClassId=@rClassId
	AND SA.DivisionId = @rDivisionId
	AND SA.BatchId = @rBatchId
	AND AM.CCECAGroupId= @rCCECSGroupId
	AND ((AM.Id = @rCCECSId  OR @rCCECSId = 0))
	
--EXECUTE(@query)

END
GO
PRINT N'Creating [sAssessment].[pAPICSExamScoreSetupAdd]...';


GO


CREATE PROCEDURE [sAssessment].[pAPICSExamScoreSetupAdd]
	 	
	@rStrXml [nvarchar](max)
	--@rOrgId int

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

SET @rStrXml=REPLACE(@rStrXml,'&','AND')
DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml

BEGIN
	BEGIN TRY
	 BEGIN	
	 
	
		UPDATE AI 
		SET AI.ObtianMark = A.TotalMarks 
			--AI.GradeIndicator = GradeTitle   
		FROM sAssessment.tCCECSExamScore AI
		INNER JOIN OPENXML (@loDoc, '/Table/CSExamGrade', 1)
			WITH ( 				
						AcademicId bigint,
						CCECSId int,
						ExamId int,
						TotalMarks decimal(12,2) 
						 
						--GradeTitle nvarchar(50)
									
				  ) A 	ON AI.AcademicId = A.AcademicId AND AI.ExamId=A.ExamId
		AND A.CCECSId = AI.CCECSId 
	
		INSERT INTO sAssessment.tCCECSExamScore
			(ExamId,AcademicId,CCECSId,ObtianMark )
			
			SELECT	
			A.ExamId,A.AcademicId,A.CCECSId,A.TotalMarks 
         			
			FROM OPENXML (@loDoc, '/Table/CSExamGrade', 1)
			WITH ( 				
					ExamId int,
					AcademicId bigint,	
					CCECSId int,				
					TotalMarks decimal(12,2) 
					 
					--GradeTitle nvarchar(50),
					
				  ) A  LEFT JOIN sAssessment.tCCECSExamScore AI ON AI.AcademicId = A.AcademicId AND AI.ExamId=A.ExamId  AND A.CCECSId = AI.CCECSId 
			       WHERE (AI.AcademicId IS NULL AND AI.ExamId IS NULL AND AI.CCECSId IS NULL)
		
 	 SELECT 1 AS Result
	END		
	END TRY
	
	BEGIN CATCH 
	
		
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Creating [sAssessment].[pAPISubjectActivityExamIndicatorAdd]...';


GO


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

DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml
BEGIN
	 BEGIN TRY
	 BEGIN	
	 DECLARE @lNextNumber BIGINT 
	 DECLARE @lCount INT

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


GO
CREATE PROCEDURE [sAssessment].[pAPISubjectActivityExamIndicatorGet]
	  @rClassId bigint,
	  @rDivisionId Bigint,
	  @rExamId int,
	  @rOrgId int,
	  @rSubjectActivityId int,  --@rCCECSGroupId int,
	  @rBatchId int=0,
	  @rSubActivityId int=0 --@rCCECSId int=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 	

SELECT 
	SA.AcademicId,
	SA.RollNo,
	SA.Code AS Number,
	SA.Name,
	SSA.Title,	 
	ISNULL(SEC.IndicatorIds,'') AS ActivityIndicator
FROM  
	sAssessment.tCCESubjectActivityMaster SAM 	
	INNER JOIN sAssessment.tCCESubjectSubActivityMaster SSA ON SAM.Id=SSA.SubjectActivityId  
	INNER JOIN sAssessment.vCCEExamClassSubject CS ON CS.ClassSubjectId=SAM.ClassSubjectId
	INNER JOIN sSetup.tClassMaster CMM ON CMM.Id=CS.ClassId
	INNER JOIN sStudent.vStudentAcademic SA ON   SA.ClassId = CMM.Id AND SA.StatusId=1
	LEFT JOIN sAssessment.tCCESubjectSubActivityExamScore SEC  ON SEC.SubjectSubActivityId=SSA.Id AND SEC.AcademicId=SA.AcademicId AND SEC.ExamId= @rExamId AND (SEC.SubjectSubActivityId = @rSubActivityId  OR @rSubActivityId = 0 )
	LEFT JOIN sAssessment.tOptionalSubject o on o.AcademicId=SA.AcademicID and o.ClassSubjectId=CS.ClassSubjectId  
	AND SEC.ExamId= @rExamId
WHERE  
	SSA.OrgId= @rOrgId 
	AND SAM.ClassSubjectId= @rClassId
	AND SSA.SubjectActivityId= @rSubjectActivityId
	AND SA.DivisionId= @rDivisionId
	And SA.BatchId = @rBatchId
	AND ((CS.IsOptional = 1 AND  isnull(o.AcademicId,0)<>0) OR (CS.IsOptional = 0))
	AND SSA.Id = @rSubActivityId

END
GO
PRINT N'Creating [sAssessment].[pAPISubjectActivityMarkEntryBulkAdd]...';


GO


CREATE PROCEDURE [sAssessment].[pAPISubjectActivityMarkEntryBulkAdd]
	 	
	@rStrXml [nvarchar](max),
	@rOrgId int	
	 	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

SET @rStrXml=REPLACE(@rStrXml,'&','AND')
DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml

BEGIN 
	 BEGIN	
		UPDATE AI SET AI.Marks = Mark FROM sAssessment.tCCESubjectSubActivityExamScore AI
			INNER JOIN OPENXML (@loDoc, '/Table/SubjectActivityScoreBulk', 1)
				WITH ( 				
							AcademicId Bigint,
							SubjectSubActivityId int,--CCECSId int,
							ExamId int,
							Mark decimal(10,2)			
					  ) A 	ON AI.AcademicId = A.AcademicId AND AI.ExamId=A.ExamId
			AND A.SubjectSubActivityId = AI.SubjectSubActivityId--AND A.CCECSId = AI.CCECSId 
			INNER JOIN sSetup.tOrganizationMaster OM ON  OM.Id = @rORGId	
			  			
		
	
	BEGIN	
		INSERT INTO sAssessment.tCCESubjectSubActivityExamScore
			(ExamId,AcademicId,SubjectSubActivityId,Marks)
			
			SELECT	ExamId,AcademicId,AM.Id,Mark
         			
			FROM OPENXML (@loDoc, '/Table/SubjectActivityScoreBulk', 1)
			WITH ( 				
					ExamId int,
					AcademicId Bigint,					
					
					SubjectSubActivityId int,
					Mark decimal(10,2)--CCECSId int
				  ) A 	
			INNER JOIN sAssessment.tCCESubjectSubActivityMaster AM ON AM.Id = A.SubjectSubActivityId 			
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = AM.OrgId AND OM.Id = @rORGId
			AND A.AcademicId NOT IN (Select AcademicId From sAssessment.tCCESubjectSubActivityExamScore Where AcademicId =A.AcademicId AND A.ExamId = ExamId AND SubjectSubActivityId=AM.Id)
	     SELECT 1 AS Result
	END
	
	 
	 
    END	
	 
		
END
GO
PRINT N'Creating [sAssessment].[pAPISubjectActivityMarkGet]...';


GO
CREATE PROCEDURE [sAssessment].[pAPISubjectActivityMarkGet]
	  @rClassId bigint,
	  @rDivisionID Bigint,
	  @rExamId int,
	  @rOrgId int,
	  @rSubjectActivityId int,  --@rCCECSGroupId int,
	  @rBatchId int=0,
	  @rSubActivityId int=0, --@rCCECSId int=0,
	  @rSubjectId int=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 	

SELECT 
	SA.AcademicId,
	SA.RollNo,
	SA.Code AS Number,
	SA.Name,
	SSA.Title,	 
	ISNULL(SEC.Marks,'0') AS ActivityMark
FROM  
	sAssessment.tCCESubjectActivityMaster SAM 	
	INNER JOIN sAssessment.tCCESubjectSubActivityMaster SSA ON SAM.Id=SSA.SubjectActivityId  
	INNER JOIN sAssessment.vCCEExamClassSubject CS ON CS.ClassSubjectId=SAM.ClassSubjectId
	INNER JOIN sSetup.tClassMaster CMM ON CMM.Id=CS.ClassId
	INNER JOIN sStudent.vStudentAcademic SA ON   SA.ClassId = CMM.Id 
	LEFT JOIN sAssessment.tCCESubjectSubActivityExamScore SEC  ON SEC.SubjectSubActivityId=SSA.Id AND SEC.AcademicId=SA.AcademicId AND SEC.ExamId= @rExamId
	LEFT JOIN sAssessment.tOptionalSubject o on o.AcademicId=SA.AcademicId and o.ClassSubjectId=CS.ClassSubjectId
WHERE  
	SSA.OrgId= @rOrgId
	AND SSA.SubjectActivityId= @rSubjectActivityId
	AND SAM.ClassSubjectId= @rClassId
	AND SA.DivisionId= @rDivisionID
	And SA.BatchId = @rBatchId
	ANd CS.ClassSubjectId = @rSubjectId
	AND ((CS.IsOptional = 1 AND    isnull(o.AcademicId,0) <> 0) OR (CS.IsOptional = 0))
	AND SA.StatusId=1
	AND SSA.Id = @rSubActivityId

END
GO
PRINT N'Creating [sAssessment].[pAPISubjectActivityScoreBulkAdd]...';


GO


CREATE PROCEDURE [sAssessment].[pAPISubjectActivityScoreBulkAdd]
	 	
	@rStrXml [nvarchar](max)
	 	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

SET @rStrXml=REPLACE(@rStrXml,'&','AND')
DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml

BEGIN 
	 BEGIN	
		UPDATE AI 
		SET AI.Grade = Term1Grade,
		AI.GradeIndicator = GradeTitle   
		FROM sAssessment.tCCESubjectSubActivityExamScore AI
		INNER JOIN OPENXML (@loDoc, '/Table/SubjectActivityScoreBulk', 1)
			WITH ( 				
						AcademicId bigint,
						SubjectSubActivityId int,
						ExamId int,
						Term1Grade nvarchar(20),
						GradeTitle nvarchar(50)
									
				  ) A 	ON AI.AcademicId = A.AcademicId AND AI.ExamId=A.ExamId
		AND A.SubjectSubActivityId = AI.SubjectSubActivityId 
		
		INSERT INTO  sAssessment.tCCESubjectSubActivityExamScore
			(ExamId,AcademicId,SubjectSubActivityId,Grade,GradeIndicator)
			
			SELECT	
			A.ExamId,A.AcademicId,A.SubjectSubActivityId,Term1Grade,GradeTitle
         			
			FROM OPENXML (@loDoc, '/Table/SubjectActivityScoreBulk', 1)
			WITH ( 				
					ExamId int,
					AcademicId bigint,					
					Term1Grade nvarchar(20),
					GradeTitle nvarchar(50),
					SubjectSubActivityId int
				  ) A  LEFT JOIN sAssessment.tCCESubjectSubActivityExamScore AI ON AI.AcademicId = A.AcademicId AND AI.ExamId=A.ExamId  AND A.SubjectSubActivityId = AI.SubjectSubActivityId 
			       WHERE (AI.AcademicId IS NULL AND AI.ExamId IS NULL AND AI.SubjectSubActivityId IS NULL)
	
 	 SELECT 1 AS Result
	END		
	 
		
END
GO
PRINT N'Creating [sAssessment].[pAPISubjectActivityScoreBulkGet]...';


GO
CREATE PROCEDURE [sAssessment].[pAPISubjectActivityScoreBulkGet]
	  @rClassId bigint,
	  @rDivisionID Bigint,
	  @rExamId int,
	  @rOrgId int,
	  @rSubjectActivityId int,  --@rCCECSGroupId int,
	  @rBatchId int=0,
	  @rSubActivityId int=0 --@rCCECSId int=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 	

SELECT 
	SA.AcademicId,
	SA.RollNo,
	SA.Code AS Number,
	SA.Name,
	SSA.Title, 
	ISNULL(SEC.Grade,'') AS ActivityGrade,
	GSD.Id AS GradeId
FROM  
	sAssessment.tCCESubjectActivityMaster SAM 	
	INNER JOIN sAssessment.tCCESubjectSubActivityMaster SSA ON SAM.Id=SSA.SubjectActivityId  
	INNER JOIN sAssessment.vCCEExamClassSubject CS ON CS.ClassSubjectId=SAM.ClassSubjectId
	INNER JOIN sSetup.tClassMaster CMM ON CMM.Id=CS.ClassId
	INNER JOIN sStudent.vStudentAcademic SA ON   SA.ClassId = CMM.Id 
	LEFT JOIN sAssessment.tCCESubjectSubActivityExamScore SEC  ON SEC.SubjectSubActivityId=SSA.Id AND SEC.AcademicId=SA.AcademicId AND SEC.ExamId= @rExamId  AND (SEC.SubjectSubActivityId = @rSubActivityId  OR @rSubActivityId = 0 )
	LEFT JOIN sAssessment.tOptionalSubject o on o.AcademicId=SA.AcademicID and o.ClassSubjectId=CS.ClassSubjectId  
	AND SEC.ExamId = @rExamId 
    LEFT JOIN sAssessment.tGradeSetDetail GSD ON SAM.GradeSetId = GSD.GradeSetId AND GSD.GradeCode = SEC.Grade
WHERE  
	SSA.OrgId= @rOrgId
	AND SAM.ClassSubjectId= @rClassId
	AND SSA.SubjectActivityId= @rSubjectActivityId
	AND SA.DivisionId= @rDivisionID
	And SA.BatchId = @rBatchId
	AND SA.StatusID=1
	AND SSA.Id = @rSubActivityId
END
GO
PRINT N'Creating [sFee].[pRptStudentOptionalFeeListGet]...';


GO
CREATE PROCEDURE [sFee].[pRptStudentOptionalFeeListGet]	 
		@rClassId int = 0,
		@rDivisionId int = 0,
		@rAdmissionCategoryId int = 0,		
		@rBatchId int = 0,
		@rOrgId int = 0,
		@rReceiptBookId int = 0,
		@rDepartmentId int = 0,
		@rOrgGroupBatchId int = 0,
		@rCommonBatch int = 0,
		@rFeeId nvarchar(max) = '',
		@rFromRollNo int = 0,
		@rToRollNo int = 0,
		@rFilterId int = 0,
		@rOrgGroupId int = 0,
		@rCode nvarchar(20) = '',
		@rReportId int = 0,
		@rIsDisplayOrgGroup bit = 0,
		@rIsFilter bit = 0,  
		@rBuilder1 nvarchar(max) = '',  
		@rBuilder2 nvarchar(max) = ''

		WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 		
	SELECT 
			@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
			@rIsFilter AS IsFilter,
			@rBuilder1 AS Builder1,  
			@rBuilder2 AS Builder2,  
			SA.AcademicId,
			SA.Code,
			SA.Name,
			SA.RollNo,
			SA.ClassName,
			SA.DivisionName,
			ISNULL(FO.FeeSetupId,0) AS FeeSetupId,			
			ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
			ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo,
			FM.Id AS FeeId,
			FM.Title AS FeeName
	FROM 
		sFee.tFeeOptional FO
		INNER JOIN sStudent.vStudentAcademic SA ON FO.SourceId=SA.AcademicId
		INNER JOIN sFee.tFeeSetup FS ON FS.Id = FO.FeeSetupId AND FO.SourceTypeId=2001
		INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id = FS.ReceiptBookId
		INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = FO.BatchId AND SA.BatchId = BM.Id
		INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id = BM.OrgGroupBatchId
		LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId	
		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) AND (SA.OrgGroupBatchId = AR.OrgGroupBatchId))   
		LEFT JOIN  
		(SELECT AT.SourceId,B.OrgGroupBatchId 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))    
			AND (SA.OrgGroupBatchId = RT.OrgGroupBatchId)
	WHERE 
		(RBM.OrgGroupId = @rOrgGroupId)
		AND	((SA.OrgId=@rOrgId) OR (@rOrgId = 0))		
		AND ((BM.Id=@rBatchId) OR (@rBatchId = 0))
		AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((SA.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))		
		AND ((FS.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))	
		AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))	
		AND ((OGBM.Id = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))
		AND ((OGBM.CommonOrgGroupBatchId = @rCommonBatch) OR (@rCommonBatch = 0))
		AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo = 0))
		AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo = 0))		
		AND (ISNULL(FS.FeeId,0) IN (SELECT cast(item as int) FROM sCommon.fnsplit(@rFeeId,',')) OR @rFeeId='')
		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.Code = @rCode) OR (@rCode = ''))
		ORDER BY SA.AcademicId
END
GO
PRINT N'Creating [sHostel].[pRptHostelAttendanceSheetGet]...';


GO

CREATE PROCEDURE [sHostel].[pRptHostelAttendanceSheetGet]
	 
	 @rOrgId int,
	 @rHostelId int,
	 @rRoomId int,
	 @rStudentCode nvarchar(20)='',
	 @rStudentName nvarchar(100)='',
	 @rClassId int,
	 @rDivisionId int,
	 @rOrgGroupBatchId int=0
	 	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON 
BEGIN 		
	SELECT
		SD.StudentId,			
		SD.AcademicId,
		SD.Code AS StudentCode,
		SD.Name AS StudentName,
		SD.ClassName + ' - ' + SD.DivisionName AS Class
	FROM 
		sHostel.tAssignRoom AR 
		INNER JOIN sStudent.vStudentAcademic SD ON SD.StudentId = AR.SourceId AND AR.SourceTypeId = 2003
		INNER JOIN sHostel.tRoomMaster RM ON AR.RoomId = RM.Id 
		INNER JOIN sHostel.tHostelMaster HM ON HM.Id = RM.HostelId
		INNER JOIN sSetup.tOrganizationMaster O ON O.Id = SD.OrgId
		INNER JOIN  sHostel.tHostelAdmission HA On HA.SourceId=AR.SourceId AND AR.SourceTypeId = 2003 AND HA.OrgGroupBatchId=@rOrgGroupBatchId
	WHERE
		AR.SourceTypeId = 2003
		AND ((SD.OrgId = @rOrgId) OR (ISNULL(@rOrgId,0) = 0))
		AND ((HM.Id = @rHostelId) OR (ISNULL(@rHostelId,0) = 0))
		AND ((RM.Id = @rRoomId) OR (ISNULL(@rRoomId,0) = 0))
		AND ((SD.ClassId = @rClassId) OR (ISNULL(@rClassId,0) = 0))
		AND ((SD.DivisionId = @rDivisionId) OR (ISNULL(@rDivisionId,0) = 0))
		AND ((SD.Code = @rStudentCode) OR (ISNULL(@rStudentCode,'') = ''))
		AND ((SD.FirstName like @rStudentName + '%') OR (ISNULL(@rStudentName,'') = ''))
END
GO
PRINT N'Creating [sHrm].[pDigitalFormChangeListGet]...';


GO
 
 
CREATE PROCEDURE [sHrm].[pDigitalFormChangeListGet]

	  @rId int=0,
	  @rOrgId smallint=0,
	  @rEmployeeCode nvarchar(100),
	  @rDepartmentId bigint=0
	
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	 
		SELECT 
			(SELECT MAX(AutoId) FROM sHrm.tDigitalFormEmployee WHERE DigitalFormId = DF.Id AND EmployeeId = DFS.EmployeeId) as Id,
			DF.Id as DigitalFormId,
			DF.Code,
			DF.Title,
			ECD.EmployeeId,
			ECD.Code as EmployeeCode,
			ECD.EmployeeName AS Name,
			ECD.DepartmentName AS DepartmentName
		FROM 
			sHrm.tDigitalForm DF
			INNER JOIN (SELECT DigitalFormId,EmployeeId FROM sHrm.tDigitalFormEmployee GROUP By EmployeeId,DigitalFormId) DFS ON DFS.DigitalFormId = DF.Id
			INNER JOIN sHrm.vEmployeeCommonDetail ECD ON ECD.EmployeeId = DFS.EmployeeId
		WHERE 
			((DF.OrgId = @rOrgId)OR (@rOrgId=0))
			AND ((DF.Id = @rId) OR (@rId = 0))		
			AND ((ECD.Code = @rEmployeeCode) OR (@rEmployeeCode=0))
			AND ((ECD.DepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))
			AND ((ECD.OrgId = @rOrgId) OR (@rOrgId = 0))
	   ORDER BY Id Asc
END
GO
PRINT N'Creating [sHrm].[pDigitalFormChangeRequestAdd]...';


GO
 
 
CREATE  PROCEDURE [sHrm].[pDigitalFormChangeRequestAdd]
			@rEmployeeId 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 sHrm.tDigitalFormEmployee WHERE DigitalFormId = @rDigitalFormId AND EmployeeId = @rEmployeeId AND FieldTypeId = @rFieldTypeId AND UpdateFieldId = @rUpdateFieldId)
			BEGIN
			INSERT INTO sHrm.tDigitalFormEmployee
				(
				DigitalFormId,
				EmployeeId,
				FieldTypeId,
				UpdateFieldId,
				NewValue,
				OldValueImage,
				NewValueImage,
				StatusId,
				Remark,
				CreatedUserId,
				CreatedDateTime
				)
			Values
				(
				@rDigitalFormId,
				@rEmployeeId,
				@rFieldTypeId,
				@rUpdateFieldId,
				@rNewValue,
				@rOldValueImage,
				@rNewValueImage,
				@rStatusId,
				@rRemark,
				@rCreatedUserId,
				sCommon.fGetDate()
				)

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

			
			END
			ELSE
			BEGIN
			UPDATE 
				sHrm.tDigitalFormEmployee
			SET
				NewValue = @rNewValue
				,Remark = @rRemark
				,CreatedUserId = @rCreatedUserId
				,CreatedDateTime = sCommon.fGetDate()
				,StatusId = @rStatusId
			WHERE
				DigitalFormId = @rDigitalFormId 
				AND EmployeeId = @rEmployeeId 
				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'Creating [sHrm].[pDigitalFormCustomFieldApprove]...';


GO
 
CREATE PROCEDURE [sHrm].[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 sHrm.vEmployeeCommonDetail WHERE EmployeeId = @rId)
	BEGIN
		 DECLARE @lEmployeeId BigInt
		 SET @lEmployeeId = (SELECT EmployeeId FROM sHrm.vEmployeeCommonDetail WHERE EmployeeId = @rId)

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

		IF(@rStatusId = 550)
			BEGIN
			CREATE TABLE ListofEmpData(Id bigint,EmployeeId bigint,SubCategory nvarchar(150),CustomFieldId int,UpdatedUserId bigint,IsExist bit);
			insert into ListofEmpData VALUES (@rId,@lEmployeeId,@rNewValue,@rCustomFieldId,@rActionUserId,0)
	 --SELECT * FROM ListofEmpData
		UPDATE LD SET IsExist=1 
		   FROM sHrm.tEmployeeCustomFieldData SC
		      LEFT JOIN ListofEmpData LD ON SC.EmployeeId=LD.EmployeeId 
		      AND  EXISTS (SELECT EmployeeCustomFieldId FROM sHrm.tEmployeeCustomFieldData WHERE EmployeeId=LD.EmployeeId AND EmployeeCustomFieldId = LD.CustomFieldId) 
		
		
		set @sql='INSERT INTO sHrm.tEmployeeCustomFieldData
					(EmployeeId,EmployeeCustomFieldId,FieldData,CreatedUserId,CreatedDateTime)
					SELECT
						LD.EmployeeId,ISNULL('+@rCustomFieldId+',0),LD.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
					FROM
						ListofEmpData LD WHERE LD.IsExist=0'
			
		Exec sp_executesql @sql
		set @sql='UPDATE sHrm.tEmployeeCustomFieldData set FieldData = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sHrm.tEmployeeCustomFieldData SC 
					INNER JOIN ListofEmpData LD ON SC.EmployeeId=LD.EmployeeId AND SC.EmployeeCustomFieldId=LD.CustomFieldId AND IsExist=1'
		print @sql
		Exec sp_executesql @sql
	
		Drop Table ListofEmpData
			 SET @lResult = 1;
	      IF(@lResult = 1)
			BEGIN
				UPDATE sHrm.tDigitalFormEmployee
				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 ListofEmpData(Id bigint,EmployeeId bigint,SubCategory nvarchar(150),CustomFieldId int,UpdatedUserId bigint,IsExist bit);
			insert into ListofEmpData VALUES (@rId,@lEmployeeId,@rOldValue,@rCustomFieldId,@rActionUserId,0)
	 
		UPDATE LD SET IsExist=1 
		   FROM sHrm.tSEmployeeCustomFieldData SC
		      LEFT JOIN ListofEmpData LD ON SC.EmployeeId=LD.EmployeeId 
		      AND  EXISTS (SELECT EmployeeCustomFieldId FROM sHrm.tEmployeeCustomFieldData WHERE EmployeeId=LD.EmployeeId AND EmployeeCustomFieldId = LD.CustomFieldId) 
		
		
		set @sql='INSERT INTO sHrm.tEmployeeCustomFieldData
					(EmployeeId,EmployeeCustomFieldId,FieldData,CreatedUserId,CreatedDateTime)
					SELECT
						LD.EmployeeId,ISNULL('+@rCustomFieldId+',0),LD.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
					FROM
						ListofEmpData LD WHERE LD.IsExist=0'
			
		Exec sp_executesql @sql
		set @sql='UPDATE sHrm.tEmployeeCustomFieldData set FieldData = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sHrm.tEmployeeCustomFieldData SC 
					INNER JOIN ListofEmpData LD ON SC.EmployeeId=LD.EmployeeId AND SC.EmployeeCustomFieldId=LD.CustomFieldId AND IsExist=1'
		print @sql
		Exec sp_executesql @sql
	
		Drop Table ListofEmpData
			 SET @lResult = 1;
	      IF(@lResult = 1)
			BEGIN
				UPDATE sHrm.tDigitalFormEmployee
				SET
					StatusId = @rStatusId
					,ActionRemark = @rActionRemark
					,ActionUserId = @rActionUserId
					,ActionDateTime = @rActionDateTime
				WHERE 
					AutoId = @rRequestId
			END
			SELECT 2 AS Result
		END
	END
	END
GO
PRINT N'Creating [sHrm].[pDigitalFormEmployeeCustomFieldsDataGet]...';


GO
 
CREATE PROCEDURE [sHrm].[pDigitalFormEmployeeCustomFieldsDataGet]
	 		
	 @rEmployeeId bigint,	 
	 @rSubCategoryId int
	 
AS
SET NOCOUNT ON

BEGIN
		DECLARE @lDataTypeId nvarchar(1)
		SELECT @lDataTypeId=FieldTypeId FROM sHrm.tEmployeeCustomFieldMaster WHERE Id=@rSubCategoryId
		
		 Declare @Sql nvarchar(max)
		 Declare @Sql1 nvarchar(max)
		 
		 --IF(@lDataTypeId=3)   --For Free Text and Numeric
		 --BEGIN
		 
		     SET @Sql = 'select *from (Select Row_Number() OVER (PARTITION BY ECD.EmployeeId ORDER BY CASE WHEN ECF.FieldTypeId IS NOT NULL THEN ECF.FieldTypeId END Desc) as RowNumber, ECD.EmployeeId,ECD.Code,ECD.EmployeeName,
		            CASE WHEN ECF.FieldTypeId=3 OR ECF.FieldTypeId=4 THEN
					ISNULL(EC.FieldData,'''') 
					WHEN ECF.FieldTypeId=2 THEN
					ISNULL(EC.FieldData,''0'')
					WHEN ECF.FieldTypeId=1 THEN
					ISNULL(EC.FieldData,''False'') 				
					END AS SubCategory
			FROM 
		       
				 sHrm.vEmployeeCommonDetail ECD
		         LEFT JOIN sHrm.tEmployeeCustomFieldData EC ON EC.EmployeeId=ECD.EmployeeId
		         LEFT JOIN sHrm.tEmployeeCustomFieldMaster ECF ON ECF.Id=EC.EmployeeCustomFieldId AND ECF.FieldTypeId='''+@lDataTypeId+'''  AND ECF.Id= '''+CAST(@rSubCategoryId AS nvarchar(15))+''' AND ECF.IsObsolete=0 
		         
		    Where ECD.EmployeeId='+CAST(@rEmployeeId AS nvarchar(15))+') AS a where RowNumber =1'     
		 		
		  print @Sql		
		   		
			EXECUTE  sp_executesql @Sql		
	   
END
GO
PRINT N'Creating [sHrm].[pDigitalFormEmployeeListGet]...';


GO
 
 
CREATE PROCEDURE [sHrm].[pDigitalFormEmployeeListGet]
	 @rSourceId bigint,
	 @rSourceTypeId int,
	 @rOrgGroupBatchId int,
	 @rOrgId int 
		 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	
	IF(@rSourceTypeId = 95)
	BEGIN
	 DECLARE @lOrgId int,@lDepartmentId int,@lEmployeeId bigint
	

	 SELECT @lEmployeeId = ECD.EmployeeId,@lOrgId = ECD.OrgId,@lDepartmentId = ECD.DepartmentId
     FROM sHrm.vEmployeeCommonDetail ECD
     WHERE ECD.EmployeeId = @rSourceId AND ECD.OrgId = @rOrgId

     SELECT 
			 DF.Id,
			 DF.Code,
			 DF.Title,
			 DF.IsObsolete,
			 CONVERT(nvarchar,DF.CreatedDateTime,103) as CreatedDateTime, 
			 CASE WHEN U.SourceTypeId = 95 THEN (SELECT ShortName FROM sHrm.tEmployeeMaster WHERE Id = U.SourceId )
			 WHEN U.SourceTypeId = 2003 THEN (SELECT FirstName+''+LastName as Name FROM sStudent.tAcademic A INNER JOIN sStudent.tStudentMaster SM ON A.StudentId = SM.Id WHERE A.Id = U.SourceId ) ELSE 'Admin' END As CreatedBy,
			 0 as Submitted,
			 0 as NotSubmitted
     FROM 
		    [sHrm].[tDigitalForm] DF
			INNER JOIN sSecurity.tUser U ON DF.CreatedUserId = U.Id
			INNER JOIN (SELECT DFS.DigitalFormId FROM sHrm.tDigitalFormScope DFS
			WHERE (
			( 
			(DFS.SourceTypeId = 2021 AND DFS.SourceId =@lOrgId) 
			OR
			(DFS.SourceTypeId = 2017 AND DFS.SourceId =@lDepartmentId) OR
			--(DFS.SourceTypeId = 2016 AND DFS.SourceId =@lClassId) OR
			--(DFS.SourceTypeId = 2005 AND DFS.SourceId =@lDivisionId) OR
			(DFS.SourceTypeId = 95 AND DFS.SourceId =@lEmployeeId)
			--(DFS.SourceTypeId = 2001 AND DFS.SourceId =@lAcademicId)
				))
			) D
			ON D.DigitalFormId= DF.Id
	 WHERE
			DF.IsObsolete = 0
	 
	END 
END
GO
PRINT N'Creating [sHrm].[pDigitalFormFieldAdd]...';


GO
 
 
CREATE PROCEDURE [sHrm].[pDigitalFormFieldAdd]
			@rDigitalFormId bigint
           ,@rFieldTypeId smallint
           ,@rUpdateFieldId int
             
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
 
BEGIN  
		IF EXISTS (SELECT 1 FROM sHrm.tDigitalFormField WHERE DigitalFormId = @rDigitalFormId AND FieldTypeId = @rFieldTypeId AND UpdateFieldId = @rUpdateFieldId)
		BEGIN
			SELECT -103 as Result
		END
		ELSE
		BEGIN
			INSERT INTO sHrm.tDigitalFormField
			(
				DigitalFormId
			   ,FieldTypeId
			   ,UpdateFieldId
			    
			)
			VALUES
			(	
				@rDigitalFormId
			   ,@rFieldTypeId
			   ,@rUpdateFieldId
			    
			)		
			SELECT 1 AS Result
		END 
END
GO
PRINT N'Creating [sHrm].[pDigitalFormFieldApprove]...';


GO

CREATE PROCEDURE [sHrm].[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 sHrm.vEmployeeCommonDetail WHERE EmployeeId = @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 @lEmployeeId BigInt

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

			SET @lSubFunctionality = (SELECT SubFunctionalityName FROM sCommon.tUpdateFieldMaster WHERE Id = @rUpdateFieldId)
			SET @lEmployeeId = (SELECT EmployeeId FROM sHrm.vEmployeeCommonDetail WHERE EmployeeId = @rId)

			IF(@lUpdateField = 'Gender' OR @lUpdateField = 'Religion' OR @lUpdateField = 'MaritalStatus' OR @lUpdateField = 'BloodGroup' 
			 OR @lUpdateField = 'EmployeeDesignation' OR @lUpdateField = 'OrganizationDepartment' OR @lUpdateField = 'EmployeeType' 
			 OR @lUpdateField = 'EmployeeGroup' OR @lUpdateField = 'EmployeeGrade' OR @lUpdateField = 'OrgGroupDepartment' 
			OR @lUpdateField = 'EmployeeManager'  OR @lUpdateField = 'Payroll' OR  @lUpdateField = 'PayrollGroup')
			BEGIN
			SET @lUpdateField =@lUpdateField + 'Id'
			END
			IF(@lUpdateField = 'OrganizationHeadManager' )
			BEGIN
				SET @lUpdateField = 'EmployeeBusinessHeadId'
			END
			IF(@lUpdateField = 'CasteCategory' )
			BEGIN
			SET @lUpdateField = Replace(@lUpdateField,'Caste','Cast') + 'Id'
			END
			
			IF(@lUpdateField = 'FamilyCast' )
			BEGIN
				SET @lUpdateField = Replace(@lUpdateField,'Caste','Cast') 
			END
	
			Declare @Sql nvarchar(max)

			IF OBJECT_ID('ListofEmpData') IS NOT NULL	
			BEGIN 
				DROP TABLE ListofEmpData
			END	
			
			--Select @lSubFunctionality	
			IF(@rStatusId = 550)
			BEGIN

			CREATE TABLE ListofEmpData(Id bigint,EmployeeId bigint,SubCategory nvarchar(150),UpdatedUserId bigint,IsExist bit);
			insert into ListofEmpData VALUES (@rId,@lEmployeeId,@rNewValue,@rActionUserId,0)
		
			IF(@lSubFunctionality = 'EmployeeCommunication')  ----EmployeeCommunication
			BEGIN
			UPDATE ListofEmpData SET IsExist=1 WHERE EmployeeId NOT IN(SELECT EmployeeId FROM sHrm.tEmployeeCommunications)
				set @sql='INSERT INTO sHrm.tEmployeeCommunications 
							(EmployeeId,'+@lUpdateField+',CreatedUserId,CreatedDateTime)
							SELECT
								LD.EmployeeId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
							FROM
								ListofEmpData LD WHERE LD.IsExist=1'
					
				print @sql		
				Exec sp_executesql @sql
				set @sql='UPDATE sHrm.tEmployeeCommunications set '+@lUpdateField+' = LD.SubCategory,
							UpdatedUserId=LD.UpdatedUserId,
							UpdatedDateTime=sCommon.fGetDate()  
							from sHrm.tEmployeeCommunications EC 
							INNER JOIN ListofEmpData LD ON EC.EmployeeId=LD.EmployeeId AND IsExist=0'
		
				Exec sp_executesql @sql
	
		
				Drop Table ListofEmpData
					 SET @lResult = 1;
				END
			
			Else IF(@lSubFunctionality = 'EmployeeOther')         -------EmployeeOther
				BEGIN
				
				UPDATE ListofEmpData SET IsExist=1 WHERE EmployeeId NOT IN(SELECT EmployeeId FROM sHrm.tEmployeePersonalDetail) 
			
					IF(@lUpdateField = 'DateOfBirth')
					BEGIN			
						set @sql='INSERT INTO sHrm.tEmployeePersonalDetail 
								(EmployeeId,'+@lUpdateField+',CreatedUserId,CreatedDateTime)
								SELECT
									LD.EmployeeId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
								FROM
									ListofEmpData LD WHERE LD.IsExist=1'
						Exec sp_executesql @sql				
			 				
						set @sql='UPDATE sHrm.tEmployeePersonalDetail set '+@lUpdateField+' = LD.SubCategory,
									UpdatedUserId=LD.UpdatedUserId,
									UpdatedDateTime=sCommon.fGetDate()  
									from sHrm.tEmployeePersonalDetail EPD 
									INNER JOIN ListofEmpData LD ON EPD.EmployeeId=LD.EmployeeId'			
						Exec sp_executesql @sql
						set @sql='UPDATE sHrm.tEmployeePersonalDetail SET '+@lUpdateField+' = null WHERE DateOfBirth=''1900-01-01'''
						Exec sp_executesql @sql
					END
					ELSE
					BEGIN
					--Select * from ListofEmpData
					--Select @lUpdateField
						set @sql='INSERT INTO sHrm.tEmployeePersonalDetail
									(EmployeeId,'+@lUpdateField+',UpdatedUserId,UpdatedDateTime)
									SELECT
										LD.EmployeeId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
									FROM
										ListofEmpData LD WHERE LD.IsExist=1'
						Exec sp_executesql @sql				
			 				
						set @sql='UPDATE sHrm.tEmployeePersonalDetail set '+@lUpdateField+' = LD.SubCategory,
									UpdatedUserId=LD.UpdatedUserId,
									UpdatedDateTime=sCommon.fGetDate()  
									from sHrm.tEmployeePersonalDetail EPD 
									INNER JOIN ListofEmpData LD ON EPD.EmployeeId=LD.EmployeeId'
						--Select  @sql
						Exec sp_executesql @sql
						--Select ERROR_MESSAGE()
					END
					Drop Table ListofEmpData
						 SET @lResult = 1;
				 END	
				
			Else IF(@lSubFunctionality = 'JobDetail')		--------JobDetail
					BEGIN
						UPDATE ListofEmpData SET IsExist=1 WHERE EmployeeId NOT IN(SELECT EmployeeId FROM sHrm.tEmployeeJobDetail) 
					IF(@lUpdateField = 'DateOfJoining')
					BEGIN			
						set @sql='INSERT INTO sHrm.tEmployeeJobDetail 
								(EmployeeId,'+@lUpdateField+',CreatedUserId,CreatedDateTime)
								SELECT
									LD.EmployeeId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
								FROM
									ListofEmpData LD WHERE LD.IsExist=1'
						Exec sp_executesql @sql				
			 				
						set @sql='UPDATE sHrm.tEmployeeJobDetail  set '+@lUpdateField+' = LD.SubCategory,
									UpdatedUserId=LD.UpdatedUserId,
									UpdatedDateTime=sCommon.fGetDate()  
									from sHrm.tEmployeeJobDetail  EJD 
									INNER JOIN ListofEmpData LD ON EJD.EmployeeId=LD.EmployeeId'			
						Exec sp_executesql @sql
						set @sql='UPDATE sHrm.tEmployeeJobDetail SET '+@lUpdateField+' = null WHERE DateOfJoining=''1900-01-01'''
						Exec sp_executesql @sql
					END
					ELSE IF(@lUpdateField = 'DateOfleaving')
					BEGIN			
						set @sql='INSERT INTO sHrm.tEmployeeJobDetail 
								(EmployeeId,'+@lUpdateField+',CreatedUserId,CreatedDateTime)
								SELECT
									LD.EmployeeId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
								FROM
									ListofEmpData LD WHERE LD.IsExist=1'
						Exec sp_executesql @sql				
			 				
						set @sql='UPDATE sHrm.tEmployeeJobDetail  set '+@lUpdateField+' = LD.SubCategory,
									UpdatedUserId=LD.UpdatedUserId,
									UpdatedDateTime=sCommon.fGetDate()  
									from sHrm.tEmployeeJobDetail  EJD 
									INNER JOIN ListofEmpData LD ON EJD.EmployeeId=LD.EmployeeId'			
						Exec sp_executesql @sql
						set @sql='UPDATE sHrm.tEmployeeJobDetail SET '+@lUpdateField+' = null WHERE DateOfleaving=''1900-01-01'''
						Exec sp_executesql @sql
					END
					ELSE IF(@lUpdateField = 'ProbationUptoDate')
					BEGIN			
						set @sql='INSERT INTO sHrm.tEmployeeJobDetail 
								(EmployeeId,'+@lUpdateField+',CreatedUserId,CreatedDateTime)
								SELECT
									LD.EmployeeId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
								FROM
									ListofEmpData LD WHERE LD.IsExist=1'
						Exec sp_executesql @sql				
			 				
						set @sql='UPDATE sHrm.tEmployeeJobDetail  set '+@lUpdateField+' = LD.SubCategory,
									UpdatedUserId=LD.UpdatedUserId,
									UpdatedDateTime=sCommon.fGetDate()  
									from sHrm.tEmployeeJobDetail  EJD 
									INNER JOIN ListofEmpData LD ON EJD.EmployeeId=LD.EmployeeId'			
						Exec sp_executesql @sql
						set @sql='UPDATE sHrm.tEmployeeJobDetail SET '+@lUpdateField+' = null WHERE ProbationUptoDate=''1900-01-01'''
						Exec sp_executesql @sql
					END
					ELSE IF(@lUpdateField = 'AhdocUptoDate')
					BEGIN			
						set @sql='INSERT INTO sHrm.tEmployeeJobDetail 
								(EmployeeId,'+@lUpdateField+',CreatedUserId,CreatedDateTime)
								SELECT
									LD.EmployeeId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
								FROM
									ListofEmpData LD WHERE LD.IsExist=1'
						Exec sp_executesql @sql				
			 				
						set @sql='UPDATE sHrm.tEmployeeJobDetail  set '+@lUpdateField+' = LD.SubCategory,
									UpdatedUserId=LD.UpdatedUserId,
									UpdatedDateTime=sCommon.fGetDate()  
									from sHrm.tEmployeeJobDetail  EJD 
									INNER JOIN ListofEmpData LD ON EJD.EmployeeId=LD.EmployeeId'			
						Exec sp_executesql @sql
						set @sql='UPDATE sHrm.tEmployeeJobDetail SET '+@lUpdateField+' = null WHERE AhdocUptoDate=''1900-01-01'''
						Exec sp_executesql @sql
					END
					ELSE IF(@lUpdateField = 'PermanentDate')
					BEGIN			
						set @sql='INSERT INTO sHrm.tEmployeeJobDetail 
								(EmployeeId,'+@lUpdateField+',CreatedUserId,CreatedDateTime)
								SELECT
									LD.EmployeeId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
								FROM
									ListofEmpData LD WHERE LD.IsExist=1'
						Exec sp_executesql @sql				
			 				
						set @sql='UPDATE sHrm.tEmployeeJobDetail  set '+@lUpdateField+' = LD.SubCategory,
									UpdatedUserId=LD.UpdatedUserId,
									UpdatedDateTime=sCommon.fGetDate()  
									from sHrm.tEmployeeJobDetail  EJD 
									INNER JOIN ListofEmpData LD ON EJD.EmployeeId=LD.EmployeeId'			
						Exec sp_executesql @sql
						set @sql='UPDATE sHrm.tEmployeeJobDetail SET '+@lUpdateField+' = null WHERE PermanentDate=''1900-01-01'''
						Exec sp_executesql @sql
					END
					ELSE
					BEGIN
						set @sql='INSERT INTO sHrm.tEmployeeJobDetail
									(EmployeeId,'+@lUpdateField+',CreatedUserId,CreatedDateTime)
									SELECT
										LD.EmployeeId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
									FROM
										ListofEmpData LD WHERE LD.IsExist=1'
						Exec sp_executesql @sql				
			 				
						set @sql='UPDATE ssHrm.tEmployeeJobDetail set '+@lUpdateField+' = LD.SubCategory,
									UpdatedUserId=LD.UpdatedUserId,
									UpdatedDateTime=sCommon.fGetDate()  
									from sHrm.tEmployeeJobDetail EJD 
									INNER JOIN ListofEmpData LD ON EJD.EmployeeId=LD.EmployeeId'
			
						Exec sp_executesql @sql
					END
					Drop Table ListofEmpData
						 SET @lResult = 1;
					END	

			Else IF(@lSubFunctionality = 'EmployeeGeneral')			---------EmployeeGeneral
					BEGIN
						
						UPDATE ListofEmpData SET IsExist=1 WHERE EmployeeId NOT IN(SELECT Id FROM sHrm.tEmployeeMaster) 
		
						set @sql='INSERT INTO sHrm.tEmployeeMaster
									(Id,'+@lUpdateField+',CreatedUserId,CreatedDateTime)
									SELECT
										LD.EmployeeId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
									FROM
										ListofEmpData LD WHERE LD.IsExist=1'				
						Exec sp_executesql @sql
						set @sql='UPDATE sHrm.tEmployeeMaster set '+@lUpdateField+' = LD.SubCategory,
									UpdatedUserId=LD.UpdatedUserId,
									UpdatedDateTime=sCommon.fGetDate()  
									from sHrm.tEmployeeMaster EM 
									INNER JOIN ListofEmpData LD ON EM.Id=LD.EmployeeId AND IsExist=0'
		
						Exec sp_executesql @sql
					
						Drop Table ListofEmpData
							 SET @lResult = 1;
						END
			 Else IF(@lSubFunctionality = 'Statutory')	   ----------Statutory
					 BEGIN

					 UPDATE ListofEmpData SET IsExist=1 WHERE EmployeeId NOT IN(SELECT EmployeeId FROM sHrm.tEmployeeStatutoryAndOther) 
					 set @sql='INSERT INTO sHrm.tEmployeeStatutoryAndOther 
								(EmployeeId,'+@lUpdateField+',UpdatedUserId,UpdatedDateTime)
								SELECT
									LD.EmployeeId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
								FROM
									ListofEmpData LD WHERE LD.IsExist=1'				
					Exec sp_executesql @sql
					 
					 set @sql='UPDATE sHrm.tEmployeeStatutoryAndOther set '+@lUpdateField+' = LD.SubCategory,
									UpdatedUserId=LD.UpdatedUserId,
									UpdatedDateTime=sCommon.fGetDate()  
									from sHrm.tEmployeeStatutoryAndOther ES 
									INNER JOIN ListofEmpData LD ON ES.EmployeeId=LD.EmployeeId AND IsExist=0'

						Exec sp_executesql @sql
					  
						 Drop Table ListofEmpData
							 SET @lResult = 1;
					END
				
			--END	
			IF(@lResult = 1)
			BEGIN
				UPDATE sHrm.tDigitalFormEmployee
				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 ListofEmpData(Id bigint,EmployeeId bigint,SubCategory nvarchar(150),UpdatedUserId bigint,IsExist bit);
			insert into ListofEmpData VALUES (@rId,@lEmployeeId,@rNewValue,@rActionUserId,0)

			--UPDATE ListofEmpData SET IsExist=1 WHERE EmployeeId NOT IN(SELECT EmployeeId FROM sHrm.tEmployeeCommunications)

			
			IF(@lSubFunctionality = 'EmployeeCommunication')  ----EmployeeCommunication
				BEGIN
			UPDATE ListofEmpData SET IsExist=1 WHERE EmployeeId NOT IN(SELECT EmployeeId FROM sHrm.tEmployeeCommunications)
				set @sql='INSERT INTO sHrm.tEmployeeCommunications 
							(EmployeeId,'+@lUpdateField+',CreatedUserId,CreatedDateTime)
							SELECT
								LD.EmployeeId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
							FROM
								ListofEmpData LD WHERE LD.IsExist=1'
					
				print @sql		
				Exec sp_executesql @sql
				set @sql='UPDATE sHrm.tEmployeeCommunications set '+@lUpdateField+' = LD.SubCategory,
							UpdatedUserId=LD.UpdatedUserId,
							UpdatedDateTime=sCommon.fGetDate()  
							from sHrm.tEmployeeCommunications EC 
							INNER JOIN ListofEmpData LD ON EC.EmployeeId=LD.EmployeeId AND IsExist=0'
		
				Exec sp_executesql @sql
	
		
				Drop Table ListofEmpData
					 SET @lResult = 1;
				END
			
			Else IF(@lSubFunctionality = 'EmployeeOther')         -------EmployeeOther
				BEGIN
				UPDATE ListofEmpData SET IsExist=1 WHERE EmployeeId NOT IN(SELECT EmployeeId FROM sHrm.tEmployeePersonalDetail) 
					IF(@lUpdateField = 'DateOfBirth')
					BEGIN			
						set @sql='INSERT INTO sHrm.tEmployeePersonalDetail 
								(EmployeeId,'+@lUpdateField+',CreatedUserId,CreatedDateTime)
								SELECT
									LD.EmployeeId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
								FROM
									ListofEmpData LD WHERE LD.IsExist=1'
						Exec sp_executesql @sql				
			 				
						set @sql='UPDATE sHrm.tEmployeePersonalDetail set '+@lUpdateField+' = LD.SubCategory,
									UpdatedUserId=LD.UpdatedUserId,
									UpdatedDateTime=sCommon.fGetDate()  
									from sHrm.tEmployeePersonalDetail EPD 
									INNER JOIN ListofEmpData LD ON EPD.EmployeeId=LD.EmployeeId'			
						Exec sp_executesql @sql
						set @sql='UPDATE sHrm.tEmployeePersonalDetail SET '+@lUpdateField+' = null WHERE DateOfBirth=''1900-01-01'''
						Exec sp_executesql @sql
					END
					ELSE
					BEGIN
						set @sql='INSERT INTO sHrm.tEmployeePersonalDetail
									(EmployeeId,'+@lUpdateField+',CreatedUserId,CreatedDateTime)
									SELECT
										LD.EmployeeId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
									FROM
										ListofEmpData LD WHERE LD.IsExist=1'
						Exec sp_executesql @sql				
			 				
						set @sql='UPDATE sHrm.tEmployeePersonalDetail set '+@lUpdateField+' = LD.SubCategory,
									UpdatedUserId=LD.UpdatedUserId,
									UpdatedDateTime=sCommon.fGetDate()  
									from sHrm.tEmployeePersonalDetail EPD 
									INNER JOIN ListofEmpData LD ON EPD.EmployeeId=LD.EmployeeId'
			
						Exec sp_executesql @sql
					END
					Drop Table ListofEmpData
						 SET @lResult = 1;
				 END	

			Else IF(@lSubFunctionality = 'JobDetail')		--------JobDetail
					BEGIN
						UPDATE ListofEmpData SET IsExist=1 WHERE EmployeeId NOT IN(SELECT EmployeeId FROM sHrm.tEmployeeJobDetail) 
					IF(@lUpdateField = 'DateOfJoining')
					BEGIN			
						set @sql='INSERT INTO sHrm.tEmployeeJobDetail 
								(EmployeeId,'+@lUpdateField+',CreatedUserId,CreatedDateTime)
								SELECT
									LD.EmployeeId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
								FROM
									ListofEmpData LD WHERE LD.IsExist=1'
						Exec sp_executesql @sql				
			 				
						set @sql='UPDATE sHrm.tEmployeeJobDetail  set '+@lUpdateField+' = LD.SubCategory,
									UpdatedUserId=LD.UpdatedUserId,
									UpdatedDateTime=sCommon.fGetDate()  
									from sHrm.tEmployeeJobDetail  EJD 
									INNER JOIN ListofEmpData LD ON EJD.EmployeeId=LD.EmployeeId'			
						Exec sp_executesql @sql
						set @sql='UPDATE sHrm.tEmployeeJobDetail SET '+@lUpdateField+' = null WHERE DateOfJoining=''1900-01-01'''
						Exec sp_executesql @sql
					END
					ELSE IF(@lUpdateField = 'DateOfleaving')
					BEGIN			
						set @sql='INSERT INTO sHrm.tEmployeeJobDetail 
								(EmployeeId,'+@lUpdateField+',CreatedUserId,CreatedDateTime)
								SELECT
									LD.EmployeeId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
								FROM
									ListofEmpData LD WHERE LD.IsExist=1'
						Exec sp_executesql @sql				
			 				
						set @sql='UPDATE sHrm.tEmployeeJobDetail  set '+@lUpdateField+' = LD.SubCategory,
									UpdatedUserId=LD.UpdatedUserId,
									UpdatedDateTime=sCommon.fGetDate()  
									from sHrm.tEmployeeJobDetail  EJD 
									INNER JOIN ListofEmpData LD ON EJD.EmployeeId=LD.EmployeeId'			
						Exec sp_executesql @sql
						set @sql='UPDATE sHrm.tEmployeeJobDetail SET '+@lUpdateField+' = null WHERE DateOfleaving=''1900-01-01'''
						Exec sp_executesql @sql
					END
					ELSE IF(@lUpdateField = 'ProbationUptoDate')
					BEGIN			
						set @sql='INSERT INTO sHrm.tEmployeeJobDetail 
								(EmployeeId,'+@lUpdateField+',CreatedUserId,CreatedDateTime)
								SELECT
									LD.EmployeeId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
								FROM
									ListofEmpData LD WHERE LD.IsExist=1'
						Exec sp_executesql @sql				
			 				
						set @sql='UPDATE sHrm.tEmployeeJobDetail  set '+@lUpdateField+' = LD.SubCategory,
									UpdatedUserId=LD.UpdatedUserId,
									UpdatedDateTime=sCommon.fGetDate()  
									from sHrm.tEmployeeJobDetail  EJD 
									INNER JOIN ListofEmpData LD ON EJD.EmployeeId=LD.EmployeeId'			
						Exec sp_executesql @sql
						set @sql='UPDATE sHrm.tEmployeeJobDetail SET '+@lUpdateField+' = null WHERE ProbationUptoDate=''1900-01-01'''
						Exec sp_executesql @sql
					END
					ELSE IF(@lUpdateField = 'AhdocUptoDate')
					BEGIN			
						set @sql='INSERT INTO sHrm.tEmployeeJobDetail 
								(EmployeeId,'+@lUpdateField+',CreatedUserId,CreatedDateTime)
								SELECT
									LD.EmployeeId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
								FROM
									ListofEmpData LD WHERE LD.IsExist=1'
						Exec sp_executesql @sql				
			 				
						set @sql='UPDATE sHrm.tEmployeeJobDetail  set '+@lUpdateField+' = LD.SubCategory,
									UpdatedUserId=LD.UpdatedUserId,
									UpdatedDateTime=sCommon.fGetDate()  
									from sHrm.tEmployeeJobDetail  EJD 
									INNER JOIN ListofEmpData LD ON EJD.EmployeeId=LD.EmployeeId'			
						Exec sp_executesql @sql
						set @sql='UPDATE sHrm.tEmployeeJobDetail SET '+@lUpdateField+' = null WHERE AhdocUptoDate=''1900-01-01'''
						Exec sp_executesql @sql
					END
					ELSE IF(@lUpdateField = 'PermanentDate')
					BEGIN			
						set @sql='INSERT INTO sHrm.tEmployeeJobDetail 
								(EmployeeId,'+@lUpdateField+',CreatedUserId,CreatedDateTime)
								SELECT
									LD.EmployeeId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
								FROM
									ListofEmpData LD WHERE LD.IsExist=1'
						Exec sp_executesql @sql				
			 				
						set @sql='UPDATE sHrm.tEmployeeJobDetail  set '+@lUpdateField+' = LD.SubCategory,
									UpdatedUserId=LD.UpdatedUserId,
									UpdatedDateTime=sCommon.fGetDate()  
									from sHrm.tEmployeeJobDetail  EJD 
									INNER JOIN ListofEmpData LD ON EJD.EmployeeId=LD.EmployeeId'			
						Exec sp_executesql @sql
						set @sql='UPDATE sHrm.tEmployeeJobDetail SET '+@lUpdateField+' = null WHERE PermanentDate=''1900-01-01'''
						Exec sp_executesql @sql
					END
					ELSE
					BEGIN
						set @sql='INSERT INTO sHrm.tEmployeeJobDetail
									(EmployeeId,'+@lUpdateField+',CreatedUserId,CreatedDateTime)
									SELECT
										LD.EmployeeId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
									FROM
										ListofEmpData LD WHERE LD.IsExist=1'
						Exec sp_executesql @sql				
			 				
						set @sql='UPDATE ssHrm.tEmployeeJobDetail set '+@lUpdateField+' = LD.SubCategory,
									UpdatedUserId=LD.UpdatedUserId,
									UpdatedDateTime=sCommon.fGetDate()  
									from sHrm.tEmployeeJobDetail EJD 
									INNER JOIN ListofEmpData LD ON EJD.EmployeeId=LD.EmployeeId'
			
						Exec sp_executesql @sql
					END
					Drop Table ListofEmpData
						 SET @lResult = 1;
					END	

			Else IF(@lSubFunctionality = 'EmployeeGeneral')			---------EmployeeGeneral
					BEGIN
						
						UPDATE ListofEmpData SET IsExist=1 WHERE EmployeeId NOT IN(SELECT Id FROM sHrm.tEmployeeMaster) 
		
						set @sql='INSERT INTO sHrm.tEmployeeMaster
									(Id,'+@lUpdateField+',CreatedUserId,CreatedDateTime)
									SELECT
										LD.EmployeeId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
									FROM
										ListofEmpData LD WHERE LD.IsExist=1'				
						Exec sp_executesql @sql
						set @sql='UPDATE sHrm.tEmployeeMaster set '+@lUpdateField+' = LD.SubCategory,
									UpdatedUserId=LD.UpdatedUserId,
									UpdatedDateTime=sCommon.fGetDate()  
									from sHrm.tEmployeeMaster EM 
									INNER JOIN ListofEmpData LD ON EM.Id=LD.EmployeeId AND IsExist=0'
		
						Exec sp_executesql @sql
					
						Drop Table ListofEmpData
							 SET @lResult = 1;
						END
			 Else IF(@lSubFunctionality = 'Statutory')	   ----------Statutory
					 BEGIN

					 UPDATE ListofEmpData SET IsExist=1 WHERE EmployeeId NOT IN(SELECT EmployeeId FROM sHrm.tEmployeeStatutoryAndOther) 
					 set @sql='INSERT INTO sHrm.tEmployeeStatutoryAndOther 
								(EmployeeId,'+@lUpdateField+',UpdatedUserId,UpdatedDateTime)
								SELECT
									LD.EmployeeId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
								FROM
									ListofEmpData LD WHERE LD.IsExist=1'				
					Exec sp_executesql @sql
					 
					 set @sql='UPDATE sHrm.tEmployeeStatutoryAndOther set '+@lUpdateField+' = LD.SubCategory,
									UpdatedUserId=LD.UpdatedUserId,
									UpdatedDateTime=sCommon.fGetDate()  
									from sHrm.tEmployeeStatutoryAndOther ES 
									INNER JOIN ListofEmpData LD ON ES.EmployeeId=LD.EmployeeId AND IsExist=0'

						Exec sp_executesql @sql
					  
						 Drop Table ListofEmpData
							 SET @lResult = 1;
					END
			IF(@lResult = 1)
			BEGIN
				UPDATE sHrm.tDigitalFormEmployee
				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 [sHrm].[pDigitalFormFieldDetailGet]...';


GO

 
CREATE PROCEDURE [sHrm].[pDigitalFormFieldDetailGet]
	 @rCategoryId int,
	 @rSubCategory nvarchar(500),
	 @rEmployeeId bigint,
	 @rIsBlank bit = 0

AS
SET NOCOUNT ON

BEGIN
		DECLARE @lDataTypeId nvarchar(1)
		SELECT @lDataTypeId=DataTypeId FROM sCommon.tUpdateFieldMaster WHERE Field=@rSubCategory
		 
		IF(@rSubCategory = 'Gender' OR @rSubCategory = 'Religion'  OR @rSubCategory = 'MaritalStatus' OR @rSubCategory = 'BloodGroup' 
		OR @rSubCategory = 'EmployeeDesignation' OR @rSubCategory = 'OrganizationDepartment' OR @rSubCategory = 'EmployeeType'
		OR @rSubCategory = 'EmployeeGroup' OR @rSubCategory = 'EmployeeGrade' OR @rSubCategory = 'OrgGroupDepartment'
		OR @rSubCategory = 'EmployeeManager' 
		OR @rSubCategory = 'Payroll' OR @rSubCategory = 'PayrollGroup'
		)
		BEGIN
			 
			SET @rSubCategory =@rSubCategory + 'Id'
			 -- print @rSubCategory
		END
		IF(@rSubCategory = 'OrganizationHeadManager' )
		BEGIN
			SET @rSubCategory = 'EmployeeBusinessHeadId'
		END
		IF(@rSubCategory = 'CasteCategory' )
		BEGIN
			SET @rSubCategory = Replace(@rSubCategory,'Caste','Cast') + 'Id'
		END
		
		IF(@rSubCategory = 'FamilyCast' )
		BEGIN
			SET @rSubCategory = Replace(@rSubCategory,'Caste','Cast') 
		END
		 Declare @Sql nvarchar(max)
		 Declare @Sql1 nvarchar(max)
		 
		 SET @Sql =  CASE @rCategoryId					  
					 WHEN 1 THEN -- Communication
						'Select ECD.EmployeeId,ECD.Code,ECD.EmployeeName,
						CASE WHEN '+@lDataTypeId+'=1 THEN
						ISNULL(EC.'+@rSubCategory+','''') 
						WHEN '+@lDataTypeId+'=2 THEN
						ISNULL(EC.'+@rSubCategory+',''0'')
						WHEN '+@lDataTypeId+'=3 THEN
						ISNULL(EC.'+@rSubCategory+',''False'') 
						WHEN '+@lDataTypeId+'=4 THEN
						ISNULL(EC.'+@rSubCategory+',''0001/01/01'') 
						WHEN '+@lDataTypeId+'=5 THEN
						ISNULL(EC.'+@rSubCategory+',''0'') 
						END AS SubCategory
							FROM 
							sHrm.vEmployeeCommonDetail ECD
							LEFT JOIN sHrm.tEmployeeCommunications EC ON ECD.EmployeeId = EC.EmployeeId
							Where ECD.EmployeeId='+CAST(@rEmployeeId AS nvarchar(15))+'
							AND 
							('+CAST(@rIsBlank AS nvarchar(1))+'=0 
								OR ('+@lDataTypeId+'=1 AND ISNULL(EC.'+@rSubCategory+','''')='''')
								OR ('+@lDataTypeId+'=2 AND ISNULL(EC.'+@rSubCategory+',''0'')=''0'')
								OR ('+@lDataTypeId+'=3 AND ISNULL(EC.'+@rSubCategory+',''False'')=''False'')
								OR ('+@lDataTypeId+'=4 AND ISNULL(EC.'+@rSubCategory+',''0001/01/01'')=''0001/01/01'') 
							)
							 '
							
					 WHEN 2 THEN -- Other
						'Select ECD.EmployeeId,ECD.Code,ECD.EmployeeName,
						CASE WHEN '+@lDataTypeId+'=1 THEN
						ISNULL(EPD.'+@rSubCategory+','''')
						WHEN '+@lDataTypeId+'=2 THEN
						ISNULL(EPD.'+@rSubCategory+',''0'')
						WHEN '+@lDataTypeId+'=3 THEN
						ISNULL(EPD.'+@rSubCategory+',''False'')
						WHEN '+@lDataTypeId+'=4 THEN
						EPD.'+@rSubCategory+'
						WHEN '+@lDataTypeId+'=5 THEN
						ISNULL(EPD.'+@rSubCategory+',''0'')
						END AS SubCategory
							FROM 
							sHrm.vEmployeeCommonDetail ECD
							LEFT JOIN sHrm.tEmployeePersonalDetail EPD ON ECD.EmployeeId=EPD.EmployeeId
							Where ECD.EmployeeId='+CAST(@rEmployeeId AS nvarchar(15))+'
							AND 
							('+CAST(@rIsBlank AS nvarchar(1))+'=0 
								OR ('+@lDataTypeId+'=1 AND ISNULL(EPD.'+@rSubCategory+','''')='''')
								OR ('+@lDataTypeId+'=2 AND ISNULL(EPD.'+@rSubCategory+',''0'')=''0'')
								OR ('+@lDataTypeId+'=3 AND ISNULL(EPD.'+@rSubCategory+',''False'')=''False'')
								OR ('+@lDataTypeId+'=4 AND ISNULL(EPD.'+@rSubCategory+',''0001/01/01'')=''0001/01/01'') 
							)'
							
					WHEN 3 THEN -- Job Detail
						'Select ECD.EmployeeId,ECD.Code,ECD.EmployeeName,
						CASE WHEN '+@lDataTypeId+'=1 THEN
						ISNULL(EJD.'+@rSubCategory+','''')
						WHEN '+@lDataTypeId+'=2 THEN
						ISNULL(EJD.'+@rSubCategory+',''0'')
						WHEN '+@lDataTypeId+'=3 THEN
						ISNULL(EJD.'+@rSubCategory+',''False'')
						WHEN '+@lDataTypeId+'=4 THEN
						ISNULL(EJD.'+@rSubCategory+',''0001/01/01'')
						WHEN '+@lDataTypeId+'=5 THEN
						ISNULL(EJD.'+@rSubCategory+',''0'')
						END AS SubCategory 
							FROM 
							sHrm.vEmployeeCommonDetail ECD
							LEFT JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=ECD.EmployeeId
							Where ECD.EmployeeId='+CAST(@rEmployeeId AS nvarchar(15))+'
							AND 
							('+CAST(@rIsBlank AS nvarchar(1))+'=0 
								OR ('+@lDataTypeId+'=1 AND ISNULL(EJD.'+@rSubCategory+','''')='''')
								OR ('+@lDataTypeId+'=2 AND ISNULL(EJD.'+@rSubCategory+',''0'')=''0'')
								OR ('+@lDataTypeId+'=3 AND ISNULL(EJD.'+@rSubCategory+',''False'')=''False'')
								OR ('+@lDataTypeId+'=4 AND ISNULL(EJD.'+@rSubCategory+',''0001/01/01'')=''0001/01/01'') 
							)'
					 
					WHEN 4 THEN --General
					   'Select ECD.EmployeeId,ECD.Code,ECD.EmployeeName,
						CASE WHEN '+@lDataTypeId+'=1 THEN
						ISNULL(EM.'+@rSubCategory+','''')
						WHEN '+@lDataTypeId+'=2 THEN
						ISNULL(EM.'+@rSubCategory+',''0'')
						WHEN '+@lDataTypeId+'=3 THEN
						ISNULL(EM.'+@rSubCategory+',''False'')
						WHEN '+@lDataTypeId+'=4 THEN
						ISNULL(EM.'+@rSubCategory+',''0001/01/01'')
						WHEN '+@lDataTypeId+'=5 THEN
						ISNULL(EM.'+@rSubCategory+',''0'')
						END AS SubCategory
							FROM 
							sHrm.vEmployeeCommonDetail ECD
							LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id=ECD.EmployeeId
							Where ECD.EmployeeId='+CAST(@rEmployeeId AS nvarchar(15))+'
							AND 
							('+CAST(@rIsBlank AS nvarchar(1))+'=0 
								OR ('+@lDataTypeId+'=1 AND ISNULL(EM.'+@rSubCategory+','''')='''')
								OR ('+@lDataTypeId+'=2 AND ISNULL(EM.'+@rSubCategory+',''0'')=''0'')
								OR ('+@lDataTypeId+'=3 AND ISNULL(EM.'+@rSubCategory+',''False'')=''False'')
								OR ('+@lDataTypeId+'=4 AND ISNULL(EM.'+@rSubCategory+',''0001/01/01'')=''0001/01/01'') 
							)'
				   
					WHEN 5 THEN --Statutory 
					   'Select ECD.EmployeeId,ECD.Code,ECD.EmployeeName,
						CASE WHEN '+@lDataTypeId+'=1 THEN
						ISNULL(ES.'+@rSubCategory+','''')
						WHEN '+@lDataTypeId+'=2 THEN
						ISNULL(ES.'+@rSubCategory+',''0'')
						WHEN '+@lDataTypeId+'=3 THEN
						ISNULL(ES.'+@rSubCategory+',''False'')
						WHEN '+@lDataTypeId+'=4 THEN
						ISNULL(ES.'+@rSubCategory+',''0001/01/01'')
						WHEN '+@lDataTypeId+'=5 THEN
						ISNULL(ES.'+@rSubCategory+',''0'')
						END AS SubCategory
							FROM 
							sHrm.vEmployeeCommonDetail ECD
							LEFT JOIN sHrm.tEmployeeStatutoryAndOther ES ON ECD.EmployeeId=ES.EmployeeId
							Where ECD.EmployeeId='+CAST(@rEmployeeId AS nvarchar(15))+'
							AND 
							('+CAST(@rIsBlank AS nvarchar(1))+'=0 
								OR ('+@lDataTypeId+'=1 AND ISNULL(ES.'+@rSubCategory+','''')='''')
								OR ('+@lDataTypeId+'=2 AND ISNULL(ES.'+@rSubCategory+',''0'')=''0'')
								OR ('+@lDataTypeId+'=3 AND ISNULL(ES.'+@rSubCategory+',''False'')=''False'')
								OR ('+@lDataTypeId+'=4 AND ISNULL(ES.'+@rSubCategory+',''0001/01/01'')=''0001/01/01'') 
							)'
					
				
				
					END				
			
	   if(@Sql1 IS NOT NULL)		
			EXECUTE  sp_executesql @Sql1
	   else
			EXECUTE  sp_executesql @Sql
	   
END
GO
PRINT N'Creating [sHrm].[pDigitalFormFieldGet]...';


GO

CREATE PROCEDURE [sHrm].[pDigitalFormFieldGet]

	  @rDigitalFormId int
	
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	
	SELECT 
		 
		DFF.UpdateFieldId as Id,

		CASE WHEN DFF.FieldTypeId = 1 THEN (SELECT SubFunctionalityName FROM sCommon.tUpdateFieldMaster WHERE Id = DFF.UpdateFieldId) 
		WHEN DFF.FieldTypeId = 2 THEN (SELECT 'EmployeeCustomFields' as SubFunctionalityName FROM sHrm.tEmployeeCustomFieldMaster WHERE Id = DFF.UpdateFieldId) 
		WHEN DFF.FieldTypeId = 3 THEN 'EmployeeDocument' END AS SubFunctionalityName,

		CASE WHEN DFF.FieldTypeId = 1 THEN (SELECT Field FROM sCommon.tUpdateFieldMaster WHERE Id = DFF.UpdateFieldId) 
		WHEN DFF.FieldTypeId = 2 THEN (SELECT FieldTitle FROM sHrm.tEmployeeCustomFieldMaster WHERE Id = DFF.UpdateFieldId)
		WHEN DFF.FieldTypeId = 3 THEN (SELECT DocumentName FROM sCommon.tSubmitDocumentMaster WHERE SubmitDocumentFunctionalityId = 2 AND Id = DFF.UpdateFieldId ) END AS Field
	FROM 
		sHrm.tDigitalForm DF
		INNER JOIN sHrm.tDigitalFormField DFF ON DF.Id = DFF.DigitalFormId
	WHERE 
		((DF.Id = @rDigitalFormId) OR (@rDigitalFormId = 0))
		 
END
GO
PRINT N'Creating [sHrm].[pDigitalFormMasterAdd]...';


GO
 
CREATE PROCEDURE [sHrm].[pDigitalFormMasterAdd]
	 
        @rId bigint = 0,
		@rCode nvarchar(100), 
		@rTitle nvarchar(100),
		@rIsObsolete bit =0,
		@rCreatedUserId bigint,
		@rOrgId int 

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

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sHrm.tDigitalForm', 0, 1, 1,@outNextNumber = @lNextNumber output
	Print @lNextNumber
	INSERT INTO sHrm.tDigitalForm
		(
			Id
		   ,Code
		   ,Title
		   ,OrgId
		   ,IsObsolete
		   ,CreatedUserId
           ,CreatedDateTime
		)
	VALUES
		(
			@lNextNumber,
			@rCode,
			@rTitle,
			@rOrgId,
			@rIsObsolete,
			@rCreatedUserId,
			sCommon.fGetDate()
		)

	 
		    SELECT @lNextNumber AS Result
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE sHrm.tDigitalForm
	    SET
			 
        	 Id = @lNextNumber
		   ,Code = @rCode
		   ,Title = @rTitle
		   ,OrgId = @rOrgId
		   ,IsObsolete = @rIsObsolete
		   ,CreatedUserId = @rCreatedUserId
           ,CreatedDateTime = sCommon.fGetDate()

	      WHERE Id = @rId
	      
	      SELECT 11 AS Result
	 END  	

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


GO
 
 
CREATE PROCEDURE [sHrm].[pDigitalFormMasterDelete]

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

BEGIN 
	
	DELETE FROM sHrm.tDigitalForm WHERE Id = @rDigitalFormId AND OrgId = @rOrgId
	DELETE FROM sHrm.tDigitalFormField WHERE DigitalFormId = @rDigitalFormId
	DELETE FROM sHrm.tDigitalFormScope WHERE DigitalFormId = @rDigitalFormId
	SELECT 1 as Result
END
GO
PRINT N'Creating [sHrm].[pDigitalFormMasterGet]...';


GO
 
 
CREATE PROCEDURE [sHrm].[pDigitalFormMasterGet]

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

BEGIN 
	
	SELECT 
		DF.Id,
		DF.Code,
		DF.Title,
		CONVERT(nvarchar,DF.CreatedDateTime,103) as CreatedDateTime, 
		CASE WHEN U.SourceTypeId = 95 THEN (SELECT ShortName FROM sHrm.tEmployeeMaster WHERE Id = U.SourceId )
			 WHEN U.SourceTypeId = 2003 THEN (SELECT FirstName+''+LastName as Name FROM sStudent.tAcademic A INNER JOIN sStudent.tStudentMaster SM ON A.StudentId = SM.Id WHERE A.Id = U.SourceId ) ELSE 'Admin' END As CreatedBy,
		DF.IsObsolete
	FROM 
		sHrm.tDigitalForm DF
		INNER JOIN sSecurity.tUser U ON DF.CreatedUserId = U.Id
	WHERE 
	    ((DF.OrgId = @rOrgId)OR (@rOrgId=0))
		AND	((DF.Id = @rId) OR (@rId = 0))
		AND ((DF.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))		
		AND ((DF.Code like @rCode) OR (ISNULL(@rCode,'') = ''))
		
		
END
GO
PRINT N'Creating [sHrm].[pDigitalFormMasterScopeDetailGet]...';


GO
CREATE PROCEDURE [sHrm].[pDigitalFormMasterScopeDetailGet]
	@rSourceId bigint = 0,
	@rSourceTypeId int = 0,
	@rDigitalFormId bigint = 0
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 	
	  IF(@rDigitalFormId != 0)
	  BEGIN
		SELECT
			 DS.DigitalFormId,
			 DS.SourceTypeId as SourceTypeId,
			 DS.SourceId as SourceId,
			 OM.DisplayTitle AS Source,
			 'Organization' AS SourceType,
			 '' AS RollNo,
             '' AS Code,
             '' AS DepartmentName,
             OM.DisplayTitle AS OrgName
			 
			FROM sHrm.tDigitalFormScope DS
			INNER JOIN sSetup.tOrganizationMaster OM
				ON DS.SourceId=OM.Id
			WHERE DS.DigitalFormId=@rDigitalFormId AND DS.SourceTypeId=2021

			UNION ALL

			SELECT
			 DS.DigitalFormId,
			 DS.SourceTypeId  as SourceTypeId,
			 DS.SourceId as SourceId,
			 DM.DisplayTitle AS Source,
			 'Department' AS SourceType,
			 '' AS RollNo,
             '' AS Code,
             DM.Title AS DepartmentName,
             OM.DisplayTitle AS OrgName 
			 
			FROM sHrm.tDigitalFormScope DS
			INNER JOIN sSetup.tDepartmentMaster DM
				ON DS.SourceId=DM.Id
			INNER JOIN sSetup.tOrganizationMaster OM
				ON DM.OrgId=OM.Id  
			WHERE DS.DigitalFormId=@rDigitalFormId AND DS.SourceTypeId=2017


			UNION ALL
			
			SELECT
			 DS.DigitalFormId,
			 DS.SourceTypeId as SourceTypeId,
			 DS.SourceId as SourceId,
			 [sHrm].[fEmployeeNameGet](EM.FirstName , EM.MiddleName, EM.LastName,OM.EmployeeNameFormatId ) AS Source,
			 'Employee' AS SourceType,
			 '' AS RollNo,
             EM.Code,
             ECD.DepartmentName AS DepartmentName,
             OM.DisplayTitle AS OrgName 
			 
			FROM sHrm.tDigitalFormScope DS
		    INNER JOIN [sHrm].[tEmployeeMaster] EM ON DS.SourceId=EM.Id AND EM.StatusId = 7
			INNER JOIN sHrm.vEmployeeCommonDetail ECD ON ECD.EmployeeId = EM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON EM.OrgId = OM.Id 
			WHERE DS.DigitalFormId=@rDigitalFormId AND DS.SourceTypeId=95
						
			 
	  END
	  ELSE IF(@rSourceId != 0 AND @rSourceTypeId != 0)
	  BEGIN
		SELECT
			  
			 [sHrm].[fEmployeeNameGet](EM.FirstName , EM.MiddleName, EM.LastName,OM.EmployeeNameFormatId ) AS Source,
			 'Employee' AS SourceType,
			 '' AS RollNo,
             EM.Code,
             ECD.DepartmentName AS DepartmentName,
             OM.DisplayTitle AS OrgName 
			 
			FROM 
			[sHrm].[tEmployeeMaster] EM
			INNER JOIN sHrm.vEmployeeCommonDetail ECD ON ECD.EmployeeId=EM.Id AND EM.StatusId = 7
			INNER JOIN sSetup.tOrganizationMaster OM ON EM.OrgId = OM.Id
			WHERE EM.Id=@rSourceId AND @rSourceTypeId=95

		UNION ALL
		SELECT
			 DM.DisplayTitle AS Source,
			 'Department' AS SourceType,
			 '' AS RollNo,
             '' AS Code,
             DM.Title AS DepartmentName,
             OM.DisplayTitle AS OrgName 
			FROM  
			 sSetup.tDepartmentMaster DM
			INNER JOIN sSetup.tOrganizationMaster OM
				ON DM.OrgId=OM.Id 
			WHERE DM.Id=@rSourceId AND @rSourceTypeId=2017
		
		UNION ALL
		SELECT  OM.DisplayTitle AS Source,
			 'Organization' AS SourceType,
			 '' AS RollNo,
             '' AS Code,
             '' AS DepartmentName,
             OM.DisplayTitle AS OrgName  
			 FROM sSetup.tOrganizationMaster OM  
			 WHERE   OM.Id = @rSourceId AND @rSourceTypeId = 2021
		
	  END
END
GO
PRINT N'Creating [sHrm].[pDigitalFormScopeAdd]...';


GO
 
CREATE PROCEDURE [sHrm].[pDigitalFormScopeAdd]
			@rDigitalFormId bigint
           ,@rSourceTypeId smallint
           ,@rSourceId bigint
             
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
 
BEGIN  
			IF EXISTS (SELECT 1 FROM sHrm.tDigitalFormScope WHERE DigitalFormId = @rDigitalFormId AND SourceTypeId = @rSourceTypeId AND SourceId = @rSourceId)
			BEGIN
				SELECT -103 as Result
			END
			ELSE
			BEGIN
				INSERT INTO sHrm.tDigitalFormScope
				(
					DigitalFormId
				   ,SourceTypeId
				   ,SourceId
			    
				)
				VALUES
				(	
					@rDigitalFormId
				   ,@rSourceTypeId
				   ,@rSourceId
			    
				)		
				SELECT 1 AS Result
			END
END
GO
PRINT N'Creating [sHrm].[pDigitalFormScopeValidate]...';


GO
 
CREATE PROCEDURE [sHrm].[pDigitalFormScopeValidate]
	 
		@rSourceTypeId smallint,
		@rSourceId bigint,
		@rFinalSourceTypeId smallint,
		@rFinalSourceId bigint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
					/* Source Type Value
					   2017 - Department
					   95 - Employee */

	IF(@rSourceTypeId = 2017) -- Department	
		BEGIN
		
			If EXISTS(Select 1 FROM 
				[sHrm].[tEmployeeMaster] EM
				INNER JOIN sHrm.vEmployeeCommonDetail ECD ON ECD.EmployeeId=EM.Id 
				Where ECD.DepartmentId = @rSourceId AND EM.Id = @rFinalSourceId AND @rFinalSourceTypeId = 95 )
					BEGIN
						select -103 as Result,'Employee already Exists' AS Msg
						RETURN
					END 	
			
		
	    END

    
    IF(@rSourceTypeId = 95) -- Employee	
	BEGIN
		If EXISTS(Select 1 FROM 
					[sHrm].[tEmployeeMaster] EM
					INNER JOIN sHrm.vEmployeeCommonDetail  ECD ON EM.Id = ECD.EmployeeId
					INNER JOIN sSetup.tDepartmentMaster DM ON ECD.DepartmentId =  DM.Id
					Where EM.Id = @rSourceId AND DM.Id = @rFinalSourceId AND @rFinalSourceTypeId = 2017)
				BEGIN
					select -102 as Result,'Department already Exists' AS Msg
					RETURN
				END 
	
    END
			select 1 as Result,'' AS Msg
	
END
GO
PRINT N'Creating [sHrm].[pEmployeeDigitalFormDetailGet]...';


GO
 
 
CREATE PROCEDURE [sHrm].[pEmployeeDigitalFormDetailGet]

	  @rDigitalFormId int = 0,
	  @rEmployeeId bigint = 0,
	  @rId int=0,
	  @rEmployeeCode nvarchar(100)='',
	  --@rClassId bigint=0,
	  @rDepartmentId bigint=0,
	  @rStatusId smallint=0,
	  @rOrgId int=0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	
	SELECT 
		ISNULL(DFS.AutoId,0) as Id,
		DFF.UpdateFieldId as UpdateFieldId,
		DF.Id as DigitalFormId,
		ECD.EmployeeId,
		ECD.Code as EmployeeCode,
		ECD.EmployeeName AS Name,
		ECD.DepartmentName AS DepartmentName,
		ISNULL(DF.Code,'') as Code,
		ISNULL(DF.Title,'') as Title,

		CASE WHEN DFF.FieldTypeId = 1 THEN (SELECT SubFunctionalityName FROM sCommon.tUpdateFieldMaster WHERE Id = DFF.UpdateFieldId) 
		WHEN DFF.FieldTypeId = 2 THEN (SELECT 'EmployeeCustomFields' as SubFunctionalityName FROM sHrm.tEmployeeCustomFieldMaster WHERE Id = DFF.UpdateFieldId)
		WHEN DFF.FieldTypeId = 3 THEN 'EmployeeDocument' END AS SubFunctionalityName,

		CASE WHEN DFF.FieldTypeId = 1 THEN (SELECT Field FROM sCommon.tUpdateFieldMaster WHERE Id = DFF.UpdateFieldId) 
		WHEN DFF.FieldTypeId = 2 THEN (SELECT FieldTitle FROM sHrm.tEmployeeCustomFieldMaster WHERE Id = DFF.UpdateFieldId)
		WHEN DFF.FieldTypeId = 3 THEN (SELECT DocumentName FROM sCommon.tSubmitDocumentMaster WHERE SubmitDocumentFunctionalityId = 2 AND Id = DFF.UpdateFieldId ) END AS Field,

		DFF.UpdateFieldId,
		DFF.FieldTypeId,
		ISNULL(DFS.Remark,'') as Remark,
		ISNULL(DFS.ActionRemark,'') as ActionRemark,
		ISNULL(SM.Title,'') as Status,
		DFS.OldValue,
		DFS.NewValue,
		DFS.OldValueImage,
		DFS.NewValueImage
	FROM 
		sHrm.tDigitalForm DF
		INNER JOIN sHrm.tDigitalFormField DFF ON DF.Id = DFF.DigitalFormId
		INNER JOIN sHrm.tDigitalFormEmployee DFS ON DFS.DigitalFormId = DF.Id AND DFF.UpdateFieldId = DFS.UpdateFieldId
		INNER JOIN sHrm.vEmployeeCommonDetail ECD ON ECD.EmployeeId = DFS.EmployeeId
		LEFT JOIN sCommon.tStatusMaster SM ON DFS.StatusId = SM.Id
	WHERE 
		((DF.Id = @rDigitalFormId) OR (@rDigitalFormId = 0)) 
		AND ((DF.Id = @rId) OR (@rId = 0))		
		AND ((ECD.Code = @rEmployeeCode) OR (@rEmployeeCode=0))
		--AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
		AND ((ECD.DepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))
		AND ((ECD.EmployeeId = @rEmployeeId) OR (@rEmployeeId = 0))
		AND ((DFS.StatusId = @rStatusId) OR (@rStatusId = 0))
		AND ((ECD.OrgId = @rOrgId) OR (@rOrgId = 0))
END
GO
PRINT N'Creating [sHrm].[pEmployeeDigitalFormGet]...';


GO
 
 
CREATE PROCEDURE [sHrm].[pEmployeeDigitalFormGet]

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

BEGIN 
	
	SELECT 
		ISNULL(DFE.AutoId,0) as Id,
		DF.Id as DigitalFormId,
		DFF.UpdateFieldId as UpdateFieldId,
		ISNULL(DF.Code,'') as Code,
		ISNULL(DF.Title,'') as Title,

		CASE WHEN DFF.FieldTypeId = 1 THEN (SELECT SubFunctionalityName FROM sCommon.tUpdateFieldMaster WHERE Id = DFF.UpdateFieldId) 
		WHEN DFF.FieldTypeId = 2 THEN (SELECT 'EmployeeCustomFields' as SubFunctionalityName FROM sHrm.tEmployeeCustomFieldMaster WHERE Id = DFF.UpdateFieldId)
		WHEN DFF.FieldTypeId = 3 THEN 'EmployeeDocument' END AS SubFunctionalityName,

		CASE WHEN DFF.FieldTypeId = 1 THEN (SELECT Field FROM sCommon.tUpdateFieldMaster WHERE Id = DFF.UpdateFieldId) 
		WHEN DFF.FieldTypeId = 2 THEN (SELECT FieldTitle FROM sHrm.tEmployeeCustomFieldMaster WHERE Id = DFF.UpdateFieldId)
		WHEN DFF.FieldTypeId = 3 THEN (SELECT DocumentName FROM sCommon.tSubmitDocumentMaster WHERE SubmitDocumentFunctionalityId = 2 AND Id = DFF.UpdateFieldId ) END AS Field,

		DFF.UpdateFieldId,
		DFF.FieldTypeId,
		ISNULL(DFE.Remark,'') as Remark,
		ISNULL(DFE.ActionRemark,'') as ActionRemark,
		ISNULL(SM.Title,'') as Status,
		(SELECT ECD.Code FROM sHrm.vEmployeeCommonDetail ECD WHERE EmployeeId = @rEmployeeId)  as EmployeeCode
	FROM 
		sHrm.tDigitalForm DF
		INNER JOIN sHrm.tDigitalFormField DFF ON DF.Id = DFF.DigitalFormId
		LEFT JOIN sHrm.tDigitalFormEmployee DFE ON DFE.DigitalFormId = DF.Id AND DFF.UpdateFieldId = DFE.UpdateFieldId AND DFE.EmployeeId = @rEmployeeId
		LEFT JOIN sCommon.tStatusMaster SM ON DFE.StatusId = SM.Id
	WHERE 
		((DF.Id = @rDigitalFormId) OR (@rDigitalFormId = 0)) 
	 
		 
END
GO
PRINT N'Creating [sStudent].[pOnlineRegistrationCriteriaAdd]...';


GO
 
CREATE PROCEDURE [sStudent].[pOnlineRegistrationCriteriaAdd]
	
		 @rClassId int=0,
		 @rBatchId int=0,
		 @rIsOptionalSubject bit
		
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	Delete from [sStudent].[tOnlineRegistrationCriteria] where ClassId=@rClassId AND BatchId=@rBatchId
	--Select @lNextNumber
	INSERT INTO [sStudent].[tOnlineRegistrationCriteria]
		(
			  ClassId
			 ,BatchId
			 ,IsOptionalSubject
			
		)
	VALUES
		(
			  @rClassId
			 ,@rBatchId
			 ,@rIsOptionalSubject
		)
		Select ERROR_MESSAGE()
		     SELECT 103 AS Result
	
		--COMMIT TRANSACTION
	
			
END
GO
PRINT N'Creating [sStudent].[pOnlineRegistrationCriteriaOptionalSubjectAdd]...';


GO
 
 
CREATE PROCEDURE [sStudent].[pOnlineRegistrationCriteriaOptionalSubjectAdd]
	  
	@rClassId int=0,
	@rBatchId int=0,
	@rStrXml nvarchar(max) = ''
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

SET @rStrXml=REPLACE(@rStrXml,'&','AND')
SET @rStrXml=REPLACE(@rStrXml,'ANDapos;','&apos;')
DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml

BEGIN
	BEGIN TRY
		
		DELETE FROM [sStudent].[tOnlineRegistrationCriteriaOptionalSubject] WHERE ClassId = @rClassId AND BatchId = @rBatchId
	
		INSERT INTO [sStudent].[tOnlineRegistrationCriteriaOptionalSubject]
		(
			ClassId,
			BatchId,
			ClassSubjectId
		)
		SELECT
			@rClassId,@rBatchId,ClassSubjectId
		FROM
			OPENXML (@loDoc, '/Table/OptionalSubject', 1) WITH 
			( 			
			ClassSubjectId int
			)
	SELECT 1 As Result
	END TRY
	BEGIN CATCH 
	SELECT -1 AS Result
	END CATCH	
END
GO
PRINT N'Creating [sStudent].[pOnlineRegistrationOptionalSubjectAdd]...';


GO
 
CREATE PROCEDURE [sStudent].[pOnlineRegistrationOptionalSubjectAdd]
	  
	@rOnlineRegistrationStudentId bigint=0,
	@rStrXml nvarchar(max) 
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

SET @rStrXml=REPLACE(@rStrXml,'&','AND')
SET @rStrXml=REPLACE(@rStrXml,'ANDapos;','&apos;')
DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml

BEGIN
	BEGIN TRY
		
		DELETE FROM [sStudent].[tOnlineRegistrationStudentOptionalSubject] WHERE OnlineRegistrationStudentId=@rOnlineRegistrationStudentId
	
		INSERT INTO [sStudent].[tOnlineRegistrationStudentOptionalSubject]
		(
			OnlineRegistrationStudentId,
			ClassSubjectId
		)
		SELECT
			@rOnlineRegistrationStudentId,ClassSubjectId
		FROM
			OPENXML (@loDoc, '/Table/OptionalSubject', 1) WITH 
			( 			
			ClassSubjectId int
			)
	SELECT 1 As Result
	END TRY
	BEGIN CATCH 
	SELECT -1 AS Result
	END CATCH	
END
GO
 
 
GO
INSERT INTO [sSystem].[tVersionUpdate] ([VersionNumber],[VersionId],[Status],[UpdateScript],[StartDateTime],[EndDateTime],[OrgGroupId])
VALUES('22.07.04',220704,'END','Script',sCommon.fGetDate(),sCommon.fGetDate(),0)
GO